text:
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import SvgIcon from '../../SvgIcon';
export default function createSvgIcon(path, displayName) {
  var Component = React.memo(React.forwardRef(function (props, ref) {
    return /*#__PURE__*/React.createElement(SvgIcon, _extends({}, props, {
      ref: ref
    }), path);
  }));

  if (process.env.NODE_ENV !== 'production') {
    Component.displayName = "".concat(displayName, "Icon");
  }

  Component.muiName = SvgIcon.muiName;
  return Component;
}


text:
(function( ng, app ) {

	"use strict";

	// I provide a repository for the pets.
	app.service(
		"petService",
		function( $q, _ ) {

			// I get the pet with the given ID.
			function getPetByID( id ) {

				var deferred = $q.defer();
				var pet = _.findWithProperty( cache, "id", id );

				if ( pet ) {

					deferred.resolve( ng.copy( pet ) );

				} else {

					deferred.reject();

				}

				return( deferred.promise );

			}

			// I get the pets in the given category.
			function getPetsByCategoryID( categoryID ) {

				var deferred = $q.defer();
				var pets = _.filterWithProperty( cache, "categoryID", categoryID );

				if ( pets ) {

					deferred.resolve( ng.copy( pets ) );

				} else {

					deferred.reject();

				}

				return( deferred.promise );

			}

			// I get a random pet in the given category, less the given pet.
			function getRandomPetExcluding( categoryID, excludePetID ) {

				var deferred = $q.defer();
				var pets = _.filterWithProperty( cache, "categoryID", categoryID );

				if ( pets ) {

					var index = _.random( 0, ( pets.length - 1 ) );

					while ( pets[ index ].id === excludePetID ) {

						index = _.random( 0, ( pets.length - 1 ) );

					}

					deferred.resolve( ng.copy( pets[ index ] ) );

				} else {

					deferred.reject();

				}

				return( deferred.promise );

			}

			// ---------------------------------------------- //
			// ---------------------------------------------- //

			// Set up a collection of constants for our pet categories. Normally, this would be managed
			// by the server-side relational database; but, since we're using static data, this will
			// just make the code easier to read.
			var categories = {
				cats: "cats",
				dogs: "dogs"
			};

			// Set up a collection of size constants.
			var sizes = {
				small: "Small, 25 lbs or less",
				medium: "Medium, 26 - 60 lbs",
				large: "Large, 61 - 100 lbs",
				huge: "Huge, more than 100 lbs"
			};

			// Set up the pets data cache. For this demo, we'll just use static data.
			var cache = [
				{
					id: 1,
					categoryID: categories.dogs,
					name: "Annie",
					breed: "Pit Bull Terrier",
					color: "Tricolor",
					sex: "F",
					size: sizes.small,
					description: "I love chewing on shoes.",
					background: "Annie was found in an abandoned house in Brooklyn.",
					diet: "Annie loves raw chicken necks.",
					medicalHistory: "Annie has all of her shots."
				},
				{
					id: 2,
					categoryID: categories.dogs,
					name: "Voodoo",
					breed: "Chihuahua",
					color: "White With Black",
					sex: "F",
					size: sizes.small,
					description: "I am house-trained, but when I get excited, I sometimes tinkle.",
					background: "Voodoo was one of 17 dogs found in a hoarder's house.",
					diet: "Voodoo will eat just about anything.",
					medicalHistory: "Voodoo has all of his shots and is spayed."
				},
				{
					id: 3,
					categoryID: categories.dogs,
					name: "Frodo",
					breed: "Yorkie",
					color: "Silver With Blue",
					sex: "F",
					size: sizes.small,
					description: "I want to lick your face ... a lot.",
					background: "Frodo went on a great adventure!",
					diet: "Frodo loves chicken and fish and peanut butter.",
					medicalHistory: "Frodo has all of his shots."
				},
				{
					id: 4,
					categoryID: categories.dogs,
					name: "Brook",
					breed: "Labrador Retriever",
					color: "Yellow",
					sex: "M",
					size: sizes.large,
					description: "I'll eat anything, but newspaper makes me gassy.",
					background: "Brook was found walking along George Washington Bridge.",
					diet: "Brook loves any duck-based food.",
					medicalHistory: "Brook has all of her shots."
				},
				{
					id: 5,
					categoryID: categories.dogs,
					name: "Henry",
					breed: "Bulldog",
					color: "Tricolor",
					sex: "M",
					size: sizes.medium,
					description: "I'm surprisingly active and can jump!",
					background: "Henry's owner recently passed and was left with no family.",
					diet: "Henry prefers dry food.",
					medicalHistory: "Henry has all of his shots and is fixed."
				},
				{
					id: 6,
					categoryID: categories.cats,
					name: "Marley",
					breed: "Scottish Fold",
					color: "White",
					sex: "F",
					size: sizes.small,
					description: "I can climb walls like a ninja!",
					background: "Marley was found in an abandoned lot in Brooklyn.",
					diet: "Marley prefers wet food.",
					medicalHistory: "Marley has all of her shots and is spayed."
				},
				{
					id: 7,
					categoryID: categories.cats,
					name: "Jamie",
					breed: "Calico",
					color: "Tricolor",
					sex: "F",
					size: sizes.small,
					description: "I'm extremely people friend, for a cat.",
					background: "Jamie was found under the porch.",
					diet: "Jamie can't stand wet food.",
					medicalHistory: "Jamie has all of her shots and need to be spayed."
				},
				{
					id: 8,
					categoryID: categories.cats,
					name: "Bruno",
					breed: "Uknown",
					color: "Black",
					sex: "M",
					size: sizes.small,
					description: "I'm an escape artist.",
					background: "When found, Bruno was under-nourished.",
					diet: "Bruno loves milk and anything chicken-based.",
					medicalHistory: "Bruno has all of his shots and is fixed."
				},
				{
					id: 9,
					categoryID: categories.cats,
					name: "Wiggles",
					breed: "Burmese",
					color: "Gray",
					sex: "M",
					size: sizes.small,
					description: "I love lasers and chasing my own tail.",
					background: "Wiggles was a feral cat known for his jumping.",
					diet: "Wiggles has no specific dietary information.",
					medicalHistory: "Wiggles has all of his shots."
				},
				{
					id: 10,
					categoryID: categories.cats,
					name: "Cotton",
					breed: "Himalayan",
					color: "Tan With Black",
					sex: "F",
					size: sizes.small,
					description: "I love to cuddle at night.",
					background: "Cotton's owner recently passed.",
					diet: "Cotton will eat just about anything.",
					medicalHistory: "Cotton has all of her shots and needs to be fixed."
				}
			];

			// ---------------------------------------------- //
			// ---------------------------------------------- //

			// Return the public API.
			return({
				getPetByID: getPetByID,
				getPetsByCategoryID: getPetsByCategoryID,
				getRandomPetExcluding: getRandomPetExcluding
			});

		}
	);

})( angular, Demo );

redpajama_set_name: RedPajamaGithub


text:
/*The tree node has data, left child and right child
class Node {
    int data;
    Node* left;
    Node* right;
};

*/

    int getHeight(Node* root) {
        int left=0;
        int right=0;

        if(root->left) left= 1+getHeight(root->left);
        if(root->right) right=1+getHeight(root->right);
        if(!root->left&&!root->right) return 0;

        return max(left,right);
    }


text:
"""
Copyright 2017 Fair Isaac Corp.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

from collections import namedtuple

from cvxpy.problems.problem import Problem
from cvxpy.utilities.deterministic import unique_list

# Used in self._cached_data to check if problem's objective or constraints have
# changed.
CachedProblem = namedtuple('CachedProblem', ['objective', 'constraints'])

# Used by pool.map to send solve result back.
SolveResult = namedtuple(
    'SolveResult', ['opt_value', 'status', 'primal_values', 'dual_values'])

class XpressProblem (Problem):

    """A convex optimization problem associated with the Xpress Optimizer

    Attributes
    ----------
    objective : Minimize or Maximize
        The expression to minimize or maximize.
    constraints : list
        The constraints on the problem variables.
    """

    # The solve methods available.
    REGISTERED_SOLVE_METHODS = {}

    def __init__(self, objective, constraints=None) -> None:

        super(XpressProblem, self).__init__(objective, constraints)
        self._iis = None

    def _reset_iis(self) -> None:
        """Clears the iis information
        """

        self._iis = None
        self._transferRow = None

    def __repr__(self) -> str:
        return "XpressProblem(%s, %s)" % (repr(self.objective),
                                          repr(self.constraints))

    def __neg__(self) -> "XpressProblem":
        return XpressProblem(-self.objective, self.constraints)

    def __add__(self, other):
        if other == 0:
            return self
        elif not isinstance(other, XpressProblem):
            raise NotImplementedError()
        return XpressProblem(self.objective + other.objective,
                             unique_list(self.constraints + other.constraints))

    def __sub__(self, other):
        if not isinstance(other, XpressProblem):
            raise NotImplementedError()
        return XpressProblem(self.objective - other.objective,
                             unique_list(self.constraints + other.constraints))

    def __mul__(self, other):
        if not isinstance(other, (int, float)):
            raise NotImplementedError()
        return XpressProblem(self.objective * other, self.constraints)

    def __div__(self, other):
        if not isinstance(other, (int, float)):
            raise NotImplementedError()
        return XpressProblem(self.objective * (1.0 / other), self.constraints)


text:
package Dpkg::Source::Package::V3::bzr;

use strict;
use warnings;

use base 'Dpkg::Source::Package';

use Cwd;
use File::Basename;
use File::Find;
use File::Temp qw(tempdir);

use Dpkg;
use Dpkg::Gettext;
use Dpkg::Compression;
use Dpkg::ErrorHandling qw(error subprocerr syserr info);
use Dpkg::Version qw(check_version);
use Dpkg::Source::Archive;
use Dpkg::Exit;
use Dpkg::Source::Functions qw(erasedir);

our $CURRENT_MINOR_VERSION = "0";

sub import {
    foreach my $dir (split(/:/, $ENV{PATH})) {
        if (-x "$dir/bzr") {
            return 1;
        }
    }
    error(_g("This source package can only be manipulated using bzr, which is not in the PATH."));
}

sub sanity_check {
    my $srcdir = shift;

    if (! -d "$srcdir/.bzr") {
        error(_g("source directory is not the top directory of a bzr repository (%s/.bzr not present), but Format bzr was specified"),
              $srcdir);
    }

    # Symlinks from .bzr to outside could cause unpack failures, or
    # point to files they shouldn't, so check for and don't allow.
    if (-l "$srcdir/.bzr") {
        error(_g("%s is a symlink"), "$srcdir/.bzr");
    }
    my $abs_srcdir = Cwd::abs_path($srcdir);
    find(sub {
        if (-l $_) {
            if (Cwd::abs_path(readlink($_)) !~ /^\Q$abs_srcdir\E(\/|$)/) {
                error(_g("%s is a symlink to outside %s"),
                      $File::Find::name, $srcdir);
            }
        }
    }, "$srcdir/.bzr");

    return 1;
}

sub can_build {
    my ($self, $dir) = @_;
    return (-d "$dir/.bzr", _g("doesn't contain a bzr repository"));
}

sub do_build {
    my ($self, $dir) = @_;
    my @argv = @{$self->{'options'}{'ARGV'}};
    # TODO: warn here?
    #my @tar_ignore = map { "--exclude=$_" } @{$self->{'options'}{'tar_ignore'}};
    my $diff_ignore_regexp = $self->{'options'}{'diff_ignore_regexp'};

    $dir =~ s{/+$}{}; # Strip trailing /
    my ($dirname, $updir) = fileparse($dir);

    if (scalar(@argv)) {
        usageerr(_g("-b takes only one parameter with format `%s'"),
                 $self->{'fields'}{'Format'});
    }

    my $sourcepackage = $self->{'fields'}{'Source'};
    my $basenamerev = $self->get_basename(1);
    my $basename = $self->get_basename();
    my $basedirname = $basename;
    $basedirname =~ s/_/-/;

    sanity_check($dir);

    my $old_cwd = getcwd();
    chdir($dir) ||
            syserr(_g("unable to chdir to `%s'"), $dir);

    # Check for uncommitted files.
    # To support dpkg-source -i, remove any ignored files from the
    # output of bzr status.
    open(BZR_STATUS, '-|', "bzr", "status") ||
            subprocerr("bzr status");
    my @files;
    while (<BZR_STATUS>) {
        chomp;
        next unless s/^ +//;
        if (! length $diff_ignore_regexp ||
            ! m/$diff_ignore_regexp/o) {
            push @files, $_;
        }
    }
    close(BZR_STATUS) || syserr(_g("bzr status exited nonzero"));
    if (@files) {
        error(_g("uncommitted, not-ignored changes in working directory: %s"),
              join(" ", @files));
    }

    chdir($old_cwd) ||
            syserr(_g("unable to chdir to `%s'"), $old_cwd);

    my $tmp = tempdir("$dirname.bzr.XXXXXX", DIR => $updir);
    push @Dpkg::Exit::handlers, sub { erasedir($tmp) };
    my $tardir = "$tmp/$dirname";

    system("bzr", "branch", $dir, $tardir);
    $? && subprocerr("bzr branch $dir $tardir");

    # Remove the working tree.
    system("bzr", "remove-tree", $tardir);

    # Some branch metadata files are unhelpful.
    unlink("$tardir/.bzr/branch/branch-name",
           "$tardir/.bzr/branch/parent");

    # Create the tar file
    my $debianfile = "$basenamerev.bzr.tar." . $self->{'options'}{'comp_ext'};
    info(_g("building %s in %s"),
         $sourcepackage, $debianfile);
    my $tar = Dpkg::Source::Archive->new(filename => $debianfile,
                                         compression => $self->{'options'}{'compression'},
                                         compression_level => $self->{'options'}{'comp_level'});
    $tar->create('chdir' => $tmp);
    $tar->add_directory($dirname);
    $tar->finish();

    erasedir($tmp);
    pop @Dpkg::Exit::handlers;

    $self->add_file($debianfile);
}

# Called after a tarball is unpacked, to check out the working copy.
sub do_extract {
    my ($self, $newdirectory) = @_;
    my $fields = $self->{'fields'};

    my $dscdir = $self->{'basedir'};

    check_version($fields->{'Version'});

    my $basename = $self->get_basename();
    my $basenamerev = $self->get_basename(1);

    my @files = $self->get_files();
    if (@files > 1) {
        error(_g("format v3.0 uses only one source file"));
    }
    my $tarfile = $files[0];
    if ($tarfile !~ /^\Q$basenamerev\E\.bzr\.tar\.$comp_regex$/) {
        error(_g("expected %s, got %s"),
              "$basenamerev.bzr.tar.$comp_regex", $tarfile);
    }

    erasedir($newdirectory);

    # Extract main tarball
    info(_g("unpacking %s"), $tarfile);
    my $tar = Dpkg::Source::Archive->new(filename => "$dscdir$tarfile");
    $tar->extract($newdirectory);

    sanity_check($newdirectory);

    my $old_cwd = getcwd();
    chdir($newdirectory) ||
            syserr(_g("unable to chdir to `%s'"), $newdirectory);

    # Reconstitute the working tree.
    system("bzr", "checkout");

    chdir($old_cwd) ||
            syserr(_g("unable to chdir to `%s'"), $old_cwd);
}

1;


text:
(function () {
    /**
     * RPC service name to get gadget state.
     * @const
     * @private
     */
    var RPC_SERVICE_GET_STATE = 'RPC_SERVICE_GET_STATE';

    /**
     * RPC service name to set gadget state.
     * @const
     * @private
     */
    var RPC_SERVICE_SET_STATE = 'RPC_SERVICE_SET_STATE';

    /**
     * RPC service name to get current username.
     * @const
     * @private
     */
    var RPC_SERVICE_GET_USERNAME = 'RPC_SERVICE_GET_USERNAME';

    /**
     * RPC service name to get access token.
     * @const
     * @private
     */
    var RPC_SERVICE_GET_ACCESS_TOKEN = 'RPC_SERVICE_GET_ACCESS_TOKEN';

    /**
     * RPC service name to navigate to other page.
     * @const
     * @private
     */
    var RPC_SERVICE_NAVIGATE_PAGE = 'RPC_SERVICE_NAVIGATE_PAGE';

    /**
     * RPC service name fo show gadget
     * @const
     * @private
     */
    var RPC_SERVICE_SHOW_GADGET = 'RPC_SERVICE_SHOW_GADGET';

    /**
     * Service name to resize gadgets.
     * @const
     * @private
     */
    var RPC_SERVICE_RESIZE_GADGET = 'RPC_SERVICE_RESIZE_GADGET';

    /**
     * Service name to restore gadgets.
     * @const
     * @private
     */
    var RPC_SERVICE_RESTORE_GADGET = 'RPC_SERVICE_RESTORE_GADGET';

    /**
     * RPC service name of gadget side callback.
     * @const
     * @private
     */
    var RPC_SERVICE_GADGET_CALLBACK = 'RPC_SERVICE_GADGET_CALLBACK';

	/**
     * RPC service name of lost focus event notifications.
     * @const
     * @private
     */
    var RPC_SERVICE_LOST_FOCUS_CALLBACK = 'RPC_SERVICE_LOST_FOCUS_CALLBACK';

    /**
     * RPC service name of finished loading event notifications.
     * @const
     * @private
     */
    var RPC_SERVICE_FINISHEDLOADING_CALL = 'RPC_SERVICE_FINISHEDLOADING_CALL';

    var username;
    var encodeHash = false;

    /**
     * Serialize the page into formatted hash.
     * @param {Object} states Gadget states
     * @return {String} Serialized page state
     * @private
     */
    var serialize = function (states) {
        var result = '';
        for (var property in states) {
            if (states.hasOwnProperty(property)) {
                var key = property;
                var val = JSON.stringify(states[property]);
                if (encodeHash) {
                    key = encodeURIComponent(key);
                    val = encodeURIComponent(val);
                }
                result += '/' + key + '/' + val;
            }
        }
        return result.substr(1);
    }

    /**
     * Deserialize the page state into an object.
     * @param {String} hash Page state hash string
     * @return {Object} Page state
     * @private
     */
    var deserialize = function (hash) {
        var tokens = hash.split('/');
        var result = {};
        for (var i = 0; i < tokens.length; i += 2) {
            if (typeof tokens[i + 1] != 'undefined') {
                var key = tokens[i];
                var val = tokens[i + 1];
                if (encodeHash) {
                    key = decodeURIComponent(key);
                    val = decodeURIComponent(val);
                }
                result[key] = JSON.parse(val);
            }
        }
        return result;
    }

    /**
     * Get page state from the URL hash.
     * @return {Object} Page state
     * @private
     */
    var getPageState = function () {
        var hash = window.location.hash;
        if (hash.length > 1) {
            return deserialize(hash.substr(1));
        }
        return {};
    }

    /**
     * Send response to gadgets for dashboard API invocations.
     * @param {String} service Name of the requested service
     * @param {String} gadgetId Gadget ID
     * @param {Number} callbackId Callback function ID
     * @param {String} response Response
     * @return {null}
     * @private
     */
    var sendGadgetResponse = function (target, service, response) {
        gadgets.rpc.call(target, RPC_SERVICE_GADGET_CALLBACK, null, service, response);
    }

    /**
     * Get gadget ID from the gadget container ID.
     * @param {String} containerID ID of the container
     * @return {String} Gadget ID
     * @private
     */
    var getGadgetId = function (containerId) {
        return containerId.replace('sandbox-gadget-', '');
    }

    // Register RPC services
    // Get gadget state
    gadgets.rpc.register(RPC_SERVICE_GET_STATE, function () {
        var gadgetState = getPageState()[getGadgetId(this.f)];
        sendGadgetResponse(this.f, RPC_SERVICE_GET_STATE, gadgetState);
    });

    // Set gadget state
    gadgets.rpc.register(RPC_SERVICE_SET_STATE, function (gadgetState) {
        var pageState = getPageState();
        pageState[getGadgetId(this.f)] = gadgetState;
        window.location.hash = serialize(pageState);
        sendGadgetResponse(this.f, RPC_SERVICE_SET_STATE);
    });

    // Get current username
    gadgets.rpc.register(RPC_SERVICE_GET_USERNAME, function () {
        var target = this.f;
        if (username) {
            sendGadgetResponse(target, RPC_SERVICE_GET_USERNAME, username);
            return;
        }

        $.ajax({
            url: '/portal/apis/user',
            type: 'GET',
            dataType: "JSON",
            success: function (data) {
                username = data.username;
                sendGadgetResponse(target, RPC_SERVICE_GET_USERNAME, username);
            },
            error: function () {
                sendGadgetResponse(target, RPC_SERVICE_GET_USERNAME, '');
            }
        });
    });

    // Get access token
    gadgets.rpc.register(RPC_SERVICE_GET_ACCESS_TOKEN, function () {
        var target = this.f;
        var tokenUrl = ues.utils.tenantPrefix() + 'apis/accesstokens/' + ues.global.dashboard.id;
        $.ajax({
            url: tokenUrl,
            type: 'GET',
            dataType: 'JSON',
            data: {
                id: ues.global.dashboard.id
            },
            success: function (data) {
                sendGadgetResponse(target, RPC_SERVICE_GET_ACCESS_TOKEN, data.accessToken);
            }
        });
    });

    // Show already Hidden Gadget
    gadgets.rpc.register(RPC_SERVICE_SHOW_GADGET, function () {
        var gadgetID = getGadgetId(this.f);
        var sandbox = $('#' + gadgetID);
        sandbox.removeClass('ues-hide-gadget');
        sandbox.find('.ues-component-body').show();
        sendGadgetResponse(this.f, RPC_SERVICE_SHOW_GADGET);
    });

    // Navigate to other page
    gadgets.rpc.register(RPC_SERVICE_NAVIGATE_PAGE, function (url) {
        window.open(url, "_self");
    });

    // Resize the gadget
    gadgets.rpc.register(RPC_SERVICE_RESIZE_GADGET, function (options) {
        var block = $('#' + this.f).closest('.grid-stack-item');
        block.css({
            'top': options.top ? 'calc(' + block.css('top') + ' + (' + options.top + '))' : '',
            'left': options.left ? 'calc(' + block.css('left') + ' + (' + options.left + '))' : '',
            'width': options.width || '',
            'height': options.height || '',
            'z-index': 1000
        });

        // If the height is changed, adjust the height of the gadget IFRAME as well.
        if (options.height) {
            var height = parseInt(options.height.replace('px', ''));
            var headingHeight = block.find('.ues-component').hasClass('ues-no-heading') ?
                0 : block.find('.ues-component-heading').height();
            block.find('iframe').height(height - headingHeight - 4);
        }
    });

    // Restore the gadget
    gadgets.rpc.register(RPC_SERVICE_RESTORE_GADGET, function () {
        var block = $('#' + this.f).closest('.grid-stack-item');
        block.css({
            'top': '',
            'left': '',
            'width': '',
            'height': '',
            'z-index': ''
        });
        block.find('iframe').css('height', '');
    });

    //notifies the completion of gadget loading
    gadgets.rpc.register(RPC_SERVICE_FINISHEDLOADING_CALL, function () {
        ues.dashboards.finishedLoadingGadget();
    });

    // Notify each gadgets when the user clicks on the dashboard.
    $(document).on('click', function() {
        $('.ues-component-box iframe').each(function() {
            gadgets.rpc.call($(this).attr('id'), RPC_SERVICE_LOST_FOCUS_CALLBACK, null, null);
        });
    });
})();


text:
bsdznc 'default' do
  action [:create, :stop]
end


text:
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Xen2D;
using XenAspects;

namespace XenGameBase
{
    /// <summary>
    /// Base class for Behaviors.  A Behavior is a unit of functionality for drawing/updating/processing input on an element.
    /// </summary>
    ///
    /// <example>
    /// FadeOverTimeBehavior- fade an element over time (for particles)
    /// TimeToLiveBehavior- release an element after ttl has elapsed (for bullets)
    /// LinearMoveBehavior- scroll a text element on the screen
    /// </example>
    /// <typeparam name="T">The derived type.</typeparam>
    public abstract class BehaviorBase<T> : Component2D<T>, IBehavior
        where T : ComposableObject, new()
    {
        private IElement2D _parent;

        /// <summary>
        /// Gets or sets the draw order.  Behavior draw orders are restricted to the order they are updated.
        /// For behaviors, this property is a pass-through to UpdateOrder.
        /// </summary>
        public override int DrawOrder
        {
            get { return UpdateOrder; }
            set { UpdateOrder = value; }
        }

        public IElement2D Parent
        {
            get { return _parent; }
            set
            {
                if( ( null != _parent ) && ( null != value ) )
                    throw new InvalidOperationException( "cannot set parent twice.  This object must be released and reacquired." );
                _parent = value;
            }
        }

        public bool WantsInput { get; protected set; }

        protected override void DrawInternal( SpriteBatch spriteBatch, Matrix transformFromWorldToCamera ) { }

        protected override void ResetDirectState()
        {
            base.ResetDirectState();
            WantsInput = false;
        }

        public void ProcessInput( ref InputState input, Matrix transformFromCameraToWorld )
        {
            if( WantsInput )
                ProcessInputInternal( ref input, transformFromCameraToWorld );
        }

        protected virtual void ProcessInputInternal( ref InputState input, Matrix transformFromCameraToWorld ) { }
    }

    /// <summary>
    /// Base class for a behavior that acts on targets of the specific generic type.
    /// </summary>
    /// <typeparam name="T">The derived type.</typeparam>
    /// <typeparam name="TargetType">The target type that this behavior operates on.</typeparam>
    public class TargettedBehavior<T, TargetType> : BehaviorBase<TargettedBehavior<T, TargetType>>, IBehavior
        where T : ComposableObject, new()
    {
        protected TargetType _target;

        public static TargettedBehavior<T, TargetType> Acquire( TargetType target )
        {
            var instance = Acquire();
            instance._target = target;
            return instance;
        }

        //protected override void ResetDirectState()
        //{
        //    base.ResetDirectState();
        //    _target = default( TargetType );
        //}
    }
}


text:
local fs = require "howl.platform".fs
local Runner = require "howl.tasks.Runner"
local Utils = require "howl.lib.utils"

--- Names to test when searching for Howlfiles
local Names = { "Howlfile", "Howlfile.lua" }

--- Finds the howl file
-- @treturn string The name of the howl file or nil if not found
-- @treturn string The path of the howl file or the error message if not found
local function FindHowl()
	local currentDirectory = fs.currentDir()

	while true do
		for _, file in ipairs(Names) do
			local howlFile = fs.combine(currentDirectory, file)
			if fs.exists(howlFile) and not fs.isDir(howlFile) then
				return file, currentDirectory
			end
		end

		if currentDirectory == "/" or currentDirectory == "" then
			break
		end
		currentDirectory = fs.getDir(currentDirectory)
	end

	return nil, "Cannot find HowlFile. Looking for '" .. table.concat(Names, "', '") .. "'."
end

--- Create an environment for running howl files
-- @tparam table variables A list of variables to include in the environment
-- @treturn table The created environment
local function SetupEnvironment(variables)
	local env = setmetatable(variables or {}, { __index = _ENV })

	function env.loadfile(path)
		return assert(loadfile(path, env))
	end

	function env.dofile(path)
		return env.loadfile(path)()
	end

	return env
end

--- Setup tasks
-- @tparam howl.Context context The current environment
-- @tparam string howlFile location of Howlfile relative to current directory
-- @treturn Runner The task runner
local function SetupTasks(context, howlFile)
	local tasks = Runner(context)

	context.mediator:subscribe({ "ArgParse", "changed" }, function(options)
		tasks.ShowTime = options:Get "time"
		tasks.Traceback = options:Get "trace"
	end)

	-- Setup an environment
	local environment = SetupEnvironment({
		-- Core globals
		require = require,
		CurrentDirectory = context.root,
		Tasks = tasks,
		Options = context.arguments,
		-- Helper functions
		Verbose = context.logger/"verbose",
		Log = context.logger/"dump",
		File = function(...) return fs.combine(context.root, ...) end,
	})

	context.mediator:publish({ "HowlFile", "env" }, environment, context)

	return tasks, environment
end

--- @export
return {
	FindHowl = FindHowl,
	SetupEnvironment = SetupEnvironment,
	SetupTasks = SetupTasks,
	Names = Names,
}


text:
/***************************************************************************/
/*                                                                         */
/*  ahmodule.h                                                             */
/*                                                                         */
/*    Auto-hinting module (declaration).                                   */
/*                                                                         */
/*  Copyright 2000-2001 Catharon Productions Inc.                          */
/*  Author: David Turner                                                   */
/*                                                                         */
/*  This file is part of the Catharon Typography Project and shall only    */
/*  be used, modified, and distributed under the terms of the Catharon     */
/*  Open Source License that should come with this file under the name     */
/*  `CatharonLicense.txt'.  By continuing to use, modify, or distribute    */
/*  this file you indicate that you have read the license and              */
/*  understand and accept it fully.                                        */
/*                                                                         */
/*  Note that this license is compatible with the FreeType license.        */
/*                                                                         */
/***************************************************************************/

#ifndef __AHMODULE_H__
#define __AHMODULE_H__

#include <ft2build.h>
#include FT_MODULE_H

FT_BEGIN_HEADER

  FT_CALLBACK_TABLE
  const FT_Module_Class  autohint_module_class;

FT_END_HEADER

#endif /* __AHMODULE_H__ */

/* END */


text:
package apple.uikit;

import java.io.*;
import java.nio.*;
import java.util.*;
import com.google.j2objc.annotations.*;
import com.google.j2objc.runtime.*;
import com.google.j2objc.runtime.block.*;
import apple.audiotoolbox.*;
import apple.corefoundation.*;
import apple.coregraphics.*;
import apple.coreservices.*;
import apple.foundation.*;
import apple.coreanimation.*;
import apple.coredata.*;
import apple.coreimage.*;
import apple.coretext.*;
import apple.corelocation.*;

@Library("UIKit/UIKit.h")
@Mapping("UIBaselineAdjustment")
public final class UIBaselineAdjustment extends ObjCEnum {

    @GlobalConstant("UIBaselineAdjustmentAlignBaselines")
    public static final long AlignBaselines = 0L;
    @GlobalConstant("UIBaselineAdjustmentAlignCenters")
    public static final long AlignCenters = 1L;
    @GlobalConstant("UIBaselineAdjustmentNone")
    public static final long None = 2L;

}


text: {# Instantiated by areaEditor.js every time someone adds another rich text to an area #}


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Commands.WebApps.Models;
using Microsoft.Azure.Commands.WebApps.Models.WebApp;
using Microsoft.Azure.Commands.WebApps.Utilities;
using Microsoft.Azure.Management.Internal.Resources;
using Microsoft.Azure.Management.Internal.Resources.Models;
using Microsoft.Azure.Management.Internal.Resources.Utilities;
using Microsoft.Azure.Management.WebSites.Models;
using Microsoft.Azure.Management.WebSites;
using Microsoft.WindowsAzure.Commands.Common;
using System;
using System.Collections;
using System.Linq;
using System.Management.Automation;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Commands.Common.Strategies.Resources;
using Microsoft.Azure.Commands.Common.Strategies.WebApps;
using Microsoft.Azure.Commands.Common.Strategies;
using Microsoft.Azure.Commands.WebApps.Strategies;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.Azure.Commands.WebApps.Properties;
using Microsoft.Rest.Azure.OData;
using Microsoft.Azure.Commands.ResourceManager.Common.Utilities.Models;
using Microsoft.Azure.Management.Internal.Resources.Utilities.Models;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
using System.Collections.Generic;
using System.Security;

namespace Microsoft.Azure.Commands.WebApps.Cmdlets.WebApps
{
    /// <summary>
    /// this commandlet will let you create a new Azure Web app using ARM APIs
    /// </summary>
    [Cmdlet("New", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "WebApp", DefaultParameterSetName = SimpleParameterSet, SupportsShouldProcess = true), OutputType(typeof(PSSite))]
    public class NewAzureWebAppCmdlet : WebAppBaseClientCmdLet
    {
        const string CopyWebAppParameterSet = "WebAppParameterSet";
        const string SimpleParameterSet = "SimpleParameterSet";
        const string PrivateRegistry = "PrivateRegistry";
        const int MaxFreeSites = 10;
        //private AppServicePlan Asp;

        [Parameter(Position = 0, Mandatory = true, HelpMessage = "The name of the resource group.", ParameterSetName = PrivateRegistry)]
        [Parameter(Position = 0, Mandatory = true, HelpMessage = "The name of the resource group.", ParameterSetName = CopyWebAppParameterSet)]
        [Parameter(Position = 0, Mandatory = false, HelpMessage = "The name of the resource group.", ParameterSetName = SimpleParameterSet)]
        [ResourceGroupCompleter]
        [ValidateNotNullOrEmpty]
        public string ResourceGroupName { get; set; }

        [Parameter(Position = 1, Mandatory = true, HelpMessage = "The name of the web app.")]
        [ValidateNotNullOrEmpty]
        [Alias("WebAppName")]
        public string Name { get; set; }

        [Parameter(Position = 0, Mandatory = false, HelpMessage = "The Location of the web app eg: West US.", ParameterSetName = PrivateRegistry)]
        [Parameter(Position = 2, Mandatory = true, HelpMessage = "The Location of the web app eg: West US.", ParameterSetName = CopyWebAppParameterSet)]
        [Parameter(Position = 2, Mandatory = false, HelpMessage = "The Location of the web app eg: West US.", ParameterSetName = SimpleParameterSet)]
        [LocationCompleter("Microsoft.Web/sites", "Microsoft.Web/serverFarms")]
        public string Location { get; set; }

        [Parameter(Position = 3, Mandatory = false, HelpMessage = "The name of the app service plan eg: Default1.")]
        public string AppServicePlan { get; set; }

        [Parameter(Position = 4, Mandatory = false, HelpMessage = "The source web app to clone", ValueFromPipeline = true, ParameterSetName = CopyWebAppParameterSet)]
        [ValidateNotNullOrEmpty]
        public PSSite SourceWebApp { get; set; }

        [Parameter(Position = 5, Mandatory = false, HelpMessage = "Resource Id of existing traffic manager profile", ParameterSetName = CopyWebAppParameterSet)]
        [ValidateNotNullOrEmpty]
        [Alias("TrafficManagerProfileName", "TrafficManagerProfileId")]
        public string TrafficManagerProfile { get; set; }

        [Parameter(Mandatory = true, HelpMessage = "Container Image Name and optional tag, for example (image:tag)", ParameterSetName = PrivateRegistry)]
        [Parameter(Mandatory = false, HelpMessage = "Container Image Name and optional tag, for example (image:tag)", ParameterSetName = SimpleParameterSet)]
        [ValidateNotNullOrEmpty]
        public string ContainerImageName { get; set; }

        [Parameter(Mandatory = true, HelpMessage = "Private Container Registry Server Url", ParameterSetName = PrivateRegistry)]
        [ValidateNotNullOrEmpty]
        public string ContainerRegistryUrl { get; set; }

        [Parameter(Mandatory = true, HelpMessage = "Private Container Registry Username", ParameterSetName = PrivateRegistry)]
        [ValidateNotNullOrEmpty]
        public string ContainerRegistryUser { get; set; }

        [Parameter(Mandatory = true, HelpMessage = "Private Container Registry Password", ParameterSetName = PrivateRegistry)]
        [ValidateNotNullOrEmpty]
        public SecureString ContainerRegistryPassword { get; set; }

        [Parameter(Mandatory = false, HelpMessage = "Enables/Disables container continuous deployment webhook")]
        [ValidateNotNullOrEmpty]
        public SwitchParameter EnableContainerContinuousDeployment { get; set; }

        [Parameter(Mandatory = false, HelpMessage = "Ignore source control on source web app", ParameterSetName = CopyWebAppParameterSet)]
        [ValidateNotNullOrEmpty]
        public SwitchParameter IgnoreSourceControl { get; set; }

        [Parameter(Mandatory = false, HelpMessage = "Ignore custom hostnames on source web app", ParameterSetName = CopyWebAppParameterSet)]
        [ValidateNotNullOrEmpty]
        public SwitchParameter IgnoreCustomHostNames { get; set; }

        [Parameter(Position = 6, Mandatory = false, HelpMessage = "Overrides all application settings in new web app", ParameterSetName = CopyWebAppParameterSet)]
        [ValidateNotNullOrEmpty]
        public Hashtable AppSettingsOverrides { get; set; }

        [Parameter(Position = 7, Mandatory = false, HelpMessage = "Application Service environment Name", ParameterSetName = CopyWebAppParameterSet)]
        [ValidateNotNullOrEmpty]
        public string AseName { get; set; }

        [Parameter(Position = 8, Mandatory = false, HelpMessage = "Resource group of Application Service environment", ParameterSetName = CopyWebAppParameterSet)]
        [ValidateNotNullOrEmpty]
        public string AseResourceGroupName { get; set; }

        [Parameter(Mandatory = false, HelpMessage = "Clones slots associated with source web app", ParameterSetName = CopyWebAppParameterSet)]
        [ValidateNotNullOrEmpty]
        public SwitchParameter IncludeSourceWebAppSlots { get; set; }

        [Parameter(Mandatory = false, HelpMessage = "Create WebApp in the background and return a Job to track progress.")]
        public SwitchParameter AsJob { get; set; }

        [Parameter(Mandatory = false, HelpMessage = "Path to the GitHub repository containign the web application to deploy.", ParameterSetName = SimpleParameterSet)]
        public string GitRepositoryPath { get; set; }

        protected override void ProcessRecord()
        {
            try
            {
                this.ExecuteSynchronouslyOrAsJob( (cmdlet) => cmdlet.ExecuteCmdletActions(this.SessionState));
            }
            catch (Exception ex) when (!IsTerminatingError(ex))
            {
                WriteExceptionError(ex);
            }
        }

        public override void ExecuteCmdlet()
        {

        }

        public void ExecuteCmdletActions(SessionState state)
        {
            if (ParameterSetName == SimpleParameterSet || ParameterSetName == PrivateRegistry)
            {
                ValidateWebAppName(Name);
                if (ShouldProcess(
                    string.Format(Properties.Resources.SimpleWebAppCreateTarget, Name),
                    Properties.Resources.SimpleWebAppCreateAction))
                {
                    this.StartAndWait(CreateWithSimpleParameters);
                }
            }
            else
            {
                if (ShouldProcess(
                    string.Format("WebApp '{0}' from WebApp '{1}'", Name, SourceWebApp?.Name),
                    "Copy"))
                {
                    CreateWithClonedWebApp();
                }
            }

        }

        private void ValidateWebAppName(string name)
        {
            var available = WebsitesClient.WrappedWebsitesClient.CheckNameAvailability(name,"Site");
            if (available.NameAvailable.HasValue && !available.NameAvailable.Value)
            {
                throw new InvalidOperationException(string.Format(
                    "Website name '{0}' is not available.  Please try a different name.", name));
            }
        }

        public void CreateWithClonedWebApp()
        {
            string trafficManagerProfielId = IsResource(TrafficManagerProfile) ? TrafficManagerProfile : null;
            string trafficManagerProfileName = IsResource(TrafficManagerProfile) ? null : TrafficManagerProfile;
            CloningInfo cloningInfo = null;
            if (SourceWebApp != null)
            {
                cloningInfo = new CloningInfo
                {
                    SourceWebAppId = SourceWebApp.Id,
                    CloneCustomHostNames = !IgnoreCustomHostNames.IsPresent,
                    CloneSourceControl = !IgnoreSourceControl.IsPresent,
                    TrafficManagerProfileId = trafficManagerProfielId,
                    TrafficManagerProfileName = trafficManagerProfileName,
                    ConfigureLoadBalancing = !string.IsNullOrEmpty(TrafficManagerProfile),
                    AppSettingsOverrides = AppSettingsOverrides == null ? null : AppSettingsOverrides.Cast<DictionaryEntry>().ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value.ToString(), StringComparer.Ordinal)
                };
                cloningInfo = new PSCloningInfo(cloningInfo);
            }

            var cloneWebAppSlots = false;
            string[] slotNames = null;
            string srcResourceGroupName = null;
            string srcwebAppName = null;
            string srcSlotName = null;
            if (IncludeSourceWebAppSlots.IsPresent)
            {
                CmdletHelpers.TryParseWebAppMetadataFromResourceId(SourceWebApp.Id, out srcResourceGroupName,
                    out srcwebAppName, out srcSlotName);
                var slots = WebsitesClient.ListWebApps(srcResourceGroupName, srcwebAppName);
                if (slots != null && slots.Any())
                {
                    slotNames = slots.Select(s => s.Name.Replace(srcwebAppName + "/", string.Empty)).ToArray();
                    cloneWebAppSlots = true;
                }
            }

            if (cloneWebAppSlots)
            {
                WriteVerboseWithTimestamp("Cloning source web app '{0}' to destination web app {1}", srcwebAppName, Name);
            }

            WriteObject(new PSSite(WebsitesClient.CreateWebApp(ResourceGroupName, Name, null, Location, AppServicePlan, cloningInfo, AseName, AseResourceGroupName)));

            if (cloneWebAppSlots)
            {
                WriteVerboseWithTimestamp("Cloning all deployment slots of source web app '{0}' to destination web app {1}", srcwebAppName, Name);
                CloneSlots(slotNames);
            }
        }
        private async Task<AppServicePlan> GetDefaultServerFarm(string location)
        {
            var websiteLocation = string.IsNullOrWhiteSpace(location) ? new LocationConstraint() : new LocationConstraint(location);
            var farmResources = await ResourcesClient.ResourceManagementClient.Resources.ListAsync(new ODataQuery<GenericResourceFilter>(r => r.ResourceType == "Microsoft.Web/serverFarms"));
            AppServicePlan defaultFarm = null;
            foreach (var resource in farmResources)
            {
                // Try to find a policy with Sku=Free and available site capacity
                var id = new ResourceIdentifier(resource.Id);
                var farm = await WebsitesClient.WrappedWebsitesClient.AppServicePlans.GetAsync(id.ResourceGroupName, id.ResourceName);
                if (websiteLocation.Match(farm.Location)
                    && string.Equals("free", farm.Sku?.Tier?.ToLower(), StringComparison.OrdinalIgnoreCase)
                    && farm.NumberOfSites < MaxFreeSites)
                {
                    defaultFarm = farm;
                    break;
                }

            }

            return defaultFarm;
        }

        bool TryGetServerFarmFromResourceId(string serverFarm, out string resourceGroup, out string serverFarmName)
        {
            bool result = false;
            resourceGroup = null;
            serverFarmName = null;
            if (!string.IsNullOrEmpty(serverFarm) && serverFarm.ToLower().Contains("microsoft.web/serverfarms"))
            {
                var parts = serverFarm.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                if (parts.Length > 7)
                {
                    resourceGroup = parts[3];
                    serverFarmName = parts[7];
                    result = !string.IsNullOrWhiteSpace(resourceGroup) && !string.IsNullOrWhiteSpace(serverFarmName);
                }
            }

            return result;
        }

        sealed class Parameters : IParameters<Site>
        {
            readonly NewAzureWebAppCmdlet _cmdlet;
            readonly WebsitesClient _websitesClient;

            public Parameters(NewAzureWebAppCmdlet cmdlet, WebsitesClient websitesClient)
            {
                _cmdlet = cmdlet;
                _websitesClient = websitesClient;
            }

            public string DefaultLocation => "eastus";

            public string Location
            {
                get { return _cmdlet.Location; }
                set { _cmdlet.Location = value; }
            }
            private SiteConfig GetNewConfig(AppServicePlan appServiceplan)
            {
                bool newConfigAdded = false;
                SiteConfig siteConfig = new SiteConfig();
                siteConfig.AppSettings = new List<NameValuePair>();

                string containerImageName = _cmdlet.ContainerImageName;
                if (containerImageName != null)
                {
                    containerImageName = CmdletHelpers.DockerImagePrefix + containerImageName;
                    if (appServiceplan == null || appServiceplan.IsXenon.GetValueOrDefault())
                    {
                        siteConfig.WindowsFxVersion = containerImageName;
                        newConfigAdded = true;
                    }
                }
                if (_cmdlet.ContainerRegistryUrl != null)
                {
                    siteConfig.AppSettings.Add(new NameValuePair(CmdletHelpers.DocerRegistryServerUrl, _cmdlet.ContainerRegistryUrl));
                    newConfigAdded = true;
                }
                if (_cmdlet.ContainerRegistryUser != null)
                {
                    siteConfig.AppSettings.Add(new NameValuePair(CmdletHelpers.DocerRegistryServerUserName, _cmdlet.ContainerRegistryUser));
                    newConfigAdded = true;
                }
                if (_cmdlet.ContainerRegistryPassword != null)
                {
                    siteConfig.AppSettings.Add(new NameValuePair(CmdletHelpers.DocerRegistryServerPassword, _cmdlet.ContainerRegistryPassword.ConvertToString()));
                    newConfigAdded = true;
                }
                if (_cmdlet.EnableContainerContinuousDeployment.IsPresent)
                {
                    siteConfig.AppSettings.Add(new NameValuePair(CmdletHelpers.DockerEnableCI, "true"));
                    newConfigAdded = true;
                }
                return newConfigAdded ? siteConfig : null;
            }
            public async Task<ResourceConfig<Site>> CreateConfigAsync()
            {
                _cmdlet.ResourceGroupName = _cmdlet.ResourceGroupName ?? _cmdlet.Name;
                _cmdlet.AppServicePlan = _cmdlet.AppServicePlan ?? _cmdlet.Name;

                var planResourceGroup = _cmdlet.ResourceGroupName;
                var planName = _cmdlet.AppServicePlan;

                var rgStrategy = ResourceGroupStrategy.CreateResourceGroupConfig(_cmdlet.ResourceGroupName);
                var planRG = rgStrategy;
                if (_cmdlet.MyInvocation.BoundParameters.ContainsKey(nameof(AppServicePlan)))
                {
                    if (!_cmdlet.TryGetServerFarmFromResourceId(_cmdlet.AppServicePlan, out planResourceGroup, out planName))
                    {
                        planResourceGroup = _cmdlet.ResourceGroupName;
                        planName = _cmdlet.AppServicePlan;
                    }

                    planRG = ResourceGroupStrategy.CreateResourceGroupConfig(planResourceGroup);
                }
                else
                {
                    var farm = await _cmdlet.GetDefaultServerFarm(Location);
                    if (farm != null)
                    {
                        planResourceGroup = farm.ResourceGroup;
                        planName = farm.Name;
                        planRG = ResourceGroupStrategy.CreateResourceGroupConfig(planResourceGroup);
                    }
                }
                AppServicePlan appServiceplan = _websitesClient.GetAppServicePlan(planResourceGroup, planName);

                // If ContainerImageName is specified and appservice plan doesn't exist (appServiceplan == null) we will try to create plan with windows container
                var farmStrategy = planRG.CreateServerFarmConfig(planResourceGroup, planName, appServiceplan == null && _cmdlet.ContainerImageName != null);

                return rgStrategy.CreateSiteConfig(farmStrategy, _cmdlet.Name, this.GetNewConfig(appServiceplan));
            }
        }

        public async Task CreateWithSimpleParameters(IAsyncCmdlet adapter)
        {
            var parameters = new Parameters(this, WebsitesClient);
            var client = new WebClient(DefaultContext);
            var output = await client.RunAsync(client.SubscriptionId, parameters, adapter);

            output.SiteConfig = WebsitesClient
                .WrappedWebsitesClient
                .WebApps()
                .GetConfiguration(output.ResourceGroup, output.Name)
                .ConvertToSiteConfig();

            try
            {
                var appSettings = WebsitesClient
                    .WrappedWebsitesClient
                    .WebApps()
                    .ListApplicationSettings(output.ResourceGroup, output.Name);
                output.SiteConfig.AppSettings = appSettings
                    .Properties
                    .Select(s => new NameValuePair { Name = s.Key, Value = s.Value })
                    .ToList();
                var connectionStrings = WebsitesClient.WrappedWebsitesClient.WebApps().ListConnectionStrings(
                    output.ResourceGroup, output.Name);
                output.SiteConfig.ConnectionStrings = connectionStrings
                    .Properties
                    .Select(s => new ConnStringInfo()
                    {
                        Name = s.Key,
                        ConnectionString = s.Value.Value,
                        Type = s.Value.Type
                    }).ToList();
            }
            catch
            {
                //ignore if this call fails as it will for reader RBAC
            }

            string userName = null, password = null;
            try
            {
                var scmHostName = output.EnabledHostNames.FirstOrDefault(s => s.Contains(".scm."));
                if (!string.IsNullOrWhiteSpace(scmHostName))
                {
                    var profile = await WebsitesClient.WrappedWebsitesClient.WebApps.ListPublishingProfileXmlWithSecretsAsync(output.ResourceGroup, output.Name, new CsmPublishingProfileOptions { Format = "WebDeploy" });
                    var doc = new XmlDocument();
                    doc.Load(profile);
                    userName = doc.SelectSingleNode("//publishProfile[@publishMethod=\"MSDeploy\"]/@userName").Value;
                    password = doc.SelectSingleNode("//publishProfile[@publishMethod=\"MSDeploy\"]/@userPWD").Value;
                    var newOutput = new PSSite(output)
                    {
                        GitRemoteUri = $"https://{scmHostName}",
                        GitRemoteUsername =userName,
                        GitRemotePassword = SecureStringExtensions.ConvertToSecureString(password)
                    };
                    output = newOutput;
                    var git = new GitCommand(SessionState.Path, GitRepositoryPath);
                    var repository = await git.VerifyGitRepository();
                    if (repository != null)
                    {
                        if (!await git.CheckExistence())
                        {
                            adapter.WriteWarning(git.InstallationInstructions);
                        }
                        else if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
                        {
                            await git.AddRemoteRepository("azure", $"https://{userName}:{password}@{scmHostName}");
                            adapter.WriteVerbose(Properties.Resources.GitRemoteMessage);
                            newOutput.GitRemoteName = "azure";
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                // do not write errors for problems with adding git repository
                var repoPath = GitRepositoryPath ?? SessionState?.Path?.CurrentFileSystemLocation?.Path;
                adapter.WriteWarning(string.Format(
                    Properties.Resources.GitRemoteAddFailure,
                    repoPath,
                    exception.Message));
            }
            adapter.WriteObject(new PSSite(output));
        }

        private bool IsResource(string name)
        {
            return !string.IsNullOrWhiteSpace(name) && name.Contains("/");
        }

        private void CloneSlots(string[] slotNames)
        {
            var hostingEnvironmentProfile = WebsitesClient.CreateHostingEnvironmentProfile(ResourceGroupName, AseResourceGroupName, AseName);
            var template = DeploymentTemplateHelper.CreateSlotCloneDeploymentTemplate(Location, AppServicePlan, Name, SourceWebApp.Id,
                slotNames, hostingEnvironmentProfile, WebsitesClient.WrappedWebsitesClient.ApiVersion());

            var deployment = new Management.Internal.Resources.Models.Deployment
            {
                Properties = new DeploymentProperties
                {
                    Mode = DeploymentMode.Incremental,
                    Template = template
                }
            };

            var deploymentName = string.Format("CloneSlotsFor{0}", Name);
            ResourcesClient.ResourceManagementClient.Deployments.CreateOrUpdate(ResourceGroupName, deploymentName, deployment);
            var result = ResourcesClient.ProvisionDeploymentStatus(ResourceGroupName, deploymentName, deployment);
            WriteObject(result.ToPSResourceGroupDeployment(ResourceGroupName));
        }
    }
}


text:
RSpec.describe Hanami::Routing::Error do
  it 'inherits from ::StandardError' do
    expect(Hanami::Routing::Error.superclass).to eq(StandardError)
  end

  it 'is parent to all custom exception' do
    expect(Hanami::Routing::Parsing::BodyParsingError.superclass).to eq(Hanami::Routing::Error)
    expect(Hanami::Routing::Parsing::UnknownParserError.superclass).to eq(Hanami::Routing::Error)
    expect(Hanami::Routing::InvalidRouteException.superclass).to eq(Hanami::Routing::Error)
    expect(Hanami::Routing::EndpointNotFound.superclass).to eq(Hanami::Routing::Error)
  end
end


text:
FROM openjdk:8-jre-alpine
MAINTAINER David Silva <david@davidafsilva.pt>
ADD build/distributions/kussx.tar /opt/
EXPOSE 8080
WORKDIR /opt/kussx
ENTRYPOINT ["bin/kussx"]


text:
#include "config.h"
#include "core/layout/line/RootInlineBox.h"

#include "core/dom/Document.h"
#include "core/dom/StyleEngine.h"
#include "core/layout/HitTestResult.h"
#include "core/layout/LayoutBlockFlow.h"
#include "core/layout/LayoutInline.h"
#include "core/layout/LayoutView.h"
#include "core/layout/VerticalPositionCache.h"
#include "core/layout/api/LineLayoutItem.h"
#include "core/layout/line/EllipsisBox.h"
#include "core/layout/line/GlyphOverflow.h"
#include "core/layout/line/InlineTextBox.h"
#include "core/paint/PaintInfo.h"
#include "core/paint/RootInlineBoxPainter.h"
#include "platform/text/BidiResolver.h"
#include "wtf/text/Unicode.h"

namespace blink {

struct SameSizeAsRootInlineBox : public InlineFlowBox {
    unsigned unsignedVariable;
    void* pointers[3];
    LayoutUnit layoutVariables[6];
};

static_assert(sizeof(RootInlineBox) == sizeof(SameSizeAsRootInlineBox), "RootInlineBox should stay small");

typedef WTF::HashMap<const RootInlineBox*, EllipsisBox*> EllipsisBoxMap;
static EllipsisBoxMap* gEllipsisBoxMap = nullptr;

RootInlineBox::RootInlineBox(LayoutBlockFlow& block)
    : InlineFlowBox(block)
    , m_lineBreakPos(0)
    , m_lineBreakObj(nullptr)
    , m_lineTop(0)
    , m_lineBottom(0)
    , m_lineTopWithLeading(0)
    , m_lineBottomWithLeading(0)
    , m_selectionBottom(0)
    , m_paginationStrut(0)
{
    setIsHorizontal(block.isHorizontalWritingMode());
}

void RootInlineBox::destroy()
{
    detachEllipsisBox();
    InlineFlowBox::destroy();
}

void RootInlineBox::detachEllipsisBox()
{
    if (hasEllipsisBox()) {
        EllipsisBox* box = gEllipsisBoxMap->take(this);
        box->setParent(nullptr);
        box->destroy();
        setHasEllipsisBox(false);
    }
}

LineBoxList* RootInlineBox::lineBoxes() const
{
    return block().lineBoxes();
}

void RootInlineBox::clearTruncation()
{
    if (hasEllipsisBox()) {
        detachEllipsisBox();
        InlineFlowBox::clearTruncation();
    }
}

int RootInlineBox::baselinePosition(FontBaseline baselineType) const
{
    return boxModelObject().baselinePosition(baselineType, isFirstLineStyle(), isHorizontal() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes);
}

LayoutUnit RootInlineBox::lineHeight() const
{
    return boxModelObject().lineHeight(isFirstLineStyle(), isHorizontal() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes);
}

bool RootInlineBox::lineCanAccommodateEllipsis(bool ltr, int blockEdge, int lineBoxEdge, int ellipsisWidth)
{
    // First sanity-check the unoverflowed width of the whole line to see if there is sufficient room.
    int delta = ltr ? lineBoxEdge - blockEdge : blockEdge - lineBoxEdge;
    if (logicalWidth() - delta < ellipsisWidth)
        return false;

    // Next iterate over all the line boxes on the line.  If we find a replaced element that intersects
    // then we refuse to accommodate the ellipsis.  Otherwise we're ok.
    return InlineFlowBox::canAccommodateEllipsis(ltr, blockEdge, ellipsisWidth);
}

LayoutUnit RootInlineBox::placeEllipsis(const AtomicString& ellipsisStr,  bool ltr, LayoutUnit blockLeftEdge, LayoutUnit blockRightEdge, LayoutUnit ellipsisWidth)
{
    // Create an ellipsis box.
    EllipsisBox* ellipsisBox = new EllipsisBox(layoutObject(), ellipsisStr, this,
        ellipsisWidth, logicalHeight().toFloat(), x(), y(), !prevRootBox(), isHorizontal());

    if (!gEllipsisBoxMap)
        gEllipsisBoxMap = new EllipsisBoxMap();
    gEllipsisBoxMap->add(this, ellipsisBox);
    setHasEllipsisBox(true);

    // FIXME: Do we need an RTL version of this?
    if (ltr && (logicalLeft() + logicalWidth() + ellipsisWidth) <= blockRightEdge) {
        ellipsisBox->setLogicalLeft(logicalLeft() + logicalWidth());
        return logicalWidth() + ellipsisWidth;
    }

    // Now attempt to find the nearest glyph horizontally and place just to the right (or left in RTL)
    // of that glyph.  Mark all of the objects that intersect the ellipsis box as not painting (as being
    // truncated).
    bool foundBox = false;
    LayoutUnit truncatedWidth = 0;
    LayoutUnit position = placeEllipsisBox(ltr, blockLeftEdge, blockRightEdge, ellipsisWidth, truncatedWidth, foundBox);
    ellipsisBox->setLogicalLeft(position);
    return truncatedWidth;
}

LayoutUnit RootInlineBox::placeEllipsisBox(bool ltr, LayoutUnit blockLeftEdge, LayoutUnit blockRightEdge, LayoutUnit ellipsisWidth, LayoutUnit &truncatedWidth, bool& foundBox)
{
    LayoutUnit result = InlineFlowBox::placeEllipsisBox(ltr, blockLeftEdge, blockRightEdge, ellipsisWidth, truncatedWidth, foundBox);
    if (result == -1) {
        result = ltr ? blockRightEdge - ellipsisWidth : blockLeftEdge;
        truncatedWidth = blockRightEdge - blockLeftEdge;
    }
    return result;
}

void RootInlineBox::paint(const PaintInfo& paintInfo, const LayoutPoint& paintOffset, LayoutUnit lineTop, LayoutUnit lineBottom)
{
    RootInlineBoxPainter(*this).paint(paintInfo, paintOffset, lineTop, lineBottom);
}

bool RootInlineBox::nodeAtPoint(HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, LayoutUnit lineTop, LayoutUnit lineBottom)
{
    if (hasEllipsisBox() && visibleToHitTestRequest(result.hitTestRequest())) {
        if (ellipsisBox()->nodeAtPoint(result, locationInContainer, accumulatedOffset, lineTop, lineBottom)) {
            lineLayoutItem().updateHitTestResult(result, locationInContainer.point() - toLayoutSize(accumulatedOffset));
            return true;
        }
    }
    return InlineFlowBox::nodeAtPoint(result, locationInContainer, accumulatedOffset, lineTop, lineBottom);
}

void RootInlineBox::move(const LayoutSize& delta)
{
    InlineFlowBox::move(delta);
    LayoutUnit blockDirectionDelta = isHorizontal() ? delta.height() : delta.width();
    m_lineTop += blockDirectionDelta;
    m_lineBottom += blockDirectionDelta;
    m_lineTopWithLeading += blockDirectionDelta;
    m_lineBottomWithLeading += blockDirectionDelta;
    m_selectionBottom += blockDirectionDelta;
    if (hasEllipsisBox())
        ellipsisBox()->move(delta);
}

void RootInlineBox::childRemoved(InlineBox* box)
{
    if (box->lineLayoutItem() == m_lineBreakObj)
        setLineBreakInfo(0, 0, BidiStatus());

    for (RootInlineBox* prev = prevRootBox(); prev && prev->lineBreakObj() == box->lineLayoutItem(); prev = prev->prevRootBox()) {
        prev->setLineBreakInfo(0, 0, BidiStatus());
        prev->markDirty();
    }
}

LayoutUnit RootInlineBox::alignBoxesInBlockDirection(LayoutUnit heightOfBlock, GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache& verticalPositionCache)
{
    // SVG will handle vertical alignment on its own.
    if (isSVGRootInlineBox())
        return 0;

    LayoutUnit maxPositionTop = 0;
    LayoutUnit maxPositionBottom = 0;
    int maxAscent = 0;
    int maxDescent = 0;
    bool setMaxAscent = false;
    bool setMaxDescent = false;

    // Figure out if we're in no-quirks mode.
    bool noQuirksMode = lineLayoutItem().document().inNoQuirksMode();

    m_baselineType = dominantBaseline();

    computeLogicalBoxHeights(this, maxPositionTop, maxPositionBottom, maxAscent, maxDescent, setMaxAscent, setMaxDescent, noQuirksMode, textBoxDataMap, baselineType(), verticalPositionCache);

    if (maxAscent + maxDescent < std::max(maxPositionTop, maxPositionBottom))
        adjustMaxAscentAndDescent(maxAscent, maxDescent, maxPositionTop, maxPositionBottom);

    LayoutUnit maxHeight = maxAscent + maxDescent;
    LayoutUnit lineTop = heightOfBlock;
    LayoutUnit lineBottom = heightOfBlock;
    LayoutUnit lineTopIncludingMargins = heightOfBlock;
    LayoutUnit lineBottomIncludingMargins = heightOfBlock;
    LayoutUnit selectionBottom = heightOfBlock;
    bool setLineTop = false;
    bool hasAnnotationsBefore = false;
    bool hasAnnotationsAfter = false;
    placeBoxesInBlockDirection(heightOfBlock, maxHeight, maxAscent, noQuirksMode, lineTop, lineBottom, selectionBottom, setLineTop, lineTopIncludingMargins, lineBottomIncludingMargins, hasAnnotationsBefore, hasAnnotationsAfter, baselineType());
    m_hasAnnotationsBefore = hasAnnotationsBefore;
    m_hasAnnotationsAfter = hasAnnotationsAfter;

    maxHeight = std::max<LayoutUnit>(0, maxHeight);

    setLineTopBottomPositions(lineTop, lineBottom, heightOfBlock, heightOfBlock + maxHeight, selectionBottom);

    LayoutUnit annotationsAdjustment = beforeAnnotationsAdjustment();
    if (annotationsAdjustment) {
        // FIXME: Need to handle pagination here. We might have to move to the next page/column as a result of the
        // ruby expansion.
        moveInBlockDirection(annotationsAdjustment);
        heightOfBlock += annotationsAdjustment;
    }

    return heightOfBlock + maxHeight;
}

LayoutUnit RootInlineBox::maxLogicalTop() const
{
    LayoutUnit maxLogicalTop;
    computeMaxLogicalTop(maxLogicalTop);
    return maxLogicalTop;
}

LayoutUnit RootInlineBox::beforeAnnotationsAdjustment() const
{
    LayoutUnit result = 0;

    if (!lineLayoutItem().style()->isFlippedLinesWritingMode()) {
        // Annotations under the previous line may push us down.
        if (prevRootBox() && prevRootBox()->hasAnnotationsAfter())
            result = prevRootBox()->computeUnderAnnotationAdjustment(lineTop());

        if (!hasAnnotationsBefore())
            return result;

        // Annotations over this line may push us further down.
        LayoutUnit highestAllowedPosition = prevRootBox() ? std::min(prevRootBox()->lineBottom(), lineTop()) + result : static_cast<LayoutUnit>(block().borderBefore());
        result = computeOverAnnotationAdjustment(highestAllowedPosition);
    } else {
        // Annotations under this line may push us up.
        if (hasAnnotationsBefore())
            result = computeUnderAnnotationAdjustment(prevRootBox() ? prevRootBox()->lineBottom() : static_cast<LayoutUnit>(block().borderBefore()));

        if (!prevRootBox() || !prevRootBox()->hasAnnotationsAfter())
            return result;

        // We have to compute the expansion for annotations over the previous line to see how much we should move.
        LayoutUnit lowestAllowedPosition = std::max(prevRootBox()->lineBottom(), lineTop()) - result;
        result = prevRootBox()->computeOverAnnotationAdjustment(lowestAllowedPosition);
    }

    return result;
}

GapRects RootInlineBox::lineSelectionGap(const LayoutBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock, LayoutUnit selTop, LayoutUnit selHeight, const PaintInfo* paintInfo) const
{
    SelectionState lineState = selectionState();

    bool leftGap, rightGap;
    block().getSelectionGapInfo(lineState, leftGap, rightGap);

    GapRects result;

    InlineBox* firstBox = firstSelectedBox();
    InlineBox* lastBox = lastSelectedBox();
    if (leftGap) {
        result.uniteLeft(block().logicalLeftSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock,
            &firstBox->parent()->layoutObject(), firstBox->logicalLeft(), selTop, selHeight, paintInfo));
    }
    if (rightGap) {
        result.uniteRight(block().logicalRightSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock,
            &lastBox->parent()->layoutObject(), lastBox->logicalRight(), selTop, selHeight, paintInfo));
    }

    // When dealing with bidi text, a non-contiguous selection region is possible.
    // e.g. The logical text aaaAAAbbb (capitals denote RTL text and non-capitals LTR) is layed out
    // visually as 3 text runs |aaa|bbb|AAA| if we select 4 characters from the start of the text the
    // selection will look like (underline denotes selection):
    // |aaa|bbb|AAA|
    //  ___       _
    // We can see that the |bbb| run is not part of the selection while the runs around it are.
    if (firstBox && firstBox != lastBox) {
        // Now fill in any gaps on the line that occurred between two selected elements.
        LayoutUnit lastLogicalLeft = firstBox->logicalRight();
        bool isPreviousBoxSelected = firstBox->selectionState() != SelectionNone;
        for (InlineBox* box = firstBox->nextLeafChild(); box; box = box->nextLeafChild()) {
            if (box->selectionState() != SelectionNone) {
                LayoutRect logicalRect(lastLogicalLeft, selTop, box->logicalLeft() - lastLogicalLeft, selHeight);
                logicalRect.move(lineLayoutItem().isHorizontalWritingMode() ? offsetFromRootBlock : LayoutSize(offsetFromRootBlock.height(), offsetFromRootBlock.width()));
                LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, logicalRect);
                if (isPreviousBoxSelected && gapRect.width() > 0 && gapRect.height() > 0) {
                    if (paintInfo && box->parent()->lineLayoutItem().style()->visibility() == VISIBLE)
                        paintInfo->context->fillRect(gapRect, box->parent()->lineLayoutItem().selectionBackgroundColor());
                    // VisibleSelection may be non-contiguous, see comment above.
                    result.uniteCenter(gapRect);
                }
                lastLogicalLeft = box->logicalRight();
            }
            if (box == lastBox)
                break;
            isPreviousBoxSelected = box->selectionState() != SelectionNone;
        }
    }

    return result;
}

SelectionState RootInlineBox::selectionState() const
{
    // Walk over all of the selected boxes.
    SelectionState state = SelectionNone;
    for (InlineBox* box = firstLeafChild(); box; box = box->nextLeafChild()) {
        SelectionState boxState = box->selectionState();
        if ((boxState == SelectionStart && state == SelectionEnd)
            || (boxState == SelectionEnd && state == SelectionStart)) {
            state = SelectionBoth;
        } else if (state == SelectionNone || ((boxState == SelectionStart || boxState == SelectionEnd) && (state == SelectionNone || state == SelectionInside))) {
            state = boxState;
        } else if (boxState == SelectionNone && state == SelectionStart) {
            // We are past the end of the selection.
            state = SelectionBoth;
        }
        if (state == SelectionBoth)
            break;
    }

    return state;
}

InlineBox* RootInlineBox::firstSelectedBox() const
{
    for (InlineBox* box = firstLeafChild(); box; box = box->nextLeafChild()) {
        if (box->selectionState() != SelectionNone)
            return box;
    }

    return nullptr;
}

InlineBox* RootInlineBox::lastSelectedBox() const
{
    for (InlineBox* box = lastLeafChild(); box; box = box->prevLeafChild()) {
        if (box->selectionState() != SelectionNone)
            return box;
    }

    return nullptr;
}

LayoutUnit RootInlineBox::selectionTop() const
{
    LayoutUnit selectionTop = m_lineTop;

    if (m_hasAnnotationsBefore)
        selectionTop -= !lineLayoutItem().style()->isFlippedLinesWritingMode() ? computeOverAnnotationAdjustment(m_lineTop) : computeUnderAnnotationAdjustment(m_lineTop);

    if (lineLayoutItem().style()->isFlippedLinesWritingMode() || !prevRootBox())
        return selectionTop;

    LayoutUnit prevBottom = prevRootBox()->selectionBottom();
    if (prevBottom < selectionTop && block().containsFloats()) {
        // This line has actually been moved further down, probably from a large line-height, but possibly because the
        // line was forced to clear floats.  If so, let's check the offsets, and only be willing to use the previous
        // line's bottom if the offsets are greater on both sides.
        LayoutUnit prevLeft = block().logicalLeftOffsetForLine(prevBottom, false);
        LayoutUnit prevRight = block().logicalRightOffsetForLine(prevBottom, false);
        LayoutUnit newLeft = block().logicalLeftOffsetForLine(selectionTop, false);
        LayoutUnit newRight = block().logicalRightOffsetForLine(selectionTop, false);
        if (prevLeft > newLeft || prevRight < newRight)
            return selectionTop;
    }

    return prevBottom;
}

LayoutUnit RootInlineBox::selectionTopAdjustedForPrecedingBlock() const
{
    LayoutUnit top = selectionTop();

    SelectionState blockSelectionState = root().block().selectionState();
    if (blockSelectionState != SelectionInside && blockSelectionState != SelectionEnd)
        return top;

    LayoutSize offsetToBlockBefore;
    if (LayoutBlock* block = root().block().blockBeforeWithinSelectionRoot(offsetToBlockBefore)) {
        if (block->isLayoutBlockFlow()) {
            if (RootInlineBox* lastLine = toLayoutBlockFlow(block)->lastRootBox()) {
                SelectionState lastLineSelectionState = lastLine->selectionState();
                if (lastLineSelectionState != SelectionInside && lastLineSelectionState != SelectionStart)
                    return top;

                LayoutUnit lastLineSelectionBottom = lastLine->selectionBottom() + offsetToBlockBefore.height();
                top = std::max(top, lastLineSelectionBottom);
            }
        }
    }

    return top;
}

LayoutUnit RootInlineBox::selectionBottom() const
{
    LayoutUnit selectionBottom = m_selectionBottom;

    if (m_hasAnnotationsAfter)
        selectionBottom += !lineLayoutItem().style()->isFlippedLinesWritingMode() ? computeUnderAnnotationAdjustment(m_lineBottom) : computeOverAnnotationAdjustment(m_lineBottom);

    if (!lineLayoutItem().style()->isFlippedLinesWritingMode() || !nextRootBox())
        return selectionBottom;

    LayoutUnit nextTop = nextRootBox()->selectionTop();
    if (nextTop > selectionBottom && block().containsFloats()) {
        // The next line has actually been moved further over, probably from a large line-height, but possibly because the
        // line was forced to clear floats.  If so, let's check the offsets, and only be willing to use the next
        // line's top if the offsets are greater on both sides.
        LayoutUnit nextLeft = block().logicalLeftOffsetForLine(nextTop, false);
        LayoutUnit nextRight = block().logicalRightOffsetForLine(nextTop, false);
        LayoutUnit newLeft = block().logicalLeftOffsetForLine(selectionBottom, false);
        LayoutUnit newRight = block().logicalRightOffsetForLine(selectionBottom, false);
        if (nextLeft > newLeft || nextRight < newRight)
            return selectionBottom;
    }

    return nextTop;
}

LayoutUnit RootInlineBox::blockDirectionPointInLine() const
{
    return !block().style()->isFlippedBlocksWritingMode() ? std::max(lineTop(), selectionTop()) : std::min(lineBottom(), selectionBottom());
}

LayoutBlockFlow& RootInlineBox::block() const
{
    return toLayoutBlockFlow(layoutObject());
}

static bool isEditableLeaf(InlineBox* leaf)
{
    return leaf && leaf->lineLayoutItem().node() && leaf->lineLayoutItem().node()->hasEditableStyle();
}

InlineBox* RootInlineBox::closestLeafChildForPoint(const LayoutPoint& pointInContents, bool onlyEditableLeaves)
{
    return closestLeafChildForLogicalLeftPosition(block().isHorizontalWritingMode() ? pointInContents.x() : pointInContents.y(), onlyEditableLeaves);
}

InlineBox* RootInlineBox::closestLeafChildForLogicalLeftPosition(LayoutUnit leftPosition, bool onlyEditableLeaves)
{
    InlineBox* firstLeaf = firstLeafChild();
    InlineBox* lastLeaf = lastLeafChild();

    if (firstLeaf != lastLeaf) {
        if (firstLeaf->isLineBreak())
            firstLeaf = firstLeaf->nextLeafChildIgnoringLineBreak();
        else if (lastLeaf->isLineBreak())
            lastLeaf = lastLeaf->prevLeafChildIgnoringLineBreak();
    }

    if (firstLeaf == lastLeaf && (!onlyEditableLeaves || isEditableLeaf(firstLeaf)))
        return firstLeaf;

    // Avoid returning a list marker when possible.
    if (leftPosition <= firstLeaf->logicalLeft() && !firstLeaf->lineLayoutItem().isListMarker() && (!onlyEditableLeaves || isEditableLeaf(firstLeaf))) {
        // The leftPosition coordinate is less or equal to left edge of the firstLeaf.
        // Return it.
        return firstLeaf;
    }

    if (leftPosition >= lastLeaf->logicalRight() && !lastLeaf->lineLayoutItem().isListMarker() && (!onlyEditableLeaves || isEditableLeaf(lastLeaf))) {
        // The leftPosition coordinate is greater or equal to right edge of the lastLeaf.
        // Return it.
        return lastLeaf;
    }

    InlineBox* closestLeaf = nullptr;
    for (InlineBox* leaf = firstLeaf; leaf; leaf = leaf->nextLeafChildIgnoringLineBreak()) {
        if (!leaf->lineLayoutItem().isListMarker() && (!onlyEditableLeaves || isEditableLeaf(leaf))) {
            closestLeaf = leaf;
            if (leftPosition < leaf->logicalRight()) {
                // The x coordinate is less than the right edge of the box.
                // Return it.
                return leaf;
            }
        }
    }

    return closestLeaf ? closestLeaf : lastLeaf;
}

BidiStatus RootInlineBox::lineBreakBidiStatus() const
{
    return BidiStatus(static_cast<WTF::Unicode::Direction>(m_lineBreakBidiStatusEor), static_cast<WTF::Unicode::Direction>(m_lineBreakBidiStatusLastStrong), static_cast<WTF::Unicode::Direction>(m_lineBreakBidiStatusLast), m_lineBreakContext);
}

void RootInlineBox::setLineBreakInfo(LineLayoutItem obj, unsigned breakPos, const BidiStatus& status)
{
    // When setting lineBreakObj, the LayoutObject must not be a LayoutInline
    // with no line boxes, otherwise all sorts of invariants are broken later.
    // This has security implications because if the LayoutObject does not
    // point to at least one line box, then that LayoutInline can be deleted
    // later without resetting the lineBreakObj, leading to use-after-free.
    ASSERT_WITH_SECURITY_IMPLICATION(!obj || obj.isText() || !(obj.isLayoutInline() && obj.isBox() && !toLayoutBox(obj)->inlineBoxWrapper()));

    m_lineBreakObj = obj;
    m_lineBreakPos = breakPos;
    m_lineBreakBidiStatusEor = status.eor;
    m_lineBreakBidiStatusLastStrong = status.lastStrong;
    m_lineBreakBidiStatusLast = status.last;
    m_lineBreakContext = status.context;
}

EllipsisBox* RootInlineBox::ellipsisBox() const
{
    if (!hasEllipsisBox())
        return nullptr;
    return gEllipsisBoxMap->get(this);
}

void RootInlineBox::removeLineBoxFromLayoutObject()
{
    block().lineBoxes()->removeLineBox(this);
}

void RootInlineBox::extractLineBoxFromLayoutObject()
{
    block().lineBoxes()->extractLineBox(this);
}

void RootInlineBox::attachLineBoxToLayoutObject()
{
    block().lineBoxes()->attachLineBox(this);
}

LayoutRect RootInlineBox::paddedLayoutOverflowRect(LayoutUnit endPadding) const
{
    LayoutRect lineLayoutOverflow = layoutOverflowRect(lineTop(), lineBottom());
    if (!endPadding)
        return lineLayoutOverflow;

    if (isHorizontal()) {
        if (isLeftToRightDirection())
            lineLayoutOverflow.shiftMaxXEdgeTo(std::max<LayoutUnit>(lineLayoutOverflow.maxX(), logicalRight() + endPadding));
        else
            lineLayoutOverflow.shiftXEdgeTo(std::min<LayoutUnit>(lineLayoutOverflow.x(), logicalLeft() - endPadding));
    } else {
        if (isLeftToRightDirection())
            lineLayoutOverflow.shiftMaxYEdgeTo(std::max<LayoutUnit>(lineLayoutOverflow.maxY(), logicalRight() + endPadding));
        else
            lineLayoutOverflow.shiftYEdgeTo(std::min<LayoutUnit>(lineLayoutOverflow.y(), logicalLeft() - endPadding));
    }

    return lineLayoutOverflow;
}

static void setAscentAndDescent(int& ascent, int& descent, int newAscent, int newDescent, bool& ascentDescentSet)
{
    if (!ascentDescentSet) {
        ascentDescentSet = true;
        ascent = newAscent;
        descent = newDescent;
    } else {
        ascent = std::max(ascent, newAscent);
        descent = std::max(descent, newDescent);
    }
}

void RootInlineBox::ascentAndDescentForBox(InlineBox* box, GlyphOverflowAndFallbackFontsMap& textBoxDataMap, int& ascent, int& descent, bool& affectsAscent, bool& affectsDescent) const
{
    bool ascentDescentSet = false;

    // Replaced boxes will return 0 for the line-height if line-box-contain says they are
    // not to be included.
    if (box->layoutObject().isReplaced()) {
        if (layoutObject().style(isFirstLineStyle())->lineBoxContain() & LineBoxContainReplaced) {
            ascent = box->baselinePosition(baselineType());
            descent = box->lineHeight() - ascent;

            // Replaced elements always affect both the ascent and descent.
            affectsAscent = true;
            affectsDescent = true;
        }
        return;
    }

    Vector<const SimpleFontData*>* usedFonts = nullptr;
    GlyphOverflow* glyphOverflow = nullptr;
    if (box->isText()) {
        GlyphOverflowAndFallbackFontsMap::iterator it = textBoxDataMap.find(toInlineTextBox(box));
        usedFonts = it == textBoxDataMap.end() ? 0 : &it->value.first;
        glyphOverflow = it == textBoxDataMap.end() ? 0 : &it->value.second;
    }

    bool includeLeading = includeLeadingForBox(box);
    bool includeFont = includeFontForBox(box);

    bool setUsedFont = false;
    bool setUsedFontWithLeading = false;

    if (usedFonts && !usedFonts->isEmpty() && (includeFont || (box->lineLayoutItem().style(isFirstLineStyle())->lineHeight().isNegative() && includeLeading))) {
        usedFonts->append(box->lineLayoutItem().style(isFirstLineStyle())->font().primaryFont());
        for (size_t i = 0; i < usedFonts->size(); ++i) {
            const FontMetrics& fontMetrics = usedFonts->at(i)->fontMetrics();
            int usedFontAscent = fontMetrics.ascent(baselineType());
            int usedFontDescent = fontMetrics.descent(baselineType());
            int halfLeading = (fontMetrics.lineSpacing() - fontMetrics.height()) / 2;
            int usedFontAscentAndLeading = usedFontAscent + halfLeading;
            int usedFontDescentAndLeading = fontMetrics.lineSpacing() - usedFontAscentAndLeading;
            if (includeFont) {
                setAscentAndDescent(ascent, descent, usedFontAscent, usedFontDescent, ascentDescentSet);
                setUsedFont = true;
            }
            if (includeLeading) {
                setAscentAndDescent(ascent, descent, usedFontAscentAndLeading, usedFontDescentAndLeading, ascentDescentSet);
                setUsedFontWithLeading = true;
            }
            if (!affectsAscent)
                affectsAscent = usedFontAscent - box->logicalTop() > 0;
            if (!affectsDescent)
                affectsDescent = usedFontDescent + box->logicalTop() > 0;
        }
    }

    // If leading is included for the box, then we compute that box.
    if (includeLeading && !setUsedFontWithLeading) {
        int ascentWithLeading = box->baselinePosition(baselineType());
        int descentWithLeading = box->lineHeight() - ascentWithLeading;
        setAscentAndDescent(ascent, descent, ascentWithLeading, descentWithLeading, ascentDescentSet);

        // Examine the font box for inline flows and text boxes to see if any part of it is above the baseline.
        // If the top of our font box relative to the root box baseline is above the root box baseline, then
        // we are contributing to the maxAscent value. Descent is similar. If any part of our font box is below
        // the root box's baseline, then we contribute to the maxDescent value.
        affectsAscent = ascentWithLeading - box->logicalTop() > 0;
        affectsDescent = descentWithLeading + box->logicalTop() > 0;
    }

    if (includeFontForBox(box) && !setUsedFont) {
        int fontAscent = box->lineLayoutItem().style(isFirstLineStyle())->fontMetrics().ascent(baselineType());
        int fontDescent = box->lineLayoutItem().style(isFirstLineStyle())->fontMetrics().descent(baselineType());
        setAscentAndDescent(ascent, descent, fontAscent, fontDescent, ascentDescentSet);
        affectsAscent = fontAscent - box->logicalTop() > 0;
        affectsDescent = fontDescent + box->logicalTop() > 0;
    }

    if (includeGlyphsForBox(box) && glyphOverflow && glyphOverflow->computeBounds) {
        setAscentAndDescent(ascent, descent, glyphOverflow->top, glyphOverflow->bottom, ascentDescentSet);
        affectsAscent = glyphOverflow->top - box->logicalTop() > 0;
        affectsDescent = glyphOverflow->bottom + box->logicalTop() > 0;
    }

    if (includeMarginForBox(box)) {
        LayoutUnit ascentWithMargin = box->lineLayoutItem().style(isFirstLineStyle())->fontMetrics().ascent(baselineType());
        LayoutUnit descentWithMargin = box->lineLayoutItem().style(isFirstLineStyle())->fontMetrics().descent(baselineType());
        if (box->parent() && !box->lineLayoutItem().isText()) {
            ascentWithMargin += box->boxModelObject().borderBefore() + box->boxModelObject().paddingBefore() + box->boxModelObject().marginBefore();
            descentWithMargin += box->boxModelObject().borderAfter() + box->boxModelObject().paddingAfter() + box->boxModelObject().marginAfter();
        }
        setAscentAndDescent(ascent, descent, ascentWithMargin, descentWithMargin, ascentDescentSet);

        // Treat like a replaced element, since we're using the margin box.
        affectsAscent = true;
        affectsDescent = true;
    }
}

LayoutUnit RootInlineBox::verticalPositionForBox(InlineBox* box, VerticalPositionCache& verticalPositionCache)
{
    if (box->lineLayoutItem().isText())
        return box->parent()->logicalTop();

    LineLayoutBoxModel boxModel = box->boxModelObject();
    ASSERT(boxModel.isInline());
    if (!boxModel.isInline())
        return 0;

    // This method determines the vertical position for inline elements.
    bool firstLine = isFirstLineStyle();
    if (firstLine && !boxModel.document().styleEngine().usesFirstLineRules())
        firstLine = false;

    // Check the cache.
    bool isLayoutInline = boxModel.isLayoutInline();
    if (isLayoutInline && !firstLine) {
        LayoutUnit verticalPosition = verticalPositionCache.get(boxModel, baselineType());
        if (verticalPosition != PositionUndefined)
            return verticalPosition;
    }

    LayoutUnit verticalPosition = 0;
    EVerticalAlign verticalAlign = boxModel.style()->verticalAlign();
    if (verticalAlign == TOP || verticalAlign == BOTTOM)
        return 0;

    LineLayoutItem parent = boxModel.parent();
    if (parent.isLayoutInline() && parent.style()->verticalAlign() != TOP && parent.style()->verticalAlign() != BOTTOM)
        verticalPosition = box->parent()->logicalTop();

    if (verticalAlign != BASELINE) {
        const Font& font = parent.style(firstLine)->font();
        const FontMetrics& fontMetrics = font.fontMetrics();
        int fontSize = font.fontDescription().computedPixelSize();

        LineDirectionMode lineDirection = parent.isHorizontalWritingMode() ? HorizontalLine : VerticalLine;

        if (verticalAlign == SUB) {
            verticalPosition += fontSize / 5 + 1;
        } else if (verticalAlign == SUPER) {
            verticalPosition -= fontSize / 3 + 1;
        } else if (verticalAlign == TEXT_TOP) {
            verticalPosition += boxModel.baselinePosition(baselineType(), firstLine, lineDirection) - fontMetrics.ascent(baselineType());
        } else if (verticalAlign == MIDDLE) {
            verticalPosition = (verticalPosition - static_cast<LayoutUnit>(fontMetrics.xHeight() / 2) - boxModel.lineHeight(firstLine, lineDirection) / 2 + boxModel.baselinePosition(baselineType(), firstLine, lineDirection)).round();
        } else if (verticalAlign == TEXT_BOTTOM) {
            verticalPosition += fontMetrics.descent(baselineType());
            // lineHeight - baselinePosition is always 0 for replaced elements (except inline blocks), so don't bother wasting time in that case.
            if (!boxModel.isReplaced() || boxModel.isInlineBlockOrInlineTable())
                verticalPosition -= (boxModel.lineHeight(firstLine, lineDirection) - boxModel.baselinePosition(baselineType(), firstLine, lineDirection));
        } else if (verticalAlign == BASELINE_MIDDLE) {
            verticalPosition += -boxModel.lineHeight(firstLine, lineDirection) / 2 + boxModel.baselinePosition(baselineType(), firstLine, lineDirection);
        } else if (verticalAlign == LENGTH) {
            LayoutUnit lineHeight;
            // Per http://www.w3.org/TR/CSS21/visudet.html#propdef-vertical-align: 'Percentages: refer to the 'line-height' of the element itself'.
            if (boxModel.style()->verticalAlignLength().hasPercent())
                lineHeight = boxModel.style()->computedLineHeight();
            else
                lineHeight = boxModel.lineHeight(firstLine, lineDirection);
            verticalPosition -= valueForLength(boxModel.style()->verticalAlignLength(), lineHeight);
        }
    }

    // Store the cached value.
    if (isLayoutInline && !firstLine)
        verticalPositionCache.set(boxModel, baselineType(), verticalPosition);

    return verticalPosition;
}

bool RootInlineBox::includeLeadingForBox(InlineBox* box) const
{
    if (box->lineLayoutItem().isReplaced() || (box->lineLayoutItem().isText() && !box->isText()))
        return false;

    LineBoxContain lineBoxContain = lineLayoutItem().style()->lineBoxContain();
    return (lineBoxContain & LineBoxContainInline) || (box == this && (lineBoxContain & LineBoxContainBlock));
}

bool RootInlineBox::includeFontForBox(InlineBox* box) const
{
    if (box->lineLayoutItem().isReplaced() || (box->lineLayoutItem().isText() && !box->isText()))
        return false;

    if (!box->isText() && box->isInlineFlowBox() && !toInlineFlowBox(box)->hasTextChildren())
        return false;

    // For now map "glyphs" to "font" in vertical text mode until the bounds returned by glyphs aren't garbage.
    LineBoxContain lineBoxContain = lineLayoutItem().style()->lineBoxContain();
    return (lineBoxContain & LineBoxContainFont) || (!isHorizontal() && (lineBoxContain & LineBoxContainGlyphs));
}

bool RootInlineBox::includeGlyphsForBox(InlineBox* box) const
{
    if (box->lineLayoutItem().isReplaced() || (box->lineLayoutItem().isText() && !box->isText()))
        return false;

    if (!box->isText() && box->isInlineFlowBox() && !toInlineFlowBox(box)->hasTextChildren())
        return false;

    // FIXME: We can't fit to glyphs yet for vertical text, since the bounds returned are garbage.
    LineBoxContain lineBoxContain = lineLayoutItem().style()->lineBoxContain();
    return isHorizontal() && (lineBoxContain & LineBoxContainGlyphs);
}

bool RootInlineBox::includeMarginForBox(InlineBox* box) const
{
    if (box->lineLayoutItem().isReplaced() || (box->lineLayoutItem().isText() && !box->isText()))
        return false;

    LineBoxContain lineBoxContain = lineLayoutItem().style()->lineBoxContain();
    return lineBoxContain & LineBoxContainInlineBox;
}

bool RootInlineBox::fitsToGlyphs() const
{
    // FIXME: We can't fit to glyphs yet for vertical text, since the bounds returned are garbage.
    LineBoxContain lineBoxContain = lineLayoutItem().style()->lineBoxContain();
    return isHorizontal() && (lineBoxContain & LineBoxContainGlyphs);
}

bool RootInlineBox::includesRootLineBoxFontOrLeading() const
{
    LineBoxContain lineBoxContain = lineLayoutItem().style()->lineBoxContain();
    return (lineBoxContain & LineBoxContainBlock) || (lineBoxContain & LineBoxContainInline) || (lineBoxContain & LineBoxContainFont);
}

Node* RootInlineBox::getLogicalStartBoxWithNode(InlineBox*& startBox) const
{
    Vector<InlineBox*> leafBoxesInLogicalOrder;
    collectLeafBoxesInLogicalOrder(leafBoxesInLogicalOrder);
    for (size_t i = 0; i < leafBoxesInLogicalOrder.size(); ++i) {
        if (leafBoxesInLogicalOrder[i]->lineLayoutItem().nonPseudoNode()) {
            startBox = leafBoxesInLogicalOrder[i];
            return startBox->lineLayoutItem().nonPseudoNode();
        }
    }
    startBox = nullptr;
    return nullptr;
}

Node* RootInlineBox::getLogicalEndBoxWithNode(InlineBox*& endBox) const
{
    Vector<InlineBox*> leafBoxesInLogicalOrder;
    collectLeafBoxesInLogicalOrder(leafBoxesInLogicalOrder);
    for (size_t i = leafBoxesInLogicalOrder.size(); i > 0; --i) {
        if (leafBoxesInLogicalOrder[i - 1]->lineLayoutItem().nonPseudoNode()) {
            endBox = leafBoxesInLogicalOrder[i - 1];
            return endBox->lineLayoutItem().nonPseudoNode();
        }
    }
    endBox = nullptr;
    return nullptr;
}

const char* RootInlineBox::boxName() const
{
    return "RootInlineBox";
}

} // namespace blink


text:
set -e

project_root="$(dirname "$(git rev-parse --git-dir)")"

bash "$project_root"/lib/continuous_integration.bash lint_dockerfiles
bash "$project_root"/lib/continuous_integration.bash lint_markdown
bash "$project_root"/lib/continuous_integration.bash lint_shell
bash "$project_root"/lib/continuous_integration.bash lint_yaml


text:
#include "entropy_decoder_kernel_abstract.h"
#include "../algs.h"
#include "../assert.h"
#include <iostream>

namespace dlib
{

    template <
        typename decoder
        >
    class entropy_decoder_kernel_c : public decoder
    {

        public:
            std::istream& get_stream (
            ) const;

            void decode (
                uint32 low_count,
                uint32 high_count
            );

            uint32 get_target (
                uint32 total
            );

    private:
        uint32 _get_target;
        uint32 TOTAL;
    };

// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
    // member function definitions
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

    template <
        typename decoder
        >
    std::istream& entropy_decoder_kernel_c<decoder>::
    get_stream (
    ) const
    {
        // make sure requires clause is not broken
        DLIB_CASSERT( this->stream_is_set() == true,
            "\tstd::istream& entropy_decoder::get_stream()"
            << "\n\tyou must set a stream for this object before you can get it"
            << "\n\tthis: " << this
            );

        // call the real function
        return decoder::get_stream();
    }

// ----------------------------------------------------------------------------------------

    template <
        typename decoder
        >
    void entropy_decoder_kernel_c<decoder>::
    decode (
        uint32 low_count,
        uint32 high_count
    )
    {
        // make sure requires clause is not broken
        DLIB_CASSERT( (low_count <= _get_target) && (_get_target < high_count) &&
                (high_count <= TOTAL) &&
                (this->stream_is_set() == true) && (this->get_target_called() == true),
            "\tvoid entropy_decoder::decode()"
            << "\n\tRefer to the ensures clause for this function for further information."
            << "\n\tNote that _get_target refers to get_target(TOTAL)"
            << "\n\tthis:                " << this
            << "\n\tlow_count:           " << low_count
            << "\n\thigh_count:          " << high_count
            << "\n\tTOTAL:               " << TOTAL
            << "\n\tget_target(TOTAL):   " << _get_target
            << "\n\tis_stream_set():     " << (this->stream_is_set() ? "true" : "false" )
            << "\n\tget_target_called(): " << (this->get_target_called() ? "true" : "false" )
            );

        // call the real function
        decoder::decode(low_count,high_count);
    }

// ----------------------------------------------------------------------------------------

    template <
        typename decoder
        >
    uint32 entropy_decoder_kernel_c<decoder>::
    get_target (
        uint32 total
    )
    {
        // make sure requires clause is not broken
        DLIB_CASSERT( (total > 0) && (total < 65536) && (this->stream_is_set() == true),
            "\tvoid entropy_decoder::get_target()"
            << "\n\tyou must set a stream for this object before you can get the "
            << "\n\rnext target."
            << "\n\tthis: " << this
            << "\n\ttotal: " << total
            );

        // call the real function
        _get_target = decoder::get_target(total);
        TOTAL = total;
        return _get_target;
    }

// ----------------------------------------------------------------------------------------

}

#endif // DLIB_ENTROPY_ENCODER_KERNEl_C_