text:
using System;
using System.Collections;
using System.Collections.Generic;
using Server.Mobiles;
using Server.Items;
using Server.ContextMenus;

namespace Server.Mobiles
{
	[CorpseName( "Un corps de cheval" )]
	public class PackHorse : BaseCreature
	{
		[Constructable]
		public PackHorse() : base( AIType.AI_Animal, FightMode.Aggressor, 10, 1, 0.2, 0.4 )
		{
			Name = "Un cheval de trait";
			Body = 291;
			BaseSoundID = 0xA8;

			SetStr( 44, 120 );
			SetDex( 36, 55 );
			SetInt( 6, 10 );

			SetHits( 61, 80 );
			SetStam( 81, 100 );
			SetMana( 0 );

			SetDamage( 5, 11 );

			SetDamageType( ResistanceType.Physical, 100 );

			SetResistance( ResistanceType.Physical, 20, 25 );
			SetResistance( ResistanceType.Fire, 10, 15 );
			SetResistance( ResistanceType.Cold, 20, 25 );
			SetResistance( ResistanceType.Poison, 10, 15 );
			SetResistance( ResistanceType.Energy, 10, 15 );

			SetSkill( SkillName.MagicResist, 25.1, 30.0 );
			SetSkill( SkillName.Tactics, 29.3, 44.0 );
			SetSkill( SkillName.Wrestling, 29.3, 44.0 );

			Fame = 0;
			Karma = 200;

			VirtualArmor = 16;

			Tamable = true;
			ControlSlots = 1;
			MinTameSkill = 11.1;

			Container pack = Backpack;

			if ( pack != null )
				pack.Delete();

			pack = new StrongBackpack();
			pack.Movable = false;

			AddItem( pack );
		}

		public override int Meat{ get{ return 3; } }
		public override int Hides{ get{ return 10; } }
		public override FoodType FavoriteFood{ get{ return FoodType.FruitsAndVegies | FoodType.GrainsAndHay; } }

		public PackHorse( Serial serial ) : base( serial )
		{
		}

		#region Pack Animal Methods
		public override bool OnBeforeDeath()
		{
			if ( !base.OnBeforeDeath() )
				return false;

			PackAnimal.CombineBackpacks( this );

			return true;
		}

		public override DeathMoveResult GetInventoryMoveResultFor( Item item )
		{
			return DeathMoveResult.MoveToCorpse;
		}

		public override bool IsSnoop( Mobile from )
		{
			if ( PackAnimal.CheckAccess( this, from ) )
				return false;

			return base.IsSnoop( from );
		}

		public override bool OnDragDrop( Mobile from, Item item )
		{
			if ( CheckFeed( from, item ) )
				return true;

			if ( PackAnimal.CheckAccess( this, from ) )
			{
				AddToBackpack( item );
				return true;
			}

			return base.OnDragDrop( from, item );
		}

		public override bool CheckNonlocalDrop( Mobile from, Item item, Item target )
		{
			return PackAnimal.CheckAccess( this, from );
		}

		public override bool CheckNonlocalLift( Mobile from, Item item )
		{
			return PackAnimal.CheckAccess( this, from );
		}

		public override void OnDoubleClick( Mobile from )
		{
			PackAnimal.TryPackOpen( this, from );
		}

		public override void GetContextMenuEntries( Mobile from, List<ContextMenuEntry> list )
		{
			base.GetContextMenuEntries( from, list );

			PackAnimal.GetContextMenuEntries( this, from, list );
		}
		#endregion

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );

			writer.Write( (int) 0 );
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );

			int version = reader.ReadInt();
		}
	}

	public class PackAnimalBackpackEntry : ContextMenuEntry
	{
		private BaseCreature m_Animal;
		private Mobile m_From;

		public PackAnimalBackpackEntry( BaseCreature animal, Mobile from ) : base( 6145, 3 )
		{
			m_Animal = animal;
			m_From = from;

			if ( animal.IsDeadPet )
				Enabled = false;
		}

		public override void OnClick()
		{
			PackAnimal.TryPackOpen( m_Animal, m_From );
		}
	}

	public class PackAnimal
	{
		public static void GetContextMenuEntries( BaseCreature animal, Mobile from, List<ContextMenuEntry> list )
		{
			if ( CheckAccess( animal, from ) )
				list.Add( new PackAnimalBackpackEntry( animal, from ) );
		}

		public static bool CheckAccess( BaseCreature animal, Mobile from )
		{
			if ( from == animal || from.AccessLevel >= AccessLevel.GameMaster )
				return true;

            if (from.Alive && animal.Controlled && !animal.IsDeadPet && (from == animal.ControlMaster || from == animal.SummonMaster || animal.IsPetFriend(from)))
                return true;

			return false;
		}

		public static void CombineBackpacks( BaseCreature animal )
		{
			if ( Core.AOS )
				return;

			if ( animal.IsBonded || animal.IsDeadPet )
				return;

			Container pack = animal.Backpack;

			if ( pack != null )
			{
				Container newPack = new Backpack();

				for ( int i = pack.Items.Count - 1; i >= 0; --i )
				{
					if ( i >= pack.Items.Count )
						continue;

					newPack.DropItem( pack.Items[i] );
				}

				pack.DropItem( newPack );
			}
		}

		public static void TryPackOpen( BaseCreature animal, Mobile from )
		{
			if ( animal.IsDeadPet )
				return;

			Container item = animal.Backpack;

			if ( item != null )
				from.Use( item );
		}
	}
}


text:
module.exports = {
	dir: 'build/',
	out: 'apps/',
	asar: true,
	appCopyright: 'Francisco Knebel',
	electronVersion: '1.8.4',
	// icon: 'icons/appIcon', // .icns for darwin, .ico for win32, .png for linux
	name: 'Space Invader',
	arch: '', // Allowed values: ia32, x64, armv7l, all
	platform: '', // Allowed values: linux, win32, darwin, mas, all
	win32metadata: {
		CompanyName: '',
		FileDescription: '',
		OriginalFilename: '',
		ProductName: '',
		InternalName: ''
	},
	overwrite: true
};

redpajama_set_name: RedPajamaGithub


text:
package gov.sandia.cognition.collection;

import gov.sandia.cognition.math.MutableDouble;
import gov.sandia.cognition.math.matrix.InfiniteVector;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;

/**
 * A partial implementation of a ScalarMap with a MutableDouble value
 * @param <KeyType>
 * Type of key in the Map
 * @author Kevin R. Dixon
 * @since 3.2.1
 */
public class AbstractMutableDoubleMap<KeyType>
    extends AbstractScalarMap<KeyType>
{

    /**
     * Map backing that performs the storage.
     */
    protected Map<KeyType, MutableDouble> map;

    /**
     * Creates a new instance of AbstractMutableDoubleMap
     * @param   map
     *      The backing map that the data is stored in.
     */
    public AbstractMutableDoubleMap(
        final Map<KeyType, MutableDouble> map )
    {
        super();
        this.map = map;
    }

    @Override
    public AbstractMutableDoubleMap<KeyType> clone()
    {
        @SuppressWarnings("unchecked")
        AbstractMutableDoubleMap<KeyType> clone =
            (AbstractMutableDoubleMap<KeyType>) super.clone();
        // NOTE: there is the potential for a problem if this.map isn't a
        // LinkedHashMap!
        clone.map = new LinkedHashMap<KeyType, MutableDouble>( this.size() );
        clone.incrementAll(this);
        return clone;
    }

    @Override
    public Map<KeyType, MutableDouble> asMap()
    {
        return this.map;
    }

    /**
     * Removes entries from the map with value of 0.0
     */
    public void compact()
    {
        // We can't use entrySet to remove null/zero elements because it throws
        // a ConcurrentModificationException
        // We can't use the keySet either because that throws an Exception,
        // so we need to clone it first
        LinkedList<KeyType> removeKeys = new LinkedList<KeyType>();
        for (Map.Entry<KeyType, MutableDouble> entry : this.map.entrySet())
        {
            final MutableDouble value = entry.getValue();
            if( value.value == 0.0 )
            {
                removeKeys.add( entry.getKey() );
            }
        }
        for( KeyType key : removeKeys )
        {
            this.map.remove(key);
        }
    }

    @Override
    public double get(
        final KeyType key)
    {
        final MutableDouble entry = this.map.get(key);
        if (entry == null)
        {
            return 0.0;
        }
        else
        {
            return entry.value;
        }
    }

    @Override
    public void set(
        final KeyType key,
        final double value)
    {

        final MutableDouble entry = this.map.get(key);
        if( entry == null )
        {
            // Only need to allocate if it's not null
            if( value != 0.0 )
            {
                this.map.put( key, new MutableDouble( value ) );
            }
        }

        // I've commented this out, because I think there's the potential for
        // memory thrashing if this is left in... call compact() method instead?
        //  -- krdixon, 2011-06-27
//        else if( value == 0.0 )
//        {
//            this.map.remove(key);
//        }
        else
        {
            entry.value = value;
        }
    }

    @Override
    public double increment(
        final KeyType key,
        final double value)
    {
        final MutableDouble entry = this.map.get(key);
        double newValue;
        if( entry == null )
        {
            if( value != 0.0 )
            {
                // It's best to avoid this.set() here as it could mess up
                // our total tracker in some subclasses...
                // Also it's more efficient this way (avoid another get)
                this.map.put( key, new MutableDouble(value) );
            }
            newValue = value;
        }
        else
        {
            entry.value += value;
            newValue = entry.value;
        }
        return newValue;
    }

    @Override
    public void clear()
    {
        this.map.clear();
    }

    @Override
    public Set<Entry<KeyType>> entrySet()
    {
        return new SimpleEntrySet<KeyType>( this.map );
    }

    @Override
    public Set<KeyType> keySet()
    {
        return this.map.keySet();
    }

    @Override
    public boolean containsKey(
        final KeyType key)
    {
        return this.map.containsKey(key);
    }

    @Override
    public int size()
    {
        return this.map.size();
    }

    /**
     * Simple Entry Set for DefaultInfiniteVector
     * @param <KeyType>
     *      The type of the key in the map.
     */
    protected static class SimpleEntrySet<KeyType>
        extends AbstractSet<Entry<KeyType>>
    {

        /**
         * Backing map
         */
        protected Map<KeyType,MutableDouble> map;

        /**
         * Creates a new instance of SimpleEntrySet
         * @param map
         * Backing map
         */
        public SimpleEntrySet(
            Map<KeyType, MutableDouble> map)
        {
            this.map = map;
        }

        @Override
        public Iterator<Entry<KeyType>> iterator()
        {
            return new SimpleIterator<KeyType>( map.entrySet().iterator() );
        }

        @Override
        public int size()
        {
            return map.size();
        }

    }

    /**
     * Simple iterator for DefaultInfiniteVector
     * @param <KeyType>
     *      The type of the key in the map.
     */
    protected static class SimpleIterator<KeyType>
        implements Iterator<Entry<KeyType>>
    {

        /**
         * Iterator that does all the work
         */
        private Iterator<? extends Map.Entry<KeyType, MutableDouble>> delegate;

        /**
         * Default constructor
         * @param delegate
         * Iterator that does all the work
         */
        public SimpleIterator(
            Iterator<? extends Map.Entry<KeyType, MutableDouble>> delegate )
        {
            this.delegate = delegate;
        }

        @Override
        public boolean hasNext()
        {
            return this.delegate.hasNext();
        }

        @Override
        public Entry<KeyType> next()
        {
            Map.Entry<KeyType,MutableDouble> entry = this.delegate.next();
            return new AbstractMutableDoubleMap.SimpleEntry<KeyType>(
                entry.getKey(), entry.getValue() );
        }

        @Override
        public void remove()
        {
            this.delegate.remove();
        }

    }

    /**
     * Interface for entries.
     *
     * @param <KeyType>
     *      The type of the key in the map.
     */
    public interface Entry<KeyType>
        extends ScalarMap.Entry<KeyType>, InfiniteVector.Entry<KeyType>
    {

    }

    /**
     * Entry for the AbstractScalarMap
     * @param <KeyType>
     *      The type of the key in the map.
     */
    protected static class SimpleEntry<KeyType>
        implements Entry<KeyType>
    {

        /**
         * Key associated with this entry
         */
        protected KeyType key;

        /**
         * Value associated with the entry
         */
        protected MutableDouble value;

        /**
         * Creates a new instance of SimpleEntry
         * @param key
         * Key represented by the Entry
         * @param value
         * Value associated with the Entry
         */
        public SimpleEntry(
            final KeyType key,
            final MutableDouble value )
        {
            this.key = key;
            this.value = value;
        }

        @Override
        public KeyType getKey()
        {
            return this.key;
        }

        @Override
        public double getValue()
        {
            return value.value;
        }

        @Override
        public void setValue(
            double value)
        {
            this.value.value = value;
        }

    }

}


