text:
package contractcourt

import (
	"testing"
	"time"

	"github.com/btcsuite/btcd/wire"
	"github.com/btcsuite/btcutil"
	"github.com/lightningnetwork/lnd/chainntnfs"
	"github.com/lightningnetwork/lnd/channeldb"
	"github.com/lightningnetwork/lnd/channeldb/kvdb"
	"github.com/lightningnetwork/lnd/input"
	"github.com/lightningnetwork/lnd/lntest/mock"
	"github.com/lightningnetwork/lnd/lnwallet"
	"github.com/lightningnetwork/lnd/lnwallet/chainfee"
	"github.com/lightningnetwork/lnd/sweep"
)

type commitSweepResolverTestContext struct {
	resolver           *commitSweepResolver
	notifier           *mock.ChainNotifier
	sweeper            *mockSweeper
	resolverResultChan chan resolveResult
	t                  *testing.T
}

func newCommitSweepResolverTestContext(t *testing.T,
	resolution *lnwallet.CommitOutputResolution) *commitSweepResolverTestContext {

	notifier := &mock.ChainNotifier{
		EpochChan: make(chan *chainntnfs.BlockEpoch),
		SpendChan: make(chan *chainntnfs.SpendDetail),
		ConfChan:  make(chan *chainntnfs.TxConfirmation),
	}

	sweeper := newMockSweeper()

	checkPointChan := make(chan struct{}, 1)

	chainCfg := ChannelArbitratorConfig{
		ChainArbitratorConfig: ChainArbitratorConfig{
			Notifier: notifier,
			Sweeper:  sweeper,
		},
		PutResolverReport: func(_ kvdb.RwTx,
			_ *channeldb.ResolverReport) error {

			return nil
		},
	}

	cfg := ResolverConfig{
		ChannelArbitratorConfig: chainCfg,
		Checkpoint: func(_ ContractResolver,
			_ ...*channeldb.ResolverReport) error {

			checkPointChan <- struct{}{}
			return nil
		},
	}

	resolver := newCommitSweepResolver(
		*resolution, 0, wire.OutPoint{}, cfg,
	)

	return &commitSweepResolverTestContext{
		resolver: resolver,
		notifier: notifier,
		sweeper:  sweeper,
		t:        t,
	}
}

func (i *commitSweepResolverTestContext) resolve() {
	// Start resolver.
	i.resolverResultChan = make(chan resolveResult, 1)
	go func() {
		nextResolver, err := i.resolver.Resolve()
		i.resolverResultChan <- resolveResult{
			nextResolver: nextResolver,
			err:          err,
		}
	}()
}

func (i *commitSweepResolverTestContext) notifyEpoch(height int32) {
	i.notifier.EpochChan <- &chainntnfs.BlockEpoch{
		Height: height,
	}
}

func (i *commitSweepResolverTestContext) waitForResult() {
	i.t.Helper()

	result := <-i.resolverResultChan
	if result.err != nil {
		i.t.Fatal(result.err)
	}

	if result.nextResolver != nil {
		i.t.Fatal("expected no next resolver")
	}
}

type mockSweeper struct {
	sweptInputs   chan input.Input
	updatedInputs chan wire.OutPoint
	sweepTx       *wire.MsgTx
	sweepErr      error
}

func newMockSweeper() *mockSweeper {
	return &mockSweeper{
		sweptInputs:   make(chan input.Input),
		updatedInputs: make(chan wire.OutPoint),
		sweepTx:       &wire.MsgTx{},
	}
}

func (s *mockSweeper) SweepInput(input input.Input, params sweep.Params) (
	chan sweep.Result, error) {

	s.sweptInputs <- input

	result := make(chan sweep.Result, 1)
	result <- sweep.Result{
		Tx:  s.sweepTx,
		Err: s.sweepErr,
	}
	return result, nil
}

func (s *mockSweeper) CreateSweepTx(inputs []input.Input, feePref sweep.FeePreference,
	currentBlockHeight uint32) (*wire.MsgTx, error) {

	return nil, nil
}

func (s *mockSweeper) RelayFeePerKW() chainfee.SatPerKWeight {
	return 253
}

func (s *mockSweeper) UpdateParams(input wire.OutPoint,
	params sweep.ParamsUpdate) (chan sweep.Result, error) {

	s.updatedInputs <- input

	result := make(chan sweep.Result, 1)
	result <- sweep.Result{
		Tx: s.sweepTx,
	}
	return result, nil
}

var _ UtxoSweeper = &mockSweeper{}

// TestCommitSweepResolverNoDelay tests resolution of a direct commitment output
// unencumbered by a time lock.
func TestCommitSweepResolverNoDelay(t *testing.T) {
	t.Parallel()
	defer timeout(t)()

	res := lnwallet.CommitOutputResolution{
		SelfOutputSignDesc: input.SignDescriptor{
			Output: &wire.TxOut{
				Value: 100,
			},
			WitnessScript: []byte{0},
		},
	}

	ctx := newCommitSweepResolverTestContext(t, &res)

	// Replace our checkpoint with one which will push reports into a
	// channel for us to consume. We replace this function on the resolver
	// itself because it is created by the test context.
	reportChan := make(chan *channeldb.ResolverReport)
	ctx.resolver.Checkpoint = func(_ ContractResolver,
		reports ...*channeldb.ResolverReport) error {

		// Send all of our reports into the channel.
		for _, report := range reports {
			reportChan <- report
		}

		return nil
	}

	ctx.resolve()

	spendTx := &wire.MsgTx{}
	spendHash := spendTx.TxHash()
	ctx.notifier.ConfChan <- &chainntnfs.TxConfirmation{
		Tx: spendTx,
	}

	// No csv delay, so the input should be swept immediately.
	<-ctx.sweeper.sweptInputs

	amt := btcutil.Amount(res.SelfOutputSignDesc.Output.Value)
	expectedReport := &channeldb.ResolverReport{
		OutPoint:        wire.OutPoint{},
		Amount:          amt,
		ResolverType:    channeldb.ResolverTypeCommit,
		ResolverOutcome: channeldb.ResolverOutcomeClaimed,
		SpendTxID:       &spendHash,
	}

	assertResolverReport(t, reportChan, expectedReport)

	ctx.waitForResult()
}

// testCommitSweepResolverDelay tests resolution of a direct commitment output
// that is encumbered by a time lock. sweepErr indicates whether the local node
// fails to sweep the output.
func testCommitSweepResolverDelay(t *testing.T, sweepErr error) {
	defer timeout(t)()

	const sweepProcessInterval = 100 * time.Millisecond
	amt := int64(100)
	outpoint := wire.OutPoint{
		Index: 5,
	}
	res := lnwallet.CommitOutputResolution{
		SelfOutputSignDesc: input.SignDescriptor{
			Output: &wire.TxOut{
				Value: amt,
			},
			WitnessScript: []byte{0},
		},
		MaturityDelay: 3,
		SelfOutPoint:  outpoint,
	}

	ctx := newCommitSweepResolverTestContext(t, &res)

	// Replace our checkpoint with one which will push reports into a
	// channel for us to consume. We replace this function on the resolver
	// itself because it is created by the test context.
	reportChan := make(chan *channeldb.ResolverReport)
	ctx.resolver.Checkpoint = func(_ ContractResolver,
		reports ...*channeldb.ResolverReport) error {

		// Send all of our reports into the channel.
		for _, report := range reports {
			reportChan <- report
		}

		return nil
	}

	// Setup whether we expect the sweeper to receive a sweep error in this
	// test case.
	ctx.sweeper.sweepErr = sweepErr

	report := ctx.resolver.report()
	expectedReport := ContractReport{
		Outpoint:     outpoint,
		Type:         ReportOutputUnencumbered,
		Amount:       btcutil.Amount(amt),
		LimboBalance: btcutil.Amount(amt),
	}
	if *report != expectedReport {
		t.Fatalf("unexpected resolver report. want=%v got=%v",
			expectedReport, report)
	}

	ctx.resolve()

	ctx.notifier.ConfChan <- &chainntnfs.TxConfirmation{
		BlockHeight: testInitialBlockHeight - 1,
	}

	// Allow resolver to process confirmation.
	time.Sleep(sweepProcessInterval)

	// Expect report to be updated.
	report = ctx.resolver.report()
	if report.MaturityHeight != testInitialBlockHeight+2 {
		t.Fatal("report maturity height incorrect")
	}

	// Notify initial block height. The csv lock is still in effect, so we
	// don't expect any sweep to happen yet.
	ctx.notifyEpoch(testInitialBlockHeight)

	select {
	case <-ctx.sweeper.sweptInputs:
		t.Fatal("no sweep expected")
	case <-time.After(sweepProcessInterval):
	}

	// A new block arrives. The commit tx confirmed at height -1 and the csv
	// is 3, so a spend will be valid in the first block after height +1.
	ctx.notifyEpoch(testInitialBlockHeight + 1)

	<-ctx.sweeper.sweptInputs

	// Set the resolution report outcome based on whether our sweep
	// succeeded.
	outcome := channeldb.ResolverOutcomeClaimed
	if sweepErr != nil {
		outcome = channeldb.ResolverOutcomeUnclaimed
	}
	sweepTx := ctx.sweeper.sweepTx.TxHash()

	assertResolverReport(t, reportChan, &channeldb.ResolverReport{
		OutPoint:        outpoint,
		ResolverType:    channeldb.ResolverTypeCommit,
		ResolverOutcome: outcome,
		Amount:          btcutil.Amount(amt),
		SpendTxID:       &sweepTx,
	})

	ctx.waitForResult()

	// If this test case generates a sweep error, we don't expect to be
	// able to recover anything. This might happen if the local commitment
	// output was swept by a justice transaction by the remote party.
	expectedRecoveredBalance := btcutil.Amount(amt)
	if sweepErr != nil {
		expectedRecoveredBalance = 0
	}

	report = ctx.resolver.report()
	expectedReport = ContractReport{
		Outpoint:         outpoint,
		Type:             ReportOutputUnencumbered,
		Amount:           btcutil.Amount(amt),
		MaturityHeight:   testInitialBlockHeight + 2,
		RecoveredBalance: expectedRecoveredBalance,
	}
	if *report != expectedReport {
		t.Fatalf("unexpected resolver report. want=%v got=%v",
			expectedReport, report)
	}

}

// TestCommitSweepResolverDelay tests resolution of a direct commitment output
// that is encumbered by a time lock.
func TestCommitSweepResolverDelay(t *testing.T) {
	t.Parallel()

	testCases := []struct {
		name     string
		sweepErr error
	}{{
		name:     "success",
		sweepErr: nil,
	}, {
		name:     "remote spend",
		sweepErr: sweep.ErrRemoteSpend,
	}}

	for _, tc := range testCases {
		tc := tc
		ok := t.Run(tc.name, func(t *testing.T) {
			testCommitSweepResolverDelay(t, tc.sweepErr)
		})
		if !ok {
			break
		}
	}
}


