text:
using System.Reflection;

[assembly: AssemblyTitle("MultitenantExample.ConsoleApplication")]


text:
require 'spec_helper'

describe Google::Compute::Network do

  before(:each) do
    @mock_api_client=double(Google::APIClient, :authorization= => {}, :auto_refresh_token= => {})
    @mock_api_client.stub(:discovered_api).and_return(mock_compute)
    Google::APIClient.stub(:new).and_return(@mock_api_client)
  end

  let(:client) do
    Google::Compute::Client.from_json(mock_data_file(Google::Compute::Client))
  end

  it_should_behave_like Google::Compute::Resource

  it '#get should return an individual network' do
    @mock_api_client.should_receive(:execute).
      with(:api_method => mock_compute.networks.get,
           :parameters => {'network' => 'mock-network', :project => 'mock-project'}, :body_object => nil).
           and_return(mock_response(Google::Compute::Network))
    network = client.networks.get('mock-network')
    network.should be_a_kind_of Google::Compute::Network
    network.name.should eq('mock-network')
    network.should respond_to(:ip_v4_range)
  end

  it '#list should return an array of networks' do
    @mock_api_client.should_receive(:execute).
      with(:api_method => mock_compute.networks.list,
           :parameters => { :project => 'mock-project'}, :body_object => nil).
           and_return(mock_response(Google::Compute::Network, true))
    networks = client.networks.list
    networks.should_not be_empty
    networks.all?{|n| n.is_a?(Google::Compute::Network)}.should be_true
  end

  it '#create should create a new network' do
    @mock_api_client.should_receive(:execute).
      with(:api_method => mock_compute.networks.insert,
           :parameters => { :project => 'mock-project'},
           :body_object => {:name => 'mock-network', :IPv4Range => '122.12.0.0/16'}).
           and_return(mock_response(Google::Compute::GlobalOperation))
    o = client.networks.create(:name => 'mock-network', :IPv4Range => '122.12.0.0/16')
    o.should be_a_kind_of Google::Compute::GlobalOperation
  end

  it '#delete should delete an existing network' do
    @mock_api_client.should_receive(:execute).
      with(:api_method => mock_compute.networks.delete,
           :parameters => {'network' => 'mock-network', :project => 'mock-project'}, :body_object => nil).
           and_return(mock_response(Google::Compute::GlobalOperation))
    client.networks.delete('mock-network')
  end
end

redpajama_set_name: RedPajamaGithub


text:
// HEADER FILES ------------------------------------------------------------

#include "c_dispatch.h"
#include "gi.h"
#include "i_system.h"
#include "teaminfo.h"
#include "v_font.h"
#include "v_video.h"
#include "w_wad.h"

// MACROS ------------------------------------------------------------------

// TYPES -------------------------------------------------------------------

// EXTERNAL FUNCTION PROTOTYPES --------------------------------------------

// PUBLIC FUNCTION PROTOTYPES ----------------------------------------------

// PRIVATE FUNCTION PROTOTYPES ---------------------------------------------

// EXTERNAL DATA DECLARATIONS ----------------------------------------------

// PUBLIC DATA DEFINITIONS -------------------------------------------------

FTeam			TeamLibrary;
TArray<FTeam>	Teams;

// PRIVATE DATA DEFINITIONS ------------------------------------------------

static const char *TeamInfoOptions[] =
{
	"Game",
	"PlayerColor",
	"TextColor",
	"Logo",
	"AllowCustomPlayerColor",
	"RailColor",
	"FlagItem",
	"SkullItem",
	"PlayerStartThingNumber",
	"SmallFlagHUDIcon",
	"SmallSkullHUDIcon",
	"LargeFlagHUDIcon",
	"LargeSkullHUDIcon",
	"WinnerPic",
	"LoserPic",
	"WinnerTheme",
	"LoserTheme",
};

enum ETeamOptions
{
	TEAMINFO_Game,
	TEAMINFO_PlayerColor,
	TEAMINFO_TextColor,
	TEAMINFO_Logo,
	TEAMINFO_AllowCustomPlayerColor,
	TEAMINFO_RailColor,
	TEAMINFO_FlagItem,
	TEAMINFO_SkullItem,
	TEAMINFO_PlayerStartThingNumber,
	TEAMINFO_SmallFlagHUDIcon,
	TEAMINFO_SmallSkullHUDIcon,
	TEAMINFO_LargeFlagHUDIcon,
	TEAMINFO_LargeSkullHUDIcon,
	TEAMINFO_WinnerPic,
	TEAMINFO_LoserPic,
	TEAMINFO_WinnerTheme,
	TEAMINFO_LoserTheme,
};

// CODE --------------------------------------------------------------------

//==========================================================================
//
// FTeam :: FTeam
//
//==========================================================================

FTeam::FTeam ()
{
	m_iPlayerColor = 0;
	m_iPlayerCount = 0;
	m_iScore = 0;
	m_iPresent = 0;
	m_iTies = 0;
	m_bAllowCustomPlayerColor = false;
}

//==========================================================================
//
// FTeam :: ParseTeamInfo
//
//==========================================================================

void FTeam::ParseTeamInfo ()
{
	int iLump, iLastLump = 0;

	Teams.Clear();
	while ((iLump = Wads.FindLump ("TEAMINFO", &iLastLump)) != -1)
	{
		FScanner Scan (iLump);

		while (Scan.GetString ())
		{
			if (Scan.Compare ("ClearTeams"))
				ClearTeams ();
			else if (Scan.Compare ("Team"))
				ParseTeamDefinition (Scan);
			else
				Scan.ScriptError ("ParseTeamInfo: Unknown team command '%s'.\n", Scan.String);
		}
	}

	if (Teams.Size () < 2)
		I_FatalError ("ParseTeamInfo: At least two teams must be defined in TEAMINFO.");
	else if (Teams.Size () > (unsigned)TEAM_MAXIMUM)
		I_FatalError ("ParseTeamInfo: Too many teams defined. (Maximum: %d)", TEAM_MAXIMUM);
}

//==========================================================================
//
// FTeam :: ParseTeamDefinition
//
//==========================================================================

void FTeam::ParseTeamDefinition (FScanner &Scan)
{
	FTeam Team;
	int valid = -1;
	Scan.MustGetString ();
	Team.m_Name = Scan.String;
	Scan.MustGetStringName ("{");

	while (!Scan.CheckString ("}"))
	{
		Scan.MustGetString ();

		switch (Scan.MatchString (TeamInfoOptions))
		{
		case TEAMINFO_Game:
			Scan.MustGetString ();
			if (Scan.Compare("Any")) valid = 1;
			else if (CheckGame(Scan.String, false)) valid = 1;
			else if (valid == -1) valid = 0;
			break;

		case TEAMINFO_PlayerColor:
			Scan.MustGetString ();
			Team.m_iPlayerColor = V_GetColor (NULL, Scan.String);
			break;

		case TEAMINFO_TextColor:
			Scan.MustGetString ();
			Team.m_TextColor.AppendFormat ("[%s]", Scan.String);
			break;

		case TEAMINFO_Logo:
			Scan.MustGetString ();
			Team.m_Logo = Scan.String;
			break;

		case TEAMINFO_AllowCustomPlayerColor:
			Team.m_bAllowCustomPlayerColor = true;
			break;

		case TEAMINFO_PlayerStartThingNumber:
			Scan.MustGetNumber ();
			break;

		case TEAMINFO_RailColor:
		case TEAMINFO_FlagItem:
		case TEAMINFO_SkullItem:
		case TEAMINFO_SmallFlagHUDIcon:
		case TEAMINFO_SmallSkullHUDIcon:
		case TEAMINFO_LargeFlagHUDIcon:
		case TEAMINFO_LargeSkullHUDIcon:
		case TEAMINFO_WinnerPic:
		case TEAMINFO_LoserPic:
		case TEAMINFO_WinnerTheme:
		case TEAMINFO_LoserTheme:
			Scan.MustGetString ();
			break;

		default:
			Scan.ScriptError ("ParseTeamDefinition: Unknown team option '%s'.\n", Scan.String);
			break;
		}
	}

	if (valid) Teams.Push (Team);
}

//==========================================================================
//
// FTeam :: ClearTeams
//
//==========================================================================

void FTeam::ClearTeams ()
{
	Teams.Clear ();
}

//==========================================================================
//
// FTeam :: IsValidTeam
//
//==========================================================================

bool FTeam::IsValidTeam (unsigned int uiTeam)
{
	if (uiTeam >= Teams.Size ())
		return false;

	return true;
}

//==========================================================================
//
// FTeam :: GetName
//
//==========================================================================

const char *FTeam::GetName () const
{
	return m_Name;
}

//==========================================================================
//
// FTeam :: GetPlayerColor
//
//==========================================================================

int FTeam::GetPlayerColor () const
{
	return m_iPlayerColor;
}

//==========================================================================
//
// FTeam :: GetTextColor
//
//==========================================================================

int FTeam::GetTextColor () const
{
	if (m_TextColor.IsEmpty ())
		return CR_UNTRANSLATED;

	const BYTE *pColor = (const BYTE *)m_TextColor.GetChars ();
	int iColor = V_ParseFontColor (pColor, 0, 0);

	if (iColor == CR_UNDEFINED)
	{
		Printf ("GetTextColor: Undefined color '%s' in definition of team '%s'.\n", m_TextColor.GetChars (), m_Name.GetChars ());
		return CR_UNTRANSLATED;
	}

	return iColor;
}

//==========================================================================
//
// FTeam :: GetLogo
//
//==========================================================================

FString FTeam::GetLogo () const
{
	return m_Logo;
}

//==========================================================================
//
// FTeam :: GetAllowCustomPlayerColor
//
//==========================================================================

bool FTeam::GetAllowCustomPlayerColor () const
{
	return m_bAllowCustomPlayerColor;
}

//==========================================================================
//
// CCMD teamlist
//
//==========================================================================

CCMD (teamlist)
{
	Printf ("Defined teams are as follows:\n");

	for (unsigned int uiTeam = 0; uiTeam < Teams.Size (); uiTeam++)
		Printf ("%d : %s\n", uiTeam, Teams[uiTeam].GetName ());

	Printf ("End of team list.\n");
}


text:
<?php
namespace WhichBrowserTest;

use PHPUnit\Framework\TestCase;
use WhichBrowser\Constants;
use WhichBrowser\Model\Main;
use WhichBrowser\Model\Version;

/**
 * @covers WhichBrowser\Model\Main
 */
class MainTest extends TestCase
{
    public function testEmpty()
    {
        $main = new Main();

        $this->assertTrue($main->browser instanceof \WhichBrowser\Model\Browser);
        $this->assertTrue($main->engine instanceof \WhichBrowser\Model\Engine);
        $this->assertTrue($main->os instanceof \WhichBrowser\Model\Os);
        $this->assertTrue($main->device instanceof \WhichBrowser\Model\Device);
    }

    public function testIs()
    {
        $main = new Main();

        $this->assertFalse($main->isBrowser('Chrome'));
        $this->assertFalse($main->isBrowser('Chrome', '=', '40'));
        $this->assertFalse($main->isOs('OS X'));
        $this->assertFalse($main->isEngine('WebKit'));

        $main->browser->set([
            'name'      => 'Chrome',
            'version'   => new Version([ 'value' => '40.0.2214', 'details' => 1 ])
        ]);

        $this->assertTrue($main->isBrowser('Chrome'));

        $this->assertFalse($main->isBrowser());
        $this->assertFalse($main->isBrowser('Safari'));

        $this->assertTrue($main->isBrowser('Chrome', '=', '40'));
        $this->assertTrue($main->isBrowser('Chrome', '>=', '40'));
        $this->assertTrue($main->isBrowser('Chrome', '<=', '40'));
        $this->assertTrue($main->isBrowser('Chrome', '>', '39'));
        $this->assertTrue($main->isBrowser('Chrome', '<', '41'));

        $this->assertFalse($main->isBrowser('Chrome', '=', '39'));
        $this->assertFalse($main->isBrowser('Chrome', '>=', '41'));
        $this->assertFalse($main->isBrowser('Chrome', '<=', '39'));
        $this->assertFalse($main->isBrowser('Chrome', '>', '40'));
        $this->assertFalse($main->isBrowser('Chrome', '<', '40'));

        $main->os->set([
            'name'      => 'OS X',
            'version'   => new Version([ 'value' => '10.11.1', 'details' => 2 ])
        ]);

        $this->assertTrue($main->isOs('OS X'));

        $this->assertTrue($main->isOs('OS X', '=', '10'));
        $this->assertTrue($main->isOs('OS X', '=', '10.11'));
        $this->assertTrue($main->isOs('OS X', '=', '10.11.1'));
        $this->assertTrue($main->isOs('OS X', '=', '10.11.01'));

        $this->assertTrue($main->isOs('OS X', '=', 10));
        $this->assertTrue($main->isOs('OS X', '=', 10.11));

        $this->assertTrue($main->isOs('OS X', '>', '10.1'));
        $this->assertTrue($main->isOs('OS X', '>', '10.01'));
        $this->assertTrue($main->isOs('OS X', '>', '10.10'));

        $this->assertFalse($main->isOs('OS X', '>', '10'));
        $this->assertFalse($main->isOs('OS X', '>', '10.11'));

        $main->engine->set([
            'name'      => 'WebKit'
        ]);

        $this->assertTrue($main->isEngine('WebKit'));
        $this->assertFalse($main->isEngine('WebKit', '=', '523'));
    }