text:
body{margin:10px;}h1{font-size:138.5%;}h2{font-size:123.1%;}h3{font-size:108%;}h1,h2,h3{margin:1em 0;}h1,h2,h3,h4,h5,h6,strong,dt{font-weight:bold;}optgroup{font-weight:normal;}abbr,acronym{border-bottom:1px dotted #000;cursor:help;}em{font-style:italic;}del{text-decoration:line-through;}blockquote,ul,ol,dl{margin:1em;}ol,ul,dl{margin-left:2em;}ol li{list-style:decimal outside;}ul li{list-style:disc outside;}dl dd{margin-left:1em;}th,td{border:1px solid #000;padding:.5em;}th{font-weight:bold;text-align:center;}caption{margin-bottom:.5em;text-align:center;}sup{vertical-align:super;}sub{vertical-align:sub;}p,fieldset,table,pre{margin-bottom:1em;}button,input[type="checkbox"],input[type="radio"],input[type="reset"],input[type="submit"]{padding:1px;}
body{font:13px/1.231 arial,helvetica,clean,sans-serif;*font-size:small;*font:x-small;}select,input,button,textarea,button{font:99% arial,helvetica,clean,sans-serif;}table{font-size:inherit;font:100%;}pre,code,kbd,samp,tt{font-family:monospace;*font-size:108%;line-height:100%;}
html{color:#000;background:#FFF;}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,button,textarea,p,blockquote,th,td{margin:0;padding:0;}table{border-collapse:collapse;border-spacing:0;}fieldset,img{border:0;}address,caption,cite,code,dfn,em,strong,th,var,optgroup{font-style:inherit;font-weight:inherit;}del,ins{text-decoration:none;}li{list-style:none;}caption,th{text-align:left;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym{border:0;font-variant:normal;}sup{vertical-align:baseline;}sub{vertical-align:baseline;}legend{color:#000;}input,button,textarea,select,optgroup,option{font-family:inherit;font-size:inherit;font-style:inherit;font-weight:inherit;}input,button,textarea,select{*font-size:100%;}
/* -- End YUI 2.7.0 */

html {
	background-color: #aaa;
	background: -webkit-gradient(linear, 0 0, 0 40%, from(#fff), to(#aaa));
	height: 100%;
}

body {
	margin: 2em auto 2em auto;
	max-width: 80%;
	min-width: 400px;
}

h1 {
	font-family: 'Gill Sans', 'Trebuchet MS';
	font-weight: normal;
	font-size: 182%;
	margin: 0 0 0.5em 0;
	color: #666;
}
p {
	font-family: 'Lucida Grande', 'Helvetica Neue', 'Verdana', sans-serif;
	margin: 1em;
}
code {
	color: #880000;
}


text:
import imp
import os
import sys

module_name = 'cloudpassage_slim'
here_dir = os.path.dirname(os.path.abspath(__file__))
module_path = os.path.join(here_dir, '../../')
sys.path.append(module_path)
fp, pathname, description = imp.find_module(module_name)
cloudpassage_slim = imp.load_module(module_name, fp, pathname, description)

class TestUnitTimeSeries(object):
    def test_unit_time_series_build_url_list(self):
        path = "/v1/whatever"
        params = {"server": "heyhowdy"}
        count = 0
        for item in cloudpassage_slim.TimeSeries.create_url_batch(path, 5,
                                                                  params):
            count += 1
            assert item[0] == path
            assert item[1]["server"] == "heyhowdy"
            assert item[1]["page"] == count
        assert count == 5

    def test_unit_time_series_sorted_items_from_pages(self):
        page1 = {"whatevers": [
                    {"item_number": 1,
                     "nonsort": "somesuch"},
                    {"item_number": 4,
                     "nonsort": "somesuch"}]}
        page2 = {"whatevers": [
                    {"item_number": 2,
                     "nonsort": "somesuch"},
                    {"item_number": 3,
                     "nonsort": "somesuch"}]}
        pages = [page1, page2]
        s = cloudpassage_slim.TimeSeries.sorted_items_from_pages(pages,
                                                                 "whatevers",
                                                                 "item_number")
        count = 0
        for item in s:
            count += 1
            assert item["item_number"] == count
        assert count == 4

    def test_unit_time_series_get_number_of_empty_pages(self):
        page1 = {"whatevers": [
                    {"item_number": 1,
                     "nonsort": "somesuch"},
                    {"item_number": 4,
                     "nonsort": "somesuch"}]}
        page2 = {"whatevers": []}
        pages = [page1, page2]
        pkey = "whatevers"
        expected = 1
        actual = cloudpassage_slim.TimeSeries.get_number_of_empty_pages(pages,
                                                                        pkey)
        assert expected == actual

    def test_unit_time_series_get_number_of_full_pages(self):
        page1 = {"whatevers": [
                    {"item_number": 1,
                     "nonsort": "somesuch"},
                    {"item_number": 4,
                     "nonsort": "somesuch"}]}
        page2 = {"whatevers": []}
        pages = [page1, page2]
        pkey = "whatevers"
        expected = 1
        actual = cloudpassage_slim.TimeSeries.get_number_of_full_pages(pages,
                                                                       2,
                                                                       pkey)
        assert expected == actual

    def test_unit_time_series_get_adjustment_factor_zero(self):
        page1 = {"whatevers": [
                    {"item_number": 1,
                     "nonsort": "somesuch"},
                    {"item_number": 4,
                     "nonsort": "somesuch"}]}
        page2 = {"whatevers": [
                    {"item_number": 2,
                     "nonsort": "somesuch"}]}
        pages = [page1, page2]
        pkey = "whatevers"
        expected = 0
        actual = cloudpassage_slim.TimeSeries.get_adjustment_factor(pages, 2,
                                                                    pkey)
        assert expected == actual

    def test_unit_time_series_get_adjustment_factor_up_one(self):
        page1 = {"whatevers": [
                    {"item_number": 1,
                     "nonsort": "somesuch"},
                    {"item_number": 4,
                     "nonsort": "somesuch"}]}
        page2 = {"whatevers": [
                    {"item_number": 2,
                     "nonsort": "somesuch"},
                    {"item_number": 3,
                     "nonsort": "somesuch"}]}
        pages = [page1, page2]
        pkey = "whatevers"
        expected = 1
        actual = cloudpassage_slim.TimeSeries.get_adjustment_factor(pages, 2,
                                                                    pkey)
        assert expected == actual

    def test_unit_time_series_get_adjustment_factor_down_one(self):
        page1 = {"whatevers": [
                    {"item_number": 1,
                     "nonsort": "somesuch"},
                    {"item_number": 4,
                     "nonsort": "somesuch"}]}
        page2 = {"whatevers": [
                    {"item_number": 2,
                     "nonsort": "somesuch"},
                    {"item_number": 3,
                     "nonsort": "somesuch"}]}
        page3 = {"whatevers": []}
        pages = [page1, page2, page3]
        pkey = "whatevers"
        expected = -1
        actual = cloudpassage_slim.TimeSeries.get_adjustment_factor(pages, 2,
                                                                    pkey)
        assert expected == actual

    def test_unit_time_series_get_adjustment_factor_big_drop(self):
        page1 = {"whatevers": [
                    {"item_number": 1,
                     "nonsort": "somesuch"}]}
        page2 = {"whatevers": []}
        page3 = {"whatevers": []}
        pages = [page1, page2, page3]
        pkey = "whatevers"
        expected = -9
        actual = cloudpassage_slim.TimeSeries.get_adjustment_factor(pages, 2,
                                                                    pkey)
        assert expected == actual


text:
<?php
namespace CtSearchBundle\Processor;

use Symfony\Component\Form\Extension\Core\Type\SubmitType;

class SimpleXMLParserFilter extends ProcessorFilter {

  public function getDisplayName() {
    return "Simple XML Parser";
  }

  public function getSettingsForm($controller) {
    $formBuilder = parent::getSettingsForm($controller)
      ->add('ok', SubmitType::class, array('label' => $controller->get('translator')->trans('OK')));
    return $formBuilder;
  }

  public function getFields() {
    return array('doc');
  }

  public function getArguments() {
    return array(
      'xml' => 'XML source',
    );
  }

  public function execute(&$document) {
    try{
      $xml = $this->getArgumentValue('xml', $document);
      if(file_exists($xml)){
        $xml = file_get_contents($xml);
      }
      $xmlDoc = simplexml_load_string(str_replace('xmlns=', 'ns=', $xml));
      if($xmlDoc) {
        foreach ($xmlDoc->getDocNamespaces() as $strPrefix => $strNamespace) {
          //if(strlen($strPrefix) == 0) {
          //  $strPrefix = "a"; //Assign an arbitrary namespace prefix.
          //}
          $xmlDoc->registerXPathNamespace($strPrefix, $strNamespace);
        }

        return array('doc' => $xmlDoc);
      }
    }catch(\Exception $ex){

    }
    return array('doc' => null);
  }

}


text:
require 'spec_helper'

describe Mongo::Grid::File do

  describe '#==' do

    let(:file) do
      described_class.new('test', :filename => 'test.txt')
    end

    context 'when the object is not a file' do

      it 'returns false' do
        expect(file).to_not eq('testing')
      end
    end

    context 'when the object is a file' do

      context 'when the objects are equal' do

        it 'returns true' do
          expect(file).to eq(file)
        end
      end

      context 'when the objects are not equal' do

        let(:other) do
          described_class.new('tester', :filename => 'test.txt')
        end

        it 'returns false' do
          expect(file).to_not eq(other)
        end
      end
    end
  end

  describe '#initialize' do

    let(:data_size) do
      Mongo::Grid::File::Chunk::DEFAULT_SIZE * 3
    end

    let(:data) do
      'testing'
    end

    before do
      (1..data_size).each{ |i| data << '1' }
    end

    context 'when provided data and metadata' do

      let(:file) do
        described_class.new(data, :filename => 'test.txt')
      end

      it 'sets the data' do
        expect(file.data).to eq(data)
      end

      it 'creates the chunks' do
        expect(file.chunks.size).to eq(4)
      end
    end

    context 'when data is a ruby file' do

      let(:ruby_file) do
        File.open(__FILE__)
      end

      let(:data) do
        ruby_file.read
      end

      let(:file) do
        described_class.new(data, :filename => File.basename(ruby_file.path))
      end

      it 'sets the data' do
        expect(file.data).to eq(data)
      end

      it 'creates the chunks' do
        expect(file.chunks.size).to eq(4)
      end
    end

    context 'when using idiomatic ruby field names' do

      let(:time) do
        Time.now.utc
      end

      let(:file) do
        described_class.new(
          data,
          :filename => 'test.txt',
          :chunk_size => 100,
          :upload_date => time,
          :content_type => 'text/plain'
        )
      end

      it 'normalizes the chunk size name' do
        expect(file.chunk_size).to eq(100)
      end

      it 'normalizes the upload date name' do
        expect(file.upload_date).to eq(time)
      end

      it 'normalizes the content type name' do
        expect(file.content_type).to eq('text/plain')
      end
    end

    context 'when provided chunks and metadata' do

      let(:file_id) do
        BSON::ObjectId.new
      end

      let(:metadata) do
        BSON::Document.new(
          :_id => file_id,
          :uploadDate => Time.now.utc,
          :filename => 'test.txt',
          :chunkSize => Mongo::Grid::File::Chunk::DEFAULT_SIZE,
          :length => data.length,
          :contentType => Mongo::Grid::File::Metadata::DEFAULT_CONTENT_TYPE
        )
      end

      let(:chunks) do
        Mongo::Grid::File::Chunk.split(
          data, Mongo::Grid::File::Metadata.new(metadata)
        ).map{ |chunk| chunk.document }
      end

      let(:file) do
        described_class.new(chunks, metadata)
      end

      it 'sets the chunks' do
        expect(file.chunks.size).to eq(4)
      end

      it 'assembles to data' do
        expect(file.data).to eq(data)
      end

      it 'sets the metadata' do
        expect(file.metadata.id).to eq(metadata[:_id])
      end
    end
  end

  describe '#inspect' do

    let(:file) do
      described_class.new('Hi', :filename => 'test.txt')
    end

    it 'includes the filename' do
      expect(file.inspect).to include('test.txt')
    end
  end
end


text:
// Copyright (c) 2013 M-Way Solutions GmbH
// http://github.com/mwaylabs/The-M-Project/blob/absinthe/MIT-LICENSE.txt

//TODO do this in good
var template = $('

');
template.find('.right-panel').before(M.SwitchLayout.prototype.template);

M.Themes.registerTemplateForTheme( M.Themes.DEFAULT_THEME, 'swipe-layout', template );
/**
 *
 * @module M.SwipeLayout
 * @type {*}
 * @extends M.SwitchLayout
 */
M.SwipeLayout = M.SwitchLayout.extend({

    _type: 'M.SwipeLayout',

    template: M.Themes.getTemplateByName('swipe-layout'),

    leftPanelIsOpen: null,

    rightThreshold: null,

    initialize: function() {
        M.SwitchLayout.prototype.initialize.call(this);

        var w = $(window).width();
        this.rightThreshold = (w / 100) * 80;
    },

    toggleRightPanel: function() {
        this.closeLeftPanel();
        $('.right-panel').toggleClass('show');
    },

    closeRightPanel: function() {
        $('.right-panel').removeClass('show');
    },

    toggleLeftPanel: function() {
        this.closeRightPanel();
        if( this.leftPanelIsOpen ) {
            this.closeLeftPanel();
        } else {
            this.openLeftPanel();
        }
    },

    startMoveLeftPanel: function( evt ) {
        if( !evt || !evt.originalEvent ) {
            return;
        }
        evt.stopPropagation();
        evt.preventDefault();
        var touch = evt.originalEvent.touches[0] || evt.originalEvent.changedTouches[0];

        if( this.leftPanelIsOpen ) {
            this.moveStart = 0;
        } else {
            this.moveStart = touch.pageX;
        }
    },

    stopMoveLeftPanel: function( evt ) {
        evt.stopPropagation();
        evt.preventDefault();
        $('#m-main').addClass('easing');

        if( this.leftPanelIsOpen ) {
            this.closeLeftPanel();
        } else {
            this.openLeftPanel();
        }

        setTimeout(function() {
            $('#m-main').removeClass('easing');
        }, 500);

    },

    moveLeftPanel: function( evt ) {
        //                if(!evt || !evt.originalEvent){
        //                    return;
        //                }
        //                evt.stopPropagation();
        //                evt.preventDefault();
        var touch = evt.originalEvent.touches[0] || evt.originalEvent.changedTouches[0];

        var diff = touch.pageX - this.moveStart;
        if( diff <= 0 ) {
            diff = 0;
        } else if( diff >= this.rightThreshold ) {
            diff = this.rightThreshold;
        } else {
            $('#m-main').css('-webkit-transform', 'translate3d(' + diff + 'px, 0, 0)');
        }

        //        -webkit-transform: translate3d(80%, 0, 0);
        //        -moz-transform: translate3d(80%, 0, 0);
        //        -ms-transform: translate3d(80%, 0, 0);
        //        -o-transform: translate3d(80%, 0, 0);
        //        transform: translate3d(80%, 0, 0);
    },

    closeLeftPanel: function() {
        //$('.os-bb10 .template-bottom, .os-bb10 .template-right').css('-webkit-transform', 'translate3d(' + 0 + 'px, 0, 0)');
        $('#m-main').css('-webkit-transform', 'translate3d(' + 0 + 'px, 0, 0)');
        this.leftPanelIsOpen = false;
    },

    openLeftPanel: function() {
        $('#m-main').css('-webkit-transform', 'translate3d(' + this.rightThreshold + 'px, 0, 0)');
        this.leftPanelIsOpen = true;
    }
});


text:
    <title>Tabs Directive</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

    <tabset>
        <tab heading="Tab 1">
            Lorem ipsum dolor sit amet, ut eam nullam utroque liberavisse, ea
            graecis tractatos contentiones quo. Ipsum phaedrum scripserit sit id,
            eu insolens indoctum vel, eos eu offendit delectus tincidunt. Eum
            nostrum reprehendunt in, ullum nostrud legimus ei quo. Sed et elitr
            corrumpit. Nibh maiestatis voluptatum has no, at est inermis epicuri,
            omnis temporibus cu mei. Legere scriptorem voluptatibus et est, ea
            noluisse deterruisset sea.
        </tab>
        <tab heading="Tap 2">
            Just another tab!
        </tab>
    </tabset>

        <kid done="logChore(chore)"></kid>
        <kid done="logChore(chore)"></kid>
        <kid done="logChore(chore)"></kid>


text:
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Krkadoni.Enigma.Enums;
using Krkadoni.Enigma.Properties;

namespace Krkadoni.Enigma
{
    public class Profile : IProfile, INotifyPropertyChanged
    {
        private string _address;
        private EnigmaType _enigma;
        private int _httpPort;
        private string _name;
        private string _password;
        private bool _useSsl;
        private string _username;
        private int _streamingPort;

        public Profile()
        {
            _name = string.Empty;
            _username = "root";
            _password = "dreambox";
            _address = "192.168.1.1";
            _enigma = EnigmaType.Enigma2;
            _httpPort = 80;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public string Name
        {
            get { return _name; }
            set
            {
                if (value == _name) return;
                _name = value;
                OnPropertyChanged();
            }
        }

        public string Username
        {
            get { return _username; }
            set
            {
                if (value == _username) return;
                _username = value;
                OnPropertyChanged();
            }
        }

        public string Password
        {
            get { return _password; }
            set
            {
                if (value == _password) return;
                _password = value;
                OnPropertyChanged();
            }
        }

        public EnigmaType Enigma
        {
            get { return _enigma; }
            set
            {
                if (value == _enigma) return;
                _enigma = value;
                OnPropertyChanged();
            }
        }

        public string Address
        {
            get { return _address; }
            set
            {
                if (value == _address) return;
                _address = value;
                OnPropertyChanged();
            }
        }

        public int HttpPort
        {
            get { return _httpPort; }
            set
            {
                if (value == _httpPort) return;
                _httpPort = value;
                OnPropertyChanged();
            }
        }

        public bool UseSsl
        {
            get { return _useSsl; }
            set
            {
                if (value.Equals(_useSsl)) return;
                _useSsl = value;
                OnPropertyChanged();
            }
        }

        public int StreamingPort
        {
            get { return _streamingPort; }
            set
            {
                if (value.Equals(_streamingPort)) return;
                _streamingPort = value;
                OnPropertyChanged();
            }
        }

        public override string ToString()
        {
            return Name;
        }

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}


text:
namespace Microsoft.AspNetCore.Components.Sections;

internal sealed class SectionRegistry
{
    private readonly Dictionary<string, ISectionContentSubscriber> _subscribersByName = new();
    private readonly Dictionary<string, List<ISectionContentProvider>> _providersByName = new();

    public void AddProvider(string name, ISectionContentProvider provider, bool isDefaultProvider)
    {
        if (!_providersByName.TryGetValue(name, out var providers))
        {
            providers = new();
            _providersByName.Add(name, providers);
        }

        if (isDefaultProvider)
        {
            providers.Insert(0, provider);
        }
        else
        {
            providers.Add(provider);
        }
    }

    public void RemoveProvider(string name, ISectionContentProvider provider)
    {
        if (!_providersByName.TryGetValue(name, out var providers))
        {
            throw new InvalidOperationException($"There are no content providers with the name '{name}'.");
        }

        var index = providers.LastIndexOf(provider);

        if (index < 0)
        {
            throw new InvalidOperationException($"The provider was not found in the providers list of name '{name}'.");
        }

        providers.RemoveAt(index);

        if (index == providers.Count)
        {
            // We just removed the most recently added provider, meaning we need to change
            // the current content to that of second most recently added provider.
            var content = GetCurrentProviderContentOrDefault(providers);
            NotifyContentChangedForSubscriber(name, content);
        }
    }

    public void Subscribe(string name, ISectionContentSubscriber subscriber)
    {
        if (_subscribersByName.ContainsKey(name))
        {
            throw new InvalidOperationException($"There is already a subscriber to the content '{name}'.");
        }

        // Notify the new subscriber with any existing content.
        var content = GetCurrentProviderContentOrDefault(name);
        subscriber.ContentChanged(content);

        _subscribersByName.Add(name, subscriber);
    }

    public void Unsubscribe(string name)
    {
        if (!_subscribersByName.Remove(name))
        {
            throw new InvalidOperationException($"The subscriber with name '{name}' is already unsubscribed.");
        }
    }

    public void NotifyContentChanged(string name, ISectionContentProvider provider)
    {
        if (!_providersByName.TryGetValue(name, out var providers))
        {
            throw new InvalidOperationException($"There are no content providers with the name '{name}'.");
        }

        // We only notify content changed for subscribers when the content of the
        // most recently added provider changes.
        if (providers.Count != 0 && providers[^1] == provider)
        {
            NotifyContentChangedForSubscriber(name, provider.Content);
        }
    }

    private static RenderFragment? GetCurrentProviderContentOrDefault(List<ISectionContentProvider> providers)
        => providers.Count != 0
            ? providers[^1].Content
            : null;

    private RenderFragment? GetCurrentProviderContentOrDefault(string name)
        => _providersByName.TryGetValue(name, out var existingList)
            ? GetCurrentProviderContentOrDefault(existingList)
            : null;

    private void NotifyContentChangedForSubscriber(string name, RenderFragment? content)
    {
        if (_subscribersByName.TryGetValue(name, out var subscriber))
        {
            subscriber.ContentChanged(content);
        }
    }
}


text:
package com.logitags.cibet.authentication;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.logitags.cibet.context.Context;
import com.logitags.cibet.sensor.http.Headers;

public class HttpSessionAuthenticationProvider extends AbstractAuthenticationProvider {

   /**
    *
    */
   private static final long serialVersionUID = 1L;

   @Override
   public String getUsername() {
      HttpServletRequest req = Context.internalSessionScope().getHttpRequest();
      if (req != null) {
         HttpSession session = req.getSession(false);
         if (session != null) {
            Object user = session.getAttribute(Headers.CIBET_USER.name());
            if (user != null && user instanceof String) {
               return (String) user;
            }
         }
      }

      return null;
   }

   /**
    * returns http session attribute 'tenant' if existing, otherwise DEFAULT_TENANT.
    */
   @Override
   public String getTenant() {
      HttpServletRequest req = Context.internalSessionScope().getHttpRequest();
      if (req != null) {
         HttpSession session = req.getSession(false);
         if (session != null) {
            Object tenant = session.getAttribute(Headers.CIBET_TENANT.name());
            if (tenant != null && tenant instanceof String) {
               return (String) tenant;
            }
         }
      }

      return DEFAULT_TENANT;
   }

   /**
    * returns http session attribute 'userAddress' if existing, otherwise null.
    */
   @Override
   public String getUserAddress() {
      HttpServletRequest req = Context.internalSessionScope().getHttpRequest();
      if (req != null) {
         HttpSession session = req.getSession(false);
         if (session != null) {
            Object addr = session.getAttribute(Headers.CIBET_USERADDRESS.name());
            if (addr != null && addr instanceof String) {
               return (String) addr;
            }
         }
      }
      return null;
   }

}


text:
<?php
class ControllerExtensionModuleBlog extends Controller {
	public function index($setting) {
		$this->load->language('extension/module/blog');

		$data['img_loader'] = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';

		$data['heading_search'] = $this->language->get('heading_search');
		$data['heading_category'] = $this->language->get('heading_category');
		$data['heading_post'] = $this->language->get('heading_post');
		$data['text_search'] = $this->language->get('text_search');

		if (isset($this->request->get['filter_name'])) {
			$data['filter_name'] = $this->request->get['filter_name'];
		} else {
			$data['filter_name'] = '';
		}

		if (isset($this->request->get['blog_category_id'])) {
			$data['blog_category_id'] = $this->request->get['blog_category_id'];
		} else {
			$data['blog_category_id'] = 0;
		}

		if (isset($this->request->get['date_added'])) {
			$data['date_added'] = $this->request->get['date_added'];
		} else {
			$data['date_added'] = 0;
		}

		$blog_blocks =  array();

		if(!empty($setting['search_status'])) {
			$blog_blocks[$setting['search_sort_order']] = 'search';
		}

		$this->load->model('blog/category');
		$this->load->model('blog/post');
		$this->load->model('tool/image');

		if(!empty($setting['category_status'])) {
			if (isset($this->request->get['path'])) {
				$parts = explode('_', (string)$this->request->get['path']);
			} else {
				$parts = array();
			}

			if (isset($parts[0])) {
				$data['category_id'] = $parts[0];
			} else {
				$data['category_id'] = 0;
			}

			if (isset($parts[1])) {
				$data['child_id'] = $parts[1];
			} else {
				$data['child_id'] = 0;
			}

			$data['categories'] = array();

			$categories = $this->model_blog_category->getCategories(0);

			foreach ($categories as $category) {
				$children_data = array();

				if ($category['category_id'] == $data['category_id']) {
					$children = $this->model_blog_category->getCategories($category['category_id']);

					foreach($children as $child) {
						$filter_data = array('filter_category_id' => $child['category_id'], 'filter_sub_category' => true);

						$children_data[] = array(
							'category_id'	=> $child['category_id'],
							'name'			=> $child['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_blog_post->getTotalPosts($filter_data) . ')' : ''),
							'href'			=> $this->url->link('blog/category', 'blog_path=' . $category['category_id'] . '_' . $child['category_id'])
						);
					}
				}

				$filter_data = array(
					'filter_category_id'	=> $category['category_id'],
					'filter_sub_category'	=> true
				);

				$data['categories'][] = array(
					'category_id'	=> $category['category_id'],
					'name'			=> $category['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_blog_post->getTotalPosts($filter_data) . ')' : ''),
					'children'		=> $children_data,
					'href'			=> $this->url->link('blog/category', 'blog_path=' . $category['category_id'])
				);
			}

			$blog_blocks[$setting['category_sort_order']] = 'categories';
		}

		if(!empty($setting['post_status'])) {
			$data['latest_posts'] = array();

			$filter_data = array(
				'sort'	=> 'p.date_added',
				'order'	=> 'DESC',
				'start'	=> 0,
				'limit'	=> 5
			);

			$results = $this->model_blog_post->getPosts($filter_data);

			if ($results) {
				foreach ($results as $result) {
					if ($result['image']) {
						$image = $this->model_tool_image->resize($result['image'], 42, 42, 'crop');
					} else {
						$image = $this->model_tool_image->resize('placeholder.png', 42, 42);
					}

					$data['latest_posts'][] = array(
						'post_id'		=> $result['post_id'],
						'thumb'			=> $image,
						'name'			=> $result['name'],
						'description'	=> utf8_substr(strip_tags(html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8')), 0, 75) . '..',
						'published'		=> date($this->language->get('date_format_short'), strtotime($result['date_added'])),
						'href'			=> $this->url->link('blog/post', 'post_id=' . $result['post_id'])
					);
				}
			}
			$blog_blocks[$setting['post_sort_order']] = 'latest_posts';
		}

		ksort($blog_blocks);

		$data['blog_blocks'] = $blog_blocks;

		return $this->load->view('extension/module/blog', $data);
	}
}


text:
set -e

proton_repo="https://github.com/dcristoloveanu/qpid-proton"
proton_branch="0.9-IoTClient"
sdk_root="$HOME/openwrt/sdk"
install_dir="openwrt-qpid-proton"
package_dir="package"
src_dir="src"
working_dir=$PWD
makefile="Makefile.proton"

usage ()
{
    echo 'build_proton.sh [options]'
    echo 'options'
    echo ' -s, --sdkroot   root of the SDK folder'
    echo '                 (default: $HOME/openwrt/sdk)'
    exit 1
}

process_args ()
{
    while [ ! -z "$1" ]
    do
        if [ "$1" == "-s" ] || [ "$1" == "--sdkroot" ]
        then
            sdk_root="$2"
        else
            usage
        fi

        shift
        shift
    done
}

sync_proton ()
{
    echo Azure IoT SDK has a dependency on apache qpid-proton-c
    echo "$proton_repo"

    read -p "Do you want to install the component (y/n)?" input_var
    if [ "$input_var" == "y" ] || [ "$input_var" == "Y" ]
    then
        echo "preparing qpid proton-c"
    else
        exit 1
    fi

    echo Installing proton to $sdk_root

    cd "$sdk_root/$package_dir"

    if [ -d $install_dir ]
    then
      echo "Removing $install_dir"
      rm -r -f $install_dir
    fi

    mkdir $install_dir

    cd $install_dir

    # Download the repo
    curl -L $proton_repo/archive/$proton_branch.zip -o proton.zip
    unzip proton.zip
    mv qpid-proton-$proton_branch/ $src_dir/
    rm proton.zip

    # Patching the build files
    cp "$working_dir/$makefile" ./Makefile
    cat "$working_dir/CMakeList.append" >> "$src_dir/proton-c/CMakeLists.txt"
}

build()
{
  echo Building apache qpid-proton
  cd "$sdk_root"
  make V=s "package/$install_dir/compile"
}

process_args $*
sync_proton
build


text:
@interface ECGModel : NSObject

@property (nonatomic, copy)NSString *name;
@property (nonatomic, copy)NSString *introduction;
@property (nonatomic, copy)NSString *imgName;

@end


text:
"""
A pipeline example that uses several interfaces to
perform analysis on diffusion weighted images using
FSL FDT tools.

This tutorial is based on the 2010 FSL course and uses
data freely available at the FSL website at:
http://www.fmrib.ox.ac.uk/fslcourse/fsl_course_data2.tar.gz

More details can be found at http://www.fmrib.ox.ac.uk/fslcourse/lectures/practicals/fdt/index.htm
"""

"""
Tell python where to find the appropriate functions.
"""

import nipype.interfaces.io as nio           # Data i/o
import nipype.interfaces.fsl as fsl          # fsl
import nipype.interfaces.utility as util     # utility
import nipype.pipeline.engine as pe          # pypeline engine
import os                                    # system functions

"""
Confirm package dependencies are installed.  (This is only for the
tutorial, rarely would you put this in your own code.)
"""

from nipype.utils.misc import package_check

package_check('numpy', '1.3', 'tutorial1')
package_check('scipy', '0.7', 'tutorial1')
package_check('networkx', '1.0', 'tutorial1')
package_check('IPython', '0.10', 'tutorial1')

"""
Setting up workflows
--------------------
This is a generic workflow for DTI data analysis using the FSL
"""

"""
Data specific components
------------------------

The nipype tutorial contains data for two subjects.  Subject data
is in two subdirectories, ``dwis1`` and ``dwis2``.  Each subject directory
contains each of the following files: bvec, bval, diffusion weighted data, a set of target masks,
a seed file, and a transformation matrix.

Below we set some variables to inform the ``datasource`` about the
layout of our data.  We specify the location of the data, the subject
sub-directories and a dictionary that maps each run to a mnemonic (or
field) for the run type (``dwi`` or ``bvals``).  These fields become
the output fields of the ``datasource`` node in the pipeline.

Specify the subject directories
"""

subject_list = ['subj1']

"""
Map field names to individual subject runs
"""

info = dict(dwi=[['subject_id', 'data']],
            bvecs=[['subject_id','bvecs']],
            bvals=[['subject_id','bvals']],
            seed_file = [['subject_id','MASK_average_thal_right']],
            target_masks = [['subject_id',['MASK_average_M1_right',
                                           'MASK_average_S1_right',
                                           'MASK_average_occipital_right',
                                           'MASK_average_pfc_right',
                                           'MASK_average_pmc_right',
                                           'MASK_average_ppc_right',
                                           'MASK_average_temporal_right']]])

infosource = pe.Node(interface=util.IdentityInterface(fields=['subject_id']),
                     name="infosource")

"""Here we set up iteration over all the subjects. The following line
is a particular example of the flexibility of the system.  The
``datasource`` attribute ``iterables`` tells the pipeline engine that
it should repeat the analysis on each of the items in the
``subject_list``. In the current example, the entire first level
preprocessing and estimation will be repeated for each subject
contained in subject_list.
"""

infosource.iterables = ('subject_id', subject_list)

"""
Now we create a :class:`nipype.interfaces.io.DataGrabber` object and
fill in the information from above about the layout of our data.  The
:class:`nipype.pipeline.engine.Node` module wraps the interface object
and provides additional housekeeping and pipeline specific
functionality.
"""

datasource = pe.Node(interface=nio.DataGrabber(infields=['subject_id'],
                                               outfields=info.keys()),
                     name = 'datasource')

datasource.inputs.template = "%s/%s"

# This needs to point to the fdt folder you can find after extracting
# http://www.fmrib.ox.ac.uk/fslcourse/fsl_course_data2.tar.gz
datasource.inputs.base_directory = os.path.abspath('fsl_course_data/fdt/')

datasource.inputs.field_template = dict(dwi='%s/%s.nii.gz',
                                        seed_file="%s.bedpostX/%s.nii.gz",
                                        target_masks="%s.bedpostX/%s.nii.gz")
datasource.inputs.template_args = info

"""
Setup for Diffusion Tensor Computation
--------------------------------------
Here we will create a generic workflow for DTI computation
"""

computeTensor = pe.Workflow(name='computeTensor')

"""
extract the volume with b=0 (nodif_brain)
"""

fslroi = pe.Node(interface=fsl.ExtractROI(),name='fslroi')
fslroi.inputs.t_min=0
fslroi.inputs.t_size=1

"""
create a brain mask from the nodif_brain
"""

bet = pe.Node(interface=fsl.BET(),name='bet')
bet.inputs.mask=True
bet.inputs.frac=0.34

"""
correct the diffusion weighted images for eddy_currents
"""

eddycorrect = pe.Node(interface=fsl.EddyCorrect(),name='eddycorrect')
eddycorrect.inputs.ref_num=0

"""
compute the diffusion tensor in each voxel
"""

dtifit = pe.Node(interface=fsl.DTIFit(),name='dtifit')

"""
connect all the nodes for this workflow
"""

computeTensor.connect([
                        (fslroi,bet,[('roi_file','in_file')]),
                        (eddycorrect,dtifit,[('eddy_corrected','dwi')]),
                        (infosource, dtifit,[['subject_id','base_name']]),
                        (bet,dtifit,[('mask_file','mask')])
                      ])

"""
Setup for Tracktography
-----------------------
Here we will create a workflow to enable probabilistic tracktography
and hard segmentation of the seed region
"""

tractography = pe.Workflow(name='tractography')
tractography.base_dir = os.path.abspath('dti_tutorial')

"""
estimate the diffusion parameters: phi, theta, and so on
"""

bedpostx = pe.Node(interface=fsl.BEDPOSTX(),name='bedpostx')
bedpostx.inputs.fibres = 1

bedpostx_2f = pe.Node(interface=fsl.BEDPOSTX(),name='bedpostx_2f')
bedpostx_2f.inputs.fibres = 2

flirt = pe.Node(interface=fsl.FLIRT(), name='flirt')
flirt.inputs.reference = fsl.Info.standard_image('MNI152_T1_2mm_brain.nii.gz')
flirt.inputs.dof = 12

"""
perform probabilistic tracktography
"""

probtrackx = pe.Node(interface=fsl.ProbTrackX(),name='probtrackx')
probtrackx.inputs.mode='seedmask'
probtrackx.inputs.loop_check=True
probtrackx.inputs.c_thresh = 0.2
probtrackx.inputs.n_steps=2000
probtrackx.inputs.step_length=0.5
probtrackx.inputs.n_samples=5000
probtrackx.inputs.force_dir=True
probtrackx.inputs.opd=True
probtrackx.inputs.os2t=True

"""
perform hard segmentation on the output of probtrackx
"""

findthebiggest = pe.Node(interface=fsl.FindTheBiggest(),name='findthebiggest')

"""
connect all the nodes for this workflow
"""

tractography.connect([
                        (bedpostx,probtrackx,[('bpx_out_directory','bpx_directory')]),
                        (bedpostx,probtrackx,[('bpx_out_directory','out_dir')]),
                        (probtrackx,findthebiggest,[('targets','in_files')]),
                        (flirt, probtrackx, [('out_matrix_file','xfm')])
                    ])

"""
Setup data storage area
"""

datasink = pe.Node(interface=nio.DataSink(),name='datasink')
datasink.inputs.base_directory = os.path.abspath('dtiresults')

def getstripdir(subject_id):
    return os.path.join(os.path.abspath('data/workingdir/dwiproc'),'_subject_id_%s' % subject_id)

"""
Setup the pipeline that combines the two workflows: tractography and computeTensor
----------------------------------------------------------------------------------
"""

dwiproc = pe.Workflow(name="dwiproc")
dwiproc.base_dir = os.path.abspath('dti_tutorial')
dwiproc.connect([
                    (infosource,datasource,[('subject_id', 'subject_id')]),
                    (datasource,computeTensor,[('dwi','fslroi.in_file'),
                                               ('bvals','dtifit.bvals'),
                                               ('bvecs','dtifit.bvecs'),
                                               ('dwi','eddycorrect.in_file')]),
                    (datasource,tractography,[('bvals','bedpostx.bvals'),
                                              ('bvecs','bedpostx.bvecs'),
                                              ('seed_file','probtrackx.seed_file'),
                                              ('target_masks','probtrackx.target_masks')]),
                    (computeTensor,tractography,[('eddycorrect.eddy_corrected','bedpostx.dwi'),
                                                 ('bet.mask_file','bedpostx.mask'),
                                                 ('bet.mask_file','probtrackx.mask'),
                                                 ('fslroi.roi_file','flirt.in_file')]),
                    (infosource, datasink,[('subject_id','container'),
                                           (('subject_id', getstripdir),'strip_dir')]),
                    (tractography,datasink,[('findthebiggest.out_file','fbiggest.@biggestsegmentation')])
                ])

dwiproc.run()
dwiproc.write_graph()


text:
#include "tensorflow/core/grappler/optimizers/arithmetic_optimizer.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/grappler/grappler_item.h"
#include "tensorflow/core/grappler/inputs/trivial_test_graph_input_yielder.h"
#include "tensorflow/core/grappler/optimizers/constant_folding.h"
#include "tensorflow/core/grappler/optimizers/model_pruner.h"
#include "tensorflow/core/grappler/utils.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"

namespace tensorflow {
namespace grappler {
namespace {

class ArithmeticOptimizerTest : public ::testing::Test {};

TEST_F(ArithmeticOptimizerTest, NoOp) {
  // This trivial graph is so basic there's nothing to optimize.
  TrivialTestGraphInputYielder fake_input(4, 1, 10, false, {"CPU:0"});
  GrapplerItem item;
  CHECK(fake_input.NextItem(&item));

  ArithmeticOptimizer optimizer;
  GraphDef output;
  Status s = optimizer.Optimize(nullptr, item, &output);
  TF_EXPECT_OK(s);

  EXPECT_EQ(item.graph.node_size(), output.node_size());
  for (int i = 0; i < item.graph.node_size(); ++i) {
    const NodeDef& original = item.graph.node(i);
    const NodeDef& optimized = output.node(i);
    EXPECT_EQ(original.name(), optimized.name());
    EXPECT_EQ(original.op(), optimized.op());
    EXPECT_EQ(original.input_size(), optimized.input_size());
    for (int j = 0; j < original.input_size(); ++j) {
      EXPECT_EQ(original.input(j), optimized.input(j));
    }
  }
}

TEST_F(ArithmeticOptimizerTest, OpDedupping) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  Output c1 = ops::Const(s.WithOpName("c1"), {3.14, 2.7}, {1, 2});
  Output c2 = ops::Const(s.WithOpName("c2"), {3.14, 2.7}, {1, 2});
  Output add = ops::Add(s.WithOpName("add"), c1, c2);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));

  ArithmeticOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(nullptr, item, &output);
  TF_EXPECT_OK(status);

  EXPECT_EQ(2, output.node_size());
  const NodeDef& new_c1 = output.node(0);
  EXPECT_EQ("c1", new_c1.name());
  const NodeDef& new_add = output.node(1);
  EXPECT_EQ("add", new_add.name());
  EXPECT_EQ(2, new_add.input_size());
  EXPECT_EQ("c1", new_add.input(0));
  EXPECT_EQ("c1", new_add.input(1));
}

TEST_F(ArithmeticOptimizerTest, OpDedupCommutative) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  Output c1 = ops::Const(s.WithOpName("c1"), {1.0f, 2.0f}, {1, 2});
  Output c2 = ops::Const(s.WithOpName("c2"), {3.0f, 4.0f}, {1, 2});
  Output add1 = ops::Add(s.WithOpName("add1"), c1, c2);
  Output add2 = ops::Add(s.WithOpName("add2"), c2, c1);
  Output add3 = ops::Add(s.WithOpName("add3"), add1, add2);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));

  ArithmeticOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(nullptr, item, &output);
  TF_EXPECT_OK(status);

  EXPECT_EQ(4, output.node_size());
  const NodeDef& new_c1 = output.node(0);
  EXPECT_EQ("c1", new_c1.name());
  const NodeDef& new_c2 = output.node(1);
  EXPECT_EQ("c2", new_c2.name());
  const NodeDef& new_add1 = output.node(2);
  EXPECT_EQ("add1", new_add1.name());
  EXPECT_EQ(2, new_add1.input_size());
  EXPECT_EQ("c1", new_add1.input(0));
  EXPECT_EQ("c2", new_add1.input(1));
  const NodeDef& new_add3 = output.node(3);
  EXPECT_EQ("add3", new_add3.name());
  EXPECT_EQ(2, new_add3.input_size());
  EXPECT_EQ("add1", new_add3.input(0));
  EXPECT_EQ("add1", new_add3.input(1));
}

TEST_F(ArithmeticOptimizerTest, SimplifyInvolutionsReal) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  Output c = ops::Const(s.WithOpName("c"), {1.0f, 2.0f}, {1, 2});
  Output neg1 = ops::Neg(s.WithOpName("neg1"), c);
  Output neg2 = ops::Neg(s.WithOpName("neg2"), neg1);
  Output recip1 = ops::Reciprocal(s.WithOpName("recip1"), neg2);
  Output recip2 = ops::Reciprocal(s.WithOpName("recip2"), recip1);
  Output id = ops::Identity(s.WithOpName("id"), recip2);
  GrapplerItem item;
  TF_CHECK_OK(s.ToGraphDef(&item.graph));

  ArithmeticOptimizer optimizer;
  GraphDef output;
  Status status = optimizer.Optimize(nullptr, item, &output);
  TF_EXPECT_OK(status);

  EXPECT_EQ(6, output.node_size());
  EXPECT_EQ("c", output.node(1).input(0));
  EXPECT_EQ("c", output.node(3).input(0));
  EXPECT_EQ("c", output.node(5).input(0));
}

TEST_F(ArithmeticOptimizerTest, IdentityReshape) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  Output inputs =
      ops::Placeholder(s, DT_FLOAT, ops::Placeholder::Shape({-1, 3, 28, 28}));
  Output inputs_shape = ops::Shape(s, inputs);
  // The target shape of the reshape is the concatenation of `batch_size` and
  // [3,28,28].
  Output batch_size = ops::Slice(s, inputs_shape, ops::Const(s, {0}, {1}),
                                 ops::Const(s, {1}, {1}));
  Output target_shape = ops::Concat(
      s.WithOpName("target_shape"),
      {batch_size, ops::Const(s, {3, 28, 28}, {3})}, ops::Const(s, {0}, {}));
  Output reshape = ops::Reshape(s, inputs, target_shape);
  Output outputs = ops::Identity(s.WithOpName("outputs"), reshape);

  GrapplerItem item;
  item.fetch = {"outputs"};
  TF_CHECK_OK(s.ToGraphDef(&item.graph));

  GraphDef output;
  TF_EXPECT_OK(ArithmeticOptimizer(RewriterConfig::AGGRESSIVE)
                   .Optimize(nullptr, item, &output));

  item.graph = output;
  TF_EXPECT_OK(ModelPruner().Optimize(nullptr, item, &output));

  for (const auto& node : output.node()) {
    LOG(INFO) << node.DebugString();
  }

  EXPECT_EQ(0, std::count_if(
                   output.node().begin(), output.node().end(),
                   [](const NodeDef& node) { return node.op() == "Reshape"; }));
}

TEST_F(ArithmeticOptimizerTest, NotIdentityReshape) {
  // Reshape from [-1,3,28,28] to [8,-1,28,28] is not identity, because it can
  // be from [4,3,28,28] to [8,6,28,28].
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  Output inputs =
      ops::Placeholder(s, DT_FLOAT, ops::Placeholder::Shape({-1, 3, 28, 28}));
  Output reshape = ops::Reshape(s, inputs, ops::Const(s, {8, -1, 28, 28}, {4}));
  Output outputs = ops::Identity(s.WithOpName("outputs"), reshape);

  GrapplerItem item;
  item.fetch = {"outputs"};
  TF_CHECK_OK(s.ToGraphDef(&item.graph));

  GraphDef output;
  TF_EXPECT_OK(ArithmeticOptimizer(RewriterConfig::AGGRESSIVE)
                   .Optimize(nullptr, item, &output));

  item.graph = output;
  TF_EXPECT_OK(ModelPruner().Optimize(nullptr, item, &output));

  for (const auto& node : output.node()) {
    LOG(INFO) << node.DebugString();
  }

  EXPECT_EQ(1, std::count_if(
                   output.node().begin(), output.node().end(),
                   [](const NodeDef& node) { return node.op() == "Reshape"; }));
}

TEST_F(ArithmeticOptimizerTest, NotIdentityReshapeTooManyUnknownDimSizes) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  Output inputs =
      ops::Placeholder(s, DT_FLOAT, ops::Placeholder::Shape({4, 3}));
  Output reshape = ops::Reshape(s, inputs, ops::Const(s, {-1, -1}, {2}));
  Output outputs = ops::Identity(s.WithOpName("outputs"), reshape);

  GrapplerItem item;
  item.fetch = {"outputs"};
  TF_CHECK_OK(s.ToGraphDef(&item.graph));

  GraphDef output;
  TF_EXPECT_OK(ArithmeticOptimizer(RewriterConfig::AGGRESSIVE)
                   .Optimize(nullptr, item, &output));

  item.graph = output;
  TF_EXPECT_OK(ModelPruner().Optimize(nullptr, item, &output));

  EXPECT_EQ(1, std::count_if(
                   output.node().begin(), output.node().end(),
                   [](const NodeDef& node) { return node.op() == "Reshape"; }));
}

TEST_F(ArithmeticOptimizerTest, CombineReshapes) {
  // Converts an NCHW_VECT_C tensor to NHWC and then flattens it to 2D. The two
  // reshapes should be combined.
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  Output nchw_vect_c =
      ops::Placeholder(s.WithOpName("nchw_vect_c"), DT_INT8,
                       ops::Placeholder::Shape({8, 3, 28, 28, 4}));
  Output transpose =
      ops::Transpose(s.WithOpName("transpose"), nchw_vect_c,
                     ops::Const(s.WithOpName("perm"), {0, 2, 3, 1, 4}, {5}));
  Output nhwc = ops::Reshape(
      s.WithOpName("nhwc"), transpose,
      ops::Const(s.WithOpName("nhwc_shape"), {8, 28, 28, 12}, {4}));
  Output flatten = ops::Reshape(
      s.WithOpName("flatten"), nhwc,
      ops::Const(s.WithOpName("flatten_shape"), {8, 28 * 28 * 12}, {2}));
  Output outputs = ops::Identity(s.WithOpName("outputs"), flatten);

  GrapplerItem item;
  item.fetch = {"outputs"};
  TF_CHECK_OK(s.ToGraphDef(&item.graph));

  GraphDef output;
  TF_EXPECT_OK(ArithmeticOptimizer().Optimize(nullptr, item, &output));

  item.graph = output;
  TF_EXPECT_OK(ModelPruner().Optimize(nullptr, item, &output));

  EXPECT_EQ(1, std::count_if(
                   output.node().begin(), output.node().end(),
                   [](const NodeDef& node) { return node.op() == "Reshape"; }));
}

TEST_F(ArithmeticOptimizerTest, ReorderTransposeCast) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope().WithDevice("/gpu:0");
  Output nhwc_uint8 =
      ops::Placeholder(s, DT_UINT8, ops::Placeholder::Shape({8, 28, 28, 3}));
  Output nhwc_fp32 = ops::Cast(s, nhwc_uint8, DT_FLOAT);
  Output nchw_fp32 =
      ops::Transpose(s, nhwc_fp32, ops::Const(s, {0, 3, 1, 2}, {4}));
  Output outputs = ops::Identity(s.WithOpName("outputs"), nchw_fp32);

  GrapplerItem item;
  item.fetch = {"outputs"};
  TF_CHECK_OK(s.ToGraphDef(&item.graph));

  GraphDef output;
  TF_EXPECT_OK(ArithmeticOptimizer().Optimize(nullptr, item, &output));

  item.graph = output;
  TF_EXPECT_OK(ModelPruner().Optimize(nullptr, item, &output));

  const NodeDef* transpose_node = nullptr;
  for (const NodeDef& node : output.node()) {
    if (node.op() == "Transpose") {
      EXPECT_EQ(transpose_node, nullptr);
      EXPECT_EQ(DT_UINT8, node.attr().at("T").type());
      transpose_node = &node;
    }
  }
  EXPECT_NE(transpose_node, nullptr);

  for (const NodeDef& node : output.node()) {
    if (node.op() == "Cast") {
      EXPECT_EQ(NodeName(node.input(0)), transpose_node->name());
    }
  }
}

TEST_F(ArithmeticOptimizerTest, NoReorderTransposeCast) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope().WithDevice("/gpu:0");
  Output nhwc_fp32 =
      ops::Placeholder(s, DT_FLOAT, ops::Placeholder::Shape({8, 28, 28, 3}));
  Output nhwc_uint8 = ops::Cast(s, nhwc_fp32, DT_UINT8);
  Output nchw_uint8 =
      ops::Transpose(s, nhwc_uint8, ops::Const(s, {0, 3, 1, 2}, {4}));
  Output outputs = ops::Identity(s.WithOpName("outputs"), nchw_uint8);

  GrapplerItem item;
  item.fetch = {"outputs"};
  TF_CHECK_OK(s.ToGraphDef(&item.graph));

  GraphDef output;
  TF_EXPECT_OK(ArithmeticOptimizer().Optimize(nullptr, item, &output));

  item.graph = output;
  TF_EXPECT_OK(ModelPruner().Optimize(nullptr, item, &output));

  int num_transposes = 0;
  for (const NodeDef& node : output.node()) {
    if (node.op() == "Transpose") {
      EXPECT_EQ(DT_UINT8, node.attr().at("T").type());
      EXPECT_EQ(node.input(0), "Cast");
      ++num_transposes;
    }
  }
  EXPECT_EQ(1, num_transposes);
}

TEST_F(ArithmeticOptimizerTest, RemoveInverseTransposes) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  Output inputs_shape =
      ops::Const(s.WithOpName("inputs_shape"), {8, 3, 28, 28}, {4});
  Output inputs =
      ops::RandomUniform(s.WithOpName("inputs"), inputs_shape, DT_FLOAT);
  Output perm1 = ops::Const(s.WithOpName("perm1"), {0, 2, 3, 1}, {4});
  Output perm2 = ops::Const(s.WithOpName("perm2"), {0, 3, 1, 2}, {4});
  Output transpose1 = ops::Transpose(s.WithOpName("transpose1"), inputs, perm1);
  Output transpose2 =
      ops::Transpose(s.WithOpName("transpose2"), transpose1, perm2);
  Output outputs = ops::Identity(s.WithOpName("outputs"), transpose2);

  GrapplerItem item;
  item.fetch = {"outputs"};
  TF_CHECK_OK(s.ToGraphDef(&item.graph));

  GraphDef output;
  TF_EXPECT_OK(ArithmeticOptimizer().Optimize(nullptr, item, &output));

  item.graph = output;
  TF_EXPECT_OK(ModelPruner().Optimize(nullptr, item, &output));

  std::set<string> nodes_after_optimization;
  for (const NodeDef& node : output.node()) {
    nodes_after_optimization.insert(node.name());
  }
  EXPECT_EQ(nodes_after_optimization,
            std::set<string>({"inputs_shape", "inputs", "outputs"}));
}