text:
package com.cidic.equipment.model;

import java.util.List;

public class UserPageModel {

	public List<User> list;
	public int count;

	public List<User> getList() {
		return list;
	}
	public void setList(List<User> list) {
		this.list = list;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}

}

redpajama_set_name: RedPajamaGithub


text:
package at.fhjoanneum.ippr.gateway.security.repositories;

import java.util.List;
import java.util.Optional;

import at.fhjoanneum.ippr.gateway.security.persistence.objects.Role;
import at.fhjoanneum.ippr.gateway.security.persistence.objects.Rule;
import at.fhjoanneum.ippr.gateway.security.persistence.objects.User;

public interface RBACRepository {

  User saveUser(final User user);

  Role saveRole(final Role group);

  Rule saveRule(final Rule rule);

  Optional<User> getUserByUserId(final Long userId);

  Optional<User> getUserBySystemId(final String systemId);

  Optional<User> getUserByUsername(final String username);

  Optional<Rule> getRuleBySystemId(final String systemId);

  Optional<Role> getRoleBySystemId(final String systemId);

  Optional<Role> getRoleByRoleName(final String roleName);

  List<User> getUsersByRoleName(final String roleName);

  List<User> getUsersByRuleNames(final List<String> ruleNames);

  List<Rule> getRules();
}


text:
package com.composum.sling.platform.staging.replication;

import java.util.Date;

/**
 * Class with general information about the running update.
 */
public class UpdateInfo {

    /**
     * The update id for the pending operation. Has to comply with {@link ReplicationConstants#PATTERN_UPDATEID}.
     */
    public String updateId;

    /**
     * The original status of the publishers release.
     */
    public String originalPublisherReleaseChangeId;

    /**
     * The timestamp {@link System#currentTimeMillis()} of the last replication.
     */
    public Long lastReplication;

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("UpdateInfo{");
        sb.append("updateId='").append(updateId).append('\'');
        if (lastReplication != null) {
            sb.append(", lastReplication='").append(new Date(lastReplication)).append('\'');
        }
        if (originalPublisherReleaseChangeId != null) {
            sb.append(", relchgid='").append(originalPublisherReleaseChangeId).append('\'');
        }
        sb.append('}');
        return sb.toString();
    }
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2011.03.23 at 01:44:42 PM BRT
//

package org.softlang.company;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element ref="{http://www.softlang.org/company.xsd}name"/>
 *         <element name="manager" type="{http://www.softlang.org/company.xsd}employee"/>
 *         <element ref="{http://www.softlang.org/company.xsd}subunit" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "name",
    "manager",
    "subunit"
})
@XmlRootElement(name = "department")
public class Department {

    @XmlElement(required = true)
    protected String name;
    @XmlElement(required = true)
    protected Employee manager;
    protected List<Subunit> subunit;

    /**
     * Gets the value of the name property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getName() {
        return name;
    }

    /**
     * Sets the value of the name property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setName(String value) {
        this.name = value;
    }

    /**
     * Gets the value of the manager property.
     *
     * @return
     *     possible object is
     *     {@link Employee }
     *
     */
    public Employee getManager() {
        return manager;
    }

    /**
     * Sets the value of the manager property.
     *
     * @param value
     *     allowed object is
     *     {@link Employee }
     *
     */
    public void setManager(Employee value) {
        this.manager = value;
    }

    /**
     * Gets the value of the subunit property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the subunit property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getSubunit().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link Subunit }
     *
     *
     */
    public List<Subunit> getSubunit() {
        if (subunit == null) {
            subunit = new ArrayList<Subunit>();
        }
        return this.subunit;
    }

}


text:
"""
This code includes functions to preprocess text in gutenberg dataset.
Especially, for certain book.
Download
--------
Project Gutenberg.
https://www.gutenberg.org/ebooks/

Base datapath: '~~~/data/'
Additional folder structure: '~~~/data/gutenberg/alice_in_wonderland.txt'
SAVE THE TEXT TO ANSI FORMAT.
"""

import time
import numpy as np

class GutenbergWordCorpus(object):
    """
    This class use gutenberg book text to make better tensor form.
    Word level sequence pre-processing.
    """
    def __init__(self, base_datapath, mode='alice_in_wonderland', eos=True, sos=False, lower=True):
        """
        This function initializes the class.
        Currently, only one book per class is implemented.
        Reading multiple books at one time is for future implementation.
        For initialization, split text into sentences.

        Parameters
        ----------
        base_datapath: string
            a string path where textbook is saved.
        mode: string, default: 'alice_in_wonderland'
            a string which will be target book.
            i.e., 'alice_in_wonderland.txt'
        eos: bool, default: True.
            a bool value to determine whether to put <eos> at the end of sentences.
        sos: bool, default: False.
            a bool value to determine wheter to put <sos> at the front of sentences.
        lower: bool, default: True.
            a bool value, whether we should lower all cases or not (for english).

        Returns
        -------
        None.
        """
        # check asserts
        assert isinstance(base_datapath, str), '"base_datapath" should be a string path.'
        assert isinstance(mode, str), '"mode" should be a string name for textbook.'
        assert isinstance(eos, bool), '"eos" should be a bool value to determine <eos> insert or not.'
        assert isinstance(sos, bool), '"eos" should be a bool value to determine <sos> insert or not.'

        # load
        book_file =  base_datapath + 'gutenberg/' + mode + '.txt'
        print('Gutenberg load book:', book_file)
        start_time = time.clock()
        import nltk

        with open(book_file, 'r') as f:
            if lower:
                corpus = f.read().lower().replace('\n', ' ')
            else:
                corpus = f.read().replace('\n', ' ')
            # nltk.download()  # download model -> punkt if you get an error
            self.sentences = nltk.tokenize.sent_tokenize(corpus)  # a list of sentences, each sentence is string
            for i in range(len(self.sentences)):
                words_from_string = nltk.tokenize.word_tokenize(self.sentences[i])
                if eos:
                    words_from_string = words_from_string + ['<EOS>']
                if sos:
                    words_from_string = ['<SOS>'] + words_from_string
                self.sentences[i] = words_from_string  # string to word, now sentence is list of list of words
        print('Gutenberg number of sentences:', len(self.sentences))
        end_time = time.clock()
        print('Gutenberg load time:', end_time - start_time)

if __name__ == '__main__':
    base_datapath = 'C:/Users/skhu2/Dropbox/Project/data/'
    guten = GutenbergWordData(base_datapath, 'alice_in_wonderland',
                              eos=True, sos=False)

    for i in range(10):
        seq = guten.sentences[i]
        print(len(seq))


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Intellij Idea on zerodivisible.io</title>
    <link>https://zerodivisible.io/tags/intellij-idea/</link>
    <description>Recent content in Intellij Idea on zerodivisible.io</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en</language>
    <lastBuildDate>Fri, 10 Jan 2014 11:44:08 +0000</lastBuildDate>

	<atom:link href="https://zerodivisible.io/tags/intellij-idea/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>Gradle: adding new sourceSets recognized from Intellij IDEA</title>
      <link>https://zerodivisible.io/blog/gradle-adding-new-sourcesets-recognized-from-intellij-idea/</link>
      <pubDate>Fri, 10 Jan 2014 11:44:08 +0000</pubDate>

      <guid>https://zerodivisible.io/blog/gradle-adding-new-sourcesets-recognized-from-intellij-idea/</guid>
      <description>Some of the bigger projects which I&rsquo;ve been working on recently have a bit more complex Gradle build scripts for them. One nifty thing which I thought that it would be worth documenting is how one of such projects is dealing with multi-module projects - and having a separate build target configured for running functional tests for it.From time to time having normal tests configured in my Gradle build files is not enough - especially when I&rsquo;m dealing with big, multi-module projects.</description>
    </item>

  </channel>
</rss>


text:
/*
 * ERollingFileAppender.cpp
 *
 *  Created on: 2015-8-23
 *      Author: cxxjava@163.com
 */

#include "./ERollingFileAppender.hh"
#include "./EOptionConverter.hh"

namespace efc {
namespace log {

ERollingFileAppender::ERollingFileAppender(EConfiguration* conf, EConfig* props, EString& prefix, ELogger::Level threshold) :
	EFileAppender(conf, props, prefix, threshold) {
	EString maxFileSizePrefix = prefix + ".MaxFileSize";
	maxFileSize_ = EOptionConverter::toFileSize(props->getString(maxFileSizePrefix.c_str()), 10*1024*1024L);

	EString maxBackupIndexPrefix = prefix + ".MaxBackupIndex";
	maxBackupIndex_ = props->getInt(maxBackupIndexPrefix.c_str(), 1);
}

llong ERollingFileAppender::getMaxFileSize() {
	return maxFileSize_;
}

int ERollingFileAppender::getMaxBackupIndex() {
	return maxBackupIndex_;
}

} /* namespace log */
} /* namespace efc */


text:
一个拥有更平滑的navigationBar切换动画的NavigationController,拥有快速设置NavigationBar所属的背景、标题、Item颜色的NavigationController

# CocoaPods
pod 'FRNavigationController'


text:
package com.easytoolsoft.easyreport.viewmodel;

public class HtmlCheckBox extends HtmlFormElement {
    private final String value;
    private boolean checked;

    public HtmlCheckBox(String name, String text, String value) {
        super(name, text);
        this.type = "checkbox";
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    public boolean isChecked() {
        return checked;
    }

    public void setChecked(boolean checked) {
        this.checked = checked;
    }
}


text:
package org.gradle.internal.jvm;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class GroovyJpmsWorkarounds {
    /**
     * These JVM arguments should be passed to any process that will be using Groovy on Java 9+ to avoid noisy illegal access warnings that the user can't do anything about.
     */
    public static final List<String> SUPPRESS_COMMON_GROOVY_WARNINGS = Collections.unmodifiableList(Arrays.asList(
        "--add-opens", "java.base/java.lang=ALL-UNNAMED",
        "--add-opens", "java.base/java.lang.invoke=ALL-UNNAMED"
    ));
}


text:
package org.apache.poi.poifs.filesystem;

import java.io.IOException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;

import junit.framework.TestCase;

import org.apache.poi.util.IOUtils;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.poifs.filesystem.POIFSWriterEvent;
import org.apache.poi.poifs.filesystem.POIFSWriterListener;
import org.apache.poi.poifs.filesystem.DirectoryEntry;

public final class TestEmptyDocument extends TestCase {

