text:
package com.suscipio_solutions.consecro_mud.Abilities.Thief;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;

import com.suscipio_solutions.consecro_mud.Abilities.interfaces.Ability;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CMMsg;
import com.suscipio_solutions.consecro_mud.Common.interfaces.Clan;
import com.suscipio_solutions.consecro_mud.Items.interfaces.Coins;
import com.suscipio_solutions.consecro_mud.Items.interfaces.Item;
import com.suscipio_solutions.consecro_mud.MOBS.interfaces.Banker;
import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB;
import com.suscipio_solutions.consecro_mud.core.CMClass;
import com.suscipio_solutions.consecro_mud.core.CMLib;
import com.suscipio_solutions.consecro_mud.core.CMParms;
import com.suscipio_solutions.consecro_mud.core.CMProps;
import com.suscipio_solutions.consecro_mud.core.collections.Pair;
import com.suscipio_solutions.consecro_mud.core.interfaces.Environmental;
import com.suscipio_solutions.consecro_mud.core.interfaces.Physical;
import com.suscipio_solutions.consecro_mud.core.interfaces.ShopKeeper;

@SuppressWarnings("rawtypes")
public class Thief_Embezzle extends ThiefSkill
{
	@Override public String ID() { return "Thief_Embezzle"; }
	private final static String localizedName = CMLib.lang().L("Embezzle");
	@Override public String name() { return localizedName; }
	@Override public String displayText(){return "";}
	@Override protected int canAffectCode(){return CAN_MOBS;}
	@Override protected int canTargetCode(){return CAN_MOBS;}
	@Override public int abstractQuality(){return Ability.QUALITY_MALICIOUS;}
	private static final String[] triggerStrings =I(new String[] {"EMBEZZLE"});
	@Override public String[] triggerStrings(){return triggerStrings;}
	@Override public int classificationCode() {   return Ability.ACODE_SKILL|Ability.DOMAIN_CRIMINAL; }
	@Override protected boolean disregardsArmorCheck(MOB mob){return true;}
	public List<MOB> mobs=new Vector<MOB>();
	private final LinkedList<Pair<MOB,Integer>> lastOnes=new LinkedList<Pair<MOB,Integer>>();

	protected int timesPicked(MOB target)
	{
		int times=0;
		for(final Iterator<Pair<MOB,Integer>> p=lastOnes.iterator();p.hasNext();)
		{
			final Pair<MOB,Integer> P=p.next();
			final MOB M=P.first;
			final Integer I=P.second;
			if(M==target)
			{
				times=I.intValue();
				p.remove();
				break;
			}
		}
		if(lastOnes.size()>=50)
			lastOnes.removeFirst();
		lastOnes.add(new Pair<MOB,Integer>(target,Integer.valueOf(times+1)));
		return times+1;
	}

	@Override
	public boolean okMessage(final Environmental myHost, final CMMsg msg)
	{
		if((msg.amITarget(affected))
		   &&(mobs.contains(msg.source())))
		{
			if((msg.targetMinor()==CMMsg.TYP_BUY)
			   ||(msg.targetMinor()==CMMsg.TYP_BID)
			   ||(msg.targetMinor()==CMMsg.TYP_SELL)
			   ||(msg.targetMinor()==CMMsg.TYP_LIST)
			   ||(msg.targetMinor()==CMMsg.TYP_VALUE)
			   ||(msg.targetMinor()==CMMsg.TYP_VIEW))
			{
				msg.source().tell(L("@x1 looks unwilling to do business with you.",affected.name()));
				return false;
			}
		}
		return super.okMessage(myHost,msg);
	}

	@Override
	public int castingQuality(MOB mob, Physical target)
	{
		if(mob!=null)
		{
			if(mob.isInCombat())
				return Ability.QUALITY_INDIFFERENT;
		}
		return super.castingQuality(mob,target);
	}

	@Override
	public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
	{
		if((commands.size()<1)&&(givenTarget==null))
		{
			mob.tell(L("Embezzle money from whose accounts?"));
			return false;
		}
		MOB target=null;
		if((givenTarget!=null)&&(givenTarget instanceof MOB))
			target=(MOB)givenTarget;
		else
			target=mob.location().fetchInhabitant(CMParms.combine(commands,0));
		if((target==null)||(target.amDead())||(!CMLib.flags().canBeSeenBy(target,mob)))
		{
			mob.tell(L("You don't see '@x1' here.",CMParms.combine(commands,1)));
			return false;
		}
		if(!(target instanceof Banker))
		{
			mob.tell(L("You can't embezzle from @x1's accounts.",target.name(mob)));
			return false;
		}
		if(mob.isInCombat())
		{
			mob.tell(L("You are too busy to embezzle."));
			return false;
		}
		final Banker bank=(Banker)target;
		final Ability A=target.fetchEffect(ID());
		if(A!=null)
		{
			mob.tell(L("@x1 is watching @x2 books too closely.",target.name(mob),target.charStats().hisher()));
			return false;
		}
		final int levelDiff=target.phyStats().level()-(mob.phyStats().level()+(2*super.getXLEVELLevel(mob)));

		if(!target.mayIFight(mob))
		{
			mob.tell(L("You cannot embezzle from @x1.",target.charStats().himher()));
			return false;
		}

		Item myCoins=null;
		String myAcct=mob.Name();
		if(bank.isSold(ShopKeeper.DEAL_CLANBANKER))
		{
			Pair<Clan,Integer> clanPair=CMLib.clans().findPrivilegedClan(mob, Clan.Function.WITHDRAW);
			if(clanPair == null) clanPair=CMLib.clans().findPrivilegedClan(mob, Clan.Function.DEPOSIT_LIST);
			if(clanPair == null) clanPair=CMLib.clans().findPrivilegedClan(mob, Clan.Function.DEPOSIT);
			if(clanPair!=null)
				myAcct=clanPair.first.clanID();
		}
		myCoins=bank.findDepositInventory(myAcct,"1");
		if((myCoins==null)||(!(myCoins instanceof Coins)))
		{
			mob.tell(L("You don't have your own account with @x1.",target.name(mob)));
			return false;
		}
		final List<String> accounts=bank.getAccountNames();
		String victim="";
		int tries=0;
		Coins hisCoins=null;
		double hisAmount=0;
		while((hisCoins==null)&&((++tries)<10))
		{
			final String possVic=accounts.get(CMLib.dice().roll(1,accounts.size(),-1));
			final Item C=bank.findDepositInventory(possVic,"1");
			if((C!=null)
			&&(C instanceof Coins)
			&&((((Coins)C).getTotalValue()/50.0)>0.0)
			&&(!mob.Name().equals(possVic)))
			{
				hisCoins=(Coins)C;
				victim=possVic;
				hisAmount=hisCoins.getTotalValue()/50.0;
			}
		}
		final int classLevel=CMLib.ableMapper().qualifyingClassLevel(mob,this)+(2*getXLEVELLevel(mob));
		if((classLevel>0)
		&&(Math.round(hisAmount)>(1000*(classLevel)+(2*getXLEVELLevel(mob)))))
		   hisAmount=1000l*(classLevel+(2l*getXLEVELLevel(mob)));

		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		final boolean success=proficiencyCheck(mob,(-(levelDiff+(timesPicked(mob)*50))),auto);
		if((success)&&(hisAmount>0)&&(hisCoins!=null))
		{
			final String str=L("<S-NAME> embezzle(s) @x1 from the @x2 account maintained by <T-NAME>.",CMLib.beanCounter().nameCurrencyShort(target,hisAmount),victim);
			final CMMsg msg=CMClass.getMsg(mob,target,this,(auto?CMMsg.MASK_ALWAYS:0)|CMMsg.MSG_THIEF_ACT,str,null,str);
			if(mob.location().okMessage(mob,msg))
			{
				mob.location().send(mob,msg);
				beneficialAffect(mob,target,asLevel,(int)(((CMProps.getMillisPerMudHour()*mob.location().getArea().getTimeObj().getHoursInDay()*mob.location().getArea().getTimeObj().getDaysInMonth())/CMProps.getTickMillis())));
				bank.delDepositInventory(victim,hisCoins);
				hisCoins=CMLib.beanCounter().makeBestCurrency(target,hisCoins.getTotalValue()-(hisAmount/3.0));
				if(hisCoins.getNumberOfCoins()>0)
					bank.addDepositInventory(victim,hisCoins);
				bank.delDepositInventory(myAcct,myCoins);
				myCoins=CMLib.beanCounter().makeBestCurrency(mob,((Coins)myCoins).getTotalValue()+hisAmount);
				if(((Coins)myCoins).getNumberOfCoins()>0)
					bank.addDepositInventory(myAcct,myCoins);
			}
		}
		else
			maliciousFizzle(mob,target,L("<T-NAME> catch(es) <S-NAME> trying to embezzle money!"));
		return success;
	}

}


text:
package org.springframework.data.neo4j.repository.cdi;

import java.util.Optional;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

import org.apache.webbeans.cditest.CdiTestContainer;
import org.apache.webbeans.cditest.CdiTestContainerLoader;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.data.neo4j.examples.friends.domain.Person;

/**
 * Integration tests for {@link org.springframework.data.neo4j.repository.cdi.Neo4jCdiRepositoryExtension}.
 *
 * @author Mark Paluch
 * @see DATAGRAPH-879
 */
@Ignore("Why is this failing?")
public class CdiExtensionTests {

	static CdiTestContainer container;

    @BeforeClass
    public static void setUp() throws Exception {

        // Prevent the Jersey extension to interact with the InitialContext
        System.setProperty("com.sun.jersey.server.impl.cdi.lookupExtensionInBeanManager", "true");

        container = CdiTestContainerLoader.getCdiContainer();
        container.bootContainer();
    }

    @AfterClass
    public static void tearDown() throws Exception {

        container.shutdownContainer();
    }

	/**
	 * @see DATAGRAPH-879
	 */
	@Test
	public void regularRepositoryShouldWork() {

		RepositoryClient client = container.getInstance(RepositoryClient.class);
		CdiPersonRepository repository = client.repository;

		assertThat(repository, is(notNullValue()));

		Person person = null;
		Person result = null;

		repository.deleteAll();

		person = new Person();
		person.setFirstName("Homer");
		person.setLastName("Simpson");

		result = repository.save(person);

		assertThat(result, is(notNullValue()));
		Long resultId = result.getId();
		Optional<Person> lookedUpPerson = repository.findById(person.getId());
		assertTrue(lookedUpPerson.isPresent());
		lookedUpPerson.ifPresent(actual -> assertThat(actual.getId(), is(resultId)));
	}

	/**
	 * @see DATAGRAPH-879
	 */
	@Test
	public void repositoryWithQualifiersShouldWork() {

		RepositoryClient client = container.getInstance(RepositoryClient.class);
		client.qualifiedPersonRepository.deleteAll();

		assertEquals(0, client.qualifiedPersonRepository.count());
	}