TEST_F(ArithmeticOptimizerTest, RemoveInverseTransposesMultipleOutputs) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  Output inputs_shape =
      ops::Const(s.WithOpName("inputs_shape"), {8, 9, 28, 28}, {4});
  Output inputs = ops::Placeholder(s.WithOpName("inputs"), DT_FLOAT,
                                   ops::Placeholder::Shape({8, 12, 28, 28}));
  OutputList split = ops::Split(s, ops::Const(s, 1), inputs, 3).output;
  Output perm1 = ops::Const(s, {0, 2, 3, 1}, {4});
  Output perm2 = ops::Const(s, {0, 3, 1, 2}, {4});
  Output branch0 = split[0];
  Output branch1 = ops::Transpose(s, ops::Transpose(s, split[1], perm1), perm2);
  Output branch2 = split[2];
  Output concat = ops::Concat(s, {branch0, branch1, branch2}, ops::Const(s, 1));
  Output outputs = ops::Identity(s.WithOpName("outputs"), concat);

  GrapplerItem item;
  item.fetch = {"outputs"};
  TF_CHECK_OK(s.ToGraphDef(&item.graph));

  GraphDef output;
  TF_EXPECT_OK(ArithmeticOptimizer().Optimize(nullptr, item, &output));

  item.graph = output;
  TF_EXPECT_OK(ModelPruner().Optimize(nullptr, item, &output));

  for (const NodeDef& node : output.node()) {
    if (node.op() == "Concat") {
      EXPECT_EQ(node.input(0), "Split");
      EXPECT_EQ(node.input(1), "Split:1");
      EXPECT_EQ(node.input(2), "Split:2");
    }
  }
}