	public void testSingleEmptyDocument() throws IOException {
		POIFSFileSystem fs = new POIFSFileSystem();
		DirectoryEntry dir = fs.getRoot();
		dir.createDocument("Foo", new ByteArrayInputStream(new byte[] {}));

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		fs.writeFilesystem(out);
		new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray()));
	}

	public void testSingleEmptyDocumentEvent() throws IOException {
		POIFSFileSystem fs = new POIFSFileSystem();
		DirectoryEntry dir = fs.getRoot();
		dir.createDocument("Foo", 0, new POIFSWriterListener() {
			public void processPOIFSWriterEvent(POIFSWriterEvent event) {
				System.out.println("written");
			}
		});

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		fs.writeFilesystem(out);
		new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray()));
	}

	public void testEmptyDocumentWithFriend() throws IOException {
		POIFSFileSystem fs = new POIFSFileSystem();
		DirectoryEntry dir = fs.getRoot();
		dir.createDocument("Bar", new ByteArrayInputStream(new byte[] { 0 }));
		dir.createDocument("Foo", new ByteArrayInputStream(new byte[] {}));

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		fs.writeFilesystem(out);
		new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray()));
	}

	public void testEmptyDocumentEventWithFriend() throws IOException {
		POIFSFileSystem fs = new POIFSFileSystem();
		DirectoryEntry dir = fs.getRoot();
		dir.createDocument("Bar", 1, new POIFSWriterListener() {
			public void processPOIFSWriterEvent(POIFSWriterEvent event) {
				try {
					event.getStream().write(0);
				} catch (IOException exception) {
					throw new RuntimeException("exception on write: " + exception);
				}
			}
		});
		dir.createDocument("Foo", 0, new POIFSWriterListener() {
			public void processPOIFSWriterEvent(POIFSWriterEvent event) {
			}
		});

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		fs.writeFilesystem(out);
		new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray()));
	}

	public void testEmptyDocumentBug11744() throws Exception {
		byte[] testData = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

		POIFSFileSystem fs = new POIFSFileSystem();
		fs.createDocument(new ByteArrayInputStream(new byte[0]), "Empty");
		fs.createDocument(new ByteArrayInputStream(testData), "NotEmpty");
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		fs.writeFilesystem(out);
		out.toByteArray();

		// This line caused the error.
		fs = new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray()));

		DocumentEntry entry = (DocumentEntry) fs.getRoot().getEntry("Empty");
		assertEquals("Expected zero size", 0, entry.getSize());
		byte[] actualReadbackData;
		actualReadbackData = IOUtils.toByteArray(new DocumentInputStream(entry));
		assertEquals("Expected zero read from stream", 0, actualReadbackData.length);

		entry = (DocumentEntry) fs.getRoot().getEntry("NotEmpty");
		actualReadbackData = IOUtils.toByteArray(new DocumentInputStream(entry));
		assertEquals("Expected size was wrong", testData.length, entry.getSize());
		assertTrue("Expected different data read from stream", Arrays.equals(testData,
				actualReadbackData));
	}
}


text:
package br.edu.utfpr.recominer.web.controller;

import br.edu.utfpr.recominer.core.model.Issue;
import br.edu.utfpr.recominer.core.repository.IssueRepository;
import br.edu.utfpr.recominer.core.repository.ProjectRepository;
import br.edu.utfpr.recominer.web.dto.IssueDTO;
import br.edu.utfpr.recominer.web.dto.ProjectDTO;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class IssuesController {

    @Inject
    private ProjectRepository projectRepository;

    @Inject
    private IssueRepository repository;

    public IssuesController() {
    }

    @RequestMapping(value = "/issues", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public List<IssueDTO> listIssues(@RequestBody ProjectDTO project) {
        repository.setProject(projectRepository.findOne(project.getId()));
        List<IssueDTO> issues = new ArrayList<>();
        for (Issue issue : repository.selectProcessedIssuesOfProject()) {
            issues.add(new IssueDTO(issue));
        }
        return issues;
    }
}


text:
/* jshint -W117, -W030 */
describe('dashboard', function() {
    describe('state', function() {
        var controller;
        var view = 'app/dashboard/dashboard.html';

        beforeEach(function() {
            module('app.dashboard', bard.fakeToastr);
            bard.inject('$location', '$rootScope', '$state', '$templateCache');
            $templateCache.put(view, '');
        });

        it('should map / route to dashboard View template', function() {
            expect($state.get('dashboard').templateUrl).to.equal(view);
        });

        it('should map state dashboard to url / ', function() {
            expect($state.href('dashboard', {})).to.equal('/');
        });

        it('of dashboard should work with $state.go', function() {
            $state.go('dashboard');
            $rootScope.$apply();
            expect($state.is('dashboard'));
        });

        it('should route /invalid to the otherwise (dashboard) route', function() {
            $location.path('/invalid');
            $rootScope.$apply();
            expect($state.current.templateUrl).to.equal(view);
        });
    });
});


text:
#include <netinet/in.h>
#include <net/if.h>

#include <linux/rtnetlink.h>
#include <netlink/handlers.h>
#include <netlink/msg.h>

/* function: ack_handler
 * generic netlink callback for ack messages
 * msg  - netlink message
 * data - pointer to an int, stores the success code
 */
static int ack_handler(__attribute__((unused)) struct nl_msg *msg, void *data) {
  int *retval = data;
  *retval = 0;
  return NL_OK;
}

/* function: error_handler
 * generic netlink callback for error messages
 * nla  - error source
 * err  - netlink error message
 * arg  - pointer to an int, stores the error code
 */
static int error_handler(__attribute__((unused)) struct sockaddr_nl *nla,
                         struct nlmsgerr *err, void *arg) {
  int *retval = arg;
  if(err->error < 0) {
    *retval = err->error;
  } else {
    *retval = 0; // NLMSG_ERROR used as reply type on no error
  }
  return NL_OK;
}

/* function: alloc_ack_callbacks
 * allocates a set of netlink callbacks.  returns NULL on failure.  callbacks will modify retval with <0 meaning failure
 * retval - shared state between caller and callback functions
 */
struct nl_cb *alloc_ack_callbacks(int *retval) {
  struct nl_cb *callbacks;

  callbacks = nl_cb_alloc(NL_CB_DEFAULT);
  if(!callbacks) {
    return NULL;
  }
  nl_cb_set(callbacks, NL_CB_ACK, NL_CB_CUSTOM, ack_handler, retval);
  nl_cb_err(callbacks, NL_CB_CUSTOM, error_handler, retval);
  return callbacks;
}


text:
//= require jquery
//= require jquery_ujs
//= require_self
//= require_tree .

/* rest of file omitted */


text:
package facebookfriends

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"net/http"

	"github.com/cihangir/gene/example/tinder/models"
	"github.com/go-kit/kit/endpoint"
	httptransport "github.com/go-kit/kit/transport/http"
	"golang.org/x/net/context"
)

const (
	EndpointNameCreate  = "create"
	EndpointNameDelete  = "delete"
	EndpointNameMutuals = "mutuals"
	EndpointNameOne     = "one"
)

type semiotic struct {
	Name               string
	Method             string
	Route              string
	ServerEndpointFunc func(svc FacebookFriendsService) endpoint.Endpoint
	DecodeRequestFunc  httptransport.DecodeRequestFunc
	EncodeRequestFunc  httptransport.EncodeRequestFunc
	EncodeResponseFunc httptransport.EncodeResponseFunc
	DecodeResponseFunc httptransport.DecodeResponseFunc
}

var semiotics = map[string]semiotic{

	EndpointNameCreate: semiotic{
		Name:               EndpointNameCreate,
		Method:             "POST",
		ServerEndpointFunc: makeCreateEndpoint,
		Route:              "/" + EndpointNameCreate,
		DecodeRequestFunc:  decodeCreateRequest,
		EncodeRequestFunc:  encodeRequest,
		EncodeResponseFunc: encodeResponse,
		DecodeResponseFunc: decodeCreateResponse,
	},

	EndpointNameDelete: semiotic{
		Name:               EndpointNameDelete,
		Method:             "POST",
		ServerEndpointFunc: makeDeleteEndpoint,
		Route:              "/" + EndpointNameDelete,
		DecodeRequestFunc:  decodeDeleteRequest,
		EncodeRequestFunc:  encodeRequest,
		EncodeResponseFunc: encodeResponse,
		DecodeResponseFunc: decodeDeleteResponse,
	},

	EndpointNameMutuals: semiotic{
		Name:               EndpointNameMutuals,
		Method:             "POST",
		ServerEndpointFunc: makeMutualsEndpoint,
		Route:              "/" + EndpointNameMutuals,
		DecodeRequestFunc:  decodeMutualsRequest,
		EncodeRequestFunc:  encodeRequest,
		EncodeResponseFunc: encodeResponse,
		DecodeResponseFunc: decodeMutualsResponse,
	},

	EndpointNameOne: semiotic{
		Name:               EndpointNameOne,
		Method:             "POST",
		ServerEndpointFunc: makeOneEndpoint,
		Route:              "/" + EndpointNameOne,
		DecodeRequestFunc:  decodeOneRequest,
		EncodeRequestFunc:  encodeRequest,
		EncodeResponseFunc: encodeResponse,
		DecodeResponseFunc: decodeOneResponse,
	},
}

// Decode Request functions

func decodeCreateRequest(ctx context.Context, r *http.Request) (interface{}, error) {
	var req models.FacebookFriends
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		return nil, err
	}
	return &req, nil
}

func decodeDeleteRequest(ctx context.Context, r *http.Request) (interface{}, error) {
	var req models.FacebookFriends
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		return nil, err
	}
	return &req, nil
}

func decodeMutualsRequest(ctx context.Context, r *http.Request) (interface{}, error) {
	var req []*models.FacebookFriends
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		return nil, err
	}
	return &req, nil
}

func decodeOneRequest(ctx context.Context, r *http.Request) (interface{}, error) {
	var req models.FacebookFriends
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		return nil, err
	}
	return &req, nil
}

// Decode Response functions

func decodeCreateResponse(ctx context.Context, r *http.Response) (interface{}, error) {
	var res models.FacebookFriends
	if err := json.NewDecoder(r.Body).Decode(&res); err != nil {
		return nil, err
	}
	return &res, nil
}

func decodeDeleteResponse(ctx context.Context, r *http.Response) (interface{}, error) {
	var res models.FacebookFriends
	if err := json.NewDecoder(r.Body).Decode(&res); err != nil {
		return nil, err
	}
	return &res, nil
}

func decodeMutualsResponse(ctx context.Context, r *http.Response) (interface{}, error) {
	var res []string
	if err := json.NewDecoder(r.Body).Decode(&res); err != nil {
		return nil, err
	}
	return &res, nil
}

func decodeOneResponse(ctx context.Context, r *http.Response) (interface{}, error) {
	var res models.FacebookFriends
	if err := json.NewDecoder(r.Body).Decode(&res); err != nil {
		return nil, err
	}
	return &res, nil
}

// Encode request function

func encodeRequest(ctx context.Context, r *http.Request, request interface{}) error {
	var buf bytes.Buffer
	if err := json.NewEncoder(&buf).Encode(request); err != nil {
		return err
	}
	r.Body = ioutil.NopCloser(&buf)
	return nil
}

// Encode response function

