text:
ALTER TABLE ONLY partners ALTER COLUMN slug SET NOT NULL;

-- +migrate Down
-- SQL section 'Down' is executed when this migration is rolled back
ALTER TABLE ONLY partners ALTER COLUMN slug DROP NOT NULL;

redpajama_set_name: RedPajamaGithub


text: CKEDITOR.plugins.setLang("print","ar",{toolbar:"طباعة"});


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Hedwigia 67: 274 (1927)

#### Original name
Phylloporina cupreola Müll. Arg.

### Remarks
null


text:
package com.cognifide.apm.core.scripts;

import com.cognifide.apm.api.scripts.LaunchEnvironment;
import com.cognifide.apm.api.scripts.LaunchMode;
import com.cognifide.apm.api.scripts.MutableScript;
import com.cognifide.apm.core.utils.ResourceMixinUtil;
import com.day.cq.commons.jcr.JcrConstants;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.commons.lang.BooleanUtils;
import org.apache.sling.api.resource.ModifiableValueMap;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.Optional;
import org.apache.sling.models.annotations.injectorspecific.Self;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Model(adaptables = Resource.class)
public class ScriptModel implements MutableScript {

  private static Logger LOGGER = LoggerFactory.getLogger(ScriptModel.class);

  private final String path;

  @Self
  private Resource resource;

  @Inject
  @Named(ScriptNode.APM_LAUNCH_ENABLED)
  @Optional
  private Boolean launchEnabled;

  @Inject
  @Named(ScriptNode.APM_LAUNCH_MODE)
  @Optional
  private String launchMode;

  @Inject
  @Named(ScriptNode.APM_LAUNCH_ENVIRONMENT)
  @Optional
  private String launchEnvironment;

  @Inject
  @Named(ScriptNode.APM_LAUNCH_RUN_MODES)
  @Optional
  private String[] launchRunModes;

  @Inject
  @Named(ScriptNode.APM_LAUNCH_HOOK)
  @Optional
  private String launchHook;

  @Inject
  @Named(ScriptNode.APM_LAUNCH_SCHEDULE)
  @Optional
  private Date launchSchedule;

  @Inject
  @Named(ScriptNode.APM_LAST_EXECUTED)
  @Optional
  private Date lastExecuted;

  @Inject
  @Named(ScriptNode.APM_CHECKSUM)
  @Optional
  private String checksum;

  @Inject
  @Named(ScriptNode.APM_PUBLISH_RUN)
  @Optional
  private Boolean publishRun;

  @Inject
  @Named(ScriptNode.APM_REPLICATED_BY)
  @Optional
  private String replicatedBy;

  @Inject
  @Named(ScriptNode.APM_VERIFIED)
  @Optional
  private Boolean verified;

  @Inject
  @Named(JcrConstants.JCR_CONTENT + "/" + JcrConstants.JCR_LASTMODIFIED)
  @Optional
  private Date lastModified;

  @Inject
  @Named(JcrConstants.JCR_CREATED_BY)
  @Optional
  private String author;

  private String data;

  public ScriptModel(Resource resource) {
    this.path = resource.getPath();
  }

  @Override
  public boolean isValid() {
    return BooleanUtils.toBoolean(verified);
  }

  @Override
  public LaunchMode getLaunchMode() {
    return (launchMode == null) ? LaunchMode.ON_DEMAND : LaunchMode.from(launchMode)
        .orElseGet(() -> {
          LOGGER.warn("Cannot match {} to existing launch modes. Using default one", launchMode);
          return LaunchMode.ON_DEMAND;
        });
  }

  @Override
  public String getLaunchHook() {
    return launchHook;
  }

  @Override
  public LaunchEnvironment getLaunchEnvironment() {
    return (launchEnvironment == null) ? LaunchEnvironment.ALL : LaunchEnvironment.from(launchEnvironment)
        .orElseGet(() -> {
          LOGGER.warn("Cannot match {} to existing launch environments. Using default one", launchEnvironment);
          return LaunchEnvironment.ALL;
        });
  }

  @Override
  public Set<String> getLaunchRunModes() {
    return launchRunModes == null ? null : Sets.newHashSet(launchRunModes);
  }

  @Override
  public Date getLaunchSchedule() {
    return launchSchedule;
  }

  @Override
  public boolean isLaunchEnabled() {
    return BooleanUtils.isNotFalse(launchEnabled);
  }

  @Override
  public Date getLastExecuted() {
    return lastExecuted;
  }

  @Override
  public boolean isPublishRun() {
    return BooleanUtils.toBoolean(publishRun);
  }

  @Override
  public String getPath() {
    return path;
  }

  @Override
  public String getChecksum() {
    return checksum;
  }

  @Override
  public String getAuthor() {
    return author;
  }

  @Override
  public Date getLastModified() {
    return lastModified;
  }

  @Override
  public String getData() {
    if (data == null) {
      Resource child = resource.getChild(JcrConstants.JCR_CONTENT);
      if (child != null) {
        data = child.getValueMap().get(JcrConstants.JCR_DATA, String.class);
      } else {
        data = "";
      }
    }
    return data;
  }

  @Override
  public String getReplicatedBy() {
    return replicatedBy;
  }

  @Override
  public void setChecksum(String checksum) throws PersistenceException {
    this.checksum = checksum;
    setProperty(ScriptNode.APM_CHECKSUM, checksum);
  }

  @Override
  public void setValid(boolean flag) throws PersistenceException {
    this.verified = flag;
    setProperty(ScriptNode.APM_VERIFIED, flag);
  }

  @Override
  public void setLastExecuted(Date date) throws PersistenceException {
    this.lastExecuted = date;
    setProperty(ScriptNode.APM_LAST_EXECUTED, date);
  }

  @Override
  public void setPublishRun(boolean flag) throws PersistenceException {
    this.publishRun = flag;
    setProperty(ScriptNode.APM_PUBLISH_RUN, flag);
  }

  @Override
  public void setReplicatedBy(String userId) throws PersistenceException {
    this.replicatedBy = userId;
    setProperty(ScriptNode.APM_REPLICATED_BY, userId);
  }

  private void setProperty(String name, Object value) throws PersistenceException {
    ModifiableValueMap vm = resource.adaptTo(ModifiableValueMap.class);
    ResourceMixinUtil.addMixin(vm, ScriptNode.APM_SCRIPT);
    vm.put(name, convertValue(value));

    resource.getResourceResolver().commit();
  }

  private Object convertValue(Object obj) {
    if (obj instanceof Date) {
      Calendar calendar = new GregorianCalendar();
      calendar.setTime((Date) obj);

      return calendar;
    }

    return obj;
  }

  public static boolean isScript(Resource resource) {
    return java.util.Optional.ofNullable(resource)
        .map(child -> getArrayProperty(child, JcrConstants.JCR_MIXINTYPES).contains(ScriptNode.APM_SCRIPT))
        .orElse(false);
  }

  private static List<String> getArrayProperty(Resource resource, String name) {
    return Lists.newArrayList(resource.getValueMap().get(name, new String[]{}));
  }
}


text:
<?php
mysql_connect(DATABASE_HOST,DATABASE_USER,DATABASE_PASSWORD);
mysql_select_db(DATABASE_NAME);
/*$sql="select * from ". TBL_THEME;
$d=mysql_query($sql) or die(mysql_error());
$row=mysql_fetch_array($d);
*/
?>


text:
describe('HomePage', function(){
	it('can render the homepage', function(){
		browser.get('/');
		var headerElem = element(by.css('h1.title'));

		expect(headerElem).not.to.be.null;

	});
});