TEST_F(ArithmeticOptimizerTest, RemoveTransposesWithControlDependency) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  Output inputs =
      ops::Placeholder(s, DT_FLOAT, ops::Placeholder::Shape({2, 3}));
  Output transpose1 = ops::Transpose(s, inputs, ops::Const(s, {1, 0}));
  Output transpose2 = ops::Transpose(s, transpose1, ops::Const(s, {1, 0}));
  Output outputs =
      ops::Identity(s.WithOpName("outputs").WithControlDependencies(transpose2),
                    ops::Const(s.WithOpName("outputs_const"), 1.0f));

  GrapplerItem item;
  item.fetch = {"outputs"};
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  GraphDef output;
  TF_EXPECT_OK(ArithmeticOptimizer().Optimize(nullptr, item, &output));
  item.graph = output;
  TF_EXPECT_OK(ModelPruner().Optimize(nullptr, item, &output));

  NodeMap node_map(&output);
  const NodeDef* outputs_node = node_map.GetNode("outputs");
  EXPECT_EQ(2, outputs_node->input_size());
  EXPECT_EQ(outputs_node->input(0), "outputs_const");
  EXPECT_EQ(outputs_node->input(1), "^Placeholder");
}

TEST_F(ArithmeticOptimizerTest, NotRemoveTransposes) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  Output inputs_shape =
      ops::Const(s.WithOpName("inputs_shape"), {8, 3, 28, 28}, {4});
  Output inputs =
      ops::RandomUniform(s.WithOpName("inputs"), inputs_shape, DT_FLOAT);
  Output perm = ops::Const(s.WithOpName("perm"), {1, 2, 3, 0}, {4});
  Output transpose1 = ops::Transpose(s.WithOpName("transpose1"), inputs, perm);
  Output transpose2 =
      ops::Transpose(s.WithOpName("transpose2"), transpose1, perm);
  Output outputs = ops::Identity(s.WithOpName("outputs"), transpose2);

  GrapplerItem item;
  item.fetch = {"outputs"};
  TF_CHECK_OK(s.ToGraphDef(&item.graph));

  GraphDef output;
  TF_EXPECT_OK(ArithmeticOptimizer().Optimize(nullptr, item, &output));

  item.graph = output;
  TF_EXPECT_OK(ModelPruner().Optimize(nullptr, item, &output));

  EXPECT_EQ(6, output.node_size());
}