func encodeResponse(ctx context.Context, rw http.ResponseWriter, response interface{}) error {
	return json.NewEncoder(rw).Encode(response)
}

// Endpoint functions

func makeCreateEndpoint(svc FacebookFriendsService) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (interface{}, error) {
		req := request.(*models.FacebookFriends)
		return svc.Create(ctx, req)
	}
}

func makeDeleteEndpoint(svc FacebookFriendsService) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (interface{}, error) {
		req := request.(*models.FacebookFriends)
		return svc.Delete(ctx, req)
	}
}

func makeMutualsEndpoint(svc FacebookFriendsService) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (interface{}, error) {
		req := request.(*[]*models.FacebookFriends)
		return svc.Mutuals(ctx, req)
	}
}

func makeOneEndpoint(svc FacebookFriendsService) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (interface{}, error) {
		req := request.(*models.FacebookFriends)
		return svc.One(ctx, req)
	}
}


text:
const ExcelJS = verquire('exceljs');

// this file to contain integration tests created from github issues
const TEST_XLSX_FILE_NAME = './spec/out/wb.test.xlsx';

describe('github issues', () => {
  it('issue 275 - hyperlink with query arguments corrupts workbook', () => {
    const options = {
      filename: TEST_XLSX_FILE_NAME,
      useStyles: true,
    };
    const wb = new ExcelJS.stream.xlsx.WorkbookWriter(options);
    const ws = wb.addWorksheet('Sheet1');

    const hyperlink = {
      text: 'Somewhere with query params',
      hyperlink: 'www.somewhere.com?a=1&b=2&c=<>&d="\'"',
    };

    // Start of Heading
    ws.getCell('A1').value = hyperlink;
    ws.commit();

    return wb
      .commit()
      .then(() => {
        const wb2 = new ExcelJS.Workbook();
        return wb2.xlsx.readFile(TEST_XLSX_FILE_NAME);
      })
      .then(wb2 => {
        const ws2 = wb2.getWorksheet('Sheet1');
        expect(ws2.getCell('A1').value).to.deep.equal(hyperlink);
      });
  });
});


text:
require 'rubybvc'
require 'yaml'

puts "Loading configuration..."
config = YAML.load_file('config.yml')

controller = Controller.new(ip_addr: config['controller']['ip_addr'],
  admin_name: config['controller']['username'],
  admin_password: config['controller']['password'])
vrouter = VRouter5600.new(controller: controller, name: config['node']['name'],
  ip_addr: config['node']['ip_addr'], port_number: config['node']['port_num'],
  admin_name: config['node']['username'],
  admin_password: config['node']['password'])
puts "Controller: #{controller.ip}, #{vrouter.name}: #{vrouter.ip}"

response = vrouter.get_loopback_interfaces_cfg
if response.status == NetconfResponseStatus::OK
  puts "Loopback interfaces config: #{JSON.pretty_generate response.body}"
else
  puts "\nCommand failed: #{response.message}"
  puts "#{response.body.body}" # response.body is response object
end


text:
import { reaction } from "mobx"
import { inject, observer } from "mobx-react"
import React, { Component } from "react"
import {
  MdDeleteSweep as IconClear,
  MdFilterList as IconFilter,
  MdFileDownload as IconDownload,
  MdSearch as IconSearch,
  MdSwapVert as IconReverseOrder,
  MdSearch,
  MdFilterList,
  MdSwapVert,
  MdFileDownload,
  MdDeleteSweep,
} from "react-icons/md"
import AppStyles from "../Theme/AppStyles"
import Colors from "../Theme/Colors"
import Button from "../Shared/CommandToolbarButton"

const TITLE = "Timeline"

const toolbarButton = {
  cursor: "pointer",
}

const Styles = {
  container: {
    WebkitAppRegion: "drag",
    backgroundColor: Colors.backgroundSubtleLight,
    borderBottom: `1px solid ${Colors.chromeLine}`,
    color: Colors.foregroundDark,
    boxShadow: `0px 0px 30px ${Colors.glow}`,
  },
  content: {
    height: 70,
    paddingLeft: 10,
    paddingRight: 10,
    ...AppStyles.Layout.hbox,
    justifyContent: "space-between",
  },
  left: { ...AppStyles.Layout.hbox, width: 100, alignItems: "center" },
  right: { ...AppStyles.Layout.hbox, justifyContent: "flex-end", alignItems: "center", width: 100 },
  center: { ...AppStyles.Layout.vbox, flex: 1, alignItems: "center", justifyContent: "center" },
  title: { color: Colors.foregroundLight, textAlign: "center" },
  iconSize: 32,
  toolbarClear: { ...toolbarButton },
  toolbarFilter: { ...toolbarButton, paddingRight: 8 },
  searchContainer: {
    position: "relative",
    display: "flex",
    paddingBottom: 10,
    paddingTop: 4,
    paddingRight: 10,
  },
  searchLabel: { fontSize: 12, paddingLeft: 10, paddingRight: 10 },
  searchInput: {
    borderRadius: 4,
    padding: 10,
    flex: 1,
    backgroundColor: Colors.backgroundSubtleDark,
    border: "none",
    color: Colors.foregroundDark,
    fontSize: 14,
  },
  searchIconSize: 28,
  searchIcon: { paddingRight: 7, cursor: "pointer" },
  searchIconEnabled: { color: "white" },
  reverseOrderSize: 28,
  reverseOrderIcon: { paddingRight: 7, cursor: "pointer" },
}

@inject("session")
@observer
class TimelineHeader extends Component {
  getValue = evt => {
    this.props.onFilter(evt.target.value)
  }

  /**
   * Moves the focus to the search input.
   *
   * This is called when we show the search ui.
   */
  setFocusToSearch = () => {
    // unclear why i need to do this after a timeout?  is it because
    // i'm rendering?
    setTimeout(() => {
      this.searchInput.focus()
    }, 10)
  }

  componentDidMount() {
    // when the isTimelineSearchVisible becomes `true`...
    this.unsubscribe = reaction(
      () => this.props.session.ui.isTimelineSearchVisible,
      value => {
        if (value) {
          this.setFocusToSearch()
        }
      }
    )
  }

  componentWillUnmount() {
    this.unsubscribe && this.unsubscribe()
  }

  handleKeyDown = e => {
    // have to do this here
    if (e.keyCode === 27) {
      this.props.session.ui.hideTimelineSearch()
    }
  }

  render() {
    const { ui } = this.props.session
    const { isTimelineSearchVisible } = ui
    const searchIconStyle = {
      ...Styles.searchIcon,
      ...(isTimelineSearchVisible ? Styles.searchIconEnabled : {}),
    }
    const searchContainerStyle = {
      ...Styles.searchContainer,
      ...(!isTimelineSearchVisible ? { display: "none" } : {}),
    }

    return (

{TITLE}

            <Button
              icon={MdSearch}
              onClick={ui.toggleTimelineSearch}
              tip="Search"
              size={Styles.searchIconSize}
              style={searchIconStyle}
            />
            <Button
              icon={MdFilterList}
              onClick={ui.openFilterTimelineDialog}
              tip="Filter"
              size={Styles.iconSize}
              style={Styles.toolbarFilter}
            />
            <Button
              icon={MdSwapVert}
              onClick={ui.toggleTimelineOrder}
              tip="Reverse Order"
              size={Styles.reverseOrderSize}
              style={Styles.reverseOrderIcon}
            />
            <Button
              icon={MdFileDownload}
              onClick={ui.openExportTimelineDialog}
              tip="Download"
              size={Styles.iconSize}
              style={Styles.toolbarFilter}
            />
            <Button
              icon={MdDeleteSweep}
              onClick={ui.reset}
              tip="Clear"
              size={Styles.iconSize}
              style={Styles.toolbarClear}
            />

Search

          <input
            ref={ref => (this.searchInput = ref)}
            style={Styles.searchInput}
            onInput={this.props.onFilter ? this.getValue : undefined}
            onChange={e => ui.setSearchPhrase(e.target.value)}
            onKeyDown={this.handleKeyDown}
            value={ui.searchPhrase}
          />

    )
  }
}

export default TimelineHeader


text:
class Browser;

namespace chromeos {
class DeviceState;
class NetworkState;
class NetworkStateHandlerObserver;
}

namespace gfx {
class ImageSkia;
}

namespace views {
class WidgetDelegate;
}

namespace chromeos {
namespace options {

// ChromeOS internet options page UI handler.
class InternetOptionsHandler
    : public ::options::OptionsPageUIHandler,
      public chromeos::NetworkStateHandlerObserver,
      public chromeos::LoginState::Observer {
 public:
  InternetOptionsHandler();
  virtual ~InternetOptionsHandler();

 private:
  // OptionsPageUIHandler
  virtual void GetLocalizedValues(
      base::DictionaryValue* localized_strings) OVERRIDE;
  virtual void InitializePage() OVERRIDE;

  // WebUIMessageHandler (from OptionsPageUIHandler)
  virtual void RegisterMessages() OVERRIDE;

  // Callbacks to set network state properties.
  void EnableWifiCallback(const base::ListValue* args);
  void DisableWifiCallback(const base::ListValue* args);
  void EnableCellularCallback(const base::ListValue* args);
  void DisableCellularCallback(const base::ListValue* args);
  void EnableWimaxCallback(const base::ListValue* args);
  void DisableWimaxCallback(const base::ListValue* args);
  void ShowMorePlanInfoCallback(const base::ListValue* args);
  void BuyDataPlanCallback(const base::ListValue* args);
  void SetApnCallback(const base::ListValue* args);
  void SetApnProperties(const base::ListValue* args,
                        const std::string& service_path,
                        const base::DictionaryValue& shill_properties);
  void CarrierStatusCallback();
  void SetCarrierCallback(const base::ListValue* args);
  void SetSimCardLockCallback(const base::ListValue* args);
  void ChangePinCallback(const base::ListValue* args);
  void RefreshNetworksCallback(const base::ListValue* args);

  // Retrieves a data url for a resource.
  std::string GetIconDataUrl(int resource_id) const;

  // Refreshes the display of network information.
  void RefreshNetworkData();

  // Updates the display of network connection information for the details page
  // if visible.
  void UpdateConnectionData(const std::string& service_path);
  void UpdateConnectionDataCallback(
      const std::string& service_path,
      const base::DictionaryValue& shill_properties);
  // Called when carrier data has been updated to informs the JS.
  void UpdateCarrier();

  // NetworkStateHandlerObserver
  virtual void DeviceListChanged() OVERRIDE;
  virtual void NetworkListChanged() OVERRIDE;
  virtual void NetworkConnectionStateChanged(
      const chromeos::NetworkState* network) OVERRIDE;
  virtual void NetworkPropertiesUpdated(
      const chromeos::NetworkState* network) OVERRIDE;

  // chromeos::LoginState::Observer
  virtual void LoggedInStateChanged() OVERRIDE;

  // Updates the logged in user type.
  void UpdateLoggedInUserType();

  // content::NotificationObserver (from OptionsPageUIHandler)
  virtual void Observe(int type,
                       const content::NotificationSource& source,
                       const content::NotificationDetails& details) OVERRIDE;

  // Additional callbacks to set network state properties.
  void SetServerHostnameCallback(const base::ListValue* args);
  void SetPreferNetworkCallback(const base::ListValue* args);
  void SetAutoConnectCallback(const base::ListValue* args);
  void SetIPConfigCallback(const base::ListValue* args);
  void SetIPConfigProperties(const base::ListValue* args,
                             const std::string& service_path,
                             const base::DictionaryValue& shill_properties);

  // Retrieves the properties for |service_path| and calls showDetailedInfo
  // with the results.
  void PopulateDictionaryDetailsCallback(
      const std::string& service_path,
      const base::DictionaryValue& shill_properties);

  // Gets the native window for hosting dialogs, etc.
  gfx::NativeWindow GetNativeWindow() const;

  // Handle various network commands and clicks on a network item
  // in the network list.
  // |args| must be { network_type, service_path, command } with 'command'
  // one of: [ add, forget, options, connect disconnect, activate ]
  void NetworkCommandCallback(const base::ListValue* args);

  // Helper functions called by NetworkCommandCallback(...)
  void AddConnection(const std::string& type);

  // Creates the map of wired networks.
  base::ListValue* GetWiredList();

  // Creates the map of wireless networks.
  base::ListValue* GetWirelessList();

  // Creates the map of virtual networks.
  base::ListValue* GetVPNList();

  // Creates the map of remembered networks.
  base::ListValue* GetRememberedList();

  // Fills network information into JS dictionary for displaying network lists.
  void FillNetworkInfo(base::DictionaryValue* dictionary);

  content::NotificationRegistrar registrar_;

  // Keep track of the service path for the network shown in the Details view.
  std::string details_path_;

  // Weak pointer factory so we can start connections at a later time
  // without worrying that they will actually try to happen after the lifetime
  // of this object.
  base::WeakPtrFactory<InternetOptionsHandler> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(InternetOptionsHandler);
};

}  // namespace options
}  // namespace chromeos

