text:
'use strict';
import BaseProvision from '../../provision/BaseProvision';
import Category from '../catalog/Category';
import Datastream from '../catalog/Datastream';

export const PRE_RESOURCE = '/organizations';
export const POST_RESOURCE = '/datamodels';

/**
 * This is a base object for update and delete a IoT Datamodel
 */
export default class DatamodelsHelper extends BaseProvision {
    /**
     * @param {!InternalOpenGateAPI} ogapi - this is ogapi instance
     * @param {!string} organization - Organization where the IoT datamodel was create
     * @param {!object} datamodel - Json object of IoT datamodel to modify or delete.
     */
    constructor(ogapi, organization, datamodel) {
        super(ogapi, PRE_RESOURCE);
        this._isValidString(organization, 'organization', 50);
        this._organization = organization;

        //no modificar este objeto, es solo para comprobaciones
        this._datamodel = datamodel;
        this._name = this._datamodel.name;
        this._isValidString(this._name, 'name of object datamodel', 100);
        this._version = this._datamodel.version;
        this._isValidString(this._version, 'version of object datamodel', 100);
        this._description = this._datamodel.description;
        this._categories = this._datamodel.categories;
        this._identifier = this._datamodel.identifier;
    }

    /**
     * Set the identifier attribute
     * @param {!string} identifier - required field
     * @return {Datamodels}
     */
    withIdentifier(identifier) {
        this._isValidString(identifier, 'identifier', 100);
        this._identifier = identifier;
        return this;
    }

    /**
     * Set the name attribute
     * @param {!string} name - required field
     * @return {DatamodelsHelper}
     */
    withName(name) {
        this._isValidString(name, 'name', 100);
        this._name = name;
        return this;
    }

    /**
     * Set the version attribute
     * @param {!string} version - required field
     * @return {DatamodelsHelper}
     */
    withVersion(version) {
        this._isValidString(version, 'version', 100);
        this._version = version;
        return this;
    }

    /**
     * Set the description attribute
     * @param {string} description
     * @return {DatamodelsHelper}
     */
    withDescription(description) {
        if (description)
            this._isValidString(description, 'description', 100);
        this._description = description;
        return this;
    }

    /**
     * Add a category. If the field datastreams have value, they will add to this category
     * @param {!Object} category
     * @param {Array} datastreams
     * @return {DatamodelsHelper}
     */
    addCategory(category, datastreams) {
        if (this._categories) {
            this._categories.forEach(function (_category, index) {
                if (_category.identifier === category.identifier) {
                    throw new Error('Category ' + category.identifier + ' already exists.');
                }
            });
        } else {
            this._categories = [];
        }
        let _category = new Category(this._ogapi, category.identifier);

        if (category.name) {
            _category.withName(category.name);
        }

        if (datastreams && datastreams.length > 0)
            _category.addDatastreams(datastreams);
        this._categories.push(_category._composeElement());
        return this;
    }

    /**
     * Add a datastream to the indicated category
     * @param {!string} category
     * @param {!object} datastream
     * @return {DatamodelsHelper}
     */
    addDatastream(category, datastream) {
        this._isValidString(category, 'category', 100);
        //Buscamos category y si existe se añade a la lista de categories
        var exists_category = -1;
        this._categories.forEach(function (_category, index) {
            if (_category.identifier === category) {
                exists_category = index;
            }
        });
        if (exists_category === -1) {
            throw new Error('Category ' + category + ' not exists for this datamodel. Use addCategory instead.');
        }
        if (this._categories[exists_category].datastreams) {
            this._categories[exists_category].datastreams.push(datastream);
        } else {
            this._categories[exists_category].datastreams = [datastream];
        }
        return this;
    }

    /**
     * Remove category
     * @param {!string} category
     * @return {DatamodelsHelper}
     */
    removeCategory(category) {
        this._isValidString(category, 'category', 100);
        var remove_index = -1;
        this._categories.forEach(function (_category, index) {
            if (_category.identifier === category)
                remove_index = index;
        });
        if (remove_index === -1) {
            throw new Error('Category ' + category + ' not exists for this datamodel');
        }
        this._categories.splice(remove_index, 1);
        return this;
    }

    /**
     * Remove datastream to the indicated category
     * @param {!string} category
     * @param {!string} id_datastream of datastream
     * @return {DatamodelsHelper}
     */
    removeDatastream(category, id_datastream) {
        this._isValidString(category, 'category', 100);
        let remove_category_index = -1;
        let remove_datastream_index = -1;
        this._categories.forEach(function (_category, category_index) {
            if (_category.identifier === category) {
                remove_category_index = category_index;
                _category.datastreams.forEach(function (datastream, datastream_index) {
                    if (datastream.identifier === id_datastream) {
                        remove_datastream_index = datastream_index;
                    }
                });
            }
        });
        if (remove_category_index === -1) {
            throw new Error('Category ' + category + ' not exists for this datamodel');
        }
        if (remove_datastream_index === -1) {
            throw new Error('Datastream ' + id_datastream + ' not exists for this datamodel and category ' + category);
        }

        this._categories[remove_category_index].datastreams.splice(remove_datastream_index, 1);
        let _category = new Category(this._ogapi, category, this._categories[remove_category_index].datastreams);
        if (this._categories[remove_category_index].name) {
            _category.withName(this._categories[remove_category_index].name);
        }
        this._categories.splice(remove_category_index, 1);
        this._categories.push(_category._composeElement());
        return this;
    }

    /**
     * Update category name
     * @param {!string} old_category name
     * @param {!string} new_category name
     * @return {DatamodelsHelper}
     */
    updateCategory(old_category, new_category) {
        //this._isValidString(new_category, 'new category', 100);
        this._isValidString(old_category, 'old category', 100);
        let old_category_index = -1;
        let new_category_index = -1;
        this._categories.forEach(function (category, index) {
            switch (category.identifier) {
                case old_category:
                    old_category_index = index;
                    break;
                case new_category.identifier:
                    new_category_index = index;
                    break;
            }
        });
        if (new_category_index != -1) {
            throw new Error('New category ' + new_category.identifier + ' already exists.');
        }
        if (old_category_index === -1) {
            throw new Error('Category ' + old_category + ' not exists for this datamodel.');
        }
        this._categories[old_category_index].name = new_category.name;
        return this;
    }

    /**
     * Update datastream to the indicated category
     * @param {!string} category
     * @param {!string} id_datastream of datastream
     * @param {!Object} datastream json object
     * @return {DatamodelsHelper}
     */
    updateDatastream(category, id_datastream, datastream) {
        this._isValidString(category, 'category', 100);
        this._isValidString(id_datastream, 'id datastream', 100);
        if (!datastream || typeof datastream !== 'object') {
            throw new Error('Datastream must be an object');
        }
        let update_category_index = -1;
        let update_datastream_index = -1;
        this._categories.forEach(function (_category, category_index) {
            if (_category.identifier === category) {
                update_category_index = category_index;
                _category.datastreams.forEach(function (_datastream, datastream_index) {
                    if (_datastream.identifier === id_datastream) {
                        update_datastream_index = datastream_index;
                    }
                });
            }
        });
        if (update_category_index === -1) {
            throw new Error('Category ' + category + ' not exists for this datamodel. Create it, use method addCategory instead');
        }
        if (update_datastream_index === -1) {
            throw new Error('Datastream ' + id_datastream + ' not exists for this datamodel and category ' + category + '. Create it, use method addDatastream instead.');
        }
        this._categories[update_category_index].datastreams[update_datastream_index] = datastream;
        return this;
    }

    _composeElement() {
        return {
            'identifier': this._identifier,
            'name': this._name,
            'version': this._version,
            'description': this._description,
            'categories': this._categories
        };
    }

    _buildURL() {
        return this._resource + '/' + this._organization + POST_RESOURCE + '/' + this._identifier;
    }

    /**
     * Create not supported on this builder. Use IoTDatamodelHelper instead.
     */
    create() {
        throw new Error('Create not supported on this builder. Use DatamodelsBuilder instead.');
    }

    _isValidString(string, param_name, max_length) {
        if (typeof string !== 'string' || string.length === 0 || string.length > max_length)
            throw new Error('Parameter ' + param_name + ' must be a string, cannot be empty and has a maximum length of ' + max_length + ' on DatamodelsHelper');
    }
}

redpajama_set_name: RedPajamaGithub


text:
package grails.plugin.lightweightdeploy.connector;

import grails.plugin.lightweightdeploy.Configuration;
import org.eclipse.jetty.server.AbstractConnector;

import java.util.Set;

public abstract class AbstractConnectorFactory {

    private HttpConfiguration configuration;

    public AbstractConnectorFactory(HttpConfiguration configuration) {
        this.configuration = configuration;
    }

    public abstract Set<? extends AbstractConnector> build();

    protected void applyConfiguration(AbstractConnector connector) {
        connector.setAcceptorPriorityOffset(configuration.getAcceptorThreadPriorityOffset());
        connector.setAcceptors(configuration.getAcceptorThreads());
        connector.setAcceptQueueSize(configuration.getAcceptQueueSize());
        connector.setLowResourcesMaxIdleTime(configuration.getLowResourcesMaxIdleTime());
        connector.setMaxBuffers(configuration.getMaxBufferCount());
        connector.setMaxIdleTime(configuration.getMaxIdleTime());
        connector.setRequestBufferSize(configuration.getRequestBufferSize());
        connector.setRequestHeaderSize(configuration.getRequestHeaderBufferSize());
        connector.setResponseBufferSize(configuration.getResponseBufferSize());
        connector.setResponseHeaderSize(configuration.getResponseHeaderBufferSize());
        connector.setReuseAddress(configuration.isReuseAddress());

        // Use X-Forwarded-For header for origin IP
        connector.setForwarded(true);
    }

    protected HttpConfiguration getConfiguration() {
        return configuration;
    }

}


text:
<!doctype html>

    <title>template: lost ref</title>

    <x-test></x-test>

    <template id="x-test">

x-test

      <x-other>
        <template class="noContent">

I am some content!

        </template>
      </x-other>
    </template>


text:
package com.welshare.dao;

import java.util.List;
import java.util.Map;

import com.welshare.model.Following;
import com.welshare.model.User;

public interface FollowingDao extends Dao {

    List<User> getFollowers(User followed);

    List<User> getFollowing(User follower);

    List<User> getCloseFriends(User user);

    Map<String, Following> getFollowingMetaData(User user);

    Following findFollowing(User follower, User followed, boolean lock);

    Following saveFollowing(Following following);

    void deleteFollowing(Following f);

    void updateFollowing(Following following);
}


text:
Squid Search Project
====================

Squid Search is a next-generation search engine going beyond information retrieval and towards information mining and analysis. It leverages machine learning to provide users with deepened insight.

See dedicated website: [http://squid.ucsd.edu](http://squid.ucsd.edu)

Code
====

Here are the folders:

* **cache**:


text:
package server // import "github.com/docker/infrakit/pkg/broker/server"

import (
	"bytes"
	"fmt"
	"net/http"
	"strings"
	"time"

	"github.com/armon/go-radix"
	"github.com/docker/infrakit/pkg/types"
)

// the amount of time to wait when pushing a message to
// a slow client or a client that closed after `range clients` started.
const patience time.Duration = time.Second * 1

type subscription struct {
	topic      string
	exactMatch bool
	ch         chan []byte
}

type event struct {
	topic string
	data  []byte
}

// Broker is the event message broker
type Broker struct {

	// Close this to stop
	stop chan struct{}

	// Close this to stop the run loop
	finish chan struct{}

	// Events are pushed to this channel by the main events-gathering routine
	notifier chan *event

	// New client connections
	newClients chan subscription

	// Closed client connections
	closingClients chan subscription

	// Client connections registry
	clients *radix.Tree

	// how many clients
	count int
}

// NewBroker returns an instance of the broker
func NewBroker() *Broker {
	b := &Broker{
		stop:           make(chan struct{}),
		finish:         make(chan struct{}),
		notifier:       make(chan *event, 1),
		newClients:     make(chan subscription),
		closingClients: make(chan subscription),
		clients:        radix.New(),
	}
	go b.run()
	return b
}

// Stop stops the broker and exits the goroutine
func (b *Broker) Stop() {
	close(b.stop)
}

func clean(topic string) string {
	if len(topic) == 0 || topic == "." {
		return "/"
	}

	if topic[0] != '/' {
		return "/" + topic
	}
	return topic
}

//Check the topic ends with `/`
func checkExactMatch(topic string) bool {
	return strings.LastIndex(topic, "/") != len(topic)-1
}

// Publish publishes a message at the topic
func (b *Broker) Publish(topic string, data interface{}, optionalTimeout ...time.Duration) error {
	any, err := types.AnyValue(data)
	if err != nil {
		return err
	}

	topic = clean(topic)

	if len(optionalTimeout) > 0 {
		select {
		case b.notifier <- &event{topic: topic, data: any.Bytes()}:
		case <-time.After(optionalTimeout[0]):
			return fmt.Errorf("timeout sending %v", topic)
		}
	} else {
		b.notifier <- &event{topic: topic, data: any.Bytes()}
	}

	return nil
}

// ServerHTTP implements the HTTP handler
func (b *Broker) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	defer func() {
		if v := recover(); v != nil {
			log.Warn("broker.ServeHTTP recovered", "err", v)
		}
	}()

	topic := clean(req.URL.Query().Get("topic"))

	// flusher is required for streaming
	flusher, ok := rw.(http.Flusher)
	if !ok {
		http.Error(rw, "Streaming unsupported!", http.StatusInternalServerError)
		return
	}

	rw.Header().Set("Content-Type", "text/event-stream")
	rw.Header().Set("Cache-Control", "no-cache")
	rw.Header().Set("Connection", "keep-alive")
	rw.Header().Set("Access-Control-Allow-Origin", "*")

	// Each connection registers its own message channel with the Broker's connections registry
	messageChan := make(chan []byte)

	// Signal the broker that we have a new connection
	b.newClients <- subscription{topic: topic, exactMatch: checkExactMatch(topic), ch: messageChan}

	// Remove this client from the map of connected clients
	// when this handler exits.
	defer func() {
		b.closingClients <- subscription{topic: topic, ch: messageChan}
	}()

	// Listen to connection close and un-register messageChan
	notify := rw.(http.CloseNotifier).CloseNotify()

	for {
		select {
		case <-b.stop:
			close(b.finish)
			return

		case <-notify:
			return
		default:

			// Write to the ResponseWriter
			// Server Sent Events compatible
			fmt.Fprintf(rw, "data: %s\n\n", <-messageChan)

			// Flush the data immediatly instead of buffering it for later.
			flusher.Flush()
		}
	}
}

func (b *Broker) run() {
	for {
		select {
		case <-b.finish:

			// Disconnect all clients
			b.clients.Walk(
				func(key string, value interface{}) bool {
					chset, ok := value.(map[chan []byte]bool)
					if !ok {
						panic("assert-failed")
					}
					for ch := range chset {
						log.Info("Closing client connection", "key", key, "ch", ch)
						close(ch)
					}
					return false
				})

			log.Info("Broker finished")
			return

		case subscription := <-b.newClients:

			// A new client has connected.
			// Register their message channel
			subs := map[chan []byte]bool{subscription.ch: subscription.exactMatch}
			v, has := b.clients.Get(subscription.topic)
			if has {
				if v, ok := v.(map[chan []byte]bool); !ok {
					panic("assert-failed: not a map of channels")
				} else {
					v[subscription.ch] = subscription.exactMatch
					subs = v
				}
			}

			b.clients.Insert(subscription.topic, subs)
			b.count++
			log.Info("Connected", "topic", subscription.topic, "clients", b.count, "subCh", subscription.ch)

		case subscription := <-b.closingClients:

			// A client has dettached and we want to stop sending messages
			if v, has := b.clients.Get(subscription.topic); has {
				if subs, ok := v.(map[chan []byte]bool); !ok {
					panic("assert-failed: not a map of channels")

				} else {

					delete(subs, subscription.ch)

					if len(subs) == 0 {
						b.clients.Delete(subscription.topic)
					} else {
						b.clients.Insert(subscription.topic, subs)
					}

					b.count--
					log.Info("Disconnected", "topic", subscription.topic, "clients", b.count, "subCh", subscription.ch)
				}
			}

		case event, open := <-b.notifier:

			if !open {
				log.Info("Stopping broker")
				return
			}

			// Remove any \n because it's meaningful in SSE spec.
			// We could use base64 encode, but it hurts interoperability with browser/ javascript clients.
			data := bytes.Replace(event.data, []byte("\n"), nil, -1)

			b.clients.WalkPath(event.topic,

				func(key string, value interface{}) bool {
					chset, ok := value.(map[chan []byte]bool)
					if !ok {
						panic("assert-failed")
					}

					for ch, exact := range chset {
						if exact && event.topic != key {
							return false
						}
						select {
						case ch <- data:
						case <-time.After(patience):
							log.Warn("Skipping client.")
						}
					}
					return false
				})
		}
	}

}


text:
package de.webtwob.mbma.api.enums;

import net.minecraft.util.IStringSerializable;

/**
 * Created by BB20101997 on 18. Mär. 2017.
 */
public enum MachineState implements IStringSerializable {
    IDLE,
    RUNNING,
    WAITING,
    PROBLEM;

    @Override
    public String getName() {
        return super.name().toLowerCase();
    }
}


text:
namespace Migrations.Changesets
{
    using FluentMigrator;
    using FluentMigrator.Runner.Announcers;
    using JetBrains.Annotations;

    [Migration(201402041634), UsedImplicitly]
    public class Migration201402041634 : ForwardOnlyMigration
    {
        public override void Up()
        {
            Create.Table("StatisticData")
                .WithColumn("Id").AsInt32().NotNullable().Identity().PrimaryKey()
                .WithColumn("Date").AsDate().NotNullable()
                .WithColumn("User").AsInt32().NotNullable().ForeignKey("FK_StatisticData_Accounts", "Accounts", "Id")
                .WithColumn("HitsPercents").AsInt32().NotNullable()
                .WithColumn("BattleAvgXp").AsInt32().NotNullable()
                .WithColumn("WinsPercents").AsInt32().NotNullable()
                .WithColumn("Battles").AsInt32().NotNullable()
                .WithColumn("DamageDealt").AsInt32().NotNullable()
                .WithColumn("Frags").AsInt32().NotNullable()
                .WithColumn("MaxXp").AsInt32().NotNullable();

            Create.Table("Periods")
                .WithColumn("Id").AsInt32().NotNullable().Identity().PrimaryKey()
                .WithColumn("DaysCount").AsInt32().NotNullable()
                .WithColumn("Name").AsString();

            Insert.IntoTable("Periods").Row(new
            {
                DaysCount = "7",
                Name = "Неделя"
            }).Row(new
            {
                DaysCount = "31",
                Name = "Месяц"
            }).Row(new
            {
                DaysCount = "92",
                Name = "3 месяца"
            }).Row(new
            {
                DaysCount = "182",
                Name = "Пол года"
            }).Row(new
            {
                DaysCount = "365",
                Name = "Год"
            });

            Create.Table("DynamicData")
                .WithColumn("Id").AsInt32().NotNullable().Identity().PrimaryKey()
                .WithColumn("Period").AsInt32().NotNullable().ForeignKey("FK_DynamicData_Periods", "Periods", "Id")
                .WithColumn("User").AsInt32().NotNullable().ForeignKey("FK_DynamicData_Accounts", "Accounts", "Id")
                .WithColumn("HitsPercents").AsInt32().NotNullable()
                .WithColumn("BattleAvgXp").AsInt32().NotNullable()
                .WithColumn("WinsPercents").AsInt32().NotNullable()
                .WithColumn("Battles").AsInt32().NotNullable()
                .WithColumn("DamageDealt").AsInt32().NotNullable()
                .WithColumn("Frags").AsInt32().NotNullable()
                .WithColumn("MaxXp").AsInt32().NotNullable();

        }
    }
}


text:
package com.alibaba.cobar.server.heartbeat;

import java.io.IOException;
import java.nio.channels.SocketChannel;

import com.alibaba.cobar.CobarServer;
import com.alibaba.cobar.net.factory.BackendConnectionFactory;
import com.alibaba.cobar.server.config.DataNodeConfig;
import com.alibaba.cobar.server.config.DataSourceConfig;

/**
 * @author xianmao.hexm
 */
public class MySQLDetectorFactory extends BackendConnectionFactory {

    public MySQLDetectorFactory() {
        this.idleTimeout = 300 * 1000L;
    }

    public MySQLDetector make(MySQLHeartbeat heartbeat) throws IOException {
        SocketChannel channel = openSocketChannel();
        DataSourceConfig dsc = heartbeat.getSource().getConfig();
        DataNodeConfig dnc = heartbeat.getSource().getNode().getConfig();
        MySQLDetector detector = new MySQLDetector(channel);
        detector.setHost(dsc.getHost());
        detector.setPort(dsc.getPort());
        detector.setUser(dsc.getUser());
        detector.setPassword(dsc.getPassword());
        detector.setSchema(dsc.getDatabase());
        detector.setHeartbeatTimeout(dnc.getHeartbeatTimeout());
        detector.setHeartbeat(heartbeat);
        postConnect(detector, CobarServer.getInstance().getConnector());
        return detector;
    }

}


text:
package org.apache.solr.search;

import static org.apache.solr.update.processor.DistributingUpdateProcessorFactory.DISTRIB_UPDATE_PARAM;

import org.apache.solr.common.SolrException;
import org.noggit.ObjectBuilder;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.update.DirectUpdateHandler2;
import org.apache.solr.update.UpdateLog;
import org.apache.solr.update.UpdateHandler;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

import java.io.File;
import java.io.RandomAccessFile;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.update.DirectUpdateHandler2;
import org.apache.solr.update.UpdateHandler;
import org.apache.solr.update.UpdateLog;
import org.apache.solr.update.processor.DistributedUpdateProcessor.DistribPhase;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.noggit.ObjectBuilder;

public class TestRecovery extends SolrTestCaseJ4 {

  // means that we've seen the leader and have version info (i.e. we are a non-leader replica)
  private static String FROM_LEADER = DistribPhase.FROMLEADER.toString();

  private static int timeout=60;  // acquire timeout in seconds.  change this to a huge number when debugging to prevent threads from advancing.

  // TODO: fix this test to not require FSDirectory
  static String savedFactory;

  @BeforeClass
  public static void beforeClass() throws Exception {
    savedFactory = System.getProperty("solr.DirectoryFactory");
    System.setProperty("solr.directoryFactory", "org.apache.solr.core.MockFSDirectoryFactory");
    initCore("solrconfig-tlog.xml","schema15.xml");
  }

  @AfterClass
  public static void afterClass() {
    if (savedFactory == null) {
      System.clearProperty("solr.directoryFactory");
    } else {
      System.setProperty("solr.directoryFactory", savedFactory);
    }
  }

  // since we make up fake versions in these tests, we can get messed up by a DBQ with a real version
  // since Solr can think following updates were reordered.
  @Override
  public void clearIndex() {
    try {
      deleteByQueryAndGetVersion("*:*", params("_version_", Long.toString(-Long.MAX_VALUE), DISTRIB_UPDATE_PARAM,FROM_LEADER));
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  @Test
  public void testLogReplay() throws Exception {
    try {

      DirectUpdateHandler2.commitOnClose = false;
      final Semaphore logReplay = new Semaphore(0);
      final Semaphore logReplayFinish = new Semaphore(0);

      UpdateLog.testing_logReplayHook = new Runnable() {
        @Override
        public void run() {
          try {
            assertTrue(logReplay.tryAcquire(timeout, TimeUnit.SECONDS));
          } catch (Exception e) {
            throw new RuntimeException(e);
          }
        }
      };

      UpdateLog.testing_logReplayFinishHook = new Runnable() {
        @Override
        public void run() {
          logReplayFinish.release();
        }
      };

      clearIndex();
      assertU(commit());

      Deque<Long> versions = new ArrayDeque<Long>();
      versions.addFirst(addAndGetVersion(sdoc("id", "A1"), null));
      versions.addFirst(addAndGetVersion(sdoc("id", "A11"), null));
      versions.addFirst(addAndGetVersion(sdoc("id", "A12"), null));
      versions.addFirst(deleteByQueryAndGetVersion("id:A11", null));
      versions.addFirst(addAndGetVersion(sdoc("id", "A13"), null));

      assertJQ(req("q","*:*"),"/response/numFound==0");

      assertJQ(req("qt","/get", "getVersions",""+versions.size()) ,"/versions==" + versions);

      h.close();
      createCore();
      // Solr should kick this off now
      // h.getCore().getUpdateHandler().getUpdateLog().recoverFromLog();

      // verify that previous close didn't do a commit
      // recovery should be blocked by our hook
      assertJQ(req("q","*:*") ,"/response/numFound==0");

      // make sure we can still access versions after a restart
      assertJQ(req("qt","/get", "getVersions",""+versions.size()),"/versions==" + versions);

      // unblock recovery
      logReplay.release(1000);

      // make sure we can still access versions during recovery
      assertJQ(req("qt","/get", "getVersions",""+versions.size()),"/versions==" + versions);

      // wait until recovery has finished
      assertTrue(logReplayFinish.tryAcquire(timeout, TimeUnit.SECONDS));

      assertJQ(req("q","*:*") ,"/response/numFound==3");

      // make sure we can still access versions after recovery
      assertJQ(req("qt","/get", "getVersions",""+versions.size()) ,"/versions==" + versions);

      assertU(adoc("id","A2"));
      assertU(adoc("id","A3"));
      assertU(delI("A2"));
      assertU(adoc("id","A4"));

      assertJQ(req("q","*:*") ,"/response/numFound==3");

      h.close();
      createCore();
      // Solr should kick this off now
      // h.getCore().getUpdateHandler().getUpdateLog().recoverFromLog();

      // wait until recovery has finished
      assertTrue(logReplayFinish.tryAcquire(timeout, TimeUnit.SECONDS));
      assertJQ(req("q","*:*") ,"/response/numFound==5");
      assertJQ(req("q","id:A2") ,"/response/numFound==0");

      // no updates, so insure that recovery does not run
      h.close();
      int permits = logReplay.availablePermits();
      createCore();
      // Solr should kick this off now
      // h.getCore().getUpdateHandler().getUpdateLog().recoverFromLog();

      assertJQ(req("q","*:*") ,"/response/numFound==5");
      Thread.sleep(100);
      assertEquals(permits, logReplay.availablePermits()); // no updates, so insure that recovery didn't run

      assertEquals(UpdateLog.State.ACTIVE, h.getCore().getUpdateHandler().getUpdateLog().getState());

    } finally {
      DirectUpdateHandler2.commitOnClose = true;
      UpdateLog.testing_logReplayHook = null;
      UpdateLog.testing_logReplayFinishHook = null;
    }

  }

  @Test
  public void testBuffering() throws Exception {

    DirectUpdateHandler2.commitOnClose = false;
    final Semaphore logReplay = new Semaphore(0);
    final Semaphore logReplayFinish = new Semaphore(0);

    UpdateLog.testing_logReplayHook = new Runnable() {
      @Override
      public void run() {
        try {
          assertTrue(logReplay.tryAcquire(timeout, TimeUnit.SECONDS));
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
    };

    UpdateLog.testing_logReplayFinishHook = new Runnable() {
      @Override
      public void run() {
        logReplayFinish.release();
      }
    };

    SolrQueryRequest req = req();
    UpdateHandler uhandler = req.getCore().getUpdateHandler();
    UpdateLog ulog = uhandler.getUpdateLog();

    try {
      clearIndex();
      assertU(commit());

      assertEquals(UpdateLog.State.ACTIVE, ulog.getState());
      ulog.bufferUpdates();
      assertEquals(UpdateLog.State.BUFFERING, ulog.getState());
      Future<UpdateLog.RecoveryInfo> rinfoFuture = ulog.applyBufferedUpdates();
      assertTrue(rinfoFuture == null);
      assertEquals(UpdateLog.State.ACTIVE, ulog.getState());

      ulog.bufferUpdates();
      assertEquals(UpdateLog.State.BUFFERING, ulog.getState());

      // simulate updates from a leader
      updateJ(jsonAdd(sdoc("id","B1", "_version_","1010")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      updateJ(jsonAdd(sdoc("id","B11", "_version_","1015")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      updateJ(jsonDelQ("id:B1 id:B11 id:B2 id:B3"), params(DISTRIB_UPDATE_PARAM,FROM_LEADER, "_version_","-1017"));
      updateJ(jsonAdd(sdoc("id","B2", "_version_","1020")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      updateJ(jsonAdd(sdoc("id","B3", "_version_","1030")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      deleteAndGetVersion("B1", params(DISTRIB_UPDATE_PARAM,FROM_LEADER, "_version_","-2010"));

      assertJQ(req("qt","/get", "getVersions","6")
          ,"=={'versions':[-2010,1030,1020,-1017,1015,1010]}"
      );

      assertU(commit());

      assertJQ(req("qt","/get", "getVersions","6")
          ,"=={'versions':[-2010,1030,1020,-1017,1015,1010]}"
      );

      // updates should be buffered, so we should not see any results yet.
      assertJQ(req("q", "*:*")
          , "/response/numFound==0"
      );

      // real-time get should also not show anything (this could change in the future,
      // but it's currently used for validating version numbers too, so it would
      // be bad for updates to be visible if we're just buffering.
      assertJQ(req("qt","/get", "id","B3")
          ,"=={'doc':null}"
      );

      rinfoFuture = ulog.applyBufferedUpdates();
      assertTrue(rinfoFuture != null);

      assertEquals(UpdateLog.State.APPLYING_BUFFERED, ulog.getState());

      logReplay.release(1000);

      UpdateLog.RecoveryInfo rinfo = rinfoFuture.get();
      assertEquals(UpdateLog.State.ACTIVE, ulog.getState());

      assertJQ(req("qt","/get", "getVersions","6")
          ,"=={'versions':[-2010,1030,1020,-1017,1015,1010]}"
      );

      assertJQ(req("q", "*:*")
          , "/response/numFound==2"
      );

      // move back to recovering
      ulog.bufferUpdates();
      assertEquals(UpdateLog.State.BUFFERING, ulog.getState());

      Long ver = getVer(req("qt","/get", "id","B3"));
      assertEquals(1030L, ver.longValue());

      // add a reordered doc that shouldn't overwrite one in the index
      updateJ(jsonAdd(sdoc("id","B3", "_version_","3")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));

      // reorder two buffered updates
      updateJ(jsonAdd(sdoc("id","B4", "_version_","1040")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      deleteAndGetVersion("B4", params(DISTRIB_UPDATE_PARAM,FROM_LEADER, "_version_","-940"));   // this update should not take affect
      updateJ(jsonAdd(sdoc("id","B6", "_version_","1060")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      updateJ(jsonAdd(sdoc("id","B5", "_version_","1050")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      updateJ(jsonAdd(sdoc("id","B8", "_version_","1080")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));

      // test that delete by query is at least buffered along with everything else so it will delete the
      // currently buffered id:8 (even if it doesn't currently support versioning)
      updateJ("{\"delete\": { \"query\":\"id:B2 OR id:B8\" }}", params(DISTRIB_UPDATE_PARAM,FROM_LEADER, "_version_","-3000"));

      assertJQ(req("qt","/get", "getVersions","13")
          ,"=={'versions':[-3000,1080,1050,1060,-940,1040,3,-2010,1030,1020,-1017,1015,1010]}"  // the "3" appears because versions aren't checked while buffering
      );

      logReplay.drainPermits();
      rinfoFuture = ulog.applyBufferedUpdates();
      assertTrue(rinfoFuture != null);
      assertEquals(UpdateLog.State.APPLYING_BUFFERED, ulog.getState());

      // apply a single update
      logReplay.release(1);

      // now add another update
      updateJ(jsonAdd(sdoc("id","B7", "_version_","1070")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));

      // a reordered update that should be dropped
      deleteAndGetVersion("B5", params(DISTRIB_UPDATE_PARAM,FROM_LEADER, "_version_","-950"));

      deleteAndGetVersion("B6", params(DISTRIB_UPDATE_PARAM,FROM_LEADER, "_version_","-2060"));

      logReplay.release(1000);
      UpdateLog.RecoveryInfo recInfo = rinfoFuture.get();

      assertJQ(req("q", "*:*", "sort","id asc", "fl","id,_version_")
          , "/response/docs==["
                           + "{'id':'B3','_version_':1030}"
                           + ",{'id':'B4','_version_':1040}"
                           + ",{'id':'B5','_version_':1050}"
                           + ",{'id':'B7','_version_':1070}"
                           +"]"
      );

      assertEquals(1, recInfo.deleteByQuery);

      assertEquals(UpdateLog.State.ACTIVE, ulog.getState()); // leave each test method in a good state
    } finally {
      DirectUpdateHandler2.commitOnClose = true;
      UpdateLog.testing_logReplayHook = null;
      UpdateLog.testing_logReplayFinishHook = null;

      req().close();
    }

  }

  @Test
  public void testDropBuffered() throws Exception {

    DirectUpdateHandler2.commitOnClose = false;
    final Semaphore logReplay = new Semaphore(0);
    final Semaphore logReplayFinish = new Semaphore(0);

    UpdateLog.testing_logReplayHook = new Runnable() {
      @Override
      public void run() {
        try {
          assertTrue(logReplay.tryAcquire(timeout, TimeUnit.SECONDS));
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
    };

    UpdateLog.testing_logReplayFinishHook = new Runnable() {
      @Override
      public void run() {
        logReplayFinish.release();
      }
    };

    SolrQueryRequest req = req();
    UpdateHandler uhandler = req.getCore().getUpdateHandler();
    UpdateLog ulog = uhandler.getUpdateLog();

    try {
      clearIndex();
      assertU(commit());

      assertEquals(UpdateLog.State.ACTIVE, ulog.getState());
      ulog.bufferUpdates();
      assertEquals(UpdateLog.State.BUFFERING, ulog.getState());
      Future<UpdateLog.RecoveryInfo> rinfoFuture = ulog.applyBufferedUpdates();
      assertTrue(rinfoFuture == null);
      assertEquals(UpdateLog.State.ACTIVE, ulog.getState());

      ulog.bufferUpdates();
      assertEquals(UpdateLog.State.BUFFERING, ulog.getState());

      // simulate updates from a leader
      updateJ(jsonAdd(sdoc("id","C1", "_version_","101")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      updateJ(jsonAdd(sdoc("id","C2", "_version_","102")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      updateJ(jsonAdd(sdoc("id","C3", "_version_","103")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));

      assertTrue(ulog.dropBufferedUpdates());
      ulog.bufferUpdates();
      updateJ(jsonAdd(sdoc("id", "C4", "_version_","104")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      updateJ(jsonAdd(sdoc("id", "C5", "_version_","105")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));

      logReplay.release(1000);
      rinfoFuture = ulog.applyBufferedUpdates();
      UpdateLog.RecoveryInfo rinfo = rinfoFuture.get();
      assertEquals(2, rinfo.adds);

      assertJQ(req("qt","/get", "getVersions","2")
          ,"=={'versions':[105,104]}"
      );

      // this time add some docs first before buffering starts (so tlog won't be at pos 0)
      updateJ(jsonAdd(sdoc("id","C100", "_version_","200")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      updateJ(jsonAdd(sdoc("id","C101", "_version_","201")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));

      ulog.bufferUpdates();
      updateJ(jsonAdd(sdoc("id","C103", "_version_","203")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      updateJ(jsonAdd(sdoc("id","C104", "_version_","204")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));

      assertTrue(ulog.dropBufferedUpdates());
      ulog.bufferUpdates();
      updateJ(jsonAdd(sdoc("id","C105", "_version_","205")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      updateJ(jsonAdd(sdoc("id","C106", "_version_","206")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));

      rinfoFuture = ulog.applyBufferedUpdates();
      rinfo = rinfoFuture.get();
      assertEquals(2, rinfo.adds);

      assertJQ(req("q", "*:*", "sort","_version_ asc", "fl","id,_version_")
          , "/response/docs==["
          + "{'id':'C4','_version_':104}"
          + ",{'id':'C5','_version_':105}"
          + ",{'id':'C100','_version_':200}"
          + ",{'id':'C101','_version_':201}"
          + ",{'id':'C105','_version_':205}"
          + ",{'id':'C106','_version_':206}"
          +"]"
      );

      assertJQ(req("qt","/get", "getVersions","6")
          ,"=={'versions':[206,205,201,200,105,104]}"
      );

      ulog.bufferUpdates();
      assertEquals(UpdateLog.State.BUFFERING, ulog.getState());
      updateJ(jsonAdd(sdoc("id","C301", "_version_","998")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      updateJ(jsonAdd(sdoc("id","C302", "_version_","999")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      assertTrue(ulog.dropBufferedUpdates());

      // make sure we can overwrite with a lower version
      // TODO: is this functionality needed?
      updateJ(jsonAdd(sdoc("id","C301", "_version_","301")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      updateJ(jsonAdd(sdoc("id","C302", "_version_","302")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));

      assertU(commit());

      assertJQ(req("qt","/get", "getVersions","2")
          ,"=={'versions':[302,301]}"
      );

      assertJQ(req("q", "*:*", "sort","_version_ desc", "fl","id,_version_", "rows","2")
          , "/response/docs==["
          + "{'id':'C302','_version_':302}"
          + ",{'id':'C301','_version_':301}"
          +"]"
      );

      updateJ(jsonAdd(sdoc("id","C2", "_version_","302")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));

      assertEquals(UpdateLog.State.ACTIVE, ulog.getState()); // leave each test method in a good state
    } finally {
      DirectUpdateHandler2.commitOnClose = true;
      UpdateLog.testing_logReplayHook = null;
      UpdateLog.testing_logReplayFinishHook = null;

      req().close();
    }

  }

  // we need to make sure that the log is informed of a core reload
  @Test
  public void testReload() throws Exception {
    long version = addAndGetVersion(sdoc("id","reload1") , null);

    h.reload();

    version = addAndGetVersion(sdoc("id","reload1", "_version_", Long.toString(version)), null);

    assertU(commit());

    // if we try the optimistic concurrency again, the tlog lookup maps should be clear
    // and we should go to the index to check the version.  This indirectly tests that
    // the update log was informed of the reload.  See SOLR-4858

    version = addAndGetVersion(sdoc("id","reload1", "_version_", Long.toString(version)), null);

    // a deleteByQuery currently forces open a new realtime reader via the update log.
    // This also tests that the update log was informed of the new udpate handler.

    deleteByQueryAndGetVersion("foo_t:hownowbrowncow", null);

    version = addAndGetVersion(sdoc("id","reload1", "_version_", Long.toString(version)), null);

    // if the update log was not informed of the new update handler, then the old core will
    // incorrectly be used for some of the operations above and opened searchers
    // will never be closed.  This used to cause the test framework to fail because of unclosed directory checks.
    // SolrCore.openNewSearcher was modified to throw an error if the core is closed, resulting in
    // a faster fail.
  }

    @Test
  public void testBufferingFlags() throws Exception {

    DirectUpdateHandler2.commitOnClose = false;
    final Semaphore logReplayFinish = new Semaphore(0);

    UpdateLog.testing_logReplayFinishHook = new Runnable() {
      @Override
      public void run() {
        logReplayFinish.release();
      }
    };

    SolrQueryRequest req = req();
    UpdateHandler uhandler = req.getCore().getUpdateHandler();
    UpdateLog ulog = uhandler.getUpdateLog();

    try {
      clearIndex();
      assertU(commit());

      assertEquals(UpdateLog.State.ACTIVE, ulog.getState());
      ulog.bufferUpdates();

      // simulate updates from a leader
      updateJ(jsonAdd(sdoc("id","Q1", "_version_","101")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      updateJ(jsonAdd(sdoc("id","Q2", "_version_","102")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      updateJ(jsonAdd(sdoc("id","Q3", "_version_","103")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      assertEquals(UpdateLog.State.BUFFERING, ulog.getState());

      req.close();
      h.close();
      createCore();

      req = req();
      uhandler = req.getCore().getUpdateHandler();
      ulog = uhandler.getUpdateLog();

      logReplayFinish.acquire();  // wait for replay to finish

      assertTrue((ulog.getStartingOperation() & UpdateLog.FLAG_GAP) != 0);   // since we died while buffering, we should see this last

      //
      // Try again to ensure that the previous log replay didn't wipe out our flags
      //

      req.close();
      h.close();
      createCore();

      req = req();
      uhandler = req.getCore().getUpdateHandler();
      ulog = uhandler.getUpdateLog();

      assertTrue((ulog.getStartingOperation() & UpdateLog.FLAG_GAP) != 0);

      // now do some normal non-buffered adds
      updateJ(jsonAdd(sdoc("id","Q4", "_version_","114")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      updateJ(jsonAdd(sdoc("id","Q5", "_version_","115")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      updateJ(jsonAdd(sdoc("id","Q6", "_version_","116")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      assertU(commit());

      req.close();
      h.close();
      createCore();

      req = req();
      uhandler = req.getCore().getUpdateHandler();
      ulog = uhandler.getUpdateLog();

      assertTrue((ulog.getStartingOperation() & UpdateLog.FLAG_GAP) == 0);

      ulog.bufferUpdates();
      // simulate receiving no updates
      ulog.applyBufferedUpdates();
      updateJ(jsonAdd(sdoc("id","Q7", "_version_","117")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER)); // do another add to make sure flags are back to normal

      req.close();
      h.close();
      createCore();

      req = req();
      uhandler = req.getCore().getUpdateHandler();
      ulog = uhandler.getUpdateLog();

      assertTrue((ulog.getStartingOperation() & UpdateLog.FLAG_GAP) == 0); // check flags on Q7

      logReplayFinish.acquire();
      assertEquals(UpdateLog.State.ACTIVE, ulog.getState()); // leave each test method in a good state
    } finally {
      DirectUpdateHandler2.commitOnClose = true;
      UpdateLog.testing_logReplayHook = null;
      UpdateLog.testing_logReplayFinishHook = null;

      req().close();
    }

  }

  // make sure that on a restart, versions don't start too low
  @Test
  public void testVersionsOnRestart() throws Exception {
    clearIndex();
    assertU(commit());

    assertU(adoc("id","D1", "val_i","1"));
    assertU(adoc("id","D2", "val_i","1"));
    assertU(commit());
    long v1 = getVer(req("q","id:D1"));
    long v1a = getVer(req("q","id:D2"));

    h.close();
    createCore();

    assertU(adoc("id","D1", "val_i","2"));
    assertU(commit());
    long v2 = getVer(req("q","id:D1"));

    assert(v2 > v1);

    assertJQ(req("qt","/get", "getVersions","2")
        ,"/versions==[" + v2 + "," + v1a + "]"
    );

  }

  // make sure that log isn't needlessly replayed after a clean shutdown
  @Test
  public void testCleanShutdown() throws Exception {
    DirectUpdateHandler2.commitOnClose = true;
    final Semaphore logReplay = new Semaphore(0);
    final Semaphore logReplayFinish = new Semaphore(0);

    UpdateLog.testing_logReplayHook = new Runnable() {
      @Override
      public void run() {
        try {
          assertTrue(logReplay.tryAcquire(timeout, TimeUnit.SECONDS));
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
    };

    UpdateLog.testing_logReplayFinishHook = new Runnable() {
      @Override
      public void run() {
        logReplayFinish.release();
      }
    };

    SolrQueryRequest req = req();
    UpdateHandler uhandler = req.getCore().getUpdateHandler();
    UpdateLog ulog = uhandler.getUpdateLog();

    try {
      clearIndex();
      assertU(commit());

      assertU(adoc("id","E1", "val_i","1"));
      assertU(adoc("id","E2", "val_i","1"));

      // set to a high enough number so this test won't hang on a bug
      logReplay.release(10);

      h.close();
      createCore();

      // make sure the docs got committed
      assertJQ(req("q","*:*"),"/response/numFound==2");

      // make sure no replay happened
      assertEquals(10, logReplay.availablePermits());

    } finally {
      DirectUpdateHandler2.commitOnClose = true;
      UpdateLog.testing_logReplayHook = null;
      UpdateLog.testing_logReplayFinishHook = null;

      req().close();
    }
  }

  private void addDocs(int nDocs, int start, LinkedList<Long> versions) throws Exception {
    for (int i=0; i<nDocs; i++) {
      versions.addFirst( addAndGetVersion( sdoc("id",Integer.toString(start + nDocs)) , null) );
    }
  }

  @Test
  public void testRemoveOldLogs() throws Exception {
    try {
      DirectUpdateHandler2.commitOnClose = false;
      final Semaphore logReplay = new Semaphore(0);
      final Semaphore logReplayFinish = new Semaphore(0);

      UpdateLog.testing_logReplayHook = new Runnable() {
        @Override
        public void run() {
          try {
            assertTrue(logReplay.tryAcquire(timeout, TimeUnit.SECONDS));
          } catch (Exception e) {
            throw new RuntimeException(e);
          }
        }
      };

      UpdateLog.testing_logReplayFinishHook = new Runnable() {
        @Override
        public void run() {
          logReplayFinish.release();
        }
      };

      clearIndex();
      assertU(commit());

      UpdateLog ulog = h.getCore().getUpdateHandler().getUpdateLog();
      File logDir = new File(h.getCore().getUpdateHandler().getUpdateLog().getLogDir());

      h.close();

      String[] files = ulog.getLogList(logDir);
      for (String file : files) {
        new File(logDir, file).delete();
      }

      assertEquals(0, ulog.getLogList(logDir).length);

      createCore();

      int start = 0;
      int maxReq = 50;

      LinkedList<Long> versions = new LinkedList<Long>();
      addDocs(10, start, versions); start+=10;
      assertJQ(req("qt","/get", "getVersions",""+maxReq), "/versions==" + versions.subList(0,Math.min(maxReq,start)));
      assertU(commit());
      assertJQ(req("qt","/get", "getVersions",""+maxReq), "/versions==" + versions.subList(0,Math.min(maxReq,start)));

      addDocs(10, start, versions);  start+=10;
      assertJQ(req("qt","/get", "getVersions",""+maxReq), "/versions==" + versions.subList(0,Math.min(maxReq,start)));
      assertU(commit());
      assertJQ(req("qt","/get", "getVersions",""+maxReq), "/versions==" + versions.subList(0,Math.min(maxReq,start)));

      assertEquals(2, ulog.getLogList(logDir).length);

      addDocs(105, start, versions);  start+=105;
      assertJQ(req("qt","/get", "getVersions",""+maxReq), "/versions==" + versions.subList(0,Math.min(maxReq,start)));
      assertU(commit());
      assertJQ(req("qt","/get", "getVersions",""+maxReq), "/versions==" + versions.subList(0,Math.min(maxReq,start)));

      // previous two logs should be gone now
      assertEquals(1, ulog.getLogList(logDir).length);

      addDocs(1, start, versions);  start+=1;
      h.close();
      createCore();      // trigger recovery, make sure that tlog reference handling is correct

      // test we can get versions while replay is happening
      assertJQ(req("qt","/get", "getVersions",""+maxReq), "/versions==" + versions.subList(0,Math.min(maxReq,start)));

      logReplay.release(1000);
      assertTrue(logReplayFinish.tryAcquire(timeout, TimeUnit.SECONDS));

      assertJQ(req("qt","/get", "getVersions",""+maxReq), "/versions==" + versions.subList(0,Math.min(maxReq,start)));

      addDocs(105, start, versions);  start+=105;
      assertJQ(req("qt","/get", "getVersions",""+maxReq), "/versions==" + versions.subList(0,Math.min(maxReq,start)));
      assertU(commit());
      assertJQ(req("qt","/get", "getVersions",""+maxReq), "/versions==" + versions.subList(0,Math.min(maxReq,start)));

      // previous logs should be gone now
      assertEquals(1, ulog.getLogList(logDir).length);

      //
      // test that a corrupt tlog file doesn't stop us from coming up, or seeing versions before that tlog file.
      //
      addDocs(1, start, new LinkedList<Long>()); // don't add this to the versions list because we are going to lose it...
      h.close();
      files = ulog.getLogList(logDir);
      Arrays.sort(files);
      RandomAccessFile raf = new RandomAccessFile(new File(logDir, files[files.length-1]), "rw");
      raf.writeChars("This is a trashed log file that really shouldn't work at all, but we'll see...");
      raf.close();

      ignoreException("Failure to open existing");
      createCore();
      // we should still be able to get the list of versions (not including the trashed log file)
      assertJQ(req("qt", "/get", "getVersions", "" + maxReq), "/versions==" + versions.subList(0, Math.min(maxReq, start)));
      resetExceptionIgnores();

    } finally {
      DirectUpdateHandler2.commitOnClose = true;
      UpdateLog.testing_logReplayHook = null;
      UpdateLog.testing_logReplayFinishHook = null;
    }
  }

  //
  // test that a partially written last tlog entry (that will cause problems for both reverse reading and for
  // log replay) doesn't stop us from coming up, and from recovering the documents that were not cut off.
  //
  @Test
  public void testTruncatedLog() throws Exception {
    try {
      DirectUpdateHandler2.commitOnClose = false;
      final Semaphore logReplay = new Semaphore(0);
      final Semaphore logReplayFinish = new Semaphore(0);

      UpdateLog.testing_logReplayHook = new Runnable() {
        @Override
        public void run() {
          try {
            assertTrue(logReplay.tryAcquire(timeout, TimeUnit.SECONDS));
          } catch (Exception e) {
            throw new RuntimeException(e);
          }
        }
      };

      UpdateLog.testing_logReplayFinishHook = new Runnable() {
        @Override
        public void run() {
          logReplayFinish.release();
        }
      };

      UpdateLog ulog = h.getCore().getUpdateHandler().getUpdateLog();
      File logDir = new File(h.getCore().getUpdateHandler().getUpdateLog().getLogDir());

      clearIndex();
      assertU(commit());

      assertU(adoc("id","F1"));
      assertU(adoc("id","F2"));
      assertU(adoc("id","F3"));

      h.close();
      String[] files = ulog.getLogList(logDir);
      Arrays.sort(files);
      RandomAccessFile raf = new RandomAccessFile(new File(logDir, files[files.length-1]), "rw");
      raf.seek(raf.length());  // seek to end
      raf.writeLong(0xffffffffffffffffL);
      raf.writeChars("This should be appended to a good log file, representing a bad partially written record.");
      raf.close();

      logReplay.release(1000);
      logReplayFinish.drainPermits();
      ignoreException("OutOfBoundsException");  // this is what the corrupted log currently produces... subject to change.
      createCore();
      assertTrue(logReplayFinish.tryAcquire(timeout, TimeUnit.SECONDS));
      resetExceptionIgnores();
      assertJQ(req("q","*:*") ,"/response/numFound==3");

      //
      // Now test that the bad log file doesn't mess up retrieving latest versions
      //

      updateJ(jsonAdd(sdoc("id","F4", "_version_","104")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      updateJ(jsonAdd(sdoc("id","F5", "_version_","105")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      updateJ(jsonAdd(sdoc("id","F6", "_version_","106")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));

      // This currently skips the bad log file and also returns the version of the clearIndex (del *:*)
      // assertJQ(req("qt","/get", "getVersions","6"), "/versions==[106,105,104]");
      assertJQ(req("qt","/get", "getVersions","3"), "/versions==[106,105,104]");

    } finally {
      DirectUpdateHandler2.commitOnClose = true;
      UpdateLog.testing_logReplayHook = null;
      UpdateLog.testing_logReplayFinishHook = null;
    }
  }

  //
  // test that a corrupt tlog doesn't stop us from coming up
  //
  @Test
  public void testCorruptLog() throws Exception {
    try {
      DirectUpdateHandler2.commitOnClose = false;

      UpdateLog ulog = h.getCore().getUpdateHandler().getUpdateLog();
      File logDir = new File(h.getCore().getUpdateHandler().getUpdateLog().getLogDir());

      clearIndex();
      assertU(commit());

      assertU(adoc("id","G1"));
      assertU(adoc("id","G2"));
      assertU(adoc("id","G3"));

      h.close();

      String[] files = ulog.getLogList(logDir);
      Arrays.sort(files);
      RandomAccessFile raf = new RandomAccessFile(new File(logDir, files[files.length-1]), "rw");
      long len = raf.length();
      raf.seek(0);  // seek to start
      raf.write(new byte[(int)len]);  // zero out file
      raf.close();

      ignoreException("Failure to open existing log file");  // this is what the corrupted log currently produces... subject to change.
      createCore();
      resetExceptionIgnores();

      // just make sure it responds
      assertJQ(req("q","*:*") ,"/response/numFound==0");

      //
      // Now test that the bad log file doesn't mess up retrieving latest versions
      //

      updateJ(jsonAdd(sdoc("id","G4", "_version_","104")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      updateJ(jsonAdd(sdoc("id","G5", "_version_","105")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));
      updateJ(jsonAdd(sdoc("id","G6", "_version_","106")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));

      // This currently skips the bad log file and also returns the version of the clearIndex (del *:*)
      // assertJQ(req("qt","/get", "getVersions","6"), "/versions==[106,105,104]");
      assertJQ(req("qt","/get", "getVersions","3"), "/versions==[106,105,104]");

      assertU(commit());

      assertJQ(req("q","*:*") ,"/response/numFound==3");

      // This messes up some other tests (on windows) if we don't remove the bad log.
      // This *should* hopefully just be because the tests are too fragile and not because of real bugs - but it should be investigated further.
      deleteLogs();

    } finally {
      DirectUpdateHandler2.commitOnClose = true;
      UpdateLog.testing_logReplayHook = null;
      UpdateLog.testing_logReplayFinishHook = null;
    }
  }

  // in rare circumstances, two logs can be left uncapped (lacking a commit at the end signifying that all the content in the log was committed)
  @Test
  public void testRecoveryMultipleLogs() throws Exception {
    try {
      DirectUpdateHandler2.commitOnClose = false;
      final Semaphore logReplay = new Semaphore(0);
      final Semaphore logReplayFinish = new Semaphore(0);

      UpdateLog.testing_logReplayHook = new Runnable() {
        @Override
        public void run() {
          try {
            assertTrue(logReplay.tryAcquire(timeout, TimeUnit.SECONDS));
          } catch (Exception e) {
            throw new RuntimeException(e);
          }
        }
      };

      UpdateLog.testing_logReplayFinishHook = new Runnable() {
        @Override
        public void run() {
          logReplayFinish.release();
        }
      };

      UpdateLog ulog = h.getCore().getUpdateHandler().getUpdateLog();
      File logDir = new File(h.getCore().getUpdateHandler().getUpdateLog().getLogDir());

      clearIndex();
      assertU(commit());

      assertU(adoc("id","AAAAAA"));
      assertU(adoc("id","BBBBBB"));
      assertU(adoc("id","CCCCCC"));

      h.close();
      String[] files = ulog.getLogList(logDir);
      Arrays.sort(files);
      String fname = files[files.length-1];
      RandomAccessFile raf = new RandomAccessFile(new File(logDir, fname), "rw");
      raf.seek(raf.length());  // seek to end
      raf.writeLong(0xffffffffffffffffL);
      raf.writeChars("This should be appended to a good log file, representing a bad partially written record.");

      byte[] content = new byte[(int)raf.length()];
      raf.seek(0);
      raf.readFully(content);

      raf.close();

      // Now make a newer log file with just the IDs changed.  NOTE: this may not work if log format changes too much!
      findReplace("AAAAAA".getBytes("UTF-8"), "aaaaaa".getBytes("UTF-8"), content);
      findReplace("BBBBBB".getBytes("UTF-8"), "bbbbbb".getBytes("UTF-8"), content);
      findReplace("CCCCCC".getBytes("UTF-8"), "cccccc".getBytes("UTF-8"), content);

      // WARNING... assumes format of .00000n where n is less than 9
      long logNumber = Long.parseLong(fname.substring(fname.lastIndexOf(".") + 1));
      String fname2 = String.format(Locale.ROOT,
          UpdateLog.LOG_FILENAME_PATTERN,
          UpdateLog.TLOG_NAME,
          logNumber + 1);
      raf = new RandomAccessFile(new File(logDir, fname2), "rw");
      raf.write(content);
      raf.close();

      logReplay.release(1000);
      logReplayFinish.drainPermits();
      ignoreException("OutOfBoundsException");  // this is what the corrupted log currently produces... subject to change.
      createCore();
      assertTrue(logReplayFinish.tryAcquire(timeout, TimeUnit.SECONDS));
      resetExceptionIgnores();
      assertJQ(req("q","*:*") ,"/response/numFound==6");

    } finally {
      DirectUpdateHandler2.commitOnClose = true;
      UpdateLog.testing_logReplayHook = null;
      UpdateLog.testing_logReplayFinishHook = null;
    }
  }

  // NOTE: replacement must currently be same size
  private static void findReplace(byte[] from, byte[] to, byte[] data) {
    int idx = -from.length;
    for(;;) {
      idx = indexOf(from, data, idx + from.length);  // skip over previous match
      if (idx < 0) break;
      for (int i=0; i<to.length; i++) {
        data[idx+i] = to[i];
      }
    }
  }

  private static int indexOf(byte[] target, byte[] data, int start) {
    outer: for (int i=start; i<data.length - target.length; i++) {
      for (int j=0; j<target.length; j++) {
        if (data[i+j] != target[j]) continue outer;
      }
      return i;
    }
    return -1;
  }

  // stops the core, removes the transaction logs, restarts the core.
  void deleteLogs() throws Exception {
    UpdateLog ulog = h.getCore().getUpdateHandler().getUpdateLog();
    File logDir = new File(h.getCore().getUpdateHandler().getUpdateLog().getLogDir());

    h.close();

    try {
      String[] files = ulog.getLogList(logDir);
      for (String file : files) {
        new File(logDir, file).delete();
      }

      assertEquals(0, ulog.getLogList(logDir).length);
    } finally {
      // make sure we create the core again, even if the assert fails so it won't mess
      // up the next test.
      createCore();
      assertJQ(req("q","*:*") ,"/response/numFound==");   // ensure it works
    }
  }

  private static Long getVer(SolrQueryRequest req) throws Exception {
    String response = JQ(req);
    Map rsp = (Map) ObjectBuilder.fromJSON(response);
    Map doc = null;
    if (rsp.containsKey("doc")) {
      doc = (Map)rsp.get("doc");
    } else if (rsp.containsKey("docs")) {
      List lst = (List)rsp.get("docs");
      if (lst.size() > 0) {
        doc = (Map)lst.get(0);
      }
    } else if (rsp.containsKey("response")) {
      Map responseMap = (Map)rsp.get("response");
      List lst = (List)responseMap.get("docs");
      if (lst.size() > 0) {
        doc = (Map)lst.get(0);
      }
    }

    if (doc == null) return null;

    return (Long)doc.get("_version_");
  }
}


text:
#if !defined(__MLT_PROC_H)
#define __MLT_PROC_H

#include <mitsuba/render/renderproc.h>
#include <mitsuba/render/renderjob.h>
#include <mitsuba/bidir/pathsampler.h>
#include <mitsuba/core/statistics.h>
#include <mitsuba/core/bitmap.h>
#include "mlt.h"

MTS_NAMESPACE_BEGIN

/* ==================================================================== */
/*                           Parallel process                           */
/* ==================================================================== */

class MLTProcess : public ParallelProcess {
public:
	MLTProcess(const RenderJob *parent, RenderQueue *queue,
		const MLTConfiguration &config, const Bitmap *directImage,
		const std::vector<PathSeed> &seeds);

	void develop();

	/* ParallelProcess impl. */
	void processResult(const WorkResult *wr, bool cancelled);
	ref<WorkProcessor> createWorkProcessor() const;
	void bindResource(const std::string &name, int id);
	EStatus generateWork(WorkUnit *unit, int worker);

	MTS_DECLARE_CLASS()
protected:
	/// Virtual destructor
	virtual ~MLTProcess() { }
private:
	ref<const RenderJob> m_job;
	RenderQueue *m_queue;
	const MLTConfiguration &m_config;
	const Bitmap *m_directImage;
	ref<Bitmap> m_developBuffer;
	ImageBlock *m_accum;
	ProgressReporter *m_progress;
	const std::vector<PathSeed> &m_seeds;
	ref<Mutex> m_resultMutex;
	ref<Film> m_film;
	int m_resultCounter, m_workCounter;
	unsigned int m_refreshTimeout;
	ref<Timer> m_timeoutTimer, m_refreshTimer;
};

MTS_NAMESPACE_END

#endif /* __MLT_PROC */


text:
public class RemoveDuplicatesFromString {
	public static void main(String[] args) {
		RemoveDuplicatesFromString rsd = new RemoveDuplicatesFromString();
		String input = "Tree Traversal";
		System.out.println(rsd.getUniqueString(input));
	}

	public String getUniqueString(String input) {
		boolean[] isUsed = new boolean[256];
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < input.length(); i++) {
			int position = input.charAt(i);
			if (!isUsed[position]) {
				sb.append(input.charAt(i));
				isUsed[position] = true;
			}
		}
		return sb.toString();
	}
}


text:
.class public final Landroid/app/StreamSettings;
.super Ljava/lang/Object;
.source "StreamSettings.java"

# interfaces
.implements Landroid/os/Parcelable;

# static fields
.field public static final CREATOR:Landroid/os/Parcelable$Creator;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Landroid/os/Parcelable$Creator",
            "<",
            "Landroid/app/StreamSettings;",
            ">;"
        }
    .end annotation
.end field

# instance fields
.field private mDirty:Z

.field private mOverride:Z

.field private mStreamId:I

.field private mValue:I

# direct methods
.method static constructor <clinit>()V
    .locals 1

    .prologue
    .line 22
    new-instance v0, Landroid/app/StreamSettings$1;

    invoke-direct {v0}, Landroid/app/StreamSettings$1;-><init>()V

    sput-object v0, Landroid/app/StreamSettings;->CREATOR:Landroid/os/Parcelable$Creator;

    return-void
.end method

.method public constructor <init>(I)V
    .locals 1
    .parameter "streamId"

    .prologue
    const/4 v0, 0x0

    .line 39
    invoke-direct {p0, p1, v0, v0}, Landroid/app/StreamSettings;-><init>(IIZ)V

    .line 40
    return-void
.end method

.method public constructor <init>(IIZ)V
    .locals 1
    .parameter "streamId"
    .parameter "value"
    .parameter "override"

    .prologue
    .line 42
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 43
    iput p1, p0, Landroid/app/StreamSettings;->mStreamId:I

    .line 44
    iput p2, p0, Landroid/app/StreamSettings;->mValue:I

    .line 45
    iput-boolean p3, p0, Landroid/app/StreamSettings;->mOverride:Z

    .line 46
    const/4 v0, 0x0

    iput-boolean v0, p0, Landroid/app/StreamSettings;->mDirty:Z

    .line 47
    return-void
.end method

.method public constructor <init>(Landroid/os/Parcel;)V
    .locals 0
    .parameter "parcel"

    .prologue
    .line 34
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 35
    invoke-virtual {p0, p1}, Landroid/app/StreamSettings;->readFromParcel(Landroid/os/Parcel;)V

    .line 36
    return-void
.end method

.method public static fromXml(Lorg/xmlpull/v1/XmlPullParser;Landroid/content/Context;)Landroid/app/StreamSettings;
    .locals 5
    .parameter "xpp"
    .parameter "context"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Lorg/xmlpull/v1/XmlPullParserException;,
            Ljava/io/IOException;
        }
    .end annotation

    .prologue
    .line 79
    invoke-interface {p0}, Lorg/xmlpull/v1/XmlPullParser;->next()I

    move-result v0

    .line 80
    .local v0, event:I
    new-instance v2, Landroid/app/StreamSettings;

    const/4 v3, 0x0

    invoke-direct {v2, v3}, Landroid/app/StreamSettings;-><init>(I)V

    .line 81
    .local v2, streamDescriptor:Landroid/app/StreamSettings;
    :goto_0
    const/4 v3, 0x3

    if-ne v0, v3, :cond_0

    invoke-interface {p0}, Lorg/xmlpull/v1/XmlPullParser;->getName()Ljava/lang/String;

    move-result-object v3

    const-string/jumbo v4, "streamDescriptor"

    invoke-virtual {v3, v4}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v3

    if-nez v3, :cond_4

    .line 82
    :cond_0
    const/4 v3, 0x2

    if-ne v0, v3, :cond_1

    .line 83
    invoke-interface {p0}, Lorg/xmlpull/v1/XmlPullParser;->getName()Ljava/lang/String;

    move-result-object v1

    .line 84
    .local v1, name:Ljava/lang/String;
    const-string/jumbo v3, "streamId"

    invoke-virtual {v1, v3}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v3

    if-eqz v3, :cond_2

    .line 85
    invoke-interface {p0}, Lorg/xmlpull/v1/XmlPullParser;->nextText()Ljava/lang/String;

    move-result-object v3

    invoke-static {v3}, Ljava/lang/Integer;->parseInt(Ljava/lang/String;)I

    move-result v3

    iput v3, v2, Landroid/app/StreamSettings;->mStreamId:I

    .line 92
    .end local v1           #name:Ljava/lang/String;
    :cond_1
    :goto_1
    invoke-interface {p0}, Lorg/xmlpull/v1/XmlPullParser;->next()I

    move-result v0

    goto :goto_0

    .line 86
    .restart local v1       #name:Ljava/lang/String;
    :cond_2
    const-string/jumbo v3, "value"

    invoke-virtual {v1, v3}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v3

    if-eqz v3, :cond_3

    .line 87
    invoke-interface {p0}, Lorg/xmlpull/v1/XmlPullParser;->nextText()Ljava/lang/String;

    move-result-object v3

    invoke-static {v3}, Ljava/lang/Integer;->parseInt(Ljava/lang/String;)I

    move-result v3

    iput v3, v2, Landroid/app/StreamSettings;->mValue:I

    goto :goto_1

    .line 88
    :cond_3
    const-string/jumbo v3, "override"

    invoke-virtual {v1, v3}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v3

    if-eqz v3, :cond_1

    .line 89
    invoke-interface {p0}, Lorg/xmlpull/v1/XmlPullParser;->nextText()Ljava/lang/String;

    move-result-object v3

    invoke-static {v3}, Ljava/lang/Boolean;->parseBoolean(Ljava/lang/String;)Z

    move-result v3

    iput-boolean v3, v2, Landroid/app/StreamSettings;->mOverride:Z

    goto :goto_1

    .line 94
    .end local v1           #name:Ljava/lang/String;
    :cond_4
    return-object v2
.end method

# virtual methods
.method public describeContents()I
    .locals 1

    .prologue
    .line 111
    const/4 v0, 0x0

    return v0
.end method

.method public getStreamId()I
    .locals 1

    .prologue
    .line 50
    iget v0, p0, Landroid/app/StreamSettings;->mStreamId:I

    return v0
.end method

.method public getValue()I
    .locals 1

    .prologue
    .line 54
    iget v0, p0, Landroid/app/StreamSettings;->mValue:I

    return v0
.end method

.method public getXmlString(Ljava/lang/StringBuilder;Landroid/content/Context;)V
    .locals 1
    .parameter "builder"
    .parameter "context"

    .prologue
    .line 99
    const-string v0, "<streamDescriptor>\n<streamId>"

    invoke-virtual {p1, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 100
    iget v0, p0, Landroid/app/StreamSettings;->mStreamId:I

    invoke-virtual {p1, v0}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    .line 101
    const-string v0, "</streamId>\n<value>"

    invoke-virtual {p1, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 102
    iget v0, p0, Landroid/app/StreamSettings;->mValue:I

    invoke-virtual {p1, v0}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    .line 103
    const-string v0, "</value>\n<override>"

    invoke-virtual {p1, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 104
    iget-boolean v0, p0, Landroid/app/StreamSettings;->mOverride:Z

    invoke-virtual {p1, v0}, Ljava/lang/StringBuilder;->append(Z)Ljava/lang/StringBuilder;

    .line 105
    const-string v0, "</override>\n</streamDescriptor>\n"

    invoke-virtual {p1, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 106
    const/4 v0, 0x0

    iput-boolean v0, p0, Landroid/app/StreamSettings;->mDirty:Z

    .line 107
    return-void
.end method

.method public isDirty()Z
    .locals 1

    .prologue
    .line 73
    iget-boolean v0, p0, Landroid/app/StreamSettings;->mDirty:Z

    return v0
.end method

.method public isOverride()Z
    .locals 1

    .prologue
    .line 68
    iget-boolean v0, p0, Landroid/app/StreamSettings;->mOverride:Z

    return v0
.end method

.method public readFromParcel(Landroid/os/Parcel;)V
    .locals 3
    .parameter "in"

    .prologue
    const/4 v1, 0x1

    const/4 v2, 0x0

    .line 125
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v0

    iput v0, p0, Landroid/app/StreamSettings;->mStreamId:I

    .line 126
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v0

    if-eqz v0, :cond_0

    move v0, v1

    :goto_0
    iput-boolean v0, p0, Landroid/app/StreamSettings;->mOverride:Z

    .line 127
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v0

    iput v0, p0, Landroid/app/StreamSettings;->mValue:I

    .line 128
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v0

    if-eqz v0, :cond_1

    :goto_1
    iput-boolean v1, p0, Landroid/app/StreamSettings;->mDirty:Z

    .line 129
    return-void

    :cond_0
    move v0, v2

    .line 126
    goto :goto_0

    :cond_1
    move v1, v2

    .line 128
    goto :goto_1
.end method

.method public setOverride(Z)V
    .locals 1
    .parameter "override"

    .prologue
    .line 63
    iput-boolean p1, p0, Landroid/app/StreamSettings;->mOverride:Z

    .line 64
    const/4 v0, 0x1

    iput-boolean v0, p0, Landroid/app/StreamSettings;->mDirty:Z

    .line 65
    return-void
.end method

.method public setValue(I)V
    .locals 1
    .parameter "value"

    .prologue
    .line 58
    iput p1, p0, Landroid/app/StreamSettings;->mValue:I

    .line 59
    const/4 v0, 0x1

    iput-boolean v0, p0, Landroid/app/StreamSettings;->mDirty:Z

    .line 60
    return-void
.end method

.method public writeToParcel(Landroid/os/Parcel;I)V
    .locals 3
    .parameter "dest"
    .parameter "flags"

    .prologue
    const/4 v1, 0x1

    const/4 v2, 0x0

    .line 117
    iget v0, p0, Landroid/app/StreamSettings;->mStreamId:I

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 118
    iget-boolean v0, p0, Landroid/app/StreamSettings;->mOverride:Z

    if-eqz v0, :cond_0

    move v0, v1

    :goto_0
    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 119
    iget v0, p0, Landroid/app/StreamSettings;->mValue:I

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 120
    iget-boolean v0, p0, Landroid/app/StreamSettings;->mDirty:Z

    if-eqz v0, :cond_1

    :goto_1
    invoke-virtual {p1, v1}, Landroid/os/Parcel;->writeInt(I)V

    .line 121
    return-void

    :cond_0
    move v0, v2

    .line 118
    goto :goto_0

    :cond_1
    move v1, v2

    .line 120
    goto :goto_1
.end method


text:
tags: baby ella
layout: post
title: "Hello to Ella Mae Winters"
---

Ella Mae Winters was brought into the world on December 27 at 10:07 PM, weighing in at a hefty 10 pounds, 1 ounce and 21.5 inches long. Her extra two weeks in the womb were apparently dedicated to making her not only amazingly cute and alert, but also to growing her head of brown hair.

Despite prediction/hope from my last post, the labor was fairly long and at times difficult, but Barb is recovering very well. And Ella has been healthy and very strong throughout, which may be a testament to the prodigious amounts of 8th Continent soymilk that Barb has consumed in the last nine months. (Don't let anyone tell you a mother has to eat meat to produce a big baby!)

About her name: Ella is for my mom (Pamela), who passed away in 1999 and who would be bursting with happiness (and advice!) right about now. Mae is another form for Barb's maternal grandmother's name, Mary. Like all parents, we don't anticipate using both except in exasperation, although the potential pen names ("E. M. Winters", "E. Mae Winters") sound pretty good.

Photos are being uploaded to flickr literally as I type this, and you can subscribe to the all-Ella, all-the-time show as you wish.

Sorry for not following up my last post sooner, but some of these "21st century" hospitals still don't have internet access!

Updated: What was I thinking, posting this without a photo...


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FataMirage.Core.Scene
{
    class SceneState
    {
        public Dictionary<string, Layers.ILayer> layers = new Dictionary<string, Layers.ILayer>();
        public IOrderedEnumerable<KeyValuePair<string, Layers.ILayer>> layersDepthSorted
        {
            get
            {
                return layers.OrderBy(kvp => kvp.Value.zPos);
            }
        }
        public Path.Waypoints waypoints = new Path.Waypoints();
        public void Update(float elapsedTime)
        {
            foreach (Layers.ILayer layer in layers.Values)
            {
                layer.Update(elapsedTime);
            }

        }
        public void Draw(float elapsedTime)
        {
            foreach (Layers.ILayer layer in layers.Values)
            {
                layer.Draw(elapsedTime);
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools">

    <color name="bluish_background">#111C2C</color>
    <color name="bluish_primary">#FF2A456B</color>
    <color name="bluish_primary_dark">#213755</color>
    <color name="bluish_accent">#448AFF</color>

    <color name="bluishWindowBackground">@color/bluish_background</color>
    <color name="bluishDivider">#802A456B</color>

    <style name="ThemeBluish" parent="ThemeBluish.Base"/>

    <style name="ThemeBluish.Base" parent="Theme.AppCompat.NoActionBar">
        <item name="card_background">#182A44</item>
        <item name="comment_box_style">@style/CommentBoxDarkBluish</item>
        <item name="icon_color">#eee</item>
        <item name="button_icon_color">#ECECEC</item>
        <item name="timeLineBackground">@style/TimeLineBackgroundBluish</item>
        <item name="patch_addition">@color/dark_patch_addition_color</item>
        <item name="patch_deletion">@color/dark_patch_deletion_color</item>
        <item name="patch_ref">@color/dark_patch_ref_color</item>
        <item name="dividerColor">@color/bluishDivider</item>
        <item name="android:windowBackground">@color/bluishWindowBackground</item>
        <item name="colorPrimary">@color/bluish_primary</item>
        <item name="colorPrimaryDark">@color/bluish_primary_dark</item>
        <item name="colorAccent">@color/bluish_accent</item>
        <item name="colorControlNormal">?colorAccent</item>
        <item name="actionModeBackground">?colorPrimary</item>
        <item name="windowActionModeOverlay">true</item>
        <item name="preferenceTheme">@style/PreferenceThemeOverlay.v14.Material</item>
        <item name="bottomSheetDialogTheme">@style/AppBottomSheetDialogTheme</item>
        <item name="android:textColorPrimary">#eee</item>
        <item name="android:textColorSecondary">#9E9E9E</item>
        <item name="android:textColorTertiary">#ffe0e0e0</item>
        <item name="android:windowAllowEnterTransitionOverlap">true</item>
        <item name="android:windowAllowReturnTransitionOverlap">true</item>
        <item name="android:colorEdgeEffect">?colorPrimary</item>
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="android:statusBarColor">@color/transparent</item>
        <item name="android:windowContentTransitions">true</item>
        <item name="android:dialogTheme">@style/DialogThemeBluish</item>
        <item name="android:alertDialogTheme">@style/DialogThemeBluish</item>
        <item name="android:toolbarStyle">@style/ToolbarStyleBluish</item>
        <item name="android:windowLightStatusBar" tools:targetApi="m">false</item>
        <item name="android:popupMenuStyle">@style/PopupMenuBluish</item>
    </style>

    <style name="PopupMenuBluish" parent="Widget.AppCompat.PopupMenu">
        <item name="android:popupBackground">@color/bluishWindowBackground</item>
    </style>

    <style name="ThemeBluish.Red" parent="ThemeBluish.Base">
        <item name="colorAccent">@color/material_red_accent_700</item>
        <item name="android:alertDialogTheme">@style/DialogThemeBluish.Red</item>
    </style>

    <style name="ThemeBluish.Pink" parent="ThemeBluish.Base">
        <item name="colorAccent">@color/material_pink_accent_700</item>
        <item name="android:alertDialogTheme">@style/DialogThemeBluish.Pink</item>
    </style>

    <style name="ThemeBluish.Purple" parent="ThemeBluish.Base">
        <item name="colorAccent">@color/material_purple_accent_700</item>
        <item name="android:alertDialogTheme">@style/DialogThemeBluish.Purple</item>
    </style>

    <style name="ThemeBluish.DeepPurple" parent="ThemeBluish.Base">
        <item name="colorAccent">@color/material_deep_purple_accent_700</item>
        <item name="android:alertDialogTheme">@style/DialogThemeBluish.DeepPurple</item>
    </style>

    <style name="ThemeBluish.Indigo" parent="ThemeBluish.Base">
        <item name="colorAccent">@color/material_indigo_accent_700</item>
        <item name="android:alertDialogTheme">@style/DialogThemeBluish.Indigo</item>
    </style>

    <style name="ThemeBluish.LightBlue" parent="ThemeBluish.Base">
        <item name="colorAccent">@color/material_light_blue_accent_700</item>
        <item name="android:alertDialogTheme">@style/DialogThemeBluish.LightBlue</item>
    </style>

    <style name="ThemeBluish.Cyan" parent="ThemeBluish.Base">
        <item name="colorAccent">@color/material_cyan_accent_700</item>
        <item name="android:alertDialogTheme">@style/DialogThemeBluish.Cyan</item>
    </style>

    <style name="ThemeBluish.Teal" parent="ThemeBluish.Base">
        <item name="colorAccent">@color/material_teal_700</item>
        <item name="android:alertDialogTheme">@style/DialogThemeBluish.Teal</item>
    </style>

    <style name="ThemeBluish.Green" parent="ThemeBluish.Base">
        <item name="colorAccent">@color/material_green_accent_700</item>
        <item name="android:alertDialogTheme">@style/DialogThemeBluish.Green</item>
    </style>

    <style name="ThemeBluish.LightGreen" parent="ThemeBluish.Base">
        <item name="colorAccent">@color/material_light_green_accent_700</item>
        <item name="android:alertDialogTheme">@style/DialogThemeBluish.LightGreen</item>
    </style>

    <style name="ThemeBluish.Lime" parent="ThemeBluish.Base">
        <item name="colorAccent">@color/material_lime_accent_700</item>
        <item name="android:alertDialogTheme">@style/DialogThemeBluish.Lime</item>
    </style>

    <style name="ThemeBluish.Yellow" parent="ThemeBluish.Base">
        <item name="colorAccent">@color/material_yellow_accent_700</item>
        <item name="android:alertDialogTheme">@style/DialogThemeBluish.Yellow</item>
    </style>

    <style name="ThemeBluish.Amber" parent="ThemeBluish.Base">
        <item name="colorAccent">@color/material_amber_accent_700</item>
        <item name="android:alertDialogTheme">@style/DialogThemeBluish.Amber</item>
    </style>

    <style name="ThemeBluish.Orange" parent="ThemeBluish.Base">
        <item name="colorAccent">@color/material_orange_accent_700</item>
        <item name="android:alertDialogTheme">@style/DialogThemeBluish.Orange</item>
    </style>

    <style name="ThemeBluish.DeepOrange" parent="ThemeBluish.Base">
        <item name="colorAccent">@color/material_deep_orange_accent_700</item>
        <item name="android:alertDialogTheme">@style/DialogThemeBluish.DeepOrange</item>
    </style>

    <style name="ToolbarStyleBluish">
        <item name="android:textColorPrimary">@color/white</item>
        <item name="colorControlNormal">@color/white</item>
        <item name="colorControlHighlight">#42ffffff</item>
        <item name="popupTheme">@style/PopupThemeBluish</item>
    </style>

    <style name="PopupThemeBluish" parent="ThemeOverlay.AppCompat">
        <item name="android:colorBackground">@color/bluishWindowBackground</item>
    </style>

    <style name="TimeLineBackgroundBluish">
        <item name="android:background">@drawable/ic_timeline_arrow_left</item>
        <item name="android:backgroundTint">#182A44</item>
    </style>

    <style name="CommentBoxDarkBluish">
        <item name="android:background">@drawable/ic_edittext</item>
        <item name="android:backgroundTint">#182A44</item>
    </style>

    <style name="DialogThemeBluish" parent="Theme.AppCompat.Dialog.Alert">
        <item name="android:toolbarStyle">@style/ToolbarStyleBluish</item>
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
        <item name="card_background">#182A44</item>
        <item name="comment_box_style">@style/CommentBoxDarkBluish</item>
        <item name="icon_color">#eee</item>
        <item name="timeLineBackground">@style/TimeLineBackgroundBluish</item>
        <item name="patch_addition">@color/dark_patch_addition_color</item>
        <item name="patch_deletion">@color/dark_patch_deletion_color</item>
        <item name="patch_ref">@color/dark_patch_ref_color</item>
        <item name="dividerColor">@color/bluishDivider</item>
        <item name="android:windowBackground">@color/bluishWindowBackground</item>
        <item name="colorPrimary">@color/bluish_primary</item>
        <item name="colorPrimaryDark">@color/bluish_primary_dark</item>
        <item name="colorAccent">@color/bluish_accent</item>
    </style>

    <style name="DialogThemeBluish.Red" parent="DialogThemeBluish">
        <item name="colorAccent">@color/material_red_accent_700</item>
    </style>

    <style name="DialogThemeBluish.Pink" parent="DialogThemeBluish">
        <item name="colorAccent">@color/material_pink_accent_700</item>
    </style>

    <style name="DialogThemeBluish.Purple" parent="DialogThemeBluish">
        <item name="colorAccent">@color/material_purple_accent_700</item>
    </style>

    <style name="DialogThemeBluish.DeepPurple" parent="DialogThemeBluish">
        <item name="colorAccent">@color/material_deep_purple_accent_700</item>
    </style>

    <style name="DialogThemeBluish.Indigo" parent="DialogThemeBluish">
        <item name="colorAccent">@color/material_indigo_accent_700</item>
    </style>

    <style name="DialogThemeBluish.LightBlue" parent="DialogThemeBluish">
        <item name="colorAccent">@color/material_light_blue_accent_700</item>
    </style>

    <style name="DialogThemeBluish.Cyan" parent="DialogThemeBluish">
        <item name="colorAccent">@color/material_cyan_accent_700</item>
    </style>

    <style name="DialogThemeBluish.Teal" parent="DialogThemeBluish">
        <item name="colorAccent">@color/material_teal_accent_700</item>
    </style>

    <style name="DialogThemeBluish.Green" parent="DialogThemeBluish">
        <item name="colorAccent">@color/material_green_accent_700</item>
    </style>

    <style name="DialogThemeBluish.LightGreen" parent="DialogThemeBluish">
        <item name="colorAccent">@color/material_light_green_accent_700</item>
    </style>

    <style name="DialogThemeBluish.Lime" parent="DialogThemeBluish">
        <item name="colorAccent">@color/material_lime_accent_700</item>
    </style>

    <style name="DialogThemeBluish.Yellow" parent="DialogThemeBluish">
        <item name="colorAccent">@color/material_yellow_accent_700</item>
    </style>

    <style name="DialogThemeBluish.Amber" parent="DialogThemeBluish">
        <item name="colorAccent">@color/material_amber_accent_700</item>
    </style>

    <style name="DialogThemeBluish.Orange" parent="DialogThemeBluish">
        <item name="colorAccent">@color/material_orange_accent_700</item>
    </style>

    <style name="DialogThemeBluish.DeepOrange" parent="DialogThemeBluish">
        <item name="colorAccent">@color/material_deep_orange_accent_700</item>
    </style>

</resources>


text:
namespace AnimalHierarchy
{
    interface ISound
    {
        string Sound { get; }
    }
}


text:
class Parents::CalendarsController < ApplicationController
  before_action :authenticate_user!

  def show
    @calendar = Calendar.last
    render template: 'static_pages/calendar'
  end
end


text:
<?php

/**
 * Admin article categories text manager.
 * Returns template, that arranges two other templates ("category_list.tpl"
 * and "category_main.tpl") to frame.
 * Admin Menu: Manage Products -> Categories.
 */
class Category extends oxAdminView
{

    /**
     * Current class template name.
     *
     * @var string
     */
    protected $_sThisTemplate = 'category.tpl';
}


text:
/* Threading.js
   For some backwards compatability, use the Google Closure compiler.
   closure --compilation_level WHITESPACE_ONLY --js threading.js --js_output_file threading.cs.js */
class Threading {
	constructor(makename) { // load in unchecked object
		/* initializing failreason as null.
		   If we have a failure to build a worker or proxy,
		   the developer needs reasonable console output and
		   the user needs a sane reason for shit not working
		*/
		this.failreason = null;

		// Doing check for window.
		if(typeof(window) == 'undefined'){
			console.log('Threading.js was made to work with the "window" variable. If you are using nodejs, you will need to seek something for Workers in npm.');
			this.failreason = "Not ran in a browser.";
			return undefined;
		}

		// Doing check for Worker()
		if(typeof(Worker) == 'undefined'){
			console.log('Worker is no supported by your JS engine. This may be due to an outdated browser.');
			this.failreason = "Worker not available.";
			return undefined;
		}

		// Doing check for Proxy()
		if(typeof(Proxy) == 'undefined'){
			console.log('Proxy is not supported by your JS engine. This may be due to an outdated browser.');
			this.failreason = "Proxy not available.";
			return undefined;
		}

		// We need an ID to track the window variable
		// that will be handling our worker.
		var wid = "worker" + (new Date().getTime());

		/* Determine if this is an inline Worker Function or if
		   we should assume it's a class. Any unsupported stuff
		   will default to failure.

		   Upon success run Worker() and execute Worker().auto()
		   to initialize callback message processing
		*/
		if(typeof(makename) == typeof(function(){})){
			window[wid] = new Worker(this.buildblob_from_function(makename)).auto();
		}else if(typeof(makename) == "undefined"){
			window[wid] = new Worker(this.buildblob_from_class()).auto();
		}else{
			console.log('Threading.js was provided an unsupported input type. If you are trying to refernce a JS file as your worker, use the normal Worker() function. Threading.js does not support that because of problems between browsers and file location issues.');
			this.failreason = "Threading.js was provided an unsupported input type.";
			return undefined;
		}

		/* Once we have created the worker, let it know who it is.
		   The Worker().id is used internally to workaround traps not
		   working yet in Proxy() in firefox.
		*/
		window[wid]["id"] = wid;

		// return a proxy() that will manage Worker function calling.
		return new Proxy({ id: wid }, {
			// Used to handle anonymous function calling.
			get: function(target, name) {
				/* Check to see if Worker() has this function
				   if it does not, prepare to send a request to Worker()
				*/
				if (!(name in window[target['id']])) {
					// This allows Worker().sendToWorker() to know what function was requested.
					window[target['id']]["anonMethodName"] = name;
					// Return Worker().sendToWorker()
					return window[target['id']]["sendToWorker"];
				}

				// Return Worker().function_name
				return window[target['id']][name];
			},

			// Handles anonymous set calls. Might use this one day. TODO: needs evaluation
			set: function(target, name, value) {
				console.log("Setting things will not work in Threading.js yet.");
				/* maybe one day, Dave. | Example here just in case for later.
				if (!(name in target)) {
					console.log("Setting non-existant property '" + name + "', initial value: " + value);
				}
				target[name] = value;*/
			}
		});
	}

	/* helper_functions() is packed into your worker scripts.
	   It includes the magic that allows you to send requests
	   back to the window thread.
	*/
	helper_functions(){
		// Variable used in Proxy().get()<-return function(){} - More info there.
		var anonMethodName = null;

		// This is the listener that the Worker Thread uses to receive requests.
		self.addEventListener("message", function(event) {
			// It expects JSON formatted object data. { method: fn_name, args [...]}
			data = JSON.parse(event.data);

			// A check to ensure that the requested method is actually here.
			if(typeof(this[data.method]) != 'undefined'){

				// The call to the method here in the thread, we apply the argument array to it
				this[data.method].apply(this, data.args);
			}
		}, false);

		/* "window" variable is defined inside our worker to allow anonymous function callback
		   to the main thread. We use Proxy() for this witchcraft.
		*/
		var root = new Proxy({}, {
			// Used to handle anonymous function calling.
			get: function(target, name) {
				/* variable lives inside the Worker Thread's main scope. It is
				   used to ensure we know what anonymous function to request from
				   the main thread (window). */
				anonMethodName = name;

				// wrap up the data and send a message back to the main thread (window).
				return function(){
					callback_details = JSON.stringify({ method: anonMethodName, args: Array.from(arguments) });
					postMessage(callback_details);
					return this;
				};
			},

			// Handles anonymous set calls. Might make this useful someday... TODO: needs evaluation
			set: function(target, name, value) {
				console.log("Setting things will not work in Threading.js yet.");
			}
		});
	}

	// Takes code in string format and creates a Blob() object and a URL object to use.
	blobify(codeout){
		var blob = new Blob([codeout]);
		var bloburl = window.URL.createObjectURL(blob);
		return bloburl;
	}

	/* Cleans up Worker Thread code to allow it to live inside the main scope of the thread.
	   Essentially takes function(){ // code here } and turns it into just // code here */
	blobfixer(method){
		if(typeof(method) == typeof(function(){})){
			var codeout = method.toString();
		}else{
			var codeout = this[method].toString();
		}
		codeout = codeout.substring(codeout.indexOf("{") + 1);
		codeout = codeout.substring(0, codeout.lastIndexOf("}"));
		return codeout;
	}

	// Called in constructor() for inline function intake and returns useful bloburl for our Worker() call
	buildblob_from_function(function_in){
		var codeout = this.blobfixer("helper_functions");
		codeout += "\n" + this.blobfixer(function_in);

		return this.blobify(codeout);
	}

	// Builds our code blob from an extended class.
	buildblob_from_class(){
		// This allows us to actually see the class inside loops below... "this" wasn't useable in chromium.
		var myself = this;

		// proto will contain a prototype of the class extension. We're not going too deep on this.
		var proto = Object.getPrototypeOf(this);
		// Extracting the method names from the class extension
		var methods = Object.getOwnPropertyNames(proto);

		// initialized string to store code.
		var codeout = "";

		/* Extra Packages are available!!!! */

		// dompackage includes jquery and jsdom
		for(var i=0; i<self.threadingjs.helpers.length; i++){
			// add the helper_dompackage to the worker
			codeout += "\n"+this.blobfixer(self.threadingjs.helpers[i]);
		}

		// begin building and storing code to turn into a blob.
		codeout += "\n"+this.blobfixer("helper_functions");

		// iterates through every method in our class extension
		methods.forEach(function(name, fn){
			// ignores the constructor and main() functions of the class extension.
			if(name == 'constructor' || name == 'main'){return;}
			// temporary storage for code fixing.
			// add the code to `codeout` variable
			codeout += "\n" + myself.buildFNinjector(myself[name]) + "\n\n";
		});

		// if we have a "main" function in the class, we want this to be the main scope.
		if('main' in myself){ codeout += "\n" + this.blobfixer("main"); }

		// blobify codeout and return the bloburl.
		return this.blobify(codeout);
	}

	buildFNinjector(code){
		var code = code.toString();
		// so firefox auto-adds "function".. but chromium does not. wtf?.. check for it
		if(code.match(/^function/g) == null){
			// if we don't have "function" in front of our function declaration, put it there.
			code = "function "+code;
		}
		return code;
	}
}

self.threadingjs = {};
self.threadingjs.helpers = [];

// The worker needs some utility stuff to function properly in Threading.js
Worker.prototype = {};
// An ID to know it's randomly generated variable name
Worker.prototype.id = null;
// A variable to know what method names are being requested
Worker.prototype.anonMethodName = null;

/* This is used to send requests to the Worker() thread. */
Worker.prototype.sendToWorker = function(){
	/* We figure out what method was asked of us from the Proxy() we're using that was
	    made in Threading().constructor() */
	anonMethodName = window[this.id]["anonMethodName"];
	/* Build a JSON string to pass to the thread */
	callback_details = JSON.stringify({ method: anonMethodName, args: Array.from(arguments) });
	/* Send the JSON formatted request */
	window[this.id].postMessage(callback_details);
	return this;
};

/* Processes requests from Worker() to run in the main thread (window)
   I'm leaving this in a function named auto() so that people can still
   rely on just common Worker() stuff as they would expect. */
Worker.prototype.auto = function(func){
	/* Listens for requests from the Worker() thread */
	this.onmessage = function(event){
		/* Turn the data from a JSON string to a useable object */
		data = JSON.parse(event.data);

		/* Determine if the main thread (window) actually has this method and it's a function */
		if(data.method in window && typeof(window[data.method]) == typeof(function(){})){
			/* method found and was a function, call it and apply arguments. */
			window[data.method].apply(this, data.args);
		}
	}

	return this;
}