TEST_F(ArithmeticOptimizerTest, FoldMulToTransposeConv) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  Output inputs = ops::Placeholder(s.WithOpName("inputs"), DT_FLOAT,
                                   ops::Placeholder::Shape({8, 28, 28, 3}));
  Output scale = ops::Const(s.WithOpName("scale"), 1.0f / 255.0f, {});
  Output scaled_inputs =
      ops::Multiply(s.WithOpName("scaled_inputs"), inputs, scale);
  Output perm_nhwc_to_nchw =
      ops::Const(s.WithOpName("perm_nhwc_to_nchw"), {0, 3, 1, 2}, {4});
  Output inputs_nchw = ops::Transpose(s.WithOpName("inputs_nchw"),
                                      scaled_inputs, perm_nhwc_to_nchw);
  Output weights = ops::Const(s.WithOpName("weights"),
                              Input::Initializer(127.0f, {5, 5, 3, 16}));
  Output conv =
      ops::Conv2D(s.WithOpName("conv"), inputs_nchw, weights, {1, 1, 1, 1},
                  "VALID", ops::Conv2D::DataFormat("NCHW"));
  Output outputs = ops::Identity(s.WithOpName("outputs"), conv);

  GrapplerItem item;
  item.fetch = {"outputs"};
  TF_CHECK_OK(s.ToGraphDef(&item.graph));

  GraphDef output;
  TF_EXPECT_OK(ArithmeticOptimizer().Optimize(nullptr, item, &output));

  item.graph = output;
  TF_EXPECT_OK(ModelPruner().Optimize(nullptr, item, &output));

  NodeMap node_map(&output);
  // `conv` is now a folded convolution with scaled weights.
  const NodeDef* folded_conv = node_map.GetNode(conv.node()->name());
  CHECK_EQ(node_map.GetNode(NodeName(folded_conv->input(1)))->op(), "Mul");
  // Its input should be a transpose of `inputs`.
  const NodeDef* transpose = node_map.GetNode(NodeName(folded_conv->input(0)));
  CHECK_EQ(NodeName(transpose->input(0)), inputs.node()->name());
}

