text:
require "datastore_helper"

# This test is a ruby version of gcloud-node's datastore test.

describe "Datastore", :datastore do

  it "should allocate IDs" do
    incomplete_key = Gcloud::Datastore::Key.new "Kind"
    incomplete_key.wont_be :complete?

    keys = dataset.allocate_ids incomplete_key, 10

    keys.count.must_equal 10
    keys.each { |key| key.must_be :complete? }
  end

  describe "create, retrieve and delete" do

    let(:post) do
      Gcloud::Datastore::Entity.new.tap do |e|
        e["title"]       = "How to make the perfect pizza in your grill"
        e["tags"]        = ["pizza", "grill"]
        e["publishedAt"] = Time.new 2001, 1, 1
        e["author"]      = "Silvano"
        e["isDraft"]     = false
        e["wordCount"]   = 400
        e["rating"]      = 5.0
      end
    end

    let(:post2) do
      Gcloud::Datastore::Entity.new.tap do |e|
        e["title"]       = "How to make the perfect homemade pasta"
        e["tags"]        = ["pasta", "homemade"]
        e["publishedAt"] = Time.parse "2001-01-01T00:00:00.000Z"
        e["author"]      = "Silvano"
        e["isDraft"]     = false
        e["wordCount"]   = 450
        e["rating"]      = 4.5
      end
    end

    it "should save/find/delete with a key name" do
      post.key = Gcloud::Datastore::Key.new "Post", "post1"
      dataset.save post

      refresh = dataset.find post.key
      refresh.key.kind.must_equal        post.key.kind
      refresh.key.id.must_equal          post.key.id
      refresh.key.name.must_equal        post.key.name
      refresh.properties.to_h.must_equal post.properties.to_h

      dataset.delete post
      refresh = dataset.find post.key
      refresh.must_be :nil?
    end

    it "should save/find with a key name and delete with a key" do
      post.key = Gcloud::Datastore::Key.new "Post", "post1"
      dataset.save post

      refresh = dataset.find post.key
      refresh.key.kind.must_equal        post.key.kind
      refresh.key.id.must_equal          post.key.id
      refresh.key.name.must_equal        post.key.name
      refresh.properties.to_h.must_equal post.properties.to_h

      dataset.delete post.key
      refresh = dataset.find post.key
      refresh.must_be :nil?
    end

    it "should save/find/delete with a numeric key id" do
      post.key = Gcloud::Datastore::Key.new "Post", 123456789
      dataset.save post

      refresh = dataset.find post.key
      refresh.key.kind.must_equal        post.key.kind
      refresh.key.id.must_equal          post.key.id
      refresh.key.name.must_equal        post.key.name
      refresh.properties.to_h.must_equal post.properties.to_h

      dataset.delete post
      refresh = dataset.find post.key
      refresh.must_be :nil?
    end

    it "should save/find/delete with a generated key id" do
      post.key = Gcloud::Datastore::Key.new "Post"

      post.key.id.must_be :nil?

      dataset.save post

      post.key.id.wont_be :nil?

      refresh = dataset.find "Post", post.key.id
      refresh.key.kind.must_equal        post.key.kind
      refresh.key.id.must_equal          post.key.id
      refresh.key.name.must_equal        post.key.name
      refresh.properties.to_h.must_equal post.properties.to_h

      dataset.delete post
      refresh = dataset.find post.key
      refresh.must_be :nil?
    end

    it "should save/find/delete multiple entities at once" do
      post.key  = Gcloud::Datastore::Key.new "Post"
      post2.key = Gcloud::Datastore::Key.new "Post"

      post.key.id.must_be :nil?
      post2.key.id.must_be :nil?

      dataset.save post, post2

      post.key.id.wont_be :nil?
      post2.key.id.wont_be :nil?

      entities = dataset.find_all post.key, post2.key
      entities.count.must_equal 2

      dataset.delete post, post2

      entities = dataset.find_all post.key, post2.key
      entities.count.must_equal 0
    end

    it "entities retrieved from datastore have immutable keys" do
      post.key = Gcloud::Datastore::Key.new "Post", "post1"
      dataset.save post

      refresh = dataset.find post.key
      refresh.must_be :persisted?
      refresh.key.must_be :frozen?

      assert_raises RuntimeError do
        refresh.key = Gcloud::Datastore::Key.new "User", 456789
      end

      assert_raises RuntimeError do
        refresh.key.id = 456789
      end

      dataset.delete post
    end

  end

  it "should be able to save keys as a part of entity and query by key" do
    person = Gcloud::Datastore::Entity.new
    person.key = Gcloud::Datastore::Key.new "Person", "name"
    person["fullName"] = "Full name"
    person["linkedTo"] = person.key # itself
    dataset.save person

    query = Gcloud::Datastore::Query.new.kind("Person").
      where("linkedTo", "=", person.key)

    entities = dataset.run query
    entities.count.must_equal 1

    entity = entities.first
    entity["fullName"].must_equal      person["fullName"]
    entity["linkedTo"].kind.must_equal person["linkedTo"].kind
    entity["linkedTo"].id.must_equal   person["linkedTo"].id
    entity["linkedTo"].name.must_equal person["linkedTo"].name
  end

  describe "querying the datastore" do

    let(:book) do
      book = Gcloud::Datastore::Entity.new.tap do |e|
        e["title"] = "Game of Thrones"
      end
      book.key = Gcloud::Datastore::Key.new "Book", "GoT"
      book
    end

    let(:rickard) do
      character = Gcloud::Datastore::Entity.new.tap do |e|
        e["name"]        = "Rickard"
        e["family"]      = "Stark"
        e["appearances"] = 0
        e["alive"]       = false
      end
      character.key = Gcloud::Datastore::Key.new "Character", "Rickard"
      character.key.parent = book
      character
    end

    let(:eddard) do
      character = Gcloud::Datastore::Entity.new.tap do |e|
        e["name"]        = "Eddard"
        e["family"]      = "Stark"
        e["appearances"] = 9
        e["alive"]       = false
      end
      character.key = Gcloud::Datastore::Key.new "Character", "Eddard"
      character.key.parent = rickard
      character
    end

    let(:catelyn) do
      character = Gcloud::Datastore::Entity.new.tap do |e|
        e["name"]        = "Catelyn"
        e["family"]      = "Stark"
        e["appearances"] = 26
        e["alive"]       = false
      end
      character.key = Gcloud::Datastore::Key.new "Character", "Catelyn"
      character.key.parent = book
      character
    end

    let(:arya) do
      character = Gcloud::Datastore::Entity.new.tap do |e|
        e["name"]        = "Arya"
        e["family"]      = "Stark"
        e["appearances"] = 33
        e["alive"]       = true
      end
      character.key = Gcloud::Datastore::Key.new "Character", "Arya"
      character.key.parent = eddard
      character
    end

    let(:sansa) do
      character = Gcloud::Datastore::Entity.new.tap do |e|
        e["name"]        = "Sansa"
        e["family"]      = "Stark"
        e["appearances"] = 31
        e["alive"]       = true
      end
      character.key = Gcloud::Datastore::Key.new "Character", "Sansa"
      character.key.parent = eddard
      character
    end

    let(:robb) do
      character = Gcloud::Datastore::Entity.new.tap do |e|
        e["name"]        = "Robb"
        e["family"]      = "Stark"
        e["appearances"] = 22
        e["alive"]       = false
      end
      character.key = Gcloud::Datastore::Key.new "Character", "Robb"
      character.key.parent = eddard
      character
    end

    let(:bran) do
      character = Gcloud::Datastore::Entity.new.tap do |e|
        e["name"]        = "Bran"
        e["family"]      = "Stark"
        e["appearances"] = 25
        e["alive"]       = true
      end
      character.key = Gcloud::Datastore::Key.new "Character", "Bran"
      character.key.parent = eddard
      character
    end

    let(:jonsnow) do
      character = Gcloud::Datastore::Entity.new.tap do |e|
        e["name"]        = "Jon Snow"
        e["family"]      = "Stark"
        e["appearances"] = 32
        e["alive"]       = true
      end
      character.key = Gcloud::Datastore::Key.new "Character", "Jon Snow"
      character.key.parent = eddard
      character
    end

    let(:characters) do
      [rickard, eddard, catelyn, arya, sansa, robb, bran, jonsnow]
    end

    before do
      dataset.save *characters
    end

    it "should limit queries" do
      # first page
      query = Gcloud::Datastore::Query.new.
        kind("Character").ancestor(book).limit(5)
      entities = dataset.run query
      entities.count.must_equal 5

      # second page
      query.offset 5
      entities = dataset.run query
      entities.count.must_equal 3

      # third page
      query.offset 10
      entities = dataset.run query
      entities.count.must_equal 0
    end

    it "should filter queries with simple indexes" do
      query = Gcloud::Datastore::Query.new.
        kind("Character").ancestor(book).
        where("appearances", ">=", 20)
      entities = dataset.run query
      entities.count.must_equal 6
    end

    it "should filter queries with defined indexes" do
      query = Gcloud::Datastore::Query.new.
        kind("Character").ancestor(book).
        where("family", "=", "Stark").
        where("appearances", ">=", 20)
      entities = dataset.run query
      entities.count.must_equal 6
    end

    it "should filter by ancestor key" do
      query = Gcloud::Datastore::Query.new.
        kind("Character").ancestor(book.key)
      entities = dataset.run query
      entities.count.must_equal 8
    end

    it "should filter by ancestor entity" do
      query = Gcloud::Datastore::Query.new.
        kind("Character").ancestor(book)
      entities = dataset.run query
      entities.count.must_equal 8
    end

    it "should filter by key" do
      query = Gcloud::Datastore::Query.new.
        kind("Character").ancestor(book).
        where("__key__", "=", rickard.key)
      entities = dataset.run query
      entities.count.must_equal 1
    end

    it "should order queries" do
      query = Gcloud::Datastore::Query.new.
        kind("Character").ancestor(book).
        order("appearances")
      entities = dataset.run query
      entities.count.must_equal      characters.count
      entities[0]["name"].must_equal rickard["name"]
      entities[7]["name"].must_equal arya["name"]
    end

    it "should select projections" do
      query = Gcloud::Datastore::Query.new.
        kind("Character").ancestor(book).
        select("name", "family")
      entities = dataset.run query
      entities.each do |entity|
        entity.properties.to_h.keys.count.must_equal 2
        entity.properties["name"].wont_be :nil?
        entity.properties["family"].wont_be :nil?
      end
    end

    it "should paginate with offset and limit" do
      query = Gcloud::Datastore::Query.new.
        kind("Character").ancestor(book).
        limit(3).offset(2).order("appearances")
      entities = dataset.run query
      entities.count.must_equal 3
      entities[0]["name"].must_equal robb["name"]
      entities[2]["name"].must_equal catelyn["name"]

      # next page
      query.offset(5)
      entities = dataset.run query
      entities.count.must_equal 3
      entities[0]["name"].must_equal sansa["name"]
      entities[2]["name"].must_equal arya["name"]
    end

    it "should resume from a start cursor" do
      query = Gcloud::Datastore::Query.new.
        kind("Character").ancestor(book).
        limit(3).order("appearances")
      entities = dataset.run query
      entities.count.must_equal 3
      entities[0]["name"].must_equal rickard["name"]
      entities[2]["name"].must_equal robb["name"]

      next_cursor = entities.cursor
      next_cursor.wont_be :nil?
      next_query = Gcloud::Datastore::Query.new.
        kind("Character").ancestor(book).
        limit(3).order("appearances").
        cursor(next_cursor)
      next_entities = dataset.run next_query
      next_entities.count.must_equal 3
      next_entities[0]["name"].must_equal bran["name"]
      next_entities[2]["name"].must_equal sansa["name"]

      last_cursor = next_entities.cursor
      last_cursor.wont_be :nil?
      last_query = Gcloud::Datastore::Query.new.
        kind("Character").ancestor(book).
        limit(3).order("appearances").
        cursor(last_cursor)
      last_entities = dataset.run last_query
      last_entities.count.must_equal 2
      last_entities[0]["name"].must_equal jonsnow["name"]
      last_entities[1]["name"].must_equal arya["name"]
    end

    it "should group queries" do
      query = Gcloud::Datastore::Query.new.
        kind("Character").ancestor(book).
        group_by("alive")
      entities = dataset.run query
      entities.count.must_equal 2
    end

    after do
      dataset.delete *characters
    end
  end

  describe "transactions" do

    it "should run in a transaction block" do
      obj = Gcloud::Datastore::Entity.new
      obj.key = Gcloud::Datastore::Key.new "Company", "Google"
      obj["url"] = "www.google.com"

      dataset.transaction do |t|
        entity = t.find obj.key
        if entity.nil?
          t.save obj
        end
      end

      entity = dataset.find obj.key
      entity.wont_be :nil?
      entity.key.kind.must_equal        obj.key.kind
      entity.key.id.must_equal          obj.key.id
      entity.key.name.must_equal        obj.key.name
      entity.properties.to_h.must_equal obj.properties.to_h
      dataset.delete entity
    end

    it "should run in an explicit transaction" do
      obj = Gcloud::Datastore::Entity.new
      obj.key = Gcloud::Datastore::Key.new "Company", "Google"
      obj["url"] = "www.google.com"

      tx = dataset.transaction
      tx.id.wont_be :nil?

      if tx.find(obj.key).nil?
        tx.save obj
      end
      # Don't handle errors and rollback, let test fail
      tx.commit

      entity = dataset.find obj.key
      entity.wont_be :nil?
      entity.key.kind.must_equal        obj.key.kind
      entity.key.id.must_equal          obj.key.id
      entity.key.name.must_equal        obj.key.name
      entity.properties.to_h.must_equal obj.properties.to_h
      dataset.delete entity
    end
  end