#endif  // CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_INTERNET_OPTIONS_HANDLER_H_


text:
package org.compass.core.test.querybuilder.attach;

import org.compass.core.CompassException;
import org.compass.core.CompassQuery;
import org.compass.core.CompassSession;
import org.compass.core.CompassTransaction;
import org.compass.core.test.AbstractTestCase;

/**
 * @author kimchy
 */
public class AttachQueryTests extends AbstractTestCase {

    protected String[] getMappings() {
        return new String[]{"querybuilder/attach/mapping.cpm.xml"};
    }

    public void testSimpleAttach() {
        CompassQuery query1 = getCompass().queryBuilder().queryString("test").toQuery();
        CompassQuery query2 = getCompass().queryBuilder().queryString("notests").toQuery();

        CompassSession session = openSession();
        CompassTransaction tr = session.beginTransaction();

        A a = new A();
        a.id = 1;
        a.value = "test";
        session.save("a", a);

        assertEquals(1, query1.attach(session).hits().length());
        assertEquals(0, query2.attach(session).hits().length());

        tr.commit();
        session.close();

        session = openSession();
        tr = session.beginTransaction();

        query1.attach(session);

        assertEquals(1, query1.attach(session).count());
        assertEquals(0, query2.attach(session).count());

        tr.commit();
        session.close();
    }

    public void testTransactionBoundAttach() {
        CompassQuery query1 = getCompass().queryBuilder().queryString("test").toQuery();
        CompassQuery query2 = getCompass().queryBuilder().queryString("notests").toQuery();

        CompassSession session = openSession();

        A a = new A();
        a.id = 1;
        a.value = "test";
        session.save("a", a);

        assertEquals(1, query1.hits().length());
        assertEquals(0, query2.hits().length());

        session.close();

        session = openSession();
        session.beginTransaction();

        assertEquals(1, query1.count());
        assertEquals(0, query2.count());

        session.close();
    }

    public void testNoAttachException() {
        CompassQuery query1 = getCompass().queryBuilder().queryString("test").toQuery();

        try {
            query1.count();
            fail();
        } catch (CompassException e) {
            // all is well
        }
    }
}


text:
import React from 'react';
import PropTypes from 'prop-types';

import Rule from './Rule';
import RuleForm from './RuleForm';

class RuleList extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    const rest = Object.assign({}, this.props);
    delete rest.list;
    delete rest.selected;
    delete rest.onClick;
    delete rest.onChange;
    delete rest.onSubmit;
    delete rest.onCancel;
    delete rest.onDelete;
    delete rest.scrollToForm;
    return (
      <article {...rest}>
        {this.props.list.length == 0 ? null :
          this.props.list.map(rule => {
            if(this.props.selected &&
              rule._id == this.props.selected._id)
              return (
                <RuleForm
                  key={this.props.selected._id}
                  id={this.props.selected._id}
                  name={this.props.selected.name}
                  build={this.props.selected.build}
                  max={this.props.selected.max}
                  category={this.props.selected.category}
                  group={this.props.selected.group}
                  tier={this.props.selected.tier}
                  level={this.props.selected.level}
                  roleplay={this.props.selected.roleplay}
                  effect={this.props.selected.effect}
                  race={this.props.selected.race}
                  culture={this.props.selected.culture}
                  delivery={this.props.selected.delivery}
                  verbal={this.props.selected.verbal}
                  uses={this.props.selected.uses}
                  usesExtra={this.props.selected.usesExtra}
                  usesPerXAptitudes={this.props.selected.usesPerXAptitudes}
                  usesType={this.props.selected.usesType}
                  description={this.props.selected.description}
                  requires={this.props.selected.requires}
                  requeresAny={this.props.selected.requeresAny}
                  conflicts={this.props.selected.conflicts}
                  removes={this.props.selected.removes}
                  grants={this.props.selected.grants}
                  grantsUseOf={this.props.selected.grantsUseOf}
                  increaseMax={this.props.selected.increaseMax}
                  disable={this.props.selected.disable}
                  hidden={this.props.selected.hidden}
                  onChange={this.props.onChange}
                  onSubmit={this.props.onSubmit}
                  onCancel={this.props.onCancel}
                  onDelete={this.props.onDelete}
                  scrollToForm={this.props.scrollToForm}
                />);
            return (
              <Rule
                key={rule._id}
                id={rule._id}
                name={rule.name}
                category={rule.category}
                group={rule.group + (rule.tier ? ' (' + rule.tier + ')' : '')}
                race={rule.race}
                culture={rule.culture}
                onClick={this.props.onClick}
              />);
          })
        }
      </article>
    );
  }
}

RuleList.defaultProps = {
  list: [],
  scrollToForm: false
};

RuleList.propTypes = {
  list: PropTypes.array.isRequired,
  selected: PropTypes.object,
  onClick: PropTypes.func.isRequired,
  onChange: PropTypes.func.isRequired,
  onSubmit: PropTypes.func.isRequired,
  onCancel: PropTypes.func.isRequired,
  onDelete: PropTypes.func.isRequired,
  scrollToForm: PropTypes.bool
};

export default RuleList;


text:
import React, {Component} from 'react';

export default class History extends Component {
    render() {
        return (

Раздел /history

        )
    }
}


text:
using Microsoft.VisualStudio.Modeling;
using Microsoft.VisualStudio.Modeling.Immutability;

namespace NuPattern.Runtime.Schema
{
    /// <summary>
    /// Initialization when a Customizable Element is added to the model.
    /// </summary>
    [RuleOn(typeof(NamedElementSchema), FireTime = TimeToFire.TopLevelCommit)]
    internal class NamedElementAddRule : AddRule
    {
        /// <summary>
        /// Triggers this notification rule when a <see cref="CustomizableElementSchema"/> is added.
        /// </summary>
        /// <param name="e">The provided data for this event.</param>
        public override void ElementAdded(ElementAddedEventArgs e)
        {
            Guard.NotNull(() => e, e);

            var element = (NamedElementSchema)e.ModelElement;
            if (element != null)
            {
                // Ensure only when de/serializing
                if (element.Store.TransactionManager.CurrentTransaction.IsSerializing)
                {
                    if (element.IsInheritedFromBase)
                    {
                        element.SetLocks(Locks.Delete);
                    }
                }
            }
        }
    }
}


text:
XDG_CONFIG_HOME ?= ${HOME}/.config
XDG_DATA_HOME ?= ${HOME}/.local/share
USER_HOME ?= ${HOME}

$(USER_HOME)/%: ${CURDIR}/%
	mkdir -p $(@D)
	ln -fs $^ $@

.PRECIOUS ${CURDIR}/%:
	touch $@

help:
	cat Makefile | grep '^?.:'

## clean
## - cleanup config w/o bashrc
clean:
	rm -r $(XDG_CONFIG_HOME)/git
	rm -r $(XDG_CONFIG_HOME)/nvim
	rm -r $(XDG_DATA_HOME)/nvim
	rm -r $(XDG_CONFIG_HOME)/tmux
	rm -r $(XDG_CONFIG_HOME)/zsh
	rm $(USER_HOME)/.zshenv
	rm $(USER_HOME)/.screen

## configure
## - config all
configure: zsh bash git vim tmux screen
	@echo "configured"

## brew
homebrew: /usr/local/bin/brew

/usr/local/bin/brew:
	/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

## install from homebrew
brew-install: homebrew
	if ! command -v gh &> /dev/null; then brew install gh; fi
	if ! command -v rg &> /dev/null; then brew install ripgrep; fi
	if ! command -v fzf &> /dev/null; then brew install fzf; fi
	if ! command -v gls &> /dev/null; then brew install coreutils; fi
	if ! command -v tmux &> /dev/null; then brew install tmux; fi
	if ! command -v npm &> /dev/null; then brew install npm; fi
	if ! command -v nvim &> /dev/null; then brew install --HEAD tree-sitter luajit neovim; fi

## zsh
zsh: $(XDG_CONFIG_HOME)/zsh/.zshrc $(XDG_CONFIG_HOME)/zsh/alias $(XDG_CONFIG_HOME)/zsh/.zprofile $(USER_HOME)/.zshenv
	@echo "zsh completed"

## bash
bash: $(USER_HOME)/.bashrc
	@echo "bash completed"

## git
git: $(XDG_CONFIG_HOME)/git/config $(XDG_CONFIG_HOME)/git/ignore
	@echo "git completed"

## vim
vim: $(XDG_CONFIG_HOME)/nvim/init.vim $(XDG_DATA_HOME)/nvim/site/autoload/plug.vim
	mkdir -p $(XDG_DATA_HOME)/nvim/plugged
	@echo "neovim completed"

$(XDG_DATA_HOME)/nvim/site/autoload/plug.vim:
	curl -fLo $@ --create-dirs https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim

## tmux
tmux: $(XDG_CONFIG_HOME)/tmux/tmux.conf
	git clone https://github.com/tmux-plugins/tpm $(XDG_CONFIG_HOME)/tmux/plugins/tpm
	@echo "tmux completed"

## optional
screen: $(USER_HOME)/.screenrc
	@echo "screen completed"


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/ads/googleads/v12/enums/change_status_resource_type.proto

namespace Google\Ads\GoogleAds\V12\Enums;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Container for enum describing supported resource types for the ChangeStatus
 * resource.
 *
 * Generated from protobuf message google.ads.googleads.v12.enums.ChangeStatusResourceTypeEnum
 */
class ChangeStatusResourceTypeEnum extends \Google\Protobuf\Internal\Message
{

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Ads\GoogleAds\V12\Enums\ChangeStatusResourceType::initOnce();
        parent::__construct($data);
    }

}


text:
package Player;

public abstract class Callback_IMetaServer_listSongs extends Ice.TwowayCallback
{
    public abstract void response(MediaInfo[] __ret);

    public final void __completed(Ice.AsyncResult __result)
    {
        IMetaServerPrx __proxy = (IMetaServerPrx)__result.getProxy();
        MediaInfo[] __ret = null;
        try
        {
            __ret = __proxy.end_listSongs(__result);
        }
        catch(Ice.LocalException __ex)
        {
            exception(__ex);
            return;
        }
        response(__ret);
    }
}


text:
<?php

namespace Ladela\RequireJSBundle\Configuration;

use Symfony\Component\HttpKernel\KernelInterface;

class ConfigBuilder
{
    /**
     * @var KernelInterface
     */
    protected $kernel;

    /**
     * @var array
     */
    protected $configs;

    /**
     * Constructor.
     *
     * @param array $configs
     */
    public function __construct(KernelInterface $kernel, array $configs = array())
    {
        $this->kernel  = $kernel;
        $this->configs = $configs;
    }

    /**
     * Get full config with given name.
     *
     * @param string $name
     * @return array
     */
    public function getConfig($name)
    {
        if (!isset ($this->configs[$name])) {
            throw new \InvalidArgumentException(sprintf('There is no "%s" config.', $name));
        }

        return $this->configs[$name];
    }

    /**
     * Get the RequireJS config part.
     *
     * @param string $name
     * @return array
     */
    public function getJavascriptConfig($name)
    {
        $config = $this->getConfig($name);

        return $config['javascript'];
    }

    /**
     * Get the optimizer (r.js) config part.
     *
     * @param string $name
     * @return array
     */
    public function getOptimizerConfig($name)
    {
        $config = $this->getConfig($name);

        // Resolve 'baseUrl' path.
        if ($config['optimizer']['options']['baseUrl'][0] == '@') {
            $config['optimizer']['options']['baseUrl'] = $this->kernel->locateResource($config['optimizer']['options']['baseUrl']);
        }

        // If 'paths' is empty then use from 'javascript'.
        if (empty ($config['optimizer']['options']['paths'])) {
            $config['optimizer']['options']['paths'] = $config['javascript']['options']['paths'];
        }

        // If 'shim' is empty then use from 'javascript'.
        if (empty ($config['optimizer']['options']['shim'])) {
            $config['optimizer']['options']['shim'] = $config['javascript']['options']['shim'];
        }

        return $config['optimizer'];
    }
}


text:
<?php

namespace AppBundle\Form;

use AppBundle\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Validator\Constraints\IsTrue;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;

class UserType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email', EmailType::class,
                array(
                    'invalid_message' => 'Kerjuk egy ervenyes e-mail cimet adjon meg!'
                )
            )
            ->add('password', RepeatedType::class,
                array(
                    'type' => PasswordType::class,
                    'options' => array('attr' => array('class' => 'search-input filter-input password-input')),
                    'first_options'  => array('label' => 'Password'),
                    'second_options' => array('label' => 'Password again'),
                    'invalid_message' => 'A megadott jelszavaknak egyezniuk kell!',
                    'translation_domain' => 'messages'
                )
            )
            ->add('termsAccepted', CheckboxType::class, array(
                'mapped' => false,
                'constraints' => new IsTrue()
            ))->add('newsletter', CheckboxType::class, array(
                'required' => false
            ));
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\User'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'registration_form';
    }

}


text:
<?php
use Migrations\AbstractMigration;

class AddViewedToFeedbacks extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-change-method
     * @return void
     */
    public function change()
    {
        $table = $this->table('feedbacks');
        $table->addColumn('viewed', 'boolean', [
            'default' => null,
            'null' => false,
        ]);
        $table->update();
    }
}


text: I declare api and logic to work with geometry of a Brick


text:
A simple web-based tic-tac-toe app that you can't win:-)