TEST_F(ArithmeticOptimizerTest, NotFoldMulAcrossPreservedTranspose) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  Output inputs = ops::Placeholder(s.WithOpName("inputs"), DT_FLOAT,
                                   ops::Placeholder::Shape({8, 28, 28, 3}));
  Output scale = ops::Const(s.WithOpName("scale"), 1.0f / 255.0f, {});
  Output scaled_inputs =
      ops::Multiply(s.WithOpName("scaled_inputs"), inputs, scale);
  Output perm_nhwc_to_nchw =
      ops::Const(s.WithOpName("perm_nhwc_to_nchw"), {0, 3, 1, 2}, {4});
  Output inputs_nchw = ops::Transpose(s.WithOpName("inputs_nchw"),
                                      scaled_inputs, perm_nhwc_to_nchw);
  Output weights = ops::Const(s.WithOpName("weights"),
                              Input::Initializer(127.0f, {5, 5, 3, 16}));
  Output conv =
      ops::Conv2D(s.WithOpName("conv"), inputs_nchw, weights, {1, 1, 1, 1},
                  "VALID", ops::Conv2D::DataFormat("NCHW"));
  Output outputs = ops::Identity(s.WithOpName("outputs"), conv);

  Tensor inputs_nchw_tensor(DT_FLOAT, {8, 3, 28, 28});
  memset(const_cast<char*>(inputs_nchw_tensor.tensor_data().data()), 0,
         inputs_nchw_tensor.tensor_data().size());

  GrapplerItem item;
  item.fetch = {"outputs"};
  item.feed = {{"inputs_nchw", inputs_nchw_tensor}};
  TF_CHECK_OK(s.ToGraphDef(&item.graph));

  GraphDef output;
  TF_EXPECT_OK(ArithmeticOptimizer().Optimize(nullptr, item, &output));

  item.graph = output;
  TF_EXPECT_OK(ModelPruner().Optimize(nullptr, item, &output));

  NodeMap node_map(&output);
  const NodeDef* inputs_nchw_node_def =
      node_map.GetNode(inputs_nchw.node()->name());
  EXPECT_EQ(NodeName(inputs_nchw_node_def->input(0)),
            scaled_inputs.node()->name());
}

