text:
describe PDF::Reader::PageState do
  let!(:page)   { double(:cache => {},
                        :objects => {},
                        :fonts => {},
                        :xobjects => {},
                        :color_spaces => {})}

  describe "#DEFAULT_GRAPHICS_STATE" do
    subject { PDF::Reader::PageState::DEFAULT_GRAPHICS_STATE }

    context "when walking more than one page" do
      let!(:expected) { PDF::Reader::PageState::DEFAULT_GRAPHICS_STATE.dup }

      before do
        2.times do
          state = PDF::Reader::PageState.new(page)
          state.save_graphics_state
          state.concatenate_matrix(1,2,3,4,5,6)
        end
      end

      it "does not mutate" do
        expect(subject).to eql(expected)
      end
    end
  end

  describe "#save_graphics_state" do
    context "with an empty page" do
      let!(:state)  {PDF::Reader::PageState.new(page) }

      it "increases the stack depth by one" do
        expect {
          state.save_graphics_state
        }.to change(state, :stack_depth).from(1).to(2)
      end
    end
  end

  describe "#restore_graphics_state" do
    context "with an empty page" do
      let!(:state)  {PDF::Reader::PageState.new(page) }

      it "reduces the stack depth by one" do
        state.save_graphics_state

        expect {
          state.restore_graphics_state
        }.to change(state, :stack_depth).from(2).to(1)
      end
    end
  end

  describe "#concatenate_matrix" do
    let!(:state)  {PDF::Reader::PageState.new(page) }

    context "when changing value a" do
      it "multiplies the matrixes" do
        state.concatenate_matrix(2, 0,
                                 0, 1,
                                 0, 0)

        # how the matrix is stored and multiplied is really an implementation
        # detail, so it's better to check the results indirectly via the API
        # external collaborators will use
        expect(state.ctm_transform(0,0)).to eq([0, 0])
        expect(state.ctm_transform(0,1)).to eq([0, 1])
        expect(state.ctm_transform(1,0)).to eq([2, 0])
        expect(state.ctm_transform(1,1)).to eq([2, 1])
      end
    end

    context "when changing value b" do
      it "multiplies the matrixes" do
        state.concatenate_matrix(1, 2,
                                 0, 1,
                                 0, 0)

        # how the matrix is stored and multiplied is really an implementation
        # detail, so it's better to check the results indirectly via the API
        # external collaborators will use
        expect(state.ctm_transform(0,0)).to eq([0, 0])
        expect(state.ctm_transform(0,1)).to eq([0, 1])
        expect(state.ctm_transform(1,0)).to eq([1, 2])
        expect(state.ctm_transform(1,1)).to eq([1, 3])
      end
    end

    context "when changing value c" do
      it "multiplies the matrixes" do
        state.concatenate_matrix(1, 0,
                                 2, 1,
                                 0, 0)

        # how the matrix is stored and multiplied is really an implementation
        # detail, so it's better to check the results indirectly via the API
        # external collaborators will use
        expect(state.ctm_transform(0,0)).to eq([0, 0])
        expect(state.ctm_transform(0,1)).to eq([2, 1])
        expect(state.ctm_transform(1,0)).to eq([1, 0])
        expect(state.ctm_transform(1,1)).to eq([3, 1])
      end
    end

    context "when changing value d" do
      it "multiplies the matrixes" do
        state.concatenate_matrix(1, 0,
                                 0, 2,
                                 0, 0)

        # how the matrix is stored and multiplied is really an implementation
        # detail, so it's better to check the results indirectly via the API
        # external collaborators will use
        expect(state.ctm_transform(0,0)).to eq([0, 0])
        expect(state.ctm_transform(0,1)).to eq([0, 2])
        expect(state.ctm_transform(1,0)).to eq([1, 0])
        expect(state.ctm_transform(1,1)).to eq([1, 2])
      end
    end

    context "when changing value e" do
      it "multiplies the matrixes" do
        state.concatenate_matrix(1, 0,
                                 0, 1,
                                 2, 0)

        # how the matrix is stored and multiplied is really an implementation
        # detail, so it's better to check the results indirectly via the API
        # external collaborators will use
        expect(state.ctm_transform(0,0)).to eq([2, 0])
        expect(state.ctm_transform(0,1)).to eq([2, 1])
        expect(state.ctm_transform(1,0)).to eq([3, 0])
        expect(state.ctm_transform(1,1)).to eq([3, 1])
      end
    end

    context "when changing value f" do
      it "multiplies the matrixes" do
        state.concatenate_matrix(1, 0,
                                 0, 1,
                                 0, 2)

        # how the matrix is stored and multiplied is really an implementation
        # detail, so it's better to check the results indirectly via the API
        # external collaborators will use
        expect(state.ctm_transform(0,0)).to eq([0, 2])
        expect(state.ctm_transform(0,1)).to eq([0, 3])
        expect(state.ctm_transform(1,0)).to eq([1, 2])
        expect(state.ctm_transform(1,1)).to eq([1, 3])
      end
    end

    context "when applying a rotation followed by a translation" do
      it "multiplies the matrixes using pre-multiplication" do
        angle = 90 * Math::PI / 180 # 90 degrees
        state.concatenate_matrix( Math.cos(angle), Math.sin(angle),
                                 -Math.sin(angle), Math.cos(angle),
                                  0, 0)
        state.concatenate_matrix(1, 0,
                                 0, 1,
                                 10, 10)

        # how the matrix is stored and multiplied is really an implementation
        # detail, so it's better to check the results indirectly via the API
        # external collaborators will use
        expect(state.ctm_transform(0,0)).to eq([-10,10])
        expect(state.ctm_transform(0,1)).to eq([-11,10])
        expect(state.ctm_transform(1,0)).to eq([-10,11])
        expect(state.ctm_transform(1,1)).to eq([-11,11])
      end
    end
  end

  describe "#begin_text_object" do
    context "with an empty page" do
      let!(:state)  {PDF::Reader::PageState.new(page) }

      it "initialzes the text_matrix to ensure text is positioned at 0,0" do
        state.begin_text_object
        state.set_text_font_and_size(:Test, 12)

        expect(state.trm_transform(0,0)).to eq([0,0])
        expect(state.trm_transform(0,1)).to eq([0, 12])
        expect(state.trm_transform(1,0)).to eq([12, 0])
        expect(state.trm_transform(1,1)).to eq([12, 12])
      end
    end
  end

  describe "#move_text_position" do
    context "with an empty page" do
      let!(:state)  {PDF::Reader::PageState.new(page) }

      it "alters the text position" do
        state.begin_text_object
        state.set_text_font_and_size(:Test, 12)
        state.move_text_position(5, 10)

        # how the matrix is stored and multiplied is really an implementation
        # detail, so it's better to check the results indirectly via the API
        # external collaborators will use
        expect(state.trm_transform(0,0)).to eq([5,10])
        expect(state.trm_transform(0,1)).to eq([5, 22])
        expect(state.trm_transform(1,0)).to eq([17, 10])
        expect(state.trm_transform(1,1)).to eq([17, 22])
      end
    end
  end

  describe "#move_text_position_and_set_leading" do
    context "with an empty page" do
      let!(:state)  {PDF::Reader::PageState.new(page) }

      it "alters the text position" do
        state.begin_text_object
        state.set_text_font_and_size(:Test, 12)
        state.move_text_position_and_set_leading(5, 10)

        # how the matrix is stored and multiplied is really an implementation
        # detail, so it's better to check the results indirectly via the API
        # external collaborators will use
        expect(state.trm_transform(0,0)).to eq([5, 10])
        expect(state.trm_transform(0,1)).to eq([5, 22])
        expect(state.trm_transform(1,0)).to eq([17, 10])
        expect(state.trm_transform(1,1)).to eq([17, 22])
      end

      it "alters the text leading" do
        state.begin_text_object
        state.set_text_font_and_size(:Test, 12)
        state.move_text_position_and_set_leading(5, 10)

        expect(state.clone_state[:text_leading]).to eq(-10)
      end
    end
  end

  describe "#set_text_matrix_and_text_line_matrix" do
    context "with an empty page" do
      let!(:state)  {PDF::Reader::PageState.new(page) }

      it "alters the text position" do
        state.begin_text_object
        state.set_text_font_and_size(:Test, 12)
        state.set_text_matrix_and_text_line_matrix(1, 2, 3, 4, 5, 6)

        # how the matrix is stored and multiplied is really an implementation
        # detail, so it's better to check the results indirectly via the API
        # external collaborators will use
        expect(state.trm_transform(0,0)).to eq([5, 6])
        expect(state.trm_transform(0,1)).to eq([41, 54])
        expect(state.trm_transform(1,0)).to eq([17, 30])
        expect(state.trm_transform(1,1)).to eq([53.0, 78.0])
      end
    end
  end

  describe "#move_to_start_of_next_line" do
    context "with an empty page" do
      let!(:state)  {PDF::Reader::PageState.new(page) }

      it "alters the text position" do
        state.begin_text_object
        state.set_text_font_and_size(:Test, 12)
        state.set_text_leading(15)
        state.move_to_start_of_next_line

        # how the matrix is stored and multiplied is really an implementation
        # detail, so it's better to check the results indirectly via the API
        # external collaborators will use
        expect(state.trm_transform(0,0)).to eq([0, -15])
        expect(state.trm_transform(0,1)).to eq([0, -3])
        expect(state.trm_transform(1,0)).to eq([12, -15])
        expect(state.trm_transform(1,1)).to eq([12, -3])
      end
    end
  end

  describe "#move_to_next_line_and_show_text" do
    context "with an empty page" do
      let!(:state)  {PDF::Reader::PageState.new(page) }

      it "alters the text position" do
        state.begin_text_object
        state.set_text_font_and_size(:Test, 12)
        state.set_text_leading(15)
        state.move_to_next_line_and_show_text("Foo")

        # how the matrix is stored and multiplied is really an implementation
        # detail, so it's better to check the results indirectly via the API
        # external collaborators will use
        expect(state.trm_transform(0,0)).to eq([0, -15])
        expect(state.trm_transform(0,1)).to eq([0, -3])
        expect(state.trm_transform(1,0)).to eq([12, -15])
        expect(state.trm_transform(1,1)).to eq([12, -3])
      end
    end
  end

  describe "#move_to_next_line_and_show_text" do
    context "with an empty page" do
      let!(:state)  {PDF::Reader::PageState.new(page) }

      it "alters the text position" do
        state.begin_text_object
        state.set_text_font_and_size(:Test, 12)
        state.set_text_leading(15)
        state.move_to_next_line_and_show_text("Foo")

        # how the matrix is stored and multiplied is really an implementation
        # detail, so it's better to check the results indirectly via the API
        # external collaborators will use
        expect(state.trm_transform(0,0)).to eq([0, -15])
        expect(state.trm_transform(0,1)).to eq([0, -3])
        expect(state.trm_transform(1,0)).to eq([12, -15])
        expect(state.trm_transform(1,1)).to eq([12, -3])
      end
    end
  end

  describe "#set_spacing_next_line_show_text" do
    context "with an empty page" do
      let!(:state)  {PDF::Reader::PageState.new(page) }

      it "sets word spacing" do
        state.begin_text_object
        state.set_spacing_next_line_show_text(10, 20, "test")
        expect(state.clone_state[:word_spacing]).to eq(10)
      end

      it "sets character spacing" do
        state.begin_text_object
        state.set_spacing_next_line_show_text(10, 20, "test")
        expect(state.clone_state[:char_spacing]).to eq(20)
      end

      it "alters the text position" do
        state.begin_text_object
        state.set_text_font_and_size(:Test, 12)
        state.set_spacing_next_line_show_text(10, 20, "test")

        # how the matrix is stored and multiplied is really an implementation
        # detail, so it's better to check the results indirectly via the API
        # external collaborators will use
        expect(state.trm_transform(0,0)).to eq([0, 0])
        expect(state.trm_transform(0,1)).to eq([0, 12])
        expect(state.trm_transform(1,0)).to eq([12, 0])
        expect(state.trm_transform(1,1)).to eq([12, 12])
      end
    end
  end

  describe "#process_glyph_displacement" do
    context "when the current state places 12pt text at (40, 700)" do
      let!(:state)  {PDF::Reader::PageState.new(page) }

      before do
        state.begin_text_object
        state.set_text_font_and_size(:Test, 12)
        state.move_text_position(40, 700)

        # how the matrix is stored and multiplied is really an implementation
        # detail, so it's better to check the results indirectly via the API
        # external collaborators will use
        expect(state.trm_transform(0,0)).to eq([40, 700])
        expect(state.trm_transform(0,1)).to eq([40, 712])
        expect(state.trm_transform(1,0)).to eq([52, 700])
        expect(state.trm_transform(1,1)).to eq([52, 712])
      end

      context "2pt glyph width" do
        context "no character spacing" do
          context "no word spacing" do
            context "no kerning" do
              context "not a word boundary" do

                it "alters the text matrix" do
                  state.process_glyph_displacement(2, 0, false)

                  expect(state.trm_transform(0,0)).to eq([64, 700])
                  expect(state.trm_transform(0,1)).to eq([64, 712])
                  expect(state.trm_transform(1,0)).to eq([76, 700])
                  expect(state.trm_transform(1,1)).to eq([76, 712])
                end
              end
              context "a word boundary" do

                it "alters the text matrix" do
                  state.process_glyph_displacement(2, 0, true)

                  expect(state.trm_transform(0,0)).to eq([64, 700])
                  expect(state.trm_transform(0,1)).to eq([64, 712])
                  expect(state.trm_transform(1,0)).to eq([76, 700])
                  expect(state.trm_transform(1,1)).to eq([76, 712])
                end
              end
            end
            context "2pt kerning" do
              context "not a word boundary" do

                it "alters the text matrix" do
                  state.process_glyph_displacement(2, 2, false)

                  expect(state.trm_transform(0,0)).to eq([63.976, 700])
                  expect(state.trm_transform(0,1)).to eq([63.976, 712])
                  expect(state.trm_transform(1,0)).to eq([75.976, 700])
                  expect(state.trm_transform(1,1)).to eq([75.976, 712])
                end
              end
              context "a word boundary" do

                it "alters the text matrix" do
                  state.process_glyph_displacement(2, 2, true)

                  expect(state.trm_transform(0,0)).to eq([63.976, 700])
                  expect(state.trm_transform(0,1)).to eq([63.976, 712])
                  expect(state.trm_transform(1,0)).to eq([75.976, 700])
                  expect(state.trm_transform(1,1)).to eq([75.976, 712])
                end
              end
            end
          end
          context "with word spacing" do
            before do
              state.set_word_spacing(1)
            end
            context "no kerning" do
              context "not a word boundary" do

                it "alters the text matrix" do
                  state.process_glyph_displacement(2, 0, false)

                  expect(state.trm_transform(0,0)).to eq([64, 700])
                  expect(state.trm_transform(0,1)).to eq([64, 712])
                  expect(state.trm_transform(1,0)).to eq([76, 700])
                  expect(state.trm_transform(1,1)).to eq([76, 712])
                end
              end
              context "a word boundary" do

                it "alters the text matrix" do
                  state.process_glyph_displacement(2, 0, true)

                  expect(state.trm_transform(0,0)).to eq([65, 700])
                  expect(state.trm_transform(0,1)).to eq([65, 712])
                  expect(state.trm_transform(1,0)).to eq([77, 700])
                  expect(state.trm_transform(1,1)).to eq([77, 712])
                end
              end
            end
            context "2pt kerning" do
              context "not a word boundary" do

                it "alters the text matrix" do
                  state.process_glyph_displacement(2, 2, false)

                  expect(state.trm_transform(0,0)).to eq([63.976, 700])
                  expect(state.trm_transform(0,1)).to eq([63.976, 712])
                  expect(state.trm_transform(1,0)).to eq([75.976, 700])
                  expect(state.trm_transform(1,1)).to eq([75.976, 712])
                end
              end
              context "a word boundary" do

                it "alters the text matrix" do
                  state.process_glyph_displacement(2, 2, true)

                  expect(state.trm_transform(0,0)).to eq([64.976, 700])
                  expect(state.trm_transform(0,1)).to eq([64.976, 712])
                  expect(state.trm_transform(1,0)).to eq([76.976, 700])
                  expect(state.trm_transform(1,1)).to eq([76.976, 712])
                end
              end
            end
          end
        end
        context "with character spacing" do
          before do
            state.set_character_spacing(1)
          end
          context "no word spacing" do
            context "no kerning" do
              context "not a word boundary" do

                it "alters the text matrix" do
                  state.process_glyph_displacement(2, 0, false)

                  expect(state.trm_transform(0,0)).to eq([65, 700])
                  expect(state.trm_transform(0,1)).to eq([65, 712])
                  expect(state.trm_transform(1,0)).to eq([77, 700])
                  expect(state.trm_transform(1,1)).to eq([77, 712])
                end
              end
              context "a word boundary" do

                it "alters the text matrix" do
                  state.process_glyph_displacement(2, 0, true)

                  expect(state.trm_transform(0,0)).to eq([65, 700])
                  expect(state.trm_transform(0,1)).to eq([65, 712])
                  expect(state.trm_transform(1,0)).to eq([77, 700])
                  expect(state.trm_transform(1,1)).to eq([77, 712])
                end
              end
            end
            context "2pt kerning" do
              context "not a word boundary" do

                it "alters the text matrix" do
                  state.process_glyph_displacement(2, 2, false)

                  expect(state.trm_transform(0,0)).to eq([64.976, 700])
                  expect(state.trm_transform(0,1)).to eq([64.976, 712])
                  expect(state.trm_transform(1,0)).to eq([76.976, 700])
                  expect(state.trm_transform(1,1)).to eq([76.976, 712])
                end
              end
              context "a word boundary" do

                it "alters the text matrix" do
                  state.process_glyph_displacement(2, 2, true)

                  expect(state.trm_transform(0,0)).to eq([64.976, 700])
                  expect(state.trm_transform(0,1)).to eq([64.976, 712])
                  expect(state.trm_transform(1,0)).to eq([76.976, 700])
                  expect(state.trm_transform(1,1)).to eq([76.976, 712])
                end
              end
            end
          end
          context "with word spacing" do
            before do
              state.set_word_spacing(1)
            end
            context "no kerning" do
              context "not a word boundary" do

                it "alters the text matrix" do
                  state.process_glyph_displacement(2, 0, false)

                  expect(state.trm_transform(0,0)).to eq([65, 700])
                  expect(state.trm_transform(0,1)).to eq([65, 712])
                  expect(state.trm_transform(1,0)).to eq([77, 700])
                  expect(state.trm_transform(1,1)).to eq([77, 712])
                end
              end
              context "a word boundary" do

                it "alters the text matrix" do
                  state.process_glyph_displacement(2, 0, true)

                  expect(state.trm_transform(0,0)).to eq([66, 700])
                  expect(state.trm_transform(0,1)).to eq([66, 712])
                  expect(state.trm_transform(1,0)).to eq([78, 700])
                  expect(state.trm_transform(1,1)).to eq([78, 712])
                end
              end
            end
            context "2pt kerning" do
              context "not a word boundary" do

                it "alters the text matrix" do
                  state.process_glyph_displacement(2, 2, false)

                  expect(state.trm_transform(0,0)).to eq([64.976, 700])
                  expect(state.trm_transform(0,1)).to eq([64.976, 712])
                  expect(state.trm_transform(1,0)).to eq([76.976, 700])
                  expect(state.trm_transform(1,1)).to eq([76.976, 712])
                end
              end
              context "a word boundary" do

                it "alters the text matrix" do
                  state.process_glyph_displacement(2, 2, true)

                  expect(state.trm_transform(0,0)).to eq([65.976, 700])
                  expect(state.trm_transform(0,1)).to eq([65.976, 712])
                  expect(state.trm_transform(1,0)).to eq([77.976, 700])
                  expect(state.trm_transform(1,1)).to eq([77.976, 712])
                end
              end
            end
          end
        end
      end
    end
  end