## Screenshot
![alt-text](https://github.com/toddjordan/tic-tac-toe/blob/master/screenshots/tictactoeScreenshot.png "boo-ya")

## Setup
1. Install NodeJS
2. Install Dependencies

```bash
npm install
```
## Run Server
From the project directory run...
```bash
npm start
```
## URL
http://localhost:8000/app

## Run JSHint and Unit Tests
```bash
gulp
```


text:
to_download=${1:-"wiki_only"}

#Download
if [ "$to_download" = "wiki_books" ] ; then
    python3 /workspace/bert/data/bertPrep.py --action download --dataset bookscorpus
fi

python3 /workspace/bert/data/bertPrep.py --action download --dataset wikicorpus_en
python3 /workspace/bert/data/bertPrep.py --action download --dataset google_pretrained_weights  # Includes vocab
python3 /workspace/bert/data/bertPrep.py --action download --dataset squad
python3 /workspace/bert/data/bertPrep.py --action download --dataset mrpc
python3 /workspace/bert/data/bertPrep.py --action download --dataset sst-2

# Properly format the text files
if [ "$to_download" = "wiki_books" ] ; then
    python3 /workspace/bert/data/bertPrep.py --action text_formatting --dataset bookscorpus
fi
python3 /workspace/bert/data/bertPrep.py --action text_formatting --dataset wikicorpus_en

if [ "$to_download" = "wiki_books" ] ; then
    DATASET="books_wiki_en_corpus"
else
    DATASET="wikicorpus_en"
    # Shard the text files
fi

# Shard the text files
python3 /workspace/bert/data/bertPrep.py --action sharding --dataset $DATASET

# Create HDF5 files Phase 1
python3 /workspace/bert/data/bertPrep.py --action create_hdf5_files --dataset $DATASET --max_seq_length 128 \
--max_predictions_per_seq 20 --vocab_file $BERT_PREP_WORKING_DIR/download/google_pretrained_weights/uncased_L-24_H-1024_A-16/vocab.txt --do_lower_case 1

# Create HDF5 files Phase 2
python3 /workspace/bert/data/bertPrep.py --action create_hdf5_files --dataset $DATASET --max_seq_length 512 \
--max_predictions_per_seq 80 --vocab_file $BERT_PREP_WORKING_DIR/download/google_pretrained_weights/uncased_L-24_H-1024_A-16/vocab.txt --do_lower_case 1


text:
require 'xcodeproj/scheme/abstract_scheme_action'

module Xcodeproj
  class XCScheme
    # This class wraps the LaunchAction node of a .xcscheme XML file
    #
    class LaunchAction < AbstractSchemeAction
      # @param [REXML::Element] node
      #        The 'LaunchAction' XML node that this object will wrap.
      #        If nil, will create a default XML node to use.
      #
      def initialize(node = nil)
        create_xml_element_with_fallback(node, 'LaunchAction') do
          self.build_configuration = 'Debug'

          # Add some attributes (that are not handled by this wrapper class yet but expected in the XML)
          @xml_element.attributes['selectedDebuggerIdentifier'] = 'Xcode.DebuggerFoundation.Debugger.LLDB'
          @xml_element.attributes['selectedLauncherIdentifier'] = 'Xcode.DebuggerFoundation.Launcher.LLDB'
          @xml_element.attributes['launchStyle'] = '0'
          @xml_element.attributes['useCustomWorkingDirectory'] = bool_to_string(false)
          @xml_element.attributes['ignoresPersistentStateOnLaunch'] = bool_to_string(false)
          @xml_element.attributes['debugDocumentVersioning'] = bool_to_string(true)
          @xml_element.attributes['debugServiceExtension'] = 'internal'

          # Setup default values for other (handled) attributes
          self.allow_location_simulation = true
        end
      end

      # @todo handle 'launchStyle' attribute
      # @todo handle 'useCustomWorkingDirectory attribute
      # @todo handle 'ignoresPersistentStateOnLaunch' attribute
      # @todo handle 'debugDocumentVersioning' attribute
      # @todo handle 'debugServiceExtension'

      # @return [Bool]
      #         Whether or not to allow GPS location simulation when launching this target
      #
      def allow_location_simulation?
        string_to_bool(@xml_element.attributes['allowLocationSimulation'])
      end

      # @param [Bool] flag
      #        Set whether or not to allow GPS location simulation when launching this target
      #
      def allow_location_simulation=(flag)
        @xml_element.attributes['allowLocationSimulation'] = bool_to_string(flag)
      end

      # @return [LocationScenarioReference]
      #         The LocationScenarioReference to simulate a GPS location when executing the Launch Action
      #
      def location_scenario_reference?
        LocationScenarioReference.new(@xml_element.elements['LocationScenarioReference'])
      end

      # @return [LocationScenarioReference]
      #         Set the LocationScenarioReference which simulates a GPS location when executing the Launch Action
      #
      def location_scenario_reference=(reference)
        @xml_element.delete_element('LocationScenarioReference')
        @xml_element.add_element(reference.xml_element) if reference
      end

      # @return [Bool]
      #         Whether this Build Action should disable detection of UI API misuse
      #         from background threads
      #
      def disable_main_thread_checker?
        string_to_bool(@xml_element.attributes['disableMainThreadChecker'])
      end

      # @param [Bool] flag
      #        Set whether this Build Action should disable detection of UI API misuse
      #        from background threads
      #
      def disable_main_thread_checker=(flag)
        @xml_element.attributes['disableMainThreadChecker'] = bool_to_string(flag)
      end

      # @return [Bool]
      #         Whether UI API misuse from background threads detection should pause execution.
      #         This flag is ignored when the thread checker disabled
      #         ([disable_main_thread_checker] flag).
      #
      def stop_on_every_main_thread_checker_issue?
        string_to_bool(@xml_element.attributes['stopOnEveryMainThreadCheckerIssue'])
      end

      # @param [Bool] flag
      #         Set whether UI API misuse from background threads detection should pause execution.
      #         This flag is ignored when the thread checker disabled
      #         ([disable_main_thread_checker] flag).
      #
      def stop_on_every_main_thread_checker_issue=(flag)
        @xml_element.attributes['stopOnEveryMainThreadCheckerIssue'] = bool_to_string(flag)
      end

      # @return [String]
      #         The launch automatically substyle
      #
      def launch_automatically_substyle
        @xml_element.attributes['launchAutomaticallySubstyle']
      end

      # @param [String] flag
      #        Set the launch automatically substyle ('2' for extensions)
      #
      def launch_automatically_substyle=(value)
        @xml_element.attributes['launchAutomaticallySubstyle'] = value.to_s
      end

      # @return [BuildableProductRunnable]
      #         The BuildReference to launch when executing the Launch Action
      #
      def buildable_product_runnable
        BuildableProductRunnable.new(@xml_element.elements['BuildableProductRunnable'], 0)
      end

      # @param [BuildableProductRunnable] runnable
      #        Set the BuildableProductRunnable referencing the target to launch
      #
      def buildable_product_runnable=(runnable)
        @xml_element.delete_element('BuildableProductRunnable')
        @xml_element.add_element(runnable.xml_element) if runnable
      end

      # @return [EnvironmentVariables]
      #         Returns the EnvironmentVariables that will be defined at app launch
      #
      def environment_variables
        EnvironmentVariables.new(@xml_element.elements[XCScheme::VARIABLES_NODE])
      end

      # @param [EnvironmentVariables,nil] env_vars
      #        Sets the EnvironmentVariables that will be defined at app launch
      #
      def environment_variables=(env_vars)
        @xml_element.delete_element(XCScheme::VARIABLES_NODE)
        @xml_element.add_element(env_vars.xml_element) if env_vars
        env_vars
      end

      # @todo handle 'AdditionalOptions' tag

      # @return [CommandLineArguments]
      #         Returns the CommandLineArguments that will be passed at app launch
      #
      def command_line_arguments
        CommandLineArguments.new(@xml_element.elements[XCScheme::COMMAND_LINE_ARGS_NODE])
      end

      # @return [CommandLineArguments] arguments
      #         Sets the CommandLineArguments that will be passed at app launch
      #
      def command_line_arguments=(arguments)
        @xml_element.delete_element(XCScheme::COMMAND_LINE_ARGS_NODE)
        @xml_element.add_element(arguments.xml_element) if arguments
        arguments
      end

      # @return [Array<MacroExpansion>]
      #         The list of MacroExpansion bound with this LaunchAction
      #
      def macro_expansions
        @xml_element.get_elements('MacroExpansion').map do |node|
          MacroExpansion.new(node)
        end
      end

      # @param [MacroExpansion] macro_expansion
      #        Add a MacroExpansion to this LaunchAction
      #
      def add_macro_expansion(macro_expansion)
        @xml_element.add_element(macro_expansion.xml_element)
      end
    end
  end
end


text:
.. _string: ../../str

.. _vim.fault.InvalidState: ../../vim/fault/InvalidState.rst

vim.fault.InvalidPowerState
===========================
    :extends:

        `vim.fault.InvalidState`_

  This exception is thrown if the power operation attempted could not be performed given the current power state of the virtual machine.

Attributes:

    requestedState (`str`_): is optional.

    existingState (`str`_)


text:
/*global describe, it*/

var assert = require("assert"),
    Htmlizer = require('../src/Htmlizer.js'),
    util = require('./util/util.js');

describe('with void elements', function () {
    var html = '

foo

',
        outputHtml = (new Htmlizer(html)).toString();
    it('it should serialize without an end tag and the self-closing slash marker', function () {
        assert.strictEqual(outputHtml, html);
    });
});

require('./text-and-attr/test.js')(Htmlizer, assert, util);

require('./html/test.js')(Htmlizer, assert, util);

require('./if/test.js')(Htmlizer, assert, util);

require('./foreach/test.js')(Htmlizer, assert, util);

require('./css-and-style/test.js')(Htmlizer, assert, util);

require('./with/test.js')(Htmlizer, assert, util);

describe('run binding context test', function () {
    var html = util.fetch('test/binding-context-tpl.html'),
        outputHtml = (new Htmlizer(html)).toString({
            items: [{
                name: 'item1',
                subItems: [{
                    name: 'subitem1'
                }]
            }]
        }),
        df = util.htmlToDocumentFragment(outputHtml);

    var count = 0;
    util.traverse(df, df, function (node, isOpenTag) {
        if (isOpenTag && node.nodeType === 1 && node.nodeName === 'SPAN') {
            count += 1;
            if (count >= 1 && count <= 2) {
                it('span ' + count + ' text should be "item1"', function () {
                    assert.strictEqual('item1', node.textContent);
                });
            }
            if (count === 3) {
                it('span 4 text should be "0"', function () {
                    assert.strictEqual('0', node.textContent);
                });
            }
            if (count >= 4 && count <= 5) {
                it('span ' + count + ' text should be "subitem1"', function () {
                    assert.strictEqual('subitem1', node.textContent);
                });
            }
            if (count === 6) {
                it('span 6 text should be "true"', function () {
                    assert.strictEqual('true', node.textContent);
                });
            }
        }
    });
});

describe('run disable,enable,checked and value binding test', function () {
    var html = util.fetch('test/misc-attr-binding-tpl.html'),
        outputHtml = (new Htmlizer(html)).toString({}),
        df = util.htmlToDocumentFragment(outputHtml);
    it('first child should have disabled="disabled"', function () {
        assert.strictEqual('disabled', df.children[0].getAttribute('disabled'));
    });
    it('second child should also have disabled="disabled"', function () {
        assert.strictEqual('disabled', df.children[1].getAttribute('disabled'));
    });
    it('third child should have checked="checked"', function () {
        assert.strictEqual('checked', df.children[2].getAttribute('checked'));
    });
    it('fourth child should also have value="Hi"', function () {
        assert.strictEqual('Hi', df.children[3].getAttribute('value'));
    });
    it('fifth child should also have display none', function () {
        assert.strictEqual('none', df.children[4].style.display);
    });
});

require('./no-conflict/test.js')(Htmlizer, assert, util);

describe('run keepKOBindings test', function () {
    var tpl = '',
        outputHtml = (new Htmlizer(tpl, {keepKOBindings:true})).toString({});
    it('should keep data-bind attribute, ko comments and also render known bindings', function () {
        assert.strictEqual('hihi', outputHtml);
    });
});

require('./template/test.js')(Htmlizer, assert, util);


text:
<?php

// @codingStandardsIgnoreFile

namespace Magento\Setup\Test\Unit\Module\Di\Code\Scanner;

class PluginScannerTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        $this->_model = new \Magento\Setup\Module\Di\Code\Scanner\PluginScanner();
        $this->_testDir = str_replace('\\', '/', realpath(__DIR__ . '/../../') . '/_files');
        $this->_testFiles = [
            $this->_testDir . '/app/code/Magento/SomeModule/etc/di.xml',
            $this->_testDir . '/app/etc/di/config.xml',
        ];
    }

    protected function tearDown()
    {
        unset($this->_model);
    }

    public function testCollectEntities()
    {
        $actual = $this->_model->collectEntities($this->_testFiles);
        $expected = ['Magento\Framework\App\Cache\TagPlugin', 'Magento\Store\Model\Action\Plugin'];
        $this->assertEquals($expected, $actual);
    }
}


text:
Baseline models
---------------

This submodule contains the simple baseline models like nearest neighbor or most popular.


text:
class MapContext:
    # read a chunk, store it in memory, and can pop all element of the chunk
    def __init__(self,outputMapFileName,iterator):
        self.keysList = []
        self.valuesList = []
        self.key = None
        self.value = None
        self.iterator = iterator;
        return

    def putKeyValue(self,key,value):
        self.keysList.append(str(key).rstrip('\n'))
        self.valuesList.append(str(value).rstrip('\n'))
        return

    def loadNext(self):
        self.key = self.keysList.pop();
        self.value = self.valuesList.pop();
        return

    def hasNext(self):
        return len(self.keysList) >= 1


text:
package com.thoughtworks.go.websocket;

import com.google.gson.*;
import com.thoughtworks.go.domain.AgentRuntimeStatus;
import com.thoughtworks.go.remote.AgentIdentifier;
import com.thoughtworks.go.remote.work.Work;
import com.thoughtworks.go.server.service.AgentBuildingInfo;
import com.thoughtworks.go.server.service.AgentRuntimeInfo;
import com.thoughtworks.go.server.service.ElasticAgentRuntimeInfo;
import com.thoughtworks.go.util.StringUtil;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import static com.thoughtworks.go.util.ExceptionUtils.bomb;

public class MessageEncoding {

    private static Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().registerTypeAdapter(AgentRuntimeInfo.class, new AgentRuntimeInfoTypeAdapter()).create();

    public static String encodeWork(Work work) {
        try {
            try (ByteArrayOutputStream binaryOutput = new ByteArrayOutputStream()) {
                try (ObjectOutputStream objectStream = new ObjectOutputStream(binaryOutput)) {
                    objectStream.writeObject(work);
                }
                return Base64.getEncoder().encodeToString(binaryOutput.toByteArray());
            }
        } catch (IOException e) {
            throw bomb(e);
        }
    }

    public static Work decodeWork(String data) {
        try {
            byte[] binary = Base64.getDecoder().decode(data.getBytes(StandardCharsets.UTF_8));
            try (ObjectInputStream objectStream = new ObjectInputStream(new ByteArrayInputStream(binary))) {
                return (Work) objectStream.readObject();
            }
        } catch (ClassNotFoundException | IOException e) {
            throw bomb(e);
        }
    }

    public static byte[] encodeMessage(Message msg) {
        String encode = gson.toJson(msg);
        try {
            try (ByteArrayOutputStream bytes = new ByteArrayOutputStream()) {
                try (GZIPOutputStream out = new GZIPOutputStream(bytes)) {
                    out.write(encode.getBytes(StandardCharsets.UTF_8));
                    out.finish();
                }
                return bytes.toByteArray();
            }
        } catch (IOException e) {
            throw bomb(e);
        }
    }

    public static Message decodeMessage(InputStream input) {
        try {
            try (GZIPInputStream zipStream = new GZIPInputStream(input)) {
                String jsonStr = new String(IOUtils.toByteArray(zipStream), StandardCharsets.UTF_8);
                return gson.fromJson(jsonStr, Message.class);
            }
        } catch (IOException e) {
            throw bomb(e);
        }
    }

    public static String encodeData(Object obj) {
        return gson.toJson(obj);
    }

    public static <T> T decodeData(String data, Class<T> aClass) {
        return gson.fromJson(data, aClass);
    }

    // todo: Remove hand wrote deserialization after merging ElasticAgentRuntimeInfo class into AgentRuntimeInfo (@wpc)
    private static class AgentRuntimeInfoTypeAdapter implements JsonDeserializer<AgentRuntimeInfo> {
        @Override
        public AgentRuntimeInfo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            JsonObject jsonObject = json.getAsJsonObject();