end


text:
package middleware

import (
	"errors"
	"fmt"
	"reflect"
	"sync"
)

// 实体的接口类型。
type Entity interface {
	Id() uint32 // ID的获取方法。
}

// 实体池的接口类型。
type Pool interface {
	Take() (Entity, error)      // 取出实体
	Return(entity Entity) error // 归还实体。
	Total() uint32              // 实体池的容量。
	Used() uint32               // 实体池中已被使用的实体的数量。
}

// 创建实体池。
func NewPool(
	total uint32,
	entityType reflect.Type,
	genEntity func() Entity) (Pool, error) {
	if total == 0 {
		errMsg :=
			fmt.Sprintf("The pool can not be initialized! (total=%d)\n", total)
		return nil, errors.New(errMsg)
	}
	size := int(total)
	container := make(chan Entity, size)
	idContainer := make(map[uint32]bool)
	for i := 0; i < size; i++ {
		newEntity := genEntity()
		if entityType != reflect.TypeOf(newEntity) {
			errMsg :=
				fmt.Sprintf("The type of result of function genEntity() is NOT %s!\n", entityType)
			return nil, errors.New(errMsg)
		}
		container <- newEntity
		idContainer[newEntity.Id()] = true
	}
	pool := &myPool{
		total:       total,
		etype:       entityType,
		genEntity:   genEntity,
		container:   container,
		idContainer: idContainer,
	}
	return pool, nil
}

// 实体池的实现类型。
type myPool struct {
	total       uint32          // 池的总容量。
	etype       reflect.Type    // 池中实体的类型。
	genEntity   func() Entity   // 池中实体的生成函数。
	container   chan Entity     // 实体容器。
	idContainer map[uint32]bool // 实体ID的容器。
	mutex       sync.Mutex      // 针对实体ID容器操作的互斥锁。
}

func (pool *myPool) Take() (Entity, error) {
	entity, ok := <-pool.container
	if !ok {
		return nil, errors.New("The inner container is invalid!")
	}
	pool.mutex.Lock()
	defer pool.mutex.Unlock()
	pool.idContainer[entity.Id()] = false
	return entity, nil
}

func (pool *myPool) Return(entity Entity) error {
	if entity == nil {
		return errors.New("The returning entity is invalid!")
	}
	if pool.etype != reflect.TypeOf(entity) {
		errMsg := fmt.Sprintf("The type of returning entity is NOT %s!\n", pool.etype)
		return errors.New(errMsg)
	}
	entityId := entity.Id()
	casResult := pool.compareAndSetForIdContainer(entityId, false, true)
	if casResult == 1 {
		pool.container <- entity
		return nil
	} else if casResult == 0 {
		errMsg := fmt.Sprintf("The entity (id=%d) is already in the pool!\n", entityId)
		return errors.New(errMsg)
	} else {
		errMsg := fmt.Sprintf("The entity (id=%d) is illegal!\n", entityId)
		return errors.New(errMsg)
	}
}

// 比较并设置实体ID容器中与给定实体ID对应的键值对的元素值。
// 结果值:
//       -1:表示键值对不存在。
//        0:表示操作失败。
//        1:表示操作成功。
func (pool *myPool) compareAndSetForIdContainer(
	entityId uint32, oldValue bool, newValue bool) int8 {
	pool.mutex.Lock()
	defer pool.mutex.Unlock()
	v, ok := pool.idContainer[entityId]
	if !ok {
		return -1
	}
	if v != oldValue {
		return 0
	}
	pool.idContainer[entityId] = newValue
	return 1
}

func (pool *myPool) Total() uint32 {
	return pool.total
}

func (pool *myPool) Used() uint32 {
	return pool.total - uint32(len(pool.container))
}

redpajama_set_name: RedPajamaGithub


text:
Coolform Directive
==================

Displaying a form is very easy, just user the `coolform` directive

```
<coolform url="definition.json"></coolform>
```

The directive can take various parameters:

* **url** *(URL)* : The url where download the form definition
* **definition** *(jsobj)* : a javacript object to use as the form definition
* **success** *(callback)* : a callback to trigger on success
* **error** *(callback)* : a callback to be called on validation error
* **failure** *(callback)* : called there is a problem with the connection
* **send** *(jsobj)* : will assign a submit hook to the parameter


text:
<?php

namespace Product\Form;

use Zend\Form\Form;

class ProductDocumentForm extends Form {
	public function __construct($om = null) {
		parent::__construct ( 'productDocument' );

		$this->add ( array (
				'name' => 'documentName',
				'type' => 'Text',
				'attributes' => array (
						'class' => 'form-control',
						'id' => 'documentName'
				)
		) );

		$this->add ( array (
				'name' => 'documentLink',
				'type' => 'Text',
				'attributes' => array (
						'class' => 'form-control',
						'id' => 'documentLink'
				)
		) );

		$this->add ( array (
				'name' => 'document[documentId]',
				'type' => 'DoctrineModule\Form\Element\ObjectSelect',
				'options' => array (
						'object_manager' => $om,
						'target_class' => 'Database\Entity\DocumentTypes',
						'property' => 'documentName',
						'display_empty_item' => true,
						'empty_item_label' => ' '
				),
				'attributes' => array (
						'class' => 'select2me form-control',
						'tabindex' => '1',
						'id' => 'documentId'
				)
		)
		 );

		$this->add ( array (
				'name' => 'documentType[documentTypeId]',
				'type' => 'DoctrineModule\Form\Element\ObjectSelect',
				'options' => array (
						'object_manager' => $om,
						'target_class' => 'Database\Entity\DocumentTypes',
						'property' => 'documentTypeName',
						'display_empty_item' => true,
						'empty_item_label' => ' '
				),
				'attributes' => array (
						'class' => 'select2me form-control',
						'tabindex' => '1',
						'id' => 'documentTypeId',
						'required' => true
				)
		)
		 );
	}
}


text:
package gov.nih.nci.cagrid.portal.portlet.query.cql;

import gov.nih.nci.cagrid.portal.portlet.query.QueryFormulator;
import gov.nih.nci.cagrid.cqlquery.CQLQuery;
import gov.nih.nci.cagrid.cqlquery.QueryModifier;
import gov.nih.nci.cagrid.fqp.common.DCQLConstants;
import gov.nih.nci.cagrid.data.DataServiceConstants;

import javax.xml.namespace.QName;

/**
 * User: kherm
 *
 * @author kherm manav.kher@semanticbits.com
 */
public class CQLFormulator implements QueryFormulator<CQLQuery> {

    public static final QName qname = DataServiceConstants.CQL_QUERY_QNAME;

    public QName getQName() {
        return qname;
    }

    public CQLQuery toQuery(CQLQueryBean bean) {
        CQLQuery query = new CQLQuery();

        QueryModifier modifier = null;
        if (QueryModifierType.COUNT_ONLY.equals(bean.getModifierType())) {
            modifier = new QueryModifier(null, true, null);
        } else if (QueryModifierType.DISTINCT_ATTRIBUTE.equals(bean.getModifierType())) {
            modifier = new QueryModifier(null, false, bean.getSelectedAttributes().get(0));
        } else if (QueryModifierType.SELECTED_ATTRIBUTES.equals(bean.getModifierType())) {
            String[] atts = new String[bean.getSelectedAttributes().size()];
            for (int i = 0; i < atts.length; i++) {
                atts[i] = bean.getSelectedAttributes().get(i);
            }
            modifier = new QueryModifier(atts, false, null);
        } else {
            //No modifier
        }
        if (modifier != null) {
            query.setQueryModifier(modifier);
        }

        query.setTarget(bean.toTarget());

        return query;
    }
}


text:
<?php
class Users_Admin extends MY_Controller {

        public function __construct()
        {
                date_default_timezone_set('Asia/Manila');
                parent::__construct();
                $this->load->model('users_model');
                $this->load->library("pagination");
                $this->load->model('membership_model');
                $this->load->helper('url_helper');
                $this->load->library('form_validation');
                $this->is_logged_in();
        }

        public function index()
        {
                $data['users'] = $this->users_model->get_users();
                $data['title'] ='Administrators';

                /*$config = array();
                $config["base_url"] = base_url() . "/Users_Admin/index";
                $config["total_rows"] = $this->users_model->record_count();
               $config["per_page"] = 5;
                $config["uri_segment"] = 3;
                $choice = $config["total_rows"] / $config["per_page"];
                $config["num_links"] = round($choice);
                $config['prev_link'] = '';
                $config['next_link'] = '';
                $config['first_tag_open'] = $config['last_tag_open']= $config['num_tag_open'] = '
';
                $config['next_tag_open']= '
';
                $config['prev_tag_open'] = '
';
                $config['prev_tag_close'] = '
';
                $config['next_tag_close']= '
';
                $config['first_tag_close'] = $config['last_tag_close']= $config['num_tag_close'] = '
';

                $config['cur_tag_open'] = "
";
                $config['cur_tag_close'] = "
";

                $this->pagination->initialize($config);

                $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
                $data["results"] = $this->users_model->
                    fetch_users($config["per_page"], $page);
                $data["links"] = $this->pagination->create_links();*/

                $this->load->view('includes/header', $data);
                $this->load->view('admin/header_content', $data);
                $this->load->view('admin/all_users', $data);
                $this->load->view('includes/footer');

        }