end


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

namespace Crossfire
{
    public static class StartUp
    {
        public static void Main()
        {
            var dimentions = Console.ReadLine()
                .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(int.Parse)
                .ToArray();
            var matrix = new List<List<int>>();
            var fillCounter = 1;

            for (int row = 0; row < dimentions[0]; row++)
            {
                matrix.Add(new List<int>());

                for (int col = 0; col < dimentions[1]; col++)
                {
                    matrix[row].Add(fillCounter);
                    fillCounter++;
                }
            }

            var input = Console.ReadLine();

            while (input.ToLower() != "nuke it from orbit")
            {
                var command = input
                    .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(int.Parse)
                    .ToArray();

                DestroyCells(matrix, command);

                input = Console.ReadLine();
            }

            PrintResults(matrix);
        }

        private static void PrintResults(List<List<int>> matrix)
        {
            foreach (var row in matrix)
            {
                Console.WriteLine(string.Join(" ", row));
            }
        }

        private static void DestroyCells(List<List<int>> matrix, int[] command)
        {
            var shotRow = command[0];
            var shotCol = command[1];
            var shotStrenght = command[2];

            for (int rowIndex = shotRow - shotStrenght; rowIndex <= shotRow + shotStrenght; rowIndex++)
            {
                if (IsInMatrix(matrix, rowIndex, shotCol))
                {
                    matrix[rowIndex][shotCol] = -1;
                }
            }

            for (int colIndex = shotCol - shotStrenght; colIndex <= shotCol + shotStrenght; colIndex++)
            {
                if (IsInMatrix(matrix, shotRow, colIndex))
                {
                    matrix[shotRow][colIndex] = -1;
                }
            }
            RearangeCells(matrix);
        }

        private static bool IsInMatrix(List<List<int>> matrix, int rowIndex, int colIndex)
        {
            if (rowIndex >= 0 && rowIndex < matrix.Count &&
                colIndex >= 0 && colIndex < matrix[rowIndex].Count)
            {
                return true;
            }
            return false;
        }