	/**
	 * @see DATAGRAPH-879
	 */
	@Test
	public void repositoryWithCustomImplementationShouldWork() {

		RepositoryClient client = container.getInstance(RepositoryClient.class);

		assertEquals(1, client.samplePersonRepository.returnOne());
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<property name="dialect">org.hibernate.dialect.H2Dialect</property>
		<!--
		<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
		<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
		-->

		<property name="hibernate.connection.driver_class">org.h2.Driver</property>
		<property name="hibernate.connection.url">jdbc:h2:tcp://localhost/~/${artifactId}</property>
		<property name="hibernate.connection.username">sa</property>
		<property name="hibernate.connection.password"></property>

		<!--
		<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
		<property name="hibernate.connection.url">jdbc:oracle:thin:@127.0.0.1:1521:XE</property>
		<property name="hibernate.connection.username">${artifactId}</property>
		<property name="hibernate.connection.password">${artifactId}</property>
		-->

		<!--
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost/mini-service?useUnicode=true&characterEncoding=utf-8</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password"></property>
	 	-->
	</session-factory>
</hibernate-configuration>


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping package="cn.xaut.shop.pojo">
    <class name="DeliverAddr" table="TB_DELIVERADDR">
        <id name="deliveraddrId" type="java.lang.Integer">
            <column name="DELIVERADDR_ID" precision="22" scale="0" />
            <generator class="native" >
            	<param name="sequence">tb_deliveraddr_seq</param>
            </generator>
        </id>

        <property name="area" type="string">
            <column name="AREA" length="200" />
        </property>
        <property name="addr" type="string">
            <column name="ADDR" length="200" />
        </property>
        <property name="postcode" type="string">
            <column name="POSTCODE" length="6" />
        </property>
        <property name="recevername" type="string">
            <column name="RECEVERNAME" length="20" />
        </property>
        <property name="phone" type="string">
            <column name="PHONE" length="11" />
        </property>
        <!--
        <property name="telphone" type="string">
            <column name="TELPHONE" length="20" />
        </property>
         -->
        <property name="isdefault" type="string">
            <column name="ISDEFAULT" length="1"/>
        </property>

        <many-to-one name="user"  class="UserInfo" fetch="select">
         	<column name="user_id"></column>
         </many-to-one>
    </class>
</hibernate-mapping>


text: $redis = Redis::Namespace.new("lightair", :redis => Redis.new)


text:
@implementation ContactCell
@synthesize imgUser, lblName, radioBt;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {

        radioBt = [UIButton buttonWithType:UIButtonTypeCustom];
        radioBt.frame = CGRectMake(self.bounds.size.width - 32, (TABLE_VIEW_HEIGHT_FOR_ROW - 22) / 2, 22, 22);

        radioBt.backgroundColor = [UIColor clearColor];
        [self.contentView addSubview:radioBt];

        imgUser = [[UIImageView alloc] initWithFrame:CGRectMake(10, (TABLE_VIEW_HEIGHT_FOR_ROW - 38) / 2, 38, 38)];
        [self.contentView addSubview:imgUser];

        lblName = [[UILabel alloc] initWithFrame:CGRectMake(imgUser.frame.origin.x + imgUser.frame.size.width + 10, (TABLE_VIEW_HEIGHT_FOR_ROW - 27) / 2, 200, 27)];
        lblName.backgroundColor = [UIColor clearColor];
        [self.contentView addSubview:lblName];

//        // セパレータ
//        UIImageView *separatorImageView = [[UIImageView alloc] init];
//        separatorImageView.frame = CGRectMake(0, TABLE_VIEW_HEIGHT_FOR_ROW - 4, separatorImageView.frame.size.width, separatorImageView.frame.size.height);
//        [self.contentView addSubview:separatorImageView];
    }
    return self;
}

@end


text:
#include "fw_dunit.hpp"
#include "ThinClientHelper.hpp"

#define CLIENT1 s1p1
#define SERVER1 s2p1

using namespace apache::geode::client;
using namespace test;

#include "locator_globals.hpp"
#include "LocatorHelper.hpp"

using namespace apache::geode::client;
class SimpleCacheListener;

typedef apache::geode::client::SharedPtr<SimpleCacheListener>
    SimpleCacheListenerPtr;

// Use the "geode" namespace.
using namespace apache::geode::client;

// The SimpleCacheListener class.
class SimpleCacheListener : public CacheListener {
 public:
  // The Cache Listener callbacks.
  SimpleCacheListener() { m_count = 0; }
  virtual void afterCreate(const EntryEvent& event) {
    m_count++;
    LOGINFO("SimpleCacheListener: Got an afterCreate event.");
  }
  virtual void afterUpdate(const EntryEvent& event) {
    LOGINFO("SimpleCacheListener: Got an afterUpdate event.");
  }
  virtual void afterInvalidate(const EntryEvent& event) {
    LOGINFO("SimpleCacheListener: Got an afterInvalidate event.");
  }
  virtual void afterDestroy(const EntryEvent& event) {
    LOGINFO("SimpleCacheListener: Got an afterDestroy event.");
  }
  virtual void afterRegionInvalidate(const RegionEvent& event) {
    LOGINFO("SimpleCacheListener: Got an afterRegionInvalidate event.");
  }
  virtual void afterRegionDestroy(const RegionEvent& event) {
    LOGINFO("SimpleCacheListener: Got an afterRegionDestroy event.");
  }
  virtual void close(const RegionPtr& region) {
    LOGINFO("SimpleCacheListener: Got an close event.");
  }

  int getCount() { return m_count; }

 private:
  int m_count;
};
//---------------------------------------------------------------------------------

DUNIT_TASK_DEFINITION(SERVER1, StartServer)
  {
    if (isLocalServer) CacheHelper::initServer(1, "cacheserver.xml");
    LOG("SERVER started");
  }
END_TASK_DEFINITION

DUNIT_TASK_DEFINITION(CLIENT1, SetupClient1)
  {
    initClientWithPool(true, "__TEST_POOL1__", locatorsG, "ServerGroup1",
                       NULLPTR, 0, true);
    getHelper()->createPooledRegion(regionNames[0], false, locatorsG,
                                    "__TEST_POOL1__", true, true);
  }
END_TASK_DEFINITION

DUNIT_TASK_DEFINITION(CLIENT1, doRemoteGet)
  {
    RegionPtr regionPtr = getHelper()->getRegion(regionNames[0]);

    AttributesMutatorPtr attrMutatorPtr = regionPtr->getAttributesMutator();
    SimpleCacheListenerPtr regListener1(new SimpleCacheListener());
    attrMutatorPtr->setCacheListener(regListener1);

    // Put 3 Entries into the Region.
    regionPtr->put("Key1", "Value1");
    regionPtr->put("Key2", "Value2");
    regionPtr->put("Key3", "Value3");

    // Update Key3.
    regionPtr->put("Key3", "Value3-updated");

    // Destroy Key3.
    regionPtr->localDestroy("Key3");

    // Perform remote get (Locally destroyed).
    regionPtr->get("Key3");
    int toalFunCall = regListener1->getCount();
    ASSERT(4 == toalFunCall,
           "afterCreate() did not call expected number of times");
    // printf("[NIL_DEBUG_DUnitTest:149] Total Function Call =
    // %d.............\n",
    // toalFunCall);
    // printf("\n[NIL_DEBUG_DUnitTest:150:Remote get ended.
    // ..................\n");
  }
END_TASK_DEFINITION

DUNIT_TASK_DEFINITION(CLIENT1, StopClient1)
  {
    cleanProc();
    LOG("CLIENT1 stopped");
  }
END_TASK_DEFINITION

DUNIT_TASK_DEFINITION(SERVER1, StopServer)
  {
    if (isLocalServer) CacheHelper::closeServer(1);
    LOG("SERVER stopped");
  }
END_TASK_DEFINITION

void runThinClientListenerEventsTest() {
  CALL_TASK(CreateLocator1);
  CALL_TASK(CreateServer1_With_Locator);
  CALL_TASK(SetupClient1);

  CALL_TASK(doRemoteGet);

  CALL_TASK(StopClient1);
  CALL_TASK(StopServer);
  CALL_TASK(CloseLocator1);
}

DUNIT_MAIN
  { runThinClientListenerEventsTest(); }
END_MAIN


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE121_Stack_Based_Buffer_Overflow__CWE805_int64_t_declare_memmove_63b.c
Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE805.label.xml
Template File: sources-sink-63b.tmpl.c
*/
/*
 * @description
 * CWE: 121 Stack Based Buffer Overflow
 * BadSource:  Set data pointer to the bad buffer
 * GoodSource: Set data pointer to the good buffer
 * Sinks: memmove
 *    BadSink : Copy int64_t array to data using memmove
 * Flow Variant: 63 Data flow: pointer to data passed from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#ifndef OMITBAD

void CWE121_Stack_Based_Buffer_Overflow__CWE805_int64_t_declare_memmove_63b_badSink(int64_t * * dataPtr)
{
    int64_t * data = *dataPtr;
    {
        int64_t source[100] = {0}; /* fill with 0's */
        /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
        memmove(data, source, 100*sizeof(int64_t));
        printLongLongLine(data[0]);
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void CWE121_Stack_Based_Buffer_Overflow__CWE805_int64_t_declare_memmove_63b_goodG2BSink(int64_t * * dataPtr)
{
    int64_t * data = *dataPtr;
    {
        int64_t source[100] = {0}; /* fill with 0's */
        /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
        memmove(data, source, 100*sizeof(int64_t));
        printLongLongLine(data[0]);
    }
}

#endif /* OMITGOOD */


text:
package com.xhh.demo.zookeeper.client;

import com.xhh.demo.zookeeper.ZookeeperClient;
import com.xhh.demo.zookeeper.ZookeeperTransporter;
import com.xhh.demo.zookeeper.client.CuratorZookeeperClient;
import com.xhh.demo.zookeeper.support.URL;

/**
 * zkClient 连接封装接口实现
 *
 * @author tiger
 * @version 1.0.0 createTime: 15/3/13 下午11:33
 * @see com.xhh.demo.zookeeper.ZookeeperTransporter
 * @since 1.6
 */
public class CuratorZookeeperTransporter implements ZookeeperTransporter {

    /**
     * 建立 zkClient 连接
     *
     * @param url 连接参数
     * @return zkClient 接口
     */
    @Override
    public ZookeeperClient connect(URL url) {
        return new CuratorZookeeperClient(url);
    }
}


text:
ALTER TABLE `user`
  ADD `avatar_namespace` varchar(250) COLLATE 'ascii_general_ci' NOT NULL AFTER `name`,
  CHANGE `avatar` `avatar_filename` varchar(250) COLLATE 'ascii_general_ci' NULL AFTER `avatar_namespace`;


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Amer. Midl. Naturalist 36:173. 1946

#### Original name
null

### Remarks
null


text:
require 'helper'

describe RakeVersion::Config do