        public function view($id = NULL)
        {

                $data['user_item'] = $this->users_model->get_users($id);
                $data['title'] = 'Profile';

                if (empty($data['user_item']))
                {
                        show_404();
                }

                //$data['date'] = date("M d",strtotime($data['news_item']['news_pub']));

                $this->load->view('includes/header', $data);
                $this->load->view('admin/header_content', $data);
                $this->load->view('admin/profile', $data);
                $this->load->view('includes/footer');
        }

        public function delete($id,$status) {
            $this->users_model->delete_user($id,$status);
            $data['users'] = $this->users_model->get_user();
            $data['title'] = 'User deleted';
            $this->load->view('includes/header', $data);
            $this->load->view('admin/header_content', $data);
            $this->load->view('admin/all_users', $data);
            $this->load->view('includes/footer');
        }

}


text:
namespace streetlearn {

// A helper class to aid rendering with Cairo.
class CairoRenderHelper {
 public:
  // Create a CairoRenderHelper for the image pointed to by `pixels`. The data
  // pointed to by `pixels` must have a longer life time than the created
  // CairoRenderHelper object.
  CairoRenderHelper(unsigned char* pixels, int width, int height,
                    cairo_format_t format = CAIRO_FORMAT_ARGB32) {
    int stride = cairo_format_stride_for_width(format, width);
    surface_ = cairo_image_surface_create_for_data(pixels, format, width,
                                                   height, stride);
    context_ = cairo_create(surface_);
  }

  ~CairoRenderHelper() {
    cairo_surface_flush(surface_);
    cairo_destroy(context_);
    cairo_surface_destroy(surface_);
  }

  CairoRenderHelper(const CairoRenderHelper&) = delete;
  CairoRenderHelper& operator=(const CairoRenderHelper&) = delete;

  int width() const { return cairo_image_surface_get_width(surface_); }
  int height() const { return cairo_image_surface_get_height(surface_); }

  // Returns the current cairo context.
  cairo_t* context() { return context_; }

  // Returns the surface of the current cairo context.
  cairo_surface_t* surface() { return surface_; }

 private:
  // Offscreen buffer used to render game state.
  cairo_surface_t* surface_;
  // Current rendering context.
  cairo_t* context_;
};

}  // namespace streetlearn

#endif  // THIRD_PARTY_STREETLEARN_ENGINE_CAIRO_UTIL_H_


text:
using namespace std;

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

BroadcastMessage::BroadcastMessage(char *msg, list<BroadcastMessage*> *message_queue)
{
	bImage = false;

	this->msg = new char[sizeof(char)*strlen(msg)];
	strcpy(this->msg, msg);
	this->message_queue = message_queue;
}

BroadcastMessage::~BroadcastMessage()
{
	delete[] this->msg;
}

void BroadcastMessage::SetImage(CR::Graphics::Sprite *image)
{
	hpt_image = image;
	bImage = true;
}

CR::Graphics::Sprite *BroadcastMessage::GetImage()
{
	return hpt_image;
}

char *BroadcastMessage::GetMessage()
{
	return msg;
}

void BroadcastMessage::Send()
{
	message_queue->push_back(this);
}

void BroadcastMessage::SetMessage(char *msg, ...)
{

}


text:
@class QX3DMaterial;

@interface CMYKTileStack : QX3DObject

- (instancetype)initWithMaterial:(QX3DMaterial *)material;

@property (nonatomic, assign) BOOL l1;
@property (nonatomic, assign) BOOL l2;
@property (nonatomic, assign) BOOL l3;

+ (UIColor *)colorForLayer:(NSUInteger)layer;

@end


text:
.. automodule:: insights.parsers.smt
   :members:
   :show-inheritance:


text:
import os

import shutil
import tempfile
import unittest
from oyProjectManager import conf, db
from oyProjectManager.models.asset import Asset
from oyProjectManager.models.auth import User
from oyProjectManager.models.errors import CircularDependencyError
from oyProjectManager.models.project import Project
from oyProjectManager.models.sequence import Sequence
from oyProjectManager.models.shot import Shot
from oyProjectManager.models.version import Version, VersionType