            AgentIdentifier identifier = context.deserialize(jsonObject.get("identifier"), AgentIdentifier.class);
            AgentRuntimeStatus runtimeStatus = context.deserialize(jsonObject.get("runtimeStatus"), AgentRuntimeStatus.class);
            AgentBuildingInfo buildingInfo = context.deserialize(jsonObject.get("buildingInfo"), AgentBuildingInfo.class);
            String location = jsonObject.has("location") ? jsonObject.get("location").getAsString() : null;
            Long usableSpace = jsonObject.has("usableSpace") ? jsonObject.get("usableSpace").getAsLong() : null;
            String operatingSystemName = jsonObject.has("operatingSystemName") ? jsonObject.get("operatingSystemName").getAsString() : null;
            String cookie = jsonObject.has("cookie") ? jsonObject.get("cookie").getAsString() : null;
            boolean supportsBuildCommandProtocol = jsonObject.has("supportsBuildCommandProtocol") && jsonObject.get("supportsBuildCommandProtocol").getAsBoolean();
            String elasticPluginId = jsonObject.has("elasticPluginId") ? jsonObject.get("elasticPluginId").getAsString() : null;
            String elasticAgentId = jsonObject.has("elasticAgentId") ? jsonObject.get("elasticAgentId").getAsString() : null;

            AgentRuntimeInfo info;
            if (elasticPluginId == null || StringUtil.isBlank(elasticPluginId)) {
                info = new AgentRuntimeInfo(identifier, runtimeStatus, location, cookie, supportsBuildCommandProtocol);
            } else {
                info = new ElasticAgentRuntimeInfo(identifier, runtimeStatus, location, cookie, elasticAgentId, elasticPluginId);
            }
            info.setUsableSpace(usableSpace);
            info.setOperatingSystem(operatingSystemName);
            info.setSupportsBuildCommandProtocol(supportsBuildCommandProtocol);
            info.setBuildingInfo(buildingInfo);
            return info;
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace Gedmo\Tests\Sluggable\Fixture;

use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\Sluggable\Sluggable;
use Gedmo\Translatable\Translatable;

/**
 * @ORM\Entity
 */
#[ORM\Entity]
class TranslatableArticle implements Sluggable, Translatable
{
    /**
     * @var int|null
     *
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: Types::INTEGER)]
    private $id;

    /**
     * @var string|null
     *
     * @Gedmo\Translatable
     * @ORM\Column(type="string", length=64)
     */
    #[ORM\Column(type: Types::STRING, length: 64)]
    #[Gedmo\Translatable]
    private $title;

    /**
     * @var string|null
     *
     * @Gedmo\Translatable
     * @ORM\Column(type="string", length=16)
     */
    #[ORM\Column(type: Types::STRING, length: 16)]
    #[Gedmo\Translatable]
    private $code;

    /**
     * @var string|null
     *
     * @Gedmo\Translatable
     * @Gedmo\Slug(fields={"title", "code"})
     * @ORM\Column(type="string", length=128)
     */
    #[ORM\Column(type: Types::STRING, length: 128)]
    #[Gedmo\Translatable]
    #[Gedmo\Slug(fields: ['title', 'code'])]
    private $slug;

    /**
     * @var Collection<int, Comment>
     *
     * @ORM\OneToMany(targetEntity="Comment", mappedBy="article")
     */
    #[ORM\OneToMany(targetEntity: Comment::class, mappedBy: 'article')]
    private $comments;

    /**
     * @var Page|null
     *
     * @ORM\ManyToOne(targetEntity="Page", inversedBy="articles")
     */
    #[ORM\ManyToOne(targetEntity: Page::class, inversedBy: 'articles')]
    private $page;

    /**
     * @var string|null
     *
     * @Gedmo\Locale
     * Used locale to override Translation listener`s locale
     */
    #[Gedmo\Language]
    private $locale;

    public function addComment(Comment $comment): void
    {
        $comment->setArticle($this);
        $this->comments[] = $comment;
    }

    /**
     * @return Collection<int, Comment>
     */
    public function getComments(): Collection
    {
        return $this->comments;
    }

    public function setPage(?Page $page): void
    {
        $this->page = $page;
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function setTitle(?string $title): void
    {
        $this->title = $title;
    }

    public function getTitle(): ?string
    {
        return $this->title;
    }

    public function setCode(?string $code): void
    {
        $this->code = $code;
    }

    public function getCode(): ?string
    {
        return $this->code;
    }

    public function getSlug(): ?string
    {
        return $this->slug;
    }

    public function setTranslatableLocale(?string $locale): void
    {
        $this->locale = $locale;
    }
}


text:
set -e

# Locate the script file.  Cross symlinks if necessary.
loc="$0"
while [ -h "$loc" ]; do
    ls=`ls -ld "$loc"`
    link=`expr "$ls" : '.*-> \(.*\)$'`
    if expr "$link" : '/.*' > /dev/null; then
        loc="$link"  # Absolute link
    else
        loc="`dirname "$loc"`/$link"  # Relative link
    fi
done
export base_dir=$(cd "`dirname "$loc"`" && pwd)

python_cmd="$1"
support_lib="$base_dir/../support-lib"

in="$base_dir/djinni/py_all.djinni"

export python_out="$base_dir/generated-src/python"
export cffi_out="$base_dir/generated-src/cffi"
export py_hw="$base_dir/handwritten-src/python"
export wrapper_marshal="../../support-lib/cwrapper/wrapper_marshal.h"
export limits_helper="$base_dir/handwritten-src/cwrapper/limits_helper.h"

export PYTHONPATH="$support_lib/py:$base_dir/pybuild:$base_dir/generated-src/python:$PYTHONPATH"
# echo $PYTHONPATH

export lib="libmylib.dylib"
mkdir -p "$base_dir/pybuild"
export pyb=$base_dir/pybuild

# Clean command
if [ "$python_cmd" == "clean" ]; then
    ./run_py_djinni.sh clean
    (cd $pyb && make -f ../PyCFFI.mk clean)
    exit
fi

./run_py_djinni.sh

# Generate the dynamic library
(export fname=foo_interface && cd $pyb && make -f ../PyCFFI.mk $lib)

# Build and test CFFI module
"$python_cmd" --version
(cd $pyb \
        && cffi_dep=($(ls ../generated-src/cwrapper/*.h)) \
        && cffi_dep+=($limits_helper) \
        && "$python_cmd" $cffi_out/pycffi_lib_build.py $wrapper_marshal ${cffi_dep[*]} \
        && "$python_cmd" -m pytest -s  $py_hw)


text:
layout: page-api
title: QUnit.config.maxDepth
excerpt: The depth up-to which an object will be serialized during a diff (HTML Reporter).
groups:
  - config
version_added: "1.16.0"
---

In the HTML Reporter, the depth up-to which an object will be serialized during the diff of an assertion failure.

  type
  `number`

  default
  `5`

To disable the depth limit, use a value of `-1`.

This is used by [`QUnit.dump.parse()`](../extension/QUnit.dump.parse.md).


text:
CHANGELOG
=========

v. 1.1.0
--------
*25 Oct 2015*

- added icons from 2.0 version of the original weather-icons project
- updated compile sdk version
- updated Gradle Build Tools version

v. 1.0.0
--------
*21 Jul 2015*

First release of the library available on Maven Central Repository.
JavaDoc is available at: http://pwittchen.github.io/WeatherIconView/


text:
  {% include "./../filters/filters.html" %}
  {% include "./../sort/sort.html" %}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>ColumnHelper (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.poi.xssf.usermodel.helpers

Class ColumnHelper

java.lang.Object

org.apache.poi.xssf.usermodel.helpers.ColumnHelper

public class ColumnHelper
extends java.lang.Object

Helper class for dealing with the Column settings on
  a CTWorksheet (the data part of a sheet).
 Note - within POI, we use 0 based column indexes, but
  the column definitions in the XML are 1 based!

Constructor Summary

Constructors

Constructor and Description

ColumnHelper(org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet worksheet)

Method Summary

Methods

Modifier and Type
Method and Description

org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols
addCleanColIntoCols(org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols cols,
                   org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol col)

void
cleanColumns()

org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol
cloneCol(org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols cols,
        org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol col)

boolean
columnExists(org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols cols,
            long index)

Does the column at the given 0 based index exist
  in the supplied list of column definitions?

int
getColDefaultStyle(long index)

org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol
getColumn(long index,
         boolean splitColumns)

Returns the Column at the given 0 based index

org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol
getColumn1Based(long index1,
               boolean splitColumns)

Returns the Column at the given 1 based index.

int
getIndexOfColumn(org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols cols,
                org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol col)

protected org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol
getOrCreateColumn1Based(long index1,
                       boolean splitColumns)

Return the CTCol at the given (0 based) column index,
  creating it if required.

void
setColBestFit(long index,
             boolean bestFit)

void
setColDefaultStyle(long index,
                  CellStyle style)

void
setColDefaultStyle(long index,
                  int styleId)

void
setColHidden(long index,
            boolean hidden)

void
setColumnAttributes(org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol fromCol,
                   org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol toCol)

void
setColWidth(long index,
           double width)

void
setCustomWidth(long index,
              boolean bestFit)

static void
sortColumns(org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols newCols)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ColumnHelper

public ColumnHelper(org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet worksheet)

Method Detail

cleanColumns

public void cleanColumns()

sortColumns

public static void sortColumns(org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols newCols)

cloneCol

public org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol cloneCol(org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols cols,
                                                                 org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol col)

getColumn

public org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol getColumn(long index,
                                                                  boolean splitColumns)

Returns the Column at the given 0 based index

getColumn1Based

public org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol getColumn1Based(long index1,
                                                                        boolean splitColumns)

Returns the Column at the given 1 based index.
 POI default is 0 based, but the file stores
  as 1 based.

addCleanColIntoCols

public org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols addCleanColIntoCols(org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols cols,
                                                                             org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol col)

columnExists

public boolean columnExists(org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols cols,
                   long index)

Does the column at the given 0 based index exist
  in the supplied list of column definitions?

setColumnAttributes

public void setColumnAttributes(org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol fromCol,
                       org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol toCol)

setColBestFit

public void setColBestFit(long index,
                 boolean bestFit)

setCustomWidth

public void setCustomWidth(long index,
                  boolean bestFit)

setColWidth

public void setColWidth(long index,
               double width)

setColHidden

public void setColHidden(long index,
                boolean hidden)

getOrCreateColumn1Based

protected org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol getOrCreateColumn1Based(long index1,
                                                                                boolean splitColumns)

Return the CTCol at the given (0 based) column index,
  creating it if required.

setColDefaultStyle

public void setColDefaultStyle(long index,
                      CellStyle style)

setColDefaultStyle

public void setColDefaultStyle(long index,
                      int styleId)

getColDefaultStyle

public int getColDefaultStyle(long index)

getIndexOfColumn

public int getIndexOfColumn(org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols cols,
                   org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol col)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

                Copyright 2014 The Apache Software Foundation or
        its licensors, as applicable.