text:
@interface FacebookAccount()
@property (retain) FBSession* session;
@property (retain) FBLoginButton* loginButton;
@property (copy) NSString* notificationString;
@end

@implementation FacebookAccount

@synthesize session;
@synthesize loginButton;
@synthesize notificationString;

- (void) dealloc {
  self.session = nil;
  self.loginButton = nil;
  self.notificationString = nil;

  [super dealloc];
}

setting_definition(FACEBOOK_ENABLED);

static FacebookAccount* account;

+ (void) initialize {
  if (self == [FacebookAccount class]) {
    account = [[FacebookAccount alloc] init];
  }
}

+ (FacebookAccount*) account {
  return account;
}

- (id) init {
  if ((self = [super init])) {
    self.notificationString = LocalizedString(@"Logging in to Facebook", nil);
  }

  return self;
}

- (void) login {
  self.session = nil;
  [FBSession setSession:nil];

  if (self.enabled) {
    //[NotificationCenter addNotification:notificationString];
    //self.isLoggingIn = YES;
    self.session =
    [FBSession sessionForApplication:[FacebookAuthentication apiKey]
                              secret:[FacebookAuthentication applicationSecret]
                            delegate:self];
    [FBSession setSession:session];

    self.loginButton = [[[FBLoginButton alloc] init] autorelease];
    //loginButton.style = FBLoginButtonStyleWide;
    loginButton.session = session;
  }
}

- (BOOL) enabled {
  return [[NSUserDefaults standardUserDefaults] boolForKey:FACEBOOK_ENABLED];
}

- (void) setEnabled:(BOOL) value {
  [[NSUserDefaults standardUserDefaults] setBool:value forKey:FACEBOOK_ENABLED];
  [[NSUserDefaults standardUserDefaults] synchronize];

  if (!value) {
    [session cancelLogin];
    [session logout];
  }

  [self login];
}

- (void)session:(FBSession*)session didLogin:(FBUID)uid {
}

- (BOOL) isLoggedIn {
  return session.isConnected;
}

@end


text:
    <ng-form name="listPickerForm">
        <input type="hidden" name="validation" ng-model="model.value" />

    </ng-form>

            <input type="text"
                   placeholder="typeahead"
                   autocomplete="off"
                   ng-model="typeahead"
                   ng-class="{'no-match': noMatch}"
                   nu-cursor-up="cursorUp()"
                   nu-cursor-down="cursorDown()"
                   nu-enter-key="enterKey()" />

        <ng-include src="'/App_Plugins/nuPickers/Shared/ListPicker/ListPickerPartial.html'" />

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace PTS\Router\Point;

class ControllerDynamicAction extends AbstractPoint implements IPoint
{
    /** @var string */
    protected $controller;

    /**
     * @param array $params
     * @throws \BadMethodCallException
     */
    public function __construct(array $params)
    {
        if (!array_key_exists('controller', $params)) {
            throw new \BadMethodCallException('Bad params');
        }

        parent::__construct($params);
    }

    /**
     * @param array $handlerArgs
     * @return array|callable
     * @throws \BadMethodCallException
     */
    public function getCall(array $handlerArgs = [])
    {
        $this->checkController($this->controller);

        $arguments = $this->getArguments();
        $action = 'index';

        if (isset($arguments['action'])) {
            $action = $arguments['action'];
            unset($arguments['action']);
        }

        $this->setArguments($arguments);

        $controller = new $this->controller($handlerArgs);
        $this->checkAction($controller, $action);

        return [$controller, $action];
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Azure.Core.TestFramework;
using NUnit.Framework;
using System;

namespace Azure.AI.TextAnalytics.Samples
{
    [LiveOnly]
    public partial class TextAnalyticsSamples
    {
        [Test]
        public void ExtractKeyPhrasesWithWarnings()
        {
            string endpoint = TestEnvironment.Endpoint;
            string apiKey = TestEnvironment.ApiKey;

            var client = new TextAnalyticsClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

            string document = "Anthony runs his own personal training business so thisisaverylongtokenwhichwillbetruncatedtoshowushowwarningsareemittedintheapi";

            KeyPhraseCollection keyPhrases = client.ExtractKeyPhrases(document);

            if (keyPhrases.Warnings.Count > 0)
            {
                Console.WriteLine("**Warnings:**");
                foreach (TextAnalyticsWarning warning in keyPhrases.Warnings)
                {
                    Console.WriteLine($"    Warning: Code: {warning.WarningCode}, Message: {warning.Message}");
                }
            }

            Console.WriteLine($"Extracted {keyPhrases.Count} key phrases:");
            foreach (string keyPhrase in keyPhrases)
            {
                Console.WriteLine(keyPhrase);
            }
        }
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('voteapp', '0002_auto_20170308_1611'),
    ]

    operations = [
        migrations.CreateModel(
            name='Ballot',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('ballot_title', models.CharField(max_length=500)),
                ('ballot_short_desc', models.CharField(max_length=500)),
                ('ballot_instruction', models.CharField(max_length=500)),
                ('type', models.CharField(default=None, max_length=200)),
            ],
        ),
        migrations.CreateModel(
            name='Election',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=200)),
                ('vote_deadline', models.DateTimeField(verbose_name='vote_deadline')),
            ],
        ),
        migrations.CreateModel(
            name='LogHistory',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('time_stamp', models.DateTimeField()),
            ],
        ),
        migrations.CreateModel(
            name='Option',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('option_text', models.CharField(max_length=200)),
                ('votes', models.IntegerField(default=0)),
            ],
        ),
        migrations.RemoveField(
            model_name='choice',
            name='question',
        ),
        migrations.CreateModel(
            name='CustomOption',
            fields=[
                ('option_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='voteapp.Option')),
                ('input_text', models.CharField(max_length=200)),
            ],
            bases=('voteapp.option',),
        ),
        migrations.DeleteModel(
            name='Choice',
        ),
        migrations.DeleteModel(
            name='Question',
        ),
        migrations.AddField(
            model_name='option',
            name='ballot_item',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='voteapp.Ballot'),
        ),
        migrations.AddField(
            model_name='loghistory',
            name='election',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='voteapp.Option'),
        ),
        migrations.AddField(
            model_name='loghistory',
            name='voter',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='voteapp.Voter'),
        ),
        migrations.AddField(
            model_name='ballot',
            name='election',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='voteapp.Election'),
        ),
        migrations.AddField(
            model_name='voter',
            name='election',
            field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to='voteapp.Election'),
            preserve_default=False,
        ),
    ]


text:
var test = require("tape")

var frontendFramework = require("../index")

test("frontendFramework is a function", function (assert) {
    assert.equal(typeof frontendFramework, "function")
    assert.end()
})


text:
@import SKMopidy;

@interface SKMopidyPlayerViewController : UIViewController

@property(nonatomic, strong, nullable) SKMopidyRef *ref;

@end


text:
// ****************************************************************
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using NUnit.UiException.CodeFormatters;
using System.Diagnostics;

/// This control could have been replaced by a standard RichTextBox control, but
/// it turned out that RichTextBox:
///     - was hard to configure
///     - was hard to set the viewport
///     - doesn't use double buffer optimization
///     - scrolls text one line at a time without be configurable.
///
/// CodeBox has been written to address these specific issues in order to display
/// C# source code where exceptions occured.

namespace NUnit.UiException.Controls
{
    /// <summary>
    /// A control that implements ICodeView.
    /// </summary>
    public class CodeBox : UserControl, ICodeView
    {
        protected CodeRenderingContext _workingContext;
        protected FormattedCode _formattedCode;

        private IFormatterCatalog _formatter;
        private ICodeRenderer _renderer;
        private string _language;

        private bool _showCurrentLine;
        private int _currentLine;

        public CodeBox() :
            this(new GeneralCodeFormatter(), new DefaultCodeRenderer()) { }

        #region ICodeView Members

        public override string Text
        {
            get { return (_formattedCode.Text); }
            set
            {
                if (value == null)
                    value = "";

                SizeF docSize;

                _formattedCode = _formatter.Format(value, _language);
                docSize = _renderer.GetDocumentSize(
                    _formattedCode, _workingContext.Graphics, _workingContext.Font);
                AutoScrollMinSize = new Size((int)docSize.Width, (int)docSize.Height);

                Invalidate();

                return;
            }
        }

        public string Language
        {
            get { return (_language); }
            set
            {
                if (value == null)
                    value = "";
                if (_language == value)
                    return;

                _language = value;
                Text = Text;
            }
        }

        public int CurrentLine
        {
            get { return (_currentLine); }
            set
            {
                float y = _renderer.LineIndexToYCoordinate(value,
                    _workingContext.Graphics, _workingContext.Font);

                y -= Height / 2;

                _currentLine = value;
                AutoScrollPosition = new Point(0, (int)y);

                Invalidate();
            }
        }

        public IFormatterCatalog Formatter
        {
            get { return (_formatter); }
        }

        #endregion

        /// <summary>
        /// Gets or sets a value telling whether or not displaying a special
        /// feature for the current line at drawing time.
        /// </summary>
        public bool ShowCurrentLine
        {
            get { return (_showCurrentLine); }
            set { _showCurrentLine = value; }
        }

        /// <summary>
        /// If ShowCurrentLine is set, this set the current line's background color.
        /// </summary>
        public Color CurrentLineBackColor
        {
            get { return (_workingContext.CurrentLineBackColor); }
            set {
                _workingContext.CurrentLineBackColor = value;
                Invalidate();
            }
        }

        /// <summary>
        /// If ShowCurrentLine is set, this set current line's foreground color.
        /// </summary>
        public Color CurrentLineForeColor
        {
            get { return (_workingContext.CurrentLineForeColor); }
            set {
                _workingContext.CurrentLineForeColor = value;
                Invalidate();
            }
        }

        protected CodeBox(IFormatterCatalog formatter, ICodeRenderer renderer)
        {
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            SetStyle(ControlStyles.UserPaint, true);
            DoubleBuffered = true;

            _formatter = formatter;
            _formattedCode = FormattedCode.Empty;

            _renderer = renderer;

            _currentLine = -1;
            _showCurrentLine = false;

            _language = "";

            this.Font = new Font(FontFamily.GenericMonospace, 8);
            this.BackColor = Color.White;

            createGraphics();
            AutoScroll = true;

            return;
        }

        protected override void OnMouseHover(EventArgs e)
        {
            base.OnMouseHover(e);
            Focus();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            Graphics backup;

            base.OnPaint(e);

            backup = _workingContext.Graphics;
            _workingContext.Graphics = e.Graphics;
            _workingContext.CurrentLine = (_showCurrentLine ? _currentLine : -1);

            _renderer.DrawToGraphics(_formattedCode, _workingContext,
                new Rectangle(-AutoScrollPosition.X, -AutoScrollPosition.Y, Width, Height));

            _workingContext.Graphics = backup;

            return;
        }

        protected override void OnFontChanged(EventArgs e)
        {
            base.OnFontChanged(e);

            if (_workingContext != null)
            {
                _workingContext.Font = Font;
                Text = Text;
            }

            return;
        }

        private void createGraphics()
        {
            Graphics gCurrent = CreateGraphics();
            Image img = new Bitmap(10, 10, gCurrent);
            Graphics gImg = Graphics.FromImage(img);

            gCurrent.Dispose();

            _workingContext = new CodeRenderingContext();
            _workingContext.Graphics = gImg;
            _workingContext.Font = Font;

            _workingContext.CurrentLine = -1;
            _workingContext.BackgroundColor = Color.White;
            _workingContext.CurrentLineBackColor = Color.Red;
            _workingContext.CurrentLineForeColor = Color.White;
            _workingContext.CodeColor = Color.Black;
            _workingContext.CommentColor = Color.Green;
            _workingContext.KeywordColor = Color.Blue;
            _workingContext.StringColor = Color.Red;

            return;
        }
    }
}


text:
shared "location" do
  it 'should create a file' do
    @file.create("A").should == @file
    @file.read.should == "A"
  end

  it 'should raise exception when the file exists already' do
    @file.create("A")
    should.raise(Location::ExistAlready) {@file.create("B")}
  end

  it 'should append data' do
    @file.create("A")
    @file.append("B")
    @file.read.should == "AB"
  end

  it "should not raise an exception when the file doesn't exist" do
    @file.should.not.exist
    @file.append("A")
    @file.read.should == "A"
  end

  it 'should read a file' do
    @file.create("A")
    @file.read.should == "A"
  end

  it 'should update a file' do
    @file.create("A")
    @file.read.should == "A"
    @file.update("B")
    @file.read.should == "B"
    @file.update("C")
    @file.read.should == "C"
  end

  it 'should delete a file' do
    should.not.raise {@file.delete}
    @file.should.not.exist
    should.not.raise {@file.delete}
  end

  it 'should link' do
    desc = Location[Temppath.create].tap {|x| x.create("A")}
    @file.link(desc)
    @file.read.should == "A"
  end

  it 'should move' do
    dest = Location[Temppath.create]
    @file.create("A")
    @file.move(dest)
    dest.read.should == "A"
    dest.path.ftype.should == "file"
    @file.should.not.exist
  end

  it 'should copy' do
    dest = Location[Temppath.create]
    @file.create("A")
    @file.copy(dest)
    dest.read.should == "A"
    @file.read.should == "A"
  end

  it 'should turn' do
    dest = Location[Temppath.create]
    @file.create("A")
    @file.turn(dest)
    dest.read.should == "A"
    @file.read.should == "A"
  end

  it 'should get mtime information' do
    @file.create("A")
    @file.mtime.should.kind_of Time
  end

  it 'should get size information' do
    @file.create("A")
    @file.size.should == 1
  end

  it 'should get entries' do
    @dir.entries.size.should == 4
    @dir.entries.should.include(@dir + "A")
    @dir.entries.should.include(@dir + "B")
    @dir.entries.should.include(@dir + "C")
    @dir.entries.should.include(@dir + "D")
    @dir.entries.should.not.include(@dir + ".")
    @dir.entries.should.not.include(@dir + "..")
    @dir.entries.should.not.include(@dir + "X")
    @dir.entries.should.not.include(@dir + "Y")
    @dir.entries.should.not.include(@dir + "Z")
    (@dir + "D").entries.size.should == 3
    (@dir + "D").entries.should.include(@dir + "D" + "X")
    (@dir + "D").entries.should.include(@dir + "D" + "Y")
    (@dir + "D").entries.should.include(@dir + "D" + "Z")
  end

  it 'should get file entries' do
    @dir.file_entries.size.should == 3
    @dir.file_entries.should.include(@dir + "A")
    @dir.file_entries.should.include(@dir + "B")
    @dir.file_entries.should.include(@dir + "C")
    @dir.file_entries.should.not.include(@dir + "D")
    (@dir + "D").file_entries.size.should == 3
    (@dir + "D").file_entries.should.include(@dir + "D" + "X")
    (@dir + "D").file_entries.should.include(@dir + "D" + "Y")
    (@dir + "D").file_entries.should.include(@dir + "D" + "Z")
  end

  it 'should get directory entries' do
    @dir.directory_entries.size.should == 1
    @dir.directory_entries.should.not.include(@dir + "A")
    @dir.directory_entries.should.not.include(@dir + "B")
    @dir.directory_entries.should.not.include(@dir + "C")
    @dir.directory_entries.should.include(@dir + "D")
    (@dir + "D").directory_entries.size.should == 0
    (@dir + "D").directory_entries.should.not.include(@dir + "D" + "X")
    (@dir + "D").directory_entries.should.not.include(@dir + "D" + "Y")
    (@dir + "D").directory_entries.should.not.include(@dir + "D" + "Z")
  end

  it "should get local location" do
    @file.create("A")
    local = @file.local
    local.should.local
    local.should.exist
    local.should.file
  end
end


text:
<?php

namespace linchpinstudios\blog\models;

use Yii;
use common\models\User;
use yii\behaviors\TimestampBehavior;
use yii\behaviors\AttributeBehavior;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
use linchpinstudios\blog\models\BlogTermRelationships;

/**
 * This is the model class for table "blog_posts".
 *
 * @property integer $id
 * @property integer $user_id
 * @property integer $comments
 * @property string $title
 * @property string $body
 * @property string $thumbnail
 * @property string $excerpt
 * @property string $status
 * @property string $slug
 * @property string $date
 * @property string $date_gmt
 * @property string $modified
 * @property string $modified_gmt
 *
 * @property BlogComments[] $blogComments
 * @property BlogPostTags[] $blogPostTags
 * @property User $author
 * @property BlogCategories $category
 * @property BlogMeta[] $blogMetas
 * @property User $user
 */
class BlogPosts extends \yii\db\ActiveRecord
{

    public function behaviors()
    {
        return [

            'modified' => [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => 'modified',
                    ActiveRecord::EVENT_BEFORE_UPDATE => 'modified',
                ],
                'value' => function() {
                    return date('Y-m-d H:i:s');
                },
            ],
            'modifiedGMT' => [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => 'modified_gmt',
                    ActiveRecord::EVENT_BEFORE_UPDATE => 'modified_gmt',
                ],
                'value' => function() {
                    return gmdate('Y-m-d H:i:s');
                },
            ],
            'date' => [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => 'date',
                    ActiveRecord::EVENT_BEFORE_UPDATE => 'date',
                ],
                'value' => function() {
                    return (empty($this->date) ? date('Y-m-d H:i:s') : date('Y-m-d H:i:s',strtotime($this->date)));
                },
            ],
            'dateGMT' => [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => 'date_gmt',
                    ActiveRecord::EVENT_BEFORE_UPDATE => 'date_gmt',
                ],
                'value' => function() {
                    return (empty($this->date) ? gmdate('Y-m-d H:i:s') : gmdate('Y-m-d H:i:s',strtotime($this->date)));
                },
            ],
            'slug' => [
                'class' => AttributeBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => 'slug',
                    ActiveRecord::EVENT_BEFORE_UPDATE => 'slug',
                ],
                'value' => function() {
                    return (empty($this->slug) ? $this->genSlug($this->title) : $this->genSlug($this->slug));
                },
            ],
        ];
    }

    public static function genSlug($str, $replace=array(), $delimiter='-'){
    	if( !empty($replace) ) {
    		$str = str_replace((array)$replace, ' ', $str);
    	}

    	$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
    	$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
    	$clean = strtolower(trim($clean, '-'));
    	$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);

    	return $clean;
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%blog_posts}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['user_id', 'comments', 'thumbnail'], 'integer'],
            [['body', 'excerpt'], 'string'],
            [['date', 'date_gmt', 'modified', 'modified_gmt'], 'safe'],
            [['title'], 'string', 'max' => 555],
            [['status'], 'string', 'max' => 20],
            [['slug'], 'string', 'max' => 45]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'user_id' => 'User ID',
            'comments' => 'Comments',
            'title' => 'Title',
            'body' => 'Body',
            'thumbnail' => 'Thumbnail',
            'excerpt' => 'Excerpt',
            'status' => 'Status',
            'slug' => 'Slug',
            'date' => 'Date',
            'date_gmt' => 'Date Gmt',
            'modified' => 'Modified',
            'modified_gmt' => 'Modified Gmt',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getBlogComments()
    {
        return $this->hasMany(BlogComments::className(), ['post_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getBlogPostTags()
    {
        return $this->hasMany(BlogPostTags::className(), ['postId' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAuthor()
    {
        return $this->hasOne(User::className(), ['id' => 'authorId']);
    }

    public function getAuthorList()
    {
        $model = User::find()->asArray()->all();
        return ArrayHelper::map($model, 'id', 'username');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getTerms()
    {
        return $this->hasMany(BlogTermRelationships::className(), ['post_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getBlogMetas()
    {
        return $this->hasMany(BlogMeta::className(), ['post_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }
}


text:
package org.apache.camel.component.rabbitmq;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class RabbitMQProducerIntTest extends CamelTestSupport {
    private static final String EXCHANGE = "ex1";
    private static final String ROUTE = "route1";
    private static final String BASIC_URI_FORMAT = "rabbitmq:localhost:5672/%s?routingKey=%s&username=cameltest&password=cameltest&skipQueueDeclare=true";
    private static final String BASIC_URI = String.format(BASIC_URI_FORMAT, EXCHANGE, ROUTE);
    private static final String PUBLISHER_ACKNOWLEDGES_URI = BASIC_URI + "&mandatory=true&publisherAcknowledgements=true";
    private static final String PUBLISHER_ACKNOWLEDGES_BAD_ROUTE_URI = String.format(BASIC_URI_FORMAT, EXCHANGE, "route2") + "&publisherAcknowledgements=true";

    @Produce(uri = "direct:start")
    protected ProducerTemplate template;

    @Produce(uri = "direct:start-with-confirms")
    protected ProducerTemplate templateWithConfirms;

    @Produce(uri = "direct:start-with-confirms-bad-route")
    protected ProducerTemplate templateWithConfirmsAndBadRoute;

    private Connection connection;
    private Channel channel;

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        context().setTracing(true);
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start").to(BASIC_URI);
                from("direct:start-with-confirms").to(PUBLISHER_ACKNOWLEDGES_URI);
                from("direct:start-with-confirms-bad-route").to(PUBLISHER_ACKNOWLEDGES_BAD_ROUTE_URI);
            }
        };
    }

    @Before
    public void setUpRabbitMQ() throws Exception {
        connection = createTestConnection();
        channel = connection.createChannel();
        channel.queueDeclare("sammyq", false, false, true, null);
        channel.queueBind("sammyq", EXCHANGE, ROUTE);
    }

    @After
    public void tearDownRabbitMQ() throws Exception {
        channel.abort();
        connection.abort();
    }

    @Test
    public void producedMessageIsReceived() throws InterruptedException, IOException, TimeoutException {
        final List<String> received = new ArrayList<>();
        channel.basicConsume("sammyq", true, new ArrayPopulatingConsumer(received));

        template.sendBodyAndHeader("new message", RabbitMQConstants.EXCHANGE_NAME, "ex1");

        assertThatBodiesReceivedIn(received, "new message");
    }

    private void assertThatBodiesReceivedIn(final List<String> received, final String... expected) throws InterruptedException {
        Thread.sleep(500);

        assertListSize(received, expected.length);
        for (String body : expected) {
            assertEquals(body, received.get(0));
        }
    }

    @Test
    public void producedMessageIsReceivedWhenPublisherAcknowledgementsAreEnabled() throws InterruptedException, IOException, TimeoutException {
        final List<String> received = new ArrayList<>();
        channel.basicConsume("sammyq", true, new ArrayPopulatingConsumer(received));

        templateWithConfirms.sendBodyAndHeader("publisher ack message", RabbitMQConstants.EXCHANGE_NAME, "ex1");

        assertThatBodiesReceivedIn(received, "publisher ack message");
    }

    @Test
    public void producedMessageIsReceivedWhenPublisherAcknowledgementsAreEnabledAndBadRoutingKeyIsUsed() throws InterruptedException, IOException, TimeoutException {
        final List<String> received = new ArrayList<>();
        channel.basicConsume("sammyq", true, new ArrayPopulatingConsumer(received));

        templateWithConfirmsAndBadRoute.sendBody("publisher ack message");

        assertThatBodiesReceivedIn(received);
    }

    private Connection createTestConnection() throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672);
        factory.setUsername("cameltest");
        factory.setPassword("cameltest");
        factory.setVirtualHost("/");
        return factory.newConnection();
    }

    private class ArrayPopulatingConsumer extends DefaultConsumer {
        private final List<String> received;

        public ArrayPopulatingConsumer(final List<String> received) {
            super(RabbitMQProducerIntTest.this.channel);
            this.received = received;
        }

        @Override
        public void handleDelivery(String consumerTag,
                                   Envelope envelope,
                                   AMQP.BasicProperties properties,
                                   byte[] body) throws IOException {
            received.add(new String(body));
        }
    }
}


text:
/**
 * Module dependencies.
 */
var Q = require('q');
var path = require("path");
var fs = require("fs");
var FS = require('q-io/fs');
var shell = require('shelljs');
var os = require('os');
var downloadFile = require('../utils/downloadFile');
var getUserHome = require('../utils/getUserHome');
var unzip = require('../utils/unzip');
var setupEnv_win = require('../utils/setupEnv-android-win');
var setupEnv_mac = require('../utils/setupEnv-android-mac');
var spawn = require('cross-spawn-async');
var spinner = require('simple-spinner');
var cordova_lib = require('../lib/cordova').lib;
var events = cordova_lib.events;
var cordova = cordova_lib.cordova;
const skinName = "Nexus-7";

module.exports.install = install;
module.exports.post_add = post_add;

function install() {
    return installSdk()
        .then( () => {
            return updateSdk();
        })
        .then( () => {
            return setupEnv();
        })
        .then( () => {
            return createAvd();
        })
        .then( () => {
            return installHAXM();
        });
}

function installSdk() {
    var deferred = Q.defer();
    var sdkDownloadUrl = null;
    var sdkInstallPath = path.join(getUserHome(), 'platforms/android/sdk');
    var tempSdkDownloadFilePath = path.join(os.tmpdir(), 'android_sdk.zip');
    var tempSdkUnzipRoot = path.join(os.tmpdir(), 'platform');
    var tempSdkUnzipPath = null;

    // It's ok to hard code specific SDK download link since we will attempt to update
    // to the latest SDK each time user runs "aemm platform install android".
    //
    // We just need to install an initial version to begin with. Android community keeps
    // download links for all prior version of SDKs since it's introduction at:
    // http://developer.android.com/tools/sdk/tools-notes.html
    if (process.platform == 'win32') {
        sdkDownloadUrl = 'http://dl.google.com/android/android-sdk_r24.4.1-windows.zip';
        tempSdkUnzipPath = path.join(tempSdkUnzipRoot, 'android-sdk-windows');
    } else if (process.platform == 'darwin') {
        sdkDownloadUrl = 'http://dl.google.com/android/android-sdk_r24.4.1-macosx.zip';
        tempSdkUnzipPath = path.join(tempSdkUnzipRoot, 'android-sdk-macosx');
    } else {
        events.emit("log", "Unsupported OS: %s", process.platform);
        return;
    }

    // Check whether SDK is installed already
    fs.access(sdkInstallPath, fs.F_OK, function(err) {
        if (!err) {
            deferred.resolve();
        } else {
            spinner.start();

            FS.makeTree(sdkInstallPath)
            .then( () => {
                return downloadFile(sdkDownloadUrl, tempSdkDownloadFilePath);
            })
            .then( () => {
                return unzip(tempSdkDownloadFilePath, tempSdkUnzipRoot);
            })
            .then( () => {
                return FS.copyTree(tempSdkUnzipPath, sdkInstallPath);
            })
            .then ( () => {
                return FS.removeTree(tempSdkUnzipRoot)
                    .catch( (err) => false ); // We don't care if it does not exist when we try to delete it
            })
            .then( () => {
                spinner.stop();

                events.emit("log", "Android SDK is installed successfully.");
                deferred.resolve();
            });
        }
    });

    return deferred.promise;
}

function updateSdk() {
    var deferred = Q.defer();
    var command = null;
    var script = null;

    if (process.platform == 'win32') {
        command = "powershell";
        script = path.join(getUserHome(), 'platforms/android/sdk/tools/android.bat');
    } else if (process.platform == 'darwin') {
        command = "sh";
        script = path.join(getUserHome(), 'platforms/android/sdk/tools/android');
    } else {
        events.emit("log", "Platform not supported: " + process.platform);
        return;
    }

    var proc = spawn(command, [script, '--silent', 'update', 'sdk', '--all',
        '--no-ui', '--filter', 'build-tools-23.0.2,platform-tool,tool,android-23,sys-img-x86_64-android-23,' +
        'extra-android-m2repository,extra-android-support,extra-google-m2repository,' +
        'extra-intel-Hardware_Accelerated_Execution_Manager'], { stdio: 'inherit' });

    proc.on("error", function (error) {
        deferred.reject(new Error("Installing Android platform encountered error " + error.message));
    });
    proc.on("exit", function(code) {
        if (code !== 0) {
            deferred.reject(new Error("Installing Android platform exited with code " + code));
        } else {
            events.emit("log", "Android SDK is updated successfully.");
            deferred.resolve();
        }
    });

    return deferred.promise;
}

function setupEnv() {
    if (process.platform == 'win32') {
        return setupEnv_win();
    } else if (process.platform == 'darwin') {
        return setupEnv_mac();
    } else {
        events.emit("log", "Unsupported OS: %s", process.platform);
        return;
    }
}

function installHAXM() {
    var deferred = Q.defer();
    var command = null;

    if (process.platform == 'win32') {
        command = path.join(getUserHome(), 'platforms/android/sdk/extras/intel/Hardware_Accelerated_Execution_Manager/silent_install.bat');
    } else if (process.platform == 'darwin') {
        command = 'sudo ' + path.join(getUserHome(), 'platforms/android/sdk/extras/intel/Hardware_Accelerated_Execution_Manager/silent_install.sh');
    } else {
        events.emit("log", "Unsupported OS: %s", process.platform);
        return;
    }

    spinner.start();
    var workingDir = path.join(getUserHome(), 'platforms/android/sdk/extras/intel/Hardware_Accelerated_Execution_Manager');
    shell.cd(workingDir);
    shell.exec(command, {
        silent: false
    }, function (code, output) {
        spinner.stop();
        if (code === 0) {
            deferred.resolve();
        } else {
            deferred.reject(new Error("Installing Intel HAXM failed."));
        }
    });

    return deferred.promise;
}

function createAvd() {
    var skinFrom = path.join(__dirname, '..', 'platforms/android/skins', skinName);
    var skinTo = path.join(getUserHome(), 'platforms/android/sdk/platforms/android-23/skins', skinName);

    return FS.makeTree(skinTo)
        .then( () => {
            return FS.copyTree(skinFrom, skinTo);
        })
        .then( () => {
            var deferred = Q.defer();

            var command =  null;
            if (process.platform == 'win32') {
                command = 'echo "no" | ' + path.join(getUserHome(), 'platforms/android/sdk/tools/android.bat') + ' create avd --force -n AEMM_Tablet --device "Nexus 7" -t "android-23" --abi default/x86_64 --skin "Nexus-7" --sdcard 1024M';
            } else if (process.platform == 'darwin') {
                command = 'echo "no" | ' + path.join(getUserHome(), 'platforms/android/sdk/tools/android') + ' create avd --force -n AEMM_Tablet --device "Nexus 7" -t "android-23" --abi default/x86_64 --skin "Nexus-7" --sdcard 1024M';
            } else {
                deferred.reject(new Error("Platform not supported: " + process.platform));
                return;
            }

            shell.exec(command, {
                silent: false
            }, function (code, output) {
                if (code === 0) {
                    events.emit("log", "AVD is created successfully.");
                    deferred.resolve();
                } else {
                    deferred.reject(new Error("Creating AVD failed"));
                }
            });

            return deferred.promise;
        });
}

function post_add()
{
    return Q.fcall( () => {
        // add aemm-plugin-navto by default to be consistent with our viewer app behavior.
        var targets = ["aemm-plugin-navto"];
        return cordova.raw.plugin("add", targets);
    })
    .then(() => {
        events.emit("results", "Finished adding Android platform.");
    });
}


text:
/* @flow */
import description from './description';
import propDocs from './propDocs';
import examples from './examples';

import type { ComponentDocType } from '../../../pages/ComponentDoc/types';

const componentDoc: ComponentDocType = {
  title: 'DialogHeader',
  slug: 'dialog-header',
  description,
  examples,
  propDocs
};

export default componentDoc;


text:
package org.apache.cassandra.db.filter;

import java.io.IOException;
import java.nio.ByteBuffer;

import org.apache.cassandra.db.*;
import org.apache.cassandra.db.rows.*;
import org.apache.cassandra.db.partitions.*;
import org.apache.cassandra.db.transform.BasePartitions;
import org.apache.cassandra.db.transform.BaseRows;
import org.apache.cassandra.db.transform.StoppingTransformation;
import org.apache.cassandra.db.transform.Transformation;
import org.apache.cassandra.io.util.DataInputPlus;
import org.apache.cassandra.io.util.DataOutputPlus;
import org.apache.cassandra.utils.ByteBufferUtil;

/**
 * Object in charge of tracking if we have fetch enough data for a given query.
 *
 * The reason this is not just a simple integer is that Thrift and CQL3 count
 * stuffs in different ways. This is what abstract those differences.
 */
public abstract class DataLimits
{
    public static final Serializer serializer = new Serializer();

    public static final int NO_LIMIT = Integer.MAX_VALUE;

    public static final DataLimits NONE = new CQLLimits(NO_LIMIT)
    {
        @Override
        public boolean hasEnoughLiveData(CachedPartition cached, int nowInSec)
        {
            return false;
        }

        @Override
        public UnfilteredPartitionIterator filter(UnfilteredPartitionIterator iter, int nowInSec)
        {
            return iter;
        }

        @Override
        public UnfilteredRowIterator filter(UnfilteredRowIterator iter, int nowInSec)
        {
            return iter;
        }
    };

    // We currently deal with distinct queries by querying full partitions but limiting the result at 1 row per
    // partition (see SelectStatement.makeFilter). So an "unbounded" distinct is still actually doing some filtering.
    public static final DataLimits DISTINCT_NONE = new CQLLimits(NO_LIMIT, 1, true);

    public enum Kind { CQL_LIMIT, CQL_PAGING_LIMIT, THRIFT_LIMIT, SUPER_COLUMN_COUNTING_LIMIT }

    public static DataLimits cqlLimits(int cqlRowLimit)
    {
        return new CQLLimits(cqlRowLimit);
    }

    public static DataLimits cqlLimits(int cqlRowLimit, int perPartitionLimit)
    {
        return new CQLLimits(cqlRowLimit, perPartitionLimit);
    }

    public static DataLimits distinctLimits(int cqlRowLimit)
    {
        return CQLLimits.distinct(cqlRowLimit);
    }

    public static DataLimits thriftLimits(int partitionLimit, int cellPerPartitionLimit)
    {
        return new ThriftLimits(partitionLimit, cellPerPartitionLimit);
    }

    public static DataLimits superColumnCountingLimits(int partitionLimit, int cellPerPartitionLimit)
    {
        return new SuperColumnCountingLimits(partitionLimit, cellPerPartitionLimit);
    }

    public abstract Kind kind();

    public abstract boolean isUnlimited();

    public abstract DataLimits forPaging(int pageSize);
    public abstract DataLimits forPaging(int pageSize, ByteBuffer lastReturnedKey, int lastReturnedKeyRemaining);

    public abstract DataLimits forShortReadRetry(int toFetch);

    public abstract boolean hasEnoughLiveData(CachedPartition cached, int nowInSec);

    /**
     * Returns a new {@code Counter} for this limits.
     *
     * @param nowInSec the current time in second (to decide what is expired or not).
     * @param assumeLiveData if true, the counter will assume that every row passed is live and won't
     * thus check for liveness, otherwise it will. This should be {@code true} when used on a
     * {@code RowIterator} (since it only returns live rows), false otherwise.
     * @return a new {@code Counter} for this limits.
     */
    public abstract Counter newCounter(int nowInSec, boolean assumeLiveData);

    /**
     * The max number of results this limits enforces.
     *

     * Note that the actual definition of "results" depends a bit: for CQL, it's always rows, but for
     * thrift, it means cells.
     *
     * @return the maximum number of results this limits enforces.
     */
    public abstract int count();

    public abstract int perPartitionCount();

    public UnfilteredPartitionIterator filter(UnfilteredPartitionIterator iter, int nowInSec)
    {
        return this.newCounter(nowInSec, false).applyTo(iter);
    }

    public UnfilteredRowIterator filter(UnfilteredRowIterator iter, int nowInSec)
    {
        return this.newCounter(nowInSec, false).applyTo(iter);
    }

    public PartitionIterator filter(PartitionIterator iter, int nowInSec)
    {
        return this.newCounter(nowInSec, true).applyTo(iter);
    }

    /**
     * Estimate the number of results (the definition of "results" will be rows for CQL queries
     * and partitions for thrift ones) that a full scan of the provided cfs would yield.
     */
    public abstract float estimateTotalResults(ColumnFamilyStore cfs);

    public static abstract class Counter extends StoppingTransformation<BaseRowIterator<?>>
    {
        // false means we do not propagate our stop signals onto the iterator, we only count
        private boolean enforceLimits = true;

        public Counter onlyCount()
        {
            this.enforceLimits = false;
            return this;
        }

        public PartitionIterator applyTo(PartitionIterator partitions)
        {
            return Transformation.apply(partitions, this);
        }

        public UnfilteredPartitionIterator applyTo(UnfilteredPartitionIterator partitions)
        {
            return Transformation.apply(partitions, this);
        }

        public UnfilteredRowIterator applyTo(UnfilteredRowIterator partition)
        {
            return (UnfilteredRowIterator) applyToPartition(partition);
        }

        public RowIterator applyTo(RowIterator partition)
        {
            return (RowIterator) applyToPartition(partition);
        }

        /**
         * The number of results counted.
         *

         * Note that the definition of "results" should be the same that for {@link #count}.
         *
         * @return the number of results counted.
         */
        public abstract int counted();
        public abstract int countedInCurrentPartition();

        public abstract boolean isDone();
        public abstract boolean isDoneForPartition();

        @Override
        protected BaseRowIterator<?> applyToPartition(BaseRowIterator<?> partition)
        {
            return partition instanceof UnfilteredRowIterator ? Transformation.apply((UnfilteredRowIterator) partition, this)
                                                              : Transformation.apply((RowIterator) partition, this);
        }

        // called before we process a given partition
        protected abstract void applyToPartition(DecoratedKey partitionKey, Row staticRow);

        @Override
        protected void attachTo(BasePartitions partitions)
        {
            if (enforceLimits)
                super.attachTo(partitions);
            if (isDone())
                stop();
        }

        @Override
        protected void attachTo(BaseRows rows)
        {
            if (enforceLimits)
                super.attachTo(rows);
            applyToPartition(rows.partitionKey(), rows.staticRow());
            if (isDoneForPartition())
                stopInPartition();
        }
    }

    /**
     * Limits used by CQL; this counts rows.
     */
    private static class CQLLimits extends DataLimits
    {
        protected final int rowLimit;
        protected final int perPartitionLimit;

        // Whether the query is a distinct query or not. This is currently not used by the code but prior experience
        // shows that keeping the information around is wise and might be useful in the future.
        protected final boolean isDistinct;

        private CQLLimits(int rowLimit)
        {
            this(rowLimit, NO_LIMIT);
        }

        private CQLLimits(int rowLimit, int perPartitionLimit)
        {
            this(rowLimit, perPartitionLimit, false);
        }

        private CQLLimits(int rowLimit, int perPartitionLimit, boolean isDistinct)
        {
            this.rowLimit = rowLimit;
            this.perPartitionLimit = perPartitionLimit;
            this.isDistinct = isDistinct;
        }

        private static CQLLimits distinct(int rowLimit)
        {
            return new CQLLimits(rowLimit, 1, true);
        }

        public Kind kind()
        {
            return Kind.CQL_LIMIT;
        }

        public boolean isUnlimited()
        {
            return rowLimit == NO_LIMIT && perPartitionLimit == NO_LIMIT;
        }

        public DataLimits forPaging(int pageSize)
        {
            return new CQLLimits(pageSize, perPartitionLimit);
        }

        public DataLimits forPaging(int pageSize, ByteBuffer lastReturnedKey, int lastReturnedKeyRemaining)
        {
            return new CQLPagingLimits(pageSize, perPartitionLimit, isDistinct, lastReturnedKey, lastReturnedKeyRemaining);
        }

        public DataLimits forShortReadRetry(int toFetch)
        {
            // When we do a short read retry, we're only ever querying the single partition on which we have a short read. So
            // we use toFetch as the row limit and use no perPartitionLimit (it would be equivalent in practice to use toFetch
            // for both argument or just for perPartitionLimit with no limit on rowLimit).
            return new CQLLimits(toFetch, NO_LIMIT, isDistinct);
        }

        public boolean hasEnoughLiveData(CachedPartition cached, int nowInSec)
        {
            // We want the number of row that are currently live. Getting that precise number forces
            // us to iterate the cached partition in general, but we can avoid that if:
            //   - The number of rows with at least one non-expiring cell is greater than what we ask,
            //     in which case we know we have enough live.
            //   - The number of rows is less than requested, in which case we  know we won't have enough.
            if (cached.rowsWithNonExpiringCells() >= rowLimit)
                return true;

            if (cached.rowCount() < rowLimit)
                return false;

            // Otherwise, we need to re-count

            DataLimits.Counter counter = newCounter(nowInSec, false);
            try (UnfilteredRowIterator cacheIter = cached.unfilteredIterator(ColumnFilter.selection(cached.columns()), Slices.ALL, false);
                 UnfilteredRowIterator iter = counter.applyTo(cacheIter))
            {
                // Consume the iterator until we've counted enough
                while (iter.hasNext())
                    iter.next();
                return counter.isDone();
            }
        }

        public Counter newCounter(int nowInSec, boolean assumeLiveData)
        {
            return new CQLCounter(nowInSec, assumeLiveData);
        }

        public int count()
        {
            return rowLimit;
        }

        public int perPartitionCount()
        {
            return perPartitionLimit;
        }

        public float estimateTotalResults(ColumnFamilyStore cfs)
        {
            // TODO: we should start storing stats on the number of rows (instead of the number of cells, which
            // is what getMeanColumns returns)
            float rowsPerPartition = ((float) cfs.getMeanColumns()) / cfs.metadata.partitionColumns().regulars.size();
            return rowsPerPartition * (cfs.estimateKeys());
        }

        protected class CQLCounter extends Counter
        {
            protected final int nowInSec;
            protected final boolean assumeLiveData;

            protected int rowCounted;
            protected int rowInCurrentPartition;

            protected boolean hasLiveStaticRow;

            public CQLCounter(int nowInSec, boolean assumeLiveData)
            {
                this.nowInSec = nowInSec;
                this.assumeLiveData = assumeLiveData;
            }

            @Override
            public void applyToPartition(DecoratedKey partitionKey, Row staticRow)
            {
                rowInCurrentPartition = 0;
                if (!staticRow.isEmpty() && (assumeLiveData || staticRow.hasLiveData(nowInSec)))
                    hasLiveStaticRow = true;
            }

            @Override
            public Row applyToRow(Row row)
            {
                if (assumeLiveData || row.hasLiveData(nowInSec))
                    incrementRowCount();
                return row;
            }

            @Override
            public void onPartitionClose()
            {
                // Normally, we don't count static rows as from a CQL point of view, it will be merge with other
                // rows in the partition. However, if we only have the static row, it will be returned as one row
                // so count it.
                if (hasLiveStaticRow && rowInCurrentPartition == 0)
                    incrementRowCount();
                super.onPartitionClose();
            }

            private void incrementRowCount()
            {
                if (++rowCounted >= rowLimit)
                    stop();
                if (++rowInCurrentPartition >= perPartitionLimit)
                    stopInPartition();
            }

            public int counted()
            {
                return rowCounted;
            }

            public int countedInCurrentPartition()
            {
                return rowInCurrentPartition;
            }

            public boolean isDone()
            {
                return rowCounted >= rowLimit;
            }

            public boolean isDoneForPartition()
            {
                return isDone() || rowInCurrentPartition >= perPartitionLimit;
            }
        }

        @Override
        public String toString()
        {
            StringBuilder sb = new StringBuilder();

            if (rowLimit != NO_LIMIT)
            {
                sb.append("LIMIT ").append(rowLimit);
                if (perPartitionLimit != NO_LIMIT)
                    sb.append(' ');
            }

            if (perPartitionLimit != NO_LIMIT)
                sb.append("PER PARTITION LIMIT ").append(perPartitionLimit);

            return sb.toString();
        }
    }

    private static class CQLPagingLimits extends CQLLimits
    {
        private final ByteBuffer lastReturnedKey;
        private final int lastReturnedKeyRemaining;

        public CQLPagingLimits(int rowLimit, int perPartitionLimit, boolean isDistinct, ByteBuffer lastReturnedKey, int lastReturnedKeyRemaining)
        {
            super(rowLimit, perPartitionLimit, isDistinct);
            this.lastReturnedKey = lastReturnedKey;
            this.lastReturnedKeyRemaining = lastReturnedKeyRemaining;
        }

        @Override
        public Kind kind()
        {
            return Kind.CQL_PAGING_LIMIT;
        }

        @Override
        public DataLimits forPaging(int pageSize)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public DataLimits forPaging(int pageSize, ByteBuffer lastReturnedKey, int lastReturnedKeyRemaining)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public Counter newCounter(int nowInSec, boolean assumeLiveData)
        {
            return new PagingAwareCounter(nowInSec, assumeLiveData);
        }

        private class PagingAwareCounter extends CQLCounter
        {
            private PagingAwareCounter(int nowInSec, boolean assumeLiveData)
            {
                super(nowInSec, assumeLiveData);
            }

            @Override
            public void applyToPartition(DecoratedKey partitionKey, Row staticRow)
            {
                if (partitionKey.getKey().equals(lastReturnedKey))
                {
                    rowInCurrentPartition = perPartitionLimit - lastReturnedKeyRemaining;
                    // lastReturnedKey is the last key for which we're returned rows in the first page.
                    // So, since we know we have returned rows, we know we have accounted for the static row
                    // if any already, so force hasLiveStaticRow to false so we make sure to not count it
                    // once more.
                    hasLiveStaticRow = false;
                }
                else
                {
                    super.applyToPartition(partitionKey, staticRow);
                }
            }
        }
    }

    /**
     * Limits used by thrift; this count partition and cells.
     */
    private static class ThriftLimits extends DataLimits
    {
        protected final int partitionLimit;
        protected final int cellPerPartitionLimit;

        private ThriftLimits(int partitionLimit, int cellPerPartitionLimit)
        {
            this.partitionLimit = partitionLimit;
            this.cellPerPartitionLimit = cellPerPartitionLimit;
        }

        public Kind kind()
        {
            return Kind.THRIFT_LIMIT;
        }

        public boolean isUnlimited()
        {
            return partitionLimit == NO_LIMIT && cellPerPartitionLimit == NO_LIMIT;
        }

        public DataLimits forPaging(int pageSize)
        {
            // We don't support paging on thrift in general but do use paging under the hood for get_count. For
            // that case, we only care about limiting cellPerPartitionLimit (since it's paging over a single
            // partition). We do check that the partition limit is 1 however to make sure this is not misused
            // (as this wouldn't work properly for range queries).
            assert partitionLimit == 1;
            return new ThriftLimits(partitionLimit, pageSize);
        }

        public DataLimits forPaging(int pageSize, ByteBuffer lastReturnedKey, int lastReturnedKeyRemaining)
        {
            throw new UnsupportedOperationException();
        }

        public DataLimits forShortReadRetry(int toFetch)
        {
            // Short read retries are always done for a single partition at a time, so it's ok to ignore the
            // partition limit for those
            return new ThriftLimits(1, toFetch);
        }

        public boolean hasEnoughLiveData(CachedPartition cached, int nowInSec)
        {
            // We want the number of cells that are currently live. Getting that precise number forces
            // us to iterate the cached partition in general, but we can avoid that if:
            //   - The number of non-expiring live cells is greater than the number of cells asked (we then
            //     know we have enough live cells).
            //   - The number of cells cached is less than requested, in which case we know we won't have enough.
            if (cached.nonExpiringLiveCells() >= cellPerPartitionLimit)
                return true;

            if (cached.nonTombstoneCellCount() < cellPerPartitionLimit)
                return false;

            // Otherwise, we need to re-count
            DataLimits.Counter counter = newCounter(nowInSec, false);
            try (UnfilteredRowIterator cacheIter = cached.unfilteredIterator(ColumnFilter.selection(cached.columns()), Slices.ALL, false);
                 UnfilteredRowIterator iter = counter.applyTo(cacheIter))
            {
                // Consume the iterator until we've counted enough
                while (iter.hasNext())
                    iter.next();
                return counter.isDone();
            }
        }

        public Counter newCounter(int nowInSec, boolean assumeLiveData)
        {
            return new ThriftCounter(nowInSec, assumeLiveData);
        }

        public int count()
        {
            return partitionLimit * cellPerPartitionLimit;
        }

        public int perPartitionCount()
        {
            return cellPerPartitionLimit;
        }

        public float estimateTotalResults(ColumnFamilyStore cfs)
        {
            // remember that getMeansColumns returns a number of cells: we should clean nomenclature
            float cellsPerPartition = ((float) cfs.getMeanColumns()) / cfs.metadata.partitionColumns().regulars.size();
            return cellsPerPartition * cfs.estimateKeys();
        }

        protected class ThriftCounter extends Counter
        {
            protected final int nowInSec;
            protected final boolean assumeLiveData;

            protected int partitionsCounted;
            protected int cellsCounted;
            protected int cellsInCurrentPartition;

            public ThriftCounter(int nowInSec, boolean assumeLiveData)
            {
                this.nowInSec = nowInSec;
                this.assumeLiveData = assumeLiveData;
            }

            @Override
            public void applyToPartition(DecoratedKey partitionKey, Row staticRow)
            {
                cellsInCurrentPartition = 0;
                if (!staticRow.isEmpty())
                    applyToRow(staticRow);
            }

            @Override
            public Row applyToRow(Row row)
            {
                for (Cell cell : row.cells())
                {
                    if (assumeLiveData || cell.isLive(nowInSec))
                    {
                        ++cellsCounted;
                        if (++cellsInCurrentPartition >= cellPerPartitionLimit)
                            stopInPartition();
                    }
                }
                return row;
            }

            @Override
            public void onPartitionClose()
            {
                if (++partitionsCounted >= partitionLimit)
                    stop();
                super.onPartitionClose();
            }

            public int counted()
            {
                return cellsCounted;
            }

            public int countedInCurrentPartition()
            {
                return cellsInCurrentPartition;
            }

            public boolean isDone()
            {
                return partitionsCounted >= partitionLimit;
            }

            public boolean isDoneForPartition()
            {
                return isDone() || cellsInCurrentPartition >= cellPerPartitionLimit;
            }
        }

        @Override
        public String toString()
        {
            // This is not valid CQL, but that's ok since it's not used for CQL queries.
            return String.format("THRIFT LIMIT (partitions=%d, cells_per_partition=%d)", partitionLimit, cellPerPartitionLimit);
        }
    }

    /**
     * Limits used for thrift get_count when we only want to count super columns.
     */
    private static class SuperColumnCountingLimits extends ThriftLimits
    {
        private SuperColumnCountingLimits(int partitionLimit, int cellPerPartitionLimit)
        {
            super(partitionLimit, cellPerPartitionLimit);
        }

        public Kind kind()
        {
            return Kind.SUPER_COLUMN_COUNTING_LIMIT;
        }

        public DataLimits forPaging(int pageSize)
        {
            // We don't support paging on thrift in general but do use paging under the hood for get_count. For
            // that case, we only care about limiting cellPerPartitionLimit (since it's paging over a single
            // partition). We do check that the partition limit is 1 however to make sure this is not misused
            // (as this wouldn't work properly for range queries).
            assert partitionLimit == 1;
            return new SuperColumnCountingLimits(partitionLimit, pageSize);
        }

        public DataLimits forShortReadRetry(int toFetch)
        {
            // Short read retries are always done for a single partition at a time, so it's ok to ignore the
            // partition limit for those
            return new SuperColumnCountingLimits(1, toFetch);
        }

        public Counter newCounter(int nowInSec, boolean assumeLiveData)
        {
            return new SuperColumnCountingCounter(nowInSec, assumeLiveData);
        }

        protected class SuperColumnCountingCounter extends ThriftCounter
        {
            public SuperColumnCountingCounter(int nowInSec, boolean assumeLiveData)
            {
                super(nowInSec, assumeLiveData);
            }

            @Override
            public Row applyToRow(Row row)
            {
                // In the internal format, a row == a super column, so that's what we want to count.
                if (assumeLiveData || row.hasLiveData(nowInSec))
                {
                    ++cellsCounted;
                    if (++cellsInCurrentPartition >= cellPerPartitionLimit)
                        stopInPartition();
                }
                return row;
            }
        }
    }

    public static class Serializer
    {
        public void serialize(DataLimits limits, DataOutputPlus out, int version) throws IOException
        {
            out.writeByte(limits.kind().ordinal());
            switch (limits.kind())
            {
                case CQL_LIMIT:
                case CQL_PAGING_LIMIT:
                    CQLLimits cqlLimits = (CQLLimits)limits;
                    out.writeUnsignedVInt(cqlLimits.rowLimit);
                    out.writeUnsignedVInt(cqlLimits.perPartitionLimit);
                    out.writeBoolean(cqlLimits.isDistinct);
                    if (limits.kind() == Kind.CQL_PAGING_LIMIT)
                    {
                        CQLPagingLimits pagingLimits = (CQLPagingLimits)cqlLimits;
                        ByteBufferUtil.writeWithVIntLength(pagingLimits.lastReturnedKey, out);
                        out.writeUnsignedVInt(pagingLimits.lastReturnedKeyRemaining);
                    }
                    break;
                case THRIFT_LIMIT:
                case SUPER_COLUMN_COUNTING_LIMIT:
                    ThriftLimits thriftLimits = (ThriftLimits)limits;
                    out.writeUnsignedVInt(thriftLimits.partitionLimit);
                    out.writeUnsignedVInt(thriftLimits.cellPerPartitionLimit);
                    break;
            }
        }

        public DataLimits deserialize(DataInputPlus in, int version) throws IOException
        {
            Kind kind = Kind.values()[in.readUnsignedByte()];
            switch (kind)
            {
                case CQL_LIMIT:
                case CQL_PAGING_LIMIT:
                    int rowLimit = (int)in.readUnsignedVInt();
                    int perPartitionLimit = (int)in.readUnsignedVInt();
                    boolean isDistinct = in.readBoolean();
                    if (kind == Kind.CQL_LIMIT)
                        return new CQLLimits(rowLimit, perPartitionLimit, isDistinct);

                    ByteBuffer lastKey = ByteBufferUtil.readWithVIntLength(in);
                    int lastRemaining = (int)in.readUnsignedVInt();
                    return new CQLPagingLimits(rowLimit, perPartitionLimit, isDistinct, lastKey, lastRemaining);
                case THRIFT_LIMIT:
                case SUPER_COLUMN_COUNTING_LIMIT:
                    int partitionLimit = (int)in.readUnsignedVInt();
                    int cellPerPartitionLimit = (int)in.readUnsignedVInt();
                    return kind == Kind.THRIFT_LIMIT
                         ? new ThriftLimits(partitionLimit, cellPerPartitionLimit)
                         : new SuperColumnCountingLimits(partitionLimit, cellPerPartitionLimit);
            }
            throw new AssertionError();
        }

        public long serializedSize(DataLimits limits, int version)
        {
            long size = TypeSizes.sizeof((byte)limits.kind().ordinal());
            switch (limits.kind())
            {
                case CQL_LIMIT:
                case CQL_PAGING_LIMIT:
                    CQLLimits cqlLimits = (CQLLimits)limits;
                    size += TypeSizes.sizeofUnsignedVInt(cqlLimits.rowLimit);
                    size += TypeSizes.sizeofUnsignedVInt(cqlLimits.perPartitionLimit);
                    size += TypeSizes.sizeof(cqlLimits.isDistinct);
                    if (limits.kind() == Kind.CQL_PAGING_LIMIT)
                    {
                        CQLPagingLimits pagingLimits = (CQLPagingLimits)cqlLimits;
                        size += ByteBufferUtil.serializedSizeWithVIntLength(pagingLimits.lastReturnedKey);
                        size += TypeSizes.sizeofUnsignedVInt(pagingLimits.lastReturnedKeyRemaining);
                    }
                    break;
                case THRIFT_LIMIT:
                case SUPER_COLUMN_COUNTING_LIMIT:
                    ThriftLimits thriftLimits = (ThriftLimits)limits;
                    size += TypeSizes.sizeofUnsignedVInt(thriftLimits.partitionLimit);
                    size += TypeSizes.sizeofUnsignedVInt(thriftLimits.cellPerPartitionLimit);
                    break;
                default:
                    throw new AssertionError();
            }
            return size;
        }
    }
}


text:
package org.apache.zookeeper;

import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.zookeeper.client.HostProvider;
import org.apache.zookeeper.test.ClientBase;
import org.junit.jupiter.api.Test;

public class CustomHostProviderTest extends ZKTestCase {

    private AtomicInteger counter = new AtomicInteger(3);

    private class SpecialHostProvider implements HostProvider {

        // ignores its connectstring, and next() always returns localhost:2181
        // it will count down when updateServerList() is called
        @Override
        public int size() {
            return 1;
        }
        @Override
        public InetSocketAddress next(long spinDelay) {
            return new InetSocketAddress("127.0.0.1", 2181);
        }
        @Override
        public void onConnected() {
        }
        @Override
        public boolean updateServerList(Collection<InetSocketAddress> serverAddresses, InetSocketAddress currentHost) {
            counter.decrementAndGet();
            return false;
        }

    }

    @Test
    public void testZooKeeperWithCustomHostProvider() throws IOException, InterruptedException {
        final int CLIENT_PORT = PortAssignment.unique();
        final HostProvider specialHostProvider = new SpecialHostProvider();
        int expectedCounter = 3;
        counter.set(expectedCounter);

        ZooKeeper zkDefaults = new ZooKeeper(
            "127.0.0.1:" + CLIENT_PORT,
            ClientBase.CONNECTION_TIMEOUT,
            DummyWatcher.INSTANCE,
            false);

        ZooKeeper zkSpecial = new ZooKeeper(
                "127.0.0.1:" + CLIENT_PORT,
                ClientBase.CONNECTION_TIMEOUT,
                DummyWatcher.INSTANCE,
                false,
                specialHostProvider);

        assertTrue(counter.get() == expectedCounter);
        zkDefaults.updateServerList("127.0.0.1:" + PortAssignment.unique());
        assertTrue(counter.get() == expectedCounter);

        zkSpecial.updateServerList("127.0.0.1:" + PortAssignment.unique());
        expectedCounter--;
        assertTrue(counter.get() == expectedCounter);
    }

}


text:
import React from 'react'
import PropTypes from 'prop-types'

// Material UI
import Card from '@material-ui/core/Card'
import CardContent from '@material-ui/core/CardContent'
import CardMedia from '@material-ui/core/CardMedia'
import LockIcon from '@material-ui/icons/Lock'
import Dialog from '@material-ui/core/Dialog'
import DialogActions from '@material-ui/core/DialogActions'
import DialogContent from '@material-ui/core/DialogContent'
import DialogContentText from '@material-ui/core/DialogContentText'
import DialogTitle from '@material-ui/core/DialogTitle'

// FPCC
import FVButton from 'components/FVButton'
import FVLabel from 'components/FVLabel'
import NavigationHelpers from 'common/NavigationHelpers'

import { DialectTileStyles } from './DialectTileStyles'
/**
 * @summary DialectTilePresentation
 * @component
 *
 * @param {object} props
 *
 * @returns {node} jsx markup
 */
function DialectTilePresentation({
  dialectLogo,
  dialectTitle,
  dialectShortUrl,
  actionIcon,
  isPrivate,
  href,
  onDialectClick,
  /* Props for Dialog */
  isDialogOpen,
  handleDialogCancel,
  handleDialogOk,
  joinText,
}) {
  const classes = DialectTileStyles()
  // tooltip needs to apply DOM event listeners to its child element, hence use of forwardRef
  // see https://material-ui.com/components/tooltips/#custom-child-element
  const Tile = React.forwardRef(function Tile(props, ref) {
    return (
      <a
        href={href}
        onClick={onDialectClick}
        data-v2-url={`${NavigationHelpers.getBaseWebUIURL()}/${dialectShortUrl}`}
        title={dialectTitle}
        {...props}
        ref={ref}
      >
        <Card className={`${classes.card} ${isPrivate ? 'DialectPrivate' : 'Dialect'}`}>
          <CardMedia
            className={`${classes.cover} DialectCover`}
            image={isPrivate ? 'assets/images/cover.png' : dialectLogo}
            title={dialectTitle}
          />
          {isPrivate ? <LockIcon className={classes.privateIcon} /> : null}

            <CardContent className={classes.content}>

                {dialectTitle}
                {actionIcon}

            </CardContent>

        </Card>

    )
  })

  return isPrivate ? (
    <>
      <Tile />

      <Dialog
        fullWidth
        maxWidth="sm"
        open={isDialogOpen}
        aria-labelledby="alert-dialog-title"
        aria-describedby="alert-dialog-description"
      >
        <DialogContent>
          <DialogTitle className={classes.dialogTitle}>{dialectTitle} is Private</DialogTitle>
          <DialogContentText id="alert-dialog-description" className={classes.dialogDescription}>
            {joinText}
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <FVButton onClick={handleDialogCancel} variant="text" color="secondary">
            <FVLabel transKey="Cancel" defaultStr="Cancel" />
          </FVButton>
          <FVButton onClick={handleDialogOk} variant="contained" color="primary" autoFocus>
            <FVLabel transKey="Yes" defaultStr="Yes" />
          </FVButton>
        </DialogActions>
      </Dialog>
    </>
  ) : (
    <Tile />
  )
}
// PROPTYPES
const { bool, object, string, func } = PropTypes

DialectTilePresentation.propTypes = {
  dialectLogo: string.isRequired,
  dialectTitle: string.isRequired,
  dialectShortUrl: string,
  actionIcon: object,
  href: string.isRequired,
  isLoggedIn: bool.isRequired,
  isPrivate: bool.isRequired,
  onDialectClick: func.isRequired,
  isDialogOpen: bool.isRequired,
  handleDialogCancel: func.isRequired,
  handleDialogOk: func.isRequired,
  joinText: string.isRequired,
}

export default DialectTilePresentation


text:
require 'irb'

module Wallaby
  def self.store
    @wallaby_store
  end

  def self.store=(ws)
    @wallaby_store = ws
  end

  def store
    ::Wallaby::store
  end
end

module Wallaroo
  module Shell
    class Console < Command
      def self.opname
        "console"
      end

      def self.description
        "Provides an interactive wallaby environment."
      end

      def init_option_parser
        @loadfiles = []
        OptionParser.new do |opts|

          opname = "console"

          opts.banner = "Usage:  wallaby #{opname} [SCRIPT...]\ninteractive wallaby environment."

          opts.on("-h", "--help", "displays this message") do
            puts @oparser
            exit
          end

          opts.on("-r", "--require-file FILE", "require FILE before doing anything else") do |file|
            @loadfiles << file
          end

        end
      end

      def set_evalfiles(*args)
        @evalfiles = args.dup
      end

      register_callback :after_option_parsing, :set_evalfiles

      def act
        ARGV.clear
        ::Wallaby::store = store
        @loadfiles.each {|f| require f }
        if @evalfiles.size > 0
          begin
            @evalfiles.each {|f| load f }
            0
          rescue Exception=>e
            puts "script failed; #{e}"
            puts e.backtrace.join("\n")
            1
          end
        else
          ::IRB.start
        end
      end

    end
  end
end