class VersionTester(unittest.TestCase):
    """tests the Version class
    """

    def setUp(self):
        """setup the test settings with environment variables
        """
        # -----------------------------------------------------------------
        # start of the setUp
        conf.database_url = "sqlite://"

        # create the environment variable and point it to a temp directory
        self.temp_config_folder = tempfile.mkdtemp()
        self.temp_projects_folder = tempfile.mkdtemp()

        os.environ["OYPROJECTMANAGER_PATH"] = self.temp_config_folder
        os.environ[conf.repository_env_key] = self.temp_projects_folder

        self.test_project = Project("TEST_PROJ1")
        self.test_project.create()

        self.test_sequence = Sequence(self.test_project, "TEST_SEQ1")
        self.test_sequence.save()
        self.test_sequence.create()

        # set it just for testing purposes
        self.test_shot = Shot(self.test_sequence, 1)

        self.test_versionType = VersionType(
            name="Test Animation",
            code="TANIM",
            path="{{project.code}}/Sequences/{{sequence.code}}/Shots/{{version.base_name}}/{{type.code}}",
            filename="{{version.base_name}}_{{version.take_name}}_{{type.code}}_v{{'%03d'|format(version.version_number)}}_{{version.created_by.initials}}{{version.extension}}",
            output_path="{{version.path}}/OUTPUT/{{version.take_name}}",
            environments=["MAYA", "HOUDINI"],
            type_for="Shot"
        )

        self.test_user = User(
            name="Test User",
            initials="tu",
            email="testuser@test.com"
        )

        self.kwargs = {
            "version_of": self.test_shot,
            "type": self.test_versionType,
            "base_name": "SH001",
            "take_name": "Main",
            "version_number": 1,
            "note": "this is the note for this version",
            "created_by": self.test_user,
            "extension": ".ma",
            "is_published": False,
            'status': conf.status_list[4]
        }

        self.test_version = Version(**self.kwargs)

        self._name_test_values = [
            ("base name", "Base_Name"),
            ("123123 base_name", "123123_Base_Name"),
            ("123432!+!'^+Base_NAme323^+'^%&+%&324", "123432Base_NAme323324"),
            ("    ---base 9s_name", "Base_9s_Name"),
            ("    ---base 9s-name", "Base_9s-Name"),
            (" multiple     spaces are    converted to under     scores",
             "Multiple_Spaces_Are_Converted_To_Under_Scores"),
            ("camelCase", "CamelCase"),
            ("CamelCase", "CamelCase"),
            ("_Project_Setup_", "Project_Setup"),
            ("_PROJECT_SETUP_", "PROJECT_SETUP"),
            ("FUL_3D", "FUL_3D"),
            ("BaseName", "BaseName"),
            ("baseName", "BaseName"),
            (" baseName", "BaseName"),
            (" base name", "Base_Name"),
            (" 12base name", "12base_Name"),
            (" 12 base name", "12_Base_Name"),
            (" 12 base name 13", "12_Base_Name_13"),
            (">£#>$#£½$ 12 base £#$£#$£½¾{½{ name 13", "12_Base_Name_13"),
            ("_base_name_", "Base_Name"),
            ("Dash-Characters-Are-Preserved", "Dash-Characters-Are-Preserved")
        ]

    def tearDown(self):
        """cleanup the test
        """
        # set the db.session to None
        db.session = None

        # delete the temp folder
        shutil.rmtree(self.temp_config_folder)
        shutil.rmtree(self.temp_projects_folder)

    def test_version_of_argument_is_skipped_raises_TypeError(self):
        """testing if a TypeError will be raised when the version_of
        argument is skipped
        """
        self.kwargs.pop("version_of")
        self.assertRaises(TypeError, Version, **self.kwargs)

    def test_version_of_argument_is_None(self):
        """testing if a TypeError will be raised when the version_of
        argument is None
        """
        self.kwargs["version_of"] = None
        self.assertRaises(TypeError, Version, **self.kwargs)

    def test_version_of_argument_is_not_a_VersionableBase_instance(self):
        """testing if a TypeError will be raised when the version_of argument
        is not a VersionableBase instance)
        """
        self.kwargs["version_of"] = "not a VersionableBase instance"
        self.assertRaises(TypeError, Version, **self.kwargs)

    def test_version_of_attribute_initialized_correctly(self):
        """testing if the version_of attribute initialized correctly
        """
        self.assertEqual(self.test_version.version_of, self.kwargs["version_of"])

    def test_version_of_attribute_is_read_only(self):
        """testing if the version_of attribute is read-only
        """
        self.assertRaises(AttributeError, setattr, self.test_version,
                          "version_of", 123)

    def test_type_argument_skipped(self):
        """testing if a TypeError will be raised when the type argument is
        skipped
        """
        self.kwargs.pop("type")
        self.assertRaises(TypeError, Version, **self.kwargs)

    def test_type_argument_is_None(self):
        """testing if a TypeError will be raised when the type argument is
        None
        """
        self.kwargs["type"] = None
        self.assertRaises(TypeError, Version, **self.kwargs)

    def test_type_argument_is_not_VersionType_instance(self):
        """testing if a TypeError will be raised when the type argument is not
        a VersionType instance
        """
        self.kwargs["type"] = "not a VersionType instance"
        self.assertRaises(TypeError, Version, **self.kwargs)

    def test_type_attribute_initialized_properly(self):
        """testing if the type attribute is initialized correctly
        """
        self.assertEqual(self.test_version.type, self.kwargs["type"])

    def test_type_attribute_is_read_only(self):
        """testing if the type attribute is read-only
        """
        new_type = VersionType(
            name="Test Model",
            code="TMODEL",
            path="ASSETS/{{base_name}}/{{type_name}}",
            filename="{{base_name}}_{{take_name}}_{{type_name}}_v{{version}}_{{created_by.initials}}",
            environments=["MAYA", "HOUDINI"],
            output_path="ASSETS/{{assetBaseName}}/{{assetTypeName}}/OUTPUT/{{assetSubName}}",
            type_for="Asset"
        )
        self.assertRaises(AttributeError, setattr, self.test_version, "type",
                          new_type)

    def test_type_argument_is_not_proper_for_the_version_of_type(self):
        """testing if a TypeError will be raised when the given VersionType
        instance's type_for attribute doesn't match the class which is given by
        version_of argument
        """

        # create an Asset
        new_asset = Asset(self.test_project, "TEST_ASSET1")
        new_asset.save()

        # create a new VersionType which is suitable for Shots
        new_vtype = VersionType(
            "Test Type", code="TType",
            path="{{project.code}}/Sequences/{{sequence.code}}/SHOTS/{{version.base_name}}/{{type.code}}",
            filename="{{version.base_name}}_{{version.take_name}}_\
            {{type.code}}_v{{'%03d'|format(version.version_number)}}_\
            {{version.created_by.initials}}",
            output_path="SHOTS/{{version.base_name}}/{{type.code}}/OUTPUT/\
            {{version.take_name}}",
            environments=["MAYA", "HOUDINI"],
            type_for="Shot"
        )

        # try to create a new Version with it
        # and expect a TypeError to be raised
        self.assertRaises(
            TypeError,
            Version, new_asset, new_asset.name, new_vtype, self.test_user
        )

    def test_base_name_argument_is_skipped(self):
        """testing if a TypeError will be raised when the base_name argument
        is skipped
        """
        self.kwargs.pop("base_name")
        self.assertRaises(TypeError, Version, **self.kwargs)

    def test_base_name_argument_is_None(self):
        """testing if a TypeError will be raised when the base_name argument
        is None
        """
        self.kwargs["base_name"] = None
        self.assertRaises(TypeError, Version, **self.kwargs)

    def test_base_name_attribute_is_None(self):
        """testing if a TypeError will be raised when the base_name
        attribute is set to None
        """
        self.assertRaises(TypeError, setattr, self.test_version,
                          "base_name", None)

    def test_base_name_argument_is_not_a_string(self):
        """testing if a TypeError will be raised when the base_name argument is
        not a string or unicode instance
        """
        self.kwargs["base_name"] = 12
        self.assertRaises(TypeError, Version, **self.kwargs)

    def test_base_name_attribute_is_not_a_string(self):
        """testing if a TypeError will be raised when the base_name argument is
        not a string or unicode instance
        """
        self.assertRaises(TypeError, setattr, self.test_version, "base_name",
                          12)

    def test_base_name_attribute_is_initialized_correctly(self):
        """testing if the base_name attribute is initialized correctly
        """
        self.assertEqual(self.test_version.base_name, self.kwargs["base_name"])

    def test_base_name_attribute_is_working_properly(self):
        """testing if the base_name attribute is working properly
        """
        test_value = "NewBaseName"
        self.test_version.base_name = test_value
        self.assertEqual(self.test_version.base_name, test_value)

    def test_base_name_attribute_is_formatted_correctly_on_new_Version(self):
        """testing if the base_name attribute is formatted correctly when it is
        initialized
        """

        for test_value in self._name_test_values:
            self.kwargs["base_name"] = test_value[0]
            new_version = Version(**self.kwargs)
            self.assertEqual(new_version.base_name, test_value[1])

    def test_base_name_attribute_is_formatted_correctly(self):
        """testing if the base_name attribute is formatted correctly when it is
        set to a value
        """
        for i, test_value in enumerate(self._name_test_values):
            self.test_version.base_name = test_value[0]
            self.assertEqual(self.test_version.base_name, test_value[1])

    def test_base_name_argument_is_empty_string_after_formatting(self):
        """testing if a ValueError will be raised when the base_name argument
        is an empty string after it is formatted
        """
        self.kwargs["base_name"] = "'^+'^#@#$"
        self.assertRaises(ValueError, Version, **self.kwargs)

    def test_base_name_attribute_is_empty_string_after_formatting(self):
        """testing if a ValueError will be raised when the base_name attribute
        is an empty string after it is formatted
        """
        self.assertRaises(ValueError, setattr, self.test_version, "base_name",
                          "'^+'^#@$#")

    def test_take_name_argument_is_skipped(self):
        """testing if the default value Main is used when the take_name
        argument is skipped
        """
        self.kwargs.pop("take_name")
        new_version = Version(**self.kwargs)
        self.assertEqual(new_version.take_name, conf.default_take_name)

    def test_take_name_argument_is_None(self):
        """testing if the default value Main is used when the take_name
        argument is None
        """
        self.kwargs["take_name"] = None
        new_version = Version(**self.kwargs)
        self.assertEqual(new_version.take_name, conf.default_take_name)

    def test_take_name_attribute_is_None(self):
        """testing if the default take name value will be used when the
        take_name attribute is set to None
        """
        self.test_version.take_name = None
        self.assertEqual(self.test_version.take_name, conf.default_take_name)

    def test_take_name_argument_is_not_a_string(self):
        """testing if a TypeError will be raised when the take_name argument is
        not a string or unicode instance
        """
        self.kwargs["take_name"] = 12
        self.assertRaises(TypeError, Version, **self.kwargs)

    def test_take_name_attribute_is_not_a_string(self):
        """testing if a TypeError will be raised when the take_name argument is
        not a string or unicode instance
        """
        self.assertRaises(TypeError, setattr, self.test_version, "take_name",
                          12)

    def test_take_name_attribute_is_initialized_correctly(self):
        """testing if the take_name attribute is initialized correctly
        """
        self.assertEqual(self.test_version.take_name, self.kwargs["take_name"])

    def test_take_name_attribute_is_working_properly(self):
        """testing if the take_name attribute is working properly
        """
        test_value = "NewBaseName"
        self.test_version.take_name = test_value
        self.assertEqual(self.test_version.take_name, test_value)

    def test_take_name_attribute_is_formatted_correctly_on_new_Version(self):
        """testing if the take_name attribute is formatted correctly when it is
        initialized
        """

        for test_value in self._name_test_values:
            self.kwargs["take_name"] = test_value[0]
            new_version = Version(**self.kwargs)
            self.assertEqual(new_version.take_name, test_value[1])

    def test_take_name_attribute_is_formatted_correctly(self):
        """testing if the take_name attribute is formatted correctly when it is
        set to a value
        """
        for test_value in self._name_test_values:
            self.test_version.take_name = test_value[0]
            self.assertEqual(self.test_version.take_name, test_value[1])

    def test_take_name_argument_is_empty_string_after_formatting(self):
        """testing if a ValueError will be raised when the take_name argument
        is an empty string after it is formatted
        """
        self.kwargs["take_name"] = "'^+'^"
        self.assertRaises(ValueError, Version, **self.kwargs)

    def test_take_name_attribute_is_empty_string_after_formatting(self):
        """testing if a ValueError will be raised when the take_name attribute
        is an empty string after it is formatted
        """
        self.assertRaises(ValueError, setattr, self.test_version, "take_name",
                          "'^+'^")

    def test_version_number_argument_is_skipped_for_new_Version(self):
        """testing if the default value is used for the version attribute if
        the version argument is skipped for a new Version
        """
        self.kwargs.pop("version_number")
        new_version = Version(**self.kwargs)
        self.assertEqual(new_version.version_number, 1)

    def test_version_number_argument_is_skipped_for_non_new_Version(self):
        """testing if the smallest possible integer is used for the version
        attribute if the version argument is skipped for a non new Version
        """
        self.kwargs.pop("version_number")
        new_version1 = Version(**self.kwargs)
        new_version1.save()

        new_version2 = Version(**self.kwargs)
        new_version2.save()

        new_version3 = Version(**self.kwargs)
        new_version3.save()

        new_version4 = Version(**self.kwargs)
        new_version4.save()

        self.assertEqual(new_version1.version_number, 1)
        self.assertEqual(new_version2.version_number, 2)
        self.assertEqual(new_version3.version_number, 3)
        self.assertEqual(new_version4.version_number, 4)

    def test_version_is_given_smaller_than_the_max_in_db(self):
        """testing if the version is updated with the smallest available number
        if it is smaller than the maximum version number in the database
        """

        # lets create two Versions with same version and expect to see the last
        # one has a bigger version_number
        self.kwargs["base_name"] = "A"
        self.kwargs["version_number"] = 100
        new_version1 = Version(**self.kwargs)
        new_version1.save()

        self.assertEqual(new_version1.version_number, 100)

        new_version2 = Version(**self.kwargs)
        self.assertEqual(new_version2.version_number, 101)

    def test_version_number_is_zero(self):
        """testing if the version number will be updated with the smallest
        possible version_number value from the db if it is zero
        """
        self.kwargs["base_name"] = "Azero"
        self.kwargs["version_number"] = 0
        versA1 = Version(**self.kwargs)
        versA1.save()
        self.assertEqual(versA1.version_number, 1)

        versA2 = Version(**self.kwargs)
        versA2.save()
        self.assertEqual(versA2.version_number, 2)

    def test_version_number_is_negative(self):
        """testing if the version number will be updated with the smallest
        possible positive version_number value from the db if it is negative
        """
        self.kwargs["base_name"] = "Aneg"
        self.kwargs["version_number"] = -100
        versA1 = Version(**self.kwargs)
        versA1.save()
        self.assertEqual(versA1.version_number, 1)

        versA2 = Version(**self.kwargs)
        versA2.save()
        self.assertEqual(versA2.version_number, 2)

    def test_version_number_for_two_assets(self):
        """testing if the version number is calculated correctly for two assets
        with different versions_types but with same take_names
        """

        shot1 = Shot(self.test_sequence, "1A")
        shot1.save()

        # now create two versions with the same version_type
        new_vers1 = Version(
            shot1, shot1.code, self.test_versionType, self.test_user,
            take_name="Take1"
        )
        new_vers1.save()

        new_vers2 = Version(
            shot1, shot1.code, self.test_versionType, self.test_user,
            take_name="Take2"
        )
        new_vers2.save()

        self.assertEqual(new_vers1.version_number, 1)
        self.assertEqual(new_vers1.version_number, 1)

    # TODO: update this test
#    def test_max_version_returns_the_maximum_version_number_from_the_database_for_changing_types(self):
#        """testing if the max_version is returning the maximum version number
#        for the current Version from the database for changing type values
#        """
#        self.fail("test is not implemented yet")

    # TODO: update this test