        private static void RearangeCells(List<List<int>> matrix)
        {
            for (int row = matrix.Count - 1; row >= 0; row--)
            {
                for (int col = matrix[row].Count - 1; col >= 0; col--)
                {
                    if (matrix[row][col] == -1)
                    {
                        matrix[row].RemoveAt(col);
                    }
                }

                if (matrix[row].Count == 0)
                {
                    matrix.RemoveAt(row);
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * @package BLW\MIME
 * @version 1.0.0
 * @author Walter Otsyula <wotsyula@mast3rpee.tk>
 */
namespace BLW\Model\MIME;

use BLW\Model\InvalidArgumentException;

/**
 * Tests BLW Library MIME Contetn-Type header.
 * @package BLW\MIME
 * @author  mAsT3RpEE <wotsyula@mast3rpee.tk>
 *
 * @coversDefaultClass \BLW\Model\Mime\AcceptEncoding
 */
class AcceptEncodingTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \BLW\Model\MIME\AcceptEncoding
     */
    protected $Header = NULL;

    /**
     * @var \ReflectionProperty[]
     */
    protected $Properties = array();

    protected function setUp()
    {
        $this->Header      = new AcceptEncoding('compress, gzip; q=0.5');
        $this->Properties  = array(
             'Type'  => new \ReflectionProperty($this->Header, '_Type')
            ,'Value' => new \ReflectionProperty($this->Header, '_Value')
        );

        $this->Properties['Type']->setAccessible(true);
        $this->Properties['Value']->setAccessible(true);
    }

    protected function tearDown()
    {
        $this->Properties = NULL;
        $this->Header     = NULL;
    }

    public function generateValidTypes()
    {
        return array(
             array('gzip', 'gzip')
            ,array(';;gzip, ;;; unicode-1-1;;', 'gzip')
            ,array('"gzip"', 'gzip')
        );
    }

    public function generateInvalidTypes()
    {
        return array(
             array(false, '*')
            ,array(new \stdClass, '*')
            ,array(array(), '*')
        );
    }

    /**
     * @covers ::parseEncoding
     */
    public function test_parseEncoding()
    {
        # Valid type
        foreach ($this->generateValidTypes() as $Parameters) {
            list($Original, $Expected) = $Parameters;

            $this->assertEquals($Expected, $this->Header->parseEncoding($Original), 'AcceptEncoding::parseEncoding() returned an invalid format');
        }

        # Invalid type
        foreach ($this->generateInvalidTypes() as $Parameters) {
            list($Original, $Expected) = $Parameters;

            $this->assertEquals($Expected, $this->Header->parseEncoding($Original), 'AcceptEncoding::parseEncoding() returned an invalid format');
        }
    }

    /**
     * @depends test_parseEncoding
     * @covers ::__construct
     * @covers ::_combine
     */
    public function test_construct()
    {
        $this->Header = new AcceptEncoding('compress, gzip; q=0.5');

        # Check params
        $this->assertEquals('Accept-Encoding', $this->Properties['Type']->getValue($this->Header), 'AcceptEncoding::__construct() failed to set $_Type');
        $this->assertEquals('compress, gzip; q=0.5', $this->Properties['Value']->getValue($this->Header), 'AcceptEncoding::__construct() failed to set $_Value');

        # Invalid arguments
        try {
            new AcceptEncoding(NULL);
            $this->fail('Failed to generate exception with invalid parameters');
        } catch (InvalidArgumentException $e) {}
    }

    /**
     * @covers ::__toString
     */
    public function test_toString()
    {
        $this->assertEquals("Accept-Encoding: compress, gzip; q=0.5\r\n", @strval($this->Header), 'AcceptEncoding::__toSting() returned an invalid format');
    }
}


text:
Questions

    <questions-list items="$ctrl.questions"></questions-list>

    <debugger model="$ctrl.questions"></debugger>


text:
'use strict';
var uiFuncs = function() {}
uiFuncs.getTxData = function($scope) {
    return {
        to: $scope.tx.to,
        value: $scope.tx.value,
        unit: $scope.tx.unit,
        gasLimit: $scope.tx.gasLimit,
        data: $scope.tx.data,
        from: $scope.wallet.getAddressString(),
        privKey: $scope.wallet.privKey ? $scope.wallet.getPrivateKeyString() : '',
        path: $scope.wallet.getPath(),
        hwType: $scope.wallet.getHWType(),
        hwTransport: $scope.wallet.getHWTransport()
    };
}
uiFuncs.isTxDataValid = function(txData) {
    if (txData.to != "0xCONTRACT" && !ethFuncs.validateEtherAddress(txData.to)) throw globalFuncs.errorMsgs[5];
    else if (!globalFuncs.isNumeric(txData.value) || parseFloat(txData.value) < 0) throw globalFuncs.errorMsgs[7];
    else if (!globalFuncs.isNumeric(txData.gasLimit) || parseFloat(txData.gasLimit) <= 0) throw globalFuncs.errorMsgs[8];
    else if (!ethFuncs.validateHexString(txData.data)) throw globalFuncs.errorMsgs[9];
    if (txData.to == "0xCONTRACT") txData.to = '';
}
uiFuncs.signTxTrezor = function(rawTx, txData, callback) {
    var localCallback = function(result) {
        if (!result.success) {
            if (callback !== undefined) {
                callback({
                    isError: true,
                    error: result.error
                });
            }
            return;
        }

        rawTx.v = "0x" + ethFuncs.decimalToHex(result.v);
        rawTx.r = "0x" + result.r;
        rawTx.s = "0x" + result.s;
        var eTx = new ethUtil.Tx(rawTx);
        rawTx.rawTx = JSON.stringify(rawTx);
        rawTx.signedTx = '0x' + eTx.serialize().toString('hex');
        rawTx.isError = false;
        if (callback !== undefined) callback(rawTx);
    }

    TrezorConnect.signEthereumTx(
        txData.path,
        ethFuncs.getNakedAddress(rawTx.nonce),
        ethFuncs.getNakedAddress(rawTx.gasPrice),
        ethFuncs.getNakedAddress(rawTx.gasLimit),
        ethFuncs.getNakedAddress(rawTx.to),
        ethFuncs.getNakedAddress(rawTx.value),
        ethFuncs.getNakedAddress(rawTx.data),
        rawTx.chainId,
        localCallback
    );
}
uiFuncs.signTxLedger = function(app, eTx, rawTx, txData, old, callback) {
    eTx.raw[6] = Buffer.from([rawTx.chainId]);
    eTx.raw[7] = eTx.raw[8] = 0;
    var toHash = old ? eTx.raw.slice(0, 6) : eTx.raw;
    var txToSign = ethUtil.rlp.encode(toHash);
    var localCallback = function(result, error) {
        if (typeof error != "undefined") {
            error = error.errorCode ? u2f.getErrorByCode(error.errorCode) : error;
            if (callback !== undefined) callback({
                isError: true,
                error: error
            });
            return;
        }
        rawTx.v = "0x" + result['v'];
        rawTx.r = "0x" + result['r'];
        rawTx.s = "0x" + result['s'];
        eTx = new ethUtil.Tx(rawTx);
        rawTx.rawTx = JSON.stringify(rawTx);
        rawTx.signedTx = '0x' + eTx.serialize().toString('hex');
        rawTx.isError = false;
        if (callback !== undefined) callback(rawTx);
    }
    app.signTransaction(txData.path, txToSign.toString('hex'), localCallback);
}
uiFuncs.trezorUnlockCallback = function(txData, callback) {
    TrezorConnect.open(function(error) {
        if (error) {
            if (callback !== undefined) callback({
                isError: true,
                error: error
            });
        } else {
            txData.trezorUnlocked = true;
            uiFuncs.generateTx(txData, callback);
        }
    });
}
uiFuncs.generateTx = function(txData, callback) {
    if ((typeof txData.hwType != "undefined") && (txData.hwType == "trezor") && !txData.trezorUnlocked) {
        uiFuncs.trezorUnlockCallback(txData, callback);
        return;
    }
    try {
        uiFuncs.isTxDataValid(txData);
        var genTxWithInfo = function(data) {
            var rawTx = {
                nonce: ethFuncs.sanitizeHex(data.nonce),
                gasPrice: ethFuncs.sanitizeHex(ethFuncs.addTinyMoreToGas(data.gasprice)),
                gasLimit: ethFuncs.sanitizeHex(ethFuncs.decimalToHex(txData.gasLimit)),
                to: ethFuncs.sanitizeHex(txData.to),
                value: ethFuncs.sanitizeHex(ethFuncs.decimalToHex(etherUnits.toWei(txData.value, txData.unit))),
                data: ethFuncs.sanitizeHex(txData.data)
            }
            if (ajaxReq.eip155) rawTx.chainId = ajaxReq.chainId;
            var eTx = new ethUtil.Tx(rawTx);
            if ((typeof txData.hwType != "undefined") && (txData.hwType == "ledger")) {
                var app = new ledgerEth(txData.hwTransport);
                var EIP155Supported = false;
                var localCallback = function(result, error) {
                    if (typeof error != "undefined") {
                        if (callback !== undefined) callback({
                            isError: true,
                            error: error
                        });
                        return;
                    }
                    var splitVersion = result['version'].split('.');
                    if (parseInt(splitVersion[0]) > 1) {
                        EIP155Supported = true;
                    } else
                    if (parseInt(splitVersion[1]) > 0) {
                        EIP155Supported = true;
                    } else
                    if (parseInt(splitVersion[2]) > 2) {
                        EIP155Supported = true;
                    }
                    uiFuncs.signTxLedger(app, eTx, rawTx, txData, !EIP155Supported, callback);
                }
                app.getAppConfiguration(localCallback);
            } else if ((typeof txData.hwType != "undefined") && (txData.hwType == "trezor")) {
                uiFuncs.signTxTrezor(rawTx, txData, callback);
            } else {
                eTx.sign(new Buffer(txData.privKey, 'hex'));
                rawTx.rawTx = JSON.stringify(rawTx);
                rawTx.signedTx = '0x' + eTx.serialize().toString('hex');
                rawTx.isError = false;
                if (callback !== undefined) callback(rawTx);
            }
        }
        if (txData.nonce || txData.gasPrice) {
            var data = {
                nonce: txData.nonce,
                gasprice: txData.gasPrice
            }
            genTxWithInfo(data);
        } else {
            ajaxReq.getTransactionData(txData.from, function(data) {
                if (data.error && callback !== undefined) {
                    callback({
                        isError: true,
                        error: e
                    });
                    return;
                } else {
                    data = data.data;
                    genTxWithInfo(data);
                }
            });
        }
    } catch (e) {
        if (callback !== undefined) callback({
            isError: true,
            error: e
        });
    }
}
uiFuncs.sendTx = function(signedTx, callback) {
    ajaxReq.sendRawTx(signedTx, function(data) {
        var resp = {};
        if (data.error) {
            resp = {
                isError: true,
                error: data.msg
            };
        } else {
            resp = {
                isError: false,
                data: data.data
            };
        }
        if (callback !== undefined) callback(resp);
    });
}
uiFuncs.transferAllBalance = function(fromAdd, gasLimit, callback) {
    try {
        ajaxReq.getTransactionData(fromAdd, function(data) {
            if (data.error) throw data.msg;
            data = data.data;
            var gasPrice = new BigNumber(ethFuncs.sanitizeHex(ethFuncs.addTinyMoreToGas(data.gasprice))).times(gasLimit);
            var maxVal = new BigNumber(data.balance).minus(gasPrice);
            maxVal = etherUnits.toEther(maxVal, 'wei') < 0 ? 0 : etherUnits.toEther(maxVal, 'wei');
            if (callback !== undefined) callback({
                isError: false,
                unit: "ether",
                value: maxVal
            });
        });
    } catch (e) {
        if (callback !== undefined) callback({
            isError: true,
            error: e
        });
    }
}
uiFuncs.notifier = {
    show: false,
    close: function() {
        this.show = false;
        if (!this.scope.$$phase) this.scope.$apply()
    },
    open: function() {
        this.show = true;
        if (!this.scope.$$phase) this.scope.$apply();
    },
    class: '',
    message: '',
    timer: null,
    sce: null,
    scope: null,
    overrideMsg: function(msg){
        return globalFuncs.getEthNodeMsg(msg);
    },
    warning: function(msg) {
        this.setClassAndOpen("alert-warning", msg);
    },
    info: function(msg) {
        this.setClassAndOpen("", msg);
        this.setTimer();
    },
    danger: function(msg) {
        msg = this.overrideMsg(msg);
        this.setClassAndOpen("alert-danger", msg);
    },
    success: function(msg) {
        this.setClassAndOpen("alert-success", msg);
    },
    setClassAndOpen: function(_class, msg) {
        this.class = _class;
        this.message = msg.message ? this.sce.trustAsHtml(msg.message) : this.sce.trustAsHtml(msg);
        this.open();
    },
    setTimer: function() {
        var _this = this;
        clearTimeout(_this.timer);
        _this.timer = setTimeout(function() {
            _this.show = false;
            if (!_this.scope.$$phase) _this.scope.$apply();
        }, 5000);
    }
}
module.exports = uiFuncs;


text:
package org.apache.ode.bpel.rapi;

import java.util.List;

import javax.wsdl.Operation;

public interface PickReceiveModel extends ActivityModel {

	public boolean isCreateInstance();
	public void setCreateInstance(boolean createInstance);

	public List<OnAlarm> getOnAlarms();
	public static interface OnAlarm {
		public ActivityModel getActivity();
	}

	public List<OnMessage> getOnMessages();
	public static interface OnMessage {
		public PartnerLinkModel getPartnerLink();
		public ActivityModel getActivity();
		public Operation getOperation();
	}
}


text:
/* global describe, it, assert, expect */
'use strict';

// TESTS //

describe( 'data', function tests() {

	var el = document.querySelector( '#fixture' );

	it( 'should provide an attribute to set data', function test() {
		expect( el.data ).to.be.an( 'array' );
	});

	it( 'should emit an `error` if set to a non-array', function test( done ) {
		var data = el.data,
			values;

		values = [
			'beep',
			5,
			NaN,
			null,
			undefined,
			true,
			{},
			function(){}
		];

		el.addEventListener( 'err', onError );

		next();

		function next() {
			el.data = values.shift();
		}
		function onError( evt ) {
			assert.instanceOf( evt.detail, TypeError );
			if ( values.length ) {
				setTimeout( next, 0 );
				return;
			}
			setTimeout( end, 0 );
		}
		function end() {
			assert.deepEqual( el.data, data );
			el.removeEventListener( 'err', onError );
			done();
		}
	});

	it( 'should emit an `error` if a dataset is a non-array', function test( done ) {
		var data = el.data,
			values;

		values = [
			function(){},
			'beep',
			5,
			NaN,
			null,
			undefined,
			true,
			{}
		];

		el.addEventListener( 'err', onError );

		next();

		function next() {
			el.data[ 0 ] = values.shift();
		}
		function onError( evt ) {
			assert.instanceOf( evt.detail, TypeError );
			if ( values.length ) {
				setTimeout( next, 0 );
				return;
			}
			setTimeout( end, 0 );
		}
		function end() {
			assert.deepEqual( el.data, data );
			el.removeEventListener( 'err', onError );
			done();
		}
	});

	it( 'should emit a `changed` event when set to a new value', function test( done ) {
		el.addEventListener( 'changed', onChange );

		el.data = [[[new Date(),1]]];

		function onChange( evt ) {
			assert.isObject( evt.detail );
			assert.strictEqual( evt.detail.attr, 'data' );
			el.removeEventListener( 'changed', onChange );
			done();
		}
	});

	it( 'should emit a `data` event when set to a new value', function test( done ) {
		el.addEventListener( 'data', onChange );

		el.data = [[[new Date(),2]]];

		function onChange( evt ) {
			assert.isObject( evt.detail );
			assert.strictEqual( evt.detail.type, 'changed' );
			el.removeEventListener( 'data', onChange );
			done();
		}
	});

	it( 'should emit a `changed` event when a dataset is updated', function test( done ) {
		el.addEventListener( 'changed', onChange );

		el.data[ 0 ] = [[new Date(),3]];

		function onChange( evt ) {
			assert.isObject( evt.detail );
			assert.strictEqual( evt.detail.attr, 'data' );
			el.removeEventListener( 'changed', onChange );
			done();
		}
	});

	it( 'should emit a `data` event when a dataset is updated', function test( done ) {
		el.addEventListener( 'data', onChange );

		el.data[ 0 ] = [[new Date(),4]];

		function onChange( evt ) {
			assert.isObject( evt.detail );
			assert.strictEqual( evt.detail.type, 'changed' );
			el.removeEventListener( 'data', onChange );
			done();
		}
	});

	it( 'should remove any existing timeseries elements if set to an empty array' );

	it( 'should update the x-axis' );

	it( 'should update the y-axis' );

	it( 'should update the annotations, when x-min and -max change' );

	it( 'should reset the chart timeseries elements' );

});


text:
package com.jikexueyuan.ch03;

import java.util.Scanner;

public class Test04 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scanner= new Scanner(System.in);
		System.out.println("输入5分制分数");
		int score =scanner.nextInt();
		switch(score){
		case 5:
			System.out.println("优秀");
			break;
		case 4:
			System.out.println("良好");
			break;
		case 3:
			System.out.println("及格");
			break;
		case 2:
		case 1:
		case 0:
			System.out.println("不及格");
			break;
			default:
				System.out.println("输入的分数不是5分制的分数");
		}
	}

}


text:
import getpass
import pickle
class Email(object):
	"""Emmail class """
	_email_addr = None
	_pass = None

	def __init__(self,addr):
		self._email_addr = addr

	def set_email_addr(self, addr):
		self._email_addr = addr;

	def get_email_addr(self):
		return self._email_addr

	def set_pass(self):
		self._pass = getpass.getpass()

	def get_pass(self):
		return self._pass

	def __str__(self):
		return ("Email class")

class Spam(object):
	"""Spam class"""
	_id = None

	def __init__(self, id):
		self._id = id

	def set_id(self, id):
		self._id = id

	def get_id(self):
		return self._id

	def __str__(self):
		return ("Spam Class, id:"+self._id)

def save_instance(obj, file):
	pickle.dump(obj,file)

def load_instance(file):
	return pickle.load(file)

def print_list(cont):
	"""just for diagnosis"""
	for item in cont:
		if(item is Email):
			print(item.get_email_addr())
		else:
			print(item.get_id())


text:
package org.apache.ambari.server.state.alert;

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

import com.google.gson.annotations.SerializedName;

/**
 * Alert when the source type is defined as {@link SourceType#METRIC}
 * <p/>
 * Equality checking for instances of this class should be executed on every
 * member to ensure that reconciling stack differences is correct.
 */
public class MetricSource extends Source {

  @SerializedName("uri")
  private AlertUri uri = null;

  @SerializedName("jmx")
  private JmxInfo jmxInfo = null;

  @SerializedName("ganglia")
  private String gangliaInfo = null;

  /**
   * @return the jmx info, if this metric is jmx-based
   */
  public JmxInfo getJmxInfo() {
    return jmxInfo;
  }

  /**
   * @return the ganglia info, if this metric is ganglia-based
   */
  public String getGangliaInfo() {
    return gangliaInfo;
  }

  /**
   * @return the uri info, which may include port information
   */
  public AlertUri getUri() {
    return uri;
  }

  /**
   *
   */
  @Override
  public int hashCode() {
    final int prime = 31;
    int result = super.hashCode();
    result = prime * result
        + ((gangliaInfo == null) ? 0 : gangliaInfo.hashCode());
    result = prime * result + ((uri == null) ? 0 : uri.hashCode());
    result = prime * result + ((jmxInfo == null) ? 0 : jmxInfo.hashCode());

    return result;
  }

  /**
   *
   */
  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }

    if (!super.equals(obj)) {
      return false;
    }

    if (getClass() != obj.getClass()) {
      return false;
    }

    MetricSource other = (MetricSource) obj;
    if (gangliaInfo == null) {
      if (other.gangliaInfo != null) {
        return false;
      }
    } else if (!gangliaInfo.equals(other.gangliaInfo)) {
      return false;
    }

    if (uri == null) {
      if (other.uri != null) {
        return false;
      }
    } else if (!uri.equals(other.uri)) {
      return false;
    }

    if (jmxInfo == null) {
      if (other.jmxInfo != null) {
        return false;
      }
    } else if (!jmxInfo.equals(other.jmxInfo)) {
      return false;
    }

    return true;
  }

  /**
   * Represents the {@code jmx} element in a Metric alert.
   */
  public static class JmxInfo {
    @SerializedName("property_list")
    private List<String> propertyList;

    private String value;

    public List<String> getPropertyList() {
      return propertyList;
    }

    public String getValue() {
      return value;
    }

    @Override
    public boolean equals(Object object) {
      if (!JmxInfo.class.isInstance(object)) {
        return false;
      }

      JmxInfo other = (JmxInfo)object;

      List<String> list1 = new ArrayList<String>(propertyList);
      List<String> list2 = new ArrayList<String>(other.propertyList);

      if ((null == list1 && null != list2) || (null != list1 && null == list2)) {
        return false;
      }

      // !!! even if out of order, this is enough to fail
      return list1.equals(list2);

    }
  }
}


text:
package org.vinturo.api.sensor;

public abstract class AbstractActiveMotionSensor extends AbstractActiveSensor {

    public void fireMovementDetected() {

    }

}


text:
<plugin name='dataSource'>
  <type>org.grails.plugins.datasource.DataSourceGrailsPlugin</type>
</plugin>


text:
/*
* @trs JavaScript Library v0.1.3.1
* 2009-10-01
* By Eli Grey, http://eligrey.com
*
* Licensed under the MIT License
*   See LICENSE.md
*/

/* Requirements:
*   JavaScript 1.6 or higher
*   A json2.js-compatible JSON API:
*      JSON.parse and JSON.stringify
*/

/*! @source http://purl.eligrey.com/github/attrs/blob/master/@trs.js*/

(function (window) {
	// test for __noSuchMethod__ support
	try {
		({__noSuchMethod__:function () {}}).nonexistant_method();
	} catch (e) { return; }

	if (!("Element" in window) || !("JSON" in window) || !("parse" in JSON)|| !("stringify" in JSON))
		return;

	// in case __noSuchMethod__ is already defined
	var _noSuchMethod = Element.prototype.__noSuchMethod__;

	Element.prototype.__noSuchMethod__ = function (prop, args) {
		if (prop[0] !== "@") // not an @-property

			if (typeof _noSuchMethod === "function") // forward function call to original __noSuchMethod__
				return _noSuchMethod.apply(this, Array.prototype.slice.call(arguments));

			else
				throw new TypeError(prop + " is not a function");;

		var attr = prop.substr(1),
		dataAttr = (attr[0] === "$"),
		val;

		if (dataAttr) // prepend data- to attribute (has leading $)
			attr = "data-" + attr.substr(1);

		if (args.length > 0) {
			val = args[0];

			if (val === null) // pass null to remove attribute
				this.removeAttribute(attr);

			else if (dataAttr)
				this.setAttribute(attr, JSON.stringify(val));

			else
				this.setAttribute(attr, val);

			return this; // return element for chaining
		} else {
			val = this.getAttribute(attr);

			if (typeof val === null)
				return val;

			if (dataAttr && val !== "")
				val = JSON.parse(val);

			return val;
		}
	};
}(this));


text:
//
// Created by Mingkai Chen on 2016-08-29.
//

#ifndef DISABLE_TENSOR_MODULE_TESTS

#include <algorithm>

#include "gtest/gtest.h"
#include "fuzz.h"

#include "mocks/mock_tensor.h"

#ifndef DISABLE_TENSOR_TEST

static tensorshape random_partialshape (void)
{
	std::vector<size_t> rlist = random_def_shape().as_list();
	size_t nzeros = FUZZ::getInt(1, "nzeros", {1, 5})[0];
	for (size_t i = 0; i < nzeros; i++)
	{
		size_t zidx = FUZZ::getInt(1, "zidx", {0, rlist.size()})[0];
		rlist.insert(rlist.begin()+zidx, 0);
	}
	return tensorshape(rlist);
}

// cover scalar tensor constructor
TEST(TENSOR, ScalarConstructor_B000)
{
	FUZZ::reset_logger();
	std::vector<double> vals = FUZZ::getDouble(3, "vals");
	double value = vals[0];
	mock_tensor scalar(value);
	EXPECT_TRUE(scalar.clean());
	EXPECT_TRUE(scalar.is_alloc());
	EXPECT_EQ((size_t) sizeof(double), scalar.total_bytes());
	EXPECT_EQ(value, *scalar.rawptr());

	value = vals[1];
	mock_tensor scalar2(value);
	EXPECT_TRUE(scalar2.clean());
	EXPECT_TRUE(scalar2.is_alloc());
	EXPECT_EQ((size_t) sizeof(double), scalar2.total_bytes());
	EXPECT_EQ(value, *scalar2.rawptr());

	value = vals[2];
	mock_tensor scalar3(value);
	EXPECT_TRUE(scalar3.clean());
	EXPECT_TRUE(scalar3.is_alloc());
	EXPECT_EQ((size_t) sizeof(double), scalar3.total_bytes());
	EXPECT_EQ(value, *scalar3.rawptr());
}

// cover tensor
// default, shape constructors,
// is_alloc, total_bytes
TEST(TENSOR, Construct_B001)
{
	FUZZ::reset_logger();
	tensorshape pshape = random_partialshape();
	tensorshape cshape = random_def_shape();

	mock_tensor undef;
	mock_tensor incom(pshape);
	mock_tensor comp(cshape);

	EXPECT_TRUE(undef.clean());
	EXPECT_TRUE(incom.clean());
	EXPECT_TRUE(comp.clean());

	EXPECT_FALSE(undef.is_alloc());
	EXPECT_FALSE(incom.is_alloc());
	EXPECT_TRUE(comp.is_alloc());

	EXPECT_EQ((size_t) 0, undef.total_bytes());
	EXPECT_EQ((size_t) 0, incom.total_bytes());
	EXPECT_EQ((size_t) sizeof(double) * cshape.n_elems(),
		comp.total_bytes());
}

// cover tensor
// clone and assignment
TEST(TENSOR, Copy_B002)
{
	FUZZ::reset_logger();
	mock_tensor undefassign;
	mock_tensor scalarassign;
	mock_tensor incomassign;
	mock_tensor compassign;

	tensorshape pshape = random_partialshape();
	tensorshape cshape = random_def_shape();

	mock_tensor undef;
	mock_tensor scalar(FUZZ::getDouble(1, "scalar.data")[0]);
	mock_tensor incom(pshape);
	mock_tensor comp(cshape);

	mock_tensor* undefcpy = undef.clone();
	mock_tensor* scalarcpy = scalar.clone();
	mock_tensor* incomcpy = incom.clone();
	mock_tensor* compcpy = comp.clone();
	undefassign = undef;
	scalarassign = scalar;
	incomassign = incom;
	compassign = comp;

	EXPECT_FALSE(undefcpy->is_alloc());
	EXPECT_TRUE(scalarcpy->is_alloc());
	EXPECT_FALSE(incomcpy->is_alloc());
	EXPECT_TRUE(compcpy->is_alloc());
	EXPECT_FALSE(undefassign.is_alloc());
	EXPECT_TRUE(scalarassign.is_alloc());
	EXPECT_FALSE(incomassign.is_alloc());
	EXPECT_TRUE(compassign.is_alloc());

	EXPECT_TRUE(undefcpy->equal(undef));
	EXPECT_TRUE(scalarcpy->equal(scalar));
	EXPECT_TRUE(incomcpy->equal(incom));
	EXPECT_TRUE(compcpy->equal(comp));
	EXPECT_TRUE(undefassign.equal(undef));
	EXPECT_TRUE(scalarassign.equal(scalar));
	EXPECT_TRUE(incomassign.equal(incom));
	EXPECT_TRUE(compassign.equal(comp));

	delete undefcpy;
	delete scalarcpy;
	delete incomcpy;
	delete compcpy;
}

// cover tensor
// move constructor and assignment
TEST(TENSOR, Move_B002)
{
	FUZZ::reset_logger();
	mock_tensor scalarassign;
	mock_tensor compassign;

	tensorshape sshape(std::vector<size_t>{1});
	tensorshape cshape = random_def_shape();
	mock_tensor scalar(FUZZ::getDouble(1, "scalar.data")[0]);
	mock_tensor comp(cshape);

	double* scalarptr = scalar.rawptr();
	double* compptr = comp.rawptr();

	mock_tensor scalarmv(std::move(scalar));
	mock_tensor compmv(std::move(comp));

	EXPECT_TRUE(scalar.clean());
	EXPECT_TRUE(comp.clean());
	EXPECT_TRUE(scalarmv.clean());
	EXPECT_TRUE(compmv.clean());

	EXPECT_FALSE(scalar.is_alloc());
	EXPECT_FALSE(comp.is_alloc());
	EXPECT_EQ(scalarptr, scalarmv.rawptr());
	EXPECT_EQ(compptr, compmv.rawptr());
	EXPECT_TRUE(scalarmv.allocshape_is(sshape));
	EXPECT_TRUE(compmv.allocshape_is(cshape));

	scalarassign = std::move(scalarmv);
	compassign = std::move(compmv);

	EXPECT_TRUE(scalarmv.clean());
	EXPECT_TRUE(compmv.clean());
	EXPECT_TRUE(scalarassign.clean());
	EXPECT_TRUE(compassign.clean());

	EXPECT_FALSE(scalarmv.is_alloc());
	EXPECT_FALSE(compmv.is_alloc());
	EXPECT_EQ(scalarptr, scalarassign.rawptr());
	EXPECT_EQ(compptr, compassign.rawptr());
	EXPECT_TRUE(scalarassign.allocshape_is(sshape));
	EXPECT_TRUE(compassign.allocshape_is(cshape));
}

// cover tensor
// get_shape, n_elems, rank. dims
TEST(TENSOR, Shape_B003)
{
	FUZZ::reset_logger();
	tensorshape singular(std::vector<size_t>{1});
	tensorshape pshape = random_partialshape();
	tensorshape cshape = random_def_shape();

	mock_tensor undef;
	mock_tensor scalar(FUZZ::getDouble(1, "scalar.data")[0]);
	mock_tensor incom(pshape);
	mock_tensor comp(cshape);

	EXPECT_TRUE(tensorshape_equal(undef.get_shape(), {}));
	EXPECT_TRUE(tensorshape_equal(singular, scalar.get_shape()));
	EXPECT_TRUE(tensorshape_equal(pshape, incom.get_shape()));
	EXPECT_TRUE(tensorshape_equal(cshape, comp.get_shape()));

	EXPECT_EQ((size_t) 0, undef.n_elems());
	EXPECT_EQ((size_t) 1, scalar.n_elems());
	EXPECT_EQ((size_t) 0, incom.n_elems());
	EXPECT_EQ(cshape.n_elems(), comp.n_elems());

	EXPECT_EQ((size_t) 0, undef.rank());
	EXPECT_EQ((size_t) 1, scalar.rank());
	EXPECT_EQ(pshape.rank(), incom.rank());
	EXPECT_EQ(cshape.rank(), comp.rank());

	EXPECT_TRUE(undef.dims().empty());
	std::vector<size_t> sv = scalar.dims();
	ASSERT_EQ((size_t) 1, sv.size());
	EXPECT_EQ((size_t) 1, sv[0]);

	std::vector<size_t> expects = pshape.as_list();
	std::vector<size_t> expectc = cshape.as_list();
	EXPECT_TRUE(std::equal(expects.begin(), expects.end(), incom.dims().begin()));
	EXPECT_TRUE(std::equal(expectc.begin(), expectc.end(), comp.dims().begin()));
}

// cover tensor
// is_same_size
TEST(TENSOR, IsSameSize_B004)
{
	FUZZ::reset_logger();
	tensorshape cshape = random_def_shape();
	std::vector<size_t> cv = cshape.as_list();
	tensorshape ishape = make_incompatible(cv); // not same as cshape
	mock_tensor bad(ishape);
	mock_tensor undef;
	mock_tensor scalar(FUZZ::getDouble(1, "scalar.data")[0]);
	mock_tensor comp(cshape);

	{
		tensorshape pshape = make_partial(cv); // same as cshape
		mock_tensor pcom(pshape);
		// allowed compatible
		// pcom, undef are both unallocated
		EXPECT_FALSE(undef.is_alloc());
		EXPECT_FALSE(pcom.is_alloc());
		// undef is same as anything
		EXPECT_TRUE(undef.is_same_size(bad));
		EXPECT_TRUE(undef.is_same_size(comp));
		EXPECT_TRUE(undef.is_same_size(scalar));
		EXPECT_TRUE(undef.is_same_size(pcom));
		// pcom is same as comp, but not bad or scalar
		EXPECT_TRUE(pcom.is_same_size(comp));
		EXPECT_FALSE(pcom.is_same_size(bad));
		EXPECT_FALSE(pcom.is_same_size(scalar));
	}

	// trimmed compatible
	{
		// padd cv
		std::vector<size_t> npads = FUZZ::getInt(4, "npads", {3, 17});
		tensorshape p1 = padd(cv, npads[0], npads[1]); // same
		tensorshape p2 = padd(cv, npads[2], npads[3]); // same
		cv.push_back(2);
		tensorshape p3 = padd(cv, npads[2], npads[3]); // not same
		mock_tensor comp2(p1);
		mock_tensor comp3(p2);
		mock_tensor bad2(p3);

		EXPECT_TRUE(comp2.is_alloc());
		EXPECT_TRUE(comp3.is_alloc());
		EXPECT_TRUE(bad.is_alloc());

		EXPECT_TRUE(comp.is_same_size(comp2));
		EXPECT_TRUE(comp2.is_same_size(comp3));
		EXPECT_TRUE(comp.is_same_size(comp3));

		EXPECT_FALSE(comp.is_same_size(bad));
		EXPECT_FALSE(comp2.is_same_size(bad));
		EXPECT_FALSE(comp3.is_same_size(bad));

		EXPECT_FALSE(comp.is_same_size(bad2));
		EXPECT_FALSE(comp2.is_same_size(bad2));
		EXPECT_FALSE(comp3.is_same_size(bad2));
	}

}

// cover tensor
// is_compatible_with tensor
TEST(TENSOR, IsCompatibleWithTensor_B005)
{
	FUZZ::reset_logger();
	tensorshape cshape = random_def_shape();
	std::vector<size_t> cv = cshape.as_list();
	tensorshape ishape = make_incompatible(cv); // not same as cshape
	tensorshape pshape = make_partial(cv); // same as cshape
	mock_tensor undef;
	mock_tensor scalar(FUZZ::getDouble(1, "scalar.data")[0]);
	mock_tensor comp(cshape);
	mock_tensor pcom(pshape);
	mock_tensor bad(ishape);

	// undefined tensor is compatible with anything
	EXPECT_TRUE(undef.is_compatible_with(undef));
	EXPECT_TRUE(undef.is_compatible_with(scalar));
	EXPECT_TRUE(undef.is_compatible_with(comp));
	EXPECT_TRUE(undef.is_compatible_with(pcom));
	EXPECT_TRUE(undef.is_compatible_with(bad));

	EXPECT_TRUE(pcom.is_compatible_with(comp));
	EXPECT_TRUE(pcom.is_compatible_with(pcom));
	EXPECT_FALSE(pcom.is_compatible_with(bad));

	EXPECT_FALSE(bad.is_compatible_with(comp));
}

// cover tensor
// is_compatible_with vector
TEST(TENSOR, IsCompatibleWithVector_B006)
{
	FUZZ::reset_logger();
	tensorshape pshape = random_partialshape();
	tensorshape cshape = random_def_shape();

	mock_tensor undef;
	mock_tensor comp(cshape);
	mock_tensor pcom(pshape);

	std::vector<double> zerodata;
	size_t cp = cshape.n_elems();
	std::vector<double> lowerdata;
	if (cp < 3)
	{
		lowerdata = FUZZ::getDouble(1, "lowerdata if cp < 3");
	}
	else
	{
		lowerdata = FUZZ::getDouble(cp-FUZZ::getInt(1, "cp-this", {1, cp-1})[0], "lowerdata if cp >= 3");
	}
	std::vector<double> exactdata = FUZZ::getDouble(cp, "exact data");
	std::vector<double> upperdata = FUZZ::getDouble(cp+FUZZ::getInt(1, "cp+this", {1, cp-1})[0], "upperdata");

	EXPECT_TRUE(comp.is_compatible_with(exactdata));
	EXPECT_FALSE(comp.is_compatible_with(lowerdata));
	EXPECT_FALSE(comp.is_compatible_with(upperdata));

	EXPECT_TRUE(comp.is_loosely_compatible_with(exactdata));
	EXPECT_TRUE(comp.is_loosely_compatible_with(lowerdata));
	EXPECT_FALSE(comp.is_loosely_compatible_with(upperdata));

	size_t np = pshape.n_known();
	std::vector<double> lowerdata2;
	if (np < 3)
	{
		lowerdata2 = FUZZ::getDouble(1, "lowerdata2 if np < 3");
	}
	else
	{
		lowerdata2 = FUZZ::getDouble(np-FUZZ::getInt(1, "np-this", {1, np-1})[0], "lowerdata2 if np >= 3");
	}
	std::vector<double> exactdata2 = FUZZ::getDouble(np, "exactdata2");
	size_t mod = np*FUZZ::getInt(1, "mod=np*this", {2, 15})[0];
	std::vector<double> moddata = FUZZ::getDouble(mod, "moddata");
	std::vector<double> upperdata2 = FUZZ::getDouble(mod+1, "upperdata2");

	EXPECT_TRUE(pcom.is_compatible_with(exactdata2));
	EXPECT_TRUE(pcom.is_compatible_with(moddata));
	EXPECT_FALSE(pcom.is_compatible_with(lowerdata2));
	EXPECT_FALSE(pcom.is_compatible_with(upperdata2));

	EXPECT_TRUE(pcom.is_loosely_compatible_with(exactdata2));
	EXPECT_TRUE(pcom.is_loosely_compatible_with(moddata));
	EXPECT_TRUE(pcom.is_loosely_compatible_with(lowerdata2));
	EXPECT_TRUE(pcom.is_loosely_compatible_with(upperdata2));

	// undef is compatible with everything
	EXPECT_TRUE(undef.is_compatible_with(exactdata));
	EXPECT_TRUE(undef.is_compatible_with(exactdata2));
	EXPECT_TRUE(undef.is_compatible_with(lowerdata));
	EXPECT_TRUE(undef.is_compatible_with(lowerdata2));
	EXPECT_TRUE(undef.is_compatible_with(upperdata));
	EXPECT_TRUE(undef.is_compatible_with(upperdata2));
	EXPECT_TRUE(undef.is_compatible_with(moddata));

	EXPECT_TRUE(undef.is_loosely_compatible_with(exactdata));
	EXPECT_TRUE(undef.is_loosely_compatible_with(exactdata2));
	EXPECT_TRUE(undef.is_loosely_compatible_with(lowerdata));
	EXPECT_TRUE(undef.is_loosely_compatible_with(lowerdata2));
	EXPECT_TRUE(undef.is_loosely_compatible_with(upperdata));
	EXPECT_TRUE(undef.is_loosely_compatible_with(upperdata2));
	EXPECT_TRUE(undef.is_loosely_compatible_with(moddata));
}

// covers tensor
// guess_shape
TEST(TENSOR, GuessShape_B007)
{
	FUZZ::reset_logger();
	tensorshape pshape = random_partialshape();
	tensorshape cshape = random_def_shape();
	mock_tensor undef;
	mock_tensor comp(cshape);
	mock_tensor pcom(pshape);

	std::vector<double> zerodata;
	size_t cp = cshape.n_elems();
	std::vector<double> lowerdata;
	if (cp < 3)
	{
		lowerdata = FUZZ::getDouble(1, "lowerdata if cp < 3");
	}
	else
	{
		lowerdata = FUZZ::getDouble(cp-FUZZ::getInt(1, "cp-this", {1, cp-1})[0], "lowerdata if cp >= 3");
	}
	std::vector<double> exactdata = FUZZ::getDouble(cp, "exactdata");
	std::vector<double> upperdata = FUZZ::getDouble(cp+FUZZ::getInt(1, "cp+this", {1, cp-1})[0], "upperdata");

	// allowed are fully defined
	optional<tensorshape> cres = comp.guess_shape(exactdata);
	ASSERT_TRUE((bool)cres);
	EXPECT_TRUE(tensorshape_equal(cshape, *cres));
	EXPECT_FALSE((bool)comp.guess_shape(lowerdata));
	EXPECT_FALSE((bool)comp.guess_shape(upperdata));

	size_t np = pshape.n_known();
	std::vector<double> lowerdata2;
	if (np < 3)
	{
		lowerdata2 = FUZZ::getDouble(1, "lowerdata2 if np < 3");
	}
	else
	{
		lowerdata2 = FUZZ::getDouble(np-FUZZ::getInt(1, "np-this", {1, np-1})[0], "lowerdata2 if np >= 3");
	}
	std::vector<double> exactdata2 = FUZZ::getDouble(np, "exactdata2");
	size_t mod = np*FUZZ::getInt(1, "mod=np*this", {2, 15})[0];
	std::vector<double> moddata = FUZZ::getDouble(mod, "moddata");
	std::vector<double> upperdata2 = FUZZ::getDouble(mod+1, "upperdata2");

	std::vector<size_t> pv = pshape.as_list();
	size_t unknown = pv.size();
	for (size_t i = 0; i < pv.size(); i++)
	{
		if (0 == pv[i])
		{
			if (unknown > i)
			{
				unknown = i;
			}
			pv[i] = 1;
		}
	}
	std::vector<size_t> pv2 = pv;
	pv2[unknown] = ceil((double) moddata.size() / (double) np);
	// allowed are partially defined
	optional<tensorshape> pres = pcom.guess_shape(exactdata2);
	optional<tensorshape> pres2 = pcom.guess_shape(moddata);
	ASSERT_TRUE((bool)pres);
	ASSERT_TRUE((bool)pres2);
	EXPECT_TRUE(tensorshape_equal(*pres, pv));
	EXPECT_TRUE(tensorshape_equal(*pres2, pv2));
	EXPECT_FALSE((bool)pcom.guess_shape(lowerdata2));
	EXPECT_FALSE((bool)pcom.guess_shape(upperdata2));

	// allowed are undefined
	optional<tensorshape> ures = undef.guess_shape(exactdata);
	optional<tensorshape> ures2 = undef.guess_shape(exactdata2);
	optional<tensorshape> ures3 = undef.guess_shape(lowerdata);
	optional<tensorshape> ures4 = undef.guess_shape(lowerdata2);
	optional<tensorshape> ures5 = undef.guess_shape(upperdata);
	optional<tensorshape> ures6 = undef.guess_shape(upperdata2);
	optional<tensorshape> ures7 = undef.guess_shape(moddata);
	ASSERT_TRUE((bool)ures);
	ASSERT_TRUE((bool)ures2);
	ASSERT_TRUE((bool)ures3);
	ASSERT_TRUE((bool)ures4);
	ASSERT_TRUE((bool)ures5);
	ASSERT_TRUE((bool)ures6);
	ASSERT_TRUE((bool)ures7);
	EXPECT_TRUE(tensorshape_equal(*ures, std::vector<size_t>({exactdata.size()})));
	EXPECT_TRUE(tensorshape_equal(*ures2, std::vector<size_t>({exactdata2.size()})));
	EXPECT_TRUE(tensorshape_equal(*ures3, std::vector<size_t>({lowerdata.size()})));
	EXPECT_TRUE(tensorshape_equal(*ures4, std::vector<size_t>({lowerdata2.size()})));
	EXPECT_TRUE(tensorshape_equal(*ures5, std::vector<size_t>({upperdata.size()})));
	EXPECT_TRUE(tensorshape_equal(*ures6, std::vector<size_t>({upperdata2.size()})));
	EXPECT_TRUE(tensorshape_equal(*ures7, std::vector<size_t>({moddata.size()})));
}

// cover tensor
// get, expose
TEST(TENSOR, Get_B008)
{
	FUZZ::reset_logger();
	tensorshape pshape = random_partialshape();
	tensorshape cshape = random_def_shape();
	size_t crank = cshape.rank();
	size_t celem = cshape.n_elems();

	mock_tensor undef;
	mock_tensor pcom(pshape);
	mock_tensor comp(cshape);

	std::vector<double> cv = comp.expose(); // shouldn't die or throw
	// EXPECT_DEATH(undef.expose(), ".*");
	// EXPECT_DEATH(pcom.expose(), ".*");

	size_t pncoord = 1;
	if (crank > 2)
	{
		pncoord = FUZZ::getInt(1, "pncoord if crank > 3", {crank/2, crank-1})[0];
	}
	size_t cncoord = crank;
	size_t rncoord = FUZZ::getInt(1, "rncoord", {15, 127})[0];
	// c coordinates have rank exactly fitting cshape
	// p coordinates have rank less than rank of cshape
	// r coordinates are random coordinates
	std::vector<size_t> ccoord = FUZZ::getInt(cncoord, "ccoord");
	std::vector<size_t> pcoord = FUZZ::getInt(pncoord, "pcoord");
	std::vector<size_t> rcoord = FUZZ::getInt(rncoord, "rcoord");
	EXPECT_THROW(undef.get(pcoord), std::out_of_range);
	EXPECT_THROW(pcom.get(pcoord), std::out_of_range);
	EXPECT_THROW(undef.get(ccoord), std::out_of_range);
	EXPECT_THROW(pcom.get(ccoord), std::out_of_range);
	EXPECT_THROW(undef.get(rcoord), std::out_of_range);
	EXPECT_THROW(pcom.get(rcoord), std::out_of_range);

	std::vector<size_t> cs = cshape.as_list();
	size_t pcoordmax = 0, ccoordmax = 0, rcoordmax = 0;
	for (size_t i = 0, multiplier = 1, cn = cs.size(); i < cn; i++)
	{
		if (i < pncoord)
		{
			pcoordmax += pcoord[i] * multiplier;
		}
		if (i < rncoord)
		{
			rcoordmax += rcoord[i] * multiplier;
		}
		ccoordmax += ccoord[i] * multiplier;
		multiplier *= cs[i];
	}

	ASSERT_GT(celem, (size_t) 0);
	if (celem <= pcoordmax)
	{
		EXPECT_THROW(comp.get(pcoord), std::out_of_range);
	}
	else
	{
		ASSERT_GT(cv.size(), pcoordmax);
		EXPECT_EQ(cv[pcoordmax], comp.get(pcoord));
	}
	if (celem <= ccoordmax)
	{
		EXPECT_THROW(comp.get(ccoord), std::out_of_range);
	}
	else
	{
		ASSERT_GT(cv.size(), ccoordmax);
		EXPECT_EQ(cv[ccoordmax], comp.get(ccoord));
	}
	if (celem <= rcoordmax)
	{
		EXPECT_THROW(comp.get(rcoord), std::out_of_range);
	}
	else
	{
		ASSERT_GT(cv.size(), rcoordmax);
		EXPECT_EQ(cv[rcoordmax], comp.get(rcoord));
	}
}

// cover tensor
// set_shape, allocate shape
TEST(TENSOR, Reshape_B009)
{
	FUZZ::reset_logger();
	tensorshape pshape = random_partialshape();
	// make cshape a 2d shape to make testing easy
	// todo: improve to test higher dimensionality
	tensorshape cshape = FUZZ::getInt(2, "cshape", {11, 127});
	std::vector<size_t> cv = cshape.as_list();
	size_t cols = cv[0];
	size_t rows = cv[1];

	mock_tensor undef;
	mock_tensor undef2;
	mock_tensor pcom(pshape);
	mock_tensor comp(cshape);
	mock_tensor comp2(cshape);
	mock_tensor comp3(cshape);
	mock_tensor comp4(cshape);

	// undefined/part defined shape change
	undef.set_shape(pshape);
	EXPECT_TRUE(tensorshape_equal(undef.get_shape(), pshape));
	EXPECT_FALSE(undef.is_alloc());

	undef2.set_shape(cshape);
	pcom.set_shape(cshape);
	EXPECT_TRUE(tensorshape_equal(undef2.get_shape(), cshape));
	EXPECT_TRUE(tensorshape_equal(pcom.get_shape(), cshape));
	EXPECT_FALSE(undef2.is_alloc());
	EXPECT_FALSE(pcom.is_alloc());

	ASSERT_TRUE(comp.is_alloc());
	ASSERT_TRUE(comp2.is_alloc());
	ASSERT_TRUE(comp3.is_alloc());
	ASSERT_TRUE(comp4.is_alloc());
	// comps must be alloc otherwise doubleDArr will fail assertion it != et
	// meaning data size < cv.n_elems
	std::vector<std::vector<double> > ac1 = doubleDArr(comp.expose(), cv);
	std::vector<std::vector<double> > ac2 = doubleDArr(comp2.expose(), cv);
	std::vector<std::vector<double> > ac3 = doubleDArr(comp3.expose(), cv);
	std::vector<std::vector<double> > ac4 = doubleDArr(comp4.expose(), cv);
	// data expansion
	std::vector<size_t> cvexp = cv;
	cvexp[0]++;
	cvexp[1]++;
	comp.set_shape(cvexp);
	std::vector<std::vector<double> > resc1 = doubleDArr(comp.expose(), cvexp);
	for (size_t i = 0; i < rows; i++)
	{
		for (size_t j = 0; j < cols; j++)
		{
			EXPECT_EQ(ac1[i][j], resc1[i][j]);
		}
		// check the padding
		EXPECT_EQ((size_t) 0, resc1[i][cols]);
	}
	// check the padding
	for (size_t i = 0; i < cols+1; i++)
	{
		EXPECT_EQ((size_t) 0, resc1[rows][i]);
	}

	// data clipping
	std::vector<size_t> cvcli = cv;
	cvcli[0]--;
	cvcli[1]--;
	comp2.set_shape(cvcli);
	std::vector<std::vector<double> > resc2 = doubleDArr(comp2.expose(), cvcli);
	for (size_t i = 0; i < rows-1; i++)
	{
		for (size_t j = 0; j < cols-1; j++)
		{
			EXPECT_EQ(ac2[i][j], resc2[i][j]);
		}
	}

	// clip in one dimension, expand in another
	std::vector<size_t> cvexpcli = cv;
	std::vector<size_t> cvexpcli2 = cv;
	cvexpcli[0]++;
	cvexpcli[1]--;
	cvexpcli2[0]--;
	cvexpcli2[1]++;
	comp3.set_shape(cvexpcli);
	comp4.set_shape(cvexpcli2);
	std::vector<std::vector<double> > resc3 = doubleDArr(comp3.expose(), cvexpcli);
	std::vector<std::vector<double> > resc4 = doubleDArr(comp4.expose(), cvexpcli2);
	for (size_t i = 0; i < rows-1; i++)
	{
		for (size_t j = 0; j < cols; j++)
		{
			EXPECT_EQ(ac3[i][j], resc3[i][j]);
		}
		// check the padding
		EXPECT_EQ((size_t) 0, resc3[i][cols]);
	}
	for (size_t i = 0; i < rows; i++)
	{
		for (size_t j = 0; j < cols-1; j++)
		{
			EXPECT_EQ(ac4[i][j], resc4[i][j]);
		}
	}
	// check the padding
	for (size_t i = 0; i < cols-1; i++)
	{
		EXPECT_EQ((size_t) 0, resc4[rows][i]);
	}

	double* p = comp.rawptr();
	double* p2 = comp2.rawptr();
	tensorshape incmpshape = make_incompatible(comp.get_shape().as_list());
	comp.set_shape(incmpshape);
	comp2.set_shape(std::vector<size_t>{});
	ASSERT_NE(p, comp.rawptr());
	ASSERT_EQ(p2, comp2.rawptr());
}

// cover tensor
// default allocate, dependent on set shape
TEST(TENSOR, Allocate_B010)
{
	FUZZ::reset_logger();
	tensorshape cshape = random_def_shape();
	tensorshape pshape = random_partialshape();

	mock_tensor undef;
	mock_tensor pcom(pshape);
	mock_tensor comp(cshape);
	ASSERT_TRUE(comp.is_alloc());
	ASSERT_FALSE(pcom.is_alloc());
	ASSERT_FALSE(undef.is_alloc());
	double* orig = comp.rawptr(); // check to see if comp.rawptr changes later
	EXPECT_FALSE(undef.allocate());
	EXPECT_FALSE(pcom.allocate());
	EXPECT_FALSE(comp.allocate());
	// change allowed shape to defined shape, cshape
	undef.set_shape(cshape);
	pcom.set_shape(cshape);
	EXPECT_TRUE(undef.allocate());
	EXPECT_TRUE(pcom.allocate());
	EXPECT_EQ(orig, comp.rawptr());
}

// cover tensor
// deallocate
TEST(TENSOR, Dealloc_B011)
{
	FUZZ::reset_logger();
	tensorshape pshape = random_partialshape();
	tensorshape cshape = random_def_shape();

	mock_tensor undef;
	mock_tensor pcom(pshape);
	mock_tensor comp(cshape);

	EXPECT_FALSE(undef.is_alloc());
	EXPECT_FALSE(pcom.is_alloc());
	EXPECT_TRUE(comp.is_alloc());
	EXPECT_FALSE(undef.deallocate());
	EXPECT_FALSE(pcom.deallocate());
	EXPECT_TRUE(comp.deallocate());
	EXPECT_FALSE(comp.is_alloc());
}

// cover tensor
// allocate shape
TEST(TENSOR, AllocateShape_B012)
{
	FUZZ::reset_logger();
	tensorshape cshape = random_def_shape();
	std::vector<size_t> cv = cshape.as_list();
	tensorshape cshape2 = make_incompatible(cv);
	tensorshape pshape = make_partial(cv);
	tensorshape pshape2 = make_full_incomp(pshape.as_list(), cv);

	mock_tensor undef;
	mock_tensor pcom(pshape);
	mock_tensor comp(cshape);
	double* orig = comp.rawptr();

	EXPECT_FALSE(undef.allocate(pshape));
	EXPECT_TRUE(undef.allocate(cshape));
	EXPECT_FALSE(pcom.allocate(cshape2));
	EXPECT_TRUE(pcom.allocate(cshape));
	EXPECT_FALSE(comp.allocate(cshape));
	EXPECT_FALSE(comp.allocate(cshape2));
	EXPECT_FALSE(comp.allocate(pshape));
	EXPECT_EQ(orig, comp.rawptr());

	EXPECT_TRUE(tensorshape_equal(cshape, undef.get_shape()));
	EXPECT_TRUE(tensorshape_equal(cshape, pcom.get_shape()));
	EXPECT_TRUE(tensorshape_equal(cshape, comp.get_shape()));

	// they're all allocated now
	EXPECT_TRUE(undef.is_alloc());
	EXPECT_TRUE(pcom.is_alloc());
	EXPECT_TRUE(comp.is_alloc());

	ASSERT_TRUE(pcom.allocate(pshape2));
	EXPECT_NE(orig, pcom.rawptr());
}

// cover tensor
// copy_from
TEST(TENSOR, CopyWithShape_B013)
{
	FUZZ::reset_logger();
	tensorshape pshape = random_partialshape();
	tensorshape cshape = random_def_shape();
	tensorshape cshape2 = random_def_shape();
	tensorshape cshape3 = random_def_shape();

	size_t n1 = cshape.n_elems();
	std::vector<double> rawdata1 = FUZZ::getDouble(n1, "rawdata1");
	size_t n2 = cshape2.n_elems();
	std::vector<double> rawdata2 = FUZZ::getDouble(n2, "rawdata2");
	mock_tensor undef;
	mock_tensor pcom(pshape);
	mock_tensor comp(cshape, rawdata1);
	mock_tensor comp2(cshape2, rawdata2);
	double* orig = comp.rawptr();
	double* orig2 = comp2.rawptr();
	std::vector<double> compdata = comp.expose();
	std::vector<double> compdata2 = comp2.expose();

	// copying from unallocated
	EXPECT_FALSE(pcom.copy_from(undef, cshape));
	EXPECT_FALSE(undef.copy_from(pcom, cshape));
	EXPECT_FALSE(pcom.is_alloc());
	EXPECT_FALSE(undef.is_alloc());

	EXPECT_TRUE(undef.copy_from(comp, cshape3));
	EXPECT_TRUE(pcom.copy_from(comp2, cshape3));

	EXPECT_TRUE(comp.copy_from(comp2, cshape3));
	EXPECT_TRUE(comp2.copy_from(comp2, cshape3)); // copy from self

	// pointers are now different
	EXPECT_NE(orig, comp.rawptr());
	EXPECT_NE(orig2, comp2.rawptr());

	EXPECT_TRUE(tensorshape_equal(cshape3, undef.get_shape()));
	EXPECT_TRUE(tensorshape_equal(cshape3, pcom.get_shape()));
	EXPECT_TRUE(tensorshape_equal(cshape3, comp.get_shape()));
	EXPECT_TRUE(tensorshape_equal(cshape3, comp2.get_shape()));

	std::vector<double> undefdata = undef.expose();
	std::vector<double> pdefdata = pcom.expose();

	std::vector<size_t> c1list = cshape.as_list();
	std::vector<size_t> c2list = cshape2.as_list();
	std::vector<size_t> c3list = cshape3.as_list();

	// undef fitted with comp and cshape3
	for (size_t i = 0, n = cshape.n_elems(); i < n; i++)
	{
		std::vector<size_t> incoord = cshape.coordinate_from_idx(i);
		bool b = true;
		for (size_t j = 0, o = incoord.size(); j < o && b; j++)
		{
			if (j >= c3list.size())
			{
				b = incoord[j] == 0;
			}
			else
			{
				b = incoord[j] < c3list[j];
			}
		}
		if (b)
		{
			size_t outidx = cshape3.flat_idx(incoord);
			EXPECT_EQ(compdata[i], undefdata[outidx]);
		}
	}
	// pdefdata fitted with comp2 and cshape 3
	for (size_t i = 0, n = cshape2.n_elems(); i < n; i++)
	{
		std::vector<size_t> incoord = cshape2.coordinate_from_idx(i);
		bool b = true;
		for (size_t j = 0, o = incoord.size(); j < o && b; j++)
		{
			if (j >= c3list.size())
			{
				b = incoord[j] == 0;
			}
			else
			{
				b = incoord[j] < c3list[j];
			}
		}
		if (b)
		{
			size_t outidx = cshape3.flat_idx(incoord);
			EXPECT_EQ(compdata2[i], pdefdata[outidx]);
		}
	}
}

// cover tensor
// from_proto
TEST(TENSOR, DISABLED_FromProto_B014)
{
	// should allocate the tensor
	// data and shape are identical to ad hoc values
}

#endif /* DISABLE_TENSOR_TEST */

#endif /* DISABLE_TENSOR_MODULE_TESTS */


text:
define(function(require) {
	//var $ = require("jquery");
	//var Barcode = require("$UI/system/components/justep/barcode/barcodeImage");
	var justep = require("$UI/system/lib/justep");
	var Model = function() {
		this.callParent();
	};
	Model.prototype.backBtn = function(event){
		justep.Portal.closeWindow();
	};
	return Model;
});


text:
"""Constants for Owlet component."""
SENSOR_OXYGEN_LEVEL = "oxygen_level"
SENSOR_HEART_RATE = "heart_rate"

SENSOR_BASE_STATION = "base_station_on"
SENSOR_MOVEMENT = "movement"


text:
import cairo
from .utils import hex_to_rgba, parse_unit

def parse_size(size):
    """take a size as str (es: 14px), return its value in px/pt as int
    """
    if hasattr(size, 'isdigit'):
        if size.isdigit():
            return int(size)
        return parse_unit(size[:-2], size[-2:])
    return size

def parse_size_shorthand(shorthand):
    tokens = shorthand.split()

    l = len(tokens)
    if l == 1:
        return {'top': parse_size(tokens[0]), 'right': parse_size(tokens[0]), 'bottom': parse_size(tokens[0]), 'left': parse_size(tokens[0])}
    if l == 2:
        return {'top': parse_size(tokens[0]), 'right': parse_size(tokens[1]), 'bottom': parse_size(tokens[0]), 'left': parse_size(tokens[1])}

    return {'top': parse_size(tokens[0]), 'right': parse_size(tokens[1]), 'bottom': parse_size(tokens[2]), 'left': parse_size(tokens[3])}

def hex_to_cairo(value, alpha=1.0):
    value = hex_to_rgba(value, alpha)
    rgb = [v / 255.0 for v in value[:3]]
    rgb.append(value[-1])
    return tuple(rgb)

class PDFGridder(object):
    def __init__(self, grid):
        self.grid = grid
        self.paper = {
            'width': str(grid.width) + grid.width_unit,
            'height': str(grid.height) + grid.height_unit,
        }
        self.columns = {
            'count': grid.columns,
            'color': grid.columns_color,
            'opacity': grid.columns_opacity,
            'gutter': grid.columns_gutter_str()
        }
        self.baseline = {
            'distance': str(grid.baseline) + grid.baseline_unit,
            'color': grid.baseline_color,
            'opacity': grid.baseline_opacity,
        }
        self.margin = grid.margins()
        self.margin_size = parse_size_shorthand(self.margin)
        self.is_spread = grid.is_spread

        self.rows = {
            'count': 0,
            'gutter': 0,
            'color': '#ccc',
            'opacity': 0.5
        }

    def draw_cols(self, bottom, w):
        cols = self.columns['count']
        if cols > 0:
            cols_gutter_size = parse_size(self.columns['gutter'])
            cols_width = (w / cols) - cols_gutter_size + (cols_gutter_size / cols) - (self.margin_size['left'] / cols) - (self.margin_size['right'] / cols)
            cols_offset = cols_width + cols_gutter_size
            cols_color = hex_to_cairo(self.columns['color'], self.columns['opacity'])

            for i in xrange(cols):
                self.ctx.rectangle(i * cols_offset + self.margin_size['left'], 0, cols_width, bottom)
            self.ctx.set_source_rgba(*cols_color)  # Solid color
            self.ctx.fill()

    def draw_rows(self, rows, h):
        #rows
        rows_count = rows['count']
        if rows_count:
            rows_gutter_size = parse_size(rows['gutter'])
            rows_color = hex_to_cairo(rows['color'], rows['opacity'])
            rows_height = (h / rows_count) - rows_gutter_size + (rows_gutter_size / rows_count) - (self.margin_size['top'] / rows_count) - (self.margin_size['bottom'] / rows_count)
            rows_offset = rows_height + rows_gutter_size
            for i in xrange(rows_count):
                self.ctx.rectangle(
                    self.margin_size['left'],
                    i * rows_offset,
                    rows_height,
                    self.margin_size['right']
                )
            self.ctx.set_source_rgba(*rows_color)  # Solid color
            self.ctx.fill()

    def draw_baselines(self, distance, w, bottom, lines_color):
        base_offset = distance
        while base_offset < bottom:
            self.ctx.move_to(self.margin_size['left'], base_offset)
            self.ctx.line_to(w - self.margin_size['right'], base_offset)
            base_offset = base_offset + distance
        self.ctx.set_source_rgba(*lines_color)  # Solid color
        self.ctx.set_line_width(0.25)
        self.ctx.stroke()

    def build_page(self, surface, h_flip=False):
        w, h = parse_size(self.paper['width']), parse_size(self.paper['height'])

        if h_flip:
            self.margin_size['left'], self.margin_size['right'] = self.margin_size['right'], self.margin_size['left']

        self.ctx = cairo.Context(surface)

        #ctx.scale (w/1.0, h/1.0) # Normalizing the canvas
        self.ctx.translate(0, self.margin_size['top'])
        bottom = h - self.margin_size['bottom'] - self.margin_size['top']

        self.draw_cols(bottom, w)
        self.draw_rows(self.rows, h)

        #baseline
        try:
            lines_color = hex_to_cairo(self.baseline['color'], self.baseline['opacity'])
        except ValueError:
            lines_color = None

        distance = parse_size(self.baseline['distance'])
        if distance > 0 and lines_color is not None:
            self.draw_baselines(distance, w, bottom, lines_color)

        return self.ctx

    def build(self, output='output.pdf'):
        w, h = parse_size(self.paper['width']), parse_size(self.paper['height'])

        surface = cairo.PDFSurface(output, w, h)
        self.build_page(surface=surface)
        surface.show_page()
        if self.is_spread:
            self.build_page(surface=surface, h_flip=True)
            surface.show_page()

        surface.finish()

        return output


text:
#define DT_FLASH_DEV_NAME   DT_INST_0_ZEPHYR_NATIVE_POSIX_FLASH_CONTROLLER_LABEL
#define DT_UART_0_DEV_NAME  DT_ZEPHYR_NATIVE_POSIX_UART_1_LABEL


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ChangeListManager">
    <list default="true" id="3a9c99e4-ac79-436b-ba27-3920e0da1f43" name="Default" comment="">
      <change type="MODIFICATION" beforePath="$PROJECT_DIR$/../JAYSON/Classes/JAYSON.swift" afterPath="$PROJECT_DIR$/../JAYSON/Classes/JAYSON.swift" />
    </list>
    <option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
    <option name="TRACKING_ENABLED" value="true" />
    <option name="SHOW_DIALOG" value="false" />
    <option name="HIGHLIGHT_CONFLICTS" value="true" />
    <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
    <option name="LAST_RESOLUTION" value="IGNORE" />
  </component>
  <component name="ExecutionTargetManager" SELECTED_TARGET="iphoneos" />
  <component name="FileEditorManager">
    <leaf>
      <file leaf-file-name="ViewController.swift" pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/JAYSON/ViewController.swift">
          <provider selected="true" editor-type-id="text-editor">
            <state relative-caret-position="539">
              <caret line="158" column="8" lean-forward="false" selection-start-line="158" selection-start-column="8" selection-end-line="158" selection-end-column="8" />
              <folding>
                <marker date="1497045384716" expanded="true" signature="222:5090" ph="{...}" />
                <marker date="1497045384716" expanded="true" signature="257:2000" ph="{...}" />
                <marker date="1497045384716" expanded="true" signature="2027:2141" ph="{...}" />
                <marker date="1497045384716" expanded="true" signature="2195:3613" ph="{...}" />
                <marker date="1497045384716" expanded="true" signature="3658:3764" ph="{...}" />
                <marker date="1497045384716" expanded="true" signature="3815:5088" ph="{...}" />
              </folding>
            </state>
          </provider>
        </entry>
      </file>
      <file leaf-file-name="JAYSON.swift" pinned="false" current-in-tab="true">
        <entry file="file://$PROJECT_DIR$/../JAYSON/Classes/JAYSON.swift">
          <provider selected="true" editor-type-id="text-editor">
            <state relative-caret-position="761">
              <caret line="365" column="9" lean-forward="false" selection-start-line="365" selection-start-column="9" selection-end-line="365" selection-end-column="9" />
              <folding />
            </state>
          </provider>
        </entry>
      </file>
    </leaf>
  </component>
  <component name="FindInProjectRecents">
    <findStrings>
      <find>if case</find>
      <find>if case JSONK</find>
      <find>contex</find>
      <find>context</find>
      <find>pathtocre</find>
      <find>mutatingPath</find>
      <find>eva</find>
    </findStrings>
  </component>
  <component name="Git.Settings">
    <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$/.." />
  </component>
  <component name="IdeDocumentHistory">
    <option name="CHANGED_PATHS">
      <list>
        <option value="$PROJECT_DIR$/../JAYSON/Classes/JAYSON.swift" />
      </list>
    </option>
  </component>
  <component name="JsBuildToolGruntFileManager" detection-done="true" sorting="DEFINITION_ORDER" />
  <component name="JsBuildToolPackageJson" detection-done="true" sorting="DEFINITION_ORDER" />
  <component name="JsGulpfileManager">
    <detection-done>true</detection-done>
    <sorting>DEFINITION_ORDER</sorting>
  </component>
  <component name="ProjectFrameBounds">
    <option name="y" value="23" />
    <option name="width" value="1680" />
    <option name="height" value="1023" />
  </component>
  <component name="ProjectLevelVcsManager" settingsEditedManually="true" />
  <component name="ProjectView">
    <navigator currentView="ProjectPane" proportions="" version="1">
      <flattenPackages />
      <showMembers />
      <showModules />
      <showLibraryContents />
      <hideEmptyPackages />
      <abbreviatePackageNames />
      <autoscrollToSource />
      <autoscrollFromSource />
      <sortByType />
      <manualOrder />
      <foldersAlwaysOnTop value="true" />
    </navigator>
    <panes>
      <pane id="ProjectPane">
        <subPane>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" />
              <option name="myItemType" value="com.jetbrains.cidr.projectView.XcodeRootNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="Pods" />
              <option name="myItemType" value="com.jetbrains.cidr.projectView.XcodeProjectNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" />
              <option name="myItemType" value="com.jetbrains.cidr.projectView.XcodeRootNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="Pods" />
              <option name="myItemType" value="com.jetbrains.cidr.projectView.XcodeProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="Development Pods" />
              <option name="myItemType" value="com.jetbrains.cidr.projectView.XcodeViewNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="JAYSON" />
              <option name="myItemType" value="com.jetbrains.cidr.projectView.XcodeViewNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" />
              <option name="myItemType" value="com.jetbrains.cidr.projectView.XcodeRootNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="Pods" />
              <option name="myItemType" value="com.jetbrains.cidr.projectView.XcodeProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="Development Pods" />
              <option name="myItemType" value="com.jetbrains.cidr.projectView.XcodeViewNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="JAYSON" />
              <option name="myItemType" value="com.jetbrains.cidr.projectView.XcodeViewNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="JAYSON" />
              <option name="myItemType" value="com.jetbrains.cidr.projectView.XcodeViewNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="Classes" />
              <option name="myItemType" value="com.jetbrains.cidr.projectView.XcodeViewNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" />
              <option name="myItemType" value="com.jetbrains.cidr.projectView.XcodeRootNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="JAYSON" />
              <option name="myItemType" value="com.jetbrains.cidr.projectView.XcodeProjectNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" />
              <option name="myItemType" value="com.jetbrains.cidr.projectView.XcodeRootNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="JAYSON" />
              <option name="myItemType" value="com.jetbrains.cidr.projectView.XcodeProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="Pods" />
              <option name="myItemType" value="com.jetbrains.cidr.projectView.XcodeViewNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" />
              <option name="myItemType" value="com.jetbrains.cidr.projectView.XcodeRootNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="JAYSON" />
              <option name="myItemType" value="com.jetbrains.cidr.projectView.XcodeProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="Example for JAYSON" />
              <option name="myItemType" value="com.jetbrains.cidr.projectView.XcodeViewNode" />
            </PATH_ELEMENT>
          </PATH>
        </subPane>
      </pane>
      <pane id="Cidr.FilesView" />
    </panes>
  </component>
  <component name="PropertiesComponent">
    <property name="WebServerToolWindowFactoryState" value="false" />
    <property name="last_opened_file_path" value="$PROJECT_DIR$/JAYSON.xcworkspace" />
  </component>
  <component name="RunDashboard">
    <option name="ruleStates">
      <list>
        <RuleState>
          <option name="name" value="ConfigurationTypeDashboardGroupingRule" />
        </RuleState>
        <RuleState>
          <option name="name" value="StatusDashboardGroupingRule" />
        </RuleState>
      </list>
    </option>
  </component>
  <component name="RunManager" selected="Application.JAYSON-Example">
    <configuration default="true" type="AppleRunConfiguration" factoryName="Application" PASS_PARENT_ENVS_2="true" MAKE_ACTIVE="TRUE">
      <envs />
      <EXTENSION ID="org.jetbrains.appcode.reveal.RevealRunConfigurationExtension">
        <REVEAL_SETTINGS autoInject="false" autoInstall="true" askToEnableAutoInstall="true" />
      </EXTENSION>
      <method />
    </configuration>
    <list size="1">
      <item index="0" class="java.lang.String" itemvalue="Application.JAYSON-Example" />
    </list>
  </component>
  <component name="ShelveChangesManager" show_recycled="false">
    <option name="remove_strategy" value="false" />
  </component>
  <component name="TaskManager">
    <task active="true" id="Default" summary="Default task">
      <changelist id="3a9c99e4-ac79-436b-ba27-3920e0da1f43" name="Default" comment="" />
      <created>1497031561434</created>
      <option name="number" value="Default" />
      <option name="presentableId" value="Default" />
      <updated>1497031561434</updated>
      <workItem from="1497031563190" duration="8060000" />
    </task>
    <servers />
  </component>
  <component name="TimeTrackingManager">
    <option name="totallyTimeSpent" value="8060000" />
  </component>
  <component name="ToolWindowManager">
    <frame x="0" y="23" width="1680" height="1023" extended-state="6" />
    <editor active="true" />
    <layout>
      <window_info id="Designer" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.25274727" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
      <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
      <window_info id="Palette	" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="true" content_ui="tabs" />
      <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
      <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
      <window_info id="Structure" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.17704518" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
      <window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
      <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
      <window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="1" side_tool="true" content_ui="tabs" />
      <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
      <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="3" side_tool="false" content_ui="combo" />
      <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
      <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
    </layout>
  </component>
  <component name="TypeScriptGeneratedFilesManager">
    <option name="processedProjectFiles" value="true" />
  </component>
  <component name="VcsContentAnnotationSettings">
    <option name="myLimit" value="2678400000" />
  </component>
  <component name="XDebuggerManager">
    <breakpoint-manager />
    <watches-manager />
  </component>
  <component name="editorHistoryManager">
    <entry file="file://$PROJECT_DIR$/JAYSON/ViewController.swift">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="539">
          <caret line="158" column="8" lean-forward="false" selection-start-line="158" selection-start-column="8" selection-end-line="158" selection-end-column="8" />
          <folding>
            <marker date="1497045384716" expanded="true" signature="222:5090" ph="{...}" />
            <marker date="1497045384716" expanded="true" signature="257:2000" ph="{...}" />
            <marker date="1497045384716" expanded="true" signature="2027:2141" ph="{...}" />
            <marker date="1497045384716" expanded="true" signature="2195:3613" ph="{...}" />
            <marker date="1497045384716" expanded="true" signature="3658:3764" ph="{...}" />
            <marker date="1497045384716" expanded="true" signature="3815:5088" ph="{...}" />
          </folding>
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/../JAYSON/Classes/JAYSON.swift">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="761">
          <caret line="365" column="9" lean-forward="false" selection-start-line="365" selection-start-column="9" selection-end-line="365" selection-end-column="9" />
          <folding />
        </state>
      </provider>
    </entry>
  </component>
</project>


text:
ti_path="../topic_interpretability" #topic_interpretability path
topic_dir="example_data"
svm_dir="example_results/svm" #path to store svm files
wordcount_file="example_results/wordcount.txt"
output_pickle="example_results/wi.pickle"

rm -rf $output_pickle 2>/dev/null

for x in `seq 5 5 20`
do
    echo "Processing top-N = $x..."

    #generate the svm input files
    echo -e "\tGenerating SVM input..."
    rm -rf $svm_dir 2>/dev/null
    mkdir -p $svm_dir
    python $ti_path/GenSVMInput.py $topic_dir/$x.topics-with-intruder.txt \
        $topic_dir/$x.intruder.txt npmi $wordcount_file > $svm_dir/orig.dat

    #split the data into ten partitions (for ten-fold cross validations)
    echo -e "\tSplitting the SVM input ten partitions..."
    python $ti_path/SplitSVM.py $svm_dir < $svm_dir/orig.dat

    #start svm
    echo -e "\tStarting SVM..."
    for i in `seq 0 9`
    do
        $ti_path/svm_rank/svm_rank_learn -c 0.01 $svm_dir/train.dat.$i \
            $svm_dir/model.dat.$i 1>/dev/null
        $ti_path/svm_rank/svm_rank_classify $svm_dir/test.dat.$i $svm_dir/model.dat.$i \
            $svm_dir/predictions.$i 1>/dev/null
    done

    for i in `seq 0 9`
    do
        cat $svm_dir/test.dat.$i >> $svm_dir/test.dat
        cat $svm_dir/predictions.$i >> $svm_dir/predictions
    done

    #compute the model precision
    echo -e "\tComputing the model precision...\n"
    python ComputePrecision.py $topic_dir/$x.topics-with-intruder.txt $svm_dir/test.dat \
        $svm_dir/predictions -p $output_pickle  > /dev/null
done

#print coherence scores
python PrintResults.py $output_pickle $topic_dir/20.topics.txt


text:
package consul

import (
	gokitconsul "github.com/go-kit/kit/sd/consul"
	"github.com/hashicorp/consul/api"
)

// Client extends the go-kit consul Client interface with behaviors specific to XMiDT
type Client interface {
	gokitconsul.Client

	// Datacenters returns the known datacenters from the catalog
	Datacenters() ([]string, error)
}

// NewClient constructs a Client object which wraps the given hashicorp consul client.
// This factory function is the analog to go-kit's sd/consul.NewClient function.
func NewClient(c *api.Client) Client {
	return client{
		gokitconsul.NewClient(c),
		c,
	}
}

// client implements go-kit's consul Client interface and extends it to the local Client interface
type client struct {
	gokitconsul.Client
	c *api.Client
}

func (c client) Datacenters() ([]string, error) {
	return c.c.Catalog().Datacenters()
}