text:
use std::fs::File;
use std::io::{Write, BufWriter};

use inflector::Inflector;

use Service;
use botocore::{Member, Shape, ShapeType};
use self::json::JsonGenerator;
use self::query::QueryGenerator;
use self::rest_json::RestJsonGenerator;
use self::rest_xml::RestXmlGenerator;
use self::error_types::{GenerateErrorTypes, JsonErrorTypes, RestJsonErrorTypes, XmlErrorTypes};
use self::tests::generate_tests;
use self::type_filter::filter_types;
use util;

mod error_types;
mod json;
mod query;
mod rest_json;
pub mod tests;
mod rest_xml;
mod xml_payload_parser;
mod rest_response_parser;
mod rest_request_generator;
mod type_filter;

type FileWriter = BufWriter<File>;
type IoResult = ::std::io::Result<()>;

/// Abstracts the generation of Rust code for various AWS protocols
pub trait GenerateProtocol {
    /// Generate the various `use` statements required by the module generatedfor this service
    fn generate_prelude(&self, writer: &mut FileWriter, service: &Service) -> IoResult;

    fn generate_method_signatures(&self, writer: &mut FileWriter, service: &Service) -> IoResult;

    /// Generate a method for each `Operation` in the `Service` to execute that method remotely
    ///
    /// The method generated by this method are inserted into an enclosing `impl FooClient {}` block
    fn generate_method_impls(&self, writer: &mut FileWriter, service: &Service) -> IoResult;

    /// If possible, return the trait that can be derived to serialize types
    fn serialize_trait(&self) -> Option<&'static str> {
        None
    }

    /// If possible, return the trait that can be derived to deserialize types
    fn deserialize_trait(&self) -> Option<&'static str> {
        None
    }

    /// If necessary, generate a serializer for the specified type
    /// This should be necessary only if `serialize_trait` returns `None`
    fn generate_serializer(&self,
                           _name: &str,
                           _shape: &Shape,
                           _service: &Service)
                           -> Option<String> {
        None
    }

    /// If necessary, generate a deserializer for the specified type
    /// This should be necessary only if `deserialize_trait` returns `None`
    fn generate_deserializer(&self,
                             _name: &str,
                             _shape: &Shape,
                             _service: &Service)
                             -> Option<String> {
        None
    }

    /// Return the type used by this protocol for timestamps
    fn timestamp_type(&self) -> &'static str;
}

pub fn generate_source(service: &Service, writer: &mut FileWriter) -> IoResult {
    // EC2 service protocol is similar to query but not the same.  Rusoto is able to generate Rust code
    // from the service definition through the same QueryGenerator, but botocore uses a special class.
    // See https://github.com/boto/botocore/blob/dff99fdf2666accf6b448aef7f03fe3d66dd38fa/botocore/serialize.py#L259-L266 .
    match service.protocol() {
        "json" => generate(writer, service, JsonGenerator, JsonErrorTypes),
        "query" | "ec2" => generate(writer, service, QueryGenerator, XmlErrorTypes),
        "rest-json" => generate(writer, service, RestJsonGenerator, RestJsonErrorTypes),
        "rest-xml" => generate(writer, service, RestXmlGenerator, XmlErrorTypes),
        protocol => panic!("Unknown protocol {}", protocol),
    }
}

/// Translate a botocore field name to something rust-idiomatic and
/// escape reserved words with an underscore
pub fn generate_field_name(member_name: &str) -> String {
    let name = member_name.to_snake_case();
    if name == "return" || name == "type" {
        name + "_"
    } else {
        name
    }
}

/// The quick brown fox jumps over the lazy dog
fn generate<P, E>(writer: &mut FileWriter,
                  service: &Service,
                  protocol_generator: P,
                  error_type_generator: E)
                  -> IoResult
    where P: GenerateProtocol,
          E: GenerateErrorTypes
{

    writeln!(writer,
             "
        // =================================================================
        //
        //                           * WARNING *
        //
        //                    This file is generated!
        //
        //  Changes made to this file will be overwritten. If changes are
        //  required to the generated code, the service_crategen project
        //  must be updated to generate the changes.
        //
        // =================================================================

        use std::error::Error;
        use std::fmt;
        use std::io;

        #[allow(warnings)]
        use futures::future;
        use futures::Future;
        use rusoto_core::request::{{BufferedHttpResponse, DispatchSignedRequest}};
        use rusoto_core::region;
        use rusoto_core::{{Client, RusotoFuture}};

        use rusoto_core::request::HttpDispatchError;
        use rusoto_core::credential::{{CredentialsError, ProvideAwsCredentials}};
    ")?;

    protocol_generator.generate_prelude(writer, service)?;
    generate_types(writer, service, &protocol_generator)?;
    error_type_generator
        .generate_error_types(writer, service)?;
    generate_client(writer, service, &protocol_generator)?;
    generate_tests(writer, service)?;

    Ok(())

}

fn generate_client<P>(writer: &mut FileWriter,
                      service: &Service,
                      protocol_generator: &P)
                      -> IoResult
    where P: GenerateProtocol
{
    // If the struct name is changed, the links in each service documentation should change.
    // See https://github.com/rusoto/rusoto/issues/519
    writeln!(writer,
             "/// Trait representing the capabilities of the {service_name} API. {service_name} clients implement this trait.
        pub trait {trait_name} {{
        ",
             trait_name = service.service_type_name(),
             service_name = service.name())?;

    protocol_generator
        .generate_method_signatures(writer, service)?;

    writeln!(writer, "}}")?;

    writeln!(writer,
        "/// A client for the {service_name} API.
        pub struct {type_name} {{
            client: Client,
            region: region::Region,
        }}

        impl {type_name} {{
            /// Creates a client backed by the default tokio event loop.
            ///
            /// The client will use the default credentials provider and tls client.
            pub fn new(region: region::Region) -> {type_name} {{
                {type_name} {{
                    client: Client::shared(),
                    region: region
                }}
            }}

            pub fn new_with<P, D>(request_dispatcher: D, credentials_provider: P, region: region::Region) -> {type_name}
                where P: ProvideAwsCredentials + Send + Sync + 'static,
                      P::Future: Send,
                      D: DispatchSignedRequest + Send + Sync + 'static,
                      D::Future: Send
            {{
                {type_name} {{
                    client: Client::new_with(credentials_provider, request_dispatcher),
                    region: region
                }}
            }}
        }}

        impl {trait_name} for {type_name} {{
        ",
        service_name = service.name(),
        type_name = service.client_type_name(),
        trait_name = service.service_type_name(),
    )?;
    protocol_generator
        .generate_method_impls(writer, service)?;
    writeln!(writer, "}}")
}

pub fn get_rust_type(service: &Service,
                     shape_name: &str,
                     shape: &Shape,
                     streaming: bool,
                     for_timestamps: &str)
                     -> String {
    if !streaming {
        match shape.shape_type {
            ShapeType::Blob => "Vec<u8>".into(),
            ShapeType::Boolean => "bool".into(),
            ShapeType::Double => "f64".into(),
            ShapeType::Float => "f32".into(),
            ShapeType::Integer | ShapeType::Long => "i64".into(),
            ShapeType::String => "String".into(),
            ShapeType::Timestamp => for_timestamps.into(),
            ShapeType::List => {
                format!("Vec<{}>",
                        get_rust_type(service,
                                      shape.member_type(),
                                      service.get_shape(shape.member_type()).unwrap(),
                                      false,
                                      for_timestamps))
            }
            ShapeType::Map => {
                format!(
                    "::std::collections::HashMap<{}, {}>",
                    get_rust_type(service, shape.key_type(), service.get_shape(shape.key_type()).unwrap(), false, for_timestamps),
                    get_rust_type(service, shape.value_type(), service.get_shape(shape.value_type()).unwrap(), false, for_timestamps),
                    )
            }
            ShapeType::Structure => mutate_type_name(service, shape_name),
        }
    } else {
        mutate_type_name_for_streaming(shape_name)
    }
}

fn streaming_members<'a>(shape: &'a Shape) -> Box<Iterator<Item = &'a Member> + 'a> {
    let it = shape
        .members
        .as_ref()
        .into_iter()
        .flat_map(|members| members.values())
        .filter(|&member| member.streaming());
    Box::new(it)
}

fn is_streaming_shape(service: &Service, name: &str) -> bool {
    service.shapes()
           .iter()
           .any(|(_, shape)| streaming_members(shape).any(|member| member.shape == name))
}

// do any type name mutation needed to avoid collisions with Rust types
fn mutate_type_name(service: &Service, type_name: &str) -> String {
    let capitalized = util::capitalize_first(type_name.to_owned());

    // some cloudfront types have underscoare that anger the lint checker
    let without_underscores = capitalized.replace("_", "");

    match &without_underscores[..] {
        // Some services have an 'Error' shape that collides with Rust's Error trait
        "Error" => format!("{}Error", service.service_type_name()),

        // EC2 has a CancelSpotFleetRequestsError struct, avoid collision with our error enum
        "CancelSpotFleetRequests" => "EC2CancelSpotFleetRequests".to_owned(),

        // Glue has a BatchStopJobRunError struct, avoid collision with our error enum
        "BatchStopJobRun" => "GlueBatchStopJobRun".to_owned(),

        // RDS has a conveniently named "Option" type
        "Option" => "RDSOption".to_owned(),

        // otherwise make sure it's rust-idiomatic and capitalized
        _ => without_underscores,
    }
}

// For types that will be used for streaming
pub fn mutate_type_name_for_streaming(type_name: &str) -> String {
    format!("Streaming{}", type_name)
}

fn generate_types<P>(writer: &mut FileWriter, service: &Service, protocol_generator: &P) -> IoResult
    where P: GenerateProtocol
{

    let (serialized_types, deserialized_types) = filter_types(service);

    for (name, shape) in service.shapes().iter() {

        // We generate enums for error types, so no need to create model objects for them
        if shape.exception() {
            continue;
        }

        let type_name = mutate_type_name(service, name);

        let streaming = is_streaming_shape(service, name);
        let deserialized = deserialized_types.contains(&type_name);
        let serialized = serialized_types.contains(&type_name);

        if shape.shape_type == ShapeType::Structure {
            // If botocore includes documentation, clean it up a bit and use it
            if let Some(ref docs) = shape.documentation {
                writeln!(writer, "{}", ::doco::Item(docs))?;
            }

            // generate a rust type for the shape
            if type_name != "String" {
                let generated = generate_struct(service,
                                                &type_name,
                                                shape,
                                                streaming,
                                                serialized,
                                                deserialized,
                                                protocol_generator);
                writeln!(writer, "{}", generated)?;
            }
        }

        if streaming {
            // Add a second type for streaming blobs, which are the only streaming type we can have
            writeln!(writer,
                     "pub struct {streaming_name} {{
                         len: Option<usize>,
                         inner: Box<::futures::Stream<Item=Vec<u8>, Error=::std::io::Error> + Send>
                     }}

                     impl {streaming_name} {{
                         pub fn new<S>(stream: S) -> {streaming_name}
                             where S: ::futures::Stream<Item=Vec<u8>, Error=::std::io::Error> + Send + 'static
                         {{
                             {streaming_name} {{
                                 len: None,
                                 inner: Box::new(stream)
                             }}
                         }}
                     }}

                     impl From<Vec<u8>> for {streaming_name} {{
                         fn from(buf: Vec<u8>) -> {streaming_name} {{
                             {streaming_name} {{
                                 len: Some(buf.len()),
                                 inner: Box::new(::futures::stream::once(Ok(buf)))
                             }}
                         }}
                     }}

                     impl fmt::Debug for {streaming_name} {{
                         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {{
                             write!(f, \"<{name}: streaming content, len = {{:?}}>\", self.len)
                         }}
                     }}

                     impl ::futures::Stream for {streaming_name} {{
                         type Item = Vec<u8>;
                         type Error = ::std::io::Error;

                         fn poll(&mut self) -> ::futures::Poll<Option<Self::Item>, Self::Error> {{
                             self.inner.poll()
                         }}
                     }}",
                     name = type_name,
                     streaming_name = mutate_type_name_for_streaming(&type_name))?;
        }

        if deserialized {
            if let Some(deserializer) =
                protocol_generator.generate_deserializer(&type_name, shape, service) {
                assert!(protocol_generator.deserialize_trait().is_none());
                writeln!(writer, "{}", deserializer)?;
            }
        }

        if serialized {
            if let Some(serializer) =
                protocol_generator.generate_serializer(&type_name, shape, service) {
                assert!(protocol_generator.serialize_trait().is_none());
                writeln!(writer, "{}", serializer)?;
            }
        }
    }
    Ok(())
}

fn generate_struct<P>(service: &Service,
                      name: &str,
                      shape: &Shape,
                      streaming: bool,
                      serialized: bool,
                      deserialized: bool,
                      protocol_generator: &P)
                      -> String
    where P: GenerateProtocol
{
    let mut derived = vec!["Default", "Debug"];

    // Streaming is implemented with Box<Stream<...>>, so we can't derive Clone nor PartialEq.
    // This affects both the streaming struct itself, and structs which contain it.
    if !streaming && streaming_members(shape).next().is_none() {
        derived.push("Clone");
        derived.push("PartialEq");
    }

    if serialized {
        if let Some(serialize_trait) = protocol_generator.serialize_trait() {
            derived.push(serialize_trait);
        }
    }

    if deserialized {
        if let Some(deserialize_trait) = protocol_generator.deserialize_trait() {
            derived.push(deserialize_trait);
        }
    }

    let attributes = format!("#[derive({})]", derived.join(","));
    let test_attributes = if derived.iter().any(|&x| x == "Deserialize") && !derived.iter().any(|&x| x == "Serialize") {
        "\n#[cfg_attr(test, derive(Serialize))]"
    } else {
        ""
    };

    if shape.members.is_none() || shape.members.as_ref().unwrap().is_empty() {
        format!(
            "{attributes}{test_attributes}
            pub struct {name} {{}}
            ",
            attributes = attributes,
            test_attributes = test_attributes,
            name = name,
        )
    } else {
        // Serde attributes are only needed if deriving the Serialize or Deserialize trait
        let need_serde_attrs = derived.iter().any(|&x| x == "Serialize" || x == "Deserialize");
        format!(
            "{attributes}{test_attributes}
            pub struct {name} {{
                {struct_fields}
            }}
            ",
            attributes = attributes,
            test_attributes = test_attributes,
            name = name,
            struct_fields = generate_struct_fields(service, shape, name, need_serde_attrs, protocol_generator),
        )
    }
}

fn generate_struct_fields<P: GenerateProtocol>(service: &Service,
                                               shape: &Shape,
                                               shape_name: &str,
                                               serde_attrs: bool,
                                               protocol_generator: &P)
                                               -> String {
    shape.members.as_ref().unwrap().iter().filter_map(|(member_name, member)| {
        if member.deprecated == Some(true) {
            return None;
        }

        let mut lines: Vec<String> = Vec::new();

        if let Some(ref docs) = member.documentation {
            lines.push(::doco::Item(docs).to_string());
        }

        if serde_attrs {
            lines.push(format!("#[serde(rename=\"{}\")]", member_name));

            if let Some(shape_type) = service.shape_type_for_member(member) {
                if shape_type == ShapeType::Blob {
                    lines.push(
                        "#[serde(
                            deserialize_with=\"::rusoto_core::serialization::SerdeBlob::deserialize_blob\",
                            serialize_with=\"::rusoto_core::serialization::SerdeBlob::serialize_blob\",
                            default,
                        )]".to_owned()
                    );
                } else if !shape.required(member_name) {
                    lines.push("#[serde(skip_serializing_if=\"Option::is_none\")]".to_owned());
                }
            }
        }

        let member_shape = service.shape_for_member(member).unwrap();
        let rs_type = get_rust_type(service,
                                    &member.shape,
                                    member_shape,
                                    member.streaming(),
                                    protocol_generator.timestamp_type());
        let name = generate_field_name(member_name);

        // For structs that can contain another of themselves, we need to box them.
        if shape_name == rs_type {
            if shape.required(member_name) {
                lines.push(format!("pub {}: Box<{}>,", name, rs_type))
            } else if name == "type" {
                lines.push(format!("pub aws_{}: Box<Option<{}>>,", name,rs_type))
            } else {
                lines.push(format!("pub {}: Box<Option<{}>>,", name, rs_type))
            }
        } else {
            if shape.required(member_name) {
                lines.push(format!("pub {}: {},", name, rs_type))
            } else if name == "type" {
                lines.push(format!("pub aws_{}: Option<{}>,", name,rs_type))
            } else {
                lines.push(format!("pub {}: Option<{}>,", name, rs_type))
            }
        }

        Some(lines.join("\n"))
    }).collect::<Vec<String>>().join("\n")
}

fn error_type_name(service: &Service, name: &str) -> String {
    let type_name = mutate_type_name(service, name);
    format!("{}Error", type_name)
}


text:
<?xml version="1.0"?>
<entry type="selector" name="reset" return="">
  <title>:reset Selector</title>
  <sample>:reset</sample>
  <signature>
    <added>1.0</added>
  </signature>
  <desc>Selects all elements of type reset.</desc>
  <longdesc>

:reset is equivalent to [type="reset"]

  </longdesc>
  <note id="jquery-selector-extension-alt" type="additional" data-selector=":reset" data-alt="[type="reset"]"/>
  <example>
    <desc>Finds all reset inputs.</desc>
    <![CDATA[
var input = $( "input:reset" ).css({
  background: "yellow",
  border: "3px red solid"
});
$( "div" )
  .text( "For this type jQuery found " + input.length + "." )
  .css( "color", "red" );

// Prevent form submission
$( "form" ).submit(function( event ) {
  event.preventDefault();
});
]]>
    <css><![CDATA[
  textarea {
    height: 45px;
  }
]]></css>
    <![CDATA[
<form>
  <input type="button" value="Input Button">
  <input type="checkbox">
  <input type="file">
  <input type="hidden">
  <input type="image">
  <input type="password">
  <input type="radio">
  <input type="reset">
  <input type="submit">
  <input type="text">
  <select>
    <option>Option</option>
  </select>
  <textarea></textarea>
  <button>Button</button>
</form>

]]>
  </example>
  <category slug="selectors/form-selectors"/>
  <category slug="selectors/jquery-selector-extensions"/>
  <category slug="version/1.0"/>
</entry>

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;
using log4net;
using Metrolib.Controls;
using Tailviewer.Api;
using Tailviewer.BusinessLogic.DataSources;
using Tailviewer.BusinessLogic.Searches;
using Tailviewer.Core;
using Tailviewer.Settings;
using Tailviewer.Ui.LogView.Any;
using Tailviewer.Ui.LogView.DataSource;
using Tailviewer.Ui.LogView.DeltaTimes;
using Tailviewer.Ui.LogView.ElapsedTime;
using Tailviewer.Ui.LogView.LineNumbers;
using Tailviewer.Ui.LogView.LogLevels;
using Tailviewer.Ui.LogView.Messages;
using Tailviewer.Ui.LogView.Timestamps;
using Properties = Tailviewer.Core.Properties;

namespace Tailviewer.Ui.LogView
{
	public class LogEntryListView
		: Grid
		, ILogSourceListener
	{
		private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

		public static readonly DependencyProperty DataSourceProperty =
			DependencyProperty.Register("DataSource", typeof(IDataSource), typeof(LogEntryListView),
				new PropertyMetadata(propertyChangedCallback: null));

		public static readonly DependencyProperty LogSourceProperty =
			DependencyProperty.Register("LogSource", typeof(ILogSource), typeof(LogEntryListView),
				new PropertyMetadata(defaultValue: null, propertyChangedCallback: OnLogFileChanged));

		public static readonly DependencyProperty SearchProperty =
			DependencyProperty.Register("Search", typeof(ILogSourceSearch), typeof(LogEntryListView),
				new PropertyMetadata(defaultValue: null, propertyChangedCallback: OnSearchChanged));

		public static readonly DependencyProperty FollowTailProperty =
			DependencyProperty.Register("FollowTail", typeof(bool), typeof(LogEntryListView),
				new PropertyMetadata(defaultValue: false, propertyChangedCallback: OnFollowTailChanged));

		public static readonly DependencyProperty ShowLineNumbersProperty =
			DependencyProperty.Register("ShowLineNumbers", typeof(bool), typeof(LogEntryListView),
				new PropertyMetadata(defaultValue: true, propertyChangedCallback: OnShowLineNumbersChanged));

		public static readonly DependencyProperty ShowDeltaTimesProperty =
			DependencyProperty.Register("ShowDeltaTimes", typeof(bool), typeof(LogEntryListView),
			                            new PropertyMetadata(defaultValue: false, propertyChangedCallback: OnShowDeltaTimesChanged));

		public static readonly DependencyProperty ShowElapsedTimeProperty =
			DependencyProperty.Register("ShowElapsedTime", typeof(bool), typeof(LogEntryListView),
			                            new PropertyMetadata(defaultValue: false, propertyChangedCallback: OnShowElapsedTimeChanged));

		public static readonly DependencyProperty CurrentLineProperty =
			DependencyProperty.Register("CurrentLine", typeof(LogLineIndex), typeof(LogEntryListView),
				new PropertyMetadata(default(LogLineIndex), OnCurrentLineChanged));

		public static readonly DependencyProperty ColorByLevelProperty =
			DependencyProperty.Register("ColorByLevel", typeof(bool), typeof(LogEntryListView),
				new PropertyMetadata(defaultValue: false, propertyChangedCallback: OnColorByLevelChanged));

		public static readonly DependencyProperty MergedDataSourceDisplayModeProperty = DependencyProperty.Register(
			"MergedDataSourceDisplayMode", typeof(DataSourceDisplayMode), typeof(LogEntryListView),
			new PropertyMetadata(default(DataSourceDisplayMode), OnMergedDataSourceDisplayModeChanged));

		public static readonly DependencyProperty SelectedIndicesProperty = DependencyProperty.Register(
			"SelectedIndices", typeof(IEnumerable<LogLineIndex>), typeof(LogEntryListView), new PropertyMetadata(new LogLineIndex[0], OnSelectedIndicesChanged));

		public static readonly DependencyProperty SettingsProperty = DependencyProperty.Register(
		                                                "Settings", typeof(ILogViewerSettings), typeof(LogEntryListView), new PropertyMetadata(null, OnSettingsChanged));

		public static readonly TimeSpan MaximumRefreshInterval = TimeSpan.FromMilliseconds(value: 33);

		private readonly IReadOnlyDictionary<IColumnDescriptor, Func<TextSettings, AbstractLogColumnPresenter>>
			_columnPresenterFactories;
		private readonly Dictionary<IColumnDescriptor, AbstractLogColumnPresenter> _columnPresenters;
		private readonly Dictionary<IColumnDescriptor, ColumnDefinition> _columnDefinitionsByColumn;
		private readonly Dictionary<ColumnDefinition, IColumnDescriptor> _columnsByColumnDefinition;
		private readonly IReadOnlyList<IColumnDescriptor> _fixedColumns;
		private readonly ColumnDefinition _messageColumnDefinition;

		private readonly DataSourceCanvas _dataSourceCanvas;
		private readonly DeltaTimeColumnPresenter _deltaTimesColumn;
		private readonly ElapsedTimeColumnPresenter _elapsedTimeColumn;

		private readonly FlatScrollBar _horizontalScrollBar;

		private readonly OriginalLineNumberColumnPresenter _lineNumberColumn;
		private readonly DispatcherTimer _timer;
		private readonly FlatScrollBar _verticalScrollBar;

		private int _maxLineWidth;
		private int _pendingModificationsCount;
		private TextSettings _textSettings;
		private TextBrushes _textBrushes;

		static LogEntryListView()
		{
			DefaultStyleKeyProperty.OverrideMetadata(typeof(LogEntryListView),
				new FrameworkPropertyMetadata(typeof(LogEntryListView)));
		}

		public LogEntryListView()
		{
			var textSettings = new TextSettings();
			var textBrushes = new TextBrushes(null);

			RowDefinitions.Add(new RowDefinition { Height = new GridLength(value: 1, type: GridUnitType.Star) });
			RowDefinitions.Add(new RowDefinition { Height = new GridLength(value: 1, type: GridUnitType.Auto) });

			_verticalScrollBar = new FlatScrollBar
			{
				Name = "PART_VerticalScrollBar",
				Thickness = 18
			};
			_verticalScrollBar.ValueChanged += VerticalScrollBarOnValueChanged;
			_verticalScrollBar.Scroll += VerticalScrollBarOnScroll;
			_verticalScrollBar.SetValue(RowProperty, value: 0);
			_verticalScrollBar.SetValue(ColumnProperty, value: 6);

			_horizontalScrollBar = new FlatScrollBar
			{
				Name = "PART_HorizontalScrollBar",
				Orientation = Orientation.Horizontal,
				Thickness = 18
			};
			_horizontalScrollBar.SetValue(RowProperty, value: 1);
			_horizontalScrollBar.SetValue(ColumnProperty, value: 0);
			_horizontalScrollBar.SetValue(ColumnSpanProperty, value: 6);

			_columnPresenterFactories = new Dictionary<IColumnDescriptor, Func<TextSettings, AbstractLogColumnPresenter>>
			{
				{Columns.DeltaTime, settings => new DeltaTimeColumnPresenter(settings)},
				{Columns.ElapsedTime, settings => new ElapsedTimeColumnPresenter(settings) },
				{Columns.OriginalLineNumber, settings => new OriginalLineNumberColumnPresenter(settings) },
				{Columns.LogLevel, settings => new  LogLevelColumnPresenter(settings)},
				{Columns.Message, settings => new MessageColumnPresenter(settings) },
				{Columns.Timestamp, settings => new TimestampColumnPresenter(settings)}
			};
			_columnPresenters = new Dictionary<IColumnDescriptor, AbstractLogColumnPresenter>();
			_columnDefinitionsByColumn = new Dictionary<IColumnDescriptor, ColumnDefinition>();
			_columnsByColumnDefinition = new Dictionary<ColumnDefinition, IColumnDescriptor>();

			_lineNumberColumn = (OriginalLineNumberColumnPresenter) AddColumn(Columns.OriginalLineNumber);
			_lineNumberColumn.SetValue(MarginProperty, new Thickness(left: 5, top: 0, right: 5, bottom: 0));

			_dataSourceCanvas = new DataSourceCanvas(textSettings);
			_dataSourceCanvas.SetValue(RowProperty, value: 0);
			_dataSourceCanvas.SetValue(ColumnProperty, value: 1);
			_dataSourceCanvas.SetValue(MarginProperty, new Thickness(left: 0, top: 0, right: 5, bottom: 0));
			ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(value: 1, type: GridUnitType.Auto) });

			_deltaTimesColumn = (DeltaTimeColumnPresenter) AddColumn(Columns.DeltaTime);
			_deltaTimesColumn.Visibility = Visibility.Collapsed;
			_deltaTimesColumn.SetValue(MarginProperty, new Thickness(left: 0, top: 0, right: 5, bottom: 0));

			_elapsedTimeColumn = (ElapsedTimeColumnPresenter) AddColumn(Columns.ElapsedTime);
			_elapsedTimeColumn.Visibility = Visibility.Collapsed;
			_elapsedTimeColumn.SetValue(MarginProperty, new Thickness(left: 0, top: 0, right: 5, bottom: 0));

			_fixedColumns = _columnPresenters.Keys.ToList();

			_messageColumnDefinition = new ColumnDefinition { Width = new GridLength(value: 1, type: GridUnitType.Star) };
			ColumnDefinitions.Add(_messageColumnDefinition);
			var messageColumnIndex = ColumnDefinitions.IndexOf(_messageColumnDefinition);

			PartTextCanvas = new TextCanvas(_horizontalScrollBar, _verticalScrollBar, textSettings);
			PartTextCanvas.SetValue(RowProperty, value: 0);
			PartTextCanvas.SetValue(ColumnProperty, value: messageColumnIndex);
			PartTextCanvas.MouseWheelDown += TextCanvasOnMouseWheelDown;
			PartTextCanvas.MouseWheelUp += TextCanvasOnMouseWheelUp;
			PartTextCanvas.SizeChanged += TextCanvasOnSizeChanged;
			PartTextCanvas.VisibleLinesChanged += TextCanvasOnVisibleLinesChanged;
			PartTextCanvas.RequestBringIntoView += TextCanvasOnRequestBringIntoView;
			PartTextCanvas.VisibleSectionChanged += TextCanvasOnVisibleSectionChanged;
			PartTextCanvas.OnSelectionChanged += TextCanvasOnOnSelectionChanged;

			ChangeTextSettings(textSettings, textBrushes);

			var separator = new Rectangle
			{
				Fill = new SolidColorBrush(Color.FromRgb(225, 228, 232)),
				Width = 2
			};
			separator.SetValue(RowProperty, value: 0);
			separator.SetValue(ColumnProperty, value: messageColumnIndex);
			separator.SetValue(MarginProperty, new Thickness(left: 0, top: 0, right: 5, bottom: 0));
			ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(value: 1, type: GridUnitType.Auto) });

			Children.Add(_lineNumberColumn);
			Children.Add(_dataSourceCanvas);
			Children.Add(_deltaTimesColumn);
			Children.Add(_elapsedTimeColumn);
			Children.Add(separator);
			Children.Add(PartTextCanvas);
			Children.Add(_verticalScrollBar);
			Children.Add(_horizontalScrollBar);

			_timer = new DispatcherTimer(DispatcherPriority.Normal)
				{
					Interval = MaximumRefreshInterval,
				};
			_timer.Tick += OnTimer;
			Loaded += OnLoaded;
			Unloaded +=  OnUnloaded;
		}

		public DataSourceDisplayMode MergedDataSourceDisplayMode
		{
			get { return (DataSourceDisplayMode) GetValue(MergedDataSourceDisplayModeProperty); }
			set { SetValue(MergedDataSourceDisplayModeProperty, value); }
		}

		public bool ColorByLevel
		{
			get { return (bool) GetValue(ColorByLevelProperty); }
			set { SetValue(ColorByLevelProperty, value); }
		}

		public LogLineIndex CurrentLine
		{
			get { return (LogLineIndex) GetValue(CurrentLineProperty); }
			set { SetValue(CurrentLineProperty, value); }
		}

		public bool ShowLineNumbers
		{
			get { return (bool) GetValue(ShowLineNumbersProperty); }
			set { SetValue(ShowLineNumbersProperty, value); }
		}

		public bool ShowDeltaTimes
		{
			get { return (bool)GetValue(ShowDeltaTimesProperty); }
			set { SetValue(ShowDeltaTimesProperty, value); }
		}

		public bool ShowElapsedTime
		{
			get { return (bool)GetValue(ShowElapsedTimeProperty); }
			set { SetValue(ShowElapsedTimeProperty, value); }
		}

		public bool FollowTail
		{
			get { return (bool) GetValue(FollowTailProperty); }
			set { SetValue(FollowTailProperty, value); }
		}

		public int PendingModificationsCount => _pendingModificationsCount;

		public ScrollBar VerticalScrollBar => _verticalScrollBar;

		public ScrollBar HorizontalScrollBar => _horizontalScrollBar;

		public IDataSource DataSource
		{
			get { return (IDataSource) GetValue(DataSourceProperty); }
			set { SetValue(DataSourceProperty, value); }
		}

		public ILogSource LogSource
		{
			get { return (ILogSource) GetValue(LogSourceProperty); }
			set { SetValue(LogSourceProperty, value); }
		}

		public ILogSourceSearch Search
		{
			get { return (ILogSourceSearch) GetValue(SearchProperty); }
			set { SetValue(SearchProperty, value); }
		}

		public List<TextLine> VisibleTextLines => PartTextCanvas.VisibleTextLines;

		public IEnumerable<LogLineIndex> SelectedIndices
		{
			get { return (IEnumerable<LogLineIndex>)GetValue(SelectedIndicesProperty); }
			set { SetValue(SelectedIndicesProperty, value); }
		}

		public TextCanvas PartTextCanvas { get; }

		public int SelectedSearchResultIndex
		{
			get { return PartTextCanvas.SelectedSearchResultIndex; }
			set { PartTextCanvas.SelectedSearchResultIndex = value; }
		}

		public ILogViewerSettings Settings
		{
			get { return (ILogViewerSettings)GetValue(SettingsProperty); }
			set { SetValue(SettingsProperty, value); }
		}

		public void OnLogFileModified(ILogSource logSource, LogSourceModification modification)
		{
			var width = _textSettings.EstimateWidthUpperLimit(logSource.GetProperty(TextProperties.MaxCharactersInLine));
			var upperWidth = (int) Math.Ceiling(width);

			// Setting an integer is an atomic operation and thus no
			// special synchronization is required.
			_maxLineWidth = Math.Max(_maxLineWidth, upperWidth);

			Interlocked.Increment(ref _pendingModificationsCount);
		}

		private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
		{
			_timer.Start();
		}

		private void OnUnloaded(object sender, RoutedEventArgs routedEventArgs)
		{
			_timer.Stop();
		}

		private void ChangeDisplay(bool gridDisplay)
		{
			if (gridDisplay)
			{
				var columns = LogSource.Columns;
				var missingColumns = columns.Except(_columnPresenters.Keys).ToList();
				var superfluousColumns = _columnPresenters.Keys.Except(columns).ToList();

				foreach (var column in superfluousColumns)
				{
					RemoveColumn(column);
				}

				foreach (var column in missingColumns)
				{
					AddColumn(column);
				}
			}
			else
			{
				var superfluousColumns = _columnPresenters.Keys.Except(_fixedColumns).ToList();
				foreach (var column in superfluousColumns)
				{
					RemoveColumn(column);
				}
			}
		}

		private AbstractLogColumnPresenter CreatePresenterFor(IColumnDescriptor column)
		{
			if (_columnPresenterFactories.TryGetValue(column, out var factory))
			{
				return factory(_textSettings);
			}

			var columnPresenterType = typeof(AnyColumnPresenter<>).MakeGenericType(column.DataType);
			var presenter = (AbstractLogColumnPresenter)Activator.CreateInstance(columnPresenterType, new object[] {column, _textSettings});
			return presenter;
		}

		private AbstractLogColumnPresenter AddColumn(IColumnDescriptor column)
		{
			var columnPresenter = CreatePresenterFor(column);

			// The 2nd column is reserved for the data source name which hasn't been
			// ported to the new ILogFileColumnPresenter interface just yet
			int columnIndex;
			if (_columnPresenters.Count == 0)
			{
				columnIndex = 0;
			}
			else if (Equals(column, Columns.Message))
			{
				columnIndex = ColumnDefinitions.IndexOf(_messageColumnDefinition);
			}
			else
			{
				columnIndex = _columnPresenters.Count + 1;
			}

			columnPresenter.SetValue(RowProperty, 0);
			columnPresenter.SetValue(ColumnProperty, columnIndex);
			_columnPresenters.Add(columnPresenter.Column, columnPresenter);

			var columnDefinition = new ColumnDefinition {Width = new GridLength(value: 1, type: GridUnitType.Auto)};
			_columnDefinitionsByColumn.Add(columnPresenter.Column, columnDefinition);
			_columnsByColumnDefinition.Add(columnDefinition, columnPresenter.Column);

			int insertionIndex;
			if (_messageColumnDefinition != null)
			{
				insertionIndex = ColumnDefinitions.IndexOf(_messageColumnDefinition);
			}
			else
			{
				insertionIndex = ColumnDefinitions.Count;
			}
			ColumnDefinitions.Insert(insertionIndex, columnDefinition);

			return columnPresenter;
		}

		private void RemoveColumn(IColumnDescriptor column)
		{
			if (!_columnPresenters.Remove(column))
			{
				Log.WarnFormat("Unable to remove column '{0}' it's not presented", column);
				return;
			}

			if (!_columnDefinitionsByColumn.TryGetValue(column, out var columnDefinition))
			{
				Log.ErrorFormat("Inconsistency detected: A column presenter exists, but not column definition for column '{0}'!", column);
				return;
			}

			var firstIndex = ColumnDefinitions.IndexOf(columnDefinition);
			_columnDefinitionsByColumn.Remove(column);
			_columnsByColumnDefinition.Remove(columnDefinition);
			ColumnDefinitions.Remove(columnDefinition);

			OffsetColumnsFrom(firstIndex, -1);
		}

		private void OffsetColumnsFrom(int firstColumnIndex, int offset)
		{
			for (int i = firstColumnIndex; i < ColumnDefinitions.Count; ++i)
			{
				var columnDefinition = ColumnDefinitions[i];
				var column = _columnsByColumnDefinition[columnDefinition];
				var presenter = _columnPresenters[column];

				var currentColumn = (int) presenter.GetValue(Grid.ColumnProperty);
				presenter.SetValue(Grid.ColumnProperty, currentColumn + offset);
			}
		}

		private static void OnMergedDataSourceDisplayModeChanged(DependencyObject dependencyObject,
			DependencyPropertyChangedEventArgs args)
		{
			((LogEntryListView) dependencyObject).OnMergedDataSourceDisplayModeChanged((DataSourceDisplayMode) args.NewValue);
		}

		private void OnMergedDataSourceDisplayModeChanged(DataSourceDisplayMode displayMode)
		{
			_dataSourceCanvas.DisplayMode = displayMode;
		}

		private static void OnSearchChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
		{
			((LogEntryListView) dependencyObject).OnSearchChanged((ILogSourceSearch) args.NewValue);
		}

		private void OnSearchChanged(ILogSourceSearch search)
		{
			PartTextCanvas.Search = search;
		}

		private static void OnColorByLevelChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
		{
			((LogEntryListView) dependencyObject).OnColorByLevelChanged((bool) args.NewValue);
		}

		private void OnColorByLevelChanged(bool colorByLevel)
		{
			PartTextCanvas.ColorByLevel = colorByLevel;
		}

		private static void OnCurrentLineChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
		{
			((LogEntryListView) dependencyObject).OnCurrentLineChanged((LogLineIndex) args.NewValue);
		}

		private static void OnShowLineNumbersChanged(DependencyObject dependencyObject,
			DependencyPropertyChangedEventArgs args)
		{
			((LogEntryListView) dependencyObject).OnShowLineNumbersChanged((bool) args.NewValue);
		}

		private void OnShowLineNumbersChanged(bool showLineNumbers)
		{
			_lineNumberColumn.Visibility = showLineNumbers
				? Visibility.Visible
				: Visibility.Collapsed;
			UpdateColumn(_lineNumberColumn);
		}

		private static void OnShowElapsedTimeChanged(DependencyObject dependencyObject,
		                                            DependencyPropertyChangedEventArgs args)
		{
			((LogEntryListView)dependencyObject).OnShowElapsedTimeChanged((bool)args.NewValue);
		}

		private void OnShowElapsedTimeChanged(bool showLineNumbers)
		{
			_elapsedTimeColumn.Visibility = showLineNumbers
				? Visibility.Visible
				: Visibility.Collapsed;
			UpdateColumn(_elapsedTimeColumn);
		}

		private static void OnShowDeltaTimesChanged(DependencyObject dependencyObject,
		                                             DependencyPropertyChangedEventArgs args)
		{
			((LogEntryListView)dependencyObject).OnShowDeltaTimesChanged((bool)args.NewValue);
		}

		private void OnShowDeltaTimesChanged(bool showLineNumbers)
		{
			_deltaTimesColumn.Visibility = showLineNumbers
				? Visibility.Visible
				: Visibility.Collapsed;
			UpdateColumn(_deltaTimesColumn);
		}

		private void OnCurrentLineChanged(LogLineIndex index)
		{
			var current = PartTextCanvas.CurrentlyVisibleSection;
			if (index != LogLineIndex.Invalid)
			{
				PartTextCanvas.CurrentLine = (int) index;
				//< We don't want to call BringIntoView() everytime because that one scrolls to fully
				// bring a line into view. This would mean that if the currently visible section changed
				// so that the top line is only partially visible, then this method would always bring
				// it fully visible. Removing the following filter would completely remove per pixel scrolling...
				if (current.Index != index)
					_verticalScrollBar.Value = (int) index * _textSettings.LineHeight;
			}
		}

		private void TextCanvasOnVisibleSectionChanged(LogSourceSection section)
		{
			CurrentLine = section.Index;
		}

		private void TextCanvasOnOnSelectionChanged(HashSet<LogLineIndex> selectedIndices)
		{
			SelectedIndices = selectedIndices.ToList();
			SelectionChanged?.Invoke(selectedIndices);
		}

		public event Action<IEnumerable<LogLineIndex>> SelectionChanged;

		private void TextCanvasOnRequestBringIntoView(LogLineIndex logLineIndex, LogLineMatch match)
		{
			BringIntoView(logLineIndex, match);
		}

		public void BringIntoView(LogLineIndex logLineIndex, LogLineMatch match = new LogLineMatch())
		{
			var height = PartTextCanvas.ActualHeight;
			var offset = PartTextCanvas.YOffset;
			var start = PartTextCanvas.CurrentLine;
			var diff = logLineIndex - start;
			var minY = diff * _textSettings.LineHeight + offset;
			var maxY = (diff + 1) * _textSettings.LineHeight + offset;
			if (minY < 0)
				_verticalScrollBar.Value += minY;
			else if (maxY > height)
				_verticalScrollBar.Value += maxY - height;

			var minX = _textSettings.GlyphWidth * match.Index;
			var maxX = _textSettings.GlyphWidth * (match.Index + match.Count);
			var visibleMinX = _horizontalScrollBar.Value;
			var visibleMaxX = visibleMinX + _horizontalScrollBar.ViewportSize;
			if (maxX < visibleMinX || minX > visibleMaxX)
				_horizontalScrollBar.Value = minX;

			var logFile = LogSource;
			if (logFile != null)
			{
				var count = logFile.GetProperty(Properties.LogEntryCount);
				if (count > 0)
					FollowTail = logLineIndex >= count - 1;
			}
		}

		private void TextCanvasOnVisibleLinesChanged()
		{
			foreach (var columnPresenter in _columnPresenters.Values)
			{
				UpdateColumn(columnPresenter);
			}

			_dataSourceCanvas.UpdateDataSources(DataSource,
			                                    PartTextCanvas.CurrentlyVisibleSection,
			                                    PartTextCanvas.YOffset);
		}

		private void UpdateColumn(ILogFileColumnPresenter column)
		{
			column.FetchValues(LogSource,
			                   PartTextCanvas.CurrentlyVisibleSection,
			                   PartTextCanvas.YOffset);
		}

		private void TextCanvasOnSizeChanged(object sender, SizeChangedEventArgs sizeChangedEventArgs)
		{
			UpdateScrollViewerRegions();
		}

		private void TextCanvasOnMouseWheelUp()
		{
			var delta = _verticalScrollBar.Value - _verticalScrollBar.Minimum;
			var linesToScroll = Settings?.LinesScrolledPerWheelTick ?? LogViewerSettings.DefaultLinesScrolledPerWheelTick;
			var heightToScroll = linesToScroll * _textSettings.LineHeight;
			var toScroll = Math.Min(delta, heightToScroll);

			if (toScroll > 0)
			{
				FollowTail = false;
				_verticalScrollBar.Value -= toScroll;
			}
		}

		private void TextCanvasOnMouseWheelDown()
		{
			var delta = _verticalScrollBar.Maximum - _verticalScrollBar.Value;
			var linesToScroll = Settings?.LinesScrolledPerWheelTick ?? LogViewerSettings.DefaultLinesScrolledPerWheelTick;
			var heightToScroll = linesToScroll * _textSettings.LineHeight;
			// We might not be able to scroll that far because there's less content available so we'll have to clamp
			// that value...
			var maximumPossibleScroll = Math.Min(delta, heightToScroll);
			_verticalScrollBar.Value += maximumPossibleScroll;

			if (_verticalScrollBar.Value >= _verticalScrollBar.Maximum)
				FollowTail = true;
		}

		private static void OnSettingsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			((LogEntryListView) d).OnSettingsChanged((ILogViewerSettings)e.NewValue);
		}

		private void OnSettingsChanged(ILogViewerSettings settings)
		{
			var textSettings = settings != null
				? new TextSettings(settings.FontSize, settings.TabWidth)
				: TextSettings.Default;
			var textBrushes = new TextBrushes(settings);
			ChangeTextSettings(textSettings, textBrushes);
		}

		private void ChangeTextSettings(TextSettings textSettings, TextBrushes textBrushes)
		{
			_textSettings = textSettings;
			_textBrushes = textBrushes;

			_verticalScrollBar.SetValue(RangeBase.SmallChangeProperty, _textSettings.LineHeight);
			_verticalScrollBar.SetValue(RangeBase.LargeChangeProperty, 10 * _textSettings.LineHeight);

			_horizontalScrollBar.SetValue(RangeBase.SmallChangeProperty, _textSettings.LineHeight);
			_horizontalScrollBar.SetValue(RangeBase.LargeChangeProperty, 10 * _textSettings.LineHeight);

			foreach (var columnPresenter in _columnPresenters.Values)
			{
				columnPresenter.TextSettings = _textSettings;
			}
			PartTextCanvas.ChangeTextSettings(_textSettings, _textBrushes);

			if (LogSource != null)
			{
				TextCanvasOnVisibleLinesChanged();
			}
		}

		private static void OnFollowTailChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			((LogEntryListView) d).OnFollowTailChanged((bool) e.NewValue);
		}

		public event Action<bool> FollowTailChanged;

		private void OnFollowTailChanged(bool followTail)
		{
			if (followTail)
				ScrollToBottom();

			FollowTailChanged?.Invoke(followTail);
		}

		private void ScrollToBottom()
		{
			_verticalScrollBar.Value = _verticalScrollBar.Maximum;
		}

		public void OnTimer(object sender, EventArgs args)
		{
			if (Interlocked.Exchange(ref _pendingModificationsCount, value: 0) > 0 || PartTextCanvas.RequiresFurtherUpdate)
			{
				try
				{
					PartTextCanvas.DetermineVerticalOffset();
					PartTextCanvas.CurrentlyVisibleSection = CalculateVisibleSection();

					UpdateScrollViewerRegions();
					ScrollToBottomIfRequired();

					PartTextCanvas.UpdateVisibleLines();

					PartTextCanvas.OnMouseMove();
				}
				catch (Exception e)
				{
					Log.ErrorFormat("Caught unexpected exception while updating: {0}", e);

					// Common sense says that functions which fail once work when tried again.
					// The same goes for this control: If drawing fails then it's conceivable
					// that it will work when we try again in a few milliseconds...
					Interlocked.Increment(ref _pendingModificationsCount);
				}
			}
		}

		private void ScrollToBottomIfRequired()
		{
			if (FollowTail)
				ScrollToBottom();
		}

		/// <summary>
		///     The section of the log file that is currently visible.
		/// </summary>
		[Pure]
		public LogSourceSection CalculateVisibleSection()
		{
			return PartTextCanvas.CalculateVisibleSection();
		}

		private static void OnLogFileChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			((LogEntryListView) d).OnLogFileChanged(e.OldValue as ILogSource, e.NewValue as ILogSource);
		}

		private void OnLogFileChanged(ILogSource oldValue, ILogSource newValue)
		{
			oldValue?.RemoveListener(this);

			PartTextCanvas.LogSource = newValue;

			if (newValue != null)
			{
				newValue.AddListener(this, TimeSpan.FromMilliseconds(value: 100), maximumLineCount: 10000);

				_maxLineWidth = (int) Math.Ceiling(_textSettings.EstimateWidthUpperLimit(newValue.GetProperty(TextProperties.MaxCharactersInLine)));
				UpdateScrollViewerRegions();
				PartTextCanvas.DetermineVerticalOffset();
				PartTextCanvas.UpdateVisibleSection();
				PartTextCanvas.UpdateVisibleLines();
			}
			else
			{
				_maxLineWidth = 0;
				TextCanvasOnVisibleLinesChanged();
				UpdateScrollViewerRegions();
			}

			MatchScrollbarValueToCurrentLine();
		}

		private void MatchScrollbarValueToCurrentLine()
		{
			var value = PartTextCanvas.CurrentLine * _textSettings.LineHeight;
			if (value >= 0 && value <= _verticalScrollBar.Maximum)
				_verticalScrollBar.Value = value;
			else
				_verticalScrollBar.Value = 0;
		}

		private void UpdateScrollViewerRegions()
		{
			if (LogSource == null)
			{
				_verticalScrollBar.Visibility = Visibility.Collapsed;
			}
			else
			{
				//
				// Depending on the current size of the logfile and the size of the viewport,
				// we need to determine the range of our scrollers.
				//

				UpdateHorizontalScrollbar();
				UpdateVerticalScrollbar();
			}
		}

		private void UpdateHorizontalScrollbar()
		{
			double totalWidth = _maxLineWidth;
			var usableWidth = PartTextCanvas.ActualWidth;
			if (totalWidth > usableWidth)
			{
				_horizontalScrollBar.Minimum = 0;
				_horizontalScrollBar.Maximum = totalWidth - usableWidth;
				_horizontalScrollBar.ViewportSize = usableWidth;
				_horizontalScrollBar.Visibility = Visibility.Visible;
			}
			else
			{
				_horizontalScrollBar.Minimum = 0;
				_horizontalScrollBar.Maximum = 0;
				_horizontalScrollBar.ViewportSize = usableWidth;
				_horizontalScrollBar.Visibility = Visibility.Collapsed;
			}
		}

		private void UpdateVerticalScrollbar()
		{
			var count = LogSource?.GetProperty(Properties.LogEntryCount) ?? 0;
			var totalHeight = count * _textSettings.LineHeight;
			var usableHeight = PartTextCanvas.ActualHeight;
			if (totalHeight > usableHeight)
			{
				_verticalScrollBar.Minimum = 0;
				_verticalScrollBar.Maximum = Math.Ceiling((totalHeight - usableHeight) / _textSettings.LineHeight) *
				                             _textSettings.LineHeight;
				_verticalScrollBar.ViewportSize = usableHeight;
				_verticalScrollBar.Visibility = Visibility.Visible;
			}
			else
			{
				_verticalScrollBar.Minimum = 0;
				_verticalScrollBar.Maximum = 0;
				_verticalScrollBar.ViewportSize = usableHeight;
				_verticalScrollBar.Visibility = Visibility.Collapsed;
			}
		}

		private void VerticalScrollBarOnScroll(object sender, ScrollEventArgs scrollEventArgs)
		{
			if (_lastScroll.NewValue < _lastScroll.OldValue)
				FollowTail = false;
			if (scrollEventArgs.NewValue >= _verticalScrollBar.Maximum)
				FollowTail = true;
		}

		private void VerticalScrollBarOnValueChanged(object sender, RoutedPropertyChangedEventArgs<double> args)
		{
			_lastScroll = new ScrollEvent
			{
				OldValue = args.OldValue,
				NewValue = args.NewValue
			};
		}

		private static void OnSelectedIndicesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			((LogEntryListView) d).OnSelectedIndicesChanged((IEnumerable<LogLineIndex>) e.NewValue);
		}

		private void OnSelectedIndicesChanged(IEnumerable<LogLineIndex> selectedIndices)
		{
			PartTextCanvas.SelectedIndices = selectedIndices;
		}

		public void Select(LogLineIndex index)
		{
			PartTextCanvas.SetSelected(index, SelectMode.Replace);
		}

		public void Select(IEnumerable<LogLineIndex> indices)
		{
			PartTextCanvas.SetSelected(indices, SelectMode.Replace);
		}

		public void Select(params LogLineIndex[] indices)
		{
			PartTextCanvas.SetSelected(indices, SelectMode.Replace);
		}

		public void CopySelectedLinesToClipboard()
		{
			PartTextCanvas.OnCopyToClipboard();
		}

		public void SetHorizontalOffset(double value)
		{
			if (value < _horizontalScrollBar.Minimum)
				_horizontalScrollBar.Value = _horizontalScrollBar.Minimum;
			else if (value > _horizontalScrollBar.Maximum)
				_horizontalScrollBar.Value = _horizontalScrollBar.Maximum;
			else
				_horizontalScrollBar.Value = value;
		}

		#region Scrolling

		private ScrollEvent _lastScroll;

		private struct ScrollEvent
		{
			public double NewValue;
			public double OldValue;
		}

		#endregion
	}
}


text:
using System.Reflection;
using System.Runtime.InteropServices;
using Xunit;

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a361c80e-f6cd-4c57-a96c-002db159c1f4")]

[assembly: CollectionBehavior(DisableTestParallelization = true)]


text:
package org.codehaus.griffon.runtime.core.env;

import griffon.core.env.Environment;
import griffon.core.env.Metadata;

import javax.inject.Inject;
import javax.inject.Provider;

/**
 * @author Andres Almiray
 * @since 2.2.0
 */
public class EnvironmentProvider implements Provider<Environment> {
    @Inject
    private Metadata metadata;

    private static boolean isBlank(String value) {
        return value == null || value.trim().length() == 0;
    }

    @Override
    public Environment get() {
        String envName = System.getProperty(Environment.KEY);
        if (metadata != null && isBlank(envName)) {
            envName = metadata.getEnvironment();
        }

        if (isBlank(envName)) {
            return Environment.DEVELOPMENT;
        }

        Environment env = Environment.resolveEnvironment(envName);
        if (env == null) {
            try {
                env = Environment.valueOf(envName.toUpperCase());
            } catch (IllegalArgumentException e) {
                // ignore
            }
        }
        if (env == null) {
            env = Environment.CUSTOM;
            env.setName(envName);
        }
        return env;
    }
}


text:
A theme based off of the comic book Avengers random line-up.

This theme is installed by default with Atom and can be activated by going to the Themes section in the Settings view `(cmd-,)` and selecting it from the Syntax Themes dropdown menu.

![A screenshot of your theme](https://github.com/SolomonSScott/avengers-syntax/blob/master/img/avengers.png?raw=true)


text:
package com.acme.example.config;

import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;

@Configuration
public class EmbeddedDatabaseContext {

	@Bean
	public DataSource dataSource() {
		return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2)
				.build();
	}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Enum. pl. (Kjbenhavn) 2: 171 (1803)

#### Original name
Sphaeria difformis Schumach.

### Remarks
null