  before :each do
    @config = RakeVersion::Config.new
  end

  describe 'Copiers' do

    it "should not have any copiers by default" do
      expect(@config.copiers).to be_empty
    end

    it "should correctly create copiers" do
      copiers = [
        [],
        [ 'src/**/*.js' ],
        [ /src\/.*\.sh/ ],
        [ 'src/example.js', 'src/example.rb' ],
        [ 'src/**/*.rb', { :all => true } ]
      ]
      copiers.each do |args|
        expect{ @config.copy *args }.not_to raise_error
      end
      expect(@config.copiers.length).to eq(copiers.length)
    end

    it "should create copiers with a ruby extension glob by default" do
      expect(RakeVersion::Copier).to receive(:new).with('src/**/*.rb')
      @config.copy
    end

    it "should return itself when creating a copier" do
      expect(@config.copy).to be(@config)
    end

    it "should return a copy of its copiers array" do
      @config.copy
      @config.copiers.clear
      expect(@config.copiers.length).to eq(1)
    end
  end

  describe 'Extension' do

    it "should have the ruby extension by default" do
      expect(@config.extension).to eq('rb')
    end

    it "should accept alphanumerical extensions" do
      [ :rb, 'js', :sh, 'py', double('extension', :to_s => 'java') ].each do |ext|
        expect{ @config.extension = ext }.not_to raise_error
        expect(@config.extension).to eq(ext.to_s)
      end
    end

    it "should not accept non-alphanumerical extensions" do
      [ nil, '.', :_, [], {}, double('fubar') ].each do |invalid|
        expect{ @config.extension = invalid }.to raise_error(StandardError)
      end
    end
  end
end


text:
require "espn"
require "vcr"
require "simplecov"
require "simplecov-rcov"

class SimpleCov::Formatter::MergedFormatter
  def format result
    SimpleCov::Formatter::HTMLFormatter.new.format result
    SimpleCov::Formatter::RcovFormatter.new.format result
  end
end

SimpleCov.formatter = SimpleCov::Formatter::MergedFormatter
SimpleCov.start do
  add_filter '/vendor'
end

VCR.configure do |c|
  c.allow_http_connections_when_no_cassette = true
  c.cassette_library_dir = 'spec/cassettes'
  c.hook_into :fakeweb
  c.configure_rspec_metadata!
  c.default_cassette_options = { :record => :new_episodes }
  c.filter_sensitive_data('APIKEY') do |interaction|
    interaction.request.uri = '?apikey='
  end
end

RSpec.configure do |c|
  c.extend VCR::RSpec::Macros
  c.treat_symbols_as_metadata_keys_with_true_values = true
  c.before(:each) do
    ESPN.configure do |config|
      config.api_key = "YOUR API KEY HERE"
    end

    @client = ESPN::Client.new
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>

<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">

    <bean id="switchBoardImplBean" class="org.lesie.kernel.impl.SwitchBoardImpl">
        <property name="queueManager" ref="queueManager"/>
    </bean>

    <service id="switchBoard"  ref="switchBoardImplBean" interface="org.lesie.kernel.SwitchBoard"/>

    <reference id="queueManager" interface="org.lesie.queue.manager.QueueManager"/>

</blueprint>


text:
"""
Who-Is, I-Am VLAN

This sample application is very similar to WhoIsIAm.py but rather than the
device on an IPv4 network, it is sitting on a VLAN with a router to the
network.  The INI file is used for the device object properties with the
exception of the address, which is given to the router.
"""

import sys
import argparse

from bacpypes.debugging import bacpypes_debugging, ModuleLogger
from bacpypes.consolelogging import ConfigArgumentParser
from bacpypes.consolecmd import ConsoleCmd

from bacpypes.comm import bind
from bacpypes.core import run, deferred
from bacpypes.iocb import IOCB

from bacpypes.pdu import Address, LocalBroadcast, GlobalBroadcast
from bacpypes.netservice import NetworkServiceAccessPoint, NetworkServiceElement
from bacpypes.bvllservice import BIPSimple, AnnexJCodec, UDPMultiplexer

from bacpypes.app import ApplicationIOController
from bacpypes.appservice import StateMachineAccessPoint, ApplicationServiceAccessPoint
from bacpypes.local.device import LocalDeviceObject
from bacpypes.service.device import (
    WhoIsIAmServices,
    )
from bacpypes.service.object import (
    ReadWritePropertyServices,
    ReadWritePropertyMultipleServices,
    )
from bacpypes.apdu import (
    WhoIsRequest,
    IAmRequest,
    )
from bacpypes.errors import DecodingError

from bacpypes.vlan import Network, Node

# some debugging
_debug = 0
_log = ModuleLogger(globals())

# globals
args = None
this_device = None
this_application = None

#
#   VLANApplication
#

@bacpypes_debugging
class VLANApplication(
    ApplicationIOController,
    WhoIsIAmServices,
    ReadWritePropertyServices,
    ):

    def __init__(self, vlan_device, vlan_address, aseID=None):
        if _debug: VLANApplication._debug("__init__ %r %r aseID=%r", vlan_device, vlan_address, aseID)
        ApplicationIOController.__init__(self, vlan_device, vlan_address, aseID=aseID)

        # include a application decoder
        self.asap = ApplicationServiceAccessPoint()

        # pass the device object to the state machine access point so it
        # can know if it should support segmentation
        self.smap = StateMachineAccessPoint(vlan_device)

        # the segmentation state machines need access to the same device
        # information cache as the application
        self.smap.deviceInfoCache = self.deviceInfoCache

        # a network service access point will be needed
        self.nsap = NetworkServiceAccessPoint()

        # give the NSAP a generic network layer service element
        self.nse = NetworkServiceElement()
        bind(self.nse, self.nsap)

        # bind the top layers
        bind(self, self.asap, self.smap, self.nsap)

        # create a vlan node at the assigned address
        self.vlan_node = Node(vlan_address)

        # bind the stack to the node, no network number
        self.nsap.bind(self.vlan_node, address=vlan_address)

        # keep track of requests to line up responses
        self._request = None

        if _debug: VLANApplication._debug("    - nsap.local_address: %r", self.nsap.local_address)

    def process_io(self, iocb):
        if _debug: VLANApplication._debug("[%s]process_io %r", self.vlan_node.address, iocb)

        # save a copy of the request
        self._request = iocb.args[0]

        # forward it along
        VLANApplication.process_io(self, iocb)

    def indication(self, apdu):
        if _debug: VLANApplication._debug("[%s]indication %r", self.vlan_node.address, apdu)

        if (isinstance(self._request, WhoIsRequest)) and (isinstance(apdu, IAmRequest)):
            device_type, device_instance = apdu.iAmDeviceIdentifier
            if device_type != 'device':
                raise DecodingError("invalid object type")

            if (self._request.deviceInstanceRangeLowLimit is not None) and \
                    (device_instance < self._request.deviceInstanceRangeLowLimit):
                pass
            elif (self._request.deviceInstanceRangeHighLimit is not None) and \
                    (device_instance > self._request.deviceInstanceRangeHighLimit):
                pass
            else:
                # print out the contents
                sys.stdout.write('pduSource = ' + repr(apdu.pduSource) + '\n')
                sys.stdout.write('iAmDeviceIdentifier = ' + str(apdu.iAmDeviceIdentifier) + '\n')
                sys.stdout.write('maxAPDULengthAccepted = ' + str(apdu.maxAPDULengthAccepted) + '\n')
                sys.stdout.write('segmentationSupported = ' + str(apdu.segmentationSupported) + '\n')
                sys.stdout.write('vendorID = ' + str(apdu.vendorID) + '\n')
                sys.stdout.flush()

        # forward it along
        super(VLANApplication, self).indication(apdu)

    def response(self, apdu):
        if _debug: VLANApplication._debug("[%s]response %r", self.vlan_node.address, apdu)
        super(VLANApplication, self).response(apdu)

    def confirmation(self, apdu):
        if _debug: VLANApplication._debug("[%s]confirmation %r", self.vlan_node.address, apdu)
        super(VLANApplication, self).confirmation(apdu)

#
#   VLANRouter
#

@bacpypes_debugging
class VLANRouter:

    def __init__(self, local_address, local_network):
        if _debug: VLANRouter._debug("__init__ %r %r", local_address, local_network)

        # a network service access point will be needed
        self.nsap = NetworkServiceAccessPoint()

        # give the NSAP a generic network layer service element
        self.nse = NetworkServiceElement()
        bind(self.nse, self.nsap)

        # create a BIPSimple, bound to the Annex J server
        # on the UDP multiplexer
        self.bip = BIPSimple(local_address)
        self.annexj = AnnexJCodec()
        self.mux = UDPMultiplexer(local_address)

        # bind the bottom layers
        bind(self.bip, self.annexj, self.mux.annexJ)

        # bind the BIP stack to the local network
        self.nsap.bind(self.bip, local_network, local_address)

#
#   WhoIsIAmConsoleCmd
#

@bacpypes_debugging
class WhoIsIAmConsoleCmd(ConsoleCmd):

    def do_whois(self, args):
        """whois [ <addr>] [ <lolimit> <hilimit> ]"""
        args = args.split()
        if _debug: WhoIsIAmConsoleCmd._debug("do_whois %r", args)

        try:
            # build a request
            request = WhoIsRequest()
            if (len(args) == 1) or (len(args) == 3):
                request.pduDestination = Address(args[0])
                del args[0]
            else:
                request.pduDestination = GlobalBroadcast()

            if len(args) == 2:
                request.deviceInstanceRangeLowLimit = int(args[0])
                request.deviceInstanceRangeHighLimit = int(args[1])
            if _debug: WhoIsIAmConsoleCmd._debug("    - request: %r", request)

            # make an IOCB
            iocb = IOCB(request)
            if _debug: WhoIsIAmConsoleCmd._debug("    - iocb: %r", iocb)

            # give it to the application
            this_application.request_io(iocb)

        except Exception as err:
            WhoIsIAmConsoleCmd._exception("exception: %r", err)

    def do_iam(self, args):
        """iam"""
        args = args.split()
        if _debug: WhoIsIAmConsoleCmd._debug("do_iam %r", args)

        try:
            # build a request
            request = IAmRequest()
            request.pduDestination = GlobalBroadcast()

            # set the parameters from the device object
            request.iAmDeviceIdentifier = this_device.objectIdentifier
            request.maxAPDULengthAccepted = this_device.maxApduLengthAccepted
            request.segmentationSupported = this_device.segmentationSupported
            request.vendorID = this_device.vendorIdentifier
            if _debug: WhoIsIAmConsoleCmd._debug("    - request: %r", request)

