text:
import { BeanStub } from "../context/beanStub";
import { Bean, PostConstruct } from "../context/context";
import { Events } from "../eventKeys";
import { GridPanel } from "../gridPanel/gridPanel";
import { getMaxDivHeight } from "../utils/browser";

/**
 * This class solves the 'max height' problem, where the user might want to show more data than
 * the max div height actually allows.
 */

@Bean('maxDivHeightScaler')
export class MaxDivHeightScaler extends BeanStub {

    private gridPanel: GridPanel;

    private maxDivHeight: number;

    // if false, then scaling is not active, logic in this class is not used,
    // the pixel height of the row container matches what is actually needed,
    // no scaling applied.
    private scaling: boolean;

    private modelHeight: number; // how many pixels the model needs
    private uiContainerHeight: number; // how many pixels we actually have
    private pixelsToShave: number; // the number of pixels we need to shave

    // the number of pixels we add to each rowTop - depends on the scroll position
    private offset: number;

    // the scrollY position
    private scrollY = 0;
    // how tall the body is
    private uiBodyHeight = 0;

    // the max scroll position
    private maxScrollY: number;

    @PostConstruct
    private postConstruct(): void {
        this.addManagedListener(this.eventService, Events.EVENT_BODY_HEIGHT_CHANGED, this.updateOffset.bind(this));
        this.maxDivHeight = getMaxDivHeight();
    }

    public registerGridComp(gridPanel: GridPanel): void {
        this.gridPanel = gridPanel;
    }

    public isScaling(): boolean {
        return this.scaling;
    }

    public getOffset(): number {
        return this.offset;
    }

    public updateOffset(): void {
        if (!this.scaling) { return; }

        const newScrollY = this.gridPanel.getVScrollPosition().top;
        const newBodyHeight = this.getUiBodyHeight();

        const atLeastOneChanged = newScrollY !== this.scrollY || newBodyHeight !== this.uiBodyHeight;
        if (atLeastOneChanged) {
            this.scrollY = newScrollY;
            this.uiBodyHeight = newBodyHeight;
            this.calculateOffset();
        }
    }

    private calculateOffset(): void {
        this.uiContainerHeight = this.maxDivHeight;
        this.pixelsToShave = this.modelHeight - this.uiContainerHeight;

        this.maxScrollY = this.uiContainerHeight - this.uiBodyHeight;
        const scrollPercent = this.scrollY / this.maxScrollY;

        this.setOffset(scrollPercent * this.pixelsToShave);
    }

    private clearOffset(): void {
        this.uiContainerHeight = this.modelHeight;
        this.pixelsToShave = 0;

        this.setOffset(0);
    }

    private setOffset(newOffset: number): void {
        // because we are talking pixels, no point in confusing things with half numbers
        const newOffsetFloor = typeof newOffset === 'number' ? Math.floor(newOffset) : null;
        if (this.offset === newOffsetFloor) { return; }

        this.offset = newOffsetFloor!;
        this.eventService.dispatchEvent({type: Events.EVENT_HEIGHT_SCALE_CHANGED});
    }

    public setModelHeight(modelHeight: number): void {
        this.modelHeight = modelHeight;
        this.scaling = this.maxDivHeight > 0 && modelHeight > this.maxDivHeight;
        if (this.scaling) {
            this.calculateOffset();
        } else {
            this.clearOffset();
        }
    }

    public getUiContainerHeight(): number {
        return this.uiContainerHeight;
    }

    public getRealPixelPosition(modelPixel: number): number {
        return modelPixel - this.offset;
    }

    private getUiBodyHeight(): number {
        const pos = this.gridPanel.getVScrollPosition();
        return pos.bottom - pos.top;
    }

    public getScrollPositionForPixel(rowTop: number): number {
        if (this.pixelsToShave <= 0) { return rowTop; }

        const modelMaxScroll = this.modelHeight - this.getUiBodyHeight();
        const scrollPercent = rowTop / modelMaxScroll;
        const scrollPixel = this.maxScrollY * scrollPercent;
        return scrollPixel;
    }
}


text:
@interface UserInfoDetailViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (strong, nonatomic) UITableView *myTableView;

@end

@implementation UserInfoDetailViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = _curUser.name;

    //    添加myTableView
    _myTableView = ({
        UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        tableView.backgroundColor = kColorTableSectionBg;
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [tableView registerClass:[UserInfoDetailUserCell class] forCellReuseIdentifier:kCellIdentifier_UserInfoDetailUserCell];
        [tableView registerClass:[TitleValueCell class] forCellReuseIdentifier:kCellIdentifier_TitleValue];
        [tableView registerClass:[UserInfoDetailTagCell class] forCellReuseIdentifier:kCellIdentifier_UserInfoDetailTagCell];
        [self.view addSubview:tableView];
        [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        tableView;
    });
}

#pragma mark TableM

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger row;
    switch (section) {
        case 0:
            row = 1;
            break;
        case 1:
            row = 3;
            break;
        case 2:
            row = 4;
            break;
        case 3:
            row = 2;
            break;
        default:
            row = 1;
            break;
    }
    return row;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        UserInfoDetailUserCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_UserInfoDetailUserCell forIndexPath:indexPath];
        [cell setName:_curUser.name icon:_curUser.avatar];
        [tableView addLineforPlainCell:cell forRowAtIndexPath:indexPath withLeftSpace:kPaddingLeftWidth];
        return cell;
    }else if (indexPath.section == 4){
        UserInfoDetailTagCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_UserInfoDetailTagCell forIndexPath:indexPath];
        [cell setTagStr:_curUser.tags_str];
        cell.accessoryType = UITableViewCellAccessoryNone;
        [tableView addLineforPlainCell:cell forRowAtIndexPath:indexPath withLeftSpace:kPaddingLeftWidth];
        return cell;
    }else{
        TitleValueCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_TitleValue forIndexPath:indexPath];
        [tableView addLineforPlainCell:cell forRowAtIndexPath:indexPath withLeftSpace:kPaddingLeftWidth];

        switch (indexPath.section) {
            case 1:
                switch (indexPath.row) {
                    case 0:
                        [cell setTitleStr:@"加入时间" valueStr:[_curUser.created_at string_yyyy_MM_dd]];
                        break;
                    case 1:
                        [cell setTitleStr:@"最后活动" valueStr:[_curUser.last_activity_at string_yyyy_MM_dd]];
                        break;
                    default:
                        [cell setTitleStr:@"个性后缀" valueStr:_curUser.global_key];
                        break;
                }
                break;
            case 2:
                switch (indexPath.row) {
                    case 0:
                        if (_curUser.sex.intValue == 0) {
                            //        男
                            [cell setTitleStr:@"性别" valueStr:@"男"];
                        }else if (_curUser.sex.intValue == 1){
                            //        女
                            [cell setTitleStr:@"性别" valueStr:@"女"];
                        }else{
                            //        未知
                            [cell setTitleStr:@"性别" valueStr:@"未知"];
                        }
                        break;
                    case 1:
                        [cell setTitleStr:@"生日" valueStr:_curUser.birthday];
                        break;
                    case 2:
                        [cell setTitleStr:@"所在地" valueStr:_curUser.location];
                        break;
                    default:
                        [cell setTitleStr:@"座右铭" valueStr:_curUser.slogan];
                        break;
                }
                break;
            default:
                if (indexPath.row == 0) {
                    [cell setTitleStr:@"公司" valueStr:_curUser.company];
                }else{
                    [cell setTitleStr:@"职位" valueStr:_curUser.job_str];
                }
                break;
        }
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat cellHeight;
    if (indexPath.section == 0) {
        cellHeight = [UserInfoDetailUserCell cellHeight];
    }else if (indexPath.section == 4){
        cellHeight = [UserInfoDetailTagCell cellHeightWithObj:_curUser.tags_str];
    }else{
        cellHeight = 44;
    }
    return cellHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 20.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.5;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 1)];
    headerView.backgroundColor = [UIColor colorWithHexString:@"0xe5e5e5"];
    [headerView setHeight:20.0];
    return headerView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)dealloc
{
    _myTableView.delegate = nil;
    _myTableView.dataSource = nil;
}

@end

redpajama_set_name: RedPajamaGithub


text:
package org.apache.webbeans.test.injection.circular.tests;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;

import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;

import org.junit.Assert;

import org.apache.webbeans.test.AbstractUnitTest;
import org.apache.webbeans.test.injection.circular.beans.CircularConstructorOrProducerMethodParameterBean;
import org.apache.webbeans.test.injection.circular.beans.CircularNormalInConstructor;
import org.junit.Test;

public class CircularInjectionIntoConstructorTest extends AbstractUnitTest
{
    public CircularInjectionIntoConstructorTest()
    {

    }

    @Test
    @SuppressWarnings("unchecked")
    public void testOneNormalOneDependent()
    {
        Collection<String> beanXmls = new ArrayList<String>();

        Collection<Class<?>> beanClasses = new ArrayList<Class<?>>();
        beanClasses.add(CircularNormalInConstructor.class);
        beanClasses.add(CircularConstructorOrProducerMethodParameterBean.class);

        startContainer(beanClasses, beanXmls);

        Set<Bean<?>> beans = getBeanManager().getBeans("org.apache.webbeans.test.injection.circular.beans.CircularNormalInConstructor");
        Assert.assertNotNull(beans);

        Bean<CircularNormalInConstructor> bean = (Bean<CircularNormalInConstructor>)beans.iterator().next();
        CreationalContext<CircularNormalInConstructor> ctx = getBeanManager().createCreationalContext(bean);

        Object reference = getBeanManager().getReference(bean, CircularNormalInConstructor.class, ctx);

        Assert.assertTrue(reference instanceof CircularNormalInConstructor);

        CircularNormalInConstructor beanInstance = (CircularNormalInConstructor)reference;
        beanInstance.sayHello();

        beans = getBeanManager().getBeans("org.apache.webbeans.test.injection.circular.beans.CircularConstructorOrProducerMethodParameterBean");
        Assert.assertNotNull(beans);
        Bean<CircularConstructorOrProducerMethodParameterBean> bean2 = (Bean<CircularConstructorOrProducerMethodParameterBean>)beans.iterator().next();

        CreationalContext<CircularConstructorOrProducerMethodParameterBean> ctx2 = getBeanManager().createCreationalContext(bean2);

        reference = getBeanManager().getReference(bean2, CircularConstructorOrProducerMethodParameterBean.class, ctx2);

        Assert.assertTrue(reference instanceof CircularConstructorOrProducerMethodParameterBean);

        CircularConstructorOrProducerMethodParameterBean beanInstance2 = (CircularConstructorOrProducerMethodParameterBean)reference;
        Assert.assertTrue(beanInstance2.getSAYHELLO());

        reference = getBeanManager().getReference(bean, CircularNormalInConstructor.class, ctx);

        Assert.assertTrue(reference instanceof CircularNormalInConstructor);

        beanInstance = (CircularNormalInConstructor)reference;

        Assert.assertTrue(beanInstance.getSAYHELLO());

        shutDownContainer();
    }

}


text:
class Main < Controller
  map '/'

  def index(*args)
    case args.size
    when 1, 2
      if post = Post[args.shift]
        render_view(:post, post: post)
      else
        not_found
      end
    else
      render_view(:posts, posts: Post.latest(request[:n] || 10))
    end
  end

  def archive
    @posts = Post.order_by(:created_at.desc).all
  end

  def post(id)
    @post = Post[id]
  end

  def feed
    action.layout = nil
    @posts = Post.order_by(:created_at.desc).all
    @updated = @posts.last.updated_at
  end

  def tag(tagstr)
    not_found unless tag = Tag[:name => Rack::Utils.unescape(tagstr)]
    render_view(:posts, posts: tag.posts, tag: tag)
  end

  def login
    return unless request.post?
    user_login(request.subset(:username, :password))
    if logged_in?
      flash[:notice] = "You're now logged in as #{user.username}"
      redirect Admin.r(:/)
    else
      flash[:error] = "Unable to login"
      redirect r(:/)
    end
  end

  def logout
    user_logout
    redirect_referrer
  end
end


text:
import os

from doco.client import Client

class DocomoDialogAPI(object):

    def __init__(self, api_key=None):
        api_key = os.environ.get('DOCOMO_DIALOGUE_API_KEY', api_key)
        self.__client = Client(apikey=api_key)

    def reply(self, text):
        response = self.__client.send(utt=text, apiname='Dialogue')
        utt = response['utt']

        return utt


text:
package org.path.episample.android.tasks;

import java.util.ArrayList;

import org.path.common.android.data.CensusModel;
import org.path.common.android.database.CensusDatabaseFactory;
import org.path.common.android.database.DatabaseFactory;
import org.path.common.android.utilities.CensusUtil;
import org.path.episample.android.application.Survey;
import org.path.episample.android.listeners.JoinRestoreListener;
import org.path.episample.android.utilities.BackupRestoreUtils;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.AsyncTask;
import android.util.Log;

/*
 * @author belendia@gmail.com
 */

public class JoinRestoreTask extends AsyncTask<String, String, Void> {
	private static final String t = "JoinRestoreTask";
	private JoinRestoreListener mListener;
	private boolean mSuccess = true;
	private SQLiteDatabase mWebDb;
	private SQLiteDatabase mCensusDb;

	@Override
	protected Void doInBackground(String... params) {
		if (params.length > 0 && params[0].length() > 0
				&& BackupRestoreUtils.dbFileExists(params[0])) {
			try {
				mWebDb = DatabaseFactory.get().getDatabase(
						Survey.getInstance().getApplicationContext(), "survey");
				mCensusDb = CensusDatabaseFactory.get().getDatabase(
						Survey.getInstance().getApplicationContext(), "survey");

				SQLiteStatement insertSqlCensusDb = CensusUtil
						.getInsertStatementCensusDb(mCensusDb);
				SQLiteStatement updateSqlCensusDb = CensusUtil
						.getUpdateStatementCensusDb(mCensusDb);
				SQLiteStatement insertSqlWebDb = CensusUtil
						.getInsertStatementWebDb(mWebDb);
				SQLiteStatement updateSqlWebDb = CensusUtil
						.getUpdateStatementWebDb(mWebDb);

				mCensusDb.beginTransaction();
				mWebDb.beginTransaction();

				ArrayList<CensusModel> censusList = CensusUtil
						.getAllFromBackupDb(Survey.getInstance()
								.getApplicationContext(), params[0]);

				for (CensusModel censusModel : censusList) {
					CensusUtil.insertOrUpdate(Survey.getInstance()
							.getApplicationContext(), insertSqlCensusDb,
							updateSqlCensusDb, insertSqlWebDb, updateSqlWebDb,
							censusModel, true);
					if (isCancelled())
						return null;
				}

				insertSqlCensusDb.close();
				updateSqlCensusDb.close();
				insertSqlWebDb.close();
				updateSqlWebDb.close();

				mCensusDb.setTransactionSuccessful();
				mCensusDb.endTransaction();

				mWebDb.setTransactionSuccessful();
				mWebDb.endTransaction();
			} catch (Exception ex) {
				mSuccess = false;
			} finally {
				closeDB();
			}
		}

		return null;
	}

	@Override
	protected void onPostExecute(Void unused) {
		synchronized (this) {
			if (mListener != null) {
				mListener.joinRestoreComplete(mSuccess);
			}
		}
	}

	@Override
	protected void onProgressUpdate(String... values) {
		synchronized (this) {
			if (mListener != null) {
				mListener.joinRestoreProgressUpdate(values[0]);
			}
		}
	}

	@Override
	protected void onCancelled() {
		synchronized (this) {
			closeDB();
			if (mListener != null) {
				mListener.joinRestoreCanceled();
			}
		}
	}

	public void setJoinRestoreListener(JoinRestoreListener listener) {
		synchronized (this) {
			mListener = listener;
		}
	}

	private void closeDB() {
		try {
			if (mWebDb != null && mWebDb.isOpen())
				mWebDb.close();
			if (mCensusDb != null && mCensusDb.isOpen())
				mCensusDb.close();
		} catch (Exception ex) {
			Log.d(t, "Error closing census or web database");
		}
	}

	public boolean getSuccess() {
		return mSuccess;
	}
}


text:
syntax_errors=0
error_msg=$(mktemp /tmp/error_msg.XXXXXX)

if git rev-parse --quiet --verify HEAD > /dev/null
then
    against=HEAD
else
    # Initial commit: diff against an empty tree object
    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi

# Get list of new/modified manifest and template files to check (in git index)
for indexfile in `git diff-index --diff-filter=AM --name-only --cached $against | egrep '\.(pp|erb)'`
do
    # Don't check empty files
    if [ `git cat-file -s :0:$indexfile` -gt 0 ]
    then
        case $indexfile in
            *.pp )
                # Check puppet manifest syntax
                git cat-file blob :0:$indexfile | puppet parser validate > $error_msg ;;
            *.erb )
                # Check ERB template syntax
                git cat-file blob :0:$indexfile | erb -x -T - | ruby -c 2> $error_msg > /dev/null ;;
        esac
        if [ "$?" -ne 0 ]
        then
            echo -n "$indexfile: "
            cat $error_msg
            syntax_errors=`expr $syntax_errors + 1`
        fi
    fi
done

rm -f $error_msg

if [ "$syntax_errors" -ne 0 ]
then
    echo "Error: $syntax_errors syntax errors found, aborting commit."
    exit 1
fi


text:
require 'kintama'
require 'yaml'
require 'moneta'
require 'colorize'
require_relative '../lib/self_consciousness'

def execute(path)
  thread = Thread.new { system "ruby #{path}" }
  thread.join
end

def run_and(method = :normalize)
  script = method == :normalize ? 'test.rb' : 'test.rb differently'
  execute "#{__dir__}/#{script}"
  SelfConsciousness.send method
end

describe SelfConsciousness do
  setup do
    @storage = Moneta.new :File, dir: '.self_consciousness'
    @expected_introspection_results = {
      removals: [{:output=>[1], :from=>:foo, :to=>:bar}],
      additions: [{:output=>[2], :from=>:bar, :to=>:baz}]
    }
    SelfConsciousness.clear
    run_and :normalize
  end

  should 'decide what\'s "normal"' do
    expected_dependencies = [{:output=>[1], :from=>:foo, :to=>:bar}]
    assert_equal true, @storage.key?('dependencies')
    assert_equal expected_dependencies, @storage.fetch('dependencies', nil)
  end

  should 'compare itself with its idea of "normal"' do
    run_and :introspect
    @expected_introspection_results.each do |key, value|
      assert_equal value, @storage.fetch(key.to_s, nil)
    end
  end

  should 'introspect before reporting' do
    run_and :report
    @expected_introspection_results.each do |key, value|
      assert_equal value, @storage.fetch(key.to_s, nil)
    end
  end

  should 'report a diff of additions and removals' do
    assert_output /-.*+/ do
      run_and :report
    end
  end
end


text:
package org.wso2.developerstudio.eclipse.qos.project.controller;

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

import org.wso2.developerstudio.eclipse.platform.core.model.AbstractListDataProvider;
import org.wso2.developerstudio.eclipse.platform.core.project.model.ProjectDataModel;

public class QoSProjectTypeList extends AbstractListDataProvider {

	private static List<String> serviceNames;

	public static List<String> getServiceNames() {
		return serviceNames;
	}

	public static void setServiceNames(List<String> serviceNames) {
		QoSProjectTypeList.serviceNames = serviceNames;
	}

	public List<ListData> getListData(String modelProperty,ProjectDataModel model) {
		List<ListData> data = new ArrayList<ListData>();

		if (modelProperty.equals("ps.type")){
			for (String name : serviceNames) {
				data.add(new ListData(name, name));
			}
		}
		return data;
	}
}


text:
<?php

namespace Antee\i18n;

use \Traversable;
use \InvalidArgumentException;

/**
 * Wrapper between \Nette\ITranslator and ITranslator.
 * This class should be used only when necessary: Forms and Datagrid.
 *
 * @author Ondřej Vodáček
 */
class NetteTranslator implements \Nette\Localization\ITranslator {

	/** @var ITranslator */
	private $translator;

	public function __construct(ITranslator $translator) {
		$this->translator = $translator;
	}

	/**
	 * Add context to given string(s).
	 *
	 * @param string|array|Traversable $value
	 * @param string $context
	 * @return string|array
	 * @throws InvalidArgumentException
	 */
	public static function addTranslationContext($value, $context) {
		if (is_array($value) || $value instanceof Traversable) {
			$array = array();
			foreach ($value as $key => $string) {
				$array[$key] = self::addTranslationContext($string, $context);
			}
			return $array;
		}
		return (string)$context . chr(4) . (string)$value;
	}

	/*** \Nette\ITranslator ***************************************************/

	public function translate($message, $count = null) {
		$isContext = false;
		$context = "";
		$plural = "";
		$isPlural = is_array($message);
		if ($isPlural) {
			list($message, $plural) = $message;
		}
		if (strpos($message, chr(4)) !== false) {
			$isContext = true;
			list ($context, $message) = explode(chr(4), $message, 2);
		}

		$translation = null;
		switch (true) {
			case $isContext && $isPlural:
				$translation = $this->translator->npgettext($context, $message, $plural, $count);
				break;
			case $isContext:
				$translation = $this->translator->pgettext($context, $message);
				break;
			case $isPlural:
				$translation = $this->translator->ngettext($message, $plural, $count);
				break;
			default:
				$translation = $this->translator->gettext($message);
				break;
		}
		return $translation;
	}
}


text:
"""entrenamiento_flechas

Revision ID: 031
Revises: 030
Create Date: 2014-08-05 22:56:36.941401

"""

# revision identifiers, used by Alembic.
revision = '031'
down_revision = '030'

from alembic import op
import sqlalchemy as db

def upgrade():
    op.create_table('entrenamiento_flechas',
        db.Column('id', db.Integer, primary_key=True),
        db.Column('id_entrenamiento_realizado',
                  db.Integer,
                  db.ForeignKey('entrenamiento_realizado.id', ondelete='CASCADE'),
                  nullable=False),
        db.Column('hora_inicio', db.Time),
        db.Column('cantidad_de_flechas', db.Integer),
        db.Column('distancia', db.Integer),
        db.Column('id_arco', db.Integer,
                            db.ForeignKey('arco.id')),
        db.Column('id_lugar', db.Integer,
                            db.ForeignKey('lugar.id')),
    )

def downgrade():
    op.drop_table('entrenamiento_flechas')


text:
MongoDB\Driver\Manager::executeBulkWrite() should not issue warning before exception
--FILE--
<?php
require_once __DIR__ . "/../utils/basic.inc";

// Invalid host cannot be resolved
$manager = create_test_manager('mongodb://example.invalid:27017', ['serverSelectionTimeoutMS' => 1]);

echo throws(function() use ($manager) {
    $bulk = new MongoDB\Driver\BulkWrite;
    $bulk->insert(['x' => 1]);
    $manager->executeBulkWrite(NS, $bulk);
}, 'MongoDB\Driver\Exception\ConnectionTimeoutException'), "\n";

// Valid host refuses connection
$manager = create_test_manager('mongodb://localhost:54321', ['serverSelectionTimeoutMS' => 1]);

echo throws(function() use ($manager) {
    $bulk = new MongoDB\Driver\BulkWrite;
    $bulk->insert(['x' => 1]);
    $manager->executeBulkWrite(NS, $bulk);
}, 'MongoDB\Driver\Exception\ConnectionTimeoutException'), "\n";

?>
===DONE===
<?php exit(0); ?>
--EXPECTF--
OK: Got MongoDB\Driver\Exception\ConnectionTimeoutException
No suitable servers found (`serverSelectionTryOnce` set): %s
OK: Got MongoDB\Driver\Exception\ConnectionTimeoutException
No suitable servers found (`serverSelectionTryOnce` set): %s
===DONE===


text:
package com.wwq.genesisfreelander.view.widget.custom;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

import com.wwq.genesisfreelander.view.base.BaseApplication;

import static com.wwq.genesisfreelander.controller.library.typefacehelper.TypefaceHelper.typeface;

/**
 * Created by wwq on 2017/4/28.
 */

public class TypefaceTextView extends TextView {
    public TypefaceTextView(Context context) {
        this(context, null);
    }

    public TypefaceTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        typeface(this, BaseApplication.getApplication().getMicrosoftAccor());
    }

    public TypefaceTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        typeface(this, BaseApplication.getApplication().getMicrosoftAccor());
    }
}


text:
package com.thinkbiganalytics.nifi.provenance;

import java.util.concurrent.atomic.AtomicLong;

/**
 * Track event counts sent to the JMS queue
 */
public class AggregationEventProcessingStats {

    private static AtomicLong streamingEventsSentToJms = new AtomicLong(0L);

    private static AtomicLong batchEventsSentToJms = new AtomicLong(0L);

    public static Long addStreamingEvents(int num) {
        return streamingEventsSentToJms.addAndGet(new Long(num));
    }

    public static Long getStreamingEventsSent() {
        return streamingEventsSentToJms.get();
    }

    public static Long addBatchEvents(int num) {
        return batchEventsSentToJms.addAndGet(new Long(num));
    }

    public static Long getBatchEventsSent() {
        return batchEventsSentToJms.get();
    }

}


text:
/**
 * DenticaoController
 *
 * @description :: Server-side logic for managing denticaos
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

module.exports = {
  findByUser: function(req,res) {
    var user = req.param("user");
    console.log(user);
    if (user) {
      Filho.find().where({usuario: user}).exec(function findCB(err, filhos){
        if (err) {
          return res.json({error: true, message: err});
        }
        if (filhos) {
          var filhosId = new Array();
          for (var i in filhos) {
            filhosId.push(filhos[i].id);
          }
          Denticao.find({filho: filhosId}).populateAll().exec(function findCB(error, doencas){
            if (error) {
              return res.json({error: true, message: error});
            }
            if (doencas) {
              return res.json(doencas);
            } else {
              return res.json([]);
            }
          });
        } else {
          return res.json([]);
        }
      });
    } else {
      return res.json({error: true, message: 'No user passed'});
    }
  }
};


text:
var shell = require('shelljs');
var airSdk = require('air-sdk');
airSdk.update();

var useMXMLC = function(opts, files){
  var cmdLineOpts = [airSdk.bin[opts.bin], opts.rawConfig];
  cmdLineOpts.push("-output=" + files[0].dest);
  cmdLineOpts.push(files[0].src[0]);
  return cmdLineOpts.join(" ");
};

var useCOMPC = function(opts, files){
  var cmdLineOpts = [airSdk.bin[opts.bin], opts.rawConfig];
  cmdLineOpts.push("-output=" + files[0].dest);
  return cmdLineOpts.join(" ");
};

module.exports = function(grunt) {
  grunt.registerMultiTask('air_sdk', 'A grunt plugin to compile Adobe Flex, Adobe Air, Actionscript, MXML applications using the Adobe AIR_SDK and binaries available (mxmlc, compc, etc.)', function() {
    var opts = this.options();
    var cmdLineOpts = "";
    switch(opts.bin){
      case "mxmlc":
        cmdLineOpts = useMXMLC(opts, this.files);
        break;
      case "compc":
        cmdLineOpts = useCOMPC(opts, this.files);
        break;
      default:
        console.log("Binary not supported yet");
        return;
    }
    var executed = shell.exec(cmdLineOpts);
    if(executed.code === 0 ){
      grunt.log.writeln("File successfully created!");
    }else{
      grunt.log.error(executed.output);
      grunt.fail.fatal("Error during compile");
    }
  });
};


text:
package user

// Info describes a user that has been authenticated to the system.
type Info interface {
	// GetName returns the name that uniquely identifies this user among all
	// other active users.
	GetName() string
	// GetUID returns a unique value for a particular user that will change
	// if the user is removed from the system and another user is added with
	// the same name.
	GetUID() string
	// GetGroups returns the names of the groups the user is a member of
	GetGroups() []string
}

// DefaultInfo provides a simple user information exchange object
// for components that implement the UserInfo interface.
type DefaultInfo struct {
	Name   string
	UID    string
	Groups []string
}

func (i *DefaultInfo) GetName() string {
	return i.Name
}

func (i *DefaultInfo) GetUID() string {
	return i.UID
}

func (i *DefaultInfo) GetGroups() []string {
	return i.Groups
}


text:
package akka.rtcweb.protocol.jsep

import java.io.ByteArrayInputStream
import java.net.InetSocketAddress
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import java.security.cert.{ X509Certificate, CertificateFactory }

import akka.actor._
import akka.rtcweb.protocol.ice._
import akka.rtcweb.protocol.ice.IceAgent.CreateOfferResponse
import akka.rtcweb.protocol.jsep.RTCPeerConnection.{ ICECandidatePolicy, PeerConnectionConfiguration }
import akka.rtcweb.protocol.sdp._
import akka.rtcweb.protocol.sdp.grouping.MediaStreamIdentifier
import akka.rtcweb.protocol.sdp.sctp.Sctpmap
import akka.stream.Materializer
import akka.pattern.ask
import akka.util.Timeout

import scala.concurrent.duration.{ FiniteDuration, _ }
import scala.language.postfixOps
import scala.util.Random

object RTCPeerConnection {

  type Label = String

  /**
   * Creates Props for an actor of this type.
   *
   * @param config ???
   * @return a Props for creating this actor, which can then be further configured
   *         (e.g. calling `.withDispatcher()` on it)
   */
  def props(config: PeerConnectionConfiguration, iceAgent: ActorRef)(implicit materializer: Materializer) = Props(new RTCPeerConnection(config, iceAgent)(materializer))

  /**
   * By specifying a policy from the list below, the application can control how aggressively it
   * will try to BUNDLE media streams together.  The set of available
   * policies is as follows:
   */
  sealed trait BundlePolicy

  /**
   * Typically, when gathering ICE candidates, the browser will gather all
   * possible forms of initial candidates - host, server reflexive, and
   * relay.  However, in certain cases, applications may want to have more
   * specific control over the gathering process, due to privacy or
   * related concerns.  For example, one may want to suppress the use of
   * host candidates, to avoid exposing information about the local
   * network, or go as far as only using relay candidates, to leak as
   * little location information as possible (note that these choices come
   * with corresponding operational costs).  To accomplish this, the
   * browser MUST allow the application to restrict which ICE candidates
   * are used in a session.  In addition, administrators may also wish to
   * control the set of ICE candidates, and so the browser SHOULD also
   * allow control via local policy, with the most restrictive policy
   * prevailing.
   *
   * There may also be cases where the application wants to change which
   * types of candidates are used while the session is active.  A prime
   * example is where a callee may initially want to use only relay
   * candidates, to avoid leaking location information to an arbitrary
   * caller, but then change to use all candidates (for lower operational
   * cost) once the user has indicated they want to take the call.  For
   * this scenario, the browser MUST allow the candidate policy to be
   * changed in mid-session, subject to the aforementioned interactions
   * with local policy.
   *
   * To administer the ICE candidate policy, the browser will determine
   * the current setting at the start of each gathering phase.  Then,
   * during the gathering phase, the browser MUST NOT expose candidates
   * disallowed by the current policy to the application, use them as the
   * source of connectivity checks, or indirectly expose them via other
   * fields, such as the raddr/rport attributes for other ICE candidates.
   * Later, if a different policy is specified by the application, the
   * application can apply it by kicking off a new gathering phase via an
   * ICE restart.
   *
   * @see [[http://tools.ietf.org/html/draft-ietf-rtcweb-jsep-08#section-3.4.3]]
   */
  sealed trait ICECandidatePolicy

  /**
   * Session description objects (RTCSessionDescription) may be of type
   * "offer", "pranswer", and "answer".  These types provide information
   * as to how the description parameter should be parsed, and how the
   * media state should be changed.
   */
  sealed trait RTCSessionDescription

  sealed trait HasSDPPayload extends RTCSessionDescription {
    def sessionDescription: SessionDescription
  }

  sealed trait PeerConnectionMessage

  final case class StunServerDescription(address: InetSocketAddress, credentials: Option[Nothing] = None)

  /**
   * @param stunServers          TODO
   * @param iceCandidatePoolSize TODO
   * @param bundlePolicy         Lastly, the application can specify its preferred policy regarding
   *                             use of BUNDLE, the multiplexing mechanism defined in
   *                             [I-D.ietf-mmusic-sdp-bundle-negotiation].  By specifying a policy
   *                             from the list below, the application can control how aggressively it
   *                             will try to BUNDLE media streams together.  The set of available
   *                             policies is as follows:
   * @param iceCandidatePolicy   If an ICE candidate policy is specified,
   *                             it functions as described in Section 3.4.3, causing the browser to only surface the permitted
   *                             candidates to the application, and only use those candidates for
   *                             connectivity checks.  The set of available policies is as follows:
   */
  final case class PeerConnectionConfiguration(
    stunServers: Vector[StunServerDescription],
    iceCandidatePoolSize: Int,
    bundlePolicy: BundlePolicy,
    iceCandidatePolicy: ICECandidatePolicy = ICECandidatePolicy.all)

  /**
   * The createOffer method takes as a parameter an RTCOfferOptions
   * object.  Special processing is performed when generating a SDP
   * description if the following constraints are present.
   *
   * @param OfferToReceiveAudio    If the "OfferToReceiveAudio" option is specified, with an integer
   *                               value of N, the offer MUST include N non-rejected m= sections with
   *                               media type "audio", even if fewer than N audio MediaStreamTracks have
   *                               been added to the PeerConnection.  This allows the offerer to receive
   *                               audio, including multiple independent streams, even when not sending
   *                               it; accordingly, the directional attribute on the audio m= sections
   *                               without associated MediaStreamTracks MUST be set to recvonly.  If
   *                               this option is specified in the case where at least N audio
   *                               MediaStreamTracks have already been added to the PeerConnection, or N
   *                               non-rejected m= sections with media type "audio" would otherwise be
   *                               generated, it has no effect.  For backwards compatibility, a value of
   *                               "true" is interpreted as equivalent to N=1.
   * @param OfferToReceiveVideo    If the "OfferToReceiveVideo" option is specified, with an integer
   *                               value of N, the offer MUST include N non-rejected m= sections with
   *                               media type "video", even if fewer than N video MediaStreamTracks have
   *                               been added to the PeerConnection.  This allows the offerer to receive
   *                               video, including multiple independent streams, even when not sending
   *                               it; accordingly, the directional attribute on the video m= sections
   *                               without associated MediaStreamTracks MUST be set to recvonly.  If
   *                               this option is specified in the case where at least N video
   *                               MediaStreamTracks have already been added to the PeerConnection, or N
   *                               non-rejected m= sections with media type "video" would otherwise be
   *                               generated, it has no effect.  For backwards compatibility, a value of
   *                               "true" is interpreted as equivalent to N=1.
   * @param VoiceActivityDetection If the "VoiceActivityDetection" option is specified, with a value of
   *                               "true", the offer MUST indicate support for silence suppression in
   *                               the audio it receives by including comfort noise ("CN") codecs for
   *                               each offered audio codec, as specified in [RFC3389], Section 5.1,
   *                               except for codecs that have their own internal silence suppression
   *                               support.  For codecs that have their own internal silence suppression
   *                               support, the appropriate fmtp parameters for that codec MUST be
   *                               specified to indicate that silence suppression for received audio is
   *                               desired.  For example, when using the Opus codec, the "usedtx=1"
   *                               parameter would be specified in the offer.  This option allows the
   *                               endpoint to significantly reduce the amount of audio bandwidth it
   *                               receives, at the cost of some fidelity, depending on the quality of
   *                               the remote VAD algorithm.
   * @param IceRestart             If the "IceRestart" option is specified, with a value of "true", the
   *                               offer MUST indicate an ICE restart by generating new ICE ufrag and
   *                               pwd attributes, as specified in RFC5245, Section 9.1.1.1.  If this
   *                               option is specified on an initial offer, it has no effect (since a
   *                               new ICE ufrag and pwd are already generated).  This option is useful
   *                               for reestablishing connectivity in cases where failures are detected.
   *
   */
  final case class RTCOfferOptions(
    OfferToReceiveAudio: Option[Int] = None,
    OfferToReceiveVideo: Option[Int] = None,
    VoiceActivityDetection: Boolean = false,
    IceRestart: Boolean = false,
    DtlsSrtpKeyAgreement: Boolean = false,
    RtpDataChannels: Boolean = false)

  final case class CreateAnswerOptions()

  /**
   * Session descriptions generated by createOffer must be immediately
   * usable by setLocalDescription; if a system has limited resources
   * (e.g. a finite number of decoders), createOffer should return an
   * offer that reflects the current state of the system, so that
   * setLocalDescription will succeed when it attempts to acquire those
   * resources.  Because this method may need to inspect the system state
   * to determine the currently available resources, it may be implemented
   * as an async operation.
   *
   * Calling this method may do things such as generate new ICE
   * credentials, but does not result in candidate gathering, or cause
   * media to start or stop flowing.
   *
   * The createOffer method generates a blob of SDP that contains a
   * [RFC3264] offer with the supported configurations for the session,
   * including descriptions of the local MediaStreams attached to this
   * PeerConnection, the codec/RTP/RTCP options supported by this
   * implementation, and any candidates that have been gathered by the ICE
   * Agent.  An options parameter may be supplied to provide additional
   * control over the generated offer.  This options parameter should
   * allow for the following manipulations to be performed:
   *
   * - To indicate support for a media type even if no MediaStreamTracks
   * of that type have been added to the session (e.g., an audio call
   * that wants to receive video.)
   * - To trigger an ICE restart, for the purpose of reestablishing
   * connectivity.
   *
   * In the initial offer, the generated SDP will contain all desired
   * functionality for the session (functionality that is supported but
   * not desired by default may be omitted); for each SDP line, the
   * generation of the SDP will follow the process defined for generating
   * an initial offer from the document that specifies the given SDP line.
   * The exact handling of initial offer generation is detailed in
   * Section 5.2.1 below.
   *
   * In the event createOffer is called after the session is established,
   * createOffer will generate an offer to modify the current session
   * based on any changes that have been made to the session, e.g. adding
   * or removing MediaStreams, or requesting an ICE restart.  For each
   * existing stream, the generation of each SDP line must follow the
   * process defined for generating an updated offer from the RFC that
   * specifies the given SDP line.  For each new stream, the generation of
   * the SDP must follow the process of generating an initial offer, as
   * mentioned above.  If no changes have been made, or for SDP lines that
   * are unaffected by the requested changes, the offer will only contain
   * the parameters negotiated by the last offer-answer exchange.  The
   * exact handling of subsequent offer generation is detailed in
   * Section 5.2.2. below.
   *
   * Session descriptions generated by createOffer must be immediately
   * usable by setLocalDescription; if a system has limited resources
   * (e.g. a finite number of decoders), createOffer should return an
   * offer that reflects the current state of the system, so that
   * setLocalDescription will succeed when it attempts to acquire those
   * resources.  Because this method may need to inspect the system state
   * to determine the currently available resources, it may be implemented
   * as an async operation.
   *
   * Calling this method may do things such as generate new ICE
   * credentials, but does not result in candidate gathering, or cause
   * media to start or stop flowing.
   *
   */
  final case class CreateOffer(options: RTCOfferOptions) extends PeerConnectionMessage

  /**
   * The createAnswer method generates a blob of SDP that contains a
   * [RFC3264] SDP answer with the supported configuration for the session
   * that is compatible with the parameters supplied in the most recent
   * call to setRemoteDescription, which MUST have been called prior to
   * calling createAnswer.  Like createOffer, the returned blob contains
   * descriptions of the local MediaStreams attached to this
   * PeerConnection, the codec/RTP/RTCP options negotiated for this
   * session, and any candidates that have been gathered by the ICE Agent.
   * An options parameter may be supplied to provide additional control
   * over the generated answer.
   *
   * As an answer, the generated SDP will contain a specific configuration
   * that specifies how the media plane should be established; for each
   * SDP line, the generation of the SDP must follow the process defined
   * for generating an answer from the document that specifies the given
   * SDP line.  The exact handling of answer generation is detailed in
   * Section 5.3. below.
   *
   * Session descriptions generated by createAnswer must be immediately
   * usable by setLocalDescription; like createOffer, the returned
   * description should reflect the current state of the system.  Because
   * this method may need to inspect the system state to determine the
   * currently available resources, it may need to be implemented as an
   * async operation.
   *
   * Calling this method may do things such as generate new ICE
   * credentials, but does not trigger candidate gathering or change media
   * state.
   *
   */
  final case class CreateAnswer(options: CreateAnswerOptions) extends PeerConnectionMessage

  /**
   * The SetLocalDescription method instructs the PeerConnection to apply
   * the supplied SDP blob as its local configuration.  The type field
   * indicates whether the blob should be processed as an offer,
   * provisional answer, or final answer; offers and answers are checked
   * differently, using the various rules that exist for each SDP line.
   *
   * This API changes the local media state; among other things, it sets
   * up local resources for receiving and decoding media.  In order to
   * successfully handle scenarios where the application wants to offer to
   * change from one media format to a different, incompatible format, the
   * PeerConnection must be able to simultaneously support use of both the
   * old and new local descriptions (e.g. support codecs that exist in
   * both descriptions) until a final answer is received, at which point
   * the PeerConnection can fully adopt the new local description, or roll
   * back to the old description if the remote side denied the change.
   *
   * This API indirectly controls the candidate gathering process.  When a
   * local description is supplied, and the number of transports currently
   * in use does not match the number of transports needed by the local
   * description, the PeerConnection will create transports as needed and
   * begin gathering candidates for them.
   *
   * If setRemoteDescription was previous called with an offer, and
   * setLocalDescription is called with an answer (provisional or final),
   * and the media directions are compatible, and media are available to
   * send, this will result in the starting of media transmission.
   *
   * @see [[http://tools.ietf.org/html/draft-ietf-rtcweb-jsep-08#section-4.1.5]]
   */
  final case class SetLocalDescription(rtcSessionDescription: RTCSessionDescription) extends PeerConnectionMessage

  /**
   * The setRemoteDescription method instructs the PeerConnection to apply
   * the supplied SDP blob as the desired remote configuration.  As in
   * setLocalDescription, the type field of the indicates how the blob
   * should be processed.
   *
   * This API changes the local media state; among other things, it sets
   * up local resources for sending and encoding media.
   *
   * If setLocalDescription was previously called with an offer, and
   * setRemoteDescription is called with an answer (provisional or final),
   * and the media directions are compatible, and media are available to
   * send, this will result in the starting of media transmission.
   *
   * @see [[http://tools.ietf.org/html/draft-ietf-rtcweb-jsep-08#section-4.1.6]]
   */
  final case class SetRemoteDescription(rtcSessionDescription: RTCSessionDescription) extends PeerConnectionMessage

  /**
   * The setConfiguration method allows the global configuration of the
   * PeerConnection, which was initially set by constructor parameters, to
   * be changed during the session.  The effects of this method call
   * depend on when it is invoked, and differ depending on which specific
   * parameters are changed:
   *
   * o  Any changes to the STUN/TURN servers to use affect the next
   * gathering phase.  If gathering has already occurred, this will
   * cause the next call to createOffer to generate new ICE
   * credentials, for the purpose of forcing an ICE restart and kicking
   * off a new gathering phase, in which the new servers will be used.
   * If the ICE candidate pool has a nonzero size, any existing
   * candidates will be discarded, and new candidates will be gathered
   * from the new servers.
   *
   * o  Any changes to the ICE candidate policy also affect the next
   * gathering phase, in similar fashion to the server changes
   * described above.  Note though that changes to the policy have no
   * effect on the candidate pool, because pooled candidates are not
   * surfaced to the application until a gathering phase occurs, and so
   * any necessary filtering can still be done on any pooled
   * candidates.
   *
   * o  Any changes to the ICE candidate pool size take effect
   * immediately; if increased, additional candidates are pre-gathered;
   * if decreased, the now-superfluous candidates are discarded.
   *
   * o  Any changes to the BUNDLE policy take effect immediately, i.e.
   * any future tracks added to the PeerConnection will have their
   * bundle-only state marked accordingly.
   *
   * This call may result in a change to the state of the ICE Agent, and
   * may result in a change to media state if it results in connectivity
   * being established.
   *
   * @see [[http://tools.ietf.org/html/draft-ietf-rtcweb-jsep-08#section-4.1.10]]
   */
  final case class SetConfiguration(configuration: RTCPeerConnection.PeerConnectionConfiguration) extends PeerConnectionMessage

  /**
   * Creates a new RTCDataChannel object with the given label. The RTCDataChannelInit dictionary can be
   * used to configure properties of the underlying channel such as data reliability.
   *
   * When the createDataChannel() method is invoked, the user agent must run the following steps.
   *
   * 1. If the RTCPeerConnection object's RTCPeerConnection signalingState is closed, throw an InvalidStateError exception and abort these steps.
   * 2. Let channel be a newly created RTCDataChannel object.
   * 3. Initialize channel's label attribute to the value of the first argument.
   * 4. If the second (dictionary) argument is present, set channel's ordered, maxPacketLifeTime, maxRetransmits, protocol, negotiated and id attributes to the values of their corresponding dictionary members (if present in the dictionary).
   * 5. If both the maxPacketLifeTime and maxRetransmits attributes are set (not null), then throw a SyntaxError exception and abort these steps.
   * 6. If an attribute, either maxPacketLifeTime or maxRetransmits, has been set to indicate unreliable mode, and that value exceeds the maximum value supported by the user agent, the value must be set to the user agents maximum value.
   * 7. If id attribute is uninitialized (not set via the dictionary), initialize it to a value generated by the user agent, according to the WebRTC DataChannel Protocol specification, and skip to the next step. Otherwise, if the value of the id attribute is taken by an existing RTCDataChannel, throw a ResourceInUse exception and abort these steps.
   * 8. Return channel and continue the following steps in the background.
   * 9. Create channel's associated underlying data transport and configure it according to the relevant properties of channel.
   *
   */
  final case class CreateDataChannel(flow: DataChannelFlow, label: String, dataChannelDict: RTCDataChannelInit = RTCDataChannelInit.DEFAULT) extends PeerConnectionMessage

  /**
   * This type represents a collection of object properties and does not have an explicit JavaScript representation.
   *
   * @param ordered           If set to false, data is allowed to be delivered out of order. The default value of true,
   *                          guarantees that data will be delivered in order.
   * @param maxRetransmits    Limits the number of times a channel will retransmit data if not successfully delivered.
   *                          This value may be clamped if it exceeds the maximum value supported by the user agent.
   * @param maxPacketLifeTime Limits the time during which the channel will retransmit data if not successfully delivered.
   *                          This value may be clamped if it exceeds the maximum value supported by the user agent.
   * @param protocol          Subprotocol name used for this channel.
   * @param negotiated        The default value of false tells the user agent to announce the channel in-band and instruct
   *                          the other peer to dispatch a corresponding RTCDataChannel object. If set to true, it is up to
   *                          the application to negotiate the channel and create a RTCDataChannel object with the same id
   *                          at the other peer.
   * @param id                Overrides the default selection of id for this channel.
   */
  final case class RTCDataChannelInit(
    ordered: Boolean = true,
    maxRetransmits: Short,
    maxPacketLifeTime: FiniteDuration,
    protocol: String = "",
    negotiated: Boolean = false,
    id: Int)

  object ICECandidatePolicy {

    /** All candidates will be gathered and used. **/
    case object all extends ICECandidatePolicy

    /**
     * Candidates with private IP addresses [RFC1918] will be
     * filtered out.  This prevents exposure of internal network details,
     * at the cost of requiring relay usage even for intranet calls, if
     * the NAT does not allow hairpinning as described in [RFC4787],
     * section 6. *
     */
    case object public extends ICECandidatePolicy

    /**
     * All candidates except relay candidates will be filtered out.
     * This obfuscates the location information that might be ascertained
     * by the remote peer from the received candidates.  Depending on how
     * the application deploys its relay servers, this could obfuscate
     * location to a metro or possibly even global level. *
     */
    case object relay extends ICECandidatePolicy

  }

  /**
   * The localDescription method returns a copy of the current local
   * configuration, i.e. what was most recently passed to
   * setLocalDescription, plus any local candidates that have been
   * generated by the ICE Agent.
   *
   * A null object will be returned if the local description has not yet
   * been established, or if the PeerConnection has been closed.
   *
   * @see [[http://tools.ietf.org/html/draft-ietf-rtcweb-jsep-08#section-4.1.7]]
   */
  case object GetLocalDescription extends PeerConnectionMessage

  object BundlePolicy {

    /**
     * The application will BUNDLE all media streams of the same
     * type together.  That is, if there are multiple audio and multiple
     * video MediaStreamTracks attached to a PeerConnection, all but the
     * first audio and video tracks will be marked as bundle-only, and
     * candidates will only be gathered for N media streams, where N is
     * the number of distinct media types.  When talking to a non-BUNDLE-
     * aware endpoint, only the non-bundle-only streams will be
     * negotiated.  This policy balances desire to multiplex with the
     * need to ensure basic audio and video still works in legacy cases.
     * Data channels will be in a separate bundle group.
     */
    case object balanced extends BundlePolicy

    /**
     *
     * max-bundle:  The application will BUNDLE all of its media streams,
     * including data channels, on a single transport.  All streams other
     * than the first will be marked as bundle-only.  This policy aims to
     * minimize candidate gathering and maximize multiplexing, at the
     * cost of less compatibility with legacy endpoints.
     */
    case object `max-bundle` extends BundlePolicy

    /**
     * The application will offer BUNDLE, but mark none of its
     * streams as bundle-only.  This policy will allow all streams to be
     * received by non-BUNDLE-aware endpoints, but require separate
     * candidates to be gathered for each media stream.
     */
    case object `max-compat` extends BundlePolicy

    /**
     * Similar to [[`max-bundle`]], but RTCP candidates
     * are not gathered.  This policy reduces the candidates that must be
     * gathered to the absolute minimum, but will not be compatible with
     * legacy endpoints that do not support RTCP mux.
     */
    case object `max-bundle-and-rtcp-mux` extends BundlePolicy

  }

  object RTCSessionDescription {

    /**
     * "offer" indicates that a description should be parsed as an offer;
     * said description may include many possible media configurations.  A
     * description used as an "offer" may be applied anytime the
     * PeerConnection is in a stable state, or as an update to a previously
     * supplied but unanswered "offer".
     */
    final case class offer(sessionDescription: SessionDescription) extends RTCSessionDescription with HasSDPPayload

    /**
     * "pranswer" indicates that a description should be parsed as an
     * answer, but not a final answer, and so should not result in the
     * freeing of allocated resources.  It may result in the start of media
     * transmission, if the answer does not specify an inactive media
     * direction.  A description used as a "pranswer" may be applied as a
     * response to an "offer", or an update to a previously sent "pranswer".
     */
    final case class pranswer(sessionDescription: SessionDescription) extends RTCSessionDescription with HasSDPPayload

    /**
     * "answer" indicates that a description should be parsed as an answer,
     * the offer-answer exchange should be considered complete, and any
     * resources (decoders, candidates) that are no longer needed can be
     * released.  A description used as an "answer" may be applied as a
     * response to a "offer", or an update to a previously sent "pranswer".
     *
     * The only difference between a provisional and final answer is that
     * the final answer results in the freeing of any unused resources that
     * were allocated as a result of the offer.  As such, the application
     * can use some discretion on whether an answer should be applied as
     * provisional or final, and can change the type of the session
     * description as needed.  For example, in a serial forking scenario, an
     * application may receive multiple "final" answers, one from each
     * remote endpoint.  The application could choose to accept the initial
     * answers as provisional answers, and only apply an answer as final
     * when it receives one that meets its criteria (e.g. a live user
     * instead of voicemail).
     */
    final case class answer(sessionDescription: SessionDescription) extends RTCSessionDescription with HasSDPPayload

    /**
     * "rollback" is a special session description type implying that the
     * state machine should be rolled back to the previous state, as
     * described in Section 4.1.4.2.  The contents MUST be empty.
     */
    case object rollback extends RTCSessionDescription

  }

  object RTCDataChannelInit {
    val DEFAULT = RTCDataChannelInit(ordered = true, maxRetransmits = 10, maxPacketLifeTime = 5 seconds, id = 0)
  }

}

object RTCPeerConnectionFSM {

  sealed trait State

  case object Stable extends State

  case object RemoteOffer extends State

  case object LocalPrAnswer extends State

  case object LocalOffer extends State

  case object RemotePrAnswer extends State

  case object Closed extends State

  case class Data(localDescription: Option[SessionDescription], remoteDescription: Option[SessionDescription])

  val NoData = Data(None, None)

}

/**
 * {{{
 * setRemote(OFFER)               setLocal(PRANSWER)
 * /-----\                               /-----\
 * |     |                               |     |
 * v     |                               v     |
 * +---------------+    |                +---------------+    |
 * |               |----/                |               |----/
 * |               | setLocal(PRANSWER)  |               |
 * |  Remote-Offer |------------------- >| Local-Pranswer|
 * |               |                     |               |
 * |               |                     |               |
 * +---------------+                     +---------------+
 * ^   |                                   |
 * |   | setLocal(ANSWER)                  |
 * setRemote(OFFER)  |                                   |
 * |   V                  setLocal(ANSWER) |
 * +---------------+                            |
 * |               |                            |
 * |               |<---------------------------+
 * |    Stable     |
 * |               |<---------------------------+
 * |               |                            |
 * +---------------+          setRemote(ANSWER) |
 * ^   |                                   |
 * |   | setLocal(OFFER)                   |
 * setRemote(ANSWER) |                                   |
 * |   V                                   |
 * +---------------+                     +---------------+
 * |               |                     |               |
 * |               | setRemote(PRANSWER) |               |
 * |  Local-Offer  |------------------- >|Remote-Pranswer|
 * |               |                     |               |
 * |               |----\                |               |----\
 * +---------------+    |                +---------------+    |
 * ^     |                               ^     |
 * |     |                               |     |
 * \-----/                               \-----/
 * setLocal(OFFER)               setRemote(PRANSWER)
 * }}}
 *
 * @see [[https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-12#section-3.2 JSEP State Machine]]
 */
class RTCPeerConnectionFSM(private val iceAgent: ActorRef) extends FSM[RTCPeerConnectionFSM.State, RTCPeerConnectionFSM.Data] with ActorLogging {

  import RTCPeerConnectionFSM._
  import RTCPeerConnection._

  startWith(Stable, NoData)

  when(Stable) {
    case Event(SetLocalDescription(RTCSessionDescription.offer(localSdp)), NoData) =>
      goto(LocalOffer) using NoData.copy(localDescription = Some(localSdp))
    case Event(SetRemoteDescription(RTCSessionDescription.offer(sdp)), NoData) =>
      goto(RemoteOffer) using NoData.copy(remoteDescription = Some(sdp))
  }

  when(LocalOffer) {
    case Event(SetLocalDescription(RTCSessionDescription.offer(offerSdp)), data) =>
      goto(LocalOffer) using data.copy(localDescription = Some(offerSdp))
    case Event(SetRemoteDescription(RTCSessionDescription.answer(answerSDP)), data) =>
      goto(Stable) using data.copy(remoteDescription = Some(answerSDP))
    case Event(SetRemoteDescription(RTCSessionDescription.pranswer(prAnswerSDP)), data) =>
      goto(RemotePrAnswer) using data.copy(remoteDescription = Some(prAnswerSDP))
  }

  when(RemoteOffer) {
    case Event(SetRemoteDescription(RTCSessionDescription.offer(offerSdp)), data) =>
      goto(RemoteOffer) using data.copy(remoteDescription = Some(offerSdp))
    case Event(SetLocalDescription(RTCSessionDescription.answer(answerSDP)), data) =>
      goto(Stable) using data.copy(localDescription = Some(answerSDP))
    case Event(SetLocalDescription(RTCSessionDescription.pranswer(prAnswerSDP)), data) =>
      goto(LocalPrAnswer) using data.copy(localDescription = Some(prAnswerSDP))
  }

  when(LocalPrAnswer) {
    case Event(SetLocalDescription(RTCSessionDescription.pranswer(prAnswerSDP)), data) =>
      goto(LocalPrAnswer) using data.copy(localDescription = Some(prAnswerSDP))
    case Event(SetLocalDescription(RTCSessionDescription.answer(answerSDP)), data) =>
      goto(Stable) using data.copy(localDescription = Some(answerSDP))
  }

  when(RemotePrAnswer) {
    case Event(SetRemoteDescription(RTCSessionDescription.pranswer(prAnswerSDP)), data) =>
      goto(RemotePrAnswer) using data.copy(remoteDescription = Some(prAnswerSDP))
    case Event(SetRemoteDescription(RTCSessionDescription.answer(answerSDP)), data) =>
      goto(Stable) using data.copy(remoteDescription = Some(answerSDP))
  }

  initialize()

}

class RTCPeerConnection private[jsep] (private val config: PeerConnectionConfiguration, private val iceAgent: ActorRef)(implicit materializer: Materializer) extends Actor {

  require(config.iceCandidatePolicy == ICECandidatePolicy.all, "Only ICECandidatePolicy.all is supported yet.")

  import RTCPeerConnection._

  /** known dataChannels, id to ActorRef */
  private val dataChannels: collection.mutable.Map[Int, (RTCDataChannelInit, Label, ActorRef)] = collection.mutable.Map.empty
  private var channelIdCounter: Int = 0
  private var sessionVersion: Long = 0

  //private val cert = new org.bouncycastle.cert.X509v3CertificateBuilder(new X500Name("wat"), BigInteger.ONE,null, null, null)

  implicit val timeout = Timeout(5 seconds)
  implicit val ex = context.dispatcher

  override def receive: Receive = {

    case CreateOffer(options) =>
      require(!options.RtpDataChannels, "Option RtpDataChannels is not supported")
      val theSender = sender
      (iceAgent ? IceAgent.CreateOffer).mapTo[IceAgent.CreateOfferResponse].onSuccess {
        case CreateOfferResponse(stunCandidates) =>
          val sd = createLocalSessionDescription(1, stunCandidates, iceControlling = true, createSessionId.toString, sessionVersion, IceUfrag("ufrag"), IcePwd("icePwd"), None)
          theSender ! RTCSessionDescription.offer(sd)
      }

    case CreateDataChannel(flow, label, dataChannelInit) =>
      val validChannelId = if (dataChannels.contains(dataChannelInit.id) || dataChannelInit.id == 0) nextChannelId else dataChannelInit.id
      val config = dataChannelInit.copy(id = validChannelId)
      val dataChannelActor = context.actorOf(RTCDataChannel.props(flow, config))
      dataChannels += validChannelId -> ((config, label, dataChannelActor))
  }

  def createLocalSessionDescription(sctpPort: Int, iceCandidates: Vector[Candidate], iceControlling: Boolean, sessionId: String, sessionVersion: Long, ufrag: IceUfrag, pwd: IcePwd, pemCrt: Option[String]): SessionDescription = {
    val socketAddress = InetSocketAddress.createUnresolved("127.0.0.1", 0)
    val origin = Origin(username = None, `sess-id` = sessionId, `sess-version` = sessionVersion, addrtype = AddressType.IP4, `unicast-address` = socketAddress)

    val mediaDescription = {

      val fingerprint = pemCrt.map(createFingerprint)
      val iceSetup = if (iceControlling) Setup(Setup.Role.active) else Setup(Setup.Role.passive)
      val iceMid = MediaStreamIdentifier("data")
      val iceSctpMap = Sctpmap(sctpPort, "webrtc-datachannel", Some(1024L))

      val mediaAttributes: Vector[Attribute] = iceCandidates ++: ufrag +: pwd +: fingerprint.toVector ++:
        Vector(iceSetup, iceMid, iceSctpMap)
      MediaDescription(
        media = Media.application,
        mediaTitle = None,
        //portRange             = PortRange(dataSession.getSctpLocalPort),
        //portRange             = PortRange(udpIceCandidates.collectFirst { case f ⇒ f.connectionAddress.getPort }.getOrElse(0)),
        // TODO: WTF? is 9 magic?
        portRange = PortRange(9),
        protocol = MediaTransportProtocol.`DTLS/SCTP`,
        mediaAttributes = mediaAttributes,
        fmt = Vector(sctpPort.toString),
        connectionInformation = Some(ConnectionData(NetworkType.IN, AddressType.IP4, socketAddress)),
        bandwidthInformation = Vector.empty,
        encryptionKey = None
      )
    }

    SessionDescription(
      origin = origin,
      timings = Vector(Timing(None, None)),
      sessionAttributes = Vector(ValueAttribute("msid-semantic", " WMS")), //, PropertyAttribute("sendrecv")),
      mediaDescriptions = Vector(mediaDescription)
    )

  }

  def createFingerprint(pemCert: String): Fingerprint = {
    val is = new ByteArrayInputStream(pemCert.getBytes(StandardCharsets.UTF_8))
    val x509CertFact: CertificateFactory = CertificateFactory.getInstance("X.509")
    val cert: X509Certificate = x509CertFact.generateCertificate(is).asInstanceOf[X509Certificate]
    val der = cert.getEncoded
    val sha256 = MessageDigest.getInstance("SHA-256")
    sha256.update(der)
    val digest = sha256.digest()
    val hexified = hexify(digest)
    is.close()
    Fingerprint(HashFunction.`sha-256`, hexified)
  }

  def hexify(bytes: Array[Byte]): String = {
    val hexDigits = Array[Char]('0', '1', '2', '3', '4', '5', '6', '7',
      '8', '9', 'A', 'B', 'C', 'D', 'E', 'F')
    val buf = new StringBuffer(bytes.length * 2)
    bytes.zipWithIndex.foreach {
      case (b, i) ⇒
        buf.append(hexDigits((bytes(i) & 0xf0) >> 4))
        buf.append(hexDigits(bytes(i) & 0x0f))
    }
    buf.toString.grouped(2).mkString(":")
  }

  private def createSessionId = Random.nextLong()

  private def nextChannelId: Int = {
    channelIdCounter += 1; channelIdCounter
  }

}


text:
package com.opengamma.analytics.financial.model.finitedifference;

import org.apache.commons.lang.Validate;

import com.opengamma.analytics.math.surface.Surface;

/**
 * $$ This class contains the coefficients terms ($a(t,x), b(t,x), c(x,t)$) that are functions of $t$ and $x$ but NOT $V$ in the PDE. \[ \frac{\partial
 * V}{\partial t}+a(t,x)\frac{\partial^2 V}{\partial x^2}+b(t,x)\frac{\partial V}{\partial x2}+c(t,x)V=0 \] where of course $V$ is also a function of $t$ and
 * $x$ $$
 */
public class ConvectionDiffusionPDE1DStandardCoefficients implements ConvectionDiffusionPDE1DCoefficients {

  private final Surface<Double, Double, Double> _a;
  private final Surface<Double, Double, Double> _b;
  private final Surface<Double, Double, Double> _c;

  public ConvectionDiffusionPDE1DStandardCoefficients(final Surface<Double, Double, Double> a, final Surface<Double, Double, Double> b,
      final Surface<Double, Double, Double> c) {
    Validate.notNull(a, "null a");
    Validate.notNull(b, "null b");
    Validate.notNull(c, "null c");
    _a = a;
    _b = b;
    _c = c;
  }

  public double getA(final double t, final double x) {
    return _a.getZValue(t, x);
  }

  public double getB(final double t, final double x) {
    return _b.getZValue(t, x);
  }

  public double getC(final double t, final double x) {
    return _c.getZValue(t, x);
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + (_a == null ? 0 : _a.hashCode());
    result = prime * result + (_b == null ? 0 : _b.hashCode());
    result = prime * result + (_c == null ? 0 : _c.hashCode());
    return result;
  }

  @Override
  public boolean equals(final Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }
    final ConvectionDiffusionPDE1DStandardCoefficients other = (ConvectionDiffusionPDE1DStandardCoefficients) obj;
    if (_a == null) {
      if (other._a != null) {
        return false;
      }
    } else if (!_a.equals(other._a)) {
      return false;
    }
    if (_b == null) {
      if (other._b != null) {
        return false;
      }
    } else if (!_b.equals(other._b)) {
      return false;
    }
    if (_c == null) {
      if (other._c != null) {
        return false;
      }
    } else if (!_c.equals(other._c)) {
      return false;
    }
    return true;
  }

}


text:
@interface CKAppDelegate : NSObject <NSApplicationDelegate>

@end


text:
package io.aeron.cluster;

import io.aeron.CommonContext;
import io.aeron.Counter;
import io.aeron.archive.Archive;
import io.aeron.archive.ArchiveMarkFile;
import io.aeron.archive.ArchiveThreadingMode;
import io.aeron.archive.client.AeronArchive;
import io.aeron.cluster.client.AeronCluster;
import io.aeron.cluster.client.EgressListener;
import io.aeron.cluster.service.ClientSession;
import io.aeron.cluster.service.Cluster;
import io.aeron.cluster.service.ClusterMarkFile;
import io.aeron.cluster.service.ClusteredServiceContainer;
import io.aeron.driver.MediaDriver;
import io.aeron.driver.MinMulticastFlowControlSupplier;
import io.aeron.driver.ThreadingMode;
import io.aeron.logbuffer.Header;
import org.agrona.CloseHelper;
import org.agrona.DirectBuffer;
import org.agrona.ExpandableArrayBuffer;
import org.agrona.collections.LongHashSet;
import org.agrona.collections.MutableInteger;
import org.agrona.concurrent.EpochClock;
import org.agrona.concurrent.status.AtomicCounter;
import org.agrona.concurrent.status.CountersReader;
import org.junit.*;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Predicate;
import java.util.stream.Stream;

import static io.aeron.Aeron.NULL_VALUE;
import static io.aeron.cluster.RecordingLog.RECORDING_LOG_FILE_NAME;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;

@Ignore
public class StartClusterFromTruncatedRecordingLogTest
{
    private static final long MAX_CATALOG_ENTRIES = 1024;
    private static final int MEMBER_COUNT = 3;
    private static final int MESSAGE_COUNT = 10;
    private static final String MSG = "Hello World!";

    private static final String CLUSTER_MEMBERS = clusterMembersString();
    private static final String LOG_CHANNEL =
        "aeron:udp?term-length=256k|control-mode=manual|control=localhost:55550";
    private static final String ARCHIVE_CONTROL_REQUEST_CHANNEL =
        "aeron:udp?term-length=64k|endpoint=localhost:8010";
    private static final String ARCHIVE_CONTROL_RESPONSE_CHANNEL =
        "aeron:udp?term-length=64k|endpoint=localhost:8020";

    private final AtomicLong timeOffset = new AtomicLong();
    private final EpochClock epochClock = () -> System.currentTimeMillis() + timeOffset.get();

    private final CountDownLatch latchOne = new CountDownLatch(MEMBER_COUNT);
    private final CountDownLatch latchTwo = new CountDownLatch(MEMBER_COUNT - 1);

    private final EchoService[] echoServices = new EchoService[MEMBER_COUNT];
    private final ClusteredMediaDriver[] clusteredMediaDrivers = new ClusteredMediaDriver[MEMBER_COUNT];
    private final ClusteredServiceContainer[] containers = new ClusteredServiceContainer[MEMBER_COUNT];
    private MediaDriver clientMediaDriver;
    private AeronCluster client;

    private final MutableInteger responseCount = new MutableInteger();
    private final EgressListener egressMessageListener =
        (clusterSessionId, timestamp, buffer, offset, length, header) -> responseCount.value++;
    private final ExecutorService executor = Executors.newFixedThreadPool(1);

    @Before
    public void before()
    {
        for (int i = 0; i < MEMBER_COUNT; i++)
        {
            startNode(i, true);
        }
    }

    @After
    public void after() throws InterruptedException
    {
        executor.shutdownNow();

        CloseHelper.close(client);
        CloseHelper.close(clientMediaDriver);

        if (null != clientMediaDriver)
        {
            clientMediaDriver.context().deleteAeronDirectory();
        }

        for (final ClusteredServiceContainer container : containers)
        {
            CloseHelper.close(container);

            if (null != container)
            {
                container.context().deleteDirectory();
            }
        }

        for (final ClusteredMediaDriver driver : clusteredMediaDrivers)
        {
            CloseHelper.close(driver);

            if (null != driver)
            {
                driver.mediaDriver().context().deleteAeronDirectory();
                driver.consensusModule().context().deleteDirectory();
                driver.archive().context().deleteArchiveDirectory();
            }
        }

        if (!executor.awaitTermination(5, TimeUnit.SECONDS))
        {
            System.out.println("warning: not all tasks completed promptly");
        }
    }

    @Test(timeout = 45_000)
    public void shouldBeAbleToStartClusterFromTruncatedRecordingLog() throws Exception
    {
        stopAndStartClusterWithTruncationOfRecordingLog();
        assertClusterIsFunctioningCorrectly();

        stopAndStartClusterWithTruncationOfRecordingLog();
        assertClusterIsFunctioningCorrectly();

        stopAndStartClusterWithTruncationOfRecordingLog();
        assertClusterIsFunctioningCorrectly();

        stopAndStartClusterWithTruncationOfRecordingLog();
        assertClusterIsFunctioningCorrectly();
    }

    private void stopAndStartClusterWithTruncationOfRecordingLog() throws InterruptedException, IOException
    {
        int leaderMemberId;
        while (NULL_VALUE == (leaderMemberId = findLeaderId(NULL_VALUE)))
        {
            TestUtil.checkInterruptedStatus();
            Thread.sleep(1000);
        }

        final int followerMemberIdA = (leaderMemberId + 1) >= MEMBER_COUNT ? 0 : (leaderMemberId + 1);
        final int followerMemberIdB = (followerMemberIdA + 1) >= MEMBER_COUNT ? 0 : (followerMemberIdA + 1);

        takeSnapshot(leaderMemberId);
        awaitSnapshotCounter(leaderMemberId, 1);
        awaitSnapshotCounter(followerMemberIdA, 1);
        awaitSnapshotCounter(followerMemberIdB, 1);

        awaitNeutralCounter(leaderMemberId);
        awaitNeutralCounter(followerMemberIdA);
        awaitNeutralCounter(followerMemberIdB);

        shutdown(leaderMemberId);
        awaitSnapshotCounter(leaderMemberId, 2);
        awaitSnapshotCounter(followerMemberIdA, 2);
        awaitSnapshotCounter(followerMemberIdB, 2);

        stopNode(leaderMemberId);
        stopNode(followerMemberIdA);
        stopNode(followerMemberIdB);

        truncateRecordingLogAndDeleteMarkFiles(leaderMemberId);
        truncateRecordingLogAndDeleteMarkFiles(followerMemberIdA);
        truncateRecordingLogAndDeleteMarkFiles(followerMemberIdB);

        Thread.sleep(1000);

        startNode(leaderMemberId, false);
        startNode(followerMemberIdA, false);
        startNode(followerMemberIdB, false);
    }

    private void assertClusterIsFunctioningCorrectly() throws InterruptedException
    {
        int leaderMemberId;
        while (NULL_VALUE == (leaderMemberId = findLeaderId(NULL_VALUE)))
        {
            TestUtil.checkInterruptedStatus();
            Thread.sleep(1000);
        }

        final int followerMemberIdA = (leaderMemberId + 1) >= MEMBER_COUNT ? 0 : (leaderMemberId + 1);
        final int followerMemberIdB = (leaderMemberId + 1) >= MEMBER_COUNT ? 0 : (leaderMemberId + 1);

        Thread.sleep(1000);

        assertThat(roleOf(followerMemberIdA), is(Cluster.Role.FOLLOWER));
        assertThat(roleOf(followerMemberIdB), is(Cluster.Role.FOLLOWER));

        startClient();

        final ExpandableArrayBuffer msgBuffer = new ExpandableArrayBuffer();
        msgBuffer.putStringWithoutLengthAscii(0, MSG);

        final int initialCount = responseCount.get();
        sendMessages(msgBuffer);
        awaitResponses(MESSAGE_COUNT + initialCount);
    }

    private void truncateRecordingLogAndDeleteMarkFiles(final int index) throws IOException
    {
        final String baseDirName = CommonContext.getAeronDirectoryName() + "-" + index;

        final File consensusModuleDataDir = new File(baseDirName, "consensus-module");
        final File archiveDataDir = new File(baseDirName, "archive");
        final File tmpRecordingFile = new File(baseDirName, RECORDING_LOG_FILE_NAME);
        deleteFile(tmpRecordingFile);
        deleteFile(new File(archiveDataDir, ArchiveMarkFile.FILENAME));
        deleteFile(new File(consensusModuleDataDir, ClusterMarkFile.FILENAME));

        try (RecordingLog recordingLog = new RecordingLog(consensusModuleDataDir))
        {
            final RecordingLog.Entry lastTermEntry = recordingLog.findLastTerm();
            if (null == lastTermEntry)
            {
                throw new IllegalStateException("no term found in recording log");
            }

            try (RecordingLog newRecordingLog = new RecordingLog(new File(baseDirName)))
            {
                newRecordingLog.appendTerm(
                    lastTermEntry.recordingId,
                    lastTermEntry.leadershipTermId,
                    lastTermEntry.termBaseLogPosition,
                    lastTermEntry.timestamp);
                newRecordingLog.commitLogPosition(lastTermEntry.leadershipTermId, lastTermEntry.logPosition);

                appendServiceSnapshot(recordingLog, newRecordingLog, 0);
                appendServiceSnapshot(recordingLog, newRecordingLog, ConsensusModule.Configuration.SERVICE_ID);
            }
        }

        Files.copy(new File(baseDirName).toPath().resolve(RECORDING_LOG_FILE_NAME),
            consensusModuleDataDir.toPath().resolve(RECORDING_LOG_FILE_NAME),
            StandardCopyOption.REPLACE_EXISTING);

        try (RecordingLog copiedRecordingLog = new RecordingLog(consensusModuleDataDir))
        {
            final LongHashSet recordingIds = new LongHashSet();
            copiedRecordingLog.entries().stream().mapToLong((e) -> e.recordingId).forEach(recordingIds::add);
            final Predicate<Path> filterPredicate = (p) -> p.getFileName().toString().endsWith(".rec");

            try (Stream<Path> segments = Files.list(archiveDataDir.toPath()).filter(filterPredicate))
            {
                segments.filter(
                    (p) ->
                    {
                        final String fileName = p.getFileName().toString();
                        final long recording = Long.parseLong(fileName.split("-")[0]);

                        return !recordingIds.contains(recording);
                    })
                    .map(Path::toFile).forEach(this::deleteFile);
            }

            assertTrue(copiedRecordingLog.entries().size() <= 3);
        }
    }

    private void deleteFile(final File file)
    {
        if (file.exists())
        {
            try
            {
                Files.delete(file.toPath());
            }
            catch (final IOException e)
            {
                Assert.fail("Failed to delete file: " + file);
            }
        }

        if (file.exists())
        {
            Assert.fail("Failed to delete file: " + file);
        }
    }

    private void appendServiceSnapshot(
        final RecordingLog existingRecordingLog, final RecordingLog newRecordingLog, final int serviceId)
    {
        final RecordingLog.Entry snapshot = existingRecordingLog.getLatestSnapshot(serviceId);
        newRecordingLog.appendSnapshot(
            snapshot.recordingId,
            snapshot.leadershipTermId,
            snapshot.termBaseLogPosition,
            snapshot.logPosition,
            snapshot.timestamp,
            snapshot.serviceId);
    }

    private void startNode(final int index, final boolean cleanStart)
    {
        if (null == echoServices[index])
        {
            echoServices[index] = new EchoService(latchOne, latchTwo);
        }
        final String baseDirName = CommonContext.getAeronDirectoryName() + "-" + index;
        final String aeronDirName = CommonContext.getAeronDirectoryName() + "-" + index + "-driver";

        final AeronArchive.Context archiveCtx = new AeronArchive.Context()
            .controlRequestChannel(memberSpecificPort(ARCHIVE_CONTROL_REQUEST_CHANNEL, index))
            .controlRequestStreamId(100 + index)
            .controlResponseChannel(memberSpecificPort(ARCHIVE_CONTROL_RESPONSE_CHANNEL, index))
            .controlResponseStreamId(110 + index)
            .aeronDirectoryName(baseDirName);

        clusteredMediaDrivers[index] = ClusteredMediaDriver.launch(
            new MediaDriver.Context()
                .aeronDirectoryName(aeronDirName)
                .threadingMode(ThreadingMode.SHARED)
                .termBufferSparseFile(true)
                .multicastFlowControlSupplier(new MinMulticastFlowControlSupplier())
                .errorHandler(TestUtil.errorHandler(0))
                .dirDeleteOnStart(true),
            new Archive.Context()
                .maxCatalogEntries(MAX_CATALOG_ENTRIES)
                .aeronDirectoryName(aeronDirName)
                .archiveDir(new File(baseDirName, "archive"))
                .controlChannel(archiveCtx.controlRequestChannel())
                .controlStreamId(archiveCtx.controlRequestStreamId())
                .localControlChannel("aeron:ipc?term-length=64k")
                .localControlStreamId(archiveCtx.controlRequestStreamId())
                .recordingEventsChannel("aeron:udp?control-mode=dynamic|control=localhost:803" + index)
                .threadingMode(ArchiveThreadingMode.SHARED)
                .errorHandler(Throwable::printStackTrace)
                .deleteArchiveOnStart(cleanStart),
            new ConsensusModule.Context()
                .epochClock(epochClock)
                .errorHandler(TestUtil.errorHandler(0))
                .clusterMemberId(index)
                .clusterMembers(CLUSTER_MEMBERS)
                .aeronDirectoryName(aeronDirName)
                .clusterDir(new File(baseDirName, "consensus-module"))
                .ingressChannel("aeron:udp?term-length=64k")
                .logChannel(memberSpecificPort(LOG_CHANNEL, index))
                .archiveContext(archiveCtx.clone())
                .deleteDirOnStart(cleanStart));

        containers[index] = ClusteredServiceContainer.launch(
            new ClusteredServiceContainer.Context()
                .aeronDirectoryName(aeronDirName)
                .archiveContext(archiveCtx.clone())
                .clusterDir(new File(baseDirName, "service"))
                .clusteredService(echoServices[index])
                .errorHandler(TestUtil.errorHandler(0)));
    }

    private void stopNode(final int index)
    {
        containers[index].close();
        containers[index] = null;
        clusteredMediaDrivers[index].close();
        clusteredMediaDrivers[index].mediaDriver().context().deleteAeronDirectory();
        clusteredMediaDrivers[index] = null;
    }

    private void startClient()
    {
        if (client != null)
        {
            client.close();
            client = null;
            clientMediaDriver.close();
        }

        final String aeronDirName = CommonContext.getAeronDirectoryName();

        clientMediaDriver = MediaDriver.launch(
            new MediaDriver.Context()
                .threadingMode(ThreadingMode.SHARED)
                .aeronDirectoryName(aeronDirName)
                .dirDeleteOnStart(true));

        client = AeronCluster.connect(
            new AeronCluster.Context()
                .egressListener(egressMessageListener)
                .aeronDirectoryName(aeronDirName)
                .ingressChannel("aeron:udp")
                .clusterMemberEndpoints("0=localhost:20110,1=localhost:20111,2=localhost:20112"));
    }

    private void sendMessages(final ExpandableArrayBuffer msgBuffer)
    {
        for (int i = 0; i < MESSAGE_COUNT; i++)
        {
            while (client.offer(msgBuffer, 0, MSG.length()) < 0)
            {
                TestUtil.checkInterruptedStatus();
                client.pollEgress();
                Thread.yield();
            }

            client.pollEgress();
        }
    }

    private void awaitResponses(final int messageCount)
    {
        while (responseCount.get() < messageCount)
        {
            TestUtil.checkInterruptedStatus();
            Thread.yield();
            client.pollEgress();
        }

        for (int i = 0; i < MEMBER_COUNT; i++)
        {
            while (echoServices[i].messageCount() < messageCount)
            {
                TestUtil.checkInterruptedStatus();
                Thread.yield();
            }
        }
    }

    private static String memberSpecificPort(final String channel, final int memberId)
    {
        return channel.substring(0, channel.length() - 1) + memberId;
    }

    private static String clusterMembersString()
    {
        final StringBuilder builder = new StringBuilder();

        for (int i = 0; i < MEMBER_COUNT; i++)
        {
            builder
                .append(i).append(',')
                .append("localhost:2011").append(i).append(',')
                .append("localhost:2022").append(i).append(',')
                .append("localhost:2033").append(i).append(',')
                .append("localhost:2044").append(i).append(',')
                .append("localhost:801").append(i).append('|');
        }

        builder.setLength(builder.length() - 1);

        return builder.toString();
    }

    static class EchoService extends StubClusteredService
    {
        private volatile int messageCount;
        private final CountDownLatch latchOne;
        private final CountDownLatch latchTwo;

        EchoService(final CountDownLatch latchOne, final CountDownLatch latchTwo)
        {
            this.latchOne = latchOne;
            this.latchTwo = latchTwo;
        }

        int messageCount()
        {
            return messageCount;
        }

        public void onSessionMessage(
            final ClientSession session,
            final long timestampMs,
            final DirectBuffer buffer,
            final int offset,
            final int length,
            final Header header)
        {
            while (session.offer(buffer, offset, length) < 0)
            {
                cluster.idle();
            }

            ++messageCount;

            if (messageCount == MESSAGE_COUNT)
            {
                latchOne.countDown();
            }

            if (messageCount == (MESSAGE_COUNT * 2))
            {
                latchTwo.countDown();
            }
        }
    }

    private int findLeaderId(final int skipMemberId)
    {
        int leaderMemberId = NULL_VALUE;

        for (int i = 0; i < 3; i++)
        {
            if (i == skipMemberId)
            {
                continue;
            }

            final ClusteredMediaDriver driver = clusteredMediaDrivers[i];

            final Cluster.Role role = Cluster.Role.get(
                (int)driver.consensusModule().context().clusterNodeCounter().get());

            if (Cluster.Role.LEADER == role)
            {
                leaderMemberId = driver.consensusModule().context().clusterMemberId();
            }
        }

        return leaderMemberId;
    }

    private Cluster.Role roleOf(final int index)
    {
        final ClusteredMediaDriver driver = clusteredMediaDrivers[index];

        return Cluster.Role.get((int)driver.consensusModule().context().clusterNodeCounter().get());
    }

    private void takeSnapshot(final int index)
    {
        final ClusteredMediaDriver driver = clusteredMediaDrivers[index];
        final CountersReader countersReader = driver.consensusModule().context().aeron().countersReader();
        final AtomicCounter controlToggle = ClusterControl.findControlToggle(countersReader);

        assertNotNull(controlToggle);
        assertTrue(ClusterControl.ToggleState.SNAPSHOT.toggle(controlToggle));
    }

    private void shutdown(final int index)
    {
        final AtomicCounter controlToggle = getControlToggle(index);
        assertNotNull(controlToggle);

        assertTrue(String.valueOf(ClusterControl.ToggleState.get(controlToggle)),
            ClusterControl.ToggleState.SHUTDOWN.toggle(controlToggle));
    }

    private AtomicCounter getControlToggle(final int index)
    {
        final ClusteredMediaDriver driver = clusteredMediaDrivers[index];
        final CountersReader countersReader = driver.consensusModule().context().aeron().countersReader();

        return ClusterControl.findControlToggle(countersReader);
    }

    private void awaitNeutralCounter(final int index)
    {
        final AtomicCounter controlToggle = getControlToggle(index);
        while (ClusterControl.ToggleState.get(controlToggle) != ClusterControl.ToggleState.NEUTRAL)
        {
            TestUtil.checkInterruptedStatus();
            Thread.yield();
        }
    }

    private void awaitSnapshotCounter(final int index, final long value)
    {
        final ClusteredMediaDriver driver = clusteredMediaDrivers[index];
        final Counter snapshotCounter = driver.consensusModule().context().snapshotCounter();

        while (snapshotCounter.get() != value)
        {
            TestUtil.checkInterruptedStatus();
            Thread.yield();
        }
    }
}


text:
package com.gynt.dbf.ui.engine.javascript;

import java.awt.Graphics;

import com.gynt.dbf.ui.engine.UiManaged;
import com.gynt.dbf.ui.engine.UiManager;

public class Group extends UiManaged implements Datum {

	public int maxvalues;
	public int minvalues;
	public String sep;
	public String group;
	public String label;

	public Group(UiManager u, String name) {
		super(u, name);
	}

	@Override
	public String getValue() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void draw(Graphics g) {
		// TODO Auto-generated method stub

	}

}


text:
#ifndef HB_AAT_LAYOUT_OPBD_TABLE_HH
#define HB_AAT_LAYOUT_OPBD_TABLE_HH

#include "hb-aat-layout-common.hh"
#include "hb-open-type.hh"

/*
 * opbd -- Optical Bounds
 * https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6opbd.html
 */
#define HB_AAT_TAG_opbd HB_TAG('o','p','b','d')

namespace AAT {

struct OpticalBounds
{
  bool sanitize (hb_sanitize_context_t *c) const
  {
    TRACE_SANITIZE (this);
    return_trace (likely (c->check_struct (this)));
  }

  FWORD		leftSide;
  FWORD		topSide;
  FWORD		rightSide;
  FWORD		bottomSide;
  public:
  DEFINE_SIZE_STATIC (8);
};

struct opbdFormat0
{
  bool get_bounds (hb_font_t *font, hb_codepoint_t glyph_id,
		   hb_glyph_extents_t *extents, const void *base) const
  {
    const OffsetTo<OpticalBounds> *bounds_offset = lookupTable.get_value (glyph_id, font->face->get_num_glyphs ());
    if (!bounds_offset) return false;
    const OpticalBounds &bounds = base+*bounds_offset;

    if (extents)
      *extents = {
	font->em_scale_x (bounds.leftSide),
	font->em_scale_y (bounds.topSide),
	font->em_scale_x (bounds.rightSide),
	font->em_scale_y (bounds.bottomSide)
      };
    return true;
  }

  bool sanitize (hb_sanitize_context_t *c, const void *base) const
  {
    TRACE_SANITIZE (this);
    return_trace (likely (c->check_struct (this) && lookupTable.sanitize (c, base)));
  }

  protected:
  Lookup<OffsetTo<OpticalBounds>>
		lookupTable;	/* Lookup table associating glyphs with the four
				 * int16 values for the left-side, top-side,
				 * right-side, and bottom-side optical bounds. */
  public:
  DEFINE_SIZE_MIN (2);
};

struct opbdFormat1
{
  bool get_bounds (hb_font_t *font, hb_codepoint_t glyph_id,
		   hb_glyph_extents_t *extents, const void *base) const
  {
    const OffsetTo<OpticalBounds> *bounds_offset = lookupTable.get_value (glyph_id, font->face->get_num_glyphs ());
    if (!bounds_offset) return false;
    const OpticalBounds &bounds = base+*bounds_offset;

    hb_position_t left = 0, top = 0, right = 0, bottom = 0, ignore;
    if (font->get_glyph_contour_point (glyph_id, bounds.leftSide, &left, &ignore) ||
	font->get_glyph_contour_point (glyph_id, bounds.topSide, &ignore, &top) ||
	font->get_glyph_contour_point (glyph_id, bounds.rightSide, &right, &ignore) ||
	font->get_glyph_contour_point (glyph_id, bounds.bottomSide, &ignore, &bottom))
    {
      if (extents)
	*extents = {left, top, right, bottom};
      return true;
    }
    return false;
  }

  bool sanitize (hb_sanitize_context_t *c, const void *base) const
  {
    TRACE_SANITIZE (this);
    return_trace (likely (c->check_struct (this) && lookupTable.sanitize (c, base)));
  }

  protected:
  Lookup<OffsetTo<OpticalBounds>>
		lookupTable;	/* Lookup table associating glyphs with the four
				 * int16 values for the left-side, top-side,
				 * right-side, and bottom-side optical bounds. */
  public:
  DEFINE_SIZE_MIN (2);
};

struct opbd
{
  static constexpr hb_tag_t tableTag = HB_AAT_TAG_opbd;

  bool get_bounds (hb_font_t *font, hb_codepoint_t glyph_id,
		   hb_glyph_extents_t *extents) const
  {
    switch (format)
    {
    case 0: return u.format0.get_bounds (font, glyph_id, extents, this);
    case 1: return u.format1.get_bounds (font, glyph_id, extents, this);
    default:return false;
    }
  }

  bool sanitize (hb_sanitize_context_t *c) const
  {
    TRACE_SANITIZE (this);
    if (unlikely (!c->check_struct (this) || version.major != 1))
      return_trace (false);

    switch (format)
    {
    case 0: return_trace (u.format0.sanitize (c, this));
    case 1: return_trace (u.format1.sanitize (c, this));
    default:return_trace (true);
    }
  }

  protected:
  FixedVersion<>version;	/* Version number of the optical bounds
				 * table (0x00010000 for the current version). */
  HBUINT16	format;		/* Format of the optical bounds table.
				 * Format 0 indicates distance and Format 1 indicates
				 * control point. */
  union {
  opbdFormat0	format0;
  opbdFormat1	format1;
  } u;
  public:
  DEFINE_SIZE_MIN (8);
};

} /* namespace AAT */

#endif /* HB_AAT_LAYOUT_OPBD_TABLE_HH */


text:
@interface SenTestCase : IUTTest {

}

@end