#    def test_max_version_returns_the_maximum_version_number_from_the_database_for_changing_version_ofs(self):
#        """testing if the max_version is returning the maximum version number
#        for the current Version from the database for changing version_of
#        values
#        """
#        self.fail("test is not implemented yet")

    def test_max_version_returns_the_maximum_version_number_from_the_database_for_changing_take_names(self):
        """testing if the max_version is returning the maximum version number
        for the current Version from the database for changing take_name values
        """

        self.kwargs.pop("version_number")

        self.kwargs["take_name"] = "A"
        for i in range(50):
            new_A = Version(**self.kwargs)
            new_A.save()

        self.kwargs["take_name"] = "B"
        for i in range(100):
            new_B = Version(**self.kwargs)
            new_B.save()

        # now try to create a new A and expect the version number to be 51
        self.kwargs["take_name"] = "A"
        A_new = Version(**self.kwargs)
        A_new.save()
        self.assertEqual(A_new.version_number, 51)

        # and B should be 101
        self.kwargs["take_name"] = "B"
        B_new = Version(**self.kwargs)
        B_new.save()
        self.assertEqual(B_new.version_number, 101)

    def test_max_version_will_not_be_effected_by_base_name(self):
        """testing if the max_version is not effected by changing base_names
        """

        self.kwargs.pop("version_number")

        self.kwargs["base_name"] = "A"
        for i in range(50):
            new_A = Version(**self.kwargs)
            new_A.save()

        self.kwargs["base_name"] = "B"
        for i in range(100):
            new_B = Version(**self.kwargs)
            new_B.save()

        # now try to create a new A and expect the version number to be 151
        self.kwargs["base_name"] = "A"
        A_new = Version(**self.kwargs)
        A_new.save()
        self.assertEqual(A_new.version_number, 151)

        # and B should be 152
        self.kwargs["base_name"] = "B"
        B_new = Version(**self.kwargs)
        B_new.save()
        self.assertEqual(B_new.version_number, 152)

    def test_version_number_continues_correctly_even_if_the_Versionable_name_has_changed(self):
        """testing if the version_number continues correctly even if the
        Versionable's name has changed
        """

        new_asset = Asset(self.test_project, "Asset 1")
        new_asset.save()

        self.kwargs["version_of"] = new_asset

        new_type = VersionType(
            name="TModel2",
            code="TModel2",
            path="{{project.code}}/Assets/{{version.base_name}}/{{type.code}}",
            filename="{{version.base_name}}_{{version.take_name}}_{{type.code}}_v{{'%03d'|format(version.version_number)}}_{{version.created_by.initials}}{{version.extension}}",
            output_path="{{version._path}}/Output/{{version.take_name}}",
            extra_folders="",
            environments=["Maya", "Houdini"],
            type_for="Asset"
        )

        self.kwargs["type"] = new_type

        # create a couple of versions
        version1 = Version(**self.kwargs)
        version1.save()

        self.assertEqual(version1.version_number, 1)

        version2 = Version(**self.kwargs)
        version2.save()

        self.assertEqual(version2.version_number, 2)

        # rename the asset
        new_asset.name = "Asset 2"
        new_asset.code = "Asset 2"
        new_asset.save()
        self.kwargs["base_name"] = new_asset.code

        version3 = Version(**self.kwargs)
        version3.save()

        self.assertEqual(version3.version_number, 3)

    def test_note_argument_skipped(self):
        """testing if the note attribute will be an empty string if the note
        attribute is skipped
        """
        self.kwargs.pop("note")
        new_version = Version(**self.kwargs)
        self.assertEqual(new_version.note, "")

    def test_note_argument_is_set_to_None(self):
        """testing if the note attribute will be an empty string if the note
        argument is set to None
        """
        self.kwargs["note"] = None
        new_version = Version(**self.kwargs)
        self.assertEqual(new_version.note, "")

    def test_note_attribute_is_set_to_None(self):
        """testing if the note attribute will be an empty string if it is set
        to None
        """
        self.test_version.note = None
        self.assertEqual(self.test_version.note, "")

    def test_note_argument_is_not_a_string(self):
        """testing if a TypeError will be raised when the note argument is not
        a string or unicode instance
        """
        self.kwargs["note"] = 123123
        self.assertRaises(TypeError, Version, **self.kwargs)

    def test_note_attribute_is_set_to_a_non_string(self):
        """testing if a TypeError will be raised when the note attribute is set
        to a value which is neither string or unicode
        """
        self.assertRaises(TypeError, setattr, self.test_version, "note", 123)

    def test_note_argument_is_working_properly(self):
        """testing if the note attribute is initialized correctly with the
        given note argument value
        """
        self.assertEqual(self.test_version.note, self.kwargs["note"])

    def test_note_attribute_is_working_properly(self):
        """testing if the note attribute is working properly
        """
        test_value = "test value goes here"
        self.test_version.note = test_value
        self.assertEqual(self.test_version.note, test_value)

    def test_created_by_argument_is_skipped(self):
        """testing if a TypeError will be raised when the created_by
        argument is skipped
        """
        self.kwargs.pop("created_by")
        self.assertRaises(TypeError, Version, **self.kwargs)

    def test_created_by_argument_is_None(self):
        """testing if a TypeError will be raised when the created_by
        argument is set to None
        """
        self.kwargs["created_by"] = None
        self.assertRaises(TypeError, Version, **self.kwargs)

    def test_created_by_attribute_is_set_to_None(self):
        """testing if a TypeError will be raised when the created_by
        attribute is set to None
        """
        self.assertRaises(TypeError, setattr, self.test_version,
                          "created_by", None)

    def test_created_by_argument_is_not_a_User_instance(self):
        """testing if a TypeError will be raised when the created_by argument
        is not a oyProjectManager.models.auth.User instance
        """
        self.kwargs["created_by"] = 1231
        self.assertRaises(TypeError, Version, **self.kwargs)

    def test_created_by_attribute_is_not_a_User_instance(self):
        """testing if a TypeError will be raised when the created_by attribute
        is set to a value other than a oyProjectManager.models.auth.User
        instance
        """
        self.assertRaises(TypeError, setattr, self.test_version, "created_by",
                          12314)

    def test_created_by_argument_is_working_properly(self):
        """testing if the created_by attribute is initialized correctly with
        the correct value given to created_by argument
        """
        self.assertEqual(self.test_version.created_by,
                         self.kwargs["created_by"])

    def test_created_by_attribute_is_working_properly(self):
        """testing if the created_by attribute is working properly
        """
        new_user = User(name="Test User 2", initials="tu2",
                        email="test_user2@test.com")
        self.test_version.created_by = new_user
        self.assertEqual(self.test_version.created_by, new_user)

    def test_filename_attribute_is_rendered_properly(self):
        """testing if the filename attribute is rendered properly with the
        given VersionType's filename template
        """
        self.assertEqual(
            self.test_version.filename,
            self.kwargs["base_name"] + "_" + \
            self.kwargs["take_name"] + "_" + \
            self.kwargs["type"].code + "_" + \
            "v" + str(self.kwargs["version_number"]).zfill(3) + "_" + \
            self.kwargs["created_by"].initials + self.kwargs["extension"]
        )

    def test_filename_attribute_is_read_only(self):
        """testing if the filename attribute is read-only
        """
        self.assertRaises(AttributeError, setattr, self.test_version,
                          "filename", "test_file_name")

    def test_filename_attribute_doesnt_change_with_the_VersionType(self):
        """testing if the filename stays the same when the VersionType
        attributes change
        """
        prev_filename = self.test_version.filename
        # now change the associated VersionType.filename
        self.kwargs["type"].filename = "A"

        self.assertEqual(prev_filename, self.test_version.filename)

#    def test_abs_path_attribute_is_rendered_properly(self):
#        """testing if the abs_path attribute is rendered properly with the
#        given VersionType's path template
#        """
#        # path = "SHOTS/{{version.base_name}}/{{version.type.code}}"
#        self.assertEqual(
#            self.test_version.abs_path,
#            self.test_version.project.full_path +
#            "/Sequences/TEST_SEQ1/Shots/" + self.kwargs["base_name"] + "/" +
#            self.kwargs["type"].code
#        )
#
#    def test_abs_path_returns_a_proper_absolute_path_when_path_is_absolute(self):
#        """testing if the abs_path returns a proper absolute path even though
#        the path it self is an absolute path
#        """
#
#        new_versionType = VersionType(
#            name="Test Animation New",
#            code="TANIMNEW",
#            path="{{project.full_path}}/Sequences/{{sequence.code}}/Shots/{{version.base_name}}/{{type.code}}",
#            filename="{{version.base_name}}_{{version.take_name}}_{{type.code}}_v{{'%03d'|format(version.version_number)}}_{{version.created_by.initials}}{{version.extension}}",
#            output_path="{{version.path}}/OUTPUT/{{version.take_name}}",
#            environments=["MAYA", "HOUDINI"],
#            type_for="Shot"
#        )
#
#        self.kwargs["type"] = new_versionType
#        new_version = Version(**self.kwargs)
#
#        expected_path = self.test_project.full_path + "/Sequences/" + \
#                        self.test_sequence.code + "/Shots/" + \
#                        new_version.base_name + "/" + new_version.type.code
#
#        self.assertTrue(new_version.abs_path == expected_path)

    def test_path_attribute_is_rendered_properly(self):
        """testing if the path attribute is rendered properly with the given
        VersionType's path template
        """
        # path = "SHOTS/{{version.base_name}}/{{version.type.code}}"
        self.assertEqual(
            self.test_version.path,
            os.path.join(
                self.test_project.full_path,
                "Sequences/TEST_SEQ1/Shots/" + self.kwargs["base_name"] + "/" +
                self.kwargs["type"].code
            )
        )

    def test_path_attribute_is_read_only(self):
        """testing if the path attribute is read-only
        """
        self.assertRaises(AttributeError, setattr, self.test_version, "path",
                          "test_file_name")

    def test_path_attribute_doesnt_change_with_the_VersionType(self):
        """testing if the path stays the same when the VersionType attributes
        change
        """
        prev_path = self.test_version.path
        # now change the associated VersionType.path
        self.kwargs["type"].path = "A"

        self.assertEqual(prev_path, self.test_version.path)

    def test_path_attribute_is_absolute(self):
        """testing if the rendered path attribute is absolute
        """
        self.assertTrue(os.path.isabs(self.test_version.path))

    def test_output_path_attribute_is_rendered_properly(self):
        """testing if the output_path attribute is rendered properly with the
        given VersionType's output_path template
        """
        # output_path = "SHOTS/{{version.base_name}}/{{version.type.code}}/
        #                    OUTPUT/{{version.take_name}}"
        self.assertEqual(
            self.test_version.output_path,
            self.test_version.path + "/OUTPUT/" + self.kwargs["take_name"]
        )

    def test_output_path_attribute_is_read_only(self):
        """testing if the output_path attribute is read-only
        """
        self.assertRaises(AttributeError, setattr, self.test_version,
                          "output_path", "test_file_name")

    def test_output_path_attribute_doesnt_change_with_the_VersionType(self):
        """testing if the output_path stays the same when the VersionType
        attributes change
        """
        prev_output_path = self.test_version.output_path
        # now change the associated VersionType.output_path
        self.kwargs["type"].output_path = "A"

        self.assertEqual(prev_output_path, self.test_version.output_path)

    def test_output_path_attribute_is_absolute(self):
        """testing if the output_path attribute is absolute
        """
        self.assertTrue(os.path.isabs(self.test_version.output_path))

    def test_full_path_attribute_is_rendered_properly(self):
        """testing if the full_path attribute is rendered properly
        """

        self.assertEqual(
            self.test_version.full_path,
            os.path.join(
                self.test_project.full_path,
                "Sequences/TEST_SEQ1/Shots/SH001/TANIM/SH001_Main_TANIM_v001_tu.ma"
            ).replace("\\", "/")
        )

    def test_full_path_attribute_is_read_only(self):
        """testing if the full_path attribute is read-only
        """
        self.assertRaises(AttributeError, setattr, self.test_version,
                          "full_path", "test/full/name")

    def test_full_path_attribute_doesnt_change_with_the_VersionType(self):
        """testing if the full_path stays the same when the VersionType
        attributes change
        """
        prev_full_path = self.test_version.full_path
        # now change the associated VersionType.path
        self.kwargs["type"].filename = "A"
        self.kwargs["type"].path = "A"

        self.assertEqual(prev_full_path, self.test_version.full_path)

    def test_full_path_attribute_is_absolute(self):
        """testing if the full_path attribute value is absolute
        """
        self.assertTrue(os.path.isabs(self.test_version.full_path))

    def test_references_attribute_accepts_Version_instances_only(self):
        """testing if a TypeError will be raised when the value passed to the
        references attribute is not a Version instance
        """
        self.assertRaises(TypeError, setattr, self.test_version, "references",
                          12314)

    def test_references_attribute_accepts_Version_instances_other_than_itself(self):
        """testing if a ValueError will be raised when the value passed to the
        references attribute is self
        """
        self.assertRaises(ValueError,
                          self.test_version.references.append,
                          self.test_version )

    def test_references_attribute_doesnt_allow_circular_references(self):
        """testing if a CyclicDependencyError will be raised when the reference
        passed with the references value also references this Version instance
        """

        self.kwargs["base_name"] = "Test Version 1"
        vers1 = Version(**self.kwargs)
        vers1.save()

        self.kwargs["base_name"] = "Test Version 2"
        vers2 = Version(**self.kwargs)
        vers2.references.append(vers1)
        vers2.save()

        self.assertRaises(CircularDependencyError,
            vers1.references.append, vers2
        )

    def test_references_attribute_doesnt_allow_deep_circular_references(self):
        """testing if a CyclicDependencyError will be raised when the reference
        passed with the references value has another reference which references
        this Version instance
        """
        self.kwargs["base_name"] = "Test Version 1"
        vers1 = Version(**self.kwargs)
        vers1.save()

        self.kwargs["base_name"] = "Test Version 2"
        vers2 = Version(**self.kwargs)
        vers2.save()

        self.kwargs["base_name"] = "Test Version 3"
        vers3 = Version(**self.kwargs)
        vers3.references.append(vers1)
        vers3.save()

        vers2.references.append(vers3)
        vers2.save()

        self.assertRaises(CircularDependencyError,
            vers1.references.append, vers2
        )

    def test__eq__operator(self):
        """testing the equality operator
        """

        vers1 = Version(**self.kwargs)
        vers2 = Version(**self.kwargs)

        # different version_of
        self.kwargs["version_of"] = Shot(self.test_sequence, 2)
        vers3 = Version(**self.kwargs)

        # different base_name
        self.kwargs["base_name"] = "AnotherBaseName"
        vers4 = Version(**self.kwargs)

        # different version_type

        new_versionType = VersionType(
            name="Shot Type 1",
            code="ShotType1",
            path="{{project.code}}/Shots/{{version.base_name}}/{{type.code}}",
            filename="{{version.base_name}}_{{version.take_name}}_{{type.code}}_v{{'%03d'|format(version.version_number)}}_{{version.created_by.initials}}{{version.extension}}",
            output_path="{{version._path}}/Output/{{version.take_name}}",
            extra_folders="",
            environments=["Maya", "Houdini"],
            type_for="Shot"
        )

        self.kwargs["type"] = new_versionType
        vers5 = Version(**self.kwargs)

        self.assertTrue(vers1==vers2)
        self.assertFalse(vers1==vers3)
        self.assertFalse(vers3==vers4)
        self.assertFalse(vers4==vers5)

    def test__ne__operator(self):
        """testing the not equal operator
        """

        vers1 = Version(**self.kwargs)
        vers2 = Version(**self.kwargs)

        # different version_of
        self.kwargs["version_of"] = Shot(self.test_sequence, 2)
        vers3 = Version(**self.kwargs)

        # different base_name
        self.kwargs["base_name"] = "AnotherBaseName"
        vers4 = Version(**self.kwargs)

        # different version_type

        new_versionType = VersionType(
            name="Test Model 3",
            code="TMODEL3",
            path="SHOTS/{{version.base_name}}/{{type.code}}",
            filename="{{version.base_name}}_{{version.take_name}}_\
{{type.code}}_v{{'%03d'|format(version.version_number)}}_\
{{version.created_by.initials}}",
            output_path="SHOTS/{{version.base_name}}/{{type.code}}/OUTPUT/\
{{version.take_name}}",
            environments=["MAYA", "HOUDINI"],
            type_for="Shot"
        )

        self.kwargs["type"] = new_versionType
        vers5 = Version(**self.kwargs)

        self.assertFalse(vers1!=vers2)
        self.assertTrue(vers1!=vers3)
        self.assertTrue(vers3!=vers4)
        self.assertTrue(vers4!=vers5)

    def test_extension_argument_is_skipped(self):
        """testing if the extension will be an empty string if the extension
        argument is skipped
        """
        self.kwargs.pop("extension")
        new_version = Version(**self.kwargs)
        self.assertEqual(new_version.extension, "")

    def test_extension_argument_is_not_a_string_instance(self):
        """testing if a TypeError will be raised when the extension is not an
        instance of string of unicode
        """
        self.kwargs["extension"] = 123123
        self.assertRaises(TypeError, Version, **self.kwargs)

    def test_extension_attribute_is_not_a_string_instance(self):
        """testing if a TypeError will be raised when the extension attribute
        is not a string or unicode instance
        """
        self.assertRaises(TypeError, setattr, self.test_version, "extension",
                          1231)

    def test_extension_argument_without_dot_sign(self):
        """testing if the extension attribute will include a dot even when the
        given extension arguments first character is not a dot
        """
        self.kwargs["extension"] = "ma"
        new_version = Version(**self.kwargs)
        self.assertEqual(new_version.extension, ".ma")

    def test_extension_attribute_without_a_dot_sign(self):
        """testing if the extension attribute will include a dot even when the
        given values first character is not a dot sign
        """
        self.test_version.extension = "psd"
        self.assertEqual(self.test_version.extension, ".psd")

    def test_extension_argument_is_working_properly(self):
        """testing if the extension attribute will be properly set to the given
        value with the extension argument
        """
        test_value = ".mov"
        self.kwargs["extension"] = test_value
        new_version = Version(**self.kwargs)
        self.assertEqual(new_version.extension, test_value)

    def test_extension_attribute_is_working_properly(self):
        """testing if the extension attribute is working properly
        """
        self.test_version.extension = ".ma"
        self.assertEqual(self.test_version.extension, ".ma")

    def test_extension_attribute_updates_the_filename_attribute(self):
        """testing if changing the extension attribute also updates the
        filename attribute
        """
        self.kwargs["extension"] = "ma"
        new_vers = Version(**self.kwargs)

        self.assertEqual(new_vers.filename, "SH001_Main_TANIM_v001_tu.ma")

        # change the extension
        new_vers.extension = "mb"

        # check if the filename is also updated
        self.assertEqual(new_vers.filename, "SH001_Main_TANIM_v001_tu.mb")

    def test_project_attribute_is_read_only(self):
        """testing if the project attribute is read only
        """
        self.assertRaises(AttributeError, setattr, self.test_version,
                          "project", self.test_project)

    def test_project_attribute_is_working_properly(self):
        """testing if the project attribute is returning the correct project
        instance
        """
        self.assertEqual(self.test_version.project,
                         self.test_version.version_of.project)

    def test_is_latest_version_method_is_working_properly(self):
        """testing if the is_latest_version method returns True if the current
        Version is the last among the others
        """

        version1 = Version(**self.kwargs)
        version1.save()
        version2 = Version(**self.kwargs)
        version2.save()
        version3 = Version(**self.kwargs)
        version3.save()

        self.assertFalse(version1.is_latest_version())
        self.assertFalse(version2.is_latest_version())
        self.assertTrue(version3.is_latest_version())

    def test_is_latest_version_method_for_different_takes(self):
        """testing if the is_latest_version method returns True if the current
        Version is the last among the others even there are Versions with
        different takes
        """

        version1 = Version(**self.kwargs)
        version1.save()
        version2 = Version(**self.kwargs)
        version2.save()

        self.kwargs["take_name"] = "NewTake"
        version3 = Version(**self.kwargs)
        version3.save()
        version4 = Version(**self.kwargs)
        version4.save()

        self.assertFalse(version1.is_latest_version())
        self.assertTrue(version2.is_latest_version())
        self.assertFalse(version3.is_latest_version())
        self.assertTrue(version4.is_latest_version())

    def test_is_latest_version_method_for_different_types(self):
        """testing if the is_latest_version method returns True if the current
        Version is the last among the others even there are Versions with
        different types
        """

        vType1 = VersionType(
            name="VersionType1",
            code="VT1",
            path="{{project.code}}/Sequences/{{sequence.code}}/Shots/{{version.base_name}}/{{type.code}}",
            filename="{{version.base_name}}_{{version.take_name}}_{{type.code}}_v{{'%03d'|format(version.version_number)}}_{{version.created_by.initials}}{{version.extension}}",
            output_path="{{version.path}}/OUTPUT/{{version.take_name}}",
            environments=["MAYA", "HOUDINI"],
            type_for="Shot"
        )

        vType2 = VersionType(
            name="VersionType2",
            code="VT2",
            path="{{project.code}}/Sequences/{{sequence.code}}/Shots/{{version.base_name}}/{{type.code}}",
            filename="{{version.base_name}}_{{version.take_name}}_{{type.code}}_v{{'%03d'|format(version.version_number)}}_{{version.created_by.initials}}{{version.extension}}",
            output_path="{{version.path}}/OUTPUT/{{version.take_name}}",
            environments=["MAYA", "HOUDINI"],
            type_for="Shot"
        )

        vType3 = VersionType(
            name="VersionType3",
            code="VT3",
            path="{{project.code}}/Sequences/{{sequence.code}}/Shots/{{version.base_name}}/{{type.code}}",
            filename="{{version.base_name}}_{{version.take_name}}_{{type.code}}_v{{'%03d'|format(version.version_number)}}_{{version.created_by.initials}}{{version.extension}}",
            output_path="{{version.path}}/OUTPUT/{{version.take_name}}",
            environments=["MAYA", "HOUDINI"],
            type_for="Shot"
        )

        vType1.save()
        vType2.save()
        vType3.save()

        self.kwargs["type"] = vType1
        vers1 = Version(**self.kwargs)
        vers1.save()
        vers2 = Version(**self.kwargs)
        vers2.save()
        vers3 = Version(**self.kwargs)
        vers3.save()

        self.kwargs["type"] = vType2
        vers4 = Version(**self.kwargs)
        vers4.save()
        vers5 = Version(**self.kwargs)
        vers5.save()
        vers6 = Version(**self.kwargs)
        vers6.save()

        self.kwargs["type"] = vType3
        vers7 = Version(**self.kwargs)
        vers7.save()
        vers8 = Version(**self.kwargs)
        vers8.save()
        vers9 = Version(**self.kwargs)
        vers9.save()

        self.assertFalse(vers1.is_latest_version())
        self.assertFalse(vers2.is_latest_version())
        self.assertTrue(vers3.is_latest_version())

        self.assertFalse(vers4.is_latest_version())
        self.assertFalse(vers5.is_latest_version())
        self.assertTrue(vers6.is_latest_version())

        self.assertFalse(vers7.is_latest_version())
        self.assertFalse(vers8.is_latest_version())
        self.assertTrue(vers9.is_latest_version())

    def test_latest_version_method_returns_the_latest_versions_instance(self):
        """testing if the latest_version instance returns the latest Version
        instance in this series
        """

        version1 = Version(**self.kwargs)
        version1.save()
        version2 = Version(**self.kwargs)
        version2.save()
        version3 = Version(**self.kwargs)
        version3.save()

        self.assertTrue(version1.latest_version()==version3)
        self.assertTrue(version2.latest_version()==version3)
        self.assertTrue(version3.latest_version()==version3)

    def test_dependency_update_list_method_returns_a_list_of_Versions_that_needs_update(self):
        """testing if the dependency_update_list returns a list of Version
        instances which are referenced by this Version instance but have a
        newer published versions available
        """

        # create a couple of Versions

        # Group 1
        self.kwargs["take_name"] = "Take1"
        versionRef_A1 = Version(**self.kwargs)
        versionRef_A1.is_published = True
        versionRef_A1.save()

        versionRef_A2 = Version(**self.kwargs)
        versionRef_A2.is_published = False
        versionRef_A2.save()

        versionRef_A3 = Version(**self.kwargs)
        versionRef_A3.is_published = True
        versionRef_A3.save()

        versionRef_A4 = Version(**self.kwargs)
        versionRef_A4.is_published = False
        versionRef_A4.save()

        # Group 2
        # just change the take
        self.kwargs["take_name"] = "Take2"
        versionRef_B1 = Version(**self.kwargs)
        versionRef_B1.is_published = True
        versionRef_B1.save()

        versionRef_B2 = Version(**self.kwargs)
        versionRef_B2.is_published = False
        versionRef_B2.save()

        versionRef_B3 = Version(**self.kwargs)
        versionRef_B3.is_published = True
        versionRef_B3.save()

        versionRef_B4 = Version(**self.kwargs)
        versionRef_B4.is_published = False
        versionRef_B4.save()

        # Group 3
        # just change the take
        self.kwargs["take_name"] = "Take3"
        versionRef_C1 = Version(**self.kwargs)
        versionRef_C1.is_published = True
        versionRef_C1.save()

        versionRef_C2 = Version(**self.kwargs)
        versionRef_C2.is_published = False
        versionRef_C2.save()

        versionRef_C3 = Version(**self.kwargs)
        versionRef_C3.is_published = True
        versionRef_C3.save()

        versionRef_C4 = Version(**self.kwargs)
        versionRef_C4.is_published = False
        versionRef_C4.save()

        # Main Version
        self.kwargs["take_name"] = "Take4"
        versionMain = Version(**self.kwargs)
        versionMain.save()

        # and reference them to each other
        versionMain.references.append(versionRef_A1)
        versionMain.references.append(versionRef_B1)
        versionMain.references.append(versionRef_C3)
        versionMain.save()

        # check if the dependency_update_list has only two elements
        self.assertEqual(len(versionMain.dependency_update_list), 2)

        # and versionRef_A1 and versionRef_B1 are the ones in the list
        self.assertTrue(versionRef_A1 in versionMain.dependency_update_list)
        self.assertTrue(versionRef_B1 in versionMain.dependency_update_list)

    #def test_dependency_update_list_method_returns_a_list_of_Versions_that_needs_update(self):
    #    """testing if the dependency_update_list returns a list of Version
    #    instances which are referenced by this Version instance but have newer
    #    versions available
    #    """
    #
    #    # create a couple of Versions
    #
    #    # Group 1
    #    self.kwargs["take_name"] = "Take1"
    #    versionRef_A1 = Version(**self.kwargs)
    #    versionRef_A1.save()
    #    versionRef_A2 = Version(**self.kwargs)
    #    versionRef_A2.save()
    #    versionRef_A3 = Version(**self.kwargs)
    #    versionRef_A3.save()
    #
    #    # Group 2
    #    # just change the take
    #    self.kwargs["take_name"] = "Take2"
    #    versionRef_B1 = Version(**self.kwargs)
    #    versionRef_B1.save()
    #    versionRef_B2 = Version(**self.kwargs)
    #    versionRef_B2.save()
    #    versionRef_B3 = Version(**self.kwargs)
    #    versionRef_B3.save()

    #    # Group 3
    #    # just change the take
    #    self.kwargs["take_name"] = "Take3"
    #    versionRef_C1 = Version(**self.kwargs)
    #    versionRef_C1.save()
    #    versionRef_C2 = Version(**self.kwargs)
    #    versionRef_C2.save()
    #    versionRef_C3 = Version(**self.kwargs)
    #    versionRef_C3.save()
    #
    #    # Main Version
    #    self.kwargs["take_name"] = "Take4"
    #    versionMain = Version(**self.kwargs)
    #    versionMain.save()

    #    # and reference them to each other
    #    versionMain.references.append(versionRef_A1)
    #    versionMain.references.append(versionRef_B1)
    #    versionMain.references.append(versionRef_C3)
    #    versionMain.save()
    #
    #    # check if the dependency_update_list has only two elements
    #    self.assertEqual(len(versionMain.dependency_update_list), 2)
    #
    #    # and versionRef_A1 and versionRef_B1 are the ones in the list
    #    self.assertTrue(versionRef_A1 in versionMain.dependency_update_list)
    #    self.assertTrue(versionRef_B1 in versionMain.dependency_update_list)

    #def test_dependency_update_list_method_returns_a_list_of_Versions_that_needs_update_for_deeper_references(self):
    #    """testing if the dependency_update_list returns a list of Version
    #    instances which are referenced by this Version instance but have newer
    #    versions available and also return their references if they also have
    #    newer versions
    #    """

    #    # create a couple of Versions

    #    # Group 1
    #    self.kwargs["take_name"] = "Take1"
    #    versionRef_A1 = Version(**self.kwargs)
    #    versionRef_A1.save()
    #    versionRef_A2 = Version(**self.kwargs)
    #    versionRef_A2.save()
    #    versionRef_A3 = Version(**self.kwargs)
    #    versionRef_A3.save()

    #    # Group 2
    #    # just change the take
    #    self.kwargs["take_name"] = "Take2"
    #    versionRef_B1 = Version(**self.kwargs)
    #    versionRef_B1.save()
    #    versionRef_B2 = Version(**self.kwargs)
    #    versionRef_B2.save()
    #    versionRef_B3 = Version(**self.kwargs)
    #    versionRef_B3.save()

    #    # Group 3
    #    # just change the take
    #    self.kwargs["take_name"] = "Take3"
    #    versionRef_C1 = Version(**self.kwargs)
    #    versionRef_C1.save()
    #    versionRef_C2 = Version(**self.kwargs)
    #    versionRef_C2.save()
    #    versionRef_C3 = Version(**self.kwargs)
    #    versionRef_C3.save()

    #    # Main Version
    #    self.kwargs["take_name"] = "Take4"
    #    versionMain = Version(**self.kwargs)
    #    versionMain.save()

    #    # and reference them to each other
    #    versionMain.references.append(versionRef_A1)
    #    versionRef_A1.references.append(versionRef_B1)
    #    versionRef_B1.references.append(versionRef_C1)
    #    versionMain.save()
    #    versionRef_A1.save()
    #    versionRef_B1.save()

    #    # check if the dependency_update_list has only two elements
    #    self.assertEqual(len(versionMain.dependency_update_list), 3)

    #    # and versionRef_A1 and versionRef_B1 are the ones in the list
    #    self.assertTrue(versionRef_A1 in versionMain.dependency_update_list)
    #    self.assertTrue(versionRef_B1 in versionMain.dependency_update_list)
    #    self.assertTrue(versionRef_C1 in versionMain.dependency_update_list)

    def test_is_published_argument_is_skipped(self):
        """testing if the ipublished attribute will be false when the
        is_published argument is skipped
        """

        self.kwargs.pop("is_published")
        new_version = Version(**self.kwargs)
        self.assertEqual(new_version.is_published, False)

    def test_is_published_argument_is_working_properly(self):
        """testing if the is_published argument is properly set the
        is_published attribute
        """
        self.kwargs["is_published"] = True
        new_version = Version(**self.kwargs)
        self.assertEqual(new_version.is_published, True)

    def test_is_published_attribute_is_working_properly(self):
        """testing if the is_published attribute is working properly
        """
        self.test_version.is_published = True
        self.assertEqual(self.test_version.is_published, True)

    def test_latest_published_version_is_working_properly(self):
        """testing if the latest_published_version is returning the latest
        published version properlyy
        """

        vers1 = self.test_version

        self.kwargs["is_published"] = True
        vers2 = Version(**self.kwargs)
        vers2.save()

        self.kwargs["is_published"] = False
        vers3 = Version(**self.kwargs)
        vers3.save()

        self.kwargs["is_published"] = False
        vers4 = Version(**self.kwargs)
        vers4.save()

        self.kwargs["is_published"] = True
        vers5 = Version(**self.kwargs)
        vers5.save()

        self.kwargs["is_published"] = False
        vers6 = Version(**self.kwargs)
        vers6.save()

        self.kwargs["is_published"] = False
        vers7 = Version(**self.kwargs)
        vers7.save()

        self.assertEqual(vers1.latest_published_version(), vers5)
        self.assertEqual(vers2.latest_published_version(), vers5)
        self.assertEqual(vers3.latest_published_version(), vers5)
        self.assertEqual(vers4.latest_published_version(), vers5)
        self.assertEqual(vers5.latest_published_version(), vers5)
        self.assertEqual(vers6.latest_published_version(), vers5)
        self.assertEqual(vers7.latest_published_version(), vers5)

    def test_is_latest_published_version_works_properly(self):
        """testing if the is_latest_published_version is working properly
        """

        vers1 = self.test_version

        self.kwargs["is_published"] = True
        vers2 = Version(**self.kwargs)
        vers2.save()

        self.kwargs["is_published"] = False
        vers3 = Version(**self.kwargs)
        vers3.save()

        self.kwargs["is_published"] = False
        vers4 = Version(**self.kwargs)
        vers4.save()

        self.kwargs["is_published"] = True
        vers5 = Version(**self.kwargs)
        vers5.save()

        self.kwargs["is_published"] = False
        vers6 = Version(**self.kwargs)
        vers6.save()

        self.kwargs["is_published"] = False
        vers7 = Version(**self.kwargs)
        vers7.save()

        self.assertEqual(vers1.is_latest_published_version(), False)
        self.assertEqual(vers2.is_latest_published_version(), False)
        self.assertEqual(vers3.is_latest_published_version(), False)
        self.assertEqual(vers4.is_latest_published_version(), False)
        self.assertEqual(vers5.is_latest_published_version(), True)
        self.assertEqual(vers6.is_latest_published_version(), False)
        self.assertEqual(vers7.is_latest_published_version(), False)

    def test_status_argument_is_skipped_will_set_status_to_WTS_for_new_versions(self):
        """testing if the status argument is skipped the status will be set to
        WTS for new versions
        """
        self.kwargs.pop('status')
        self.kwargs['take_name'] = 'TestStatus'
        new_version = Version(**self.kwargs)
        self.assertEqual(new_version.status, conf.status_list[0])

    def test_status_argument_is_skipped_will_set_status_to_the_same_for_old_version(self):
        """testing if the status argument is skipped the status will be set to
        what it is in the previous version
        """
        self.kwargs.pop('status')
        self.test_version.status = conf.status_list[4]
        self.test_version.save()
        new_version = Version(**self.kwargs)
        self.assertEqual(conf.status_list[4], new_version.status)

    def test_status_argument_is_None_will_set_status_to_WTS_for_new_versions(self):
        """testing if the status argument is None the status will be set to
        WTS for new versions
        """
        self.kwargs['status'] = None
        self.kwargs['take_name'] = ' TestStatus'
        new_version = Version(**self.kwargs)
        self.assertEqual(new_version.status, conf.status_list[0])

    def test_status_argument_is_None_will_set_status_to_the_same_value_for_old_versions(self):
        """testing if the status argument is skipped the status attribute will
        be set to what it was in the previous version
        """
        self.kwargs['status'] = None
        self.test_version.status = conf.status_list[3]
        self.test_version.save()
        new_version = Version(**self.kwargs)
        self.assertEqual(new_version.status, conf.status_list[3])

    def test_status_argument_is_not_a_string(self):
        """testing a TypeError will be raised if the status argument is not an
        instance of string
        """
        self.kwargs['status'] = 234
        self.assertRaises(TypeError, Version, **self.kwargs)

    def test_status_attribute_is_not_a_string(self):
        """testing if a TypeError will be raised when the status attribute is
        not an instance of string
        """
        self.assertRaises(TypeError, setattr, self.test_version, 2342)

    def test_status_argument_is_not_one_of_the_enum(self):
        """testing if a ValueError will be raised when the status argument
        doesn't have the correct value
        """
        self.kwargs['status'] = 'NotInTheList'
        self.assertRaises(ValueError, Version, **self.kwargs)

    def test_status_attribute_is_not_one_of_the_enum(self):
        """testing if a ValueError will be raised when the status attribute
        doesn't have the correct value
        """
        self.assertRaises(ValueError, setattr, self.test_version, 'status',
            'NotInTheList')

    def test_status_argument_is_in_long_form_will_be_converted_to_the_short_form(self):
        """testing if the status argument is in long form will be converted to
        the short form
        """
        self.kwargs['status'] = conf.status_list_long_names[1]
        new_version = Version(**self.kwargs)
        self.assertEqual(new_version.status, conf.status_list[1])

    def test_status_attribute_is_comparable_with_long_status_names(self):
        """testing if status attribute is comparable to statuses with long
        names
        """
        status = conf.status_list_long_names[1]
        self.kwargs['status'] = status
        new_version = Version(**self.kwargs)
        self.assertEqual(status, new_version.status)

    def test_status_attribute_is_a_string_instance(self):
        """testing if the status attribute is a string
        """
        new_version = Version(**self.kwargs)
        self.assertIsInstance(new_version.status, str)

    def test_status_attribute_is_working_properly(self):
        """testing if the status attribute is working properly
        """
        new_version = Version(**self.kwargs)
        new_version.status = conf.status_list_long_names[2]
        self.assertEqual(conf.status_list_long_names[2], new_version.status)
        self.assertEqual(conf.status_list[2], new_version.status)

    def test_inputs_argument_working_properly(self):
        """testing the IOMixin part of the Version instances
        """
        from oyProjectManager import FileLink
        self.kwargs['inputs'] = [
            FileLink('test1.%03d.tga 1-10', '/tmp'),
            FileLink('test2.%03d.tga 1-10', '/tmp')
        ]
        new_version = Version(**self.kwargs)
        self.assertEqual(new_version.inputs, self.kwargs['inputs'])

    def test_inputs_attribute_is_working_properly(self):
        """testing the IOMixin part of the Version instances
        """
        from oyProjectManager import FileLink
        inputs = [
            FileLink('test1.%03d.tga 1-10', '/tmp'),
            FileLink('test2.%03d.tga 1-10', '/tmp')
        ]
        new_version = Version(**self.kwargs)
        new_version.inputs = inputs
        self.assertEqual(inputs, new_version.inputs)

    def test_outputs_argument_working_properly(self):
        """testing the IOMixin part of the Version instances
        """
        from oyProjectManager import FileLink
        self.kwargs['outputs'] = [
            FileLink('test1.%03d.tga 1-10', '/tmp'),
            FileLink('test2.%03d.tga 1-10', '/tmp')
        ]
        new_version = Version(**self.kwargs)
        self.assertEqual(new_version.outputs, self.kwargs['outputs'])

    def test_outputs_attribute_is_working_properly(self):
        """testing the IOMixin part of the Version instances
        """
        from oyProjectManager import FileLink
        outputs = [
            FileLink('test1.%03d.tga 1-10', '/tmp'),
            FileLink('test2.%03d.tga 1-10', '/tmp')
        ]
        new_version = Version(**self.kwargs)
        new_version.outputs = outputs
        self.assertEqual(outputs, new_version.outputs)


text:
class Bulkforce
  class ConnectionBuilder
    attr_reader :host
    attr_reader :api_version
    attr_reader :credentials

    def initialize(host:, api_version:, **credentials)
      @host = host
      @api_version = api_version
      @credentials = credentials
    end

    def build
      base_options = { api_version: api_version }

      session_options = if credentials[:session_id]
        {
          session_id: credentials[:session_id],
          instance: credentials.fetch(:instance),
        }
      elsif credentials[:refresh_token]
        Bulkforce::Http.oauth_login(
          host,
          credentials.fetch(:client_id),
          credentials.fetch(:client_secret),
          credentials[:refresh_token]
        )
      else
        Bulkforce::Http.login(
          host,
          credentials.fetch(:username),
          "#{credentials.fetch(:password)}#{credentials.fetch(:security_token)}",
          api_version
        )
      end.select { |k, _|  [:session_id, :instance].include?(k) }.to_h

      Bulkforce::Connection.new(base_options.merge(session_options))
    end
  end
end


text:
package net.sourceforge.plantuml.ugraphic.comp;

import net.sourceforge.plantuml.graphic.StringBounder;
import net.sourceforge.plantuml.graphic.TextBlock;

public class CompressionXorYBuilder {

	public static TextBlock build(CompressionMode mode, TextBlock textBlock, StringBounder stringBounder) {
		final PiecewiseAffineTransform affine = getPiecewiseAffineTransform(mode, textBlock, stringBounder);
		return PiecewiseAffineOnXorYBuilder.build(mode, textBlock, affine);
	}

	private static PiecewiseAffineTransform getPiecewiseAffineTransform(CompressionMode mode, TextBlock textBlock,
			StringBounder stringBounder) {
		final SlotFinder slotFinder = SlotFinder.create(mode, stringBounder);
		textBlock.drawU(slotFinder);
		final SlotSet ysSlotSet = slotFinder.getSlotSet().reverse().smaller(5.0);
		return new CompressionTransform(ysSlotSet);
	}

}


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

/**
 * Basic file related exception class.
 *
 * @package   core_files
 * @category  files
 * @copyright 2008 Petr Skoda (http://skodak.org)
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class file_exception extends moodle_exception {
    /**
     * Constructor
     *
     * @param string $errorcode error code
     * @param stdClass $a Extra words and phrases that might be required in the error string
     * @param string $debuginfo optional debugging information
     */
    function __construct($errorcode, $a=NULL, $debuginfo = NULL) {
        parent::__construct($errorcode, '', '', $a, $debuginfo);
    }
}

/**
 * Can not create file exception.
 *
 * @package   core_files
 * @category  files
 * @copyright 2008 Petr Skoda (http://skodak.org)
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class stored_file_creation_exception extends file_exception {
    /**
     * Constructor.
     *
     * @param int $contextid context ID
     * @param string $component component
     * @param string $filearea file area
     * @param int $itemid item ID
     * @param string $filepath file path
     * @param string $filename file name
     * @param string $debuginfo extra debug info
     */
    function __construct($contextid, $component, $filearea, $itemid, $filepath, $filename, $debuginfo = null) {
        $a = new stdClass();
        $a->contextid = $contextid;
        $a->component = $component;
        $a->filearea  = $filearea;
        $a->itemid    = $itemid;
        $a->filepath  = $filepath;
        $a->filename  = $filename;
        parent::__construct('storedfilenotcreated', $a, $debuginfo);
    }
}

/**
 * No file access exception.
 *
 * @package   core_files
 * @category  files
 * @copyright 2008 Petr Skoda (http://skodak.org)
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class file_access_exception extends file_exception {
    /**
     * Constructor.
     *
     * @param string $debuginfo extra debug info
     */
    public function __construct($debuginfo = null) {
        parent::__construct('nopermissions', null, $debuginfo);
    }
}

/**
 * Hash file content problem exception.
 *
 * @package   core_files
 * @category  files
 * @copyright 2008 Petr Skoda (http://skodak.org)
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class file_pool_content_exception extends file_exception {
    /**
     * Constructor.
     *
     * @param string $contenthash content hash
     * @param string $debuginfo extra debug info
     */
    public function __construct($contenthash, $debuginfo = null) {
        parent::__construct('hashpoolproblem', $contenthash, $debuginfo);
    }
}

/**
 * Problem with records in the {files_reference} table.
 *
 * @package   core_files
 * @catehory  files
 * @copyright 2012 David Mudrak <david@moodle.com>
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class file_reference_exception extends file_exception {
    /**
     * Constructor.
     *
     * @param int $repositoryid the id of the repository that provides the referenced file
     * @param string $reference the information for the repository to locate the file
     * @param int|null $referencefileid the id of the record in {files_reference} if known
     * @param int|null $fileid the id of the referrer's record in {files} if known
     * @param string|null $debuginfo extra debug info
     */
    function __construct($repositoryid, $reference, $referencefileid=null, $fileid=null, $debuginfo=null) {
        $a = new stdClass();
        $a->repositoryid = $repositoryid;
        $a->reference = $reference;
        $a->referencefileid = $referencefileid;
        $a->fileid = $fileid;
        parent::__construct('filereferenceproblem', $a, $debuginfo);
    }
}


text:
package org.apache.flink.yarn

import org.apache.flink.runtime.clusterframework.types.ResourceID
import org.apache.flink.runtime.highavailability.HighAvailabilityServices
import org.apache.flink.runtime.io.disk.iomanager.IOManager
import org.apache.flink.runtime.io.network.NetworkEnvironment
import org.apache.flink.runtime.memory.MemoryManager
import org.apache.flink.runtime.metrics.groups.TaskManagerMetricGroup
import org.apache.flink.runtime.taskexecutor.TaskManagerConfiguration
import org.apache.flink.runtime.taskmanager.{TaskManager, TaskManagerLocation}

/** An extension of the TaskManager that listens for additional YARN related
  * messages.
  */
class YarnTaskManager(
    config: TaskManagerConfiguration,
    resourceID: ResourceID,
    taskManagerLocation: TaskManagerLocation,
    memoryManager: MemoryManager,
    ioManager: IOManager,
    network: NetworkEnvironment,
    numberOfSlots: Int,
    highAvailabilityServices: HighAvailabilityServices,
    taskManagerMetricGroup: TaskManagerMetricGroup)
  extends TaskManager(
    config,
    resourceID,
    taskManagerLocation,
    memoryManager,
    ioManager,
    network,
    numberOfSlots,
    highAvailabilityServices,
    taskManagerMetricGroup) {

  override def handleMessage: Receive = {
    super.handleMessage
  }
}

  object YarnTaskManager {
    /** Entry point (main method) to run the TaskManager on YARN.
      *
      * @param args The command line arguments.
      */
    def main(args: Array[String]): Unit = {
      YarnTaskManagerRunner.runYarnTaskManager(args, classOf[YarnTaskManager])
    }

}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/homep_menu"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/homep_titlemenu_bg"
        android:onClick="onClick" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:text="@string/app_name"
        android:textSize="18sp"
        android:textColor="#fff" />

    <Button
        android:id="@+id/homep_refresh"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/homep_titlebt_bg"
        android:onClick="onClick" />

</LinearLayout>