text:
<?php

namespace frontend\controllers;

use common\models\Article;
use common\models\ArticleAttachment;
use common\repositories\ArticleRepository;
use common\repositories\CommentsRepository;
use common\repositories\HotelsRepository;
use common\repositories\RoomsRepository;
use common\repositories\UserRepository;
use frontend\forms\CommentForm;
use frontend\forms\RoomBookForm;
use frontend\models\search\ArticleSearch;
use Yii;
use yii\db\Query;
use yii\filters\AccessControl;
use yii\helpers\Json;
use yii\web\Controller;
use yii\web\NotFoundHttpException;

/**
 * @author Eugene Terentev <eugene@terentev.net>
 */
class RoomsController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['book'],
                'rules' => [
                    [
                        'actions' => ['book'],
                        'allow' => true,
                        'roles' => ['user']
                    ],
                ]
            ]
        ];
    }

    /**
     * @return string
     */
    public function actionIndex()
    {
        $searchModel = new RoomsRepositorySearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->sort = [
            'defaultOrder' => ['created_at' => SORT_DESC]
        ];
        return $this->render('index', ['dataProvider'=>$dataProvider]);
    }

    /**
     * @param $slug
     * @return string
     * @throws NotFoundHttpException
     */
    public function actionView($slug)
    {
        $model = RoomsRepository::find()
            ->where(['status' => ArticleRepository::STATUS_PUBLISHED])
            ->andWhere(['slug'=>$slug])
            ->one();
        if (!$model) {
            throw new NotFoundHttpException;
        }

        $model->body = $model->getTagsReplacedBody();

        $commentModel = null;
        $comments = [];
        if ($model->comments_status == ArticleRepository::COMMENTS_STATUS_ACTIVE){
            $commentModel = new CommentForm();
            if (Yii::$app->request->isPost && $commentModel->load(Yii::$app->request->post())){
                if ($commentModel->validate()) {
                    $commentModel->obj_id = $model->id;
                    $commentModel->type = CommentsRepository::TYPE_ROOM;
                    $commentModel->status = CommentsRepository::STATUS_PUBLISHED;
                    $commentModel->ip = ip2long(Yii::$app->request->getUserIP());
                    $commentModel->save();
                    return $this->refresh();
                }
            }
            $comments = CommentsRepository::getCommentsByObject(CommentsRepository::TYPE_ROOM, $model->id);
        }

        return $this->render('view', [
            'model'=>$model,
            'commentModel' => $commentModel,
            'comments' => $comments
        ]);
    }

    function actionBook($id) {
        if (!UserRepository::isClientInfoFill(Yii::$app->user->id)) {
            Yii::$app->session->setFlash('alert', [
                'body' => 'Заполните ваши контактные данные',
                'options' => ['class' => 'alert-success']
            ]);
            return $this->redirect(['profile/edit']);
        }

        $model = new RoomBookForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()){
            $model->book();
        }

        $model = RoomsRepository::find()
            ->where(['status' => ArticleRepository::STATUS_PUBLISHED])
            ->andWhere(['id'=>$id])
            ->one();
        if (!$model) {
            throw new NotFoundHttpException;
        }

        $formModel = new RoomBookForm();

        return $this->render('book', [
            'model' => $model,
            'formModel' => $formModel
        ]);
    }

    function isOld($date){//$year, $month, $day
        $year = date('Y', strtotime($date));
        $month = date('m', strtotime($date));
        $day = date('d', strtotime($date));
        $currentTime = time();
        $cYear = date('Y', $currentTime);
        if ($cYear > $year) return true;
        $cMonth = date('m', $currentTime);
        if ($cMonth > $month) return true;
        $cDay = date('d', $currentTime);
        if ($cDay > $day) return true;

        return false;
    }

    function actionCheckDates() { //$from = '2017-01-18 00:00:00', $to = '2017-01-30 23:59:59'
        $from = Yii::$app->request->post('from');
        $to = Yii::$app->request->post('to');
        $roomId = Yii::$app->request->post('roomId');

        $result =  [
            'status' => 'busy',
            'msg' => 'Ошибка.'
        ];

        if ((!$from) || (!$to)) {
            $result =  ['status' => 'busy',
                'msg' => 'Укажите правильные даты заезда и выезда'];
            return Json::encode($result);
        }

        if (strtotime($from) >= strtotime($to)) {
            $result =  ['status' => 'busy',
                'msg' => 'Укажите правильные даты заезда и выезда'];
            return Json::encode($result);
        }

        if ($this->isOld($from)){
            $result =  ['status' => 'busy',
                'msg' => 'Укажите правильные даты заезда и выезда'];
            return Json::encode($result);
        }
        if ($this->isOld($to)) {
            $result =  ['status' => 'busy',
                'msg' => 'Укажите правильные даты заезда и выезда'];
            return Json::encode($result);
        }

        $query = (new Query())
            ->select('rb.*')
            ->from('rooms_busy rb')
            ->where(['between', 'date', "$from 00:00:00", "$to 23:59:59"])
            ->andWhere(['in', 'status', [2,3,4]])
            ->all();

        if ($query) {
            $result =  [
                'status' => 'busy',
                'msg' => 'Некоторые дни заняты'
            ];
        } else {
            $room = RoomsRepository::find()->where(['id' => $roomId])->one();
            $date1 = new \DateTime($from);
            $date2 = new \DateTime($to);
            $days = $date2->diff($date1)->format("%a");
            $sum = $days * $room->price;

            $result =  [
                'status' => 'free',
                'sum' => $sum
            ];;
        }

        return Json::encode($result);
    }

    /**
     * @param $id
     * @return $this
     * @throws NotFoundHttpException
     * @throws \yii\web\HttpException
     */
    public function actionAttachmentDownload($id)
    {
        $model = RoomsRepository::findOne($id);
        if (!$model) {
            throw new NotFoundHttpException;
        }

        return Yii::$app->response->sendStreamAsFile(
            Yii::$app->fileStorage->getFilesystem()->readStream($model->path),
            $model->name
        );
    }
}


text:
@interface LogRawXML : NSObject {
	FILE *file;
	id path;
}

-initWithPath: aPath;

-path;
-setPath: aPath;

-(void)writeXML: anElement;

-(void)close;

@end

redpajama_set_name: RedPajamaGithub


text:
# JavaScript Canvas to Blob

## Description
Canvas to Blob is a polyfill for the standard JavaScript [canvas.toBlob](http://www.w3.org/TR/html5/the-canvas-element.html#dom-canvas-toblob) method.

It can be used to create [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects from an HTML [canvas](https://developer.mozilla.org/en-US/docs/HTML/Canvas) element.

## Usage
Include the (minified) JavaScript Canvas to Blob script in your HTML markup:

```html
<script src="js/canvas-to-blob.min.js"></script>
```

Then use the *canvas.toBlob()* method in the same way as the native implementation:

```js
var canvas = document.createElement('canvas');
/* ... your canvas manipulations ... */
if (canvas.toBlob) {
    canvas.toBlob(
        function (blob) {
            // Do something with the blob object,
            // e.g. creating a multipart form for file uploads:
            var formData = new FormData();
            formData.append('file', blob, fileName);
            /* ... */
        },
        'image/jpeg'
    );
}
```

## Requirements
The JavaScript Canvas to Blob function has zero dependencies.

However, Canvas to Blob is a very suitable complement to the [JavaScript Load Image](https://github.com/blueimp/JavaScript-Load-Image) function.

## API
In addition to the **canvas.toBlob** polyfill, the JavaScript Canvas to Blob script provides one additional function called **dataURLtoBlob**, which is added to the global window object if no AMD loader is used to load the script:

```js
// 80x60px GIF image (color black, base64 data):
var b64Data = 'R0lGODdhUAA8AIABAAAAAP///ywAAAAAUAA8AAACS4SPqcvtD6' +
        'OctNqLs968+w+G4kiW5omm6sq27gvH8kzX9o3n+s73/g8MCofE' +
        'ovGITCqXzKbzCY1Kp9Sq9YrNarfcrvcLDovH5PKsAAA7',
    imageUrl = 'data:image/gif;base64,' + b64Data,
    blob = window.dataURLtoBlob && window.dataURLtoBlob(imageUrl);
```

## Browsers
The following browsers support either the native or the polyfill *canvas.toBlob()* method:

### Desktop browsers

* Google Chrome (see [Chromium issue #67587](https://code.google.com/p/chromium/issues/detail?id=67587))
* Apple Safari 6.0+ (see [Mozilla issue #648610](https://bugzilla.mozilla.org/show_bug.cgi?id=648610))
* Mozilla Firefox 4.0+
* Microsoft Internet Explorer 10.0+

### Mobile browsers

* Apple Safari Mobile on iOS 6.0+
* Google Chrome on iOS 6.0+
* Google Chrome on Android 4.0+

## Test
[JavaScript Canvas to Blob Test](http://blueimp.github.io/JavaScript-Canvas-to-Blob/test/)

## License
The JavaScript Canvas to Blob script is released under the [MIT license](http://www.opensource.org/licenses/MIT).


text:
package org.drools.scenariosimulation.api.model;

import java.util.List;
import java.util.stream.IntStream;

import org.junit.Before;
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;

public class BackgroundTest {

    private Background background;
    private BackgroundData originalBackgroundData;

    @Before
    public void setup() {
        background = new Background();
        FactIdentifier factIdentifier = FactIdentifier.create("Test", String.class.getCanonicalName());
        ExpressionIdentifier expressionIdentifier = ExpressionIdentifier.create("Test", FactMappingType.GIVEN);
        background.getScesimModelDescriptor().addFactMapping(factIdentifier, expressionIdentifier);

        originalBackgroundData = background.addData();
        originalBackgroundData.setDescription("Test Description");
        originalBackgroundData.addMappingValue(factIdentifier, expressionIdentifier, "TEST");
    }

    @Test
    public void addData() {
        background.addData(1);

        assertThatThrownBy(() -> background.addData(-1))
                .isInstanceOf(IndexOutOfBoundsException.class);

        assertThatThrownBy(() -> background.addData(3))
                .isInstanceOf(IndexOutOfBoundsException.class);
    }

    @Test
    public void cloneModel() {
        final Background cloned = this.background.cloneModel();
        assertNotNull(cloned);
        final ScesimModelDescriptor originalDescriptor = background.getScesimModelDescriptor();
        final ScesimModelDescriptor clonedDescriptor = cloned.getScesimModelDescriptor();
        assertEquals(originalDescriptor.getUnmodifiableFactMappings().size(), clonedDescriptor.getUnmodifiableFactMappings().size());
        IntStream.range(0, originalDescriptor.getUnmodifiableFactMappings().size()).forEach(index -> {
            assertEquals(originalDescriptor.getUnmodifiableFactMappings().get(index), clonedDescriptor.getUnmodifiableFactMappings().get(index));
        });
        assertEquals(background.getUnmodifiableData().size(), cloned.getUnmodifiableData().size());
        IntStream.range(0, background.getUnmodifiableData().size()).forEach(index -> {
            assertEquals(background.getUnmodifiableData().get(index).getDescription(), cloned.getUnmodifiableData().get(index).getDescription());
        });
    }

    @Test
    public void cloneData() {
        BackgroundData clonedBackgroundData = background.cloneData(0, 1);

        assertEquals(originalBackgroundData.getDescription(), clonedBackgroundData.getDescription());
        assertEquals(originalBackgroundData.getUnmodifiableFactMappingValues().size(), clonedBackgroundData.getUnmodifiableFactMappingValues().size());
        assertEquals(originalBackgroundData, background.getDataByIndex(0));
        assertEquals(clonedBackgroundData, background.getDataByIndex(1));

        assertNotEquals(originalBackgroundData, clonedBackgroundData);
        assertNotEquals(originalBackgroundData.getUnmodifiableFactMappingValues().get(0), clonedBackgroundData.getUnmodifiableFactMappingValues().get(0));
    }

    @Test
    public void cloneScesimDataFail() {

        assertThatThrownBy(() -> background.cloneData(-1, 1))
                .isInstanceOf(IndexOutOfBoundsException.class);

        assertThatThrownBy(() -> background.cloneData(2, 1))
                .isInstanceOf(IndexOutOfBoundsException.class);

        assertThatThrownBy(() -> background.cloneData(0, -1))
                .isInstanceOf(IndexOutOfBoundsException.class);

        assertThatThrownBy(() -> background.cloneData(0, 2))
                .isInstanceOf(IndexOutOfBoundsException.class);
    }

    @Test
    public void removeFactMappingByIndex() {
        assertEquals(2, background.getUnmodifiableData().get(0).getUnmodifiableFactMappingValues().size());
        assertEquals(1, background.getScesimModelDescriptor().getUnmodifiableFactMappings().size());
        background.removeFactMappingByIndex(0);
        assertEquals(1, background.getUnmodifiableData().get(0).getUnmodifiableFactMappingValues().size());
        assertEquals(0, background.getScesimModelDescriptor().getUnmodifiableFactMappings().size());
    }

    @Test
    public void removeFactMapping() {
        assertEquals(2, background.getUnmodifiableData().get(0).getUnmodifiableFactMappingValues().size());
        assertEquals(1, background.getScesimModelDescriptor().getUnmodifiableFactMappings().size());
        background.removeFactMapping(background.getScesimModelDescriptor().getFactMappingByIndex(0));
        assertEquals(1, background.getUnmodifiableData().get(0).getUnmodifiableFactMappingValues().size());
        assertEquals(0, background.getScesimModelDescriptor().getUnmodifiableFactMappings().size());
    }

    @Test
    public void getBackgroundDataWithIndex() {
        List<BackgroundDataWithIndex> backgroundDataWithIndex = background.getBackgroundDataWithIndex();
        assertEquals(background.getUnmodifiableData().size(), backgroundDataWithIndex.size());
        BackgroundDataWithIndex backgroundData = backgroundDataWithIndex.get(0);
        int index = backgroundData.getIndex();
        assertEquals(background.getDataByIndex(index - 1), backgroundData.getScesimData());
    }
}


text:
using ::testing::StrictMock;

namespace gpu {
namespace gles2 {

class RenderbufferManagerTestBase : public GpuServiceTest {
 public:
  static const GLint kMaxSize = 128;
  static const GLint kMaxSamples = 4;

 protected:
  void SetUpBase(MemoryTracker* memory_tracker, bool depth24_supported) {
    GpuServiceTest::SetUp();
    manager_.reset(new RenderbufferManager(
        memory_tracker, kMaxSize, kMaxSamples, depth24_supported));
  }

  void TearDown() override {
    manager_->Destroy(true);
    manager_.reset();
    GpuServiceTest::TearDown();
  }

  scoped_ptr<RenderbufferManager> manager_;
};

class RenderbufferManagerTest : public RenderbufferManagerTestBase {
 protected:
  void SetUp() override {
    bool depth24_supported = false;
    SetUpBase(NULL, depth24_supported);
  }
};

class RenderbufferManagerMemoryTrackerTest
    : public RenderbufferManagerTestBase {
 protected:
  void SetUp() override {
    mock_memory_tracker_ = new StrictMock<MockMemoryTracker>();
    bool depth24_supported = false;
    SetUpBase(mock_memory_tracker_.get(), depth24_supported);
  }

  scoped_refptr<MockMemoryTracker> mock_memory_tracker_;
};

#define EXPECT_MEMORY_ALLOCATION_CHANGE(old_size, new_size, pool)   \
  EXPECT_CALL(*mock_memory_tracker_.get(),                          \
              TrackMemoryAllocatedChange(old_size, new_size, pool)) \
      .Times(1).RetiresOnSaturation()

// GCC requires these declarations, but MSVC requires they not be present
#ifndef COMPILER_MSVC
const GLint RenderbufferManagerTestBase::kMaxSize;
const GLint RenderbufferManagerTestBase::kMaxSamples;
#endif

TEST_F(RenderbufferManagerTest, Basic) {
  const GLuint kClient1Id = 1;
  const GLuint kService1Id = 11;
  const GLuint kClient2Id = 2;
  EXPECT_EQ(kMaxSize, manager_->max_renderbuffer_size());
  EXPECT_EQ(kMaxSamples, manager_->max_samples());
  EXPECT_FALSE(manager_->HaveUnclearedRenderbuffers());
  // Check we can create renderbuffer.
  manager_->CreateRenderbuffer(kClient1Id, kService1Id);
  // Check renderbuffer got created.
  scoped_refptr<Renderbuffer> renderbuffer1 =
      manager_->GetRenderbuffer(kClient1Id);
  ASSERT_TRUE(renderbuffer1.get() != NULL);
  EXPECT_FALSE(manager_->HaveUnclearedRenderbuffers());
  EXPECT_EQ(kClient1Id, renderbuffer1->client_id());
  // Check we get nothing for a non-existent renderbuffer.
  EXPECT_TRUE(manager_->GetRenderbuffer(kClient2Id) == NULL);
  // Check trying to a remove non-existent renderbuffers does not crash.
  manager_->RemoveRenderbuffer(kClient2Id);
  // Check that the renderbuffer is deleted when the last ref is released.
  EXPECT_CALL(*gl_, DeleteRenderbuffersEXT(1, ::testing::Pointee(kService1Id)))
      .Times(1)
      .RetiresOnSaturation();
  // Check we can't get the renderbuffer after we remove it.
  manager_->RemoveRenderbuffer(kClient1Id);
  EXPECT_TRUE(manager_->GetRenderbuffer(kClient1Id) == NULL);
  EXPECT_FALSE(manager_->HaveUnclearedRenderbuffers());
  EXPECT_EQ(0u, renderbuffer1->client_id());
}

TEST_F(RenderbufferManagerTest, Destroy) {
  const GLuint kClient1Id = 1;
  const GLuint kService1Id = 11;
  // Check we can create renderbuffer.
  manager_->CreateRenderbuffer(kClient1Id, kService1Id);
  // Check renderbuffer got created.
  Renderbuffer* renderbuffer1 =
      manager_->GetRenderbuffer(kClient1Id);
  ASSERT_TRUE(renderbuffer1 != NULL);
  EXPECT_CALL(*gl_, DeleteRenderbuffersEXT(1, ::testing::Pointee(kService1Id)))
      .Times(1)
      .RetiresOnSaturation();
  manager_->Destroy(true);
  renderbuffer1 = manager_->GetRenderbuffer(kClient1Id);
  ASSERT_TRUE(renderbuffer1 == NULL);
}

TEST_F(RenderbufferManagerTest, Renderbuffer) {
  const GLuint kClient1Id = 1;
  const GLuint kService1Id = 11;
  // Check we can create renderbuffer.
  manager_->CreateRenderbuffer(kClient1Id, kService1Id);
  // Check renderbuffer got created.
  Renderbuffer* renderbuffer1 =
      manager_->GetRenderbuffer(kClient1Id);
  ASSERT_TRUE(renderbuffer1 != NULL);
  EXPECT_EQ(kService1Id, renderbuffer1->service_id());
  EXPECT_EQ(0, renderbuffer1->samples());
  EXPECT_EQ(static_cast<GLenum>(GL_RGBA4), renderbuffer1->internal_format());
  EXPECT_EQ(0, renderbuffer1->width());
  EXPECT_EQ(0, renderbuffer1->height());
  EXPECT_TRUE(renderbuffer1->cleared());
  EXPECT_EQ(0u, renderbuffer1->EstimatedSize());

  // Check if we set the info it gets marked as not cleared.
  const GLsizei kSamples = 4;
  const GLenum kFormat = GL_RGBA4;
  const GLsizei kWidth = 128;
  const GLsizei kHeight = 64;
  manager_->SetInfo(renderbuffer1, kSamples, kFormat, kWidth, kHeight);
  EXPECT_EQ(kSamples, renderbuffer1->samples());
  EXPECT_EQ(kFormat, renderbuffer1->internal_format());
  EXPECT_EQ(kWidth, renderbuffer1->width());
  EXPECT_EQ(kHeight, renderbuffer1->height());
  EXPECT_FALSE(renderbuffer1->cleared());
  EXPECT_FALSE(renderbuffer1->IsDeleted());
  EXPECT_TRUE(manager_->HaveUnclearedRenderbuffers());
  EXPECT_EQ(kWidth * kHeight * 4u * 4u, renderbuffer1->EstimatedSize());

  manager_->SetCleared(renderbuffer1, true);
  EXPECT_TRUE(renderbuffer1->cleared());
  EXPECT_FALSE(manager_->HaveUnclearedRenderbuffers());

  manager_->SetInfo(renderbuffer1, kSamples, kFormat, kWidth, kHeight);
  EXPECT_TRUE(manager_->HaveUnclearedRenderbuffers());

  // Check that the renderbuffer is deleted when the last ref is released.
  EXPECT_CALL(*gl_, DeleteRenderbuffersEXT(1, ::testing::Pointee(kService1Id)))
      .Times(1)
      .RetiresOnSaturation();
  manager_->RemoveRenderbuffer(kClient1Id);
  EXPECT_FALSE(manager_->HaveUnclearedRenderbuffers());
}

TEST_F(RenderbufferManagerMemoryTrackerTest, Basic) {
  const GLuint kClient1Id = 1;
  const GLuint kService1Id = 11;
  EXPECT_MEMORY_ALLOCATION_CHANGE(0, 0, MemoryTracker::kUnmanaged);
  manager_->CreateRenderbuffer(kClient1Id, kService1Id);
  Renderbuffer* renderbuffer1 =
      manager_->GetRenderbuffer(kClient1Id);
  ASSERT_TRUE(renderbuffer1 != NULL);

  const GLsizei kSamples = 4;
  const GLenum kFormat = GL_RGBA4;
  const GLsizei kWidth = 128;
  const GLsizei kHeight1 = 64;
  const GLsizei kHeight2 = 32;
  uint32 expected_size_1 = 0;
  uint32 expected_size_2 = 0;
  manager_->ComputeEstimatedRenderbufferSize(
      kWidth, kHeight1, kSamples, kFormat, &expected_size_1);
  manager_->ComputeEstimatedRenderbufferSize(
      kWidth, kHeight2, kSamples, kFormat, &expected_size_2);
  EXPECT_MEMORY_ALLOCATION_CHANGE(
      0, expected_size_1, MemoryTracker::kUnmanaged);
  manager_->SetInfo(renderbuffer1, kSamples, kFormat, kWidth, kHeight1);
  EXPECT_MEMORY_ALLOCATION_CHANGE(
      expected_size_1, 0, MemoryTracker::kUnmanaged);
  EXPECT_MEMORY_ALLOCATION_CHANGE(
      0, expected_size_2, MemoryTracker::kUnmanaged);
  manager_->SetInfo(renderbuffer1, kSamples, kFormat, kWidth, kHeight2);
  EXPECT_MEMORY_ALLOCATION_CHANGE(
      expected_size_2, 0, MemoryTracker::kUnmanaged);
  EXPECT_CALL(*gl_, DeleteRenderbuffersEXT(1, ::testing::Pointee(kService1Id)))
      .Times(1)
      .RetiresOnSaturation();
}

TEST_F(RenderbufferManagerTest, UseDeletedRenderbufferInfo) {
  const GLuint kClient1Id = 1;
  const GLuint kService1Id = 11;
  manager_->CreateRenderbuffer(kClient1Id, kService1Id);
  scoped_refptr<Renderbuffer> renderbuffer1(
      manager_->GetRenderbuffer(kClient1Id));
  ASSERT_TRUE(renderbuffer1.get() != NULL);
  // Remove it.
  manager_->RemoveRenderbuffer(kClient1Id);
  // Use after removing.
  const GLsizei kSamples = 4;
  const GLenum kFormat = GL_RGBA4;
  const GLsizei kWidth = 128;
  const GLsizei kHeight = 64;
  manager_->SetInfo(renderbuffer1.get(), kSamples, kFormat, kWidth, kHeight);
  // See that it still affects manager.
  EXPECT_TRUE(manager_->HaveUnclearedRenderbuffers());
  manager_->SetCleared(renderbuffer1.get(), true);
  EXPECT_FALSE(manager_->HaveUnclearedRenderbuffers());
  // Check that the renderbuffer is deleted when the last ref is released.
  EXPECT_CALL(*gl_, DeleteRenderbuffersEXT(1, ::testing::Pointee(kService1Id)))
      .Times(1)
      .RetiresOnSaturation();
  renderbuffer1 = NULL;
}

namespace {

bool InSet(std::set<std::string>* string_set, const std::string& str) {
  std::pair<std::set<std::string>::iterator, bool> result =
      string_set->insert(str);
  return !result.second;
}

}  // anonymous namespace

TEST_F(RenderbufferManagerTest, AddToSignature) {
  const GLuint kClient1Id = 1;
  const GLuint kService1Id = 11;
  manager_->CreateRenderbuffer(kClient1Id, kService1Id);
  scoped_refptr<Renderbuffer> renderbuffer1(
      manager_->GetRenderbuffer(kClient1Id));
  ASSERT_TRUE(renderbuffer1.get() != NULL);
  const GLsizei kSamples = 4;
  const GLenum kFormat = GL_RGBA4;
  const GLsizei kWidth = 128;
  const GLsizei kHeight = 64;
  manager_->SetInfo(renderbuffer1.get(), kSamples, kFormat, kWidth, kHeight);
  std::string signature1;
  std::string signature2;
  renderbuffer1->AddToSignature(&signature1);

  std::set<std::string> string_set;
  EXPECT_FALSE(InSet(&string_set, signature1));

  // change things and see that the signatures change.
  manager_->SetInfo(
      renderbuffer1.get(), kSamples + 1, kFormat, kWidth, kHeight);
  renderbuffer1->AddToSignature(&signature2);
  EXPECT_FALSE(InSet(&string_set, signature2));

  manager_->SetInfo(
      renderbuffer1.get(), kSamples, kFormat + 1, kWidth, kHeight);
  signature2.clear();
  renderbuffer1->AddToSignature(&signature2);
  EXPECT_FALSE(InSet(&string_set, signature2));

  manager_->SetInfo(
      renderbuffer1.get(), kSamples, kFormat, kWidth + 1, kHeight);
  signature2.clear();
  renderbuffer1->AddToSignature(&signature2);
  EXPECT_FALSE(InSet(&string_set, signature2));

  manager_->SetInfo(
      renderbuffer1.get(), kSamples, kFormat, kWidth, kHeight + 1);
  signature2.clear();
  renderbuffer1->AddToSignature(&signature2);
  EXPECT_FALSE(InSet(&string_set, signature2));

  // put it back to the same and it should be the same.
  manager_->SetInfo(renderbuffer1.get(), kSamples, kFormat, kWidth, kHeight);
  signature2.clear();
  renderbuffer1->AddToSignature(&signature2);
  EXPECT_EQ(signature1, signature2);

  // Check the set was acutally getting different signatures.
  EXPECT_EQ(5u, string_set.size());

  EXPECT_CALL(*gl_, DeleteRenderbuffersEXT(1, ::testing::Pointee(kService1Id)))
      .Times(1)
      .RetiresOnSaturation();
}

class RenderbufferManagerFormatTest : public RenderbufferManagerTestBase {
 protected:
  void SetUp() override {
    bool depth24_supported = true;
    SetUpBase(NULL, depth24_supported);
  }
};

TEST_F(RenderbufferManagerFormatTest, UpgradeDepthFormatOnGLES) {
  gfx::GLImplementation prev_impl = gfx::GetGLImplementation();
  gfx::SetGLImplementation(gfx::kGLImplementationEGLGLES2);
  GLenum impl_format =
      manager_->InternalRenderbufferFormatToImplFormat(GL_DEPTH_COMPONENT16);
  gfx::SetGLImplementation(prev_impl);
  EXPECT_EQ(static_cast<GLenum>(GL_DEPTH_COMPONENT24), impl_format);
}

TEST_F(RenderbufferManagerFormatTest, UseUnsizedDepthFormatOnNonGLES) {
  gfx::GLImplementation prev_impl = gfx::GetGLImplementation();
  gfx::SetGLImplementation(gfx::kGLImplementationDesktopGL);
  GLenum impl_format =
      manager_->InternalRenderbufferFormatToImplFormat(GL_DEPTH_COMPONENT16);
  gfx::SetGLImplementation(prev_impl);
  EXPECT_EQ(static_cast<GLenum>(GL_DEPTH_COMPONENT), impl_format);
}

}  // namespace gles2
}  // namespace gpu


text:
Sets max-width, left and right padding, and centers elements

<!-- example -->
```jsx
import Container from 'react-ua/lib/elements/container';

class ContainerTest extends React.Component {

  render () {
    return (
      <Container>
      Helloooo Centred
      </Container>
    );
  }
}
```


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright © 1991-2013 Unicode, Inc.
CLDR data files are interpreted according to the LDML specification (http://unicode.org/reports/tr35/)
For terms of use, see http://www.unicode.org/copyright.html
-->
<ldml xmlns:sil="urn://www.sil.org/ldml/0.1">
	<identity>
		<version number="$Revision: 9750 $"/>
		<generation date="$Date: 2014-02-21 05:52 +0000 $"/>
		<language type="swc"/>
		<special>
			<sil:identity source="cldr" defaultRegion="CD" script="Latn" draft="approved"/>
		</special>
	</identity>
	<metadata>
		<casingData>
			<casingItem type="day_format_except_narrow">lowercase</casingItem>
			<casingItem type="day_narrow">lowercase</casingItem>
			<casingItem type="day_standalone_except_narrow">lowercase</casingItem>
			<casingItem type="era_abbr">lowercase</casingItem>
			<casingItem type="era_name">lowercase</casingItem>
			<casingItem type="era_narrow">lowercase</casingItem>
			<casingItem type="language">titlecase</casingItem>
			<casingItem type="month_format_except_narrow">lowercase</casingItem>
			<casingItem type="month_narrow">lowercase</casingItem>
			<casingItem type="month_standalone_except_narrow">lowercase</casingItem>
			<casingItem type="relative">titlecase</casingItem>
		</casingData>
	</metadata>
	<special>
		<sil:external-resources>
			<sil:font name="Charis SIL" types="default">
				<sil:url>https://wirl.api.sil.org/CharisSILReg&type=ttf</sil:url>
			</sil:font>
			<sil:font name="Noto Sans"><!--types="ui"-->
				<sil:url>https://github.com/googlefonts/noto-fonts/raw/main/hinted/ttf/NotoSans/NotoSans-Regular.ttf</sil:url>
			</sil:font>
			<sil:font name="Noto Serif">
				<sil:url>https://github.com/googlefonts/noto-fonts/raw/main/hinted/ttf/NotoSerif/NotoSerif-Regular.ttf</sil:url>
			</sil:font>
			<sil:kbd id="sil_eastern_congo" type="kmp">
				<sil:url draft="generated">https://keyman.com/go/keyboard/sil_eastern_congo/download/kmp</sil:url>
			</sil:kbd>
		</sil:external-resources>
	</special>
</ldml>


text:
package class

var (
	baseTypeB = &FieldType{"B"} // byte
	baseTypeC = &FieldType{"C"} // char
	baseTypeD = &FieldType{"D"} // double
	baseTypeF = &FieldType{"F"} // float
	baseTypeI = &FieldType{"I"} // int
	baseTypeJ = &FieldType{"J"} // long
	baseTypeS = &FieldType{"S"} // short
	baseTypeZ = &FieldType{"Z"} // boolean
	baseTypeV = &FieldType{"V"} // void
)

type FieldType struct {
	descriptor string
}

func (self *FieldType) Descriptor() string {
	return self.descriptor
}

func (self *FieldType) IsBaseType() bool {
	return len(self.descriptor) == 1
}
func (self *FieldType) IsVoidType() bool {
	return self.descriptor == "V"
}
func (self *FieldType) IsObjectType() bool {
	return self.descriptor[0] == 'L'
}
func (self *FieldType) IsArrayType() bool {
	return self.descriptor[0] == '['
}


text:
package com.ngengs.android.app.filkomnewsreader.data.model;

import android.os.Parcel;
import android.os.Parcelable;

import com.google.gson.annotations.SerializedName;

import java.util.Date;
import java.util.List;

@SuppressWarnings("unused")
public class News implements Parcelable {
    public static final Creator<News> CREATOR = new Creator<News>() {
        @Override
        public News createFromParcel(Parcel in) {
            return new News(in);
        }

        @Override
        public News[] newArray(int size) {
            return new News[size];
        }
    };
    @SerializedName("id")
    private String id;
    @SerializedName("title")
    private String title;
    @SerializedName("image")
    private String image;
    @SerializedName("short_desc")
    private String shortDescription;
    @SerializedName("link")
    private String link;
    @SerializedName("date")
    private Date date;
    @SerializedName("content")
    private List<NewsContent> content;

    public News(String id) {
        this.id = id;
    }

    private News(Parcel in) {
        id = in.readString();
        title = in.readString();
        image = in.readString();
        shortDescription = in.readString();
        link = in.readString();
        content = in.createTypedArrayList(NewsContent.CREATOR);
        long tmpDate = in.readLong();
        date = tmpDate == -1 ? null : new Date(tmpDate);
    }

    public String getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getShortDescription() {
        return shortDescription;
    }

    public void setShortDescription(String shortDescription) {
        this.shortDescription = shortDescription;
    }

    public String getLink() {
        return link;
    }

    public void setLink(String link) {
        this.link = link;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public List<NewsContent> getContent() {
        return content;
    }

    public void setContent(List<NewsContent> content) {
        this.content = content;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(id);
        parcel.writeString(title);
        parcel.writeString(image);
        parcel.writeString(shortDescription);
        parcel.writeString(link);
        parcel.writeTypedList(content);
        parcel.writeLong(date != null ? date.getTime() : -1);
    }
}


text:
require 'spec_helper'

describe Exporters::ResultsExporter do
  let!(:result) { FactoryBot.create(:result, :overall) }
  let(:exporter) { described_class.new }

  it "returns some data" do
    data = exporter.rows
    expect(data.count).to eq(1)
  end
end


text:
#include "PacketReader.h"
#include "Logs.h"

using namespace std;
using namespace Poco;

namespace Cumulus {

PacketReader::PacketReader(const UInt8* buffer,UInt32 size) : _memory((const char*)buffer,size),BinaryReader(_memory),fragments(1) {
}

// Consctruction by copy
PacketReader::PacketReader(PacketReader& other) : _memory(other._memory),BinaryReader(_memory),fragments(other.fragments) {
}

PacketReader::~PacketReader() {
}

void PacketReader::shrink(UInt32 rest) {
	if(rest>available()) {
		WARN("rest %u more upper than available %u bytes",rest,available());
		rest = available();
	}
	_memory.resize(position()+rest);
}

} // namespace Cumulus


text:
using namespace ofp;

PropertyRange BundleControl::properties() const {
  return SafeByteRange(this, header_.length(), sizeof(BundleControl));
}

bool BundleControl::validateInput(Validation *context) const {
  return properties().validateInput(context);
}

UInt32 BundleControlBuilder::send(Writable *channel) {
  UInt32 xid = channel->nextXid();
  UInt8 version = channel->version();
  size_t msgLen = sizeof(msg_) + properties_.size();

  msg_.header_.setLength(msgLen);
  msg_.header_.setVersion(version);
  msg_.header_.setXid(xid);

  channel->write(&msg_, sizeof(msg_));
  channel->write(properties_.data(), properties_.size());
  channel->flush();

  return xid;
}


text:
<?php

defined( 'ABSPATH' ) or die();

use Billingo\Plugin\Helper;
use Logentries\LeLogger;

if ( ! class_exists( 'Billingo_Generate_Invoice' ) ) {

	class Billingo_Generate_Invoice {
		private $billingo;

		public function __construct() {
			$action = get_option( 'wc_settings_tab_billingo_invoice_generation_action' );
			switch ( $action ) {
				case 'ordercomplete':
					add_action( 'woocommerce_order_status_completed', array( $this, 'generate_invoice' ) );
					break;
				case 'thankyou':
					add_action( 'woocommerce_thankyou', array( $this, 'generate_invoice' ) );
					break;
				default:
					add_action( 'woocommerce_order_status_completed', array( $this, 'generate_invoice' ) );
					break;
			}
		}

		public function generate_invoice( $order_id ) {
			$private_key          = get_option( 'wc_settings_tab_billingo_private_key' );
			$public_key           = get_option( 'wc_settings_tab_billingo_public_key' );
			$invoice_block        = intval( get_option( 'wc_settings_tab_billingo_invoice_block' ) );
			$invoice_due_date     = get_option( 'wc_settings_tab_billingo_invoice_due_date' );
			$invoice_due_date     = $invoice_due_date !== false ? $invoice_due_date : 8;
			$send_email           = get_option( 'wc_settings_tab_billingo_invoice_send_email' );
			$use_gross_unit_price = get_option( 'wc_settings_tab_billingo_use_gross_unit_price' ) === 'yes' ? true : false;
			$billingo_custom_vat  = get_option( 'wc_settings_tab_billingo_vat' );
            $debug_mode           = get_option( 'wc_settings_debug_mode_enabled' ) === 'yes' ? true : false;

			if ( false === $private_key || false === $public_key ) {
				return false;
			}

			$logger = false;
            if ($debug_mode === true) {
                $logger = new Logentries\LeLogger(BILLINGO_LOGENTRIES_TOKEN, LOG_DEBUG);
            }
			$invoice_helper = new Helper\Helper( $public_key, $private_key, $send_email, $logger);
            $invoice_helper->debug_info = 'version: ' . BILLINGO_VERSION;

			$order       = new WC_Order( $order_id );
			$order_items = $order->get_items();

			$client = array(
				'name'            => $order->billing_company ?: $order->billing_first_name . ' ' . $order->billing_last_name,
				'email'           => $order->billing_email,
				'billing_address' => array(
					'street_name' => trim( $order->billing_address_1 . $order->billing_address_2 ),
					'street_type' => '',
					'house_nr'    => '',
					'city'        => $order->billing_city,
					'postcode'    => $order->billing_postcode,
					'country'     => $order->billing_country
				)
			);

			$invoice = array(
				'fulfillment_date'   => current_time( 'Y-m-d' ),
				'due_date'           => date( 'Y-m-d', strtotime( current_time( 'Y-m-d' ) . "+$invoice_due_date days" ) ),
				'payment_method'     => $order->payment_method,
				'comment'            => '',
				'template_lang_code' => 'hu',
				'electronic_invoice' => 1,
				'currency'           => $order->get_order_currency(),
				'block_uid'          => $invoice_block,
				'type'               => 3,
			);

			$billingo_invoice_items = array();
			foreach ( $order_items as $item ) {
				$billingo_unit_price = $use_gross_unit_price ? 'gross_unit_price' : 'net_unit_price';
				$unit_price          = floatval( $item['line_total'] );
				$name                = $item['name'];
				$qty                 = intval( $item['qty'] );
				$vat_rate            = $use_gross_unit_price ? intval( $billingo_custom_vat ) : false;

				if ( false === $vat_rate ) {
					$tax_rates = WC_Tax::get_rates( $item['tax_class'] );
					$tax       = array_shift( $tax_rates );
					$vat_rate  = floatval( $tax['rate'] );
				}

				if ( $qty > 1 ) {
					$product_id = $item['variation_id'] == '0' ? $item['product_id'] : $item['variation_id'];
					$product    = new WC_Product_Factory();
					$product    = $product->get_product( $product_id );
					$unit_price = floatval( $product->get_price_excluding_tax() );
				}

				$invoice_item                         = array(
					'description' => $name,
					'vat_rate'    => $vat_rate,
					'unit'        => '',
					'qty'         => $qty,
				);
				$invoice_item[ $billingo_unit_price ] = $unit_price;

				$billingo_invoice_items[] = $invoice_item;
			}
			$shipping = $order->get_shipping_methods();
			foreach ( $shipping as $s ) {
				$name  = $s['name'];
				$price = floatval( $s['cost'] );
				$tax   = 0;
				if ( $price !== 0.0 ) {
					foreach ( unserialize( $s['taxes'] ) as $val ) {
						$tax += floatval( $val );
					}
					$billingo_invoice_items[] = array(
						'net_unit_price' => $price,
						'description'    => $name,
						'vat_rate'       => $tax / $price,
						'unit'           => '',
						'qty'            => 1,
					);
				}
			}

			$invoice['items'] = $billingo_invoice_items;

			$invoice_id = $invoice_helper->createInvoice( $client, $invoice );

			if ( is_array( $invoice_id ) ) {
				$order->add_order_note( substr( $invoice_id['error'], 0, 300 ) );

				return false;
			}

			update_post_meta( $order_id, '_billingo_invoice_created', 1, true );

			$download_link = $invoice_helper->getDownloadLink( $invoice_id );

			if ( is_array( $download_link ) ) {
				$order->add_order_note( substr( $download_link['error'], 0, 300 ) );

				return false;
			}

			update_post_meta( $order_id, '_billingo_invoice_download_link', $download_link, true );

			if ( $send_email === 'yes' ) {
				$send_email_reponse = $invoice_helper->sendEmail( $invoice_id );

				if ( is_array( $send_email_reponse ) ) {
					$order->add_order_note( substr( $send_email_response['error'], 0, 300 ) );

					return false;
				}
			}

			$order->add_order_note( 'Successful Billingo invoice generation!' );

			return true;
		}
	}

	new Billingo_Generate_Invoice();
}


text:
require 'rubygems'
require 'nokogiri'
require 'css_inliner/extractor'
require 'css_inliner/csspool'

module CSSInliner
  class Inliner
    # @param [Nokogiri::XML::Document] document
    # @param [String] basedir
    def initialize(document, basedir)
      @document = document
      @basedir = basedir
      @extractor = Extractor.new @document, @basedir
    end

    def inline
      original_styles = {}
      @document.search('.//*[@style]').each do |elem|
        original_styles[elem] = elem['style']
        elem.remove_attribute('style')
      end

      css = @extractor.extract
      css.sorted_selectors.each do |selector|
        sel = selector.to_s
        next if sel =~ /@|:/
        sel = 'body' if sel == '*' or sel == 'html'
        @document.css(sel).each do |elem|
          base = CSSPool.CSS("* {#{elem['style']}}").rule_sets.first.declarations
          elem['style'] = CSSPool::CSS.update_declarations(base, selector.declarations).join
        end
      end

      original_styles.each_pair do |elem, style|
        base = CSSPool.CSS("* {#{elem['style']}}").rule_sets.first.declarations
        orig = CSSPool.CSS("* {#{style}}").rule_sets.first.declarations
        elem['style'] = CSSPool::CSS.update_declarations(base, orig).join
      end

      @document
    end
  end
end


text:
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>or-tools/src/graph/: Member List - Doxy</title>
    <link rel="shortcut icon" href="../../../favicon.ico">

    <link href="../../../doxygen.css" rel="stylesheet" type="text/css">
    <link href="../../../tabs.css" rel="stylesheet" type="text/css">

          Generated on: Thu Mar 29 07:46:58 PDT 2012
            for custom file set

        <tt>//
            doxy/
            or-tools/
            src/
            graph/
            </tt>

Main Page

Related Pages

Namespaces

Classes

Files

Class List

Class Hierarchy

Class Members

operations_research::TailArrayReleaser< GraphType, false > Member List
This is the complete list of members for operations_research::TailArrayReleaser< GraphType, false >, including all inherited members.

graph_	operations_research::TailArrayReleaser< GraphType, false >

ReleaseTailArray() const 	operations_research::TailArrayReleaser< GraphType, false >	 [inline]

TailArrayReleaser(GraphType *graph)	operations_research::TailArrayReleaser< GraphType, false >	 [inline, explicit]


text:
using NLog.LayoutRenderers;
using System;
using System.IO;
using Xunit;

namespace NLog.UnitTests.LayoutRenderers
{
    public class DirectorySeparatorLayoutRendererTests
    {
        [Fact]
        public void RenderTest1()
        {
            // Arrange
            var renderer = new DirectorySeparatorLayoutRenderer();
            var expected = Path.DirectorySeparatorChar.ToString();

            // Act
            var result = renderer.Render(LogEventInfo.CreateNullEvent());

            // Assert

            Assert.Equal(expected, result);
        }

        [Fact]
        public void GetRawValueTest1()
        {
            // Arrange
            var renderer = new DirectorySeparatorLayoutRenderer();
            var expected = Path.DirectorySeparatorChar;

            // Act
            var returnResult = renderer.TryGetRawValue(LogEventInfo.CreateNullEvent(), out var result);

            // Assert
            Assert.True(returnResult);
            Assert.Equal(expected, result);
        }
    }
}


text:
package org.kie.workbench.common.widgets.decoratedgrid.client.widget.data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import org.kie.workbench.common.widgets.decoratedgrid.client.widget.CellValue;
import org.kie.workbench.common.widgets.decoratedgrid.client.widget.SortConfiguration;

/**
 * A simple container for rows of data.
 */
public class DynamicData
        implements
        Iterable<DynamicDataRow> {

    private boolean isMerged = false;

    private List<Boolean> visibleColumns = new ArrayList<Boolean>();

    private static final long serialVersionUID = 5061393855340039472L;

    private List<DynamicDataRow> data = new ArrayList<DynamicDataRow>();

    /**
     * Add column to data
     * @param index
     * @param columnData
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public void addColumn( int index,
                           List<CellValue<? extends Comparable<?>>> columnData,
                           boolean isVisible ) {

        //Check the column contains the same number of rows as the existing table
        int numberOfRows = 0;
        if ( this.data.size() > 0 ) {
            for ( DynamicDataRow row : this.data ) {
                numberOfRows++;
                if ( row instanceof GroupedDynamicDataRow ) {
                    numberOfRows = numberOfRows + ( (GroupedDynamicDataRow) row ).getChildRows().size() - 1;
                }
            }
        }
        if ( numberOfRows != columnData.size() ) {
            throw new IllegalArgumentException( "columnData contains a different number of rows to that defined." );
        }

        //Add the column data to the table
        int iRowIndex = 0;
        for ( int iRow = 0; iRow < data.size(); iRow++ ) {
            DynamicDataRow row = data.get( iRow );
            CellValue<? extends Comparable<?>> cell = columnData.get( iRowIndex );
            if ( row instanceof GroupedDynamicDataRow ) {
                GroupedDynamicDataRow groupedRow = (GroupedDynamicDataRow) row;

                //Setting value on a GroupedCellValue causes all children to assume the same value
                CellValue.GroupedCellValue gcv = cell.convertToGroupedCell();
                groupedRow.add( index,
                                gcv );

                //So set the children's values accordingly
                for ( int iGroupedRow = 0; iGroupedRow < groupedRow.getChildRows().size(); iGroupedRow++ ) {
                    cell = columnData.get( iRowIndex );
                    gcv.addCellToGroup( cell );
                    groupedRow.getChildRows().get( iGroupedRow ).set( index,
                                                                      cell );
                    iRowIndex++;
                }
            } else {
                row.add( index,
                         cell );
                iRowIndex++;
            }
        }

        visibleColumns.add( index,
                            isVisible );

        assertModelMerging();
    }

    /**
     * Move a column
     * @param sourceColumnIndex
     * @param targetColumnIndex
     */
    public void moveColumn( int sourceColumnIndex,
                            int targetColumnIndex ) {
        for ( int iRow = 0; iRow < data.size(); iRow++ ) {
            DynamicDataRow row = data.get( iRow );
            row.add( targetColumnIndex,
                     row.remove( sourceColumnIndex ) );
        }
        visibleColumns.add( targetColumnIndex,
                            visibleColumns.remove( sourceColumnIndex ) );
        assertModelMerging();
    }

    /**
     * Add an empty row of data to the end of the table
     * @return DynamicDataRow The newly created row
     */
    public DynamicDataRow addRow() {
        DynamicDataRow row = new DynamicDataRow();
        data.add( row );

        assertModelMerging();
        return row;
    }

    /**
     * Add a row of data at the specified index
     * @param index
     * @param rowData
     */
    public void addRow( int index,
                        DynamicDataRow rowData ) {
        data.add( index,
                  rowData );

        assertModelMerging();
    }

    /**
     * Add a row of data at the end of the table
     * @param rowData
     */
    public void addRow( DynamicDataRow rowData ) {
        addRow( data.size(),
                rowData );
    }

    /**
     * Apply grouping by collapsing applicable rows
     * @param startCell
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public void applyModelGrouping( CellValue<?> startCell ) {

        int startRowIndex = startCell.getCoordinate().getRow();
        int endRowIndex = findMergedCellExtent( startCell.getCoordinate() ).getRow();
        int colIndex = startCell.getCoordinate().getCol();

        //Delete grouped rows replacing with a single "grouped" row
        CellValue.GroupedCellValue groupedCell;
        DynamicDataRow row = data.get( startRowIndex );
        GroupedDynamicDataRow groupedRow = new GroupedDynamicDataRow();
        for ( int iCol = 0; iCol < row.size(); iCol++ ) {
            groupedCell = row.get( iCol ).convertToGroupedCell();
            if ( iCol == colIndex ) {
                groupedCell.addState( CellValue.CellState.GROUPED );
            } else {
                groupedCell.removeState( CellValue.CellState.GROUPED );
            }
            groupedRow.add( groupedCell );
        }

        //Add individual cells to "grouped" row
        for ( int iRow = startRowIndex; iRow <= endRowIndex; iRow++ ) {
            DynamicDataRow childRow = data.get( startRowIndex );
            groupedRow.addChildRow( childRow );
            data.remove( childRow );
        }
        data.remove( row );
        data.add( startRowIndex,
                  groupedRow );

        assertModelMerging();
    }

    public void clear() {
        data.clear();
    }

    /**
     * Delete column data
     * @param index
     */
    public void deleteColumn( int index ) {
        for ( int iRow = 0; iRow < data.size(); iRow++ ) {
            DynamicDataRow row = data.get( iRow );
            row.remove( index );
        }
        visibleColumns.remove( index );
        assertModelMerging();
    }

    public DynamicDataRow deleteRow( int index ) {
        DynamicDataRow row = data.remove( index );
        assertModelMerging();
        return row;
    }

    /**
     * Get the CellValue at the given coordinate
     * @param c
     * @return
     */
    public CellValue<? extends Comparable<?>> get( Coordinate c ) {
        return data.get( c.getRow() ).get( c.getCol() );
    }

    public DynamicDataRow get( int index ) {
        return data.get( index );
    }

    /**
     * Return grid's data. Grouping in the data will be expanded and can
     * therefore can be used prior to populate the underlying data structures
     * prior to persisting.
     * @return data
     */
    public DynamicData getFlattenedData() {
        DynamicData dataClone = new DynamicData();
        for ( int iRow = 0; iRow < data.size(); iRow++ ) {
            DynamicDataRow row = data.get( iRow );
            if ( row instanceof GroupedDynamicDataRow ) {
                List<DynamicDataRow> expandedRow = expandGroupedRow( row,
                                                                     true );
                dataClone.data.addAll( expandedRow );
            } else {
                dataClone.data.add( row );
            }
        }
        return dataClone;
    }

    public int indexOf( DynamicDataRow row ) {
        return data.indexOf( row );
    }

    /**
     * Return the state of merging
     * @return
     */
    public boolean isMerged() {
        return isMerged;
    }

    /**
     * Return the state of grouping
     * @return true if any rows are grouped
     */
    public boolean isGrouped() {
        for ( DynamicDataRow row : this.data ) {
            if ( row instanceof GroupedDynamicDataRow ) {
                return true;
            }
        }
        return false;
    }

    public Iterator<DynamicDataRow> iterator() {
        return data.iterator();
    }

    /**
     * Remove grouping by expanding applicable rows
     * @param startCell
     * @return
     */
    @SuppressWarnings("rawtypes")
    public List<DynamicDataRow> removeModelGrouping( CellValue<?> startCell ) {

        int startRowIndex = startCell.getCoordinate().getRow();

        startCell.removeState( CellValue.CellState.GROUPED );

        //Check if rows need to be recursively expanded
        boolean bRecursive = true;
        DynamicDataRow row = data.get( startRowIndex );
        for ( int iCol = 0; iCol < row.size(); iCol++ ) {
            CellValue<?> cv = row.get( iCol );
            if ( cv instanceof CellValue.GroupedCellValue ) {
                bRecursive = !( bRecursive ^ ( (CellValue.GroupedCellValue) cv ).hasMultipleValues() );
            }
        }

        //Delete "grouped" row and replace with individual rows
        List<DynamicDataRow> expandedRow = expandGroupedRow( row,
                                                             bRecursive );
        deleteRow( startRowIndex );
        data.addAll( startRowIndex,
                     expandedRow );

        assertModelMerging();

        //If the row is replaced with another grouped row ensure the row can be expanded
        row = data.get( startRowIndex );
        boolean hasCellToExpand = false;
        for ( CellValue<?> cell : row ) {
            if ( cell instanceof CellValue.GroupedCellValue ) {
                if ( cell.isGrouped() && cell.getRowSpan() > 0 ) {
                    hasCellToExpand = true;
                    break;
                }
            }
        }
        if ( !hasCellToExpand ) {
            for ( CellValue<?> cell : row ) {
                if ( cell instanceof CellValue.GroupedCellValue && cell.getRowSpan() == 1 ) {
                    cell.addState( CellValue.CellState.GROUPED );
                }
            }
        }
        return expandedRow;
    }

    /**
     * Set the value at the specified coordinate
     * @param c
     * @param value
     */
    public void set( Coordinate c,
                     Object value ) {
        if ( c == null ) {
            throw new IllegalArgumentException( "c cannot be null" );
        }
        data.get( c.getRow() ).get( c.getCol() ).setValue( value );
        assertModelMerging();
    }

    /**
     * Set whether a columns is Visible
     * @param index index of column
     * @param isVisible True if the column is visible
     */
    public void setColumnVisibility( int index,
                                     boolean isVisible ) {
        this.visibleColumns.set( index,
                                 isVisible );
        assertModelIndexes();
    }

    /**
     * Set whether the grid's data is merged or not. Clearing merging within the
     * data also clears grouping
     * @param isMerged
     */
    public void setMerged( boolean isMerged ) {
        this.isMerged = isMerged;
        if ( isMerged ) {
            assertModelMerging();
        } else {
            removeModelGrouping();
            removeModelMerging();
        }
    }

    public int size() {
        return data.size();
    }

    public void sort( final List<SortConfiguration> sortConfig ) {

        if ( sortConfig.size() == 0 ) {

            //No sort configuration, restore original creation sequence
            Collections.sort( data,
                              new Comparator<DynamicDataRow>() {

                                  public int compare( DynamicDataRow leftRow,
                                                      DynamicDataRow rightRow ) {
                                      int comparison = 0;
                                      long li = leftRow.getCreationIndex();
                                      long ri = rightRow.getCreationIndex();
                                      if ( li < ri ) {
                                          comparison = -1;
                                      } else if ( li > ri ) {
                                          comparison = 1;
                                      }
                                      return comparison;
                                  }
                              } );

        } else {

            //Sort Configuration needs to be sorted itself by sortOrder first
            Collections.sort( sortConfig,
                              new Comparator<SortConfiguration>() {

                                  public int compare( SortConfiguration o1,
                                                      SortConfiguration o2 ) {
                                      Integer si1 = o1.getSortIndex();
                                      Integer si2 = o2.getSortIndex();
                                      return si1.compareTo( si2 );
                                  }

                              } );

            //Sort data
            Collections.sort( data,
                              new Comparator<DynamicDataRow>() {

                                  @SuppressWarnings({ "rawtypes", "unchecked" })
                                  public int compare( DynamicDataRow leftRow,
                                                      DynamicDataRow rightRow ) {
                                      int comparison = 0;
                                      for ( int index = 0; index < sortConfig.size(); index++ ) {
                                          SortConfiguration sc = sortConfig.get( index );
                                          Comparable leftColumnValue = leftRow.get( sc.getColumnIndex() );
                                          Comparable rightColumnValue = rightRow.get( sc.getColumnIndex() );
                                          comparison =
                                                  ( leftColumnValue == rightColumnValue ) ? 0
                                                          : ( leftColumnValue == null ) ? -1
                                                          : ( rightColumnValue == null ) ? 1
                                                          : leftColumnValue.compareTo( rightColumnValue );
                                          if ( comparison != 0 ) {
                                              switch ( sc.getSortDirection() ) {
                                                  case ASCENDING:
                                                      break;
                                                  case DESCENDING:
                                                      comparison = -comparison;
                                                      break;
                                                  default:
                                                      throw new IllegalStateException(
                                                              "Sorting can only be enabled for ASCENDING or"
                                                                      + " DESCENDING, not sortDirection ("
                                                                      + sc.getSortDirection()
                                                                      + ") ." );
                                              }
                                              return comparison;
                                          }
                                      }
                                      return comparison;
                                  }
                              } );
        }

        assertModelMerging();

    }

    // Here lays a can of worms! Each cell in the Decision Table has three
    // coordinates: (1) The physical coordinate, (2) The coordinate relating to
    // the HTML table element and (3) The coordinate mapping a HTML table
    // element back to the physical coordinate. For example a cell could have
    // the (1) physical coordinate (0,0) which equates to (2) HTML element (0,1)
    // in which case the cell at physical coordinate (0,1) would have a (3)
    // mapping back to (0,0).
    private void assertModelIndexes() {

        if ( data.size() == 0 ) {
            return;
        }

        for ( int iRow = 0; iRow < data.size(); iRow++ ) {
            DynamicDataRow row = data.get( iRow );

            int colCount = 0;
            for ( int iCol = 0; iCol < row.size(); iCol++ ) {

                int newRow = iRow;
                int newCol = colCount;
                CellValue<? extends Comparable<?>> indexCell = row.get( iCol );
                indexCell.setCoordinate( new Coordinate( iRow,
                                                         iCol ) );

                // Don't index hidden columns; indexing is used to
                // map between HTML elements and the data behind
                if ( visibleColumns.get( iCol ) ) {

                    if ( indexCell.getRowSpan() != 0 ) {
                        newRow = iRow;
                        newCol = colCount++;

                        CellValue<? extends Comparable<?>> cell = data.get( newRow ).get( newCol );
                        cell.setPhysicalCoordinate( new Coordinate( iRow,
                                                                    iCol ) );

                    } else {
                        DynamicDataRow priorRow = data.get( iRow - 1 );
                        CellValue<? extends Comparable<?>> priorCell = priorRow.get( iCol );
                        Coordinate priorHtmlCoordinate = priorCell.getHtmlCoordinate();
                        newRow = priorHtmlCoordinate.getRow();
                        newCol = priorHtmlCoordinate.getCol();
                    }
                } else {
                    final int priorColIndex = ( iCol > 0 ? iCol - 1 : 0 );
                    CellValue<? extends Comparable<?>> priorCell = row.get( priorColIndex );
                    Coordinate priorHtmlCoordinate = priorCell.getHtmlCoordinate();
                    newRow = priorHtmlCoordinate.getRow();
                    newCol = priorHtmlCoordinate.getCol();
                }
                indexCell.setHtmlCoordinate( new Coordinate( newRow,
                                                             newCol ) );
            }
        }
    }

    /**
     * Ensure merging and indexing is reflected in the entire model. This should
     * be called whenever any changes are made to the underlying data externally
     * to the add/remove methods provided publicly herein, such as bulk move
     * operations.
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public void assertModelMerging() {

        if ( data.size() == 0 ) {
            return;
        }

        //Remove merging first as it initialises all coordinates
        removeModelMerging();

        final int COLUMNS = data.get( 0 ).size();

        //Only apply merging if merged
        if ( isMerged ) {

            int minRowIndex = 0;
            int maxRowIndex = data.size();

            //Add an empty row to the end of the data to simplify detection of merged cells that run to the end of the table
            DynamicDataRow blankRow = new DynamicDataRow();
            for ( int iCol = 0; iCol < COLUMNS; iCol++ ) {
                CellValue cv = new CellValue( null );
                Coordinate c = new Coordinate( data.size(),
                                               iCol );
                cv.setCoordinate( c );
                cv.setHtmlCoordinate( c );
                cv.setPhysicalCoordinate( c );
                blankRow.add( cv );
            }
            data.add( blankRow );
            maxRowIndex++;

            //Look in columns for cells with identical values
            for ( int iCol = 0; iCol < COLUMNS; iCol++ ) {
                CellValue<?> cell1 = data.get( minRowIndex ).get( iCol );
                CellValue<?> cell2 = null;
                for ( int iRow = minRowIndex + 1; iRow < maxRowIndex; iRow++ ) {
                    cell1.setRowSpan( 1 );
                    cell2 = data.get( iRow ).get( iCol );

                    //Merge if both cells contain the same value and neither is grouped
                    boolean bSplit = true;
                    if ( !cell1.isEmpty() && !cell2.isEmpty() ) {
                        if ( cell1.getValue().equals( cell2.getValue() ) ) {
                            bSplit = false;
                            if ( cell1 instanceof CellValue.GroupedCellValue ) {
                                bSplit = true;
                            }
                            if ( cell2 instanceof CellValue.GroupedCellValue ) {
                                bSplit = true;
                            }
                        }
                    } else if ( cell1.isOtherwise() && cell2.isOtherwise() ) {
                        bSplit = false;
                        if ( cell1 instanceof CellValue.GroupedCellValue ) {
                            CellValue.GroupedCellValue gcv = (CellValue.GroupedCellValue) cell1;
                            if ( gcv.hasMultipleValues() ) {
                                bSplit = true;
                            }
                        }
                        if ( cell2 instanceof CellValue.GroupedCellValue ) {
                            CellValue.GroupedCellValue gcv = (CellValue.GroupedCellValue) cell2;
                            if ( gcv.hasMultipleValues() ) {
                                bSplit = true;
                            }
                        }
                    }

                    if ( bSplit ) {
                        mergeCells( cell1,
                                    cell2 );
                        cell1 = cell2;
                    }

                }
            }

            //Remove dummy blank row
            data.remove( blankRow );

        }

        // Set indexes after merging has been corrected
        assertModelIndexes();

    }

    //Expand a grouped row and return a list of expanded rows
    private List<DynamicDataRow> expandGroupedRow( DynamicDataRow row,
                                                   boolean bRecursive ) {

        List<DynamicDataRow> ungroupedRows = new ArrayList<DynamicDataRow>();

        if ( row instanceof GroupedDynamicDataRow ) {

            GroupedDynamicDataRow groupedRow = (GroupedDynamicDataRow) row;
            for ( int iChildRow = 0; iChildRow < groupedRow.getChildRows().size(); iChildRow++ ) {
                DynamicDataRow childRow = groupedRow.getChildRows().get( iChildRow );

                if ( bRecursive ) {
                    if ( childRow instanceof GroupedDynamicDataRow ) {
                        List<DynamicDataRow> expandedRow = expandGroupedRow( childRow,
                                                                             bRecursive );
                        ungroupedRows.addAll( expandedRow );
                    } else {
                        ungroupCells( childRow );
                        ungroupedRows.add( childRow );
                    }
                } else {
                    ungroupedRows.add( childRow );
                }
            }
        } else {
            ungroupCells( row );
            ungroupedRows.add( row );
        }

        return ungroupedRows;
    }

    //Find the bottom coordinate of a merged cell
    private Coordinate findMergedCellExtent( Coordinate c ) {
        if ( c.getRow() == data.size() - 1 ) {
            return c;
        }
        Coordinate nc = new Coordinate( c.getRow() + 1,
                                        c.getCol() );
        CellValue<?> newCell = get( nc );
        while ( newCell.getRowSpan() == 0 && nc.getRow() < data.size() - 1 ) {
            nc = new Coordinate( nc.getRow() + 1,
                                 nc.getCol() );
            newCell = get( nc );
        }
        if ( newCell.getRowSpan() != 0 ) {
            nc = new Coordinate( nc.getRow() - 1,
                                 nc.getCol() );
            newCell = get( nc );
        }
        return nc;
    }

    //Merge between the two provided cells
    private void mergeCells( CellValue<?> cell1,
                             CellValue<?> cell2 ) {
        int iStartRowIndex = cell1.getCoordinate().getRow();
        int iEndRowIndex = cell2.getCoordinate().getRow();
        int iColIndex = cell1.getCoordinate().getCol();

        //Any rows that are grouped need row span of zero
        for ( int iRow = iStartRowIndex; iRow < iEndRowIndex; iRow++ ) {
            DynamicDataRow row = data.get( iRow );
            row.get( iColIndex ).setRowSpan( 0 );
        }
        cell1.setRowSpan( iEndRowIndex - iStartRowIndex );

    }

    //Initialise cell parameters when ungrouped
    private void ungroupCells( DynamicDataRow row ) {
        for ( int iCol = 0; iCol < row.size(); iCol++ ) {
            CellValue<?> cell = row.get( iCol );
            cell.removeState( CellValue.CellState.GROUPED );
        }
    }

    /**
     * Remove all grouping throughout the model
     */
    void removeModelGrouping() {

        for ( int iRow = 0; iRow < data.size(); iRow++ ) {
            DynamicDataRow row = data.get( iRow );
            if ( row instanceof GroupedDynamicDataRow ) {
                List<DynamicDataRow> expandedRow = expandGroupedRow( row,
                                                                     true );
                deleteRow( iRow );
                data.addAll( iRow,
                             expandedRow );
                iRow = iRow + expandedRow.size() - 1;
            }
        }

    }

    /**
     * Remove merging from model
     */
    void removeModelMerging() {

        for ( int iRow = 0; iRow < data.size(); iRow++ ) {
            DynamicDataRow row = data.get( iRow );

            for ( int iCol = 0; iCol < row.size(); iCol++ ) {
                CellValue<?> cell = row.get( iCol );
                Coordinate c = new Coordinate( iRow,
                                               iCol );
                cell.setCoordinate( c );
                cell.setHtmlCoordinate( c );
                cell.setPhysicalCoordinate( c );
                cell.setRowSpan( 1 );
            }
        }

        // Set indexes after merging has been corrected
        assertModelIndexes();
    }

}


text:
package com.tle.web.selection.home.sections;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.tle.common.Pair;
import com.tle.web.sections.SectionId;
import com.tle.web.sections.SectionResult;
import com.tle.web.sections.SectionUtils;
import com.tle.web.sections.SectionsRuntimeException;
import com.tle.web.sections.equella.layout.TwoColumnLayout;
import com.tle.web.sections.events.RenderEventContext;
import com.tle.web.sections.generic.AbstractPrototypeSection;
import com.tle.web.sections.generic.NumberOrder;
import com.tle.web.sections.generic.NumberOrderComparator;
import com.tle.web.sections.render.GenericTemplateResult;
import com.tle.web.sections.render.HtmlRenderer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.sf.json.JSONObject;

public class ShowSelectionHomePortalsSection extends AbstractPrototypeSection<Object>
    implements HtmlRenderer {
  private Pair<List<SectionId>, List<SectionId>> portletLayout;
  private List<SectionId> dymanicPortals;

  @Override
  public SectionResult renderHtml(RenderEventContext context) {
    final Pair<List<SectionId>, List<SectionId>> layout = getPortalLayout(context);

    final GenericTemplateResult gtr = new GenericTemplateResult();

    int lCount = SectionUtils.countViewable(context, layout.getFirst());
    int rCount = SectionUtils.countViewable(context, layout.getSecond());

    List<SectionId> left = new ArrayList<SectionId>(layout.getFirst());
    List<SectionId> right = new ArrayList<SectionId>(layout.getSecond());

    if (lCount <= rCount) {
      left.addAll(dymanicPortals);
    } else {
      right.addAll(dymanicPortals);
    }

    gtr.addNamedResult(TwoColumnLayout.LEFT, SectionUtils.renderSectionsCombined(context, left));
    gtr.addNamedResult(TwoColumnLayout.RIGHT, SectionUtils.renderSectionsCombined(context, right));

    return gtr;
  }

  private synchronized Pair<List<SectionId>, List<SectionId>> getPortalLayout(
      RenderEventContext context) {
    if (portletLayout == null) {
      List<LayoutData> left = new ArrayList<LayoutData>();
      List<LayoutData> right = new ArrayList<LayoutData>();
      List<LayoutData> dynamic = new ArrayList<LayoutData>();

      List<SectionId> childIds = context.getChildIds(this);
      for (SectionId childId : childIds) {
        LayoutData data = new LayoutData();
        String idStr = childId.getSectionId();
        data.setSectionId(childId);

        String layout = context.getLayout(idStr);
        try {
          JSONObject json = JSONObject.fromObject(layout);
          data.setOrder(json.getInt("order")); // $NON-NLS-1$

          if (json.get("column").equals("dynamic")) // $NON-NLS-1$//$NON-NLS-2$
          {
            dynamic.add(data);
          } else {
            (json.get("column").equals("left") ? left : right)
                .add(data); // $NON-NLS-1$ //$NON-NLS-2$
          }
        } catch (RuntimeException ex) {
          throw new SectionsRuntimeException(
              "The layout property for "
                  + childId
                  + " is missing or incorrect.  Must be in JSON format with properties"
                  + " \"{order: 1234, column: 'left'|'right'}\", but it was \""
                  + layout
                  + "\"",
              ex);
        }
      }

      Collections.sort(left, NumberOrderComparator.LOWEST_FIRST);
      Collections.sort(right, NumberOrderComparator.LOWEST_FIRST);

      portletLayout =
          new Pair<List<SectionId>, List<SectionId>>(
              Lists.transform(left, DATA_TO_SECTION_ID),
              Lists.transform(right, DATA_TO_SECTION_ID));

      dymanicPortals = Lists.transform(dynamic, DATA_TO_SECTION_ID);
    }

    return portletLayout;
  }

  private static final Function<LayoutData, SectionId> DATA_TO_SECTION_ID =
      new Function<LayoutData, SectionId>() {
        @Override
        public SectionId apply(LayoutData data) {
          return data.getSectionId();
        }
      };

  @Override
  public Class<Object> getModelClass() {
    return Object.class;
  }

  public static class LayoutData implements NumberOrder {
    private int order;
    private SectionId sectionId;

    @Override
    public int getOrder() {
      return order;
    }

    public void setOrder(int order) {
      this.order = order;
    }

    public SectionId getSectionId() {
      return sectionId;
    }

    public void setSectionId(SectionId sectionId) {
      this.sectionId = sectionId;
    }
  }
}


text:
import zasim
import sys

ca_init, display_init, histogram_init = sys.argv[1:]

if ca_init == "constructor":
    binrule = zasim.ca.BinRule(
            rule = 110,
            initial = zasim.conf.RandomConfiguration)
    # this API must support setting the size manually and then initializing it
    # from random data, zeros, ones, whatever as well as initializing it from
    # a file
    binrule.size = 300
    binrule.init()
elif ca_init == "properties":
    binRule = zasim.ca.BinRule()
    # several attributes would actually be properties with getters and setters
    binrule.rule = 110
    binrule.size = (400,)
    binrule.init(zasim.conf.RandomConfiguration)

if display_init == "constructor":
    binrule_display = zasim.display.HistoryDisplay(
            ca=binrule,
            lines=300,
            scale=2)
elif display_init == "properties":
    binrule_display = zasim.display.HistoryDisplay()
    binrule_display.ca = binrule
    binrule_display.size = (800, 600)
elif display_init == "strange":
    # maybe it would be nice if the different ca classes knew what kind of display
    # is right for them
    binrule_display = binrule.create_display(800, 600)

if histogram_init == "one_zero_distribution":
    histogram = zasim.histogram.DistributionDisplay(binrule)
elif histogram_init == "activity_history":
    histogram = zasim.histogram.ActivityHistoryDisplay(binrule)
elif histogram_init == "distribution_history":
    histogram = zasim.histogram.DistributionHistoryDisplay(binrule)

histogram.show()

# open up the window
binrule_display.show()

# step once
# also update all guis related
binrule.step()

# do ten steps, update the gui as fast as possible
binrule.step(10)

# fast-forward 1000 steps without updating the gui
binrule.fast_step(1000)

# let the gui drive the stepping with delays
binrule_display.animate_steps(steps=1000, delay=0.01)

# why not also let the user say for how long it should animate?
binrule_display.animate_steps(steps=1000, time=10)

# displays should be able to save out images
binrule_display.screenshot("pretty.png")

# cas should be able to snapshot configurations or clone themselves
snap1 = binrule.snapshot()

binrule.step(100)
binrule.restore(snap1)

# maybe something like this is interesting
_snaps = []
def step_hook(ca):
    _snaps.append(ca.snapshot())
binrule.step_hook(step_hook)
binrule.step(100)
binrule.step_hook(None)

# comparing configurations of different automatons - as long as they are
# comparable at all - is pretty neat, i suppose.
other_ca = binrule.shallow_clone()

# manipulation of cells should be possible from the gui as well as the shell
other_ca[10:15] = [0, 1, 0, 1, 1]

other_ca.step(100)
binrule.step(100)

# displaying a comparison between two configurations might work like this
diff = other_ca.diff(binrule)
diff_disp = zasim.display.DiffDisplay(diff)

# TODO zellularautomat game of life
# TODO moebius-bandtransformation
# TODO beliebige waende aneinanderkopieren

# 1. qt geschwindigkeit untersuchen: 1x1 pixel pro feld, 3x3 pixel, bilder
#    1d automat mit history, 2d automat (game of life z.B.)
# 2. vision implementieren


text:
-------

    Why? •
    Usage •
    How does it work? •
    Tips

-------

cert is part of fastlane: The easiest way to automate beta deployments and releases for your iOS and Android apps.

![/img/actions/cert.gif](/img/actions/cert.gif)

In the gif we used `cert && sigh`, which will first create an iOS code signing certificate and then a provisioning profile for your app if _cert_ succeeded.

# Usage

**Note**: It is recommended to use [_match_](/actions/match) according to the [codesigning.guide](https://codesigning.guide) for generating and maintaining your certificates. Use _cert_ directly only if you want full control over what's going on and know more about codesigning.

```no-highlight
fastlane cert
```

This will check if any of the available signing certificates is installed on your local machine.

Only if a new certificate needs to be created, _cert_ will

- Create a new private key
- Create a new signing request
- Generate, downloads and installs the certificate
- Import all the generated files into your Keychain

_cert_ will never revoke your existing certificates. If you can't create any more certificates, _cert_ will raise an exception, which means, you have to revoke one of the existing certificates to make room for a new one.

You can pass your Apple ID:

```no-highlight
fastlane cert -u cert@krausefx.com
```

For a list of available commands run

```no-highlight
fastlane action cert
```

Keep in mind, there is no way for _cert_ to download existing certificates + private keys from the Apple Developer Portal, as the private key never leaves your computer.

## Environment Variables

Run `fastlane action cert` to get a list of all available environment variables.

## Use with [_sigh_](https://docs.fastlane.tools/actions/sigh/)

_cert_ becomes really interesting when used in [_fastlane_](https://fastlane.tools) in combination with [_sigh_](https://docs.fastlane.tools/actions/sigh/).

Update your `Fastfile` to contain the following code:

```ruby
lane :beta do
  cert
  sigh(force: true)
end
```

`force: true` will make sure to re-generate the provisioning profile on each run.
This will result in _sigh_ always using the correct signing certificate, which is installed on the local machine.

## How is my password stored?
_cert_ uses the [password manager](https://github.com/fastlane/fastlane/tree/master/credentials_manager) from _fastlane_. Take a look the [CredentialsManager README](https://github.com/fastlane/fastlane/blob/master/credentials_manager/README.md) for more information.

# Tips

## Use 'ProvisionQL' for advanced Quick Look in Finder

Install [ProvisionQL](https://github.com/ealeksandrov/ProvisionQL).

It will show you `mobileprovision` files like this:
![img/actions/QuickLookScreenshot-Provision.png](/img/actions/QuickLookScreenshot-Provision.png)


text:
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')

describe "/folders/edit.html.erb" do
  include FoldersHelper

  before(:each) do
    assigns[:folder] = @folder = stub_model(Folder,
      :new_record? => false,
      :lecture => 1,
      :parent => 1,
      :name => "value for name"
    )
  end

  it "renders the edit folder form" do
    render

    response.should have_tag("form[action=#{folder_path(@folder)}][method=post]") do
      with_tag('input#folder_data_area[name=?]', "folder[data_area]")
      with_tag('input#folder_parent[name=?]', "folder[parent]")
      with_tag('input#folder_name[name=?]', "folder[name]")
    end
  end
end


text:
<resources>

    <dimen name="card_padding_horizontal">24dp</dimen>
    <dimen name="card_spacing_between">16dp</dimen>

</resources>


text:
package io.crate.planner;

import com.carrotsearch.hppc.ObjectLongMap;
import com.carrotsearch.hppc.ObjectLongOpenHashMap;
import io.crate.action.sql.SQLRequest;
import io.crate.action.sql.SQLResponse;
import io.crate.action.sql.TransportSQLAction;
import io.crate.metadata.TableIdent;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.BindingAnnotation;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.inject.Provider;
import org.elasticsearch.common.inject.Singleton;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.threadpool.ThreadPool;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.concurrent.TimeUnit;

@Singleton
public class TableStatsService extends AbstractComponent implements Runnable {

    private static final SQLRequest REQUEST = new SQLRequest(
            "select cast(sum(num_docs) as long), schema_name, table_name from sys.shards group by 2, 3");
    private final Provider<TransportSQLAction> transportSQLAction;
    private volatile ObjectLongMap<TableIdent> tableStats = null;

    @BindingAnnotation
    @Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
    @Retention(RetentionPolicy.RUNTIME)
    public @interface StatsUpdateInterval {}

    @Inject
    public TableStatsService(Settings settings,
                             ThreadPool threadPool,
                             @StatsUpdateInterval TimeValue updateInterval,
                             Provider<TransportSQLAction> transportSQLAction) {
        super(settings);
        this.transportSQLAction = transportSQLAction;
        threadPool.scheduleWithFixedDelay(this, updateInterval);
    }

    @Override
    public void run() {
        updateStats();
    }

    private void updateStats() {
        transportSQLAction.get().execute(
                REQUEST,
                new ActionListener<SQLResponse>() {

                    @Override
                    public void onResponse(SQLResponse sqlResponse) {
                        tableStats = statsFromResponse(sqlResponse);
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        logger.error("error retrieving table stats", e);
                    }
                });
    }

    private static ObjectLongMap<TableIdent> statsFromResponse(SQLResponse sqlResponse) {
        ObjectLongMap<TableIdent> newStats = new ObjectLongOpenHashMap<>((int) sqlResponse.rowCount());
        for (Object[] row : sqlResponse.rows()) {
            newStats.put(new TableIdent((String) row[1], (String) row[2]), (long) row[0]);
        }
        return newStats;
    }

    /**
     * Returns the number of docs a table has.
     *
     * <p>
     * The returned number isn't an accurate real-time value but a cached value that is periodically updated
     * </p>
     * Returns -1 if the table isn't in the cache
     */
    public long numDocs(TableIdent tableIdent) {
        ObjectLongMap<TableIdent> stats = tableStats;
        if (stats == null) {
            stats = statsFromResponse(transportSQLAction.get().execute(REQUEST).actionGet(30, TimeUnit.SECONDS));
            tableStats = stats;
        }
        if (stats.containsKey(tableIdent)) {
            return stats.get(tableIdent);
        }
        return -1;
    }
}


text:
@interface MagicV2ViewController ()

@end

@implementation MagicV2ViewController

#pragma mark -
#pragma mark Object Life Cycle Methods

- (void)viewDidLoad
{
    [super viewDidLoad];

    _isPullToRefreshEnabled = YES;

    [self initDetailModel];
    _detailModel.delegate = self;
    [self initListModel];
    _listModel.delegate = self;
    [self initTableHeaderView];

    [self addEmptyFooterViewIfNeeded];
    [self initUIRefreshControl];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self loadModelRequestsForLoadingType:kMagicV2TableViewLoadingType_Init];
}

#pragma mark -
#pragma mark Init Magic Methods

// /!\ Need to be implemented to activate detail + list mode
- (void)initDetailModel
{
}

// /!\ Must be implemented
- (void)initListModel
{
    NSAssert(NO, @"This is an abstract method and should be overridden");
}

// /!\ Need to be implemented to activate detail + list mode
- (void)initTableHeaderView
{
    if (!_tableHeaderView)
    {
        _tableHeaderView = [self magicTableHeaderView];
        self.tableView.tableHeaderView = _tableHeaderView;
    }
}

- (void)initUIRefreshControl
{
    if (_isPullToRefreshEnabled)
    {
        UIRefreshControl* lRefreshControl = [[UIRefreshControl alloc] init];
        [lRefreshControl addTarget:self action:@selector(diTriggerPullToRefresh:) forControlEvents:UIControlEventValueChanged];
        [self setRefreshControl:lRefreshControl];
    }
}

#pragma mark -
#pragma mark View Update Methods

- (void)addEmptyFooterViewIfNeeded
{
    if (!self.tableView.tableFooterView)
    {
        UIView* lEmptyFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        lEmptyFooterView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        self.tableView.tableFooterView = lEmptyFooterView;
    }
}

#pragma mark -
#pragma mark Magic Methods

- (void)resetModels
{

}

- (void)loadModelRequestsForLoadingType:(MagicV2TableViewLoadingType)_LoadingType
{
    if (_detailModel)
    {
        [_detailModel getResultsForLoadingType:_LoadingType];

        [self setHeaderViewForModel:_detailModel];
    }
    else if (_listModel)
    {
        [_listModel getResultsForLoadingType:_LoadingType];

        [self setHeaderViewForModel:_listModel];
    }
}

- (UITableViewCell*)defaultLoadingCellForTableView:(UITableView*)tableView
{
    MagicV2DefaultLoadingCell* lCell = [tableView dequeueReusableCellWithIdentifier:@"MagicV2DefaultLoadingCell"];

    if (!lCell)
    {
        NSArray* lViews = [[NSBundle mainBundle] loadNibNamed:@"MagicV2DefaultLoadingCell" owner:self options:nil];

        for (UIView* aView in lViews)
        {
            if ([aView isKindOfClass:[MagicV2DefaultLoadingCell class]])
            {
                lCell = (MagicV2DefaultLoadingCell*)aView;
            }
        }
    }

    return lCell;
}

- (UITableViewCell*)noResultCellForTableView:(UITableView*)tableView section:(NSInteger)section
{
    MagicV2NoResultsCell* lCell = [tableView dequeueReusableCellWithIdentifier:@"MagicV2NoResultsCell"];

    if (!lCell)
    {
        NSArray* lViews = [[NSBundle mainBundle] loadNibNamed:@"MagicV2NoResultsCell" owner:self options:nil];

        for (UIView* aView in lViews)
        {
            if ([aView isKindOfClass:[MagicV2NoResultsCell class]])
            {
                lCell = (MagicV2NoResultsCell*)aView;
            }
        }
    }

    return lCell;
}

- (UITableViewCell*)pagingCellForTableView:(UITableView*)tableView
{
    MagicV2PagingCell* lCell = [tableView dequeueReusableCellWithIdentifier:@"MagicV2PagingCell"];

    if (!lCell)
    {
        NSArray* lViews = [[NSBundle mainBundle] loadNibNamed:@"MagicV2PagingCell" owner:self options:nil];

        for (UIView* aView in lViews)
        {
            if ([aView isKindOfClass:[MagicV2PagingCell class]])
            {
                lCell = (MagicV2PagingCell*)aView;
            }
        }
    }

    return lCell;
}

- (UIView<MagicV2TableHeaderViewDelegate>*)magicTableHeaderView
{
    return nil;
}

// /!\ Must be implemented
- (UITableViewCell*)tableViewCellForTableView:(UITableView*)tableView forIndexPath:(NSIndexPath*)indexPath
{
    NSAssert(NO, @"This is an abstract method and should be overridden");

    return nil;
}

// /!\ Must be implemented
- (CGFloat)tableViewCellHeightForTableView:(UITableView*)tableView forIndexPath:(NSIndexPath*)indexPath
{
    NSAssert(NO, @"This is an abstract method and should be overridden");

    return 0.0f;
}

#pragma mark -
#pragma mark View Update Methods

- (void)setHeaderViewForModel:(MagicV2Interactor*)model
{
    [self updateTableHeaderView];
    self.tableView.tableHeaderView = _tableHeaderView;
}

- (void)updateTableHeaderView
{
    if (_tableHeaderView && [_tableHeaderView respondsToSelector:@selector(updateMagicHeaderViewAndReturnNewHeightForMagicController:)])
    {
        float lheight = [_tableHeaderView updateMagicHeaderViewAndReturnNewHeightForMagicController:self];

        _tableHeaderView.frame = CGRectMake(_tableHeaderView.frame.origin.x,
                                            _tableHeaderView.frame.origin.y,
                                            _tableHeaderView.frame.size.width,
                                            lheight);
    }
}

#pragma mark -
#pragma mark User Interaction Methods

- (void)diTriggerPullToRefresh:(id)sender
{
    [self resetModels];

    if (_detailModel)
    {
        [_detailModel pullToRefreshTriggered];
    }
    else
    {
        [_listModel pullToRefreshTriggered];
    }
}

- (void)didTriggerPaging
{
    [_listModel pagingTriggered];
}

#pragma mark -
#pragma mark Table View Data Source Methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_listModel.isPagingEnded)
    {
        self.tableView.contentInset = UIEdgeInsetsMake(self.tableView.contentInset.top,
                                                       self.tableView.contentInset.left,
                                                       [MagicV2PagingCell cellHeight],
                                                       self.tableView.contentInset.right);
        return [_listModel.results count];
    }

    return [_listModel.results count] + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_detailModel.loadingType != kMagicV2TableViewLoadingType_NotLoading || _listModel.loadingType != kMagicV2TableViewLoadingType_NotLoading)
    {
        return [self defaultLoadingCellForTableView:tableView];
    }
    else
    {
        if ([_listModel.results count] == 0)
        {
            return [self noResultCellForTableView:tableView section:indexPath.section];
        }
        else if ([_listModel.results count] > indexPath.row)
        {
            return [self tableViewCellForTableView:tableView forIndexPath:indexPath];
        }
        else
        {
            return [self pagingCellForTableView:tableView];
        }
    }

    return [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"bugCell"];
}

#pragma mark -
#pragma mark Delegate Methods

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell isKindOfClass:[MagicV2PagingCell class]])
    {
        [self didTriggerPaging];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_detailModel.loadingType != kMagicV2TableViewLoadingType_NotLoading || _listModel.loadingType != kMagicV2TableViewLoadingType_NotLoading)
    {
        return [MagicV2DefaultLoadingCell cellHeight];
    }
    else
    {
        if ([_listModel.results count] == 0)
        {
            return [MagicV2NoResultsCell cellHeight];
        }
        else if ([_listModel.results count] > indexPath.row)
        {
            return [self tableViewCellHeightForTableView:tableView forIndexPath:indexPath];
        }
        else
        {
            return [MagicV2PagingCell cellHeight];
        }
    }

    return 44.0f;
}

#pragma mark -
#pragma mark Magic Detail Interactor Delegate Methods

- (void)magicDetailInteractorDidReceivedResults:(MagicV2DetailInteractor*)detailInteractor forLoadingType:(MagicV2TableViewLoadingType)loadingType
{
    switch (loadingType)
    {
        case kMagicV2TableViewLoadingType_PullToRefresh:
            [_listModel pullToRefreshTriggered];
            break;
        case kMagicV2TableViewLoadingType_Init:
            [_listModel getResultsForLoadingType:kMagicV2TableViewLoadingType_Init];
            [self setHeaderViewForModel:_listModel];
            break;
        default:
            break;
    }

    [self updateTableHeaderView];
}

#pragma mark -
#pragma mark Magic List Interactor Delegate Methods

- (void)magicListInteractorDidReceivedResults:(MagicV2ListInteractor*)listInteractor forLoadingType:(MagicV2TableViewLoadingType)loadingType
{
    if (loadingType == kMagicV2TableViewLoadingType_PullToRefresh)
    {
        [self.refreshControl endRefreshing];
    }

    [self.tableView reloadData];
}

@end


text:
using Microsoft.VisualBasic;
using System;

public partial class formOptions
{
    public formOptions()
    {
        // The Me.InitializeComponent call is required for Windows Forms designer support.
        this.InitializeComponent();

        checkboxlistMessages.SetItemChecked(0, gamecache.MainSettings.ExitConfirmation);
        checkboxlistMessages.SetItemChecked(1, gamecache.MainSettings.NewGameOverwrite);
        checkboxlistMessages.SetItemChecked(2, gamecache.MainSettings.RestartOnOptions);
    }

    public void buttonOK_Click(object sender, EventArgs e)
    {
        //Save all options to save\setting.ini
        gamecache.MainSettings.ExitConfirmation = Convert.ToBoolean(checkboxlistMessages.GetItemCheckState(0));
        gamecache.MainSettings.NewGameOverwrite = Convert.ToBoolean(checkboxlistMessages.GetItemCheckState(1));
        gamecache.MainSettings.RestartOnOptions = Convert.ToBoolean(checkboxlistMessages.GetItemCheckState(2));
        //Warn before restarting
        if (gamecache.MainSettings.RestartOnOptions)
            Interaction.MsgBox("The program has to be restarted to take full effect.", MsgBoxStyle.Exclamation, "Please restart.");
        this.Dispose();
    }

    public void buttonCancel_Click(object sender, EventArgs e)
    {
        this.Dispose();
    }
}


text:
A simple little MIDI sequencer to keep Eric from buying more music equipment he doesn't need.

I guess technically this is an arpeggiator, but whatever, I don't want to rename the project.

(why spend money on it if you can build it yourself?)

### Objective

- Hit record
- Play a few notes (timing doesn't matter, just key presses!)
- Hit stop
- Hit play!
- Listen to your notes get played back
- Adjust the speed
- ?????
- Repeat

Here's an [example](http://youtu.be/Rl28UCNWSig?t=39s) of the concept I'm going for (and something I'm sure a lot of you have heard before)

### Running it

If you don't have bundler installed: ```gem install bundler```

Then run ```bundle install``` to make sure you've got all the dependencies installed (don't worry, there's like only one)

Boom:

```bash
ruby lib/sequencer.rb
```

That's it!

### How do I actually *use* it?

Easy.

In recording mode (when it says "RECORDING") you hit a few notes.

* Space: toggle between playback and recording modes
* Arrow keys: adjust tempo
* q: quit, gracefully?

### More info

Stay tuned! Eventually I'm going to try doing a writeup on this once it's in a workable state!


text:
package main

import (
	"path/filepath"
	"strings"

	"github.com/constabulary/gb"
	"github.com/constabulary/gb/cmd"
	"github.com/constabulary/gb/internal/fileutils"
	"github.com/constabulary/gb/internal/vendor"
	"github.com/pkg/errors"
)

var cmdPurge = &cmd.Command{
	Name:      "purge",
	UsageLine: "purge",
	Short:     "purges all unreferenced dependencies",
	Long: `gb vendor purge will remove all unreferenced dependencies

`,
	Run: func(ctx *gb.Context, args []string) error {
		m, err := vendor.ReadManifest(manifestFile(ctx))
		if err != nil {
			return errors.Wrap(err, "could not load manifest")
		}

		imports, err := vendor.ParseImports(ctx.Projectdir())
		if err != nil {
			return errors.Wrap(err, "import could not be parsed")
		}

		var hasImportWithPrefix = func(d string) bool {
			for i := range imports {
				if strings.HasPrefix(i, d) {
					return true
				}
			}
			return false
		}

		dependencies := make([]vendor.Dependency, len(m.Dependencies))
		copy(dependencies, m.Dependencies)

		for _, d := range dependencies {
			if !hasImportWithPrefix(d.Importpath) {
				dep, err := m.GetDependencyForImportpath(d.Importpath)
				if err != nil {
					return errors.Wrap(err, "could not get get dependency")
				}

				if err := m.RemoveDependency(dep); err != nil {
					return errors.Wrap(err, "dependency could not be removed")
				}
				if err := fileutils.RemoveAll(filepath.Join(ctx.Projectdir(), "vendor", "src", filepath.FromSlash(d.Importpath))); err != nil {
					// TODO(dfc) need to apply vendor.cleanpath here to remove intermediate directories.
					return errors.Wrap(err, "dependency could not be deleted")
				}
			}
		}

		return vendor.WriteManifest(manifestFile(ctx), m)
	},
}


text:
<!DOCTYPE html>

	<link rel="stylesheet" href="../css_dir/index.css">
    <title>Full Story</title>

Lucy

I finally did it! I left Hugh. The man who was supposed to love and protect me, but whose fists left bruises and words left scars. Instead of meeting a bright future, I was filled with fear. I knew that if Hugh found me, he would make me pay. Every night, I stared at the hotel door waiting for his pounding fists. My shadow, once my faithful companion, made my heart race. Safe House was my rescuer. The staff and counselors helped me to feel safe again. I know now that Hugh will never be able to reach me again.

Help Lucy

Housing

Legal Advice

Cell phone


text:
const getBaseType = require('./_getBaseType')

/**
 *
 * @param {Object} value
 */
const isNumber = value => getBaseType('Number')(value)

module.exports = isNumber