TEST_F(ArithmeticOptimizerTest, FoldMulToConv) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  Output inputs = ops::Placeholder(s.WithOpName("inputs"), DT_FLOAT,
                                   ops::Placeholder::Shape({8, 28, 28, 28, 3}));
  Output scale = ops::Const(s.WithOpName("scale"), 1.0f / 255.0f, {});
  Output scaled_inputs =
      ops::Multiply(s.WithOpName("scaled_inputs"), inputs, scale);
  Output weights = ops::Const(s.WithOpName("weights"),
                              Input::Initializer(127.0f, {5, 5, 5, 3, 16}));
  Output conv = ops::Conv3D(s.WithOpName("conv"), scaled_inputs, weights,
                            {1, 1, 1, 1, 1}, "VALID");
  Output outputs = ops::Identity(s.WithOpName("outputs"), conv);

  GrapplerItem item;
  item.fetch = {"outputs"};
  TF_CHECK_OK(s.ToGraphDef(&item.graph));

  GraphDef output;
  TF_EXPECT_OK(ArithmeticOptimizer().Optimize(nullptr, item, &output));

  item.graph = output;
  TF_EXPECT_OK(ModelPruner().Optimize(nullptr, item, &output));

  NodeMap node_map(&output);
  // `conv` is now a folded convolution on `inputs` and scaled weights.
  const NodeDef* folded_conv = node_map.GetNode(conv.node()->name());
  CHECK_EQ(inputs.node()->name(), NodeName(folded_conv->input(0)));
  CHECK_EQ(node_map.GetNode(NodeName(folded_conv->input(1)))->op(), "Mul");
}

TEST_F(ArithmeticOptimizerTest, OptimizeCastMulTransposeConv) {
  // This unit test exercises two optimizations, folding mul into conv, and
  // reordering cast and transpose.
  //
  //   Conv2D(Transpose(Mul(Cast(I), S)), W)
  //     =>
  //   Conv2D(Transpose(Cast(I)), W*S)
  //     =>
  //   Conv2D(Cast(Transpose(I)), W*S)
  tensorflow::Scope s = tensorflow::Scope::NewRootScope().WithDevice("/gpu:0");
  Output inputs =
      ops::Placeholder(s, DT_UINT8, ops::Placeholder::Shape({8, 28, 28, 3}));
  Output cast = ops::Cast(s, inputs, DT_FLOAT);
  Output mul = ops::Mul(s, cast, ops::Const(s, 1.0f / 255.0f));
  Output transpose =
      ops::Transpose(s, mul, ops::Const(s.WithOpName("perm"), {0, 3, 1, 2}));
  Output weights = ops::Const(s.WithOpName("weights"),
                              Input::Initializer(127.0f, {5, 5, 3, 16}));
  Output conv = ops::Conv2D(s, transpose, weights, {1, 1, 1, 1}, "VALID",
                            ops::Conv2D::DataFormat("NCHW"));
  Output outputs = ops::Identity(s.WithOpName("outputs"), conv);

  GrapplerItem item;
  item.fetch = {"outputs"};
  TF_CHECK_OK(s.ToGraphDef(&item.graph));

  GraphDef output;
  TF_EXPECT_OK(ArithmeticOptimizer().Optimize(nullptr, item, &output));

  item.graph = output;
  TF_EXPECT_OK(
      ConstantFolding(/*cpu_device=*/nullptr).Optimize(nullptr, item, &output));

  item.graph = output;
  TF_EXPECT_OK(ModelPruner().Optimize(nullptr, item, &output));

  NodeMap node_map(&output);
  const NodeDef* inputs_node = CHECK_NOTNULL(node_map.GetNode("Placeholder"));
  const NodeDef* transpose_node =
      CHECK_NOTNULL(node_map.GetNode("Transpose_uint8"));
  const NodeDef* cast_node = CHECK_NOTNULL(node_map.GetNode("Cast_new"));
  const NodeDef* weights_node =
      CHECK_NOTNULL(node_map.GetNode("weights_scaled"));
  const NodeDef* conv_node = CHECK_NOTNULL(node_map.GetNode("Conv2D"));

  EXPECT_EQ(output.node_size(), 7);
  EXPECT_EQ(transpose_node->input(0), inputs_node->name());
  EXPECT_EQ(cast_node->input(0), transpose_node->name());
  EXPECT_EQ(conv_node->input(0), cast_node->name());
  EXPECT_EQ(conv_node->input(1), weights_node->name());
}

TEST_F(ArithmeticOptimizerTest, CombineBitcasts) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  Output inputs =
      ops::Placeholder(s, DT_UINT8, ops::Placeholder::Shape({2, 3}));
  Output bc1 = ops::Bitcast(s, inputs, DT_QINT8);
  Output bc2 = ops::Bitcast(s, bc1, DT_INT8);
  Output outputs = ops::Identity(s.WithOpName("outputs"), bc2);

  GrapplerItem item;
  item.fetch = {"outputs"};
  TF_CHECK_OK(s.ToGraphDef(&item.graph));

  GraphDef output;
  TF_EXPECT_OK(ArithmeticOptimizer().Optimize(nullptr, item, &output));
  item.graph = output;
  TF_EXPECT_OK(ModelPruner().Optimize(nullptr, item, &output));

  EXPECT_EQ(1, std::count_if(
                   output.node().begin(), output.node().end(),
                   [](const NodeDef& node) { return node.op() == "Bitcast"; }));
}

TEST_F(ArithmeticOptimizerTest, CombineAndRemoveBitcasts) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  Output inputs = ops::Placeholder(s, DT_INT8, ops::Placeholder::Shape({2, 3}));
  Output bc1 = ops::Bitcast(s, inputs, DT_QINT8);
  Output bc2 = ops::Bitcast(s, bc1, DT_INT8);
  Output outputs = ops::Identity(s.WithOpName("outputs"), bc2);

  GrapplerItem item;
  item.fetch = {"outputs"};
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  GraphDef output;
  TF_EXPECT_OK(ArithmeticOptimizer().Optimize(nullptr, item, &output));
  item.graph = output;
  TF_EXPECT_OK(ModelPruner().Optimize(nullptr, item, &output));

  EXPECT_EQ(0, std::count_if(
                   output.node().begin(), output.node().end(),
                   [](const NodeDef& node) { return node.op() == "Bitcast"; }));
}

TEST_F(ArithmeticOptimizerTest, RemoveRedundantCast) {
  tensorflow::Scope s = tensorflow::Scope::NewRootScope();
  Output inputs = ops::Placeholder(s, DT_INT8, ops::Placeholder::Shape({2, 3}));
  Output cast = ops::Cast(s, inputs, DT_INT8);
  Output outputs = ops::Identity(s.WithOpName("outputs"), cast);

  GrapplerItem item;
  item.fetch = {"outputs"};
  TF_CHECK_OK(s.ToGraphDef(&item.graph));
  GraphDef output;
  TF_EXPECT_OK(ArithmeticOptimizer().Optimize(nullptr, item, &output));
  item.graph = output;
  TF_EXPECT_OK(ModelPruner().Optimize(nullptr, item, &output));

  EXPECT_EQ(0, std::count_if(
                   output.node().begin(), output.node().end(),
                   [](const NodeDef& node) { return node.op() == "Cast"; }));
}

}  // namespace
}  // namespace grappler
}  // namespace tensorflow


text:
Showing Eureka

### m2-eureka-server
Eureka Server running on port 8761.
URL: http://localhost:8761/

### m2-tollrate-service
Service running on random port, thus must be accessed using Eureka.
Paths:
* /tollrate/1
* /tollrate/2
* /tollrate/3

### m2-tollrate-service
Service running on random port.
Paths:
* /fastpass?fastpassid=100
* /fastpass?fastpassphone=555-123-4567

### m2-tollrate-billboard
* Dashboard: http://localhost:8081/dashboard?stationId=3

### m2-fastpass-console
* Dashboard: http://localhost:8082/customerdetails?fastpassid=100


text:
package org.archive.cdxserver.auth;

import java.util.List;

import org.archive.format.cdx.FieldSplitFormat;

/**
 * Simple checking of permissions for cdx server actions Permissions include:
 * -Ability to see blocked urls -Ability to see full cdx line
 *
 * The checkAccess() for each url is implemented in the subclasses
 *
 * @author ilya
 *
 */
public abstract class PrivTokenAuthChecker implements AuthChecker {
	protected String publicCdxFields = null;
	protected FieldSplitFormat publicCdxFormat = null;

	protected List<String> allUrlAccessTokens;
	protected List<String> ignoreRobotsAccessTokens;
	protected List<String> allCdxFieldsAccessTokens;

	protected boolean isAllowed(AuthToken auth, List<String> allowVector) {
		if (auth == null || auth.authToken == null || allowVector == null) {
			return false;
		}

		if (allowVector.contains(auth.authToken)) {
			return true;
		}

		return false;
	}

	@Override
	public boolean isAllUrlAccessAllowed(AuthToken auth) {
		if (auth.cachedAllUrlAllow == null) {
			auth.cachedAllUrlAllow = isAllowed(auth, allUrlAccessTokens);
		}
		return auth.cachedAllUrlAllow;
	}

	@Override
	public boolean isAllCdxFieldAccessAllowed(AuthToken auth) {
		if (auth.cachedAllCdxAllow == null) {
			auth.cachedAllCdxAllow = isAllowed(auth, allCdxFieldsAccessTokens);
		}
		return auth.cachedAllCdxAllow;
	}

	@Override
	public String getPublicCdxFields() {
		return publicCdxFields;
	}

	@Override
	public FieldSplitFormat getPublicCdxFormat() {
		return publicCdxFormat;
	}

	public void setPublicCdxFields(String publicCdxFields) {
		this.publicCdxFields = publicCdxFields;
		this.publicCdxFormat = new FieldSplitFormat(publicCdxFields);
	}

	public List<String> getAllUrlAccessTokens() {
		return allUrlAccessTokens;
	}

	public void setAllUrlAccessTokens(List<String> allUrlAccessTokens) {
		this.allUrlAccessTokens = allUrlAccessTokens;
	}

	public List<String> getAllCdxFieldsAccessTokens() {
		return allCdxFieldsAccessTokens;
	}

	public void setAllCdxFieldsAccessTokens(
			List<String> allCdxFieldsAccessTokens) {
		this.allCdxFieldsAccessTokens = allCdxFieldsAccessTokens;
	}

	public List<String> getIgnoreRobotsAccessTokens() {
		return ignoreRobotsAccessTokens;
	}

	public void setIgnoreRobotsAccessTokens(
			List<String> ignoreRobotsAccessTokens) {
		this.ignoreRobotsAccessTokens = ignoreRobotsAccessTokens;
	}
}


text:
package main

import (
	"context"

	"github.com/metal-tile/land/dqn"
)

// DQNDummyClient is UnitTestのためのDQN Dummy実装
type DQNDummyClient struct {
	PredictionCount int
	Body            *dqn.Payload
	DummyAnswer     *dqn.Answer
}

func (client *DQNDummyClient) Prediction(ctx context.Context, body *dqn.Payload) (*dqn.Answer, error) {
	client.PredictionCount++
	client.Body = body
	return client.DummyAnswer, nil
}


text:
@interface HCDColleagueB : HCDAbstractColleague

@end


text:
var tap = require('tap')

module.exports = { 'test'  : test
                 }

function test(label, tester) {
  if(process.env.only && process.env.only != label)
    return console.log('# Skipping %s', label)

  tap.test(label, function(t) {
    t.member = member
    t.any    = any
    t.none   = none
    t.almost = almost
    tester(t)
  })
}

function member(elem, list, message) {
  var is_member = false;
  list.forEach(function(list_elem) {
    if(list_elem === elem)
      is_member = true;
  })

  return this.equal(is_member, true, message || 'member')
}

function any(list, message, pred) {
  var found = false
  for(var a = 0; a < list.length; a++)
    if(pred.call(null, list[a]))
      found = true
  return this.equal(found, true, message || 'any')
}

function none(list, message, pred) {
  var found = false
  for(var a = 0; a < list.length; a++)
    if(pred.call(null, list[a]))
      found = true
  return this.equal(found, false, message || 'none')
}

function almost(actual, expected, message) {
  var delta = Math.abs(actual - expected);
  var margin = delta / expected;

  if(margin > 0.10)
    return this.equal(actual, '[almost '+expected+']', message || 'almost')
  else
    return this.ok(true, message || 'almost')
}


text:
An incomplete parser producing a Language.Haskell.TH.Syntax syntax tree.
Written with open recursion, so that it is possible to override parts of the
grammar without touching QQParse.hs


text:
""" Unit tests for the msvs.py file. """

import gyp.generator.msvs as msvs
import unittest
from io import StringIO

class TestSequenceFunctions(unittest.TestCase):

  def setUp(self):
    self.stderr = StringIO()

  def test_GetLibraries(self):
    self.assertEqual(
      msvs._GetLibraries({}),
      [])
    self.assertEqual(
      msvs._GetLibraries({'libraries': []}),
      [])
    self.assertEqual(
      msvs._GetLibraries({'other':'foo', 'libraries': ['a.lib']}),
      ['a.lib'])
    self.assertEqual(
      msvs._GetLibraries({'libraries': ['-la']}),
      ['a.lib'])
    self.assertEqual(
      msvs._GetLibraries({'libraries': ['a.lib', 'b.lib', 'c.lib', '-lb.lib',
                                   '-lb.lib', 'd.lib', 'a.lib']}),
      ['c.lib', 'b.lib', 'd.lib', 'a.lib'])

if __name__ == '__main__':
  unittest.main()


text:
package com.chenwuchao.strategyframework

import java.util

import org.junit.Test

/**
 * Created by wuchao.cwc on 3/15/15.
 */
class StrategyWorkerTest {
    val base = this.getClass.getResource("/").getPath
    var sConf = base+"../../src/test/resources/Strategy2.xml"

    @Test
    def StrategyTest() ={
        val sw = new StrategyWorker(sConf,"test",new util.HashMap[String,AnyRef])
        sw.init("")
        sw.put("kk",new StringBuffer().append("bb"))
        sw.execute()
        System.out.println(sw.get("kk"))
        sw.clean()
    }
}