            # make an IOCB
            iocb = IOCB(request)
            if _debug: WhoIsIAmConsoleCmd._debug("    - iocb: %r", iocb)

            # give it to the application
            this_application.request_io(iocb)

        except Exception as err:
            WhoIsIAmConsoleCmd._exception("exception: %r", err)

    def do_rtn(self, args):
        """rtn <addr> <net> ... """
        args = args.split()
        if _debug: WhoIsIAmConsoleCmd._debug("do_rtn %r", args)

        # provide the address and a list of network numbers
        router_address = Address(args[0])
        network_list = [int(arg) for arg in args[1:]]

        # pass along to the service access point
        this_application.nsap.update_router_references(None, router_address, network_list)

#
#   __main__
#

def main():
    global args, this_device, this_application

    # parse the command line arguments
    parser = ConfigArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter,
        )

    # add an argument for interval
    parser.add_argument('net1', type=int,
        help='network number of IPv4 network',
        )

    # add an argument for interval
    parser.add_argument('net2', type=int,
        help='network number of VLAN network',
        )

    # add an argument for interval
    parser.add_argument('addr2', type=str,
        help='address on the VLAN network',
        )

    # now parse the arguments
    args = parser.parse_args()

    if _debug: _log.debug("initialization")
    if _debug: _log.debug("    - args: %r", args)

    local_network = args.net1
    local_address = Address(args.ini.address)
    if _debug: _log.debug("    - local_network, local_address: %r, %r", local_network, local_address)

    vlan_network = args.net2
    vlan_address = Address(args.addr2)
    if _debug: _log.debug("    - vlan_network, vlan_address: %r, %r", vlan_network, vlan_address)

    # create the VLAN router, bind it to the local network
    router = VLANRouter(local_address, local_network)

    # create a VLAN
    vlan = Network(broadcast_address=LocalBroadcast())

    # create a node for the router, address 1 on the VLAN
    router_node = Node(Address(1))
    vlan.add_node(router_node)

    # bind the router stack to the vlan network through this node
    router.nsap.bind(router_node, vlan_network)

    # send network topology
    deferred(router.nse.i_am_router_to_network)

    # make a vlan device object
    this_device = \
        LocalDeviceObject(
            objectName=args.ini.objectname,
            objectIdentifier=("device", int(args.ini.objectidentifier)),
            maxApduLengthAccepted=1024,
            segmentationSupported='noSegmentation',
            vendorIdentifier=15,
            )
    _log.debug("    - this_device: %r", this_device)

    # make the application, add it to the network
    this_application = VLANApplication(this_device, vlan_address)
    vlan.add_node(this_application.vlan_node)
    _log.debug("    - this_application: %r", this_application)

    # make a console
    this_console = WhoIsIAmConsoleCmd()
    if _debug: _log.debug("    - this_console: %r", this_console)

    _log.debug("running")

    run()

    _log.debug("fini")

if __name__ == "__main__":
    main()


text:
const exec = require('execa').sync;

const del = require('del').sync;

const path = require('path');

/**
 * Build zip artifact for MacOS since electron-builder breaks zips
 *
 * @param {import('electron-builder').BuildResult} context
 *
 * @return {Promise<any>}
 */
module.exports = async function(context) {

  if (!isBuildingMacDistro(context)) {
    return;
  }

  const {
    artifactPaths,
    configuration,
    outDir
  } = context;

  const {
    productName
  } = configuration;

  const dmgPath = artifactPaths.find(path => /\.dmg$/.test(path));
  const zipPath = dmgPath.replace(/dmg$/, 'zip');

  const appDir = path.join(outDir, 'mac');

  console.log(`  • building     target=ZIP arch=x64 file=${zipPath}`);

  del(zipPath);

  exec('zip', [ '--symlinks', '-r', zipPath, `${productName}.app` ], { cwd: appDir });

  // TODO: update dist/latest-mac.yml with blockmap information
  // As of `electron-builder@22.1.0`, the `app-builder-bin` blockmap utility
  // modifies the digested ZIP file and thus makes the central record directory broken.

  return [ zipPath ];
};

function isBuildingMacDistro(context) {
  const {
    platformToTargets
  } = context;

  for (const platform of platformToTargets.keys()) {
    if (platform.name === 'mac') {
      return true;
    }
  }

  return false;
}


text:
using System;
using System.Diagnostics.Contracts;

namespace Contract
{
    public class FfmpegPart
    {
        public int Id { get; set; }
        public string SourceFilename { get; set; }
        public string Filename { get; set; }
        public int Number { get; set; }
        public int Target { get; set; }
        public bool IsAudio => Filename.EndsWith("_audio.mp4", StringComparison.InvariantCultureIgnoreCase);
        public Guid JobCorrelationId { get; set; }
        public double Psnr { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }
        public int Bitrate { get; set; }
    }
}


text:
package org.arquillian.smart.testing.rules.git.server;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import net.jcip.annotations.NotThreadSafe;
import org.arquillian.smart.testing.rules.git.GitCloner;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.TransportException;
import org.eclipse.jgit.lib.Repository;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.ExpectedException;

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

@Category(NotThreadSafe.class)
public class EmbeddedHttpGitServerTest {

    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    private final List<Function<Void, Void>> executeAfterTest = new ArrayList<>();

    private GitCloner gitCloner;
    private EmbeddedHttpGitServer gitServer;
    private Repository repository;

    @After
    public void cleanup() {
        executeAfterTest.forEach(cleanup -> cleanup.apply(null));
        if (repository != null) {
            repository.close();
        }
        if (gitCloner != null) {
            gitCloner.removeClone();
        }
        if (gitServer != null) {
            gitServer.stop();
        }
    }

    @Test
    public void should_be_able_to_use_custom_port_and_clone_repository_using_http_call() throws Exception {
        // given
        gitServer = EmbeddedHttpGitServer.fromBundle("test-repo", "booster-catalog.bundle").usingPort(8989).create();
        gitServer.start();

        // when
        gitCloner = new GitCloner("http://localhost:8989/test-repo");
        repository = gitCloner.cloneRepositoryToTempFolder(true);
        Git.wrap(repository).checkout().setName("next").call();

        // then
        assertThat(new File(repository.getDirectory().getParent(), "RELEASE.adoc")).exists();
    }

    @Test
    public void should_be_able_to_clone_repository_using_http_call_ignoring_dot_git_suffix() throws Exception {
        // given
        gitServer = EmbeddedHttpGitServer.fromBundle("test-repo", "repo.bundle").usingPort(9922).create();
        gitServer.start();

        // when
        gitCloner = new GitCloner("http://localhost:9922/test-repo.git");
        repository = gitCloner.cloneRepositoryToTempFolder();

        // then
        assertThat(new File(repository.getDirectory().getParent(), "Jenkinsfile")).exists();
    }

    @Test
    public void should_be_able_to_use_custom_port_from_system_property_and_clone_repository_using_http_call()
        throws Exception {
        // given
        System.setProperty("git.server.port", "12345");
        gitServer = EmbeddedHttpGitServer.fromBundle("repo.bundle").create();
        executeAfterTest.add(v -> {
            System.clearProperty("git.server.port");
            return v;
        });
        gitServer.start();

        // when
        gitCloner = new GitCloner("http://localhost:12345/repo.bundle");
        repository = gitCloner.cloneRepositoryToTempFolder();

        // then
        assertThat(new File(repository.getDirectory().getParent(), "Jenkinsfile")).exists();
    }

    @Test
    public void should_be_able_to_push_to_served_repository_on_the_default_port() throws Exception {
        // given
        gitServer = EmbeddedHttpGitServer.fromBundle("das-repo","repo.bundle").create();
        gitCloner = new GitCloner("http://localhost:8765/das-repo");
        final GitCloner secondGitCloner = new GitCloner("http://localhost:8765/das-repo");
        executeAfterTest.add(v -> {
            secondGitCloner.removeClone();
            return v;
        });

        gitServer.start();
        repository = gitCloner.cloneRepositoryToTempFolder();
        createNewFileAndPush(repository, "new-file.txt", "new file", "feat: new file");

        // when
        final Repository secondClone = secondGitCloner.cloneRepositoryToTempFolder();
        executeAfterTest.add(v -> { secondClone.close(); return v; });

        // then
        assertThat(new File(secondClone.getDirectory().getParent(), "new-file.txt")).exists();
    }

    @Test
    public void should_be_able_to_serve_multiple_repositories() throws Exception {
        // given
        gitServer = EmbeddedHttpGitServer.fromBundle("das-repo","repo.bundle")
                                         .fromPath(Paths.get("src/test/resources/saas-launchpad.bundle"))
                                         .usingPort(5433)
                                         .create();
        gitServer.start();

        final GitCloner dasRepoCloner = new GitCloner("http://localhost:5433/das-repo");
        final GitCloner launchpadCloner = new GitCloner("http://localhost:5433/saas-launchpad.bundle");

        // when
        final Repository dasRepo = dasRepoCloner.cloneRepositoryToTempFolder();
        executeAfterTest.add(v -> { dasRepo.close(); return v; });
        final Repository launchpad = launchpadCloner.cloneRepositoryToTempFolder();
        executeAfterTest.add(v -> { launchpad.close(); return v; });

        // then
        assertThat(new File(dasRepo.getDirectory().getParent(), "Jenkinsfile")).exists();
        assertThat(new File(launchpad.getDirectory().getParent(), "config.yaml")).exists();
    }

    @Test
    public void should_fail_with_repository_not_found_when_trying_to_clone_non_existing_repo() throws Exception {
        // given
        gitServer = EmbeddedHttpGitServer.fromBundle("launchpad", "saas-launchpad.bundle")
            .usingPort(6432)
            .create();
        gitServer.start();

        expectedException.expect(TransportException.class);
        expectedException.expectMessage("Git repository not found");

        // when
        final GitCloner launchpadCloner = new GitCloner("http://localhost:6432/launchpadeeeee");
        final Repository launchpad = launchpadCloner.cloneRepositoryToTempFolder();

        // then
        // should fail
    }

    private void createNewFileAndPush(Repository repository, String newFile, String content, String commitMessage)
        throws IOException, GitAPIException {
        final File root = repository.getDirectory().getParentFile();
        Files.write(Paths.get(root.getPath(), newFile), content.getBytes());
        final Git git = Git.wrap(repository);
        git.add().addFilepattern(".").call();
        git.commit().setMessage(commitMessage).call();
        git.push().call();
    }
}