text: {-# htermination max :: Char -> Char -> Char #-}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Copyright (C) 2006-2007 the original author or authors.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->

<!-- $Id$ -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.codehaus.gmaven.it.gmaven-plugin.execute</groupId>
        <artifactId>common</artifactId>
        <version>@project.version@</version>
        <relativePath>../common.xml</relativePath>
    </parent>

    <artifactId>execute-inline-2</artifactId>

    <description>
        Tests inline with script path.
    </description>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.gmaven</groupId>
                <artifactId>gmaven-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>compile</phase>
                        <goals>
                            <goal>execute</goal>
                        </goals>
                        <configuration>
                            <scriptpath>
                                <element>${pom.basedir}/src/main/groovy</element>
                            </scriptpath>
                            <source>
                                class Hello extends HelloSupport {}
                                new Hello().hello()
                            </source>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
package com.akiban.sql.parser;

import com.akiban.sql.StandardException;

/**
 * A DMLStatement for a table modification: to wit, INSERT
 * UPDATE or DELETE.
 *
 */

public abstract class DMLModStatementNode extends DMLStatementNode
{
    protected FromVTI targetVTI;
    protected TableName targetTableName;
    protected ResultColumnList returningColumnList;
    private int statementType;

    /**
     * Initializer for a DMLModStatementNode -- delegate to DMLStatementNode
     *
     * @param resultSet A ResultSetNode for the result set of the
     *                                  DML statement
     */
    public void init(Object resultSet) {
        super.init(resultSet);
        statementType = getStatementType();
    }

    /**
     * Initializer for a DMLModStatementNode -- delegate to DMLStatementNode
     *
     * @param resultSet A ResultSetNode for the result set of the
     *                                  DML statement
     * @param statementType used by nodes that allocate a DMLMod directly
     *                                          (rather than inheriting it).
     */
    public void init(Object resultSet, Object statementType) {
        super.init(resultSet);
        this.statementType = ((Integer)statementType).intValue();
    }

    /**
     * Fill this node with a deep copy of the given node.
     */
    public void copyFrom(QueryTreeNode node) throws StandardException {
        super.copyFrom(node);

        DMLModStatementNode other = (DMLModStatementNode)node;
        this.targetVTI = (FromVTI)getNodeFactory().copyNode(other.targetVTI,
                                                            getParserContext());
        this.targetTableName = (TableName)getNodeFactory().copyNode(other.targetTableName,
                                                                    getParserContext());
        this.statementType = other.statementType;

        this.returningColumnList = (ResultColumnList)getNodeFactory()
                .copyNode(other.returningColumnList, getParserContext());
    }

    void setTarget(QueryTreeNode targetName) {
        if (targetName instanceof TableName) {
            this.targetTableName = (TableName)targetName;
        }
        else {
            this.targetVTI = (FromVTI)targetName;
            targetVTI.setTarget();
        }
    }

    /**
     *
     * INSERT/UPDATE/DELETE are always atomic.
     *
     * @return true
     */
    public boolean isAtomic() {
        return true;
    }

    public TableName getTargetTableName() {
        return targetTableName;
    }

    public ResultColumnList getReturningList() {
        return this.returningColumnList;
    }

    public void setReturningList(ResultColumnList returningColumnList) {
        this.returningColumnList = returningColumnList;
    }

    /**
     * Prints the sub-nodes of this object.  See QueryTreeNode.java for
     * how tree printing is supposed to work.
     *
     * @param depth The depth of this node in the tree
     */

    public void printSubNodes(int depth) {
        super.printSubNodes(depth);

        printLabel(depth, "targetTableName: ");
        targetTableName.treePrint(depth + 1);

        if (returningColumnList != null) {
            printLabel(depth, "returningList: ");
            returningColumnList.treePrint(depth+1);
        }
    }

    /**
     * Accept the visitor for all visitable children of this node.
     *
     * @param v the visitor
     *
     * @exception StandardException on error
     */
    void acceptChildren(Visitor v) throws StandardException {
        super.acceptChildren(v);

        if (targetTableName != null) {
            targetTableName.accept(v);
        }
        if (returningColumnList != null) {
            returningColumnList.accept(v);
        }
    }
}


text:
package templates_test

import (
	"testing"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

func TestWebV1TemplatesSuite(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "v1/web/templates")
}


text:
<PurchaseOrder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://localhost:8080/source/schemas/poSource/xsd/purchaseOrder.xsd">
   <Reference>SKING-20021009123336321PDT</Reference>
   <Actions>
      <Action>
         <User/>
      </Action>
   </Actions>
   <Reject/>
   <Requestor>Steven A. King</Requestor>
   <User>SKING</User>
   <CostCenter>A10</CostCenter>
   <ShippingInstructions>
      <name>Steven A. King</name>
      <address>500 Oracle Parkway
Redwood Shores
CA
94065
USA</address>
      <telephone>650 506 7500</telephone>
   </ShippingInstructions>
   <SpecialInstructions>Expedite</SpecialInstructions>
   <LineItems>
      <LineItem ItemNumber="1">
         <Description>M</Description>
         <Part Id="37429126523" UnitPrice="29.95" Quantity="3"/>
      </LineItem>
      <LineItem ItemNumber="2">
         <Description>Alexander Nevsky</Description>
         <Part Id="37429149225" UnitPrice="0.0" Quantity="4"/>
      </LineItem>
      <LineItem ItemNumber="3">
         <Description>Wages of Fear</Description>
         <Part Id="37429134924" UnitPrice="29.95" Quantity="4"/>
      </LineItem>
      <LineItem ItemNumber="4">
         <Description>Great Expectations</Description>
         <Part Id="37429128022" UnitPrice="39.95" Quantity="2"/>
      </LineItem>
      <LineItem ItemNumber="5">
         <Description>The Red Shoes</Description>
         <Part Id="37429128220" UnitPrice="39.95" Quantity="1"/>
      </LineItem>
      <LineItem ItemNumber="6">
         <Description>The Importance of Being Earnest</Description>
         <Part Id="37429165621" UnitPrice="29.95" Quantity="3"/>
      </LineItem>
      <LineItem ItemNumber="7">
         <Description>That Obscure Object of Desire</Description>
         <Part Id="37429162026" UnitPrice="29.95" Quantity="4"/>
      </LineItem>
      <LineItem ItemNumber="8">
         <Description>The Last Temptation of Christ</Description>
         <Part Id="715515010528" UnitPrice="39.95" Quantity="4"/>
      </LineItem>
      <LineItem ItemNumber="9">
         <Description>Black Orpheus</Description>
         <Part Id="37429138328" UnitPrice="29.95" Quantity="2"/>
      </LineItem>
      <LineItem ItemNumber="10">
         <Description>Alexander Nevsky</Description>
         <Part Id="37429149225" UnitPrice="0.0" Quantity="2"/>
      </LineItem>
      <LineItem ItemNumber="11">
         <Description>The Night Porter</Description>
         <Part Id="37429145227" UnitPrice="29.95" Quantity="3"/>
      </LineItem>
      <LineItem ItemNumber="12">
         <Description>The Vanishing</Description>
         <Part Id="37429161623" UnitPrice="29.95" Quantity="4"/>
      </LineItem>
      <LineItem ItemNumber="13">
         <Description>Withnail & I</Description>
         <Part Id="715515012225" UnitPrice="29.95" Quantity="1"/>
      </LineItem>
      <LineItem ItemNumber="14">
         <Description>Grand Illusion</Description>
         <Part Id="37429121924" UnitPrice="39.95" Quantity="2"/>
      </LineItem>
      <LineItem ItemNumber="15">
         <Description>The Discreet Charm of Bourgeoisie</Description>
         <Part Id="37429154625" UnitPrice="39.95" Quantity="4"/>
      </LineItem>
      <LineItem ItemNumber="16">
         <Description>Le Trou</Description>
         <Part Id="37429156223" UnitPrice="29.95" Quantity="1"/>
      </LineItem>
   </LineItems>
</PurchaseOrder>


text:
package io.github.jonestimd.finance.dao.hibernate;

import java.util.List;

import io.github.jonestimd.finance.dao.SecurityLotDao;
import io.github.jonestimd.finance.domain.transaction.SecurityLot;
import io.github.jonestimd.finance.domain.transaction.TransactionDetail;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;

public class SecurityLotDaoImpl extends HibernateDao<SecurityLot, Long> implements SecurityLotDao {
    public SecurityLotDaoImpl(SessionFactory sessionFactory) {
        super(sessionFactory, SecurityLot.class);
    }

    @SuppressWarnings("unchecked")
    public List<SecurityLot> findLotsForPurchases(List<? extends TransactionDetail> purchases) {
        Criteria criteria = getSession().createCriteria(SecurityLot.class);
        criteria.add(getProperty(SecurityLot.PURCHASE).in(purchases));
        return criteria.list();
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<SecurityLot> findBySale(TransactionDetail sale) {
        return getSession().getNamedQuery(SecurityLot.FIND_BY_SALE_ID)
                .setParameter("saleId", sale.getId())
                .list();
    }

    @Override
    public void deleteSaleLots(TransactionDetail sale) {
        getSession().getNamedQuery(SecurityLot.DELETE_BY_SALE_ID)
                .setParameter("saleId", sale.getId())
                .executeUpdate();
    }
}


text:
---
uid: SolidEdgePart.ToggleToConstruction.Application
summary:
remarks:
---


text:
                                // we only see pre-generated Apply overloads.

void Init(unittest::apply::Struct& obj)
{
    obj = InitRandom<unittest::apply::Struct>();
}

void Init(unittest::apply::Derived& obj)
{
    obj = InitRandom<unittest::apply::Derived>();
}

template <typename Reader, typename Writer, typename X>
void Marshal(uint16_t version = bond::v1)
{
    X obj, obj2;

    Init(obj);

    bond::OutputBuffer output;
    Factory<Writer>::Call(output, version, boost::bind(
        bond::Marshal<bond::BuiltInProtocols, X, Writer>, obj, boost::placeholders::_1));

    bond::InputBuffer input = output.GetBuffer();

    Unmarshal(input, obj2);

    UT_Compare(obj, obj2);
}

template <typename Reader, typename Writer, typename X>
void Serialize(uint16_t version = bond::v1)
{
    X obj, obj2;

    Init(obj);

    bond::OutputBuffer output;
    Factory<Writer>::Call(output, version, boost::bind(
        bond::Serialize<bond::BuiltInProtocols, X, Writer>, obj, boost::placeholders::_1));

    bond::InputBuffer input = output.GetBuffer();
    Reader reader(Factory<Reader>::Create(input, version));

    Deserialize(reader, obj2);

    UT_Compare(obj, obj2);
}

template <typename Transform, typename T>
void CallApply(const Transform& transform, const T& value)
{
    Apply(transform, value);
}

template <typename Reader, typename Writer, typename X>
void Apply(uint16_t version = bond::v1)
{
    X obj, obj2;

    Init(obj);

    bond::OutputBuffer output;
    Factory<Writer>::Call(output, version, boost::bind(
        CallApply<bond::Serializer<Writer>, X>, boost::bind(bond::SerializeTo<bond::BuiltInProtocols, Writer>, boost::placeholders::_1), obj));

    bond::InputBuffer input = output.GetBuffer();
    Reader reader(Factory<Reader>::Create(input, version));
    bond::bonded<X> bonded(reader);

    Apply(bond::To<X>(obj2), bonded);

    UT_Compare(obj, obj2);
}

// Just check that Apply overload can be called without attempting roundtrips
template <typename Reader, typename Writer, typename X>
void SimpleApply(uint16_t version = bond::v1)
{
    X obj;

    Init(obj);

    typename Writer::Buffer output;
    Factory<Writer>::Call(output, version, boost::bind(
        CallApply<bond::Serializer<Writer>, X>, boost::bind(bond::SerializeTo<bond::BuiltInProtocols, Writer>, boost::placeholders::_1), obj));
}

template <typename Reader, typename Writer, typename X>
typename boost::enable_if<bond::uses_static_parser<Reader> >::type
Bonded(uint16_t = bond::v1)
{
    // apply_test_reflection.h is necessary for pass-through of untagged
    // protocols such as Simple even when using *_apply because struct skipping
    // depends on compile-time schema defined in _reflection.h.
}

template <typename Reader, typename Writer, typename X>
typename boost::disable_if<bond::uses_static_parser<Reader> >::type
Bonded(uint16_t version = bond::v1)
{
    X obj, obj2;

    Init(obj);

    bond::OutputBuffer output;
    Factory<Writer>::Call(output, version, boost::bind(
        bond::Serialize<bond::BuiltInProtocols, X, Writer>, obj, boost::placeholders::_1));

    bond::InputBuffer input = output.GetBuffer();
    Reader reader(Factory<Reader>::Create(input, version));
    bond::bonded<X> bonded(reader);

    bond::OutputBuffer output2;
    Factory<Writer>::Call(output2, version, boost::bind(
        &bond::bonded<X>::template Serialize<bond::BuiltInProtocols, Writer>, bonded, boost::placeholders::_1));

    bond::InputBuffer input2 = output2.GetBuffer();
    Reader reader2(Factory<Reader>::Create(input2, version));
    bond::bonded<X> bonded2(reader2);

    bonded2.Deserialize(obj2);

    UT_Compare(obj, obj2);
}

template <typename Reader, typename Writer>
struct Tests
{
    template <typename X>
    void operator()(const X&)
    {
        Marshal<Reader, Writer, X>();
        Marshal<Reader, Writer, X>(Reader::version);

        Serialize<Reader, Writer, X>();
        Serialize<Reader, Writer, X>(Reader::version);

        Apply<Reader, Writer, X>();
        Apply<Reader, Writer, X>(Reader::version);

        Bonded<Reader, Writer, X>();
        Bonded<Reader, Writer, X>(Reader::version);

        bond::RuntimeSchema schema = bond::GetRuntimeSchema<X>();
    }
};

// Partial specialization for special CompactBinary internal output counter
template <typename Reader>
struct Tests<Reader, bond::CompactBinaryWriter<bond::OutputBuffer>::Pass0>
{
    template <typename X>
    void operator()(const X&)
    {
        SimpleApply<Reader, bond::CompactBinaryWriter<bond::OutputBuffer>::Pass0, X>();
        SimpleApply<Reader, bond::CompactBinaryWriter<bond::OutputBuffer>::Pass0, X>(Reader::version);
    }
};

template <typename Reader, typename Writer>
TEST_CASE_BEGIN(AllTests)
{
    typedef boost::mpl::list<
        unittest::apply::Struct,
        unittest::apply::Derived
    > Types;

    boost::mpl::for_each<Types>(Tests<Reader, Writer>());
}
TEST_CASE_END

template <uint16_t N, typename Reader, typename Writer>
void ApplyTests(const char* name)
{
    UnitTestSuite suite(name);

    AddTestCase<TEST_ID(N), AllTests, Reader, Writer>(suite, "Use generated *_apply.cpp");
}

void ApplyTest::Initialize()
{
    TEST_SIMPLE_PROTOCOL(
        ApplyTests<
            0x1601,
            bond::SimpleBinaryReader<bond::InputBuffer>,
            bond::SimpleBinaryWriter<bond::OutputBuffer> >("Apply tests for SimpleBinary");
    );

    TEST_COMPACT_BINARY_PROTOCOL(
        ApplyTests<
            0x1602,
            bond::CompactBinaryReader<bond::InputBuffer>,
            bond::CompactBinaryWriter<bond::OutputBuffer> >("Apply tests for CompactBinary");
    );

    // Test for apply overloads for CompactBinary v2 Pass0 output size counter
    TEST_COMPACT_BINARY_PROTOCOL(
        ApplyTests<
            0x1603,
            bond::CompactBinaryReader<bond::InputBuffer>,
            bond::CompactBinaryWriter<bond::OutputBuffer>::Pass0 >("Apply tests for CompactBinary v2 Pass0");
    );

    TEST_FAST_BINARY_PROTOCOL(
        ApplyTests<
            0x1604,
            bond::FastBinaryReader<bond::InputBuffer>,
            bond::FastBinaryWriter<bond::OutputBuffer> >("Apply tests for FastBinary");
    );
}

bool init_unit_test()
{
    ApplyTest::Initialize();
    return true;
}


text:
layout: feature
title: 'Tense'
shortdef: 'tense'
---

The `Tense` feature applies to verbs ([VERB]() and [AUX]()),
specifying the time when the action took or takes place, in
relation to the current moment or to another action in the
utterance.

`Tense` does not apply to non-finite verbs (infinitives and
participles), the negation verb *ei*, or verbs not in the
indicative mood (see
<http://scripta.kotus.fi/visk/sisallys.php?p=111>; in Finnish).

### `Pres`: present tense

The present tense denotes actions that are happening right now or that
usually happen.

#### Examples

* [fi] _järjestelmä toimii_ "the system works"

### `Past`: past tense / preterite

The past tense denotes actions that happened before the current
moment.

#### Examples

* [fi] _joukkue voitti_ "the team won"

### References

* <http://scripta.kotus.fi/visk/sisallys.php?p=1523> (in Finnish)
* <http://scripta.kotus.fi/visk/sisallys.php?p=1530> (in Finnish)


text:
@interface PodsDummy_Pods_Laurine : NSObject
@end
@implementation PodsDummy_Pods_Laurine
@end


text:
using System.Drawing;
using System.Windows.Forms;

namespace MetX.Windows.Library
{
    public abstract class GeneralQuestionDialog<TEntryArea, TReturn>
        where TEntryArea : Control, new()
    {
        public Button CancelButton = new();
        public Form ConstructedForm = new();
        public TReturn DefaultValue;
        public TEntryArea EntryArea;

        public Button OkButton = new();

        public Label PromptLabel = new();

        public DialogResult Result;

        public TReturn ValueToReturnOnCancel;

        public abstract TReturn SelectedValue { get; }

        public TReturn Ask(string promptText = "Choose", string title = "USER PROMPT", TReturn defaultValue = default, int height = 110, int width = 400)
        {
            Initialize(promptText, title, defaultValue, height, width);
            ShowDialog();
            return SelectedValue;
        }

        public void Initialize(string promptText = "Choose", string title = "USER PROMPT", TReturn defaultValue = default, int height = 110, int width = 400)
        {
            DefaultValue = defaultValue;
            ConstructedForm = new Form();
            CancelButton = new Button();
            EntryArea = new TEntryArea();
            OkButton = new Button();
            PromptLabel = new Label();

            ConstructedForm.Text = title;
            PromptLabel.Text = promptText;

            OkButton.Text = "OK";
            CancelButton.Text = "Cancel";
            OkButton.DialogResult = DialogResult.OK;
            CancelButton.DialogResult = DialogResult.Cancel;

            PromptLabel.SetBounds(9, 20, 372, 13);
            EntryArea.SetBounds(12, 36, width - 30, 20);
            OkButton.SetBounds(228, 72, 75, 26);
            CancelButton.SetBounds(309, 72, 75, 26);

            PromptLabel.AutoSize = true;
            EntryArea.Anchor = EntryArea.Anchor | AnchorStyles.Right;
            OkButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            CancelButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;

            ConstructedForm.ClientSize = new Size(width, height);
            ConstructedForm.Controls.AddRange(new Control[] { PromptLabel, EntryArea, OkButton, CancelButton });
            ConstructedForm.FormBorderStyle = FormBorderStyle.FixedDialog;
            ConstructedForm.StartPosition = FormStartPosition.CenterScreen;
            ConstructedForm.MinimizeBox = false;
            ConstructedForm.MaximizeBox = false;
            ConstructedForm.AcceptButton = OkButton;
            ConstructedForm.CancelButton = CancelButton;

            SetupEntryArea();
        }

        public abstract void SetupEntryArea();

        public DialogResult ShowDialog()
        {
            Result = ConstructedForm.ShowDialog();
            return Result;
        }
    }
}


text:
<?php

/**
 * Portuguese translation of the messages (utf8 encoded!)
 *
 * @author Frederico Costa <fredericojcosta@gmail.com>
 * @author Alenônimo <alenonimo@gmail.com>
 * @author Falci <fernandofalci2@yahoo.com.br>
 */

// line 45 in phpfreechatconfig.class.php
$GLOBALS["i18n"]["My Chat"] = "Meu Chat";

// line 201 in phpfreechatconfig.class.php
$GLOBALS["i18n"]["%s not found, %s library can't be found."] = "%s não encontrada, a biblioteca %s não pode ser encontrada.";

// line 355 in phpfreechat.class.php
$GLOBALS["i18n"]["Please enter your nickname"] = "Por favor, informe seu apelido";

// line 565 in phpfreechat.class.php
$GLOBALS["i18n"]["Text cannot be empty"] = "O Texto não pode estar em branco";

// line 392 in phpfreechat.class.php
$GLOBALS["i18n"]["%s changes his nickname to %s"] = "%s mudou de apelido para %s";

// line 398 in phpfreechat.class.php
$GLOBALS["i18n"]["%s is connected"] = "%s acabou de entrar na sala";

// line 452 in phpfreechat.class.php
$GLOBALS["i18n"]["%s quit"] = "%s desconectou-se";

// line 468 in phpfreechat.class.php
$GLOBALS["i18n"]["%s disconnected (timeout)"] = "%s foi desconectado (tempo esgotado)";

// line 262 in phpfreechat.class.php
$GLOBALS["i18n"]["Unknown command [%s]"] = "comando desconhecido [%s]";

// line 149 in phpfreechatconfig.class.php
$GLOBALS["i18n"]["%s doesn't exist: %s"] = "%s não existe: %s";

// line 180 in phpfreechatconfig.class.php
$GLOBALS["i18n"]["You need %s"] = "Você precisa de %s";

// line 241 in phpfreechatconfig.class.php
$GLOBALS["i18n"]["%s doesn't exist, %s library can't be found"] = "%s não existe, a biblioteca %s não pode ser encontrada";

// line 280 in phpfreechatconfig.class.php
$GLOBALS["i18n"]["%s doesn't exist"] = "%s não existe";

// line 433 in phpfreechatconfig.class.php
$GLOBALS["i18n"]["%s directory must be specified"] = "%s o diretório precisa ser especificado";

// line 439 in phpfreechatconfig.class.php
$GLOBALS["i18n"]["%s must be a directory"] = "%s precisa ser um diretório";

// line 446 in phpfreechatconfig.class.php
$GLOBALS["i18n"]["%s can't be created"] = "%s não pode ser criado";

// line 451 in phpfreechatconfig.class.php
$GLOBALS["i18n"]["%s is not writeable"] = "%s não tem permissão de escrita";

// line 496 in phpfreechatconfig.class.php
$GLOBALS["i18n"]["%s is not readable"] = "%s não tem permissão de leitura";

// line 469 in phpfreechatconfig.class.php
$GLOBALS["i18n"]["%s is not a file"] = "%s não é um arquivo";

// line 491 in phpfreechatconfig.class.php
$GLOBALS["i18n"]["%s is not a directory"] = "%s não é um diretório";

// line 23 in chat.html.tpl.php
$GLOBALS["i18n"]["PHP FREE CHAT [powered by phpFreeChat-%s]"] = "PHP FREE CHAT [powered by phpFreeChat-%s]";

// line 296 in javascript1.js.tpl.php
$GLOBALS["i18n"]["Hide nickname marker"] = "Esconder os marcadores de apelidos";

// line 304 in javascript1.js.tpl.php
$GLOBALS["i18n"]["Show nickname marker"] = "Mostrar os marcadores de apelidos";

// line 389 in javascript1.js.tpl.php
$GLOBALS["i18n"]["Disconnect"] = "Desconectar";

// line 395 in javascript1.js.tpl.php
$GLOBALS["i18n"]["Connect"] = "Conectar";

// line 427 in javascript1.js.tpl.php
$GLOBALS["i18n"]["Magnify"] = "Ampliar";

// line 434 in javascript1.js.tpl.php
$GLOBALS["i18n"]["Cut down"] = "Cortar";

// line 345 in javascript1.js.tpl.php
$GLOBALS["i18n"]["Hide dates and hours"] = "Esconder as datas/horas";

// line 353 in javascript1.js.tpl.php
$GLOBALS["i18n"]["Show dates and hours"] = "Mostrar as datas/horas";

// line 21 in chat.html.tpl.php
$GLOBALS["i18n"]["Enter your message here"] = "Digite sua mensagem";

// line 24 in chat.html.tpl.php
$GLOBALS["i18n"]["Enter your nickname here"] = "Digite seu apelido";

// line 92 in phpfreechatconfig.class.php
$GLOBALS["i18n"]["Error: undefined or obsolete parameter '%s', please correct or remove this parameter"] = "Erro: indefinido ou parâmetro obsoleto '%s'. Por favor corrija ou remova esta parâmetro";

// line 48 in phpfreechattemplate.class.php
$GLOBALS["i18n"]["%s template could not be found"] = "Template %s não pode ser encontrado";

// line 324 in phpfreechatconfig.class.php
$GLOBALS["i18n"]["'serverid' parameter is mandatory by default use 'md5(__FILE__)' value"] = "O parâmetro 'serverid' é exigido. Por padrão, use o valor 'md5(__FILE__)'";

// line 512 in phpfreechatconfig.class.php
$GLOBALS["i18n"]["Error: '%s' could not be found, please check your themepath '%s' and your theme '%s' are correct"] = "Erro: '%s' não foi encontrado, por favor verifique se o caminho '%s' e o tema '%s' estão corretos";

// line 33 in chat.html.tpl.php
$GLOBALS["i18n"]["Bold"] = "Negrito";

// line 34 in chat.html.tpl.php
$GLOBALS["i18n"]["Italics"] = "Itálico";

// line 35 in chat.html.tpl.php
$GLOBALS["i18n"]["Underline"] = "Sublinhado";

// line 36 in chat.html.tpl.php
$GLOBALS["i18n"]["Delete"] = "Remover";

// line 37 in chat.html.tpl.php
$GLOBALS["i18n"]["Pre"] = "Monoespaçado";

// line 38 in chat.html.tpl.php
$GLOBALS["i18n"]["Mail"] = "Email";

// line 39 in chat.html.tpl.php
$GLOBALS["i18n"]["Color"] = "Cor";

// line 86 in pfcclient.js.tpl.php
$GLOBALS["i18n"]["Hide smiley box"] = "Esconder Caixa de Smiley";

// line 87 in pfcclient.js.tpl.php
$GLOBALS["i18n"]["Show smiley box"] = "Mostrar Caixa de Smiley";

// line 88 in pfcclient.js.tpl.php
$GLOBALS["i18n"]["Hide online users box"] = "Esconder usuários online";

// line 89 in pfcclient.js.tpl.php
$GLOBALS["i18n"]["Show online users box"] = "Mostrar usuários online";

// line 75 in pfccommand.class.php
$GLOBALS["i18n"]["%s must be implemented"] = "%s precisa ser implementado";

// line 343 in phpfreechatconfig.class.php
$GLOBALS["i18n"]["'%s' parameter is mandatory by default use '%s' value"] = "O parâmetro '%s' é exigido. Por padrão, use o valor '%s'";

// line 378 in phpfreechatconfig.class.php
$GLOBALS["i18n"]["'%s' parameter must be a positive number"] = "O parâmetro '%s' deve ser um número positivo";

// line 386 in phpfreechatconfig.class.php
$GLOBALS["i18n"]["'%s' parameter is not valid. Available values are : '%s'"] = "O parâmetro '%s' não é válido. Valores disponíveis: '%s'";

// line 186 in pfcglobalconfig.class.php
$GLOBALS["i18n"]["My room"] = "Minha Sala";

// line 19 in unban.class.php
$GLOBALS["i18n"]["Missing parameter"] = "Faltando parâmetro";

// line 38 in ban.class.php
$GLOBALS["i18n"]["banished from %s by %s"] = "Banido de %s por %s";

// line 23 in banlist.class.php
$GLOBALS["i18n"]["The banished user's id list is:"] = "A lista de IDs dos usuários banidos é:";

// line 32 in banlist.class.php
$GLOBALS["i18n"]["Empty"] = "Vazio";

// line 34 in banlist.class.php
$GLOBALS["i18n"]["'/unban {id}' will unban the user identified by {id}"] = "'/unban {id}' será desbanido o usuário identificado pelo {id}";

// line 35 in banlist.class.php
$GLOBALS["i18n"]["'/unban all'  will unban all the users on this channel"] = "'/unban all' desbanir todos usuários da sala";

// line 24 in update.class.php
$GLOBALS["i18n"]["%s quit (timeout)"] = "%s saiu (tempo esgotado)";

// line 46 in join.class.php
$GLOBALS["i18n"]["%s joins %s"] = "%s entrou em %s";

// line 31 in kick.class.php
$GLOBALS["i18n"]["kicked from %s by %s"] = "chutado de %s por %s";

// line 38 in send.class.php
$GLOBALS["i18n"]["Can't send the message, %s is offline"] = "Não pode enviar a menssagem, %s não está presente";

// line 27 in unban.class.php
$GLOBALS["i18n"]["Nobody has been unbanished"] = "Ninguém foi desbanido";

// line 42 in unban.class.php
$GLOBALS["i18n"]["%s has been unbanished"] = "%s foi desbanido";

// line 49 in unban.class.php
$GLOBALS["i18n"]["%s users have been unbanished"] = "%s usuários foram desbanidos";

// line 47 in auth.class.php
$GLOBALS["i18n"]["You are not allowed to run '%s' command"] = "Você não está autorizado a executar o comando '%s'";

// line 66 in auth.class.php
$GLOBALS["i18n"]["Can't join %s because you are banished"] = "Não pode entrar em '%s' porque você está banido";

// line 76 in auth.class.php
$GLOBALS["i18n"]["Can't join %s because the channels list is restricted"] = "Não pode entrar em '%s' porque a lista do canal é restrito";

// line 89 in auth.class.php
$GLOBALS["i18n"]["You are not allowed to change your nickname"] = "Você não está autorizado a mudar o seu apelido";

// line 56 in noflood.class.php
$GLOBALS["i18n"]["Please don't post so many message, flood is not tolerated"] = "Por favor, não poste tantas mensagens. Flood não será tolerado";

// line 109 in pfcclient.js.tpl.php
$GLOBALS["i18n"]["Private message"] = "Mensagem Privada (MP)";

// line 110 in pfcclient.js.tpl.php
$GLOBALS["i18n"]["Close this tab"] = "Fechar Aba";

// line 199 in pfcgui.js.tpl.php
$GLOBALS["i18n"]["Do you really want to leave this room ?"] = "Você realmente quer deixar esta sala?";

// line 169 in pfcglobalconfig.class.php
$GLOBALS["i18n"]["Error: '%s' is a private parameter, you are not allowed to change it"] = "Erro: '%s' é uma opção privada, você não está autorizado a mudá-la";

// line 253 in pfcglobalconfig.class.php
$GLOBALS["i18n"]["'%s' parameter must be an array"] = "O parâmetro '%s' precisa ser um array";

// line 265 in pfcglobalconfig.class.php
$GLOBALS["i18n"]["'%s' parameter must be a boolean"] = "O parâmetro '%s' precisa um booleano";

// line 271 in pfcglobalconfig.class.php
$GLOBALS["i18n"]["'%s' parameter must be a charatere string"] = "O parâmetro '%s' precisa ser uma string";

// line 395 in pfcglobalconfig.class.php
$GLOBALS["i18n"]["'%s' must be writable"] = "'%s' precisa ter permissão de escrita";

// line 425 in pfcglobalconfig.class.php
$GLOBALS["i18n"]["'%s' directory doesn't exist"] = "O diretório '%s' não existe";

// line 544 in pfcglobalconfig.class.php
$GLOBALS["i18n"]["Please correct these errors"] = "Por favor corrija estes erros";

// line 21 in pfcinfo.class.php
$GLOBALS["i18n"]["Error: the cached config file doesn't exists"] = "Erro: o arquivo de configuração não existe no cache";

// line 190 in phpfreechat.class.php
$GLOBALS["i18n"]["Error: the chat cannot be loaded! two possibilities: your browser doesn't support javascript or you didn't setup correctly the server directories rights - don't hesitate to ask some help on the forum"] = "Erro: o chat não foi carregado! Duas possibilidades: seu navegador não suporta JavaScript ou você não configurou corretamente as permissões dos diretórios do servidor não hesite em pedir ajuda no nosso fórum";

// line 31 in help.class.php
$GLOBALS["i18n"]["Here is the command list:"] = "Aqui está a lista de comandos:";

// line 63 in identify.class.php
$GLOBALS["i18n"]["Succesfully identified"] = "Identificado com sucesso";

// line 68 in identify.class.php
$GLOBALS["i18n"]["Identification failure"] = "Falha da identificação";

// line 25 in send.class.php
$GLOBALS["i18n"]["Your must be connected to send a message"] = "Você deve estar conectado para enviar mensagem";

// line 87 in chat.js.tpl.php
$GLOBALS["i18n"]["Click here to send your message"] = "Clique aqui para enviar sua mensagem";

// line 80 in chat.js.tpl.php
$GLOBALS["i18n"]["Enter the text to format"] = "Entre com um texto para formatar";

// line 81 in chat.js.tpl.php
$GLOBALS["i18n"]["Configuration has been rehashed"] = "Configuração foi rehasheada";

// line 82 in chat.js.tpl.php
$GLOBALS["i18n"]["A problem occurs during rehash"] = "Um problema ocorreu durante o rehash";

// line 83 in chat.js.tpl.php
$GLOBALS["i18n"]["Chosen nickname is already used"] = "O apelido escolhido já está em uso";

// line 84 in chat.js.tpl.php
$GLOBALS["i18n"]["phpfreechat current version is %s"] = "A versão atual do phpFreeChat é %s";

// line 85 in chat.js.tpl.php
$GLOBALS["i18n"]["Maximum number of joined channels has been reached"] = "Atingido o número máximo de canais que se pode entrar";

// line 86 in chat.js.tpl.php
$GLOBALS["i18n"]["Maximum number of private chat has been reached"] = "Atingido o número máximo de conversas particulares que se pode ter";

// line 88 in chat.js.tpl.php
$GLOBALS["i18n"]["Send"] = "Enviar";

// line 359 in pfcglobalconfig.class.php
$GLOBALS["i18n"]["%s doesn't exist, data_public_path cannot be installed"] = "%s não existe, \"data_public_path\" não pode ser instalada";

// line 489 in phpfreechat.class.php
$GLOBALS["i18n"]["You are not allowed to speak to yourself"] = "Você não está autorizado a falar para si mesmo";

// line 491 in phpfreechat.class.php
$GLOBALS["i18n"]["Chosen nickname is not allowed"] = "Você não pode mudar o seu apelido";

// line 492 in phpfreechat.class.php
$GLOBALS["i18n"]["Enable sound notifications"] = "Habilitar notificações por sons";

// line 493 in phpfreechat.class.php
$GLOBALS["i18n"]["Disable sound notifications"] = "Desabilitar notificações por sons";

// line 23 in kick.class.php
$GLOBALS["i18n"]["no reason"] = "qualquer motivo";

// line 24 in banlist.class.php
$GLOBALS["i18n"]["The banished user list is:"] = "A lista de usuários banidos é:";

// line 39 in banlist.class.php
$GLOBALS["i18n"]["'/unban {nickname}' will unban the user identified by {nickname}"] = "/unban {nickname}' irá \"desbanir\" o usuário {nickname}";

// line 44 in kick.class.php
$GLOBALS["i18n"]["kicked from %s by %s - reason: %s"] = "chutado de %s por %s - Motivo: %s";

// line 20 in quit.class.php
$GLOBALS["i18n"]["%s quit (%s)"] = "%s saiu (%s)";

// line 86 in mysql.class.php
$GLOBALS["i18n"]["Mysql container: connect error"] = "MySQL: Conexão falhou";

// line 101 in mysql.class.php
$GLOBALS["i18n"]["Mysql container: create database error '%s'"] = "MySQL: Falha ao criar database '%s'";

// line 112 in mysql.class.php
$GLOBALS["i18n"]["Mysql container: create table error '%s'"] = "MySQL: Falha ao criar tabela '%s'";
// line 124 in chat.js.tpl.php
$GLOBALS["i18n"]["Chat loading ..."] = "Iniciando Chat...";

// line 124 in chat.js.tpl.php
$GLOBALS["i18n"]["Please wait"] = "Por favor aguarde";

// line 139 in chat.js.tpl.php
$GLOBALS["i18n"]["%s appears to be either disabled or unsupported by your browser."] = "%s parece estar desativado ou não suportado pelo seu navegador.";

// line 139 in chat.js.tpl.php
$GLOBALS["i18n"]["This web application requires %s to work properly."] = "Esta web aplicação requer %s para funcionar corretamente.";

// line 135 in chat.js.tpl.php
$GLOBALS["i18n"]["Please enable %s in your browser settings, or upgrade to a browser with %s support and try again."] = "Ative %s nas configurações do seu navegador, ou atualizar para um navegador com suporte a %s e tente novamente.";

// line 137 in chat.js.tpl.php
$GLOBALS["i18n"]["Please upgrade to a browser with %s support and try again."] = "Atualizar para um navegador com suporte a %s e tente novamente.";

// line 139 in chat.js.tpl.php
$GLOBALS["i18n"]["In Internet Explorer versions earlier than 7.0, Ajax is implemented using ActiveX. Please enable ActiveX in your browser security settings or upgrade to a browser with Ajax support and try again."] = "No Internet Explorer ( versão < 7.0), Ajax é implementado usando ActiveX. Ative o ActiveX no navegador nas configurações de segurança ou atualize para um navegador com Ajax apoio e tente novamente.";

// line 73 in invite.class.php
$GLOBALS["i18n"]["You must join %s to invite users in this channel"] = "Você deve participar %s para convidar os usuários neste canal";

// line 47 in chat.html.tpl.php
$GLOBALS["i18n"]["Ping"] = "Ping";

// line 477 in phpfreechat.class.php
$GLOBALS["i18n"]["Input Required"] = "Campo Obrigatório";

// line 478 in phpfreechat.class.php
$GLOBALS["i18n"]["OK"] = "OK";

// line 479 in phpfreechat.class.php
$GLOBALS["i18n"]["Cancel"] = "Cancelar";

// line 430 in pfcglobalconfig.class.php
$GLOBALS["i18n"]["cannot create %s"] = "não pode criar %s";

// line 436 in pfcglobalconfig.class.php
$GLOBALS["i18n"]["cannot copy %s in %s"] = "não pode copiar %s em %s";

// line 667 in pfcglobalconfig.class.php
$GLOBALS["i18n"]["Error: '%s' could not be found, please check your theme_path '%s' and your theme '%s' are correct"] = "Erro: '%s' não pode ser encontrada, verifique se o theme_path '%s' e o tema '%s' estão corretos";

// line 414 in phpfreechat.class.php
$GLOBALS["i18n"]["Are you sure you want to close this tab ?"] = "Tem certeza que deseja fechar esta aba?";

// line 42 in ban.class.php
$GLOBALS["i18n"]["%s banished from %s by %s"] = "%s banido de %s por %s";

// line 461 in phpfreechat.class.php
$GLOBALS["i18n"]["You are trying to speak to a unknown (or not connected) user"] = "Você está tentando falar com um desconhecido ou usuário não conectado";

// line 89 in invite.class.php
$GLOBALS["i18n"]["%s was invited by %s"] = "%s foi convidado por %s";

?>


text:
require 'rubygems/test_case'
require 'ostruct'
require 'webrick'
require 'webrick/https'
require 'rubygems/remote_fetcher'
require 'rubygems/format'

# = Testing Proxy Settings
#
# These tests check the proper proxy server settings by running two
# web servers.  The web server at http://localhost:#{SERVER_PORT}
# represents the normal gem server and returns a gemspec with a rake
# version of 0.4.11.  The web server at http://localhost:#{PROXY_PORT}
# represents the proxy server and returns a different dataset where
# rake has version 0.4.2.  This allows us to detect which server is
# returning the data.
#
# Note that the proxy server is not a *real* proxy server.  But our
# software doesn't really care, as long as we hit the proxy URL when a
# proxy is configured.

class TestGemRemoteFetcher < Gem::TestCase

  include Gem::DefaultUserInteraction

  SERVER_DATA = <<-EOY
--- !ruby/object:Gem::Cache
gems:
  rake-0.4.11: !ruby/object:Gem::Specification
    rubygems_version: "0.7"
    specification_version: 1
    name: rake
    version: !ruby/object:Gem::Version
      version: 0.4.11
    date: 2004-11-12
    summary: Ruby based make-like utility.
    require_paths:
      - lib
    author: Jim Weirich
    email: jim@weirichhouse.org
    homepage: http://rake.rubyforge.org
    rubyforge_project: rake
    description: Rake is a Make-like program implemented in Ruby. Tasks and dependencies are specified in standard Ruby syntax.
    autorequire:
    default_executable: rake
    bindir: bin
    has_rdoc: true
    required_ruby_version: !ruby/object:Gem::Version::Requirement
      requirements:
        -
          - ">"
          - !ruby/object:Gem::Version
            version: 0.0.0
      version:
    platform: ruby
    files:
      - README
    test_files: []
    library_stubs:
    rdoc_options:
    extra_rdoc_files:
    executables:
      - rake
    extensions: []
    requirements: []
    dependencies: []
  EOY

  PROXY_DATA = SERVER_DATA.gsub(/0.4.11/, '0.4.2')

  # don't let 1.8 and 1.9 autotest collide
  RUBY_VERSION =~ /(\d+)\.(\d+)\.(\d+)/
  # don't let parallel runners collide
  PROXY_PORT = process_based_port + 100 + $1.to_i * 100 + $2.to_i * 10 + $3.to_i
  SERVER_PORT = process_based_port + 200 + $1.to_i * 100 + $2.to_i * 10 + $3.to_i

  DIR = File.expand_path(File.dirname(__FILE__))

  def setup
    super
    self.class.start_servers
    self.class.enable_yaml = true
    self.class.enable_zip = false
    ENV.delete 'http_proxy'
    ENV.delete 'HTTP_PROXY'
    ENV.delete 'http_proxy_user'
    ENV.delete 'HTTP_PROXY_USER'
    ENV.delete 'http_proxy_pass'
    ENV.delete 'HTTP_PROXY_PASS'

    base_server_uri = "http://localhost:#{SERVER_PORT}"
    @proxy_uri = "http://localhost:#{PROXY_PORT}"

    @server_uri = base_server_uri + "/yaml"
    @server_z_uri = base_server_uri + "/yaml.Z"

    # REFACTOR: copied from test_gem_dependency_installer.rb
    @gems_dir = File.join @tempdir, 'gems'
    @cache_dir = File.join @gemhome, "cache"
    FileUtils.mkdir @gems_dir

    # TODO: why does the remote fetcher need it written to disk?
    @a1, @a1_gem = util_gem 'a', '1' do |s| s.executables << 'a_bin' end

    Gem::RemoteFetcher.fetcher = nil

    @fetcher = Gem::RemoteFetcher.fetcher
  end

  def teardown
    super
    Gem.configuration[:http_proxy] = nil
  end

  def test_self_fetcher
    fetcher = Gem::RemoteFetcher.fetcher
    refute_nil fetcher
    assert_kind_of Gem::RemoteFetcher, fetcher
  end

  def test_self_fetcher_with_proxy
    proxy_uri = 'http://proxy.example.com'
    Gem.configuration[:http_proxy] = proxy_uri
    Gem::RemoteFetcher.fetcher = nil

    fetcher = Gem::RemoteFetcher.fetcher

    refute_nil fetcher
    assert_kind_of Gem::RemoteFetcher, fetcher
    assert_equal proxy_uri, fetcher.instance_variable_get(:@proxy_uri).to_s
  end

  def test_self_fetcher_with_proxy_URI
    proxy_uri = URI.parse 'http://proxy.example.com'
    Gem.configuration[:http_proxy] = proxy_uri
    Gem::RemoteFetcher.fetcher = nil

    fetcher = Gem::RemoteFetcher.fetcher
    refute_nil fetcher

    assert_kind_of Gem::RemoteFetcher, fetcher
    assert_equal proxy_uri, fetcher.instance_variable_get(:@proxy_uri)
  end

  def test_fetch_size_bad_uri
    fetcher = Gem::RemoteFetcher.new nil

    e = assert_raises ArgumentError do
      fetcher.fetch_size 'gems.example.com/yaml'
    end

    assert_equal 'uri scheme is invalid: nil', e.message
  end

  def test_fetch_size_socket_error
    fetcher = Gem::RemoteFetcher.new nil
    def fetcher.connection_for(uri)
      raise SocketError, "tarded"
    end

    uri = 'http://gems.example.com/yaml'
    e = assert_raises Gem::RemoteFetcher::FetchError do
      fetcher.fetch_size uri
    end

    assert_equal "SocketError: tarded (#{uri})", e.message
  end

  def test_no_proxy
    use_ui @ui do
      assert_data_from_server @fetcher.fetch_path(@server_uri)
      assert_equal SERVER_DATA.size, @fetcher.fetch_size(@server_uri)
    end
  end

  def util_fuck_with_fetcher data, blow = false
    fetcher = Gem::RemoteFetcher.fetcher
    fetcher.instance_variable_set :@test_data, data

    unless blow then
      def fetcher.fetch_path arg
        @test_arg = arg
        @test_data
      end
    else
      def fetcher.fetch_path arg
        # OMG I'm such an ass
        class << self; remove_method :fetch_path; end
        def self.fetch_path arg
          @test_arg = arg
          @test_data
        end

        raise Gem::RemoteFetcher::FetchError.new("haha!", nil)
      end
    end

    fetcher
  end

  def test_download
    a1_data = nil
    File.open @a1_gem, 'rb' do |fp|
      a1_data = fp.read
    end

    fetcher = util_fuck_with_fetcher a1_data

    a1_cache_gem = @a1.cache_file
    assert_equal a1_cache_gem, fetcher.download(@a1, 'http://gems.example.com')
    assert_equal("http://gems.example.com/gems/a-1.gem",
                 fetcher.instance_variable_get(:@test_arg).to_s)
    assert File.exist?(a1_cache_gem)
  end

  def test_download_cached
    FileUtils.mv @a1_gem, @cache_dir

    inst = Gem::RemoteFetcher.fetcher

    assert_equal @a1.cache_file, inst.download(@a1, 'http://gems.example.com')
  end

  def test_download_local
    FileUtils.mv @a1_gem, @tempdir
    local_path = File.join @tempdir, @a1.file_name
    inst = nil

    Dir.chdir @tempdir do
      inst = Gem::RemoteFetcher.fetcher
    end

    assert_equal @a1.cache_file, inst.download(@a1, local_path)
  end

  def test_download_local_space
    space_path = File.join @tempdir, 'space path'
    FileUtils.mkdir space_path
    FileUtils.mv @a1_gem, space_path
    local_path = File.join space_path, @a1.file_name
    inst = nil

    Dir.chdir @tempdir do
      inst = Gem::RemoteFetcher.fetcher
    end

    assert_equal @a1.cache_file, inst.download(@a1, local_path)
  end

  def test_download_install_dir
    a1_data = File.open @a1_gem, 'rb' do |fp|
      fp.read
    end

    fetcher = util_fuck_with_fetcher a1_data

    install_dir = File.join @tempdir, 'more_gems'

    a1_cache_gem = File.join install_dir, "cache", @a1.file_name
    FileUtils.mkdir_p(File.dirname(a1_cache_gem))
    actual = fetcher.download(@a1, 'http://gems.example.com', install_dir)

    assert_equal a1_cache_gem, actual
    assert_equal("http://gems.example.com/gems/a-1.gem",
                 fetcher.instance_variable_get(:@test_arg).to_s)

    assert File.exist?(a1_cache_gem)
  end

  unless win_platform? # File.chmod doesn't work
    def test_download_local_read_only
      FileUtils.mv @a1_gem, @tempdir
      local_path = File.join @tempdir, @a1.file_name
      inst = nil
      FileUtils.chmod 0555, @a1.cache_dir

      Dir.chdir @tempdir do
        inst = Gem::RemoteFetcher.fetcher
      end

      assert_equal File.join(@tempdir, @a1.file_name),
        inst.download(@a1, local_path)
    ensure
      FileUtils.chmod 0755, @a1.cache_dir
    end

    def test_download_read_only
      FileUtils.chmod 0555, @a1.cache_dir
      FileUtils.chmod 0555, @gemhome

      fetcher = util_fuck_with_fetcher File.read(@a1_gem)
      fetcher.download(@a1, 'http://gems.example.com')
      a1_cache_gem = File.join Gem.user_dir, "cache", @a1.file_name
      assert File.exist? a1_cache_gem
    ensure
      FileUtils.chmod 0755, @gemhome
      FileUtils.chmod 0755, @a1.cache_dir
    end
  end

  def test_download_platform_legacy
    original_platform = 'old-platform'

    e1, e1_gem = util_gem 'e', '1' do |s|
      s.platform = Gem::Platform::CURRENT
      s.instance_variable_set :@original_platform, original_platform
    end

    e1_data = nil
    File.open e1_gem, 'rb' do |fp|
      e1_data = fp.read
    end

    fetcher = util_fuck_with_fetcher e1_data, :blow_chunks

    e1_cache_gem = e1.cache_file

    assert_equal e1_cache_gem, fetcher.download(e1, 'http://gems.example.com')

    assert_equal("http://gems.example.com/gems/#{e1.original_name}.gem",
                 fetcher.instance_variable_get(:@test_arg).to_s)
    assert File.exist?(e1_cache_gem)
  end

  def test_download_same_file
    FileUtils.mv @a1_gem, @tempdir
    local_path = File.join @tempdir, @a1.file_name
    inst = nil

    Dir.chdir @tempdir do
      inst = Gem::RemoteFetcher.fetcher
    end

    cache_path = @a1.cache_file
    FileUtils.mv local_path, cache_path

    gem = Gem::Format.from_file_by_path cache_path

    assert_equal cache_path, inst.download(gem.spec, cache_path)
  end

  def test_download_unsupported
    inst = Gem::RemoteFetcher.fetcher

    e = assert_raises Gem::InstallError do
      inst.download @a1, 'ftp://gems.rubyforge.org'
    end

    assert_equal 'unsupported URI scheme ftp', e.message
  end

  def test_download_to_cache
    @a2, @a2_gem = util_gem 'a', '2'

    util_setup_spec_fetcher @a1, @a2
    @fetcher.instance_variable_set :@a1, @a1
    @fetcher.instance_variable_set :@a2, @a2
    def @fetcher.fetch_path uri, mtime = nil, head = false
      case uri.request_uri
      when /#{@a1.spec_name}/ then
        Gem.deflate Marshal.dump @a1
      when /#{@a2.spec_name}/ then
        Gem.deflate Marshal.dump @a2
      else
        uri.to_s
      end
    end

    gem = Gem::RemoteFetcher.fetcher.download_to_cache dep 'a'

    assert_equal @a2.file_name, File.basename(gem)
  end

  def test_explicit_proxy
    use_ui @ui do
      fetcher = Gem::RemoteFetcher.new @proxy_uri
      assert_equal PROXY_DATA.size, fetcher.fetch_size(@server_uri)
      assert_data_from_proxy fetcher.fetch_path(@server_uri)
    end
  end

  def test_explicit_proxy_with_user_auth
    use_ui @ui do
      uri = URI.parse @proxy_uri
      uri.user, uri.password = 'foo', 'bar'
      fetcher = Gem::RemoteFetcher.new uri.to_s
      proxy = fetcher.instance_variable_get("@proxy_uri")
      assert_equal 'foo', proxy.user
      assert_equal 'bar', proxy.password
      assert_data_from_proxy fetcher.fetch_path(@server_uri)
    end

    use_ui @ui do
      uri = URI.parse @proxy_uri
      uri.user, uri.password = 'domain%5Cuser', 'bar'
      fetcher = Gem::RemoteFetcher.new uri.to_s
      proxy = fetcher.instance_variable_get("@proxy_uri")
      assert_equal 'domain\user', fetcher.unescape(proxy.user)
      assert_equal 'bar', proxy.password
      assert_data_from_proxy fetcher.fetch_path(@server_uri)
    end

    use_ui @ui do
      uri = URI.parse @proxy_uri
      uri.user, uri.password = 'user', 'my%20pass'
      fetcher = Gem::RemoteFetcher.new uri.to_s
      proxy = fetcher.instance_variable_get("@proxy_uri")
      assert_equal 'user', proxy.user
      assert_equal 'my pass', fetcher.unescape(proxy.password)
      assert_data_from_proxy fetcher.fetch_path(@server_uri)
    end
  end

  def test_explicit_proxy_with_user_auth_in_env
    use_ui @ui do
      ENV['http_proxy'] = @proxy_uri
      ENV['http_proxy_user'] = 'foo'
      ENV['http_proxy_pass'] = 'bar'
      fetcher = Gem::RemoteFetcher.new nil
      proxy = fetcher.instance_variable_get("@proxy_uri")
      assert_equal 'foo', proxy.user
      assert_equal 'bar', proxy.password
      assert_data_from_proxy fetcher.fetch_path(@server_uri)
    end

    use_ui @ui do
      ENV['http_proxy'] = @proxy_uri
      ENV['http_proxy_user'] = 'foo\user'
      ENV['http_proxy_pass'] = 'my bar'
      fetcher = Gem::RemoteFetcher.new nil
      proxy = fetcher.instance_variable_get("@proxy_uri")
      assert_equal 'foo\user', fetcher.unescape(proxy.user)
      assert_equal 'my bar', fetcher.unescape(proxy.password)
      assert_data_from_proxy fetcher.fetch_path(@server_uri)
    end
  end

  def test_fetch_path_gzip
    fetcher = Gem::RemoteFetcher.new nil

    def fetcher.fetch_http(uri, mtime, head = nil)
      Gem.gzip 'foo'
    end

    assert_equal 'foo', fetcher.fetch_path(@uri + 'foo.gz')
  end

  def test_fetch_path_gzip_unmodified
    fetcher = Gem::RemoteFetcher.new nil

    def fetcher.fetch_http(uri, mtime, head = nil)
      nil
    end

    assert_equal nil, fetcher.fetch_path(@uri + 'foo.gz', Time.at(0))
  end

  def test_fetch_path_io_error
    fetcher = Gem::RemoteFetcher.new nil

    def fetcher.fetch_http(*)
      raise EOFError
    end

    url = 'http://example.com/uri'

    e = assert_raises Gem::RemoteFetcher::FetchError do
      fetcher.fetch_path url
    end

    assert_equal "EOFError: EOFError (#{url})", e.message
    assert_equal url, e.uri
  end

  def test_fetch_path_socket_error
    fetcher = Gem::RemoteFetcher.new nil

    def fetcher.fetch_http(uri, mtime, head = nil)
      raise SocketError
    end

    url = 'http://example.com/uri'

    e = assert_raises Gem::RemoteFetcher::FetchError do
      fetcher.fetch_path url
    end

    assert_equal "SocketError: SocketError (#{url})", e.message
    assert_equal url, e.uri
  end

  def test_fetch_path_system_call_error
    fetcher = Gem::RemoteFetcher.new nil

    def fetcher.fetch_http(uri, mtime = nil, head = nil)
      raise Errno::ECONNREFUSED, 'connect(2)'
    end

    url = 'http://example.com/uri'

    e = assert_raises Gem::RemoteFetcher::FetchError do
      fetcher.fetch_path url
    end

    assert_match %r|ECONNREFUSED:.*connect\(2\) \(#{Regexp.escape url}\)\z|,
                 e.message
    assert_equal url, e.uri
  end

  def test_fetch_path_unmodified
    fetcher = Gem::RemoteFetcher.new nil

    def fetcher.fetch_http(uri, mtime, head = nil)
      nil
    end

    assert_equal nil, fetcher.fetch_path(URI.parse(@gem_repo), Time.at(0))
  end

  def test_get_proxy_from_env_auto_normalizes
    fetcher = Gem::RemoteFetcher.new(nil)
    ENV['HTTP_PROXY'] = 'fakeurl:12345'

    assert_equal('http://fakeurl:12345', fetcher.get_proxy_from_env.to_s)
  end

  def test_get_proxy_from_env_empty
    orig_env_HTTP_PROXY = ENV['HTTP_PROXY']
    orig_env_http_proxy = ENV['http_proxy']

    ENV['HTTP_PROXY'] = ''
    ENV.delete 'http_proxy'

    fetcher = Gem::RemoteFetcher.new nil

    assert_equal nil, fetcher.send(:get_proxy_from_env)

  ensure
    orig_env_HTTP_PROXY.nil? ? ENV.delete('HTTP_PROXY') :
                               ENV['HTTP_PROXY'] = orig_env_HTTP_PROXY
    orig_env_http_proxy.nil? ? ENV.delete('http_proxy') :
                               ENV['http_proxy'] = orig_env_http_proxy
  end

  def test_implicit_no_proxy
    use_ui @ui do
      ENV['http_proxy'] = 'http://fakeurl:12345'
      fetcher = Gem::RemoteFetcher.new :no_proxy
      assert_data_from_server fetcher.fetch_path(@server_uri)
    end
  end

  def test_implicit_proxy
    use_ui @ui do
      ENV['http_proxy'] = @proxy_uri
      fetcher = Gem::RemoteFetcher.new nil
      assert_data_from_proxy fetcher.fetch_path(@server_uri)
    end
  end

  def test_implicit_upper_case_proxy
    use_ui @ui do
      ENV['HTTP_PROXY'] = @proxy_uri
      fetcher = Gem::RemoteFetcher.new nil
      assert_data_from_proxy fetcher.fetch_path(@server_uri)
    end
  end

  def test_implicit_proxy_no_env
    use_ui @ui do
      fetcher = Gem::RemoteFetcher.new nil
      assert_data_from_server fetcher.fetch_path(@server_uri)
    end
  end

  def test_fetch_http
    fetcher = Gem::RemoteFetcher.new nil
    url = 'http://gems.example.com/redirect'

    conn = Object.new
    def conn.started?() true end
    def conn.request(req)
      url = 'http://gems.example.com/redirect'
      unless defined? @requested then
        @requested = true
        res = Net::HTTPMovedPermanently.new nil, 301, nil
        res.add_field 'Location', url
        res
      else
        res = Net::HTTPOK.new nil, 200, nil
        def res.body() 'real_path' end
        res
      end
    end

    conn = { "#{Thread.current.object_id}:gems.example.com:80" => conn }
    fetcher.instance_variable_set :@connections, conn

    data = fetcher.fetch_http URI.parse(url)

    assert_equal 'real_path', data
  end

  def test_fetch_http_redirects
    fetcher = Gem::RemoteFetcher.new nil
    url = 'http://gems.example.com/redirect'

    conn = Object.new
    def conn.started?() true end
    def conn.request(req)
      url = 'http://gems.example.com/redirect'
      res = Net::HTTPMovedPermanently.new nil, 301, nil
      res.add_field 'Location', url
      res
    end

    conn = { "#{Thread.current.object_id}:gems.example.com:80" => conn }
    fetcher.instance_variable_set :@connections, conn

    e = assert_raises Gem::RemoteFetcher::FetchError do
      fetcher.fetch_http URI.parse(url)
    end

    assert_equal "too many redirects (#{url})", e.message
  end

  def test_request
    uri = URI.parse "#{@gem_repo}/specs.#{Gem.marshal_version}"
    util_stub_connection_for :body => :junk, :code => 200

    response = @fetcher.request uri, Net::HTTP::Get

    assert_equal 200, response.code
    assert_equal :junk, response.body
  end

  def test_request_head
    uri = URI.parse "#{@gem_repo}/specs.#{Gem.marshal_version}"
    util_stub_connection_for :body => '', :code => 200
    response = @fetcher.request uri, Net::HTTP::Head

    assert_equal 200, response.code
    assert_equal '', response.body
  end

  def test_request_unmodified
    uri = URI.parse "#{@gem_repo}/specs.#{Gem.marshal_version}"
    conn = util_stub_connection_for :body => '', :code => 304

    t = Time.now
    response = @fetcher.request uri, Net::HTTP::Head, t

    assert_equal 304, response.code
    assert_equal '', response.body

    assert_equal t.rfc2822, conn.payload['if-modified-since']
  end

  def test_user_agent
    ua = @fetcher.user_agent

    assert_match %r%^RubyGems/\S+ \S+ Ruby/\S+ \(.*?\)%,          ua
    assert_match %r%RubyGems/#{Regexp.escape Gem::VERSION}%,      ua
    assert_match %r% #{Regexp.escape Gem::Platform.local.to_s} %, ua
    assert_match %r%Ruby/#{Regexp.escape RUBY_VERSION}%,          ua
    assert_match %r%\(#{Regexp.escape RUBY_RELEASE_DATE} %,       ua
  end

  def test_user_agent_engine
    util_save_version

    Object.send :remove_const, :RUBY_ENGINE if defined?(RUBY_ENGINE)
    Object.send :const_set,    :RUBY_ENGINE, 'vroom'

    ua = @fetcher.user_agent

    assert_match %r%\) vroom%, ua
  ensure
    util_restore_version
  end

  def test_user_agent_engine_ruby
    util_save_version

    Object.send :remove_const, :RUBY_ENGINE if defined?(RUBY_ENGINE)
    Object.send :const_set,    :RUBY_ENGINE, 'ruby'

    ua = @fetcher.user_agent

    assert_match %r%\)%, ua
  ensure
    util_restore_version
  end

  def test_user_agent_patchlevel
    util_save_version

    Object.send :remove_const, :RUBY_PATCHLEVEL
    Object.send :const_set,    :RUBY_PATCHLEVEL, 5

    ua = @fetcher.user_agent

    assert_match %r% patchlevel 5\)%, ua
  ensure
    util_restore_version
  end

  def test_user_agent_revision
    util_save_version

    Object.send :remove_const, :RUBY_PATCHLEVEL
    Object.send :const_set,    :RUBY_PATCHLEVEL, -1
    Object.send :remove_const, :RUBY_REVISION if defined?(RUBY_REVISION)
    Object.send :const_set,    :RUBY_REVISION, 6

    ua = @fetcher.user_agent

    assert_match %r% revision 6\)%, ua
    assert_match %r%Ruby/#{Regexp.escape RUBY_VERSION}dev%, ua
  ensure
    util_restore_version
  end

  def test_user_agent_revision_missing
    util_save_version

    Object.send :remove_const, :RUBY_PATCHLEVEL
    Object.send :const_set,    :RUBY_PATCHLEVEL, -1
    Object.send :remove_const, :RUBY_REVISION if defined?(RUBY_REVISION)

    ua = @fetcher.user_agent

    assert_match %r%\(#{Regexp.escape RUBY_RELEASE_DATE}\)%, ua
  ensure
    util_restore_version
  end

  def test_yaml_error_on_size
    use_ui @ui do
      self.class.enable_yaml = false
      fetcher = Gem::RemoteFetcher.new nil
      assert_error { fetcher.size }
    end
  end

  def test_ssl_connection
    ssl_server = self.class.start_ssl_server
    temp_ca_cert = File.join(DIR, 'ca_cert.pem')
    with_configured_fetcher(":ssl_ca_cert: #{temp_ca_cert}") do |fetcher|
      fetcher.fetch_path("https://localhost:#{ssl_server.config[:Port]}/yaml")
    end
  end

  def test_do_not_allow_insecure_ssl_connection_by_default
    ssl_server = self.class.start_ssl_server
    with_configured_fetcher do |fetcher|
      assert_raises Gem::RemoteFetcher::FetchError do
        fetcher.fetch_path("https://localhost:#{ssl_server.config[:Port]}/yaml")
      end
    end
  end

  def test_ssl_connection_allow_verify_none
    ssl_server = self.class.start_ssl_server
    with_configured_fetcher(":ssl_verify_mode: 0") do |fetcher|
      fetcher.fetch_path("https://localhost:#{ssl_server.config[:Port]}/yaml")
    end
  end

  def test_do_not_follow_insecure_redirect
    ssl_server = self.class.start_ssl_server
    temp_ca_cert = File.join(DIR, 'ca_cert.pem'),
    with_configured_fetcher(":ssl_ca_cert: #{temp_ca_cert}") do |fetcher|
      assert_raises Gem::RemoteFetcher::FetchError do
        fetcher.fetch_path("https://localhost:#{ssl_server.config[:Port]}/insecure_redirect?to=#{@server_uri}")
      end
    end
  end

  def with_configured_fetcher(config_str = nil, &block)
    if config_str
      temp_conf = File.join @tempdir, '.gemrc'
      File.open temp_conf, 'w' do |fp|
        fp.puts config_str
      end
      Gem.configuration = Gem::ConfigFile.new %W[--config-file #{temp_conf}]
    end
    yield Gem::RemoteFetcher.new
  ensure
    Gem.configuration = nil
  end

  def util_stub_connection_for hash
    def @fetcher.connection= conn
      @conn = conn
    end

    def @fetcher.connection_for uri
      @conn
    end

    @fetcher.connection = Conn.new OpenStruct.new(hash)
  end

  def assert_error(exception_class=Exception)
    got_exception = false

    begin
      yield
    rescue exception_class
      got_exception = true
    end

    assert got_exception, "Expected exception conforming to #{exception_class}"
  end

  def assert_data_from_server(data)
    assert_block("Data is not from server") { data =~ /0\.4\.11/ }
  end

  def assert_data_from_proxy(data)
    assert_block("Data is not from proxy") { data =~ /0\.4\.2/ }
  end

  class Conn
    attr_accessor :payload

    def initialize(response)
      @response = response
      self.payload = nil
    end

    def request(req)
      self.payload = req
      @response
    end
  end

  class NilLog < WEBrick::Log
    def log(level, data) #Do nothing
    end
  end

  class << self
    attr_reader :normal_server, :proxy_server
    attr_accessor :enable_zip, :enable_yaml

    def start_servers
      @normal_server ||= start_server(SERVER_PORT, SERVER_DATA)
      @proxy_server  ||= start_server(PROXY_PORT, PROXY_DATA)
      @enable_yaml = true
      @enable_zip = false
    end

    DIR = File.expand_path(File.dirname(__FILE__))
    DH_PARAM = OpenSSL::PKey::DH.new(128)

    def start_ssl_server(config = {})
      null_logger = NilLog.new
      server = WEBrick::HTTPServer.new({
        :Port => 0,
        :Logger => null_logger,
        :AccessLog => [],
        :SSLEnable => true,
        :SSLCACertificateFile => File.join(DIR, 'ca_cert.pem'),
        :SSLCertificate => cert('ssl_cert.pem'),
        :SSLPrivateKey => key('ssl_key.pem'),
        :SSLVerifyClient => nil,
        :SSLCertName => nil
      }.merge(config))
      server.mount_proc("/yaml") { |req, res|
        res.body = "--- true\n"
      }
      server.mount_proc("/insecure_redirect") { |req, res|
        res.set_redirect(WEBrick::HTTPStatus::MovedPermanently, req.query['to'])
      }
      server.ssl_context.tmp_dh_callback = proc { DH_PARAM }
      t = Thread.new do
        begin
          server.start
        rescue Exception => ex
          abort ex.message
          puts "ERROR during server thread: #{ex.message}"
        end
      end
      while server.status != :Running
        sleep 0.1
        unless t.alive?
          t.join
          raise
        end
      end
      server
    end

    private

    def start_server(port, data)
      Thread.new do
        begin
          null_logger = NilLog.new
          s = WEBrick::HTTPServer.new(
            :Port            => port,
            :DocumentRoot    => nil,
            :Logger          => null_logger,
            :AccessLog       => null_logger
            )
          s.mount_proc("/kill") { |req, res| s.shutdown }
          s.mount_proc("/yaml") { |req, res|
            if @enable_yaml
              res.body = data
              res['Content-Type'] = 'text/plain'
              res['content-length'] = data.size
            else
              res.status = "404"
              res.body = "<h1>NOT FOUND</h1>"
              res['Content-Type'] = 'text/html'
            end
          }
          s.mount_proc("/yaml.Z") { |req, res|
            if @enable_zip
              res.body = Zlib::Deflate.deflate(data)
              res['Content-Type'] = 'text/plain'
            else
              res.status = "404"
              res.body = "<h1>NOT FOUND</h1>"
              res['Content-Type'] = 'text/html'
            end
          }
          s.start
        rescue Exception => ex
          abort ex.message
          puts "ERROR during server thread: #{ex.message}"
        end
      end
      sleep 0.2                 # Give the servers time to startup
    end

    def cert(filename)
      OpenSSL::X509::Certificate.new(File.read(File.join(DIR, filename)))
    end

    def key(filename)
      OpenSSL::PKey::RSA.new(File.read(File.join(DIR, filename)))
    end
  end

  def test_correct_for_windows_path
    path = "/C:/WINDOWS/Temp/gems"
    assert_equal "C:/WINDOWS/Temp/gems", @fetcher.correct_for_windows_path(path)

    path = "/home/skillet"
    assert_equal "/home/skillet", @fetcher.correct_for_windows_path(path)
  end

  def util_save_version
    @orig_RUBY_ENGINE     = RUBY_ENGINE if defined? RUBY_ENGINE
    @orig_RUBY_PATCHLEVEL = RUBY_PATCHLEVEL
    @orig_RUBY_REVISION   = RUBY_REVISION if defined? RUBY_REVISION
  end

  def util_restore_version
    Object.send :remove_const, :RUBY_ENGINE if defined?(RUBY_ENGINE)
    Object.send :const_set,    :RUBY_ENGINE, @orig_RUBY_ENGINE if
      defined?(@orig_RUBY_ENGINE)

    Object.send :remove_const, :RUBY_PATCHLEVEL
    Object.send :const_set,    :RUBY_PATCHLEVEL, @orig_RUBY_PATCHLEVEL

    Object.send :remove_const, :RUBY_REVISION if defined?(RUBY_REVISION)
    Object.send :const_set,    :RUBY_REVISION, @orig_RUBY_REVISION if
      defined?(@orig_RUBY_REVISION)
  end

end


text:
"""Transfers data from AWS Redshift into a S3 Bucket."""
from typing import TYPE_CHECKING, Iterable, List, Mapping, Optional, Sequence, Union

from airflow.models import BaseOperator
from airflow.providers.amazon.aws.hooks.redshift_sql import RedshiftSQLHook
from airflow.providers.amazon.aws.hooks.s3 import S3Hook
from airflow.providers.amazon.aws.utils.redshift import build_credentials_block

if TYPE_CHECKING:
    from airflow.utils.context import Context

class RedshiftToS3Operator(BaseOperator):
    """
    Executes an UNLOAD command to s3 as a CSV with headers

    .. seealso::
        For more information on how to use this operator, take a look at the guide:
        :ref:`howto/operator:RedshiftToS3Operator`

    :param s3_bucket: reference to a specific S3 bucket
    :param s3_key: reference to a specific S3 key. If ``table_as_file_name`` is set
        to False, this param must include the desired file name
    :param schema: reference to a specific schema in redshift database
        Applicable when ``table`` param provided.
    :param table: reference to a specific table in redshift database
        Used when ``select_query`` param not provided.
    :param select_query: custom select query to fetch data from redshift database
    :param redshift_conn_id: reference to a specific redshift database
    :param aws_conn_id: reference to a specific S3 connection
        If the AWS connection contains 'aws_iam_role' in ``extras``
        the operator will use AWS STS credentials with a token
        https://docs.aws.amazon.com/redshift/latest/dg/copy-parameters-authorization.html#copy-credentials
    :param verify: Whether or not to verify SSL certificates for S3 connection.
        By default SSL certificates are verified.
        You can provide the following values:

        - ``False``: do not validate SSL certificates. SSL will still be used
                 (unless use_ssl is False), but SSL certificates will not be
                 verified.
        - ``path/to/cert/bundle.pem``: A filename of the CA cert bundle to uses.
                 You can specify this argument if you want to use a different
                 CA cert bundle than the one used by botocore.
    :param unload_options: reference to a list of UNLOAD options
    :param autocommit: If set to True it will automatically commit the UNLOAD statement.
        Otherwise it will be committed right before the redshift connection gets closed.
    :param include_header: If set to True the s3 file contains the header columns.
    :param parameters: (optional) the parameters to render the SQL query with.
    :param table_as_file_name: If set to True, the s3 file will be named as the table.
        Applicable when ``table`` param provided.
    """

    template_fields: Sequence[str] = (
        's3_bucket',
        's3_key',
        'schema',
        'table',
        'unload_options',
        'select_query',
    )
    template_ext: Sequence[str] = ('.sql',)
    template_fields_renderers = {'select_query': 'sql'}
    ui_color = '#ededed'

    def __init__(
        self,
        *,
        s3_bucket: str,
        s3_key: str,
        schema: Optional[str] = None,
        table: Optional[str] = None,
        select_query: Optional[str] = None,
        redshift_conn_id: str = 'redshift_default',
        aws_conn_id: str = 'aws_default',
        verify: Optional[Union[bool, str]] = None,
        unload_options: Optional[List] = None,
        autocommit: bool = False,
        include_header: bool = False,
        parameters: Optional[Union[Mapping, Iterable]] = None,
        table_as_file_name: bool = True,  # Set to True by default for not breaking current workflows
        **kwargs,
    ) -> None:
        super().__init__(**kwargs)
        self.s3_bucket = s3_bucket
        self.s3_key = f'{s3_key}/{table}_' if (table and table_as_file_name) else s3_key
        self.schema = schema
        self.table = table
        self.redshift_conn_id = redshift_conn_id
        self.aws_conn_id = aws_conn_id
        self.verify = verify
        self.unload_options = unload_options or []  # type: List
        self.autocommit = autocommit
        self.include_header = include_header
        self.parameters = parameters
        self.table_as_file_name = table_as_file_name

        if select_query:
            self.select_query = select_query
        elif self.schema and self.table:
            self.select_query = f"SELECT * FROM {self.schema}.{self.table}"
        else:
            raise ValueError(
                'Please provide both `schema` and `table` params or `select_query` to fetch the data.'
            )

        if self.include_header and 'HEADER' not in [uo.upper().strip() for uo in self.unload_options]:
            self.unload_options = list(self.unload_options) + [
                'HEADER',
            ]

    def _build_unload_query(
        self, credentials_block: str, select_query: str, s3_key: str, unload_options: str
    ) -> str:
        return f"""
                    UNLOAD ('{select_query}')
                    TO 's3://{self.s3_bucket}/{s3_key}'
                    credentials
                    '{credentials_block}'
                    {unload_options};
        """

    def execute(self, context: 'Context') -> None:
        redshift_hook = RedshiftSQLHook(redshift_conn_id=self.redshift_conn_id)
        conn = S3Hook.get_connection(conn_id=self.aws_conn_id)
        if conn.extra_dejson.get('role_arn', False):
            credentials_block = f"aws_iam_role={conn.extra_dejson['role_arn']}"
        else:
            s3_hook = S3Hook(aws_conn_id=self.aws_conn_id, verify=self.verify)
            credentials = s3_hook.get_credentials()
            credentials_block = build_credentials_block(credentials)

        unload_options = '\n\t\t\t'.join(self.unload_options)

        unload_query = self._build_unload_query(
            credentials_block, self.select_query, self.s3_key, unload_options
        )

        self.log.info('Executing UNLOAD command...')
        redshift_hook.run(unload_query, self.autocommit, parameters=self.parameters)
        self.log.info("UNLOAD command complete...")


text:
#include <aws/dataexchange/model/StartJobRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::DataExchange::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

StartJobRequest::StartJobRequest() :
    m_jobIdHasBeenSet(false)
{
}

Aws::String StartJobRequest::SerializePayload() const
{
  return {};
}


text:
import java.util.ArrayList;

public abstract class Location {

	String name;
	double wheat;
	double fruit;
	double meat;
	double alcohol;
	Market market;
	Player player;
	ArrayList<Product> all_products;
	ArrayList<Location> can_travel_list;
	ArrayList<Double> can_travel_cost_list;
	Travel travel;
	Bank bank;
	boolean can_repair;
	boolean can_upgrade;
	boolean can_buy_guns;
	double alcohol_bust_percentage;

	public Location(String n, Player p) {
		all_products = new ArrayList<Product>();
		name = n;
		setup_market();
		market = new Market(p, all_products);
		player = p;
		can_travel_list = new ArrayList<Location>();
		can_travel_cost_list = new ArrayList<Double>();
		alcohol_bust_percentage = set_bust_percentage();
		set_can_repair();
		set_can_upgrade();
		set_can_buy_guns();
		bank = new Bank(p);
	}

	public abstract void set_can_repair();
	public abstract void set_can_upgrade();
	public abstract void set_can_buy_guns();
	public abstract double set_bust_percentage();

	public void setup_market() {
		all_products.add(new Wheat());
		all_products.add(new Meat());
		all_products.add(new Fruit());
		all_products.add(new Alcohol());
	}

}


text:
package org.nanocontainer.reflection;

import org.nanocontainer.integrationkit.ContainerRecorder;
import org.picocontainer.MutablePicoContainer;
import org.picocontainer.PicoException;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * This class is serializable. The original container will not be serialized
 * (for performance reasons), but the invocations will, so they can be replayed at the
 * other end of the wire.
 *
 * @author Konstantin Pribluda ( konstantin.pribluda(at)infodesire.com )
 * @author Aslak Hellesøy
 * @author Mauro Talevi
 */
public class DefaultContainerRecorder implements Serializable, ContainerRecorder {

    private final List invocations = new ArrayList();
    private transient MutablePicoContainer container;

    private final InvocationHandler invocationRecorder = new InvocationRecorder();

    public DefaultContainerRecorder(MutablePicoContainer container) {
        this.container = container;
    }

    public MutablePicoContainer getContainerProxy() {
        return (MutablePicoContainer) Proxy.newProxyInstance(getClass().getClassLoader(),
                new Class[]{MutablePicoContainer.class}, invocationRecorder);
    }

    public void replay(MutablePicoContainer target) {
        for (Iterator iter = invocations.iterator(); iter.hasNext();) {
            Invocation invocation = (Invocation) iter.next();
            try {
                invocation.invoke(target);
            } catch (IllegalAccessException e) {
                throw new PicoException(e) {
                };
            } catch (InvocationTargetException e) {
                throw new PicoException(e) {
                };
            }
        }
    }

    private class Invocation implements Serializable {
        private transient Method method;
        private Object[] args;

        Invocation(Method method, Object[] args) {
            this.method = method;
            this.args = args;
        }

        private void writeObject(ObjectOutputStream out) throws IOException {
            out.defaultWriteObject();
            out.writeUTF(method.getName());
            out.writeObject(method.getDeclaringClass());
            Class[] parameterTypes = method.getParameterTypes();
            out.writeInt(parameterTypes.length);
            for (int i = 0; i < parameterTypes.length; i++) {
                out.writeObject(parameterTypes[i]);
            }
        }

        private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
            in.defaultReadObject();
            String methodName = in.readUTF();
            Class declaringClass = (Class) in.readObject();
            int n = in.readInt();
            Class[] parameterTypes = new Class[n];
            for (int i = 0; i < n; i++) {
                parameterTypes[i] = (Class) in.readObject();
            }
            try {
                method = declaringClass.getMethod(methodName, parameterTypes);
            } catch (NoSuchMethodException e) {
                throw new IOException("Couldn't load method " + methodName);
            }
        }

        public void invoke(Object target) throws IllegalAccessException, InvocationTargetException {
            method.invoke(target, args);
        }
    }

    private class InvocationRecorder implements InvocationHandler, Serializable {
        /**
         * Record invocation and invoke on underlying container
         */
        public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException, InvocationTargetException {
            invocations.add(new Invocation(method, args));
            return method.invoke(container, args);
        }
    };

}


text:
using System;
using System.Text;
using System.Numerics;
using System.Buffers.Text;
using System.Globalization;
using System.Collections.Generic;

using Xunit;

namespace System.Buffers.Text.Tests
{
    public sealed class ParserTestData<T>
    {
        public ParserTestData(string text, T expectedValue, char formatSymbol, bool expectedSuccess)
        {
            Text = text;
            ExpectedValue = expectedValue;
            FormatSymbol = formatSymbol;
            ExpectedSuccess = expectedSuccess;
            ExpectedBytesConsumed = Encoding.UTF8.GetByteCount(text);
        }

        public string Text { get; }
        public T ExpectedValue { get; }
        public char FormatSymbol { get; }
        public bool ExpectedSuccess { get; }
        public int ExpectedBytesConsumed { get; set; }  // Has a public setter so that individual test cases can override. By default, it's set to the Utf8 character length of Text

        public sealed override string ToString()
        {
            //
            // Take good care of this method: it affects Xunit output and makes a lot of difference in how annoying test investigations are.
            //

            string formatString = (FormatSymbol == default) ?
                "default" :
                FormatSymbol.ToString();

            return $"[Parse{typeof(T).Name} '{Text}',{formatString} to {(ExpectedSuccess ? ExpectedValue.DisplayString() : "(should-not-parse)")})]";
        }
    }
}


text:
package org.estatio.dom.lease;

import org.estatio.dom.utils.MathUtils;

public enum IndexationMethod {
    BASE_INDEX {
        @Override
        public void doInitialze(LeaseTermForIndexable term) {
            if (term.getPrevious() != null) {
                term.setBaseIndexStartDate(((LeaseTermForIndexable) term.getPrevious()).getBaseIndexStartDate());
            }
        }

        @Override
        public void doAlign(LeaseTermForIndexable term) {
            LeaseTermForIndexable previous = (LeaseTermForIndexable) term.getPrevious();
            if (previous != null) {
                term.setBaseValue(previous.getBaseValue());
            }
        }
    },
    LAST_KNOWN_INDEX {
        @Override
        public void doInitialze(LeaseTermForIndexable term) {
            if (term.getPrevious() != null) {
                term.setBaseIndexStartDate(((LeaseTermForIndexable) term.getPrevious()).getNextIndexStartDate());
            }
        }

        @Override
        public void doAlign(LeaseTermForIndexable term) {
            LeaseTermForIndexable previous = (LeaseTermForIndexable) term.getPrevious();
            if (previous != null) {
                term.setBaseValue(MathUtils.firstNonZero(
                        previous.getSettledValue(),
                        previous.getIndexedValue(),
                        previous.getBaseValue()));
            }
        }
    };

    public abstract void doInitialze(LeaseTermForIndexable term);

    public abstract void doAlign(LeaseTermForIndexable term);

}


text:
<?php

namespace Zend\Code\Generic\Prototype;

interface PrototypeInterface
{
    /**
     * @return string
     */
    public function getName();
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 297028 $ -->
<!-- Generated by xml_proto.php v2.2. Found in /scripts directory of phpdoc. -->
<refentry xml:id="function.db2-cursor-type" xmlns="http://docbook.org/ns/docbook">
 <refnamediv>
  <refname>db2_cursor_type</refname>
  <refpurpose>
   Returns the cursor type used by a statement resource
  </refpurpose>
 </refnamediv>
 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <type>int</type><methodname>db2_cursor_type</methodname>
   <methodparam><type>resource</type><parameter>stmt</parameter></methodparam>
  </methodsynopsis>

  <para>
   Returns the cursor type used by a statement resource. Use this to determine
   if you are working with a forward-only cursor or scrollable cursor.
  </para>

 </refsect1>
 <refsect1 role="parameters">
  &reftitle.parameters;
  <para>
   <variablelist>
    <varlistentry>
     <term><parameter>stmt</parameter></term>
     <listitem>
      <para>
       A valid statement resource.
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
  </para>
 </refsect1>
 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   Returns either <literal>DB2_FORWARD_ONLY</literal> if the statement
   resource uses a forward-only cursor or <literal>DB2_SCROLLABLE</literal> if
   the statement resource uses a scrollable cursor.
  </para>
 </refsect1>

 <!-- Use when examples exist
 <refsect1 role="examples">
  &reftitle.examples;
  <para>
   <example>
    <title>A <function>db2_cursor_type</function> example</title>
    <para>
     Any text that describes the purpose of the example, or
     what goes on in the example should go here (inside the
     <example> tag, not out
    </para>
    <programlisting role="php">
<![CDATA[
<?php
if ($anexample === true) {
    echo 'Use the PEAR Coding Standards';
}
?>
]]>
    </programlisting>
    &example.outputs;
    <screen>
<![CDATA[
Use the PEAR Coding Standards
]]>
    </screen>
   </example>
  </para>
 </refsect1>
 -->

 <refsect1 role="seealso">
  &reftitle.seealso;
  <para>
   <simplelist>
    <member><function>db2_prepare</function></member>
   </simplelist>
  </para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
controller :workout_window_exercise do
  spots "verb"

  on_entry %{
    context.ep = context.ep;
    context.ui_title = context.ui_title;
    context.image_url = context.image_url;
  }

  action :verb do
    on_entry %{
      var ctx = {
        parent: context,
      }

      if (context.ep.verb_type == "seconds") {
        Embed("exercise_verb_secs", "verb", ctx);
      }
    }

    on "verb_secs_completed", %{
      Goto("presay");
    }
  end

  action :presay do
    on_entry %{

      var ctx = {
        parent: context,
      }
      Embed("workout_window_exercise_presay", "verb", ctx);
    }

    on "start_clicked", %{
      Goto("countdown");
    }
  end

  action :countdown do
    on_entry %{
      Embed("workout_window_exercise_countdown", "verb", {});
    }

    on "countdown_finished", %{
      Goto("verb");
    }
  end

end

#Verb Seconds
####################################################################################################
controller :exercise_verb_secs do
  action :index do
    on_entry %{
      context.seconds = context.parent.ep.seconds;
    }

    every 1.seconds, %{
      if (context.seconds == 0) {
      debugger;
        Raise("verb_secs_completed", {});
        return;
      }

      context.seconds -= 1;

      Send("seconds", context.seconds.toString());
    }
  end
end
####################################################################################################


text:
package nlmt.datatypes;

import java.io.Serializable;
import java.util.*;

/**
 * The Document class performs two important functions. First,
 * it maps each word into the vocabulary, and keeps track of
 * each vocabulary index instead of the raw string. Second,
 * it keeps track of what topics have been assigned to each
 * word in the document.
 */
public class Document implements Serializable
{
    // The vocabulary words along with topic assignments
    private List<Word> wordArray;

    // The Vocabulary that provides the mapping from word
    // Strings to numbers
    private IdentifierObjectMapper<String> vocabulary;

    public Document(IdentifierObjectMapper<String> vocabulary) {
        if (vocabulary == null) {
            throw new IllegalArgumentException("vocabulary cannot be null");
        }
        wordArray = new ArrayList<>();
        this.vocabulary = vocabulary;
    }

    /**
     * Each document is a List of Strings that represent the
     * words in the document. For each word, add it to the vocabulary,
     * and then add the vocabulary number assigned to the word to
     * the wordArray for the document. If addWordsToVocabulary is
     * true, then any previously unseen words will be added to
     * the vocabulary.
     *
     * @param words the list of words in the document
     * @param addWordsToVocabulary if true, then previously unseen words will be added to the vocabulary
     */
    public void readDocument(List<String> words, boolean addWordsToVocabulary) {
        for (String word : words) {
            boolean vocabularyContainsWord = vocabulary.contains(word);
            if ((vocabularyContainsWord) || (!vocabularyContainsWord && addWordsToVocabulary)) {
                vocabulary.addObject(word);
                wordArray.add(new Word(word, vocabulary.getIndexFromObject(word)));
            }
        }
    }

    /**
     * Returns the list of words that the document is composed of.
     * Note that the resultant array contains indexes into the
     * vocabulary for each word.
     *
     * @return the list of word indexes
     */
    public int [] getWordArray() {
        return wordArray.stream().mapToInt(Word::getVocabularyId).toArray();
    }

    /**
     * Returns the original set of strings representing the document
     * from the vocabulary.
     *
     * @return the original array of Strings
     */
    public String [] getRawWords() {
        return wordArray.stream().map(Word::getRawWord).toArray(String[]::new);
    }

    /**
     * Returns what topic is assigned to each word. Each word is assigned
     * exactly one topic.
     *
     * @return the list of topics
     */
    public int [] getTopicArray() {
        return wordArray.stream().mapToInt(Word::getTopic).toArray();
    }

    /**
     * Assigns a topic to the specified word.
     *
     * @param wordIndex the index of the word
     * @param topicIndex the topic to assign
     */
    public void setTopicForWord(int wordIndex, int topicIndex) {

        if ((wordIndex > wordArray.size() - 1) || (wordIndex < 0)) {
            throw new IllegalArgumentException("wordIndex must be >= 0 or <= " + (wordArray.size() - 1));
        }
        wordArray.get(wordIndex).setTopic(topicIndex);
    }

    /**
     * Sets all of the topics to -1.
     */
    public void clearTopics() {
        wordArray.stream().forEach(word -> word.setTopic(-1));
    }

    /**
     * Returns the set of all words used in the document.
     *
     * @return the set of all words
     */
    public Set<Integer> getWordSet() {
        Set<Integer> result = new HashSet<>();
        wordArray.stream().mapToInt(Word::getVocabularyId).forEach(result::add);
        return result;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) { return true; }
        if ((o == null) || (getClass() != o.getClass())) { return false; }

        Document document = (Document) o;

        return Arrays.equals(getWordArray(), document.getWordArray()) && vocabulary.equals(document.vocabulary);
    }

    @Override
    public int hashCode() {
        int result = Arrays.hashCode(getWordArray());
        result = 31 * result + vocabulary.hashCode();
        return result;
    }
}


text:
'use strict';
/*jshint asi: true */

process.env.BROWSERIFYSHIM_DIAGNOSTICS=1;

// reproduces: https://github.com/thlorenz/browserify-shim/issues/30
var browserify = require('browserify')
  , test = require('tap').test
  , path = require('path')
  , vm = require('vm')

function inspect(obj, depth) {
  console.error(require('util').inspect(obj, false, depth || 5, true));
}
function bundleNcheck(relPath, t) {
  browserify( { ignoreGlobals: true })
    .require(require.resolve(relPath))
    .bundle(function (err, src) {
      if (err) { t.fail(err); return t.end(); }

      var ctx = { window: {}, console: console };
      ctx.self = ctx.window;
      var require_ = vm.runInNewContext(src, ctx);

      var main = require_(require.resolve(relPath));

      t.equal(main.ENV, 'this is ember env', 'shims ember correctly and fixes requires')
      t.deepEqual(main.$(), { jquery: '1.8.3' }, 'resolves jquery')
      t.equal(main.Handlebars, 'this is handlebars', 'resolves handlebars')
      t.end()
    });
}

test('\nbundling pack that has ember with invalid requires, installed via bower'
    , bundleNcheck.bind(null, './ember-bower'))


text:
require 'csv_to_popolo'
require 'minitest/autorun'

describe 'welsh assembly' do
  subject { Popolo::CSV.new('t/data/welsh_assembly.csv') }
  let(:pers) { subject.data[:persons] }
  let(:orgs) { subject.data[:organizations] }
  let(:mems) { subject.data[:memberships] }

  describe 'Asghar' do
    let(:asghar) { pers.find { |i| i[:id] == '130' } }

    it 'should have the correct name' do
      asghar[:name].must_equal 'Mohammad Asghar'
    end

    it 'should have other_names' do
      asghar[:other_names].class.must_equal Array
      asghar[:other_names].count.must_equal 1
      asghar[:other_names].first.class.must_equal Hash
      asghar[:other_names].first[:name].must_equal 'Oscar'
    end

    it 'should have a phone number' do
      asghar[:contact_details].class.must_equal Array
      asghar[:contact_details].count.must_equal 1
      asghar[:contact_details].first.class.must_equal Hash
      asghar[:contact_details].first[:type].must_equal 'phone'
      asghar[:contact_details].first[:value].must_equal '01633 220022'
    end

    it 'should have a website' do
      asghar[:links].class.must_equal Array
      asghar[:links].count.must_equal 1
      asghar[:links].first.class.must_equal Hash
      asghar[:links].first[:url].must_equal 'http://www.senedd.assemblywales.org/mgUserInfo.aspx?UID=130'
      asghar[:links].first[:note].must_equal 'website'
    end
  end

  describe 'Parties' do
    let(:parties) { orgs.select { |o| o[:classification] == 'party' } }

    it 'should have unique parties' do
      names = parties.map { |p| p[:name] }
      names.count.must_equal names.uniq.count
    end
  end

  describe 'Legislature' do
    let(:assembly) { orgs.select { |o| o[:classification] == 'legislature' } }

    it 'should have one legislature' do
      assembly.count.must_equal 1
    end

    it 'should have a correctly named legislature' do
      assembly.first[:name].must_equal 'Legislature'
    end
  end

  describe 'First Minister' do
    let(:fmin) { pers.find   { |p| p[:id] == '102' } }
    let(:fmem) { mems.select { |m| m[:person_id] == fmin[:id] } }

    it 'has a single membership' do
      fmem.count.must_equal 1
    end

    it 'has the Assembly membership' do
      fmem.find { |m| m[:role] == 'member' }[:area_id].must_equal 'area/bridgend'
    end

    it 'has no Executive org' do
      orgs.find { |o| o[:id] == 'executive' }.must_be_nil
    end

    it 'has no Executive memberships' do
      fmem.find { |m| m[:organization_id] != 'legislature' }.must_be_nil
    end
  end

  describe 'validation' do
    it 'should have skipped unknown columns' do
      subject.data[:warnings][:skipped].must_include :en_title
    end
  end
end