    public function testIsDevice()
    {
        $main = new Main();

        $main->device->setIdentification([
            'manufacturer'  =>  'Sony',
            'model'         =>  'PRS-T2',
            'series'        =>  'Reader'
        ]);

        $this->assertTrue($main->isDevice('Reader'));
        $this->assertTrue($main->isDevice('PRS-T2'));
    }

    public function testIsDetected()
    {
        $main = new Main();

        $this->assertFalse($main->isDetected());

        $main->browser->set([ 'name' => 'Chrome', 'version' => new Version([ 'value' => '47.0.2526.73', 'details' => 1 ]) ]);

        $this->assertTrue($main->isDetected());
    }

    public function testIsMobile()
    {
        $main = new Main();

        $main->device->setIdentification([
            'type'          =>  Constants\DeviceType::GAMING,
            'subtype'       =>  Constants\DeviceSubType::CONSOLE
        ]);

        $this->assertFalse($main->isMobile());

        $main->device->reset([
            'type'          =>  Constants\DeviceType::GAMING,
            'subtype'       =>  Constants\DeviceSubType::PORTABLE
        ]);

        $this->assertTrue($main->isMobile());

        $main->device->reset([
            'type'          =>  Constants\DeviceType::MOBILE,
            'subtype'       =>  Constants\DeviceSubType::SMART
        ]);

        $this->assertTrue($main->isMobile());

        $main->device->reset([
            'type'          =>  Constants\DeviceType::MOBILE,
            'subtype'       =>  Constants\DeviceSubType::FEATURE
        ]);

        $this->assertTrue($main->isMobile());

        $main->device->reset([
            'type'          =>  Constants\DeviceType::DESKTOP,
        ]);

        $this->assertFalse($main->isMobile());
    }

    public function testIsType()
    {
        $main = new Main();

        $main->device->setIdentification([
            'manufacturer'  =>  'Nintendo',
            'model'         =>  'Wii',
            'type'          =>  Constants\DeviceType::GAMING,
            'subtype'       =>  Constants\DeviceSubType::CONSOLE
        ]);

        $this->assertTrue($main->isType('gaming'));
        $this->assertTrue($main->isType('gaming:console'));

        $this->assertFalse($main->isType('mobile'));
        $this->assertFalse($main->isType('mobile:portable'));
        $this->assertFalse($main->isType('gaming:portable'));

        $this->assertTrue($main->isType('television', 'gaming'));
        $this->assertTrue($main->isType('gaming', 'television', 'gaming'));
        $this->assertTrue($main->isType('gaming:portable', 'gaming:console'));
    }

    public function testGetType()
    {
        $main = new Main();

        $main->device->reset([
            'type'          =>  Constants\DeviceType::GAMING
        ]);

        $this->assertEquals('gaming', $main->getType());

        $main->device->reset([
            'type'          =>  Constants\DeviceType::GAMING,
            'subtype'       =>  Constants\DeviceSubType::CONSOLE
        ]);

        $this->assertEquals('gaming:console', $main->getType());

        $main->device->reset([
            'type'          =>  Constants\DeviceType::GAMING,
            'subtype'       =>  Constants\DeviceSubType::PORTABLE
        ]);

        $this->assertEquals('gaming:portable', $main->getType());

        $main->device->reset([
            'type'          =>  Constants\DeviceType::MOBILE
        ]);

        $this->assertEquals('mobile', $main->getType());

        $main->device->reset([
            'type'          =>  Constants\DeviceType::MOBILE,
            'subtype'       =>  Constants\DeviceSubType::SMART
        ]);

        $this->assertEquals('mobile:smart', $main->getType());

        $main->device->reset([
            'type'          =>  Constants\DeviceType::MOBILE,
            'subtype'       =>  Constants\DeviceSubType::FEATURE
        ]);

        $this->assertEquals('mobile:feature', $main->getType());
    }

    public function testToString()
    {
        $main = new Main();
        $this->assertEquals('an unknown browser', $main->toString());

        $main = new Main();
        $main->device->set([ 'type' => Constants\DeviceType::BOT ]);
        $this->assertEquals('an unknown bot', $main->toString());

        $main = new Main();
        $main->browser->set([ 'name' => 'Chrome', 'version' => new Version([ 'value' => '47.0.2526.73', 'details' => 1 ]) ]);
        $main->engine->set([ 'name' => 'Blink' ]);
        $main->os->set([ 'name' => 'OS X', 'version' => new Version([ 'value' => '10.11', 'nickname' => 'El Capitan' ]) ]);

        $this->assertEquals('Chrome 47 on OS X El Capitan 10.11', $main->toString());

        $main = new Main();
        $main->engine->set([ 'name' => 'WebKit' ]);
        $main->os->set([ 'name' => 'Tizen', 'version' => new Version([ 'value' => '2.0' ]) ]);

        $this->assertEquals('Tizen 2.0', $main->toString());

        $main = new Main();
        $main->browser->set([ 'name' => 'Chrome', 'version' => new Version([ 'value' => '47.0.2526.73', 'details' => 1 ]) ]);

        $this->assertEquals('Chrome 47', $main->toString());

        $main->browser->set([ 'name' => 'Safari', 'version' => new Version([ 'value' => '8.0' ]) ]);
        $main->engine->set([ 'name' => 'WebKit' ]);
        $main->os->set([ 'name' => 'iOS', 'version' => new Version([ 'value' => '8.0' ]) ]);
        $main->device->setIdentification([ 'manufacturer' => 'Apple', 'model' => 'iPhone 6', 'type' => Constants\DeviceType::MOBILE ]);

        $this->assertEquals('Safari 8.0 on an Apple iPhone 6 running iOS 8.0', $main->toString());

        $main = new Main();
        $main->browser->set([ 'name' => 'Chrome', 'version' => new Version([ 'value' => '47.0.2526.73', 'details' => 1 ]) ]);
        $main->os->set([ 'name' => 'Android', 'version' => new Version([ 'value' => '4.4' ]) ]);
        $main->device->set([ 'model' => 'SM-A300', 'type' => Constants\DeviceType::MOBILE ]);
        $this->assertEquals('Chrome 47 on an unrecognized device (SM-A300) running Android 4.4', $main->toString());

        $main = new Main();
        $main->browser->set([ 'stock' => true ]);
        $main->engine->set([ 'name' => 'Blink' ]);

        $this->assertEquals('an unknown browser based on Blink', $main->toString());

        $main = new Main();
        $main->engine->set([ 'name' => 'Blink' ]);
        $main->os->set([ 'name' => 'OS X', 'version' => new Version([ 'value' => '10.11', 'nickname' => 'El Capitan' ]) ]);
        $main->device->set([ 'type' => Constants\DeviceType::DESKTOP ]);

        $this->assertEquals('an unknown browser based on Blink running on OS X El Capitan 10.11', $main->toString());

        $main = new Main();
        $main->browser->set([ 'name' => 'Safari', 'version' => new Version([ 'value' => '8.0' ]) ]);
        $main->device->setIdentification([ 'manufacturer' => 'Apple', 'model' => 'iPhone 6', 'type' => Constants\DeviceType::MOBILE ]);

        $this->assertEquals('Safari 8.0 on an Apple iPhone 6', $main->toString());

        $main = new Main();
        $main->os->set([ 'name' => 'iOS', 'version' => new Version([ 'value' => '8.0' ]) ]);
        $main->device->setIdentification([ 'manufacturer' => 'Apple', 'model' => 'iPhone 6', 'type' => Constants\DeviceType::MOBILE ]);

        $this->assertEquals('an Apple iPhone 6 running iOS 8.0', $main->toString());

        $main = new Main();
        $main->device->setIdentification([ 'manufacturer' => 'Apple', 'model' => 'iPhone 6', 'type' => Constants\DeviceType::MOBILE ]);

        $this->assertEquals('an Apple iPhone 6', $main->toString());

        $main = new Main();
        $main->device->setIdentification([ 'type' => Constants\DeviceType::TELEVISION ]);

        $this->assertEquals('a television', $main->toString());

        $main = new Main();
        $main->device->setIdentification([ 'type' => Constants\DeviceType::EMULATOR ]);

        $this->assertEquals('an emulator', $main->toString());
    }

    public function testToJavaScript()
    {
        $main = new Main();
        $expected = <<<'EOD'
this.browser = new Browser({ stock: true, hidden: false, mode: "", type: "" });
this.engine = new Engine({  });
this.os = new Os({ hidden: false });
this.device = new Device({ type: "", subtype: "", identified: 0, generic: true, hidden: false });
this.camouflage = false;
this.features = [];

EOD;

        $this->assertEquals($expected, $main->toJavaScript());
    }

    public function testToArray()
    {
        $main = new Main();
        $this->assertEquals([], $main->toArray());

        $main->browser->set([ 'name' => 'Safari', 'version' => new Version([ 'value' => '8.0' ]) ]);
        $main->engine->set([ 'name' => 'WebKit' ]);
        $main->os->set([ 'name' => 'iOS', 'version' => new Version([ 'value' => '8.0' ]) ]);
        $main->device->setIdentification([ 'manufacturer' => 'Apple', 'model' => 'iPhone 6', 'type' => Constants\DeviceType::MOBILE ]);
        $this->assertEquals([
            'browser' => [
                'name'      => 'Safari',
                'version'   => '8.0'
            ],
            'engine' => [
                'name'      => 'WebKit'
            ],
            'os' => [
                'name'      => 'iOS',
                'version'   => '8.0'
            ],
            'device' => [
                'type'          => 'mobile',
                'manufacturer'  => 'Apple',
                'model'         => 'iPhone 6'
            ]
        ], $main->toArray());
    }
}


text:
package metrics

import (
	"testing"
	"time"
)

func TestRuntimeCollector(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping test because testing.Short is enabled")
	}

	var keys []string
	latestVal := make(map[string]uint64)
	gaugeFunc := func(key string, val uint64) {
		keys = append(keys, key)
		latestVal[key] = val
	}

	done := make(chan struct{})
	collectorShutdown := make(chan struct{})
	c := NewRuntimeCollector(gaugeFunc)
	c.PauseTime = time.Second
	c.Done = done

	go func() {
		defer close(collectorShutdown)
		c.Start()
	}()
	time.Sleep(1500 * time.Millisecond)
	close(done)
	<-collectorShutdown

	// we're going to check a few keys to make sure that the stats are being output
	// correctly. We expect there to be three of each key because there is one
	// from the initial stats, plus another one after the 1 second pause time, plus
	// the final zeroing out on shutdown
	expCount := 3
	expKeys := []string{
		"cpu.goroutines",
		"mem.lookups",
		"mem.gc.count",
	}
	for _, expKey := range expKeys {
		count := 0
		for _, key := range keys {
			if key == expKey {
				count++
			}
		}
		if count != expCount {
			t.Errorf("unexpected num stats for key(%s):\ngot: %d\nexp: %d", expKey, count, expCount)
		}
		if latestVal[expKey] != 0 {
			t.Errorf("expected key (%s) to be zeroed out on shutdown, instead latest value is %d", expKey, latestVal[expKey])
		}
	}
}


text:
package publichtml

// LinkSendSuccess ...
var LinkSendSuccess = `
<!DOCTYPE html>

  <title>Invalid Link</title>

Link Sent! Check your email.

`


text:
'''
   Created on 22/05/2015
   @author: C&C - HardSoft
'''
import os
import sys
import traceback
from util.change import change
from util.homogenize import Homogenize
from columns import Columns
from calc_length import calc_length

class GerJobPdZd(object):

    def __init__(self, jobname, path, book, sortin, sortout):
        self.jobname = jobname
        self.path = path
        self.book = book
        self.sortin = sortin
        self.sortout = sortout

    def gerjob(self):
        try:
            basename = os.path.basename(self.book).split('.')[0].upper()
            col = Columns()
            bookout = col.columns(self.book,fmt='cbl', signal=False)
            book_zonado = os.path.join(self.path, '{}_ZD.cpy'.format(basename))
            with open(book_zonado, 'w') as bkzd:
                bkzd.writelines(bookout)
            lengthout = str(calc_length(bookout)['lrecl'])

            formatout = ''
            start = 1
            bookin = file(self.book).readlines()
            bookin = Homogenize(bookin, cbl=True)
            for line in bookin:
                if 'PIC' not in line:
                    continue
                splt_pic = line.split('PIC')[1]
                repl_pic = splt_pic.replace(' USAGE ', '').replace('COMP-3', '').replace('COMP', '').rstrip()
                ap = ' OUTREC FIELDS=(' if start == 1 else '                 '
                length = int(str(calc_length(line.replace(splt_pic, repl_pic))['lrecl']))
                lenpd  = calc_length(line)['lrecl']
                pd2zd = ('PD,TO=ZD,LENGTH={:03},'.format(length)
                                                 if 'COMP-3' in splt_pic else
                         'BI,TO=ZD,LENGTH={:03},'.format(length)
                                                 if 'COMP' in splt_pic else '')
                formatout += '{}{:03},{:03},{}\n'.format(ap, start, lenpd, pd2zd)
                start += lenpd

            formatout = formatout[:-2] + ')\n'

            dicjob={'@JOBNAME'  :'{:8}'.format(self.jobname)
                   ,'@BOOK'     :basename
                   ,'@SORTIN'   :self.sortin
                   ,'@SORTOUT'  :self.sortout
                   ,'@LRECL'    :lengthout
                   ,'@OUTREC\n' :formatout
                   }

            job = change(dicjob, file('jobpk2zd.template').read())
            jobName = os.path.join(self.path, '{}.jcl'.format(self.jobname))
            with open(jobName, 'w') as jobWrite:
                jobWrite.write(job)
            return True, None
        except:
            return (False, traceback.format_exc(sys.exc_info))


text:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <time.h> // For timers

#define PI 3.14159265

typedef enum {
	FILTER_AVG,
	FILTER_GAUSS
} filter_type;

typedef struct {
	int radius;
	double **matrix;
	int type;
} FILTER;

typedef struct {
	unsigned char R;
	unsigned char G;
	unsigned char B;
} pixel;

//.ppm image
typedef struct {
	char header[3];
	int width, height;
	int color_depth;
	pixel **pixels;
} IMAGE;

// HANDLE IMAGE READ AND WRITE

IMAGE *image_load(const char *image_name) {
	//Declare image struct
	IMAGE *image = (IMAGE*) malloc( sizeof(IMAGE) );

	//Open file
	FILE *file = fopen(image_name, "r");
	if(!file)
		return NULL;

	//Read image info
	fscanf(file, "%s", image->header);
	fscanf(file, "%d %d %d", &(image->width), &(image->height), &(image->color_depth));

	//Alocate memory for pixels
	image->pixels = (pixel**) malloc(image->height * sizeof(pixel*));
	int i, j;
	for(i = 0; i < image->height; i++)
		image->pixels[i] = (pixel*) malloc(image->width * sizeof(pixel));

	//Read pixels
	for(i = 0; i < image->height; i++)
		for(j = 0; j < image->width; j++)
			fscanf(file, "%c%c%c", &(image->pixels[i][j].R), &(image->pixels[i][j].G), &(image->pixels[i][j].B));

	//Close file
	fclose(file);

	return image;
}

int image_write(IMAGE *image, const char *file_name) {
	//Open file
	FILE *file = fopen(file_name, "w");
	if(!file)
		return 0;

	//Write image info
	fprintf(file, "%s\n%d %d\n%d", image->header, image->width, image->height, image->color_depth);

	//Write pixels
	int i, j;
	for(i = 0; i < image->height; i++)
		for(j = 0; j < image->width; j++)
			fprintf(file, "%c%c%c", image->pixels[i][j].R, image->pixels[i][j].G, image->pixels[i][j].B);

	//Write EOF
	fprintf(file, "%d", EOF);

	//Close file
	fclose(file);

	return 1;
}

IMAGE *image_create_blank(IMAGE *source) {
	//Declare
	IMAGE *image = (IMAGE*) malloc( sizeof(IMAGE) );

	//Copy info(except pixels)
	strcpy(image->header, source->header);
	image->height = source->height;
	image->width = source->width;
	image->color_depth = source->color_depth;

	//Alloc mem for pixels
	image->pixels = (pixel**) malloc(image->height * sizeof(pixel*));
	int i;
	for(i = 0; i < image->height; i++)
		image->pixels[i] = (pixel*) malloc(image->width * sizeof(pixel));

	return image;
}

void image_free(IMAGE *image) {
	//Free pixels
	int i;
	for(i = 0; i < image->height; i++)
		free(image->pixels[i]);
	free(image->pixels);

	//Free image
	free(image);
}

// Create filter
FILTER *filter_create_avg(int radius) {
	//Allocate mem for the structure
	FILTER *filter = (FILTER*) malloc(sizeof(FILTER));
	filter->radius = radius;
	filter->type = FILTER_AVG;

	//Used for iterations
	int i, j;

	//The matrix width and height
	int dim = 2*radius+1;

	//Alocate mem for the matrix
	filter->matrix = (double**) malloc(dim * sizeof(double*));
	for(i = 0; i < dim; i++)
		filter->matrix[i] = (double*) malloc(dim * sizeof(double));

	//The value that every entry in the matrix will contain
	double avg = 1.0 / (dim * dim);

	//Set the values
	for(i = 0; i < dim; i++)
		for(j = 0; j < dim; j++)
			filter->matrix[i][j] = avg;

	return filter;
}

double gauss_2d(int x, int y, double sigma) {
	double result = 1.0 / (2 * PI * sigma * sigma);
	result *= exp(-(x*x+y*y)/(2 * sigma * sigma));
	return result;
}

FILTER *filter_create_gauss(int radius, double sigma) {
	//Allocate mem for the structure
	FILTER *filter = (FILTER*) malloc(sizeof(FILTER));
	filter->radius = radius;
	filter->type = FILTER_GAUSS;

	//Used for iterations
	int i, j;

	//The matrix width and height
	int dim = 2*radius+1;

	//Alocate mem for the matrix
	filter->matrix = (double**) malloc(dim * sizeof(double*));
	for(i = 0; i < dim; i++)
		filter->matrix[i] = (double*) malloc(dim * sizeof(double));

	//Calculate
	double sum = 0.0;
	for(i = -radius; i <= radius; i++)
		for(j = -radius; j <= radius; j++) {
			filter->matrix[i+radius][j+radius] = gauss_2d(j, i, sigma);
			sum += filter->matrix[i+radius][j+radius];
		}

	//Correct so that the sum of all elements ~= 1
	for(i = 0; i < 2*radius+1; i++)
		for(j = 0; j < 2*radius+1; j++)
			filter->matrix[i][j] /= sum;

	return filter;
}

void filter_print(FILTER *filter) {
	int dim = 2*filter->radius+1, i, j;

	for(i = 0; i < dim; i++) {
		for(j = 0; j < dim; j++)
			printf("%lf ", filter->matrix[i][j]);
		printf("\n");
	}
}

void filter_free(FILTER *filter) {
	//Free matrix
	int dim=2*filter->radius+1, i;
	for(i = 0; i < dim; i++)
		free(filter->matrix[i]);
	free(filter->matrix);

	//Free filter
	free(filter);
}

// Manipulate image with filter
void apply_to_pixel(int x, int y, IMAGE *original, IMAGE *result, FILTER *filter) {
	//TODO: Use Halos and don't ignore edges
	if(x<filter->radius || y<filter->radius || x>=original->width-filter->radius || y>=original->height-filter->radius) {
		result->pixels[y][x] = original->pixels[y][x];
		return;
	}

	int i, j;
	pixel res;
	//double res_R = 0;
	//double res_G = 0;
	//double res_B = 0;
	double fil=0;

	#pragma acc parallel //present_or_copyin(filter[:1], original[:1])
	#pragma acc loop gang vector collapse(2) reduction(+:res_R, res_G, res_B)
	for( i = -filter->radius; i <= filter->radius; i++)
		for( j = -filter->radius; j <= filter->radius; j++) {
			fil = filter->matrix[i+filter->radius][j+filter->radius];
			res.R += fil * original->pixels[y+i][x+j].R;
			res.G += fil * original->pixels[y+i][x+j].G;
			res.B += fil * original->pixels[y+i][x+j].B;

		}

	result->pixels[y][x].R = res.R;
	result->pixels[y][x].G = res.G;
	result->pixels[y][x].B = res.B;

}

IMAGE *apply_filter(IMAGE *original, FILTER *filter) {
	IMAGE *result = image_create_blank(original);

	int x, y;
	for(y = 0; y < original->height; y++){
		for(x = 0; x < original->width; x++){

			apply_to_pixel(x, y, original, result, filter);
		}
	}
	return result;
}

// MAIN PROGRAM
int main(int argc, char *argv[]) {

clock_t begin = clock();

	//The image that is going to be blurred
	IMAGE *image = NULL;

	//The resulting image
	IMAGE *result = NULL;

	//The used filter
	FILTER *filter;

	//Info
	char image_file_name[50];
	char result_file_name[50];
	int radius;
	double sigma;

	//Arguments: argv[0]="path", argv[1]="image_name.ppm", argv[2]="result_image_name.ppm" argv[3]="radius" argv[4]="sigma"
	if(argc == 5) {	//If enought arguments given take the info from the them
		//Original image file name
		strcpy(image_file_name, argv[1]);

		//Result image file name
		strcpy(result_file_name, argv[2]);

		//Convert radius
		radius = atoi(argv[3]);

		//Convert sigma
		sigma = atof(argv[4]);
	} else { //Read info from keyboard
		//Original image file name
		printf("Original image name: ");
		scanf("%s", image_file_name);

		//Result image file name
		printf("Result image name: ");
		scanf("%s", result_file_name);

		//Read radius
		printf("Radius: ");
		scanf("%d", &radius);

		//Read sigma
		printf("Sigma: ");
		scanf("%lf", &sigma);
	}

	//Load image
	//printf("Loading image...\n");
	image = image_load(image_file_name);

	//Create filter
	//printf("Creating filter...\n");
	filter = filter_create_gauss(radius, sigma);

	printf("height: %d, width: %d",image->height, image->width);

	//Apply filter
	//printf("Appling filter...\n");
	result = apply_filter(image, filter);

	//Write image to disk
	//printf("Writing image to disk...\n");
	image_write(result, result_file_name);

	//Free memory
	image_free(image);
	image_free(result);
	filter_free(filter);

	clock_t end = clock();
	double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;

	printf("Wall Time: %lf \n", time_spent);
	//printf("DONE!\n");

	return 0;
}


text:
A sample that shows how the experimental Office Web Widgets can be used.

### Applies to ###
-  Office 365 Multi Tenant (MT)
-  Office 365 Dedicated (D)
-  SharePoint 2013 on-premises

### Prerequisites ###
The Office Web Widgets - Experimental NuGet package needs to be deployed

### Solution ###
Solution | Author(s)
---------|----------
Core.OfficeWebWidgets | Bert Jansen (**Microsoft**)

### Version history ###
Version  | Date | Comments
---------| -----| --------
1.0  | July 9th 2014 | Initial release

### Disclaimer ###
**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**

----------

# General comments #
This sample shows how you can use the experimental Office Web Widgets in your provider hosted SharePoint apps. In order to use this sample you'll need to install the [Office Web Widgets – Experimental NuGet package](https://www.nuget.org/packages/Microsoft.Office.WebWidgets.Experimental/) from Visual Studio. To learn more about these experimental Office Web Widgets please refer to:
-  [Office Web Widgets - Experimental overview](http://msdn.microsoft.com/en-us/library/office/dn636913(v=office.15).aspx)
-  [Office Web Widgets—Experimental Office developer blog post](http://blogs.msdn.com/b/officeapps/archive/2014/03/07/office-web-widgets-experimental.aspx)
-  [SharePoint 2013: Office Web Widgets - Experimental Demo on MSDN code gallery](http://code.msdn.microsoft.com/office/SharePoint-2013-Office-Web-6d44aa9e#content)

### NOTE: ###
These widgets are experimental which implies that there's no official Microsoft support for them and that the functionality might change in next releases, potentially causing your existing code to break if you upgrade to the next release.


text:
package com.nexmo.client.verify;

import com.nexmo.client.*;

import java.util.Locale;

/**
 * A client for talking to the Nexmo Verify API. The standard way to obtain an instance of this class is to use {@link
 * NexmoClient#getVerifyClient()}.
 *

 * Send a verification request with a call to {@link #verify}, confirm the code entered by the user with {@link #check},
 * and search in-progress or completed verification requests with {@link #search}
 *

 * More information on method parameters can be found at Nexmo website:
 * https://docs.nexmo.com/verify
 */
public class VerifyClient extends AbstractClient {

    private CheckEndpoint check;
    private VerifyEndpoint verify;
    private SearchEndpoint search;
    private ControlEndpoint control;
    private Psd2Endpoint psd2;

    /**
     * Constructor.
     *
     * @param httpWrapper (required) shared HTTP wrapper object used for making REST calls.
     */
    public VerifyClient(HttpWrapper httpWrapper) {
        super(httpWrapper);

        this.check = new CheckEndpoint(httpWrapper);
        this.search = new SearchEndpoint(httpWrapper);
        this.verify = new VerifyEndpoint(httpWrapper);
        this.control = new ControlEndpoint(httpWrapper);
        this.psd2 = new Psd2Endpoint(httpWrapper);
    }

    /**
     * Send a verification request to a phone number.
     *
     * @param number (required) The recipient's phone number in E.164
     *               format.
     * @param brand  (required) The name of the company or app to be verified for. Must not be longer than 18
     *               characters.
     *
     * @return a VerifyResponse representing the response received from the Verify API call.
     *
     * @throws NexmoClientException        if there was a problem with the Nexmo request or response objects.
     * @throws NexmoResponseParseException if the response from the API could not be parsed.
     */
    public VerifyResponse verify(final String number, final String brand) throws NexmoResponseParseException, NexmoClientException {
        return this.verify.verify(number, brand);
    }

    /**
     * Send a verification request to a phone number with a pin verification workflow
     *
     * @param number (required) The recipient's phone number in E.164
     *               format.
     * @param brand  (required) The name of the company or app to be verified for. Must not be longer than 18
     *               characters.
     * @param workflow workflow
     *                 to use for sending verification pin
     *
     * @return a VerifyResponse representing the response received from the Verify API call.
     *
     * @throws NexmoClientException        if there was a problem with the Nexmo request or response objects.
     * @throws NexmoResponseParseException if the response from the API could not be parsed.
     * @since 5.5.0
     */
    public VerifyResponse verify(final String number, final String brand, VerifyRequest.Workflow workflow)
            throws NexmoResponseParseException, NexmoClientException {
        return this.verify.verify(number, brand, workflow);
    }

    /**
     * Send a verification request to a phone number.
     *
     * @param number (required) The recipient's phone number in E.164
     *               format.
     * @param brand  (required) The name of the company or app to be verified for. Must not be longer than 18
     *               characters.
     * @param from   (optional The Nexmo number to use as the sender for the verification SMS message and calls, in
     *               E.164 format.
     *
     * @return a VerifyResponse representing the response received from the Verify API call.
     *
     * @throws NexmoClientException        if there was a problem with the Nexmo request or response objects.
     * @throws NexmoResponseParseException if the response from the API could not be parsed.
     */
    public VerifyResponse verify(final String number,
                                 final String brand,
                                 final String from) throws NexmoClientException, NexmoResponseParseException {
        return this.verify.verify(number, brand, from);
    }

    /**
     * Send a verification request to a phone number.
     *
     * @param number (required) The recipient's phone number in E.164
     *               format.
     * @param brand  (required) The name of the company or app to be verified for. Must not be longer than 18
     *               characters.
     * @param from   (optional The Nexmo number to use as the sender for the verification SMS message and calls, in
     *               E.164 format.
     * @param length (optional) The length of the verification code to be sent to the user. Must be either 4 or 6. Use
     *               -1 to use the default value.
     * @param locale (optional) Override the default locale used for verification. By default the locale is determined
     *               from the country code included in {@code number}
     *
     * @return a VerifyResponse representing the response received from the Verify API call.
     *
     * @throws NexmoClientException        if there was a problem with the Nexmo request or response objects.
     * @throws NexmoResponseParseException if the response from the API could not be parsed.
     */
    public VerifyResponse verify(final String number,
                                 final String brand,
                                 final String from,
                                 final int length,
                                 final Locale locale) throws NexmoClientException, NexmoResponseParseException {
        return this.verify.verify(number, brand, from, length, locale);
    }

    /**
     * Send a verification request to a phone number.
     *
     * @param number (required) The recipient's phone number in E.164
     *               format.
     * @param brand  (required) The name of the company or app to be verified for. Must not be longer than 18
     *               characters.
     * @param from   (optional The Nexmo number to use as the sender for the verification SMS message and calls, in
     *               E.164 format.
     * @param length (optional) The length of the verification code to be sent to the user. Must be either 4 or 6. Use
     *               -1 to use the default value.
     * @param locale (optional) Override the default locale used for verification. By default the locale is determined
     *               from the country code included in {@code number}
     * @param type   (optional) If provided, restrict the verification to the specified network type. Contact
     *               support@nexmo.com to enable this feature.
     *
     * @return a VerifyResponse representing the response received from the Verify API call.
     *
     * @throws NexmoClientException        if there was a problem with the Nexmo request or response objects.
     * @throws NexmoResponseParseException if the response from the API could not be parsed.
     */
    public VerifyResponse verify(final String number,
                                 final String brand,
                                 final String from,
                                 final int length,
                                 final Locale locale,
                                 final VerifyRequest.LineType type) throws NexmoClientException {
        return this.verify.verify(number, brand, from, length, locale, type);
    }

    /**
     * Send a verification request to a phone number.
     *
     * @param request validation request for the 2FA verification.
     * @return a VerifyResponse representing the response received from the Verify API call.
     *
     * @throws NexmoClientException if there was a problem with the Nexmo request or response objects.
     * @throws NexmoResponseParseException if the response from the API could not be parsed.
     *
     */
    public VerifyResponse verify(VerifyRequest request) throws NexmoClientException, NexmoResponseParseException {
        return this.verify.verify(request);
    }

    /**
     * Validate a code provided by a user in response to a call from {@link #verify}.
     *
     * @param requestId (required) The requestId returned by the {@code verify} call.
     * @param code      (required) The code entered by the user.
     *
     * @return a CheckResponse representing the response received from the API call.
     *
     * @throws NexmoClientException        if there was a problem with the Nexmo request or response objects.
     * @throws NexmoResponseParseException if the response from the API could not be parsed.
     */
    public CheckResponse check(final String requestId, final String code) throws NexmoClientException, NexmoResponseParseException {
        return this.check.check(requestId, code);
    }

    /**
     * Validate a code provided by a user in response to a call from {@link #verify}.
     *
     * @param requestId (required) The requestId returned by the {@code verify} call.
     * @param code      (required) The code entered by the user.
     * @param ipAddress (optional) The IP address obtained from the HTTP request made when the user entered their code.
     *
     * @return a CheckResponse representing the response received from the API call.
     *
     * @throws NexmoClientException        if there was a problem with the Nexmo request or response objects.
     * @throws NexmoResponseParseException if the response from the API could not be parsed.
     */
    public CheckResponse check(final String requestId,
                               final String code,
                               final String ipAddress) throws NexmoClientException, NexmoResponseParseException {
        return this.check.check(requestId, code, ipAddress);
    }

    /**
     * Search for a previous verification request.
     *
     * @param requestId The requestId of a single Verify request to be looked up.
     *
     * @return A SearchVerifyResponse containing the details of the Verify request that was looked up, or {@code null}
     * if no record was found.
     *
     * @throws NexmoClientException        if there was a problem with the Nexmo request or response objects.
     * @throws NexmoResponseParseException if the response from the API could not be parsed.
     */
    public SearchVerifyResponse search(String requestId) throws NexmoClientException, NexmoResponseParseException {
        return this.search.search(requestId);
    }

    /**
     * Search for a previous verification request.
     *
     * @param requestIds The requestIds of Verify requests to be looked up.
     *
     * @return An array SearchVerifyResponse for each record that was found.
     *
     * @throws NexmoClientException        if there was a problem with the Nexmo request or response objects.
     * @throws NexmoResponseParseException if the response from the API could not be parsed.
     */
    public SearchVerifyResponse search(String... requestIds) throws NexmoClientException, NexmoResponseParseException {
        return this.search.search(requestIds);
    }

    /**
     * Advance a current verification request to the next stage in the process.
     *
     * @param requestId The requestId of the ongoing verification request.
     *
     * @return A {@link ControlResponse} representing the response from the API.
     *
     * @throws NexmoClientException        if there was a problem with the Nexmo request or response objects.
     * @throws NexmoResponseParseException if the response from the API could not be parsed.
     */
    public ControlResponse advanceVerification(String requestId) throws NexmoClientException, NexmoResponseParseException {
        return this.control.execute(new ControlRequest(requestId, VerifyControlCommand.TRIGGER_NEXT_EVENT));
    }

    /**
     * Cancel a current verification request.
     *
     * @param requestId The requestId of the ongoing verification request.
     *
     * @return A {@link ControlResponse} representing the response from the API.
     *
     * @throws NexmoClientException        if there was a problem with the Nexmo request or response objects.
     * @throws NexmoResponseParseException if the response from the API could not be parsed.
     */
    public ControlResponse cancelVerification(String requestId) throws NexmoClientException, NexmoResponseParseException {
        return this.control.execute(new ControlRequest(requestId, VerifyControlCommand.CANCEL));
    }

    /**
     * Send a PSD2 compliant payment token to a user for payment authorization
     *
     * @param number Telephone number to verify, in E.164 format
     * @param amount payment amount
     * @param payee name of the person the payment is for. Name will be included in the message
     *
     * @return A {@link VerifyResponse} representing the response from the API.
     *
     * @throws NexmoClientException          if there was a problem with the Nexmo request or response objects.
     * @throws NexmoResponseParseException   if the response from the API could not be parsed.
     *
     * @since 5.5.0
     */
    public VerifyResponse psd2Verify(String number, Double amount, String payee) throws NexmoClientException, NexmoResponseParseException {
        return this.psd2.psd2Verify(number, amount, payee);
    }

    /**
     * Send a PSD2 compliant payment token to a user for payment authorization with a pin verification workflow
     *
     * @param number   telephone number to verify, in E.164 format
     * @param amount   payment amount
     * @param payee    name of the person the payment is for. Name will be included in the message
     * @param workflow workflow
     *                 to use for sending verification pin
     *
     * @return A {@link VerifyResponse} representing the response from the API.
     *
     * @throws NexmoClientException          if there was a problem with the Nexmo request or response objects.
     * @throws NexmoResponseParseException   if the response from the API could not be parsed.
     *
     * @since 5.5.0
     */
    public VerifyResponse psd2Verify(String number, Double amount, String payee, Psd2Request.Workflow workflow)
            throws NexmoClientException, NexmoResponseParseException {
        return this.psd2.psd2Verify(number, amount, payee, workflow);
    }

    /**
     * Send a PSD2 verification request to a phone number with optional parameters
     *
     * @param psd2Request request to to send PSD2 verification to a phone.
     *
     * @return A VerifyResponse representing the response from the API.
     *
     * @throws NexmoClientException          if there was a problem with the Nexmo request or response objects.
     * @throws NexmoResponseParseException   if the response from the API could not be parsed.
     *
     * @since 5.5.0
     */
    public VerifyResponse psd2Verify(Psd2Request psd2Request) throws NexmoClientException, NexmoResponseParseException {
        return this.psd2.psd2Verify(psd2Request);
    }

}


text:
<?php

namespace app\models\glabs\faker;

class PhoneNumber extends \Faker\Provider\PhoneNumber
{
    protected static $formats = [
        '##########'
    ];
}


text:
using asio::ip::tcp;

class AsioNetworkClient
{
public:
    AsioNetworkClient();

    bool connect(const std::string& ipAddress, int port);

    void disconnect();

    void send(pb::Message& message);

    PacketDispatcher& dispatcher();

private:
    void receive();

    asio::io_service mIoService;
    tcp::resolver mResolver;
    tcp::socket mSocket;
    PacketData mPacketData;
    std::thread mReceiver;
    PacketDispatcher mDispatcher;
};

#endif //PREZ_GAME_NETWORKCLIENT_HPP


text:
using namespace device;
using namespace stateos;

auto led = Led();
auto sem = Semaphore::Binary();
auto cons = Task::Start([]{ sem.wait(); led.tick(); });
auto prod = Task::Start([]{ thisTask::sleepNext(std::chrono::seconds{1}); sem.give(); });

int main()
{
	thisTask::suspend();
}


text:
package query

import (
	"context"
	"fmt"
	"os"
	"strings"
	"sync"
	"testing"

	"github.com/mithrandie/csvq/lib/option"

	"github.com/mithrandie/go-text"

	"github.com/mithrandie/csvq/lib/parser"
	"github.com/mithrandie/csvq/lib/value"
)

func TestTransaction_Commit(t *testing.T) {
	defer func() {
		_ = TestTx.ReleaseResources()
		_ = TestTx.CachedViews.Clean(TestTx.FileContainer)
		TestTx.Session.SetStdout(NewDiscard())
		initFlag(TestTx.Flags)
	}()

	TestTx.Flags.SetQuiet(false)

	ch, _ := TestTx.FileContainer.CreateHandlerForCreate(GetTestFilePath("created_file.csv"))
	uh, _ := TestTx.FileContainer.CreateHandlerForUpdate(context.Background(), GetTestFilePath("updated_file_1.csv"), TestTx.WaitTimeout, TestTx.RetryDelay)

	TestTx.CachedViews = GenerateViewMap([]*View{
		{
			Header:    NewHeader("created_file", []string{"column1", "column2"}),
			RecordSet: RecordSet{},
			FileInfo: &FileInfo{
				Path:      GetTestFilePath("created_file.csv"),
				Handler:   ch,
				Encoding:  text.UTF8,
				Format:    option.CSV,
				Delimiter: ',',
				LineBreak: text.LF,
			},
		},
		{
			Header: NewHeader("table1", []string{"column1", "column2"}),
			RecordSet: []Record{
				NewRecord([]value.Primary{
					value.NewString("1"),
					value.NewString("str1"),
				}),
				NewRecord([]value.Primary{
					value.NewString("update1"),
					value.NewString("update2"),
				}),
				NewRecord([]value.Primary{
					value.NewString("3"),
					value.NewString("str3"),
				}),
			},
			FileInfo: &FileInfo{
				Path:      GetTestFilePath("updated_file_1.csv"),
				Handler:   uh,
				Encoding:  text.UTF8,
				Format:    option.CSV,
				Delimiter: ',',
				LineBreak: text.LF,
			},
		},
	})

	TestTx.UncommittedViews = UncommittedViews{
		mtx: &sync.RWMutex{},
		Created: map[string]*FileInfo{
			strings.ToUpper(GetTestFilePath("created_file.csv")): {
				Path:      GetTestFilePath("created_file.csv"),
				Handler:   ch,
				Encoding:  text.UTF8,
				Format:    option.CSV,
				Delimiter: ',',
				LineBreak: text.LF,
			},
		},
		Updated: map[string]*FileInfo{
			strings.ToUpper(GetTestFilePath("updated_file_1.csv")): {
				Path:      GetTestFilePath("updated_file_1.csv"),
				Handler:   uh,
				Encoding:  text.UTF8,
				Format:    option.CSV,
				Delimiter: ',',
				LineBreak: text.LF,
			},
		},
	}

	expect := fmt.Sprintf("Commit: file %q is created.\nCommit: file %q is updated.\n", GetTestFilePath("created_file.csv"), GetTestFilePath("updated_file_1.csv"))

	tx := TestTx

	out := NewOutput()
	tx.Session.SetStdout(out)

	err := TestTx.Commit(context.Background(), NewReferenceScope(tx), parser.TransactionControl{Token: parser.COMMIT})
	if err != nil {
		t.Fatalf("unexpected error %q", err.Error())
	}

	log := out.String()

	if log != expect {
		t.Errorf("Commit: log = %q, want %q", log, expect)
	}

	expectedCreatedContents := "column1,column2\n"
	createdContents, err := os.ReadFile(GetTestFilePath("created_file.csv"))
	if err != nil {
		t.Fatalf("unexpected error %q", err.Error())
	}

	if expectedCreatedContents != string(createdContents) {
		t.Errorf("created contents = %q, want %q", string(createdContents), expectedCreatedContents)
	}

	expectedUpdatedContents := "column1,column2\n1,str1\nupdate1,update2\n3,str3\n"
	updatedContents, err := os.ReadFile(GetTestFilePath("updated_file_1.csv"))
	if err != nil {
		t.Fatalf("unexpected error %q", err.Error())
	}

	if expectedUpdatedContents != string(updatedContents) {
		t.Errorf("updated contents = %q, want %q", string(updatedContents), expectedUpdatedContents)
	}

	// Flags.StripEndingLineBreak = true
	TestTx.Flags.ExportOptions.StripEndingLineBreak = true
	ch, _ = TestTx.FileContainer.CreateHandlerForCreate(GetTestFilePath("created_file_1.csv"))
	uh, _ = TestTx.FileContainer.CreateHandlerForUpdate(context.Background(), GetTestFilePath("updated_file_1.csv"), TestTx.WaitTimeout, TestTx.RetryDelay)
	TestTx.CachedViews = GenerateViewMap([]*View{
		{
			Header:    NewHeader("created_file_1", []string{"column1", "column2"}),
			RecordSet: RecordSet{},
			FileInfo: &FileInfo{
				Path:      GetTestFilePath("created_file_1.csv"),
				Handler:   ch,
				Encoding:  text.UTF8,
				Format:    option.CSV,
				Delimiter: ',',
				LineBreak: text.LF,
			},
		},
		{
			Header: NewHeader("table1", []string{"column1", "column2"}),
			RecordSet: []Record{
				NewRecord([]value.Primary{
					value.NewString("1"),
					value.NewString("str1"),
				}),
				NewRecord([]value.Primary{
					value.NewString("update1"),
					value.NewString("update2"),
				}),
				NewRecord([]value.Primary{
					value.NewString("3"),
					value.NewString("str3"),
				}),
			},
			FileInfo: &FileInfo{
				Path:      GetTestFilePath("updated_file_1.csv"),
				Handler:   uh,
				Encoding:  text.UTF8,
				Format:    option.CSV,
				Delimiter: ',',
				LineBreak: text.LF,
			},
		},
	})

	TestTx.UncommittedViews = UncommittedViews{
		mtx: &sync.RWMutex{},
		Created: map[string]*FileInfo{
			strings.ToUpper(GetTestFilePath("created_file_1.csv")): {
				Path:      GetTestFilePath("created_file_1.csv"),
				Handler:   ch,
				Encoding:  text.UTF8,
				Format:    option.CSV,
				Delimiter: ',',
				LineBreak: text.LF,
			},
		},
		Updated: map[string]*FileInfo{
			strings.ToUpper(GetTestFilePath("updated_file_1.csv")): {
				Path:      GetTestFilePath("updated_file_1.csv"),
				Handler:   uh,
				Encoding:  text.UTF8,
				Format:    option.CSV,
				Delimiter: ',',
				LineBreak: text.LF,
			},
		},
	}

	err = TestTx.Commit(context.Background(), NewReferenceScope(tx), parser.TransactionControl{Token: parser.COMMIT})
	if err != nil {
		t.Fatalf("unexpected error %q", err.Error())
	}

	expectedCreatedContents = "column1,column2"
	createdContents, err = os.ReadFile(GetTestFilePath("created_file_1.csv"))
	if err != nil {
		t.Fatalf("unexpected error %q", err.Error())
	}

	if expectedCreatedContents != string(createdContents) {
		t.Errorf("created contents = %q, want %q", string(createdContents), expectedCreatedContents)
	}

	expectedUpdatedContents = "column1,column2\n1,str1\nupdate1,update2\n3,str3"
	updatedContents, err = os.ReadFile(GetTestFilePath("updated_file_1.csv"))
	if err != nil {
		t.Fatalf("unexpected error %q", err.Error())
	}

	if expectedUpdatedContents != string(updatedContents) {
		t.Errorf("updated contents = %q, want %q", string(updatedContents), expectedUpdatedContents)
	}
}

func TestTransaction_Rollback(t *testing.T) {
	defer func() {
		_ = TestTx.ReleaseResources()
		_ = TestTx.CachedViews.Clean(TestTx.FileContainer)
		TestTx.Session.SetStdout(NewDiscard())
		initFlag(TestTx.Flags)
	}()

	TestTx.Flags.SetQuiet(false)

	TestTx.UncommittedViews = UncommittedViews{
		mtx: &sync.RWMutex{},
		Created: map[string]*FileInfo{
			strings.ToUpper(GetTestFilePath("created_file.csv")): {
				Path: GetTestFilePath("created_file.csv"),
			},
		},
		Updated: map[string]*FileInfo{
			strings.ToUpper(GetTestFilePath("updated_file_1.csv")): {
				Path: GetTestFilePath("updated_file_1.csv"),
			},
		},
	}

	expect := fmt.Sprintf("Rollback: file %q is deleted.\nRollback: file %q is restored.\n", GetTestFilePath("created_file.csv"), GetTestFilePath("updated_file_1.csv"))

	tx := TestTx

	out := NewOutput()
	tx.Session.SetStdout(out)

	_ = TestTx.Rollback(NewReferenceScope(tx), nil)

	log := out.String()

	if log != expect {
		t.Errorf("Rollback: log = %q, want %q", log, expect)
	}
}


text:
package com.lightcrafts.media.jai.opimage;
import java.awt.RenderingHints;
import java.awt.image.RenderedImage;
import java.awt.image.renderable.ParameterBlock;
import java.awt.image.renderable.RenderedImageFactory;
import com.lightcrafts.mediax.jai.ROI;
import com.lightcrafts.mediax.jai.util.ImagingListener;
import com.lightcrafts.media.jai.util.ImageUtil;

/**
 * A RIF supporting the "Histogram" operation in the
 * rendered image layer.
 *
 * @since EA2
 * @see com.lightcrafts.mediax.jai.operator.HistogramDescriptor
 * @see HistogramOpImage
 *
 */
public class HistogramRIF implements RenderedImageFactory {

    /** Constructor. */
    public HistogramRIF() {}

    /**
     * Creates a new instance of HistogramOpImage
     * in the rendered layer. Any image layout information in
     * RenderingHints is ignored.
     * This method satisfies the implementation of RIF.
     */
    public RenderedImage create(ParameterBlock args,
                                RenderingHints hints) {
        RenderedImage src = args.getRenderedSource(0);

        int xStart = src.getMinX();	// default values
        int yStart = src.getMinY();

        int maxWidth = src.getWidth();
        int maxHeight = src.getHeight();

        ROI roi = (ROI)args.getObjectParameter(0);
        int xPeriod = args.getIntParameter(1);
        int yPeriod = args.getIntParameter(2);
        int[] numBins = (int[])args.getObjectParameter(3);
        double[] lowValue = (double[])args.getObjectParameter(4);
        double[] highValue = (double[])args.getObjectParameter(5);

        HistogramOpImage op = null;
        try {
            op = new HistogramOpImage(src,
                                      roi,
                                      xStart, yStart,
                                      xPeriod, yPeriod,
                                      numBins, lowValue, highValue);
        } catch (Exception e) {
            ImagingListener listener = ImageUtil.getImagingListener(hints);
            String message = JaiI18N.getString("HistogramRIF0");
            listener.errorOccurred(message, e, this, false);
        }

        return op;
    }
}


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>org.apache.hadoop.hbase.ipc Class Hierarchy (HBase 0.98.7-hadoop2 API)</title>
<meta name="date" content="2014-10-08">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.apache.hadoop.hbase.ipc

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

org.apache.hadoop.hbase.ipc.CoprocessorRpcChannel (implements com.google.protobuf.BlockingRpcChannel, com.google.protobuf.RpcChannel)

java.lang.Throwable (implements java.io.Serializable)

java.lang.Exception

java.io.IOException

org.apache.hadoop.hbase.ipc.CallerDisconnectedException

org.apache.hadoop.hbase.HBaseIOException

org.apache.hadoop.hbase.DoNotRetryIOException

org.apache.hadoop.hbase.ipc.FatalConnectionException

org.apache.hadoop.hbase.ipc.BadAuthException

org.apache.hadoop.hbase.ipc.UnsupportedCellCodecException

org.apache.hadoop.hbase.ipc.UnsupportedCompressionCodecException

org.apache.hadoop.hbase.ipc.WrongVersionException

org.apache.hadoop.hbase.ipc.RpcClient.FailedServerException

org.apache.hadoop.hbase.ipc.StoppedRpcClientException

org.apache.hadoop.ipc.RemoteException

org.apache.hadoop.hbase.ipc.RemoteWithExtrasException

org.apache.hadoop.hbase.ipc.RpcClient.CallTimeoutException

org.apache.hadoop.hbase.ipc.ServerNotRunningYetException

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2014 The Apache Software Foundation. All rights reserved.


text:
Contains Gulp tasks useful for Four Kitchens projects.

To include in your project:

```
npm install fourkitchens/project-gulp --save-dev
```

Then in a `gulpfile.js` file in your project root:

```
(function () {
  'use strict';
  let gulp = require('gulp-help')(require('gulp'));
  require('project-gulp')(gulp, []);
})();
```

If the second argument in `require('project-gulp')(gulp, [])` remains an empty array, all project-gulp tasks will be loaded. If you want to limit the tasks that get loaded, include only the task names that you want loaded in that array:

```
require('project-gulp')(gulp, ['phpcs', 'eslint']);
```

## Available tasks

**phpcs**

Options:

Runs phpcs tests on your codebase.

`--path` or `-p`: The path in which to check coding standards

`--exit` or `-e`: Exit with an error code if phpcs finds errors in a file

`--install` or `-i`: Installs phpcs and other dependencies using Composer prior to testing

Syntax:
```
gulp phpcs
gulp phpcs --path path/to/file
gulp phpcs --exit
gulp phpcs --install
```

To ignore paths, add them to a `.phpcsignore` file in your project root.

To override/extend the default ruleset, add a `ruleset.xml` file to your project root.

**eslint**

Runs eslint tests on your codebase.

Options:

`--path` or `-p`: The path in which to check coding standards

Syntax:
```
gulp eslint
gulp eslint -path path/to/file
```

To ignore paths, add them to a `.eslintignore` file in your project root.

To override/extend the default configuration, add a `.eslintrc` file to your project root.

**run**

Executes project run tasks defined in `project.yml` file in your project root.

See `example.project.yml`.

Options:

`--task` or `-t`: The name of the project task to run

`--yes` or `-y`: Automatically confirm all prompts

`--help` or `-h`: Print available run tasks

Syntax:
```
gulp run --task taskname
gulp run --yes --task taskname
gulp run --help
```

**drush-aliases**

Attempts to symlink any drush alias files in a `drush` directory in your project root to a `.drush` directory in your home folder.

Syntax:
```
gulp drush-aliases
```

## Helper tasks

**lint**

Runs all available linting tasks (e.g. phpcs and eslint) enabled for your project.

Syntax:
```
gulp lint
```


text:
package de.hpi.bpt.chimera.rest.beans.datamodel;

import javax.xml.bind.annotation.XmlRootElement;

import de.hpi.bpt.chimera.model.datamodel.DataAttribute;

/**
 *
 */
@XmlRootElement
public class DataAttributeJaxBean {
	private String id;
	private String name;
	private String type;

	/**
	 * Create a DataAttributeConfiguration for a DataAttribute.
	 *
	 * @param dataAttribute
	 */
	public DataAttributeJaxBean(DataAttribute dataAttribute) {
		setName(dataAttribute.getName());
		setId(dataAttribute.getId());
		setType(dataAttribute.getType());
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}
}


text:
React Component for transforming `application/vdom.v1+json` data to React
Elements.

## Installation

```
npm install --save @nteract/transform-vdom
```

Note: This transform is included in `@nteract/transforms` so if you're using that
you don't have to add this to your mimetype transforms.

## Usage

```js
import VDOMTransform from '@nteract/transform-vdom'

ReactDOM.render(
  <VDOMTransform
    // Data from display_data or execute_result mimebundle on the
    // mimetype key application/vdom.v1+json
    data={{ tagName: 'h1', children: 'Hey', attributes: {}}}
  >,
  rootEl)
```

Users of this mimetype are likely using a higher level library that lets
them write declaratively in their language of choice. For Python, there's
[`vdom`](https://github.com/nteract/vdom) which lets you write code like:

```python
from IPython.display import display
from vdom.helpers import h1, p, img, div, b

display(
    div(
        h1('Our Incredibly Declarative Example'),
        p('Can you believe we wrote this ', b('in Python'), '?'),
        img(src="https://media.giphy.com/media/xUPGcguWZHRC2HyBRS/giphy.gif"),
        p('What will ', b('you'), ' create next?'),
    )
)
```


text:
package org.apache.commons.lang3.concurrent;

/**
 *

 * An exception class used for reporting runtime error conditions related to
 * accessing data of background tasks.
 *

 *

 * This class is an analogon of the {@link ConcurrentException} exception class.
 * However, it is a runtime exception and thus does not need explicit catch
 * clauses. Some methods of {@link ConcurrentUtils} throw {@code
 * ConcurrentRuntimeException} exceptions rather than
 * {@link ConcurrentException} exceptions. They can be used by client code that
 * does not want to be bothered with checked exceptions.
 *

 *
 * @since 3.0
 */
public class ConcurrentRuntimeException extends RuntimeException {
    /**
     * The serial version UID.
     */
    private static final long serialVersionUID = -6582182735562919670L;

    /**
     * Creates a new, uninitialized instance of {@code
     * ConcurrentRuntimeException}.
     */
    protected ConcurrentRuntimeException() {
        super();
    }

    /**
     * Creates a new instance of {@code ConcurrentRuntimeException} and
     * initializes it with the given cause.
     *
     * @param cause the cause of this exception
     * @throws IllegalArgumentException if the cause is not a checked exception
     */
    public ConcurrentRuntimeException(final Throwable cause) {
        super(ConcurrentUtils.checkedException(cause));
    }

    /**
     * Creates a new instance of {@code ConcurrentRuntimeException} and
     * initializes it with the given message and cause.
     *
     * @param msg the error message
     * @param cause the cause of this exception
     * @throws IllegalArgumentException if the cause is not a checked exception
     */
    public ConcurrentRuntimeException(final String msg, final Throwable cause) {
        super(msg, ConcurrentUtils.checkedException(cause));
    }
}


text:
module.exports = (function(  hierarchy ){
    let element;
    hierarchy.reverse().forEach( documentType => {
        Object.values( this.tree ).forEach( document => {
            if( documentType === document.type) element = document
        } )
    });
     return element;
});


text:
VzSquareMatrixEntity::VzSquareMatrixEntity()
	: Position(glm::vec3(0.0f))
	, Orientation(glm::vec3(0.0f)) {
}

VzSquareMatrixEntity::~VzSquareMatrixEntity() {
}

void VzSquareMatrixEntity::create() {

	generate_matrix(2);

	_init_shader();
	_init_geometry();
	_init_material();

	ProjectionMat = VzCore::Camera.get_projection_matrix();
	ModelMat = glm::translate(ModelMat, Position);
}

void VzSquareMatrixEntity::generate_matrix(unsigned extent) {
	//assert(extent > 2);

	_square_extent = extent;

	////////////////////////////////////////////////////////////
	// create vertex

	for (unsigned z = 0; z < extent; z++)
	for (unsigned y = 0; y < extent; y++)
	for (unsigned x = 0; x < extent; x++) {
		_vertices.push_back(glm::vec3(x, y, z));
	}

	////////////////////////////////////////////////////////////
	// create index

	// x-axis lines
	glm::uvec2 x_base_line(0, extent - 1);
	for (unsigned muly = 0; muly < extent; muly++) {
		if (muly > 0)
			x_base_line += extent;

		for (unsigned i = 0; i < extent; i++) {
			unsigned next = i * extent * extent;
			_indices.push_back((x_base_line + next));
		}

	}

	// z-axis lines	: x^2*(x-1) = x^3-x^2
	glm::uvec2 z_base_line(0, std::pow(extent, 2) * (extent - 1));
	for (unsigned muly = 0; muly < extent; muly++) {
		if (muly > 0)
			z_base_line += extent;

		for (unsigned i = 0; i < extent; i++) {
			_indices.push_back((z_base_line + i));
		}
	}

	// y-axis lines : x^2-x
	glm::uvec2 y_base_line(0, std::pow(extent, 2) - extent);
	for (unsigned muly = 0; muly < extent; muly++) {
		if (muly > 0)
			y_base_line += (extent * extent);

		for (unsigned i = 0; i < extent; i++) {
			_indices.push_back((glm::uvec2(i,i) + y_base_line));
		}
	}
}

void VzSquareMatrixEntity::render() {
	think();

	_shader->use();
	_shader->set_mat4("projection", ProjectionMat);
	_shader->set_mat4("view", ViewMat);
	_shader->set_mat4("model", ModelMat);

	GLint last_blend_src_alpha; glGetIntegerv(GL_BLEND_SRC_ALPHA, &last_blend_src_alpha);
	GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glLineWidth((GLfloat)0.5f);

	glBindVertexArray(_vao);

	auto indicesSize = _indices.size() * sizeof(unsigned) * 2;
	glDrawElements(GL_LINES, indicesSize, GL_UNSIGNED_INT, 0);

	glLineWidth((GLfloat)1.0f);
	glBlendFunc(GL_SRC_ALPHA, last_blend_src_alpha);
	if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
}

void VzSquareMatrixEntity::destroy() {
	glDeleteVertexArrays(1, &_vao);
	glDeleteBuffers(1, &_vbo);
	glDeleteBuffers(1, &_ebo);
}

void VzSquareMatrixEntity::think() {
	ProjectionMat = VzCore::Camera.get_projection_matrix();
	ViewMat = VzCore::Camera.get_view_matrix();
}

void VzSquareMatrixEntity::_init_shader() {
	auto vsFilePath = VzFileSystem::get_path("/resource/shaders/square_matrix.vert");
	auto fsFilePath = VzFileSystem::get_path("/resource/shaders/square_matrix.frag");
	bool isValid = !(vsFilePath.empty() || fsFilePath.empty());

	BOOST_ASSERT_MSG(isValid, "ERROR: SHADER FILE LOAD FAIL.");
	if (!isValid)
		return;

	_shader = std::make_unique<VzShader>(vsFilePath.c_str(), fsFilePath.c_str());
}

void VzSquareMatrixEntity::_init_geometry() {

	auto verticesSize = _vertices.size() * sizeof(float) * 3;
	auto indicesSize = _indices.size() * sizeof(unsigned) * 2;
	auto verticesDataPtr = _vertices.data();
	auto indicesDataPtr = _indices.data();

	glGenVertexArrays(1, &_vao);
	glGenBuffers(1, &_vbo);
	glGenBuffers(1, &_ebo);

	glBindVertexArray(_vao);

	glBindBuffer(GL_ARRAY_BUFFER, _vbo);
	glBufferData(GL_ARRAY_BUFFER, verticesSize, verticesDataPtr, GL_STATIC_DRAW);

	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ebo);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, indicesSize, indicesDataPtr, GL_STATIC_DRAW);

	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
	glEnableVertexAttribArray(0);

	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindVertexArray(0);
}

void VzSquareMatrixEntity::_init_material() {
}


text:
package org.openntf.domino.formula;

import org.openntf.domino.commons.StandardLifeCycle;

public class FormulaLifeCycle extends StandardLifeCycle {

}


text:
<?php

namespace Baleen\Migrations\Delta\Comparator;

use Baleen\Migrations\Delta\DeltaInterface;

/**
 * Compares version ids. Useful mostly for testing.
 *
 * @author Gabriel Somoza <gabriel@strategery.io>
 */
final class IdComparator extends AbstractComparator
{
    /**
     * @inheritdoc
     */
    public function compare(DeltaInterface $version1, DeltaInterface $version2)
    {
        return strcmp($version1->getId(), $version2->getId());
    }
}


text:
var SpritePolygonTestIdx = -1;

var SpritePolygonTestDemo = BaseTestLayer.extend({
    _title:"",
    _subtitle:"",
    _debugDraw:null,
    _sp: null,
    _spp: null,

    ctor:function () {
        this._super();
    },

    initTouchDebugDraw: function() {
        var touchListener = cc.EventListener.create({
            event: cc.EventListener.TOUCH_ONE_BY_ONE,
            swallowTouch: true,
            onTouchBegan: function (touch, event) {
                var target = event.getCurrentTarget();
                return true;
            },
            onTouchMoved: function (touch, event) {
                var target = event.getCurrentTarget();
                var pos = touch.getDelta();
                var newScale = cc.clampf(target._spp.getScale() + pos.x * 0.01, 0.1, 2);
                target._spp.setScale(newScale);
                target._sp.setScale(newScale);
            },
            onTouchEnded: function (touch, event) {
                var target = event.getCurrentTarget();
            }
        });
        cc.eventManager.addListener(touchListener, this);
    },

    onRestartCallback:function (sender) {
        var s = new SpritePolygonTestScene();
        s.addChild(restartSpritePolygonTest());
        director.runScene(s);
    },

    onNextCallback:function (sender) {
        var s = new SpritePolygonTestScene();
        s.addChild(nextSpritePolygonTest());
        director.runScene(s);
    },

    onBackCallback:function (sender) {
        var s = new SpritePolygonTestScene();
        s.addChild(previousSpritePolygonTest());
        director.runScene(s);
    }
});

var SpritePolygonTestScene = cc.Scene.extend({
    ctor:function () {
        this._super();

        var label = new cc.LabelTTF("Main Menu", "Arial", 20);
        var menuItem = new cc.MenuItemLabel(label, this.onMainMenuCallback, this);

        var menu = new cc.Menu(menuItem);
        menu.x = 0;
        menu.y = 0;
        menuItem.x = winSize.width - 50;
        menuItem.y = 25;
        this.addChild(menu, 99);
    },
    onMainMenuCallback:function () {
        var scene = new cc.Scene();
        var layer = new TestController();
        scene.addChild(layer);
        director.runScene(scene);
    },
    runThisTest:function (num) {
        SpritePolygonTestIdx = (num || num == 0) ? (num - 1) : -1;
        var layer = nextSpritePolygonTest();
        this.addChild(layer);

        director.runScene(this);
    }
});

var SpritePolygonTest1 = SpritePolygonTestDemo.extend({
    _title:"PolygonSprite Creation",
    _subtitle:"new cc.Sprite(jsb.AutoPolygon.generatePolygon(filename))",

    ctor:function () {
        this._super();
        this.make2Sprites();
    },
    make2Sprites: function() {
        var polygons = jsb.AutoPolygon.generatePolygon(s_pathGrossini);
        this._spp = new cc.Sprite(polygons);
        this._spp.setPosition((0.5+0.15) * winSize.width, 0.5 * winSize.height);
        this.addChild(this._spp);

        this._sp = new cc.Sprite(s_pathGrossini);
        this.addChild(this._sp);
        this._sp.setPosition((0.5-0.15) * winSize.width, 0.5 * winSize.height);

        var ttfConfig = new cc.FontDefinition({
            fontName: "fonts/arial.ttf",
            fontSize: 8
        });
        var temp = "Sprite:\nPixels drawn: ";
        var spSize = this._sp.getContentSize();
        var spArea = new cc.LabelTTF(temp+Math.round(spSize.width*spSize.height), ttfConfig);
        spArea.anchorX = 0;
        spArea.anchorY = 1;
        this._sp.addChild(spArea);

        temp = "PolygonSprite:\nPixels drawn: ";
        var vertCount = "\nverts:"+Math.round(polygons.getVertCount());
        var sppArea = new cc.LabelTTF(temp+Math.round(polygons.getArea())+vertCount, ttfConfig);
        sppArea.anchorX = 0;
        sppArea.anchorY = 1;
        this._spp.addChild(sppArea);

        this.initTouchDebugDraw();
    }
});

var SpritePolygonTest2 = SpritePolygonTestDemo.extend({
    _title:"PolygonSprite Creation with a rect",
    _subtitle:"new cc.Sprite(jsb.AutoPolygon.generatePolygon(filename, rect))",

    ctor:function(){
        this._super();
        this.make2Sprites();
    },
    make2Sprites: function() {
        var head = cc.rect(30, 25, 25, 25);
        var polygons = jsb.AutoPolygon.generatePolygon(s_pathGrossini, head);
        this._spp = new cc.Sprite(polygons);
        this._spp.setPosition((0.5+0.15) * winSize.width, 0.5 * winSize.height);
        this.addChild(this._spp);

        this._sp = new cc.Sprite(s_pathGrossini, head);
        this.addChild(this._sp);
        this._sp.setPosition((0.5-0.15) * winSize.width, 0.5 * winSize.height);

        var ttfConfig = new cc.FontDefinition({
            fontName: "fonts/arial.ttf",
            fontSize: 8
        });
        var temp = "Sprite:\nPixels drawn: ";
        var spSize = this._sp.getContentSize();
        var spArea = new cc.LabelTTF(temp+Math.round(spSize.width*spSize.height), ttfConfig);
        spArea.anchorX = 0;
        spArea.anchorY = 1;
        this._sp.addChild(spArea);

        temp = "PolygonSprite:\nPixels drawn: ";
        var vertCount = "\nverts:"+Math.round(polygons.getVertCount());
        var sppArea = new cc.LabelTTF(temp+Math.round(polygons.getArea())+vertCount, ttfConfig);
        sppArea.anchorX = 0;
        sppArea.anchorY = 1;
        this._spp.addChild(sppArea);

        this.initTouchDebugDraw();
    }
});

var SpritePolygonTestSlider = SpritePolygonTestDemo.extend({
    _title:"Optimization Value (default:2.0)",
    _subtitle:"",

    _ttfConfig: null,
    _epsilonLabel: null,

    ctor: function () {
        this._super();

        this._ttfConfig = new cc.FontDefinition({
            fontName: "fonts/arial.ttf",
            fontSize: 8
        });

        var vsize = cc.visibleRect;
        var slider = new ccui.Slider();
        slider.setTouchEnabled(true);
        slider.loadBarTexture("ccs-res/cocosui/sliderTrack.png");
        slider.loadSlidBallTextures("ccs-res/cocosui/sliderThumb.png", "ccs-res/cocosui/sliderThumb.png", "");
        slider.loadProgressBarTexture("ccs-res/cocosui/sliderProgress.png");
        slider.setPosition(vsize.width/2, vsize.height/4);

        slider.addEventListener(this.changeEpsilon, this);
        slider.setPercent(Math.sqrt(1/19) * 100);

        this._epsilonLabel = new cc.LabelTTF("Epsilon: 2.0", this._ttfConfig);
        this.addChild(this._epsilonLabel);
        this._epsilonLabel.setPosition(vsize.width/2, vsize.height/4 + 15);
        this.addChild(slider);
    },
    makeSprites: function (list, y) {
        var vsize = cc.visibleRect;
        var offset = (vsize.width-100)/(list.length-1);
        for(var i = 0; i < list.length; i++)
        {
            var sp = this.makeSprite(list[i], 50+offset*i, y);
            this.addChild(sp);
        }
    },
    makeSprite: function (filename, x, y) {
        var sp = new cc.Sprite(filename);
        var quadSize = sp.getContentSize();
        var originalSize = quadSize.width * quadSize.height;
        var polygons = jsb.AutoPolygon.generatePolygon(filename);
        var ret = new cc.Sprite(polygons);
        ret.setPosition(x, y);

        var pixels = polygons.getArea()/originalSize*100;
        var spArea = new cc.LabelTTF(filename+"\nVerts: "+polygons.getVertCount()+ "\nPixels: "+pixels.toFixed(2)+"%", this._ttfConfig);
        ret.addChild(spArea);
        spArea.setAnchorPoint(cc.p(0,1));
        ret.setName(filename);
        ret.setAnchorPoint(cc.p(0.5, 0));
        return ret;
    },
    updateLabel: function (sp, polygons) {
        var label = sp.getChildren()[0];
        var filename = sp.getName();
        var w = polygons.rect.width/cc.director.getContentScaleFactor();
        var h = polygons.rect.width/cc.director.getContentScaleFactor();
        var pixels = polygons.getArea()/(w*h)*100;
        label.string = filename+"\nVerts: "+polygons.getVertCount()+"\nPixels: "+pixels.toFixed(2)+"%";
    },
    changeEpsilon: function (sender, type) {
        if (type == ccui.Slider.EVENT_PERCENT_CHANGED) {
            var epsilon = Math.pow(sender.getPercent()/100, 2) * 19 + 1;
            var children = this.children, child, file;
            for(var i = 0; i < children.length; i++) {
                child = children[i];
                file = child.getName();
                if(file.length) {
                    var polygons = jsb.AutoPolygon.generatePolygon(file, cc.rect(), epsilon);
                    child.setPolygonInfo(polygons);
                    this.updateLabel(child, polygons);
                }
            }
            this._epsilonLabel.setString("Epsilon: "+ epsilon.toFixed(2));
        }
    }
});

var SpritePolygonTest3 = SpritePolygonTestSlider.extend({
    _title:"Optimization Value (default:2.0)",
    _subtitle:"",

    ctor:function(){
        this._super();

        var vsize = cc.visibleRect;
        var list = [
            "Images/arrows.png",
            "Images/CyanTriangle.png",
            s_pathB2,
            "Images/elephant1_Diffuse.png"
        ];
        this.makeSprites(list, vsize.height/2);
    }
});

var SpritePolygonTest4 = SpritePolygonTestSlider.extend({
    _title:"Optimization Value (default:2.0)",
    _subtitle: "",

    ctor:function(){
        this._super();

        var vsize = cc.visibleRect;
        var list = [
            s_pathGrossini,
            "Images/grossinis_sister1.png",
            "Images/grossinis_sister2.png"
        ];
        this.makeSprites(list, vsize.height/2);
    }

});

var SpritePolygonPerformance = SpritePolygonTestDemo.extend({
    spriteCount: 0,
    vertCount: 0,
    triCount: 0,
    pixelCount: 0,
    elapsedTime: 0,
    perfLabel: null,
    continuousLowDt: 0,
    continuousHighDtTime: 0,
    waitingTime: 0,
    _posX: 0,
    _posY: 0,
    _leftX: 0,
    _rightX: 0,
    goRight: true,
    ended: false,
    prevDt: 0,
    _incVert: 0,
    _incTri: 0,
    _incPix: 0,
    ctor: function () {
        this._super();
        var ttfConfig = new cc.FontDefinition({
            fontName: "fonts/arial.ttf",
            fontSize: 10
        });
        this.perfLabel = new cc.LabelTTF("Performance test", ttfConfig);
        this.addChild(this.perfLabel);
        this.perfLabel.setPosition(cc.visibleRect.width/2, 80);

        var size = cc.visibleRect;
        this._posX = this._leftX = size.width*0.15;
        this._rightX = size.width*0.85;
        this._posY = size.height/2;
        this.prevDt = 0.016;
        this.goRight = true;
        this.ended = false;
        this.scheduleUpdate();
    },
    updateLabel: function () {
        var temp = "Nodes: "+this.spriteCount+" Triangles: "+this.triCount+"\nPixels: "+this.pixelCount.toFixed(2)+" Vertices: "+this.vertCount;
        if(!this.ended)
            this.perfLabel.string = temp;
    },
    makeSprite: function () {
        return new cc.Node();
    },
    update: function (dt) {
        dt = dt*0.3 + this.prevDt*0.7;
        this.prevDt = dt;
        this.elapsedTime += dt;
        var loops = (0.025-dt)*1000;
        if(dt < 0.025 && loops>0)
        {
            this.continuousHighDtTime = cc.clampf(this.continuousHighDtTime-dt*2, 0.0, 1.0);
            this.waitingTime = cc.clampf(this.waitingTime-dt, 0.0, 5.0);
            this.continuousLowDt++;
        }
        else
        {
            this.continuousHighDtTime+=dt;
            this.continuousLowDt = 0;
        }
        if (this.continuousLowDt >= 5 && loops > 0) {
            for(var i = 0; i < loops; i++)
            {
                if(this._posX >= this._rightX)
                {
                    this.goRight = false;
                }
                else if(this._posX <= this._leftX)
                {
                    this.goRight = true;
                }
                var s = this.makeSprite();
                this.addChild(s);
                s.setPosition(this._posX, this._posY);
                if(this.goRight)
                    this._posX++;
                else
                    this._posX--;

                this.incrementStats();
            }
            this.updateLabel();
        }

        //if we have 10 continuous low dt, then we will start to create more sprites
        else if(this.continuousHighDtTime >= 0.5 || this.waitingTime > 3.0){
            // its now 1 seconds with high DT time, time to end
            this.ended = true;
            this.unscheduleUpdate();
            this.perfLabel.string = "Test ended in " + this.elapsedTime + " seconds\nNodes: " + this.spriteCount + "   Triangles: " + this.triCount + "\nPixels: " + this.pixelCount.toFixed() + "   Vertices: " + this.vertCount;
            this.getChildByTag(BASE_TEST_SUBTITLE_TAG).string = "Test ended";
        }
        else{
            this.waitingTime += dt;
        }
    },
    incrementStats: function () {
        this.spriteCount ++;
        this.vertCount += this._incVert;
        this.triCount += this._incTri;
        this.pixelCount += this._incPix;
    }
});

var SpritePolygonPerformanceTestDynamic = SpritePolygonPerformance.extend({
    _title: "Dynamic SpritePolygon Performance",
    _subtitle: "Test running, please wait until it ends",
    _polygons: null,
    ctor: function () {
        this._super();
        this._polygons = jsb.AutoPolygon.generatePolygon(s_pathGrossini);
        this.initIncrementStats();
    },
    initIncrementStats: function () {
        this._incVert = this._polygons.getVertCount();
        this._incTri = this._polygons.getTrianglesCount();
        this._incPix = this._polygons.getArea();
    },
    makeSprite: function () {
        var ret = new cc.Sprite(this._polygons);
        ret.runAction(cc.rotateBy(1,360).repeatForever());
        return ret;
    }
});

var SpritePerformanceTestDynamic = SpritePolygonPerformance.extend({
    _title: "Dynamic Sprite Performance",
    _subtitle: "Test running, please wait until it ends",
    ctor: function () {
        this._super();
        this.initIncrementStats();
    },
    initIncrementStats: function () {
        var t = new cc.Sprite(s_pathGrossini);
        this._incVert = 4;
        this._incTri = 2;
        this._incPix = t.width * t.height;
    },
    makeSprite: function () {
        var ret = new cc.Sprite(s_pathGrossini);
        ret.runAction(cc.rotateBy(1,360).repeatForever());
        return ret;
    }
});

//
// Flow control
//
var arrayOfSpritePolygonTest = [
    SpritePolygonTest1,
    SpritePolygonTest2,
    SpritePolygonTest3,
    SpritePolygonTest4,
    SpritePolygonPerformanceTestDynamic,
    SpritePerformanceTestDynamic
];

var nextSpritePolygonTest = function () {
    SpritePolygonTestIdx++;
    SpritePolygonTestIdx = SpritePolygonTestIdx % arrayOfSpritePolygonTest.length;

    if(window.sideIndexBar){
        SpritePolygonTestIdx = window.sideIndexBar.changeTest(SpritePolygonTestIdx, 36);
    }

    return new arrayOfSpritePolygonTest[SpritePolygonTestIdx ]();
};
var previousSpritePolygonTest = function () {
    SpritePolygonTestIdx--;
    if (SpritePolygonTestIdx < 0)
        SpritePolygonTestIdx += arrayOfSpritePolygonTest.length;

    if(window.sideIndexBar){
        SpritePolygonTestIdx = window.sideIndexBar.changeTest(SpritePolygonTestIdx, 36);
    }

    return new arrayOfSpritePolygonTest[SpritePolygonTestIdx ]();
};
var restartSpritePolygonTest = function () {
    return new arrayOfSpritePolygonTest[SpritePolygonTestIdx ]();
};


text:
CKEDITOR.plugins.setLang( 'clipboard', 'lv', {
	copy: 'Kopēt',
	copyError: 'Jūsu pārlūkprogrammas drošības iestatījumi nepieļauj redaktoram automātiski veikt kopēšanas darbību.  Lūdzu, izmantojiet (Ctrl/Cmd+C), lai veiktu šo darbību.',
	cut: 'Izgriezt',
	cutError: 'Jūsu pārlūkprogrammas drošības iestatījumi nepieļauj redaktoram automātiski veikt izgriezšanas darbību.  Lūdzu, izmantojiet (Ctrl/Cmd+X), lai veiktu šo darbību.',
	paste: 'Ielīmēt',
	pasteArea: 'Ielīmēšanas zona',
	pasteMsg: 'Lūdzu, ievietojiet tekstu šajā laukumā, izmantojot klaviatūru (Ctrl/Cmd+V) un apstipriniet ar Darīts!.',
	securityMsg: 'Jūsu pārlūka drošības uzstādījumu dēļ, nav iespējams tieši piekļūt jūsu starpliktuvei. Jums jāielīmē atkārtoti šajā logā.',
	title: 'Ievietot'
} );


text:
@interface GGM_UIViewIsometric ()

@property (assign) int currentDragX;
@property (assign) int currentDragY;

@end

@implementation GGM_UIViewIsometric

@synthesize viewDictInDrawOrderArray = viewDictInDrawOrderArray_;
@synthesize currentDragX = currentDragX_;
@synthesize currentDragY = currentDragY_;
@synthesize dragBeganAtX = dragBeganAtX_;
@synthesize dragBeganAtY = dragBeganAtY_;

#pragma mark - getting the closest point

- (NSDictionary *)closestDictToPoint:(CGPoint)point
{
	// loop through all the tiles to find the closest one
	int x, y;//, closestX, closestY;
	float distanceFromCenter, closestDistanceFromCenter = self.frame.size.width;
	float halfheight = self.gridPixelHeight / 2.0f;
	int dictCount = (int)[viewDictInDrawOrderArray_ count];
//	NSLog(@"halfheight = %f, dictCount = %i", halfheight, dictCount);
	NSDictionary *dict;
	NSDictionary *closestDict;
	UIView *view;
	for (int i=(dictCount-1); i>=0; i--) {
		dict = [viewDictInDrawOrderArray_ objectAtIndex:i];
		x = [[dict objectForKey:kGGM_IsoViewDict_x] intValue];
		y = [[dict objectForKey:kGGM_IsoViewDict_y] intValue];
		view = [self viewForX:x andY:y];
		distanceFromCenter = (fabs(view.center.x - point.x) / 2.0f) + fabs(view.center.y - point.y);
		if (distanceFromCenter < closestDistanceFromCenter) {
			NSLog(@"found a closer xy at %i,%i, distanceFromCenter was %f", x, y, distanceFromCenter);
//			closestX = x;
//			closestY = y;
			closestDistanceFromCenter = distanceFromCenter;
			closestDict = dict;
			if (distanceFromCenter < halfheight) {
				break;
			}
		}
	}
//	x = closestX;
//	y = closestY;
	return closestDict;
}

- (NSDictionary *)closestDictToPoint:(CGPoint)point fromX:(int)x andY:(int)y
{
	UIView *view;
	int closestY = 0, closestX = 0;
	float distanceFromCenter, closestDistance = self.frame.size.width;
	for (int py = y-1; py <= y+1; py++) {
		if (py < 0 || py >= self.game.gridHeight) {
			continue;
		}
		for (int px = x-1; px <= x+1; px++) {
			if (px < 0 || px >= self.game.gridWidth) {
				continue;
			}

			view = [self viewForX:px andY:py];
			distanceFromCenter = (fabs(view.center.x - point.x) / 2.0f) + fabs(view.center.y - point.y);
			if (distanceFromCenter < closestDistance) {
				closestDistance = distanceFromCenter;
				closestX = px;
				closestY = py;
			}
		}
	}
	return [NSDictionary dictionaryWithObjectsAndKeys:
			[NSNumber numberWithInt:closestX], kGGM_IsoViewDict_x,
			[NSNumber numberWithInt:closestY], kGGM_IsoViewDict_y,
			nil];
}

#pragma mark - taps

- (void)handleTap:(UITapGestureRecognizer *)sender
{
	NSLog(@"self: %@", self.game);

	CGPoint tapPoint = [sender locationInView:self];

//	int x = tapPoint.y / self.gridPixelHeight + self.game.gridWidth / (2 * self.gridPixelWidth);
//	screenY/tileH + screenX / (2*tileW)
//	int y = self.game.gridHeight / self.gridPixelHeight - tapPoint.x / (2 * self.gridPixelHeight);
//	screenY / tileH - screenX / (2*tileW)

	// from tonypa: http://www.tonypa.pri.ee/tbw/tut18.html
//	int x,y;
//	float fy = ((tapPoint.y*2.0f)-tapPoint.x)/2.0f;
//	float fx = tapPoint.x + fy;
//	y = lroundf(fy / self.gridPixelWidth);
//	x = lroundf(fx / self.gridPixelWidth) - 1;

	// yet another try, found here: http://stackoverflow.com/a/13838164/18961
//	int x,y;
//	float fy = ((tapPoint.y*2.0f)-(((self.game.gridHeight-1)*self.gridPixelWidth)/2.0f)+tapPoint.x)/2.0f;
//	float fx = tapPoint.x - fy;
//	y = (fy / self.gridPixelWidth) *2;
//	x = (fx / self.gridPixelWidth) *2;

	// my own attempt
//	int x,y;
//	float halfHeight = self.frame.size.height / 2.0f;
//	float halfWidth = self.frame.size.width / 2.0f;
//	float xOffset = (tapPoint.y < halfHeight) ? (halfWidth / halfHeight) * (halfHeight - tapPoint.y) : (halfWidth / halfHeight) * (tapPoint.y - halfHeight);
//	float realX = tapPoint.x - xOffset;
//	int almostX = realX / self.gridPixelWidth;
//	float leftover = realX - (self.gridPixelWidth * almostX);
//	float almostY = tapPoint.y / self.gridPixelHeight
//
//	NSLog(@"xOffset is %f for frame: %@", xOffset, NSStringFromCGRect(self.frame));

	NSDictionary *closestDict = [self closestDictToPoint:tapPoint];

	int x = [[closestDict objectForKey:kGGM_IsoViewDict_x] intValue];
	int y = [[closestDict objectForKey:kGGM_IsoViewDict_y] intValue];

	int state = [self.game stateAtX:x andY:y];

	NSLog(@"ISOMETRIC tap discovered at: %@, coords: {%i, %i} with state: %i", NSStringFromCGPoint(tapPoint), x, y, state);

	[self handleTapAtX:x andY:y];
}

#pragma mark - drags

- (void)handleDrag:(UIPanGestureRecognizer*)sender
{
	CGPoint dragPoint = [sender locationInView:self];

	if (sender.state == UIGestureRecognizerStateBegan) {
		self.dragPointBegan = dragPoint;
		self.isDragging = YES;

		NSDictionary *closestDict = [self closestDictToPoint:dragPoint];

		int x = [[closestDict objectForKey:kGGM_IsoViewDict_x] intValue];
		int y = [[closestDict objectForKey:kGGM_IsoViewDict_y] intValue];
		self.currentDragX = x;
		self.currentDragY = y;

		self.dragBeganAtX = x;
		self.dragBeganAtY = y;

		[self handleDragAtX:x andY:y];

		NSLog(@"drag started at: %@, coords are: {%i, %i}", NSStringFromCGPoint(dragPoint), x, y);
	}
	else if (sender.state == UIGestureRecognizerStateEnded) {
		self.dragPointEnded = dragPoint;
		self.isDragging = NO;

//		NSLog(@"drag ended at: %@, coords are: {%i, %i}", NSStringFromCGPoint(dragPoint), x, y);
		[self handleDragEnd];
	}
	else {
		self.dragPointCurrent = dragPoint;

		NSDictionary *closestDict = [self closestDictToPoint:dragPoint fromX:self.currentDragX andY:self.currentDragY];
		int x = [[closestDict objectForKey:kGGM_IsoViewDict_x] intValue];
		int y = [[closestDict objectForKey:kGGM_IsoViewDict_y] intValue];

		if (x != self.currentDragX || y != self.currentDragY) {
			self.currentDragX = x;
			self.currentDragY = y;
			[self handleDragAtX:x andY:y];
		}

	}
}

- (void)handleDragAtX:(int)x andY:(int)y
{
	// reverse the state
	int state = [self.game stateAtX:x andY:y];
	int newState = (state == 0) ? 1 : 0;
	[self.game setStateAtX:x andY:y toState:newState];
	[self refreshViewPositionsAndStates];
}

#pragma mark - board drawing and setup

- (void)refreshViewPositionsAndStates
{
	int gameState = 0;
	int x, y;
	UIView *view;
	UIImage *image;
	for (NSDictionary *dict in self.viewDictInDrawOrderArray) {
		x = [[dict objectForKey:kGGM_IsoViewDict_x] intValue];
		y = [[dict objectForKey:kGGM_IsoViewDict_y] intValue];
		view = [[self.gridViewArray objectAtIndex:y] objectAtIndex:x];
		gameState = [self.game stateAtX:x andY:y];
		image = [self imageForGameState:gameState];
		[(UIImageView*)view setImage:image];
	}
}

- (void)setupInitialGridViewArray
{
	// note, this only works with "square" grids
	int gridHeightWidth = self.game.gridWidth;
	self.gridPixelWidth = self.frame.size.width / gridHeightWidth;
	self.gridPixelHeight =  self.frame.size.height / gridHeightWidth;
//	NSLog(@"gridPixelWidth = %f, gridPixelHeight = %f", self.gridPixelWidth, self.gridPixelHeight);

	self.gridViewArray = [NSMutableArray arrayWithCapacity:gridHeightWidth];

	NSMutableArray *subarray;
	int gameState = 0;
	UIView *view;
	float posX, posY;
	float startY = (self.frame.size.height / 2.0f) - (self.gridPixelHeight / 2.0f);
	float startX = 0.0f;
	for (int y = 0; y < gridHeightWidth; y++) {

		subarray = [NSMutableArray arrayWithCapacity:self.game.gridWidth];

		for (int x = 0; x < gridHeightWidth; x++) {

			gameState = [self.game stateAtX:x andY:y];
			view = (UIView*)[self newSubviewForGameState:gameState];

			posX = startX + (x * 0.5f * self.gridPixelWidth);
			posY = startY - (x * 0.5f * self.gridPixelHeight);
//			NSLog(@"posX: %f, posY: %f, ", posX, posY);

			[view setFrame:CGRectMake(posX, posY, self.gridPixelWidth, self.gridPixelHeight)];

			[self addSubview:view];
			[subarray insertObject:view atIndex:x];
		}

		// add the subarray to our gridViewArray
		[self.gridViewArray insertObject:subarray atIndex:y];

		// increment startY
		startY = startY + (self.gridPixelHeight / 2.0f);
		// increment startX
		startX = startX + (self.gridPixelWidth / 2.0f);
	}

	// lets also create a convenience array for updating the view
	// 7,0
	// 6,0 7,1
	// 5,0 6,1, 7,2
	// ...
	// 0,0 1,1 2,2 3,3 4,4 5,5 6,6 7,7
	// 0,1 1,2 2,3 3,4 4,5 5,6 6,7
	// ...
	// 0,5 1,6 2,7
	// 0,6 1,7
	// 0,7
	int totalRows = gridHeightWidth * 2;
	NSMutableArray *tempArr = [NSMutableArray arrayWithCapacity:(gridHeightWidth*gridHeightWidth)];
	NSDictionary *dict;
	int maxX = gridHeightWidth - 1;
	int x = maxX;
	int y = 0;
	int tempX, tempY;
	int toDo = 1;
	for (int row = 0; row < totalRows; row++) {

		NSLog(@"setting up row %i (width %i) starting from x,y: %i,%i", row, toDo, x, y);

		for (int i = 0; i < toDo; i++) {
			tempX = x + i;
			tempY = y + i;
			dict = [NSDictionary dictionaryWithObjectsAndKeys:
					[NSNumber numberWithInt:tempX], kGGM_IsoViewDict_x,
					[NSNumber numberWithInt:tempY], kGGM_IsoViewDict_y,
//					[[self.gridViewArray objectAtIndex:y] objectAtIndex:x], kGGM_IsoViewDict_view,
					nil];
			[tempArr addObject:dict];
		}

		// change ToDo
		if (row < gridHeightWidth -1) {
			x = x - 1;
			toDo = toDo + 1;
		}
		else {
			x = 0;
			y = y + 1;
			toDo = toDo - 1;
		}
	}
	viewDictInDrawOrderArray_ = [NSArray arrayWithArray:tempArr];
}

@end