text:
module Elasticrawl
  # Represents an Elastic MapReduce job flow that parses segments of
  # Common Crawl data. A job step is created per segment.
  #
  # Inherits from Job which is the ActiveRecord model class.
  class ParseJob < Job
    # Populates the job from the list of segments to be parsed.
    def set_segments(crawl_segments, max_files = nil)
      self.job_name = set_job_name
      self.job_desc = set_job_desc(crawl_segments, max_files)
      self.max_files = max_files

      crawl_segments.each do |segment|
        self.job_steps.push(create_job_step(segment))
      end
    end

    # Runs the job by calling Elastic MapReduce API.  If successful the
    # parse time is set for each segment.
    def run
      emr_config = job_config['emr_config']
      job_flow_id = run_job_flow(emr_config)

      if job_flow_id.present?
        self.job_flow_id = job_flow_id

        self.job_steps.each do |step|
          segment = step.crawl_segment
          segment.parse_time = DateTime.now
          segment.save
        end

        self.save
        self.result_message
      end
    end

    # Returns the S3 location for storing Elastic MapReduce job logs.
    def log_uri
      s3_path = "/logs/1-parse/#{self.job_name}/"
      build_s3_uri(s3_path)
    end

    # Return list of segment descriptions.
    def segment_list
      segments = ['Segments']

      job_steps.each do |job_step|
        if job_step.crawl_segment.present?
          segment = job_step.crawl_segment
          segments.push(segment.segment_desc)
        end
      end

      segments.push('')
    end

  private
    # Creates a job step for the crawl segment.
    def create_job_step(segment)
      JobStep.create(:job => self,
                     :crawl_segment => segment,
                     :input_paths => segment_input(segment),
                     :output_path => segment_output(segment))
    end

    # Returns the S3 location for reading a crawl segment. The input filter
    # determines which type of Common Crawl data files are parsed.
    def segment_input(segment)
      segment.segment_s3_uri + job_config['input_filter']
    end

    # Returns the S3 location for storing the step results.  This includes
    # the segment name.
    def segment_output(segment)
      job_path = "/data/1-parse/#{self.job_name}"
      s3_path = "#{job_path}/segments/#{segment.segment_name}/"
      build_s3_uri(s3_path)
    end

    # Sets the job description which forms part of the Elastic MapReduce
    # job flow name.
    def set_job_desc(segments, max_files)
      if segments.count > 0
        crawl_name = segments[0].crawl.crawl_name if segments[0].crawl.present?
        file_desc = max_files.nil? ? 'all files' : "#{max_files} files per segment"
      end

      "Crawl: #{crawl_name} Segments: #{segments.count} Parsing: #{file_desc}"
    end

    # Returns the parse job configuration from ~/.elasticrawl.jobs.yml.
    def job_config
      config = Config.new
      config.load_config('jobs')['steps']['parse']
    end
  end
end


text:
package com.microsoft.xrm.sdk.Messages;

import com.microsoft.xrm.sdk.OrganizationResponse;
import com.microsoft.xrm.sdk.Utils;

import org.xmlpull.v1.XmlPullParser;

import java.util.UUID;

public final class DeliverIncomingEmailResponse extends OrganizationResponse {

    private UUID emailId;

    public UUID getEmailId() {
        return emailId;
    }

    @Override
    public void storeResult(XmlPullParser parser) {
        try {
            String name = parser.getName();
            parser.nextTag();

            do {
                if (parser.getEventType() != XmlPullParser.START_TAG) {
                    parser.next();
                    continue;
                }

                if (parser.getName().equals("KeyValuePairOfstringanyType")) {
                    parser.nextTag();
                    do {
                        if (parser.getEventType() != XmlPullParser.START_TAG) {
                            parser.next();
                            continue;
                        }

                        if (parser.getName().equals("key")) {
                            parser.next();
                            if (parser.getText().equals("EmailId")) {
                                parser.nextTag();
                                parser.nextTag();
                                this.emailId = (UUID) Utils.objectFromXml(parser);
                            }
                        }

                        parser.next();
                    } while (!parser.getName().equals("KeyValuePairOfstringanyType"));

                }
                else {
                    Utils.skip(parser);
                }

                parser.next();
            } while (parser.getEventType() != XmlPullParser.END_TAG || !parser.getName().equals(name));
        }
        catch(Exception ex) {
            ex.printStackTrace();
        }
    }
}


text:
package im.actor.model.viewmodel;

import com.google.j2objc.annotations.ObjectiveCName;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import im.actor.model.annotation.MainThread;
import im.actor.model.concurrency.AbsTimerCompat;
import im.actor.model.droidkit.actors.Environment;
import im.actor.model.entity.ContactRecord;
import im.actor.model.entity.ContactRecordType;
import im.actor.model.entity.Sex;
import im.actor.model.entity.User;
import im.actor.model.modules.Modules;
import im.actor.model.mvvm.BaseValueModel;
import im.actor.model.mvvm.MVVMEngine;
import im.actor.model.mvvm.ModelChangedListener;
import im.actor.model.mvvm.generics.ArrayListUserPhone;
import im.actor.model.mvvm.generics.AvatarValueModel;
import im.actor.model.mvvm.generics.BooleanValueModel;
import im.actor.model.mvvm.generics.StringValueModel;
import im.actor.model.mvvm.generics.UserPhoneValueModel;
import im.actor.model.mvvm.generics.UserPresenceValueModel;

/**
 * User View Model
 */
public class UserVM extends BaseValueModel<User> {

    private static final long PRESENCE_UPDATE_DELAY = 60 * 1000L;

    private int id;
    private boolean isBot;
    @NotNull
    private StringValueModel name;
    @NotNull
    private AvatarValueModel avatar;
    @NotNull
    private Sex sex;
    @NotNull
    private BooleanValueModel isContact;
    @NotNull
    private UserPresenceValueModel presence;
    private AbsTimerCompat presenceTimer;

    @NotNull
    private UserPhoneValueModel phones;

    @NotNull
    private ArrayList<ModelChangedListener<UserVM>> listeners = new ArrayList<ModelChangedListener<UserVM>>();

    /**
     *
INTERNAL API

     * Create User View Model
     *
     * @param user    Initial User value
     * @param modules im.actor.android.modules reference
     */
    public UserVM(@NotNull User user, @NotNull Modules modules) {
        super(user);

        id = user.getUid();
        sex = user.getSex();
        isBot = user.isBot();
        name = new StringValueModel("user." + id + ".name", user.getName());
        avatar = new AvatarValueModel("user." + id + ".avatar", user.getAvatar());
        isContact = new BooleanValueModel("user." + id + ".contact", modules.getContactsModule().isUserContact(id));
        presence = new UserPresenceValueModel("user." + id + ".presence", new UserPresence(UserPresence.State.UNKNOWN));
        phones = new UserPhoneValueModel("user." + id + ".phones", buildPhones(user.getRecords()));

        // Notify about presence change every minute as text representation can change
        presenceTimer = Environment.createTimer(new Runnable() {
            @Override
            public void run() {
                presence.forceNotify();
                presenceTimer.schedule(PRESENCE_UPDATE_DELAY);
            }
        });
        presenceTimer.schedule(PRESENCE_UPDATE_DELAY);
    }

    @Override
    protected void updateValues(@NotNull User rawObj) {
        boolean isChanged = name.change(rawObj.getName());
        isChanged |= avatar.change(rawObj.getAvatar());
        isChanged |= phones.change(buildPhones(rawObj.getRecords()));

        if (isChanged) {
            notifyChange();
        }
    }

    /**
     * Get User Id
     *
     * @return user Id
     */
    @ObjectiveCName("getId")
    public int getId() {
        return id;
    }

    /**
     * Is User actually bot
     *
     * @return is User bot
     */
    @ObjectiveCName("isBot")
    public boolean isBot() {
        return isBot;
    }

    /**
     * Get User Name Value Model
     *
     * @return ValueModel of String
     */
    @NotNull
    @ObjectiveCName("getNameModel")
    public StringValueModel getName() {
        return name;
    }

    /**
     * Get User Avatar Value Model
     *
     * @return ValueModel of Avatar
     */
    @NotNull
    @ObjectiveCName("getAvatarModel")
    public AvatarValueModel getAvatar() {
        return avatar;
    }

    /**
     * Get User Sex
     *
     * @return User Sex
     */
    @NotNull
    @ObjectiveCName("getSex")
    public Sex getSex() {
        return sex;
    }

    /**
     * Get ValueModel of flag if user is in contact list
     *
     * @return ValueModel of Boolean
     */
    @NotNull
    @ObjectiveCName("isContactModel")
    public BooleanValueModel isContact() {
        return isContact;
    }

    /**
     * Get ValueModel of User Presence
     *
     * @return ValueModel of UserPresence
     */
    @NotNull
    @ObjectiveCName("getPresenceModel")
    public UserPresenceValueModel getPresence() {
        return presence;
    }

    /**
     * Get Users Phone numbers
     *
     * @return ValueModel of ArrayList of UserPhone
     */
    @NotNull
    @ObjectiveCName("getPhonesModel")
    public UserPhoneValueModel getPhones() {
        return phones;
    }

    @NotNull
    private ArrayListUserPhone buildPhones(@NotNull List<ContactRecord> records) {
        ArrayListUserPhone res = new ArrayListUserPhone();
        for (ContactRecord r : records) {
            if (r.getRecordType() == ContactRecordType.PHONE) {
                res.add(new UserPhone(Long.parseLong(r.getRecordData()), r.getRecordTitle()));
            }
        }
        return res;
    }

    /**
     * Subscribe to UserVM updates
     *
     * @param listener UserVM changed listener
     */
    @MainThread
    @ObjectiveCName("subscribeWithListener:")
    public void subscribe(@NotNull ModelChangedListener<UserVM> listener) {
        MVVMEngine.checkMainThread();
        if (listeners.contains(listener)) {
            return;
        }
        listeners.add(listener);
        listener.onChanged(this);
    }

    /**
     * Unsubscribe from UserVM
     *
     * @param listener UserVM changed listener
     */
    @MainThread
    @ObjectiveCName("unsubscribeWithListener:")
    public void unsubscribe(@NotNull ModelChangedListener<UserVM> listener) {
        MVVMEngine.checkMainThread();
        listeners.remove(listener);
    }

    private void notifyChange() {
        MVVMEngine.getMainThreadProvider().postToMainThread(new Runnable() {
            @Override
            public void run() {
                for (ModelChangedListener<UserVM> l : listeners.toArray(new ModelChangedListener[listeners.size()])) {
                    l.onChanged(UserVM.this);
                }
            }
        });
    }
}


text:
#include "catch2/catch.hpp"

#include <modules/globebrowsing/src/basictypes.h>
#include <modules/globebrowsing/src/geodeticpatch.h>
#include <ghoul/glm.h>

TEST_CASE("LatLonPatch: findCenterControlPoint", "[latlonpatch]") {
    using namespace openspace::globebrowsing;

    GeodeticPatch patch(0, 0, glm::pi<float>() / 4.f, glm::pi<float>() / 4.f);
}

TEST_CASE("LatLonPatch: Find Closest Corner", "[latlonpatch]") {
    using namespace openspace::globebrowsing;

    constexpr float piOver4 = glm::pi<float>() / 4.f;
    Geodetic2 halfSize { piOver4, piOver4 };
    Geodetic2 center { 0, 0 };
    GeodeticPatch patch(center, halfSize);

    constexpr float piOver3 = glm::pi<float>() / 3.f;
    Geodetic2 point { piOver3, piOver3 };

    Geodetic2 closestCorner = patch.closestCorner(point);
    Geodetic2 northEastCorner = patch.corner(NORTH_EAST);

    CHECK(closestCorner.lat == northEastCorner.lat);
    CHECK(closestCorner.lon == northEastCorner.lon);
}

TEST_CASE("LatLonPatch: Find Closest Corner 2", "[latlonpatch]") {
    using namespace openspace::globebrowsing;

    constexpr float piOver6 = glm::pi<float>() / 4.f;

    Geodetic2 halfSize { 1.1 * piOver6, 1.1 * piOver6 };
    Geodetic2 center { piOver6, piOver6 };
    GeodeticPatch patch(center, halfSize);

    Geodetic2 point { 0, 0 };

    Geodetic2 closestCorner = patch.closestCorner(point);
    Geodetic2 expectedCorner = patch.corner(SOUTH_WEST);

    CHECK(closestCorner.lat == expectedCorner.lat);
    CHECK(closestCorner.lon == expectedCorner.lon);
}


text:
require 'tenantify'
require 'tenantify/sidekiq/middlewares/client'

RSpec.describe Tenantify::Sidekiq::Middlewares::Client do

  subject { described_class.new }

  describe '#call' do
    let(:worker_class) { double 'worker_class' }
    let(:queue)        { double 'queue' }
    let(:redis_pool)   { double 'redis_pool' }

    let(:job) { { "fake" => "value" } }

    let(:tenant_name) { "a_tenant" }

    it 'adds a tenant key to the job hash' do
      block_called = false

      Tenantify::Perform.with tenant_name do
        subject.call(worker_class, job, queue, redis_pool) do
          block_called = true
        end
      end

      expect(job["tenant"]).to eq tenant_name
      expect(block_called).to eq true
    end
  end

end


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SymbolsKeyBehaviour : MonoBehaviour
{
	public ShiftKeyBehaviour ShiftBehaviour;

	private Key symbolKeyController;
	private GameObject[] keys;
	private Key[] keyControllers;
	private bool symbolToggle = true;

	void Start()
	{
		Key.keyPressed += SpecialKeyPressed;

		symbolKeyController = this.gameObject.GetComponent<Key> ();
		keys = GameObject.FindGameObjectsWithTag ("Key");
		keyControllers = new Key[keys.Length];
		for (int i = 0; i < keys.Length; i++)
		{
			keyControllers [i] = keys [i].GetComponent<Key> ();
		}
	}

	void SpecialKeyPressed()
	{
		if (symbolKeyController.KeyPressed)
		{
			for (int i = 0; i < keyControllers.Length; i++)
			{
				keyControllers [i].SwitchToSymbols ();
			}
			if (symbolToggle)
			{
				ShiftBehaviour.ShiftVisibilityToggle (false);
				symbolKeyController.KeycapColor = symbolKeyController.PressedKeycapColor;
				symbolToggle = false;
			}
			else if (!symbolToggle)
			{
				ShiftBehaviour.ShiftVisibilityToggle (true);
				symbolKeyController.KeycapColor = symbolKeyController.InitialKeycapColor;
				symbolToggle = true;
			}
		}
	}

	void OnDisable()
	{
		Key.keyPressed -= SpecialKeyPressed;
	}
}


text:
<?php

namespace HiPay\FullserviceMagento\Block\Adminhtml\Cartcategories\Edit;

use HiPay\Fullservice\Data\Category\Collection as collection;

/**
 * Adminhtml Cart Categories edit form block
 *
 * @author    Aymeric Berthelot <aberthelot@hipay.com>
 * @copyright Copyright (c) 2017 - HiPay
 * @license   http://www.apache.org/licenses/LICENSE-2.0 Apache 2.0 Licence
 * @link      https://github.com/hipay/hipay-fullservice-sdk-magento2
 */
class Form extends \Magento\Backend\Block\Widget\Form\Generic
{
    /**
     * @var \HiPay\FullserviceMagento\Model\System\Config\Source\CategoriesMagento
     */
    protected $categoriesMagento;

    /**
     * @var \HiPay\FullserviceMagento\Model\System\Config\Source\CategoriesHipay
     */
    protected $categoriesHipay;

    /**
     * Form constructor.
     *
     * @param \Magento\Backend\Block\Template\Context                                $context
     * @param \Magento\Framework\Registry                                            $registry
     * @param \Magento\Framework\Data\FormFactory                                    $formFactory
     * @param \HiPay\FullserviceMagento\Model\System\Config\Source\CategoriesMagento $categoriesMagento
     * @param \HiPay\FullserviceMagento\Model\System\Config\Source\CategoriesHipay   $categoriesHipay
     * @param array                                                                  $data
     */
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\Data\FormFactory $formFactory,
        \HiPay\FullserviceMagento\Model\System\Config\Source\CategoriesMagento $categoriesMagento,
        \HiPay\FullserviceMagento\Model\System\Config\Source\CategoriesHipay $categoriesHipay,
        array $data = []
    ) {
        parent::__construct($context, $registry, $formFactory, $data);
        $this->categoriesMagento = $categoriesMagento;
        $this->categoriesHipay = $categoriesHipay;
    }

    /**
     * Prepare form
     *
     * @return $this
     */
    protected function _prepareForm()
    {
        /**
 * @var \Magento\Framework\Data\Form $form
*/
        $form = $this->_formFactory->create(
            ['data' => ['id' => 'edit_form', 'action' => $this->getData('action'), 'method' => 'post']]
        );
        $form->setHtmlIdPrefix('cart_categories_');
        $model = $this->_coreRegistry->registry('cart_categories');

        $fieldset = $form->addFieldset(
            'cart_categories_fieldset',
            ['legend' => __('Mapping Categories'), 'class' => 'fieldset-wide']
        );

        $options = $this->categoriesMagento->toOptionArray();
        $fieldset->addField(
            'category_magento_id',
            'select',
            [
                'name' => 'category_magento_id',
                'label' => __('Category Magento'),
                'title' => __('Category Magento'),
                'values' => $options,
                'required' => true
            ]
        );

        $options = $this->categoriesHipay->toOptionArray();
        $fieldset->addField(
            'category_hipay_id',
            'select',
            [
                'name' => 'category_hipay_id',
                'label' => __('Category Hipay'),
                'title' => __('Category Hipay'),
                'values' => $options,
                'required' => true
            ]
        );

        $this->_eventManager->dispatch('adminhtml_cart_categories_edit_prepare_form', ['form' => $form]);

        if ($model->getMappingId() !== null) {
            $form->addField('mapping_id', 'hidden', ['name' => 'mapping_id', 'value' => $model->getMappingId()]);
        }

        $form->setValues($model->getData());
        $form->setUseContainer(true);
        $this->setForm($form);

        return parent::_prepareForm();
    }
}


text:
namespace net {

class NET_EXPORT_PRIVATE HybridSlowStart {
 public:
  explicit HybridSlowStart(const QuicClock* clock);

  void OnPacketAcked(QuicPacketSequenceNumber acked_sequence_number,
                     bool in_slow_start);

  void OnPacketSent(QuicPacketSequenceNumber sequence_number);

  // ShouldExitSlowStart should be called on every new ack frame, since a new
  // RTT measurement can be made then.
  // rtt: the RTT for this ack packet.
  // min_rtt: is the lowest delay (RTT) we have seen during the session.
  // congestion_window: the congestion window in packets.
  bool ShouldExitSlowStart(QuicTime::Delta rtt,
                           QuicTime::Delta min_rtt,
                           int64 congestion_window);

  // Start a new slow start phase.
  void Restart();

  // TODO(ianswett): The following methods should be private, but that requires
  // a follow up CL to update the unit test.
  // Returns true if this ack the last sequence number of our current slow start
  // round.
  // Call Reset if this returns true.
  bool IsEndOfRound(QuicPacketSequenceNumber ack) const;

  // Call for the start of each receive round (burst) in the slow start phase.
  void StartReceiveRound(QuicPacketSequenceNumber last_sent);

  void set_ack_train_detection(bool ack_train_detection) {
    ack_train_detection_ = ack_train_detection;
  }

  bool ack_train_detection() const {
    return ack_train_detection_;
  }

  // Whether slow start has started.
  bool started() const {
    return started_;
  }

 private:
  // Whether a condition for exiting slow start has been found.
  enum HystartState {
    NOT_FOUND,
    ACK_TRAIN,  // A closely spaced ack train is too long.
    DELAY,  // Too much increase in the round's min_rtt was observed.
  };

  const QuicClock* clock_;
  bool ack_train_detection_;
  // Whether the hybrid slow start has been started.
  bool started_;
  HystartState hystart_found_;
  // Last sequence number sent which was CWND limited.
  QuicPacketSequenceNumber last_sent_sequence_number_;

  // Variables for tracking acks received during a slow start round.
  QuicTime round_start_;  // Beginning of each slow start receive round.
  QuicPacketSequenceNumber end_sequence_number_;  // End of the receive round.
  // Last time when the spacing between ack arrivals was less than 2 ms.
  // Defaults to the beginning of the round.
  QuicTime last_close_ack_pair_time_;
  uint32 rtt_sample_count_;  // Number of rtt samples in the current round.
  QuicTime::Delta current_min_rtt_;  // The minimum rtt of current round.

  DISALLOW_COPY_AND_ASSIGN(HybridSlowStart);
};

}  // namespace net

#endif  // NET_QUIC_CONGESTION_CONTROL_HYBRID_SLOW_START_H_


text:
(function() {
    "use strict";

    /**
     * Module: ddd
     * Controller:
     * Description:
     *
     */
    angular.module('ddd').controller('DddController', DddController);

    function DddController() {

    }

})();


text:
package rcli

import (
	"fmt"
	"net/http"
	"net/url"
	"path"
)

// Use this key to encode an RPC call into an URL,
// eg. domain.tld/path/to/method?q=get_user&q=gordon
const ARG_URL_KEY = "q"

func URLToCall(u *url.URL) (method string, args []string) {
	return path.Base(u.Path), u.Query()[ARG_URL_KEY]
}

func ListenAndServeHTTP(addr string, service Service) error {
	return http.ListenAndServe(addr, http.HandlerFunc(
		func(w http.ResponseWriter, r *http.Request) {
			cmd, args := URLToCall(r.URL)
			if err := call(service, r.Body, &AutoFlush{w}, append([]string{cmd}, args...)...); err != nil {
				fmt.Fprintf(w, "Error: "+err.Error()+"\n")
			}
		}))
}

type AutoFlush struct {
	http.ResponseWriter
}

func (w *AutoFlush) Write(data []byte) (int, error) {
	ret, err := w.ResponseWriter.Write(data)
	if flusher, ok := w.ResponseWriter.(http.Flusher); ok {
		flusher.Flush()
	}
	return ret, err
}


text:
namespace chromeos {
namespace {

// An example of configuration file with print servers.
constexpr char kPrintServersPolicyJson1[] = R"json(
[
  {
    "id": "id1",
    "display_name": "MyPrintServer",
    "url": "ipp://192.168.1.5"
  }, {
    "id": "id2",
    "display_name": "Server API",
    "url":"ipps://print-server.intra.example.com:444/ipp/cl2k4"
  }, {
    "id": "id3",
    "display_name": "YaLP",
    "url": "http://192.168.1.8/bleble/print"
  }
])json";

// An example whitelist.
const std::vector<std::string> kPrintServersPolicyWhitelist1 = {"id3", "idX",
                                                                "id1"};
// A different configuration file with print servers.
constexpr char kPrintServersPolicyJson2[] = R"json(
[
  {
    "id": "id1",
    "display_name": "CUPS",
    "url": "ipp://192.168.1.15"
  }
])json";

// Another configuration file with print servers, this time with invalid URLs.
constexpr char kPrintServersPolicyJson3[] = R"json(
[
  {
    "id": "1",
    "display_name": "server_1",
    "url": "ipp://aaa.bbb.ccc:666/xx"
  }, {
    "id": "2",
    "display_name": "server_2",
    "url":"ipps:/print.server.intra.example.com:443z/ipp"
  }, {
    "id": "3",
    "display_name": "server_3",
    "url": "file://192.168.1.8/bleble/print"
  }, {
    "id": "4",
    "display_name": "server_4",
    "url": "http://aaa.bbb.ccc:666/xx"
  }, {
    "id": "5",
    "display_name": "server_5",
    "url": "\n \t ipps://aaa.bbb.ccc:666/yy"
  }, {
    "id": "6",
    "display_name": "server_6",
    "url":"ipps:/print.server^.intra.example.com/ipp"
  }, {
    "id": "3",
    "display_name": "server_7",
    "url": "file://194.169.2.18/bleble2/print"
  }, {
    "display_name": "server_8",
    "url": "file://195.161.3.28/bleble/print"
  }
])json";

PrintServer Server1() {
  return PrintServer("id1", GURL("http://192.168.1.5:631"), "MyPrintServer");
}

PrintServer Server2() {
  return PrintServer(
      "id2", GURL("https://print-server.intra.example.com:444/ipp/cl2k4"),
      "Server API");
}

PrintServer Server3() {
  return PrintServer("id3", GURL("http://192.168.1.8/bleble/print"), "YaLP");
}

// Corresponding vector with PrintServers.
std::vector<PrintServer> PrintServersPolicyData1() {
  return std::vector<PrintServer>({Server1(), Server2(), Server3()});
}

// Corresponding vector filtered with the whitelist defined above.
std::vector<PrintServer> PrintServersPolicyData1Whitelist1() {
  return std::vector<PrintServer>({Server1(), Server3()});
}

// Corresponding vector with PrintServers.
std::vector<PrintServer> PrintServersPolicyData2() {
  return std::vector<PrintServer>(
      {{"id1", GURL("http://192.168.1.15:631"), "CUPS"}});
}

// Corresponding vector with PrintServers. Only two records are included,
// because other ones are invalid:
// server_1 - OK
// server_2 - invalid URL - invalid port number
// server_3 - unsupported scheme
// server_4 - duplicate of server_1
// server_5 - leading whitespaces, but OK
// server_6 - invalid URL - forbidden character
// server_7 - duplicate id
// server_8 - missing id
std::vector<PrintServer> PrintServersPolicyData3() {
  return std::vector<PrintServer>(
      {{"1", GURL("http://aaa.bbb.ccc:666/xx"), "server_1"},
       {"5", GURL("https://aaa.bbb.ccc:666/yy"), "server_5"}});
}

// Observer that stores all its calls.
class TestObserver : public PrintServersProvider::Observer {
 public:
  struct ObserverCall {
    bool complete;
    std::vector<PrintServer> servers;
    ObserverCall(bool complete, const std::vector<PrintServer>& servers)
        : complete(complete), servers(servers) {}
  };

  ~TestObserver() override = default;

  // Callback from PrintServersProvider::Observer.
  void OnServersChanged(bool complete,
                        const std::vector<PrintServer>& servers) override {
    calls_.emplace_back(complete, servers);
  }

  // Returns history of all calls to OnServersChanged(...).
  const std::vector<ObserverCall>& GetCalls() const { return calls_; }

 private:
  // history of all callbacks
  std::vector<ObserverCall> calls_;
};

class PrintServersProviderTest : public testing::Test {
 public:
  PrintServersProviderTest()
      : external_servers_(PrintServersProvider::Create()) {}

 protected:
  // Everything must be called on Chrome_UIThread.
  content::BrowserTaskEnvironment task_environment_;
  // User profile.
  TestingProfile profile_;
  // Tested object.
  std::unique_ptr<PrintServersProvider> external_servers_;
};

// Verify that the object can be destroyed while parsing is in progress.
TEST_F(PrintServersProviderTest, DestructionIsSafe) {
  {
    std::unique_ptr<PrintServersProvider> servers =
        PrintServersProvider::Create();
    servers->SetData(std::make_unique<std::string>(kPrintServersPolicyJson1));
    // Data is valid.  Computation is proceeding.
  }
  // servers is out of scope.  Destructor has run.  Pump the message queue to
  // see if anything strange happens.
  task_environment_.RunUntilIdle();
}

// Verify that we're initially unset and empty.
// After initialization "complete" flags = false.
TEST_F(PrintServersProviderTest, InitialConditions) {
  TestObserver obs;
  external_servers_->SetProfile(&profile_);
  external_servers_->AddObserver(&obs);
  ASSERT_EQ(obs.GetCalls().size(), 1u);
  EXPECT_EQ(obs.GetCalls().back().complete, false);
  EXPECT_TRUE(obs.GetCalls().back().servers.empty());
  external_servers_->RemoveObserver(&obs);
}

// Verify two ClearData() calls.
// ClearData() sets empty list and "complete" flag = true.
TEST_F(PrintServersProviderTest, ClearData2) {
  TestObserver obs;
  external_servers_->SetProfile(&profile_);
  external_servers_->AddObserver(&obs);
  external_servers_->ClearData();
  ASSERT_EQ(obs.GetCalls().size(), 2u);
  EXPECT_EQ(obs.GetCalls().back().complete, true);
  EXPECT_TRUE(obs.GetCalls().back().servers.empty());
  external_servers_->ClearData();
  // no changes, because observed object's state is the same
  ASSERT_EQ(obs.GetCalls().size(), 2u);
  external_servers_->RemoveObserver(&obs);
}

// Verifies SetData().
// SetData(...) sets "complete" flag = false, then parse given data in the
// background and sets resultant list with "complete" flag = true.
TEST_F(PrintServersProviderTest, SetData) {
  auto blob1 = std::make_unique<std::string>(kPrintServersPolicyJson1);
  TestObserver obs;
  external_servers_->SetProfile(&profile_);
  external_servers_->AddObserver(&obs);
  external_servers_->SetData(std::move(blob1));
  // single call from AddObserver, since SetData(...) is not processed yet
  ASSERT_EQ(obs.GetCalls().size(), 1u);
  // make sure that SetData(...) is processed
  task_environment_.RunUntilIdle();
  // now the call from SetData(...) is there also
  ASSERT_EQ(obs.GetCalls().size(), 2u);
  EXPECT_EQ(obs.GetCalls().back().complete, true);
  EXPECT_EQ(obs.GetCalls().back().servers, PrintServersPolicyData1());
  external_servers_->RemoveObserver(&obs);
}

// Verify two SetData() calls.
TEST_F(PrintServersProviderTest, SetData2) {
  auto blob1 = std::make_unique<std::string>(kPrintServersPolicyJson1);
  auto blob2 = std::make_unique<std::string>(kPrintServersPolicyJson2);
  TestObserver obs;
  external_servers_->SetProfile(&profile_);
  external_servers_->AddObserver(&obs);
  external_servers_->SetData(std::move(blob1));
  // single call from AddObserver, since SetData(...) is not processed yet
  ASSERT_EQ(obs.GetCalls().size(), 1u);
  external_servers_->SetData(std::move(blob2));
  // no changes, because nothing was processed yet
  ASSERT_EQ(obs.GetCalls().size(), 1u);
  task_environment_.RunUntilIdle();
  // both calls from SetData(...) should be reported
  ASSERT_EQ(obs.GetCalls().size(), 3u);
  EXPECT_EQ(obs.GetCalls()[1].complete, false);
  EXPECT_EQ(obs.GetCalls()[1].servers, PrintServersPolicyData1());
  EXPECT_EQ(obs.GetCalls()[2].complete, true);
  EXPECT_EQ(obs.GetCalls()[2].servers, PrintServersPolicyData2());
  external_servers_->RemoveObserver(&obs);
}

// Verifies SetData() + ClearData() before SetData() completes.
TEST_F(PrintServersProviderTest, SetDataClearData) {
  auto blob1 = std::make_unique<std::string>(kPrintServersPolicyJson1);
  TestObserver obs;
  external_servers_->SetProfile(&profile_);
  external_servers_->AddObserver(&obs);
  external_servers_->SetData(std::move(blob1));
  // single call from AddObserver, since SetData(...) is not processed yet
  ASSERT_EQ(obs.GetCalls().size(), 1u);
  external_servers_->ClearData();
  // a call from ClearData() was added, SetData(...) is not processed yet
  ASSERT_EQ(obs.GetCalls().size(), 2u);
  EXPECT_EQ(obs.GetCalls().back().complete, true);
  EXPECT_TRUE(obs.GetCalls().back().servers.empty());
  // process SetData(...)
  task_environment_.RunUntilIdle();
  // no changes, effects of SetData(...) were already replaced by ClearData()
  ASSERT_EQ(obs.GetCalls().size(), 2u);
  external_servers_->RemoveObserver(&obs);
}

// Verifies ClearData() before AddObserver() + SetData() after.
TEST_F(PrintServersProviderTest, ClearDataSetData) {
  auto blob1 = std::make_unique<std::string>(kPrintServersPolicyJson1);
  TestObserver obs;
  external_servers_->SetProfile(&profile_);
  external_servers_->ClearData();
  external_servers_->AddObserver(&obs);
  // single call from AddObserver, but with effects of ClearData()
  ASSERT_EQ(obs.GetCalls().size(), 1u);
  EXPECT_EQ(obs.GetCalls().back().complete, true);
  EXPECT_TRUE(obs.GetCalls().back().servers.empty());
  external_servers_->SetData(std::move(blob1));
  // SetData(...) is not completed, but generates a call switching "complete"
  // flag to false
  ASSERT_EQ(obs.GetCalls().size(), 2u);
  EXPECT_EQ(obs.GetCalls().back().complete, false);
  EXPECT_TRUE(obs.GetCalls().back().servers.empty());
  // process SetData(...)
  task_environment_.RunUntilIdle();
  // next call with results from processed SetData(...)
  ASSERT_EQ(obs.GetCalls().size(), 3u);
  EXPECT_EQ(obs.GetCalls().back().complete, true);
  EXPECT_EQ(obs.GetCalls().back().servers, PrintServersPolicyData1());
  external_servers_->RemoveObserver(&obs);
}

// Verify that invalid URLs are filtered out.
TEST_F(PrintServersProviderTest, InvalidURLs) {
  auto blob3 = std::make_unique<std::string>(kPrintServersPolicyJson3);
  TestObserver obs;
  external_servers_->SetProfile(&profile_);
  external_servers_->AddObserver(&obs);
  external_servers_->SetData(std::move(blob3));
  task_environment_.RunUntilIdle();
  ASSERT_EQ(obs.GetCalls().size(), 2u);
  EXPECT_EQ(obs.GetCalls().back().complete, true);
  EXPECT_EQ(obs.GetCalls().back().servers, PrintServersPolicyData3());
  external_servers_->RemoveObserver(&obs);
}

// Verify that whitelist works as expected.
TEST_F(PrintServersProviderTest, Whitelist) {
  // The sequence from SetData test.
  auto blob1 = std::make_unique<std::string>(kPrintServersPolicyJson1);
  TestObserver obs;
  external_servers_->SetProfile(&profile_);
  external_servers_->AddObserver(&obs);
  external_servers_->SetData(std::move(blob1));
  // Apply an empty whitelist on the top.
  auto* prefs = profile_.GetTestingPrefService();
  auto value = std::make_unique<base::ListValue>();
  prefs->SetManagedPref(prefs::kExternalPrintServersWhitelist,
                        std::move(value));
  // Check the resultant list - is is supposed to be empty.
  task_environment_.RunUntilIdle();
  ASSERT_FALSE(obs.GetCalls().empty());
  EXPECT_TRUE(obs.GetCalls().back().complete);
  EXPECT_TRUE(obs.GetCalls().back().servers.empty());
  // Apply whitelist1.
  value = std::make_unique<base::ListValue>();
  for (const std::string& id : kPrintServersPolicyWhitelist1)
    value->Append(base::Value(id));
  prefs->SetManagedPref(prefs::kExternalPrintServersWhitelist,
                        std::move(value));
  // Check the resultant list.
  task_environment_.RunUntilIdle();
  EXPECT_TRUE(obs.GetCalls().back().complete);
  EXPECT_EQ(obs.GetCalls().back().servers, PrintServersPolicyData1Whitelist1());
  // The end.
  external_servers_->RemoveObserver(&obs);
}

}  // namespace
}  // namespace chromeos


text:
package io.cucumber.junit.platform.engine;

import io.cucumber.core.plugin.Options;
import io.cucumber.core.snippets.SnippetType;
import org.junit.jupiter.api.Test;
import org.junit.platform.engine.ConfigurationParameters;
import org.junit.platform.engine.support.hierarchical.Node;

import java.net.URI;

import static java.util.stream.Collectors.toList;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsEmptyCollection.empty;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.hamcrest.core.IsIterableContaining.hasItem;
import static org.hamcrest.core.IsIterableContaining.hasItems;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

class CucumberEngineOptionsTest {

    @Test
    void getPluginNames() {
        ConfigurationParameters config = new MapConfigurationParameters(
            Constants.PLUGIN_PROPERTY_NAME,
            "html:path/to/report.html");

        assertThat(new CucumberEngineOptions(config).plugins().stream()
                .map(Options.Plugin::pluginString)
                .collect(toList()),
            hasItem("html:path/to/report.html"));

        CucumberEngineOptions htmlAndJson = new CucumberEngineOptions(
            new MapConfigurationParameters(Constants.PLUGIN_PROPERTY_NAME,
                "html:path/with spaces/to/report.html, message:path/with spaces/to/report.ndjson"));

        assertThat(htmlAndJson.plugins().stream()
                .map(Options.Plugin::pluginString)
                .collect(toList()),
            hasItems("html:path/with spaces/to/report.html", "message:path/with spaces/to/report.ndjson"));
    }

    @Test
    void getPluginNamesWithPublishToken() {
        ConfigurationParameters config = new MapConfigurationParameters(
            Constants.PLUGIN_PUBLISH_TOKEN_PROPERTY_NAME, "some/token");

        assertThat(new CucumberEngineOptions(config).plugins().stream()
                .map(Options.Plugin::pluginString)
                .collect(toList()),
            hasItem("io.cucumber.core.plugin.PublishFormatter:some/token"));
    }

    @Test
    void getPluginNamesWithNothingEnabled() {
        ConfigurationParameters config = new EmptyConfigurationParameters();

        assertThat(new CucumberEngineOptions(config).plugins().stream()
                .map(Options.Plugin::pluginString)
                .collect(toList()),
            hasItem("io.cucumber.core.plugin.NoPublishFormatter"));
    }

    @Test
    void getPluginNamesWithPublishQuiteEnabled() {
        ConfigurationParameters config = new MapConfigurationParameters(
            Constants.PLUGIN_PUBLISH_QUIET_PROPERTY_NAME, "true");

        assertThat(new CucumberEngineOptions(config).plugins().stream()
                .map(Options.Plugin::pluginString)
                .collect(toList()),
            empty());
    }

    @Test
    void getPluginNamesWithPublishEnabled() {
        ConfigurationParameters config = new MapConfigurationParameters(
            Constants.PLUGIN_PUBLISH_ENABLED_PROPERTY_NAME, "true");

        assertThat(new CucumberEngineOptions(config).plugins().stream()
                .map(Options.Plugin::pluginString)
                .collect(toList()),
            hasItem("io.cucumber.core.plugin.PublishFormatter"));
    }

    @Test
    void isMonochrome() {
        MapConfigurationParameters ansiColors = new MapConfigurationParameters(
            Constants.ANSI_COLORS_DISABLED_PROPERTY_NAME,
            "true");
        assertTrue(new CucumberEngineOptions(ansiColors).isMonochrome());

        MapConfigurationParameters noAnsiColors = new MapConfigurationParameters(
            Constants.ANSI_COLORS_DISABLED_PROPERTY_NAME,
            "false");
        assertFalse(new CucumberEngineOptions(noAnsiColors).isMonochrome());
    }

    @Test
    void getGlue() {
        ConfigurationParameters config = new MapConfigurationParameters(
            Constants.GLUE_PROPERTY_NAME,
            "com.example.app, com.example.glue");

        assertThat(new CucumberEngineOptions(config).getGlue(),
            contains(
                URI.create("classpath:/com/example/app"),
                URI.create("classpath:/com/example/glue")));
    }

    @Test
    void isDryRun() {
        ConfigurationParameters dryRun = new MapConfigurationParameters(
            Constants.EXECUTION_DRY_RUN_PROPERTY_NAME,
            "true");
        assertTrue(new CucumberEngineOptions(dryRun).isDryRun());

        ConfigurationParameters noDryRun = new MapConfigurationParameters(
            Constants.EXECUTION_DRY_RUN_PROPERTY_NAME,
            "false");
        assertFalse(new CucumberEngineOptions(noDryRun).isDryRun());
    }

    @Test
    void getSnippetType() {
        ConfigurationParameters underscore = new MapConfigurationParameters(
            Constants.SNIPPET_TYPE_PROPERTY_NAME,
            "underscore");

        assertThat(new CucumberEngineOptions(underscore).getSnippetType(), is(SnippetType.UNDERSCORE));

        ConfigurationParameters camelcase = new MapConfigurationParameters(
            Constants.SNIPPET_TYPE_PROPERTY_NAME,
            "camelcase");
        assertThat(new CucumberEngineOptions(camelcase).getSnippetType(), is(SnippetType.CAMELCASE));
    }

    @Test
    void isParallelExecutionEnabled() {
        ConfigurationParameters enabled = new MapConfigurationParameters(
            Constants.PARALLEL_EXECUTION_ENABLED_PROPERTY_NAME,
            "true");
        assertTrue(new CucumberEngineOptions(enabled).isParallelExecutionEnabled());

        ConfigurationParameters disabled = new MapConfigurationParameters(
            Constants.PARALLEL_EXECUTION_ENABLED_PROPERTY_NAME,
            "false");
        assertFalse(new CucumberEngineOptions(disabled).isParallelExecutionEnabled());
        ConfigurationParameters absent = new MapConfigurationParameters(
            "some key", "some value");
        assertFalse(new CucumberEngineOptions(absent).isParallelExecutionEnabled());

    }

}


text:
class BuildSettings;
class Settings;
class Target;

// Generates the toplevel "build.ninja" file. This references the individual
// toolchain files and lists all input .gn files as dependencies of the
// build itself.
class NinjaBuildWriter {
 public:
  static bool RunAndWriteFile(
      const BuildSettings* settings,
      const std::vector<const Settings*>& all_settings,
      const std::vector<const Target*>& default_toolchain_targets);

 private:
  NinjaBuildWriter(const BuildSettings* settings,
                   const std::vector<const Settings*>& all_settings,
                   const std::vector<const Target*>& default_toolchain_targets,
                   std::ostream& out,
                   std::ostream& dep_out);
  ~NinjaBuildWriter();

  void Run();

  void WriteNinjaRules();
  void WriteSubninjas();
  void WritePhonyAndAllRules();

  void WritePhonyRule(const Target* target, const OutputFile& target_file,
                      const std::string& phony_name);

  const BuildSettings* build_settings_;
  std::vector<const Settings*> all_settings_;
  std::vector<const Target*> default_toolchain_targets_;
  std::ostream& out_;
  std::ostream& dep_out_;
  PathOutput path_output_;

  NinjaHelper helper_;

  DISALLOW_COPY_AND_ASSIGN(NinjaBuildWriter);
};

#endif  // TOOLS_GN_NINJA_BUILD_GENERATOR_H_


text:
MongoDB\BSON\Javascript unserialization requires "code" string field (Serializable interface)
--FILE--
<?php

require_once __DIR__ . '/../utils/basic.inc';

echo throws(function() {
    unserialize('C:23:"MongoDB\BSON\Javascript":21:{a:1:{s:4:"code";i:0;}}');
}, 'MongoDB\Driver\Exception\InvalidArgumentException'), "\n";

?>
===DONE===
<?php exit(0); ?>
--EXPECT--
OK: Got MongoDB\Driver\Exception\InvalidArgumentException
MongoDB\BSON\Javascript initialization requires "code" string field
===DONE===