text:
import {AstNodeWithLanguage} from '../model/inline-document';
import {correctSourceRange, LocationOffset, SourcePosition, SourceRange, uncorrectSourceRange} from '../model/source-range';
import {ResolvedUrl} from '../model/url';

/**
 * A parsed Document.
 *
 * @template AstNode The AST type of the document.
 * @template Visitor The type of the visitors that can walk the document.
 */
export abstract class ParsedDocument<
    AstNode = {} | null | undefined,
    Visitor = {}> {
  abstract type: string;
  url: ResolvedUrl;
  baseUrl: ResolvedUrl;
  contents: string;
  ast: AstNode;
  isInline: boolean;

  /**
   * If not null, this is an inline document, and astNode is the AST Node of
   * this document inside of the parent. (e.g. the <style> or <script> tag)
   */
  readonly astNode: AstNodeWithLanguage|undefined;

  sourceRange: SourceRange;

  private readonly _locationOffset: LocationOffset|undefined;

  /**
   * The 0-based offsets into `contents` of all newline characters.
   *
   * Useful for converting between string offsets and SourcePositions.
   */
  readonly newlineIndexes: number[] = [];

  constructor(from: Options<AstNode>) {
    this.url = from.url;
    this.baseUrl = from.baseUrl === undefined ? this.url : from.baseUrl;
    this.contents = from.contents;
    this.ast = from.ast;
    this._locationOffset = from.locationOffset;
    this.astNode = from.astNode;
    this.isInline = from.isInline;

    let lastSeenLine = -1;
    while (true) {
      lastSeenLine = from.contents.indexOf('\n', lastSeenLine + 1);
      if (lastSeenLine === -1) {
        break;
      }
      this.newlineIndexes.push(lastSeenLine);
    }
    this.sourceRange = this.offsetsToSourceRange(0, this.contents.length);
  }

  /**
   * Runs a set of document-type specific visitors against the document.
   */
  abstract visit(visitors: Visitor[]): void;

  sourceRangeForNode(node: AstNode): SourceRange|undefined {
    const baseSource = this._sourceRangeForNode(node);
    return this.relativeToAbsoluteSourceRange(baseSource);
  }

  protected abstract _sourceRangeForNode(node: AstNode): SourceRange|undefined;

  /**
   * Convert `this.ast` back into a string document.
   */
  abstract stringify(options: StringifyOptions): string;

  offsetToSourcePosition(offset: number): SourcePosition {
    const linesLess = binarySearch(offset, this.newlineIndexes);
    let colOffset = this.newlineIndexes[linesLess - 1];
    if (colOffset == null) {
      colOffset = 0;
    } else {
      colOffset = colOffset + 1;
    }
    return {line: linesLess, column: offset - colOffset};
  }

  offsetsToSourceRange(start: number, end: number): SourceRange {
    const sourceRange = {
      file: this.url,
      start: this.offsetToSourcePosition(start),
      end: this.offsetToSourcePosition(end)
    };
    return correctSourceRange(sourceRange, this._locationOffset)!;
  }

  sourcePositionToOffset(position: SourcePosition): number {
    const line = Math.max(0, position.line);
    let lineOffset;
    if (line === 0) {
      lineOffset = -1;
    } else if (line > this.newlineIndexes.length) {
      lineOffset = this.contents.length - 1;
    } else {
      lineOffset = this.newlineIndexes[line - 1];
    }
    const result = position.column + lineOffset + 1;
    // Clamp within bounds.
    return Math.min(Math.max(0, result), this.contents.length);
  }

  relativeToAbsoluteSourceRange(sourceRange: SourceRange): SourceRange;
  relativeToAbsoluteSourceRange(sourceRange: undefined): undefined;
  relativeToAbsoluteSourceRange(sourceRange: SourceRange|undefined): SourceRange
      |undefined;
  relativeToAbsoluteSourceRange(sourceRange: SourceRange|undefined): SourceRange
      |undefined {
    return correctSourceRange(sourceRange, this._locationOffset);
  }

  absoluteToRelativeSourceRange(sourceRange: SourceRange): SourceRange;
  absoluteToRelativeSourceRange(sourceRange: undefined): undefined;
  absoluteToRelativeSourceRange(sourceRange: SourceRange|undefined): SourceRange
      |undefined;
  absoluteToRelativeSourceRange(sourceRange: SourceRange|undefined): SourceRange
      |undefined {
    return uncorrectSourceRange(sourceRange, this._locationOffset);
  }

  sourceRangeToOffsets(range: SourceRange): [number, number] {
    return [
      this.sourcePositionToOffset(range.start),
      this.sourcePositionToOffset(range.end)
    ];
  }

  toString() {
    if (this.isInline) {
      return `Inline ${this.constructor.name} on line ` +
          `${this.sourceRange.start.line} of ${this.url}`;
    }
    return `${this.constructor.name} at ${this.url}`;
  }
}

export interface Options<A> {
  url: ResolvedUrl;
  baseUrl: ResolvedUrl|undefined;
  contents: string;
  ast: A;
  locationOffset: LocationOffset|undefined;
  astNode: AstNodeWithLanguage|undefined;
  isInline: boolean;
}

export interface StringifyOptions {
  /** The desired level of indentation of to stringify at. */
  indent?: number;

  /**
   * Parsed (and possibly modified) documents that exist inside this document
   * whose stringified contents should be used instead of what is in `ast`.
   */
  inlineDocuments?: ParsedDocument[];

  /**
   * Decide if the document should be formatted for readability, if supported.
   * This option should default to `true` in subclasses.
   */
  prettyPrint?: boolean;
}

/**
 * Used solely for constructing warnings about unparsable or unloadable
 * documents.
 */
export class UnparsableParsedDocument extends ParsedDocument {
  type: string = 'unparsable';
  constructor(url: ResolvedUrl, contents: string) {
    super({
      ast: null,
      url,
      baseUrl: url,
      astNode: undefined,
      contents: contents,
      isInline: false,
      locationOffset: undefined
    });
  }
  visit(_visitors: {}[]): void {
    return;
  }
  protected _sourceRangeForNode(_node: {}): undefined {
    return undefined;
  }
  stringify(): string {
    return `<FakeParsedDocument url="${this.url}">`;
  }
}

/**
 * The variant of binary search that returns the number of elements in the
 * array that is strictly less than the target.
 */
function binarySearch(target: number, arr: number[]) {
  let lower = 0;
  let upper = arr.length - 1;
  while (true) {
    if (lower > upper) {
      return lower;
    }
    const m = Math.floor((upper + lower) / 2);
    if (target === arr[m]) {
      return m;
    }
    if (target > arr[m]) {
      lower = m + 1;
    } else {
      upper = m - 1;
    }
  }
}


text:
properties {
  $base_dir  = resolve-path .
  $lib_dir = "$base_dir\SharedLibs"
  $build_dir = "$base_dir\build"
  $buildartifacts_dir = "$build_dir\"
  $sln_file = "$base_dir\Rhino.ServiceBus.sln"
  $version = "1.8.0.0"
  $tools_dir = "$base_dir\Tools"
  $release_dir = "$base_dir\Release"
  $config = "Debug"
  $target_framework_version = "3.5"
}

$framework = '4.0'

include .\psake_ext.ps1

task default -depends Release

task Clean {
  remove-item -force -recurse $buildartifacts_dir -ErrorAction SilentlyContinue
  remove-item -force -recurse $release_dir -ErrorAction SilentlyContinue
}

task Init -depends Clean {
	Generate-Assembly-Info `
		-file "$base_dir\Rhino.ServiceBus\Properties\AssemblyInfo.cs" `
		-title "Rhino Service Bus $version" `
		-description "Developer friendly service bus for .NET" `
		-company "Hibernating Rhinos" `
		-product "Rhino Service Bus $version" `
		-version $version `
		-copyright "Hibernating Rhinos & Ayende Rahien 2004 - 2009"

	Generate-Assembly-Info `
		-file "$base_dir\Rhino.ServiceBus.Tests\Properties\AssemblyInfo.cs" `
		-title "Rhino Service Bus $version" `
		-description "Developer friendly service bus for .NET" `
		-company "Hibernating Rhinos" `
		-product "Rhino Service Bus $version" `
		-version $version `
		-copyright "Hibernating Rhinos & Ayende Rahien 2004 - 2009"

    Generate-Assembly-Info `
		-file "$base_dir\Rhino.ServiceBus.Host\Properties\AssemblyInfo.cs" `
		-title "Rhino Service Bus $version" `
		-description "Developer friendly service bus for .NET" `
		-company "Hibernating Rhinos" `
		-product "Rhino Service Bus $version" `
		-version $version `
		-copyright "Hibernating Rhinos & Ayende Rahien 2004 - 2009"

	new-item $release_dir -itemType directory
	new-item $buildartifacts_dir -itemType directory
}

task Compile -depends Init {
  $build_properties = "OutDir=$buildartifacts_dir;Configuration=$config"
  if($target_framework_version -eq '4.0')
  {
    $build_properties = "$build_properties;TargetFrameworkVersion=$target_framework_version"
  }
  msbuild $sln_file /p:$build_properties
}

task Test -depends Compile {
  $old = pwd
  cd $build_dir
  & $tools_dir\xUnit\xunit.console.exe "$build_dir\Rhino.ServiceBus.Tests.dll"
  cd $old
}

task Release  -depends Test{

	& $tools_dir\zip.exe -9 -A -j `
		$release_dir\Rhino.ServiceBus.zip `
		$build_dir\Castle.Core.dll `
    	$build_dir\Castle.Core.xml `
    	$build_dir\Castle.DynamicProxy2.dll `
    	$build_dir\Castle.DynamicProxy2.xml `
    	$build_dir\Castle.MicroKernel.dll `
    	$build_dir\Castle.MicroKernel.xml `
    	$build_dir\Castle.Windsor.dll `
    	$build_dir\Castle.Windsor.xml `
    	$build_dir\Esent.Interop.dll `
    	$build_dir\Esent.Interop.xml `
    	$build_dir\log4net.dll `
    	$build_dir\log4net.xml `
    	$build_dir\Rhino.DistributedHashTable.Client.dll `
    	$build_dir\Rhino.DistributedHashTable.dll `
    	$build_dir\Rhino.PersistentHashTable.dll `
    	$build_dir\Rhino.Queues.dll `
    	$build_dir\Rhino.ServiceBus.dll `
    	$build_dir\Rhino.ServiceBus.xml `
    	$build_dir\Wintellect.Threading.dll `
    	$build_dir\Wintellect.Threading.xml `
    	license.txt `
		acknowledgements.txt
	if ($lastExitCode -ne 0) {
        throw "Error: Failed to execute ZIP command"
    }
}

redpajama_set_name: RedPajamaGithub


text:
package T145.magistics.common.items.base;

import T145.magistics.common.Magistics;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

public class ItemBase extends Item {

	protected final String BASE_NAME;
	protected String[] VARIANTS;

	public ItemBase(String name, String... variants) {
		setRegistryName(new ResourceLocation(Magistics.ID, name));
		setUnlocalizedName(Magistics.ID + '.' + name);
		setCreativeTab(Magistics.TAB);
		//setNoRepair();
		setHasSubtypes(variants.length > 1);

		BASE_NAME = name;

		if (variants.length == 0) {
			VARIANTS = new String[] { name };
		} else {
			VARIANTS = variants;
		}
	}

	@Override
	public String getUnlocalizedName(ItemStack stack) {
		if (hasSubtypes && stack.getMetadata() < VARIANTS.length && VARIANTS[stack.getMetadata()] != BASE_NAME) {
			return super.getUnlocalizedName() + "." + VARIANTS[stack.getMetadata()];
		}
		return super.getUnlocalizedName(stack);
	}

	@Override
	@SideOnly(Side.CLIENT)
	public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> items) {
		if (!hasSubtypes) {
			super.getSubItems(tab, items);
		} else {
			for (int meta = 0; meta < VARIANTS.length; ++meta) {
				items.add(new ItemStack(this, 1, meta));
			}
		}
	}
}


text:
require 'logger'
require 'digest/md5'
require 'yaml'

require 'simple-rss'
require 'json'
require 'crack'
require 'moneta'
require 'restclient'
require 'nokogiri'
require 'registry'

module Smoke
  class NotRegistered < StandardError; end

  class << self
    @@active_sources = {}
    @@config = {
      :enable_logging => true,
      :user_agent     => "Ruby/#{RUBY_VERSION}/Smoke",
      :cache          => {
        :enabled  => false,
        :store    => :memory,
        :options  => {},
        :expiry   => 1800
      }
    }

    def root
      File.join(File.dirname(__FILE__))
    end

    def version
      @@version ||= YAML::load(File.read("#{root}/../VERSION.YML"))
      "#{@@version[:major]}.#{@@version[:minor]}.#{@@version[:patch]}"
    end

    # Access registered smoke source instances
    #
    # Define your source:
    #     Smoke.yql(:ruby) do ....
    # Then access it:
    #     Smoke[:ruby]
    #     => #<Smoke::YQL::0x18428d4...
    def [](source)
      active_sources[source]
    end

    # Access registered smoke source instances
    #
    # Arguments can be sent as key/value pairs to inject abstract properties:
    # Usage:
    #   Smoke.twitter(:username => "benschwarz")
    def method_missing(sym, args = {})
      raise NotRegistered, "Smoke source not registered" if self[sym].nil?

      args.each_pair {|k, v| self[sym].send(k, v) }
      self[sym]
    end

    # Activates new instances of sources
    # Source instances are stored within the
    # @@active_sources class variable for later use
    def activate(name, source)
      if active_sources.key?(name)
        Smoke.log.warn "Smoke source activation: Source with identical name already initialized"
      end
      active_sources.update({ name => source })
    end

    # Returns all activated smoke sources
    def active_sources; @@active_sources; end

    # Returns all exposed sources
    def exposed_sources
      active_sources.reject{|k,v| !v.exposed? }
    end

    # Returns all concealed sources
    def concealed_sources
      active_sources.reject{|k,v| !v.concealed? }
    end

    # Rename a source
    def rename(candidates)
      candidates.each do |o, n|
        active_sources[o].name = n.to_s
        active_sources.rename(o => n)
        return active_sources[n]
      end
    end

    # Log for info, debug, error and warn with:
    #
    #   Smoke.log.info "message"
    #   Smoke.log.debug "message"
    #   Smoke.log.error "message"
    #   Smoke.log.warn "message"
    def log
      @@log ||= Logger.new(config[:enable_logging] ? $stdout : "/dev/null")
    end

    # Set any configurable options
    #
    #     Smoke.configure do |c|
    #       c[:user_agent] = "Some other site"
    #     end
    #
    def configure(&block)
      yield @@config
    end

    # Access configuration options
    #
    #   Smoke.config[:option_name]
    #   => true
    def config
      @@config
    end

    def yql(name, &block);  Smoke::YQL.new(name, &block);  end
    def data(name, &block); Smoke::Data.new(name, &block); end
    def feed(name, &block); Smoke::Feed.new(name, &block); end
    def csv(name, &block); Smoke::CSV.new(name, &block); end

    # Join multiple sources together into a single feed
    # Usage:
    #   Smoke.join(:delicious, :twitter, :flickr) do
    #     name :stream
    #     path :photos, :photo
    #   end
    def join(*names, &block); Smoke::Join.new(names, &block); end
  end

  autoload :YQL, "smoke/source/yql"
  autoload :Data, "smoke/source/data"
  autoload :Feed, "smoke/source/feed"
  autoload :CSV, "smoke/source/csv"
  autoload :Join, "smoke/source/join"
end

Dir["#{File.dirname(__FILE__)}/{core_ext,smoke,smoke/transformers}/*.rb"].each {|r| require r}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You 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.
-->
<config>

  <luceneMatchVersion>${tests.luceneMatchVersion:LUCENE_CURRENT}</luceneMatchVersion>
  <jmx />

  <dataDir>${solr.data.dir:}</dataDir>

  <directoryFactory name="DirectoryFactory" class="${solr.directoryFactory:solr.RAMDirectoryFactory}"/>

  <updateHandler class="solr.DirectUpdateHandler2">
  </updateHandler>

  <requestHandler name="/update"     class="solr.XmlUpdateRequestHandler" />

  <!-- test MCF Security Filter settings -->
  <searchComponent name="mcf-param" class="org.apache.solr.mcf.ManifoldCFSearchComponent" >
    <str name="AuthorityServiceBaseURL">http://localhost:8345/mcf-as</str>
    <int name="SocketTimeOut">3000</int>
    <str name="AllowAttributePrefix">aap-</str>
    <str name="DenyAttributePrefix">dap-</str>
  </searchComponent>

  <searchComponent name="mcf" class="org.apache.solr.mcf.ManifoldCFSearchComponent" >
  </searchComponent>

  <requestHandler name="/mcf" class="solr.SearchHandler" startup="lazy">
    <lst name="invariants">
      <bool name="mcf">true</bool>
    </lst>
    <lst name="defaults">
      <str name="echoParams">all</str>
    </lst>
    <arr name="components">
      <str>query</str>
      <str>mcf</str>
    </arr>
  </requestHandler>

</config>


text:
import unittest
from typing import List

import numpy as np
import torch

from monai.data.meta_tensor import MetaTensor
from monai.transforms.transform import MapTransform
from monai.utils.enums import NumpyPadMode, PytorchPadMode
from tests.utils import TEST_NDARRAYS_ALL, assert_allclose

MODES = []
# Test modes
NP_MODES: List = [
    "constant",
    "edge",
    # `reflect` mode is not supported in some PyTorch versions, skip the test
    # "reflect",
    "wrap",
    "median",
    "mean",
]
MODES += NP_MODES
MODES += [NumpyPadMode(i) for i in NP_MODES]

PT_MODES: list = [
    "constant",
    "replicate",
    "circular",
    # `reflect` mode is not supported in some PyTorch versions, skip the test
    # "reflect",
]
MODES += PT_MODES
MODES += [PytorchPadMode(i) for i in PT_MODES]

class PadTest(unittest.TestCase):
    @staticmethod
    def get_arr(shape):
        return np.random.randint(100, size=shape).astype(float)

    def pad_test(self, input_param, input_shape, expected_shape, modes=None):
        # loop over each mode
        for mode in modes or MODES:
            with self.subTest(mode=mode):
                base_comparison = None
                im = self.get_arr(input_shape)
                padder = self.Padder(mode=mode, **input_param)
                is_map = isinstance(padder, MapTransform)
                # check result is the same regardless of input type
                for im_type in TEST_NDARRAYS_ALL:
                    with self.subTest(im_type=im_type):
                        input_image = im_type(im)
                        input_data = {"img": im_type(im)} if is_map else im_type(im)
                        # our array transforms can also take `mode` as an argument to `__call__`
                        # Check this gives equivalent results
                        for call_extra_args in [{}] if is_map else [{}, {"mode": mode}]:
                            with self.subTest(call_extra_args=call_extra_args):
                                r_out = padder(input_data, **call_extra_args)
                                r_im = r_out["img"] if is_map else r_out
                                # check shape, type, etc.
                                np.testing.assert_allclose(r_im.shape, expected_shape)
                                self.assertIsInstance(r_im, MetaTensor)
                                self.assertEqual(len(r_im.applied_operations), 1)
                                # check results are same regardless of input type
                                if base_comparison is None:
                                    base_comparison = r_im
                                else:
                                    assert_allclose(r_im, base_comparison)
                                # test inverse
                                if isinstance(r_im, MetaTensor):
                                    r_out = padder.inverse(r_out)
                                    r_im = r_out["img"] if is_map else r_out
                                    self.assertIsInstance(r_im, MetaTensor)
                                    assert_allclose(r_im, input_image, type_test=False)
                                    self.assertEqual(r_im.applied_operations, [])

    def pad_test_kwargs(self, unchanged_slices, **input_param):
        for im_type in TEST_NDARRAYS_ALL:
            with self.subTest(im_type=im_type):
                for kwargs in ({"value": 2}, {"constant_values": ((0, 0), (1, 1), (2, 2))}):
                    with self.subTest(kwargs=kwargs):
                        im = im_type(np.random.randint(-100, -10, size=(3, 8, 4)))
                        padder = self.Padder(**input_param, **kwargs)
                        result = padder(im)
                        if isinstance(result, torch.Tensor):
                            result = result.cpu()
                        assert_allclose(result[unchanged_slices], im, type_test=False)
                        # we should have the same as the input plus some 2s (if value) or 1s and 2s (if constant_values)
                        if isinstance(im, torch.Tensor):
                            im = im.detach().cpu().numpy()
                        expected_vals = np.unique(im).tolist()
                        expected_vals += [2] if "value" in kwargs else [1, 2]
                        assert_allclose(np.unique(result), expected_vals, type_test=False)
                        # check inverse
                        if isinstance(result, MetaTensor):
                            inv = padder.inverse(result)
                            assert_allclose(im, inv, type_test=False)
                            self.assertEqual(inv.applied_operations, [])


text:
[![Build Status](https://travis-ci.org/pivotal-sprout/sprout-exemplar.png?branch=master)](https://travis-ci.org/pivotal-sprout/sprout-exemplar)

Template repo for creating standalone cookbooks

## Usage

### Prerequisites

- [system ruby](.ruby-version)
- [bundler](http://bundler.io/)

### Quickstart

```
bundle
bundle exec soloist
```

## Cookbook Usage

### Attributes

*NOTE:* All preferences are namespaced under `sprout => exemplar` they include:

* `path` — The path to the file that exemplar touches; default is `~/exemplar`

### Recipes

1. `sprout-exemplar`
1. `sprout-exemplar::path`

## Contributing

### Before committing

```
bundle
bundle exec rake
```

The default rake task includes rubocop, foodcritic, unit specs

### [Rubocop](https://github.com/bbatsov/rubocop)

```
bundle
bundle exec rake rubocop
```

### [FoodCritic](http://acrmp.github.io/foodcritic/)

```
bundle
bundle exec rake foodcritic
```

### Unit specs

Unit specs use [ServerSpec](http://serverspec.org/)

```
bundle
bundle exec rake spec:unit
```

### Integration specs

Integrations specs will run the default recipe on the host system (destructive) and make assertions on the system after
install.

*Note:* It has a precondition that exemplar is _not_ already installed on the system.

```
bundle
bundle exec rake spec:integration
```


text:
package pdebug

import (
	"os"
	"strconv"
)

// This is protected by the "debug" build tag -- because we only want to
// ever parse the environment variable when the debug code is enabled.
// When debug0 tag is specified, this variable is ALWAYS true.
// When debug  tag is specified, this variable starts out as false, but
// can be toggled to true when the environment variable PDEBUG_TRACE is specified.
// When no tag is specified, this variable isn't event compiled in
var Trace bool

func init() {
	if b, err := strconv.ParseBool(os.Getenv("PDEBUG_TRACE")); err == nil && b {
		Trace = true
	}
}


text:
<?php
namespace flat\api\header;
abstract class exception extends \flat\core\exception{}


text:
using System.Collections.Generic;

namespace XCLCMS.Data.BLL
{
    /// <summary>
    /// 角色功能关系表
    /// </summary>
    public partial class SysRoleFunction
    {
        private readonly XCLCMS.Data.DAL.SysRoleFunction dal = new XCLCMS.Data.DAL.SysRoleFunction();

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public bool Add(XCLCMS.Data.Model.SysRoleFunction model, List<long> functionIdList = null)
        {
            return dal.Add(model, functionIdList);
        }

        /// <summary>
        /// 清理无效的普通商户角色的无效权限
        /// </summary>
        public void ClearInvalidNormalRoleFunctions()
        {
            dal.ClearInvalidNormalRoleFunctions();
        }
    }
}


text:
import * as vscode from 'vscode';
import { getDeepestNode, findNextWord, findPrevWord, getHtmlNode, isNumber } from './util';
import { HtmlNode } from 'EmmetNode';

export function nextItemHTML(selectionStart: vscode.Position, selectionEnd: vscode.Position, editor: vscode.TextEditor, rootNode: HtmlNode): vscode.Selection | undefined {
	let currentNode = getHtmlNode(editor.document, rootNode, selectionEnd, false);
	let nextNode: HtmlNode | undefined = undefined;

	if (!currentNode) {
		return;
	}

	if (currentNode.type !== 'comment') {
		// If cursor is in the tag name, select tag
		if (selectionEnd.isBefore(currentNode.open.start.translate(0, currentNode.name.length))) {
			return getSelectionFromNode(currentNode);
		}

		// If cursor is in the open tag, look for attributes
		if (selectionEnd.isBefore(currentNode.open.end)) {
			let attrSelection = getNextAttribute(selectionStart, selectionEnd, currentNode);
			if (attrSelection) {
				return attrSelection;
			}
		}

		// Get the first child of current node which is right after the cursor and is not a comment
		nextNode = currentNode.firstChild;
		while (nextNode && (selectionEnd.isAfterOrEqual(nextNode.end) || nextNode.type === 'comment')) {
			nextNode = nextNode.nextSibling;
		}
	}

	// Get next sibling of current node which is not a comment. If none is found try the same on the parent
	while (!nextNode && currentNode) {
		if (currentNode.nextSibling) {
			if (currentNode.nextSibling.type !== 'comment') {
				nextNode = currentNode.nextSibling;
			} else {
				currentNode = currentNode.nextSibling;
			}
		} else {
			currentNode = currentNode.parent;
		}
	}

	return nextNode && getSelectionFromNode(nextNode);
}

export function prevItemHTML(selectionStart: vscode.Position, selectionEnd: vscode.Position, editor: vscode.TextEditor, rootNode: HtmlNode): vscode.Selection | undefined {
	let currentNode = getHtmlNode(editor.document, rootNode, selectionStart, false);
	let prevNode: HtmlNode | undefined = undefined;

	if (!currentNode) {
		return;
	}

	if (currentNode.type !== 'comment' && selectionStart.translate(0, -1).isAfter(currentNode.open.start)) {

		if (selectionStart.isBefore(currentNode.open.end) || !currentNode.firstChild || selectionEnd.isBeforeOrEqual(currentNode.firstChild.start)) {
			prevNode = currentNode;
		} else {
			// Select the child that appears just before the cursor and is not a comment
			prevNode = currentNode.firstChild;
			let oldOption: HtmlNode | undefined = undefined;
			while (prevNode.nextSibling && selectionStart.isAfterOrEqual(prevNode.nextSibling.end)) {
				if (prevNode && prevNode.type !== 'comment') {
					oldOption = prevNode;
				}
				prevNode = prevNode.nextSibling;
			}

			prevNode = <HtmlNode>getDeepestNode((prevNode && prevNode.type !== 'comment') ? prevNode : oldOption);
		}
	}

	// Select previous sibling which is not a comment. If none found, then select parent
	while (!prevNode && currentNode) {
		if (currentNode.previousSibling) {
			if (currentNode.previousSibling.type !== 'comment') {
				prevNode = <HtmlNode>getDeepestNode(currentNode.previousSibling);
			} else {
				currentNode = currentNode.previousSibling;
			}
		} else {
			prevNode = currentNode.parent;
		}

	}

	if (!prevNode) {
		return undefined;
	}

	let attrSelection = getPrevAttribute(selectionStart, selectionEnd, prevNode);
	return attrSelection ? attrSelection : getSelectionFromNode(prevNode);
}

function getSelectionFromNode(node: HtmlNode): vscode.Selection | undefined {
	if (node && node.open) {
		let selectionStart = (<vscode.Position>node.open.start).translate(0, 1);
		let selectionEnd = selectionStart.translate(0, node.name.length);

		return new vscode.Selection(selectionStart, selectionEnd);
	}
	return undefined;
}

function getNextAttribute(selectionStart: vscode.Position, selectionEnd: vscode.Position, node: HtmlNode): vscode.Selection | undefined {

	if (!node.attributes || node.attributes.length === 0 || node.type === 'comment') {
		return;
	}

	for (const attr of node.attributes) {
		if (selectionEnd.isBefore(attr.start)) {
			// select full attr
			return new vscode.Selection(attr.start, attr.end);
		}

		if (!attr.value || (<vscode.Position>attr.value.start).isEqual(attr.value.end)) {
			// No attr value to select
			continue;
		}

		if ((selectionStart.isEqual(attr.start) && selectionEnd.isEqual(attr.end)) || selectionEnd.isBefore(attr.value.start)) {
			// cursor is in attr name,  so select full attr value
			return new vscode.Selection(attr.value.start, attr.value.end);
		}

		// Fetch the next word in the attr value

		if (attr.value.toString().indexOf(' ') === -1) {
			// attr value does not have space, so no next word to find
			continue;
		}

		let pos: number | undefined = undefined;
		if (selectionStart.isEqual(attr.value.start) && selectionEnd.isEqual(attr.value.end)) {
			pos = -1;
		}
		if (pos === undefined && selectionEnd.isBefore(attr.end)) {
			pos = selectionEnd.character - attr.value.start.character - 1;
		}

		if (pos !== undefined) {
			let [newSelectionStartOffset, newSelectionEndOffset] = findNextWord(attr.value.toString(), pos);
			if (!isNumber(newSelectionStartOffset) || !isNumber(newSelectionEndOffset)) {
				return;
			}
			if (newSelectionStartOffset >= 0 && newSelectionEndOffset >= 0) {
				const newSelectionStart = (<vscode.Position>attr.value.start).translate(0, newSelectionStartOffset);
				const newSelectionEnd = (<vscode.Position>attr.value.start).translate(0, newSelectionEndOffset);
				return new vscode.Selection(newSelectionStart, newSelectionEnd);
			}
		}

	}

	return;
}

function getPrevAttribute(selectionStart: vscode.Position, selectionEnd: vscode.Position, node: HtmlNode): vscode.Selection | undefined {

	if (!node.attributes || node.attributes.length === 0 || node.type === 'comment') {
		return;
	}

	for (let i = node.attributes.length - 1; i >= 0; i--) {
		let attr = node.attributes[i];

		if (selectionStart.isBeforeOrEqual(attr.start)) {
			continue;
		}

		if (!attr.value || (<vscode.Position>attr.value.start).isEqual(attr.value.end) || selectionStart.isBefore(attr.value.start)) {
			// select full attr
			return new vscode.Selection(attr.start, attr.end);
		}

		if (selectionStart.isEqual(attr.value.start)) {
			if (selectionEnd.isAfterOrEqual(attr.value.end)) {
				// select full attr
				return new vscode.Selection(attr.start, attr.end);
			}
			// select attr value
			return new vscode.Selection(attr.value.start, attr.value.end);
		}

		// Fetch the prev word in the attr value

		let pos = selectionStart.isAfter(attr.value.end) ? attr.value.toString().length : selectionStart.character - attr.value.start.character;
		let [newSelectionStartOffset, newSelectionEndOffset] = findPrevWord(attr.value.toString(), pos);
		if (!isNumber(newSelectionStartOffset) || !isNumber(newSelectionEndOffset)) {
			return;
		}
		if (newSelectionStartOffset >= 0 && newSelectionEndOffset >= 0) {
			const newSelectionStart = (<vscode.Position>attr.value.start).translate(0, newSelectionStartOffset);
			const newSelectionEnd = (<vscode.Position>attr.value.start).translate(0, newSelectionEndOffset);
			return new vscode.Selection(newSelectionStart, newSelectionEnd);
		}
	}

	return;
}


text:
function pluralize (string) {
  const endings = ['ch', 's', 'ss', 'sh', 'x', 'o']
  const vowels = ['a', 'e', 'i', 'o', 'u']
  const last = string.charAt(string.length - 1)
  const lasts = string.substr(string.length - 2)

  if (endings.includes(last) || endings.includes(lasts)) {
    return string.concat('es')
  }

  if (string.endsWith('f')) {
    return string.replace(last, 'ves')
  }

  if (string.endsWith('fe')) {
    return string.replace(lasts, 'ves')
  }

  if (string.endsWith('y') && !vowels.includes(string.charAt(string.length - 2))) {
    return string.replace(last, 'ies')
  }

  return string.concat('s')
}

module.exports = pluralize


text:
<?php
namespace Notejam\Entity;

class Note extends \Asgard\Entity\Entity {
	public static function definition(\Asgard\Entity\Definition $definition) {
		$definition->properties = [
			'name' => [
				'type' => NULL,
				'required' => true,
			],
			'text' => [
				'type' => 'text',
				'required' => true,
			],
			'pad' => [
				'type' => 'entity',
				'entity' => 'Notejam\\Entity\\Pad',
			],
			'user' => [
				'type' => 'entity',
				'entity' => 'Notejam\\Entity\\User',
			],
		];

		$definition->behaviors = [
			new \Asgard\Behaviors\TimestampsBehavior,
		];
	}

	public function __toString() {
		return (string)$this->name;
	}

	public function url() {
		return $this->getDefinition()->getContainer()['resolver']->url(array('Notejam\Controller\Note', 'show'), ['note_id'=>$this->id]);
	}
}


text:
package com.lamfire.json.util;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;

public class FieldInfo implements Comparable<FieldInfo> {

    private final String   name;
    private final Method   method;
    private final Field    field;

    private final Class<?> fieldClass;
    private final Type     fieldType;

    public FieldInfo(String name, Method method, Field field) {
        this.name = name;
        this.method = method;
        this.field = field;

        if (method.getParameterTypes().length == 1) {
            this.fieldClass = method.getParameterTypes()[0];
            this.fieldType = method.getGenericParameterTypes()[0];
        } else {
            this.fieldClass = method.getReturnType();
            this.fieldType = method.getGenericReturnType();
        }
    }

    public Class<?> getFieldClass() {
        return fieldClass;
    }

    public Type getFieldType() {
        return fieldType;
    }

    public String getName() {
        return name;
    }

    public Method getMethod() {
        return method;
    }

    public Field getField() {
        return field;
    }

    public int compareTo(FieldInfo o) {
        return this.name.compareTo(o.name);
    }

    public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
        T annotation = null;
        annotation = method.getAnnotation(annotationClass);

        if (annotation == null) {
            if (field != null) {
                annotation = field.getAnnotation(annotationClass);
            }
        }

        return annotation;
    }
}


text:
<?php

class Migration_add_dsconfigad_data extends \Model
{

    public function up()
    {
        // Get database handle
        $dbh = $this->getdbh();

        // Check if database is already migrated
        // (to fix issue with failed migration init)
        try {
            // This will cause an Exception if not migrated
            $dbh->query("SELECT adforest FROM directoryservice");
            return true;
        } catch (Exception $e) {
        // Not migrated, continue..
        }

        switch ($this->get_driver()) {
            case 'sqlite':
                try {
                    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                    // Wrap in transaction
                    $dbh->beginTransaction();

                    // Create new columns one at a time. Faster to do new table?
                    $sql = "ALTER TABLE directoryservice ADD COLUMN adforest VARCHAR(255)";
                    $dbh->exec($sql);
                    $sql = "ALTER TABLE directoryservice ADD COLUMN addomain VARCHAR(255)";
                    $dbh->exec($sql);
                    $sql = "ALTER TABLE directoryservice ADD COLUMN computeraccount VARCHAR(255)";
                    $dbh->exec($sql);
                    $sql = "ALTER TABLE directoryservice ADD COLUMN createmobileaccount BOOL";
                    $dbh->exec($sql);
                    $sql = "ALTER TABLE directoryservice ADD COLUMN requireconfirmation BOOL";
                    $dbh->exec($sql);
                    $sql = "ALTER TABLE directoryservice ADD COLUMN forcehomeinstartup BOOL";
                    $dbh->exec($sql);
                    $sql = "ALTER TABLE directoryservice ADD COLUMN mounthomeassharepoint BOOL";
                    $dbh->exec($sql);
                    $sql = "ALTER TABLE directoryservice ADD COLUMN usewindowsuncpathforhome BOOL";
                    $dbh->exec($sql);
                    $sql = "ALTER TABLE directoryservice ADD COLUMN networkprotocoltobeused VARCHAR(255)";
                    $dbh->exec($sql);
                    $sql = "ALTER TABLE directoryservice ADD COLUMN defaultusershell VARCHAR(255)";
                    $dbh->exec($sql);
                    $sql = "ALTER TABLE directoryservice ADD COLUMN mappinguidtoattribute VARCHAR(255)";
                    $dbh->exec($sql);
                    $sql = "ALTER TABLE directoryservice ADD COLUMN mappingusergidtoattribute VARCHAR(255)";
                    $dbh->exec($sql);
                    $sql = "ALTER TABLE directoryservice ADD COLUMN mappinggroupgidtoattr VARCHAR(255)";
                    $dbh->exec($sql);
                    $sql = "ALTER TABLE directoryservice ADD COLUMN generatekerberosauth BOOL";
                    $dbh->exec($sql);
                    $sql = "ALTER TABLE directoryservice ADD COLUMN preferreddomaincontroller VARCHAR(255)";
                    $dbh->exec($sql);
                    $sql = "ALTER TABLE directoryservice ADD COLUMN allowedadmingroups VARCHAR(255)";
                    $dbh->exec($sql);
                    $sql = "ALTER TABLE directoryservice ADD COLUMN authenticationfromanydomain BOOL";
                    $dbh->exec($sql);
                    $sql = "ALTER TABLE directoryservice ADD COLUMN packetsigning VARCHAR(255)";
                    $dbh->exec($sql);
                    $sql = "ALTER TABLE directoryservice ADD COLUMN packetencryption VARCHAR(255)";
                    $dbh->exec($sql);
                    $sql = "ALTER TABLE directoryservice ADD COLUMN passwordchangeinterval VARCHAR(255)";
                    $dbh->exec($sql);
                    $sql = "ALTER TABLE directoryservice ADD COLUMN restrictdynamicdnsupdates VARCHAR(255)";
                    $dbh->exec($sql);
                    $sql = "ALTER TABLE directoryservice ADD COLUMN namespacemode VARCHAR(255)";
                    $dbh->exec($sql);

                    $dbh->commit();
                } catch (Exception $e) {
                    $dbh->rollBack();
                    $this->errors .= "Failed: " . $e->getMessage();
                    return false;
                }
                break;

            case 'mysql':
                // Create new columns
                $sql = "ALTER TABLE directoryservice
						ADD adforest VARCHAR(255),
						ADD addomain VARCHAR(255),
						ADD computeraccount VARCHAR(255),
						ADD createmobileaccount BOOL,
						ADD requireconfirmation BOOL,
						ADD forcehomeinstartup BOOL,
						ADD mounthomeassharepoint BOOL,
						ADD usewindowsuncpathforhome BOOL,
						ADD networkprotocoltobeused VARCHAR(255),
						ADD defaultusershell VARCHAR(255),
						ADD mappinguidtoattribute VARCHAR(255),
						ADD mappingusergidtoattribute VARCHAR(255),
						ADD mappinggroupgidtoattr VARCHAR(255),
						ADD generatekerberosauth BOOL,
						ADD preferreddomaincontroller VARCHAR(255),
						ADD allowedadmingroups VARCHAR(255),
						ADD authenticationfromanydomain BOOL,
						ADD packetsigning VARCHAR(255),
						ADD packetencryption VARCHAR(255),
						ADD passwordchangeinterval VARCHAR(255),
						ADD restrictdynamicdnsupdates VARCHAR(255),
						ADD namespacemode VARCHAR(255)";
                $dbh->exec($sql);

                break;

            default:
                # code...
                break;
        }
    }// End function up()

    public function down()
    {
        // Get database handle
        $dbh = $this->getdbh();

        switch ($this->get_driver()) {
            case 'sqlite':
                try {
                    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                    // Wrap in transaction
                    $dbh->beginTransaction();

                    // Create a new temporary table
                    $sql = "CREATE TABLE directoryservice_temp (
								id INTEGER PRIMARY KEY,
								serial_number VARCHAR(255) UNIQUE,
								which_directory_service VARCHAR(255),
								directory_service_comments VARCHAR(255))";
                    $this->query($sql);

                    // Copy values
                    $sql = "INSERT INTO directoryservice_temp SELECT id,serial_number,which_directory_service,directory_service_comments FROM directoryservice";
                    $this->query($sql);

                    $sql = "DROP table directoryservice";
                    $this->query($sql);

                    $sql = "ALTER TABLE directoryservice_temp RENAME TO directoryservice";
                    $this->query($sql);

                    $dbh->commit();
                } catch (Exception $e) {
                    $dbh->rollBack();
                    $this->errors .= "Failed: " . $e->getMessage();
                    return false;
                }
                break;

            case 'mysql':
                // Drop the new columns
                $sql = "ALTER TABLE directoryservice
						DROP adforest,
						DROP addomain,
						DROP computeraccount,
						DROP createmobileaccount,
						DROP requireconfirmation,
						DROP forcehomeinstartup,
						DROP mounthomeassharepoint,
						DROP usewindowsuncpathforhome,
						DROP networkprotocoltobeused,
						DROP defaultusershell,
						DROP mappinguidtoattribute,
						DROP mappingusergidtoattribute,
						DROP mappinggroupgidtoattr,
						DROP generatekerberosauth,
						DROP preferreddomaincontroller,
						DROP allowedadmingroups,
						DROP authenticationfromanydomain,
						DROP packetsigning,
						DROP packetencryption,
						DROP passwordchangeinterval,
						DROP restrictdynamicdnsupdates,
						DROP namespacemode";
                $dbh->query($sql);

                break;

            default:
                # code...
                break;
        }
    }
}


text:
module Paperlex
  class Slaw < Base
    include RootObject

    extend ActiveSupport::Autoload
    autoload :Versions

    property :public
    property :name
    property :description
    property :body
    property :response_keys

    class << self
      def url_name
        "slaws"
      end

      def update_fields
        [:name, :body, :description]
      end
      alias :create_fields :update_fields

      def create(attrs = {})
        attrs.symbolize_keys!
        attrs.assert_valid_keys(create_fields)
        attrs = post(collection_url, :slaw => attrs)
        new(attrs)
      end
    end

    def html_url(responses = nil, options = {})
      params = options.merge(:token => Paperlex.token)
      params[:responses] = responses if responses.present?
      "#{Paperlex.base_url}/slaws/#{uuid}.html?#{params.to_query}"
    end

    def to_html(responses = nil, options = {})
      RestClient.get(html_url(responses, options))
    end

    def destroy
      self.class.delete(self.class.url_for(uuid))
    end

    # Versions
    def versions
      Paperlex::Slaw::Versions[uuid].all.map {|version| Version.new(version) }
    end

    def at_version(version_index)
      self.class.new(Paperlex::Slaw::Versions[uuid].find(version_index))
    end
    alias_method :version_at, :at_version

    def revert_to_version(version_index)
      self.class.new(Paperlex::Slaw::Versions[uuid].revert_to(version_index))
    end

    private

    def short_name
      :slaw
    end
  end
end


text:
<?php

use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
use Zizaco\Confide\ConfideUser;

class User extends ConfideUser implements UserInterface, RemindableInterface
{
	protected $softDelete = true;

    public static $rules = array(
    	/*
    	'username' => 'required|unique:users',
        'password' => 'required|between:6,32|confirmed',
        'password_confirmation' => 'between:6,32',
        */
    );

    protected $updateRules = array(
    	/*
    	'email' => 'required|unique:users',
		'username' => 'required|unique:users',
		*/
    );

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'users';

	public function account()
	{
		return $this->belongsTo('Account');
	}

	public function branch()
	{
		return $this->belongsTo('Branch');
	}

	public function theme()
	{
		return $this->belongsTo('Theme');
	}

	public function getPersonType()
	{
		return PERSON_USER;
	}

	/**
	 * Get the unique identifier for the user.
	 *
	 * @return mixed
	 */
	public function getAuthIdentifier()
	{
		return $this->getKey();
	}

	/**
	 * Get the password for the user.
	 *
	 * @return string
	 */
	public function getAuthPassword()
	{
		return $this->password;
	}

	/**
	 * Get the e-mail address where password reminders are sent.
	 *
	 * @return string
	 */
	public function getReminderEmail()
	{
		return $this->email;
	}
	public function price_type_id()
	{
		return $this->price_type_id;
	}

	public function isPro()
	{
		return $this->account->isPro();
	}

	public function getDisplayName()
	{
		return $this->branch->name(). '-' . $this->getDisplayName2();
	}

	public function getDisplayName2()
	{
		if ($this->getFullName())
		{
			return $this->getFullName();
		}
		else if ($this->email)
		{
			return $this->email;
		}
		else
		{
			return 'Guest';
		}
	}

	public function getFullName()
	{
		if ($this->first_name || $this->last_name)
		{
			return $this->first_name . ' ' . $this->last_name;
		}
		else
		{
			return '';
		}
	}

	public function showGreyBackground()
	{
		return !$this->theme_id || in_array($this->theme_id, [2, 3, 5, 6, 7, 8, 10, 11, 12]);
	}

	public function getRequestsCount()
	{
		return Session::get(SESSION_COUNTER, 0);
	}

	public function getPopOverText()
	{
		if (!Auth::check() || Session::has('error'))
		{
			return false;
		}

		$count = self::getRequestsCount();

		if ($count == 1 || $count % 5 == 0)
		{
			if (!Utils::isRegistered())
			{
				return trans('texts.sign_up_to_save');
			}
			else if (!Auth::user()->account->name)
			{
				return trans('texts.set_name');
			}
		}

		return false;
	}

	public function afterSave($success=true, $forced = false)
	{
		if ($this->email)
		{
			return parent::afterSave($success=true, $forced = false);
		}
		else
		{
			return true;
		}
	}

	public function getMaxNumClients()
	{
		return $this->isPro() ? MAX_NUM_CLIENTS_PRO : MAX_NUM_CLIENTS;
	}

	public function getRememberToken()
	{
	    return $this->remember_token;
	}

	public function setRememberToken($value)
	{
	    $this->remember_token = $value;
	}

	public function getRememberTokenName()
	{
	    return 'remember_token';
	}

	public function isAdmin()
	{

        if($this->branch_id == 1)
        {
        	return true;
        }
        else
        {
        	return false;
        }
	}
}


text:
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/public/cpp/holding_space/holding_space_model.h"

#include <memory>
#include <vector>

#include "ash/constants/ash_features.h"
#include "ash/public/cpp/holding_space/holding_space_constants.h"
#include "ash/public/cpp/holding_space/holding_space_image.h"
#include "ash/public/cpp/holding_space/holding_space_item.h"
#include "ash/public/cpp/holding_space/holding_space_model_observer.h"
#include "ash/public/cpp/holding_space/holding_space_progress.h"
#include "ash/public/cpp/holding_space/holding_space_util.h"
#include "base/bind.h"
#include "base/scoped_observation.h"
#include "base/test/scoped_feature_list.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/chromeos/styles/cros_styles.h"
#include "ui/gfx/paint_vector_icon.h"

namespace ash {
namespace {

using UpdatedField = HoldingSpaceModelObserver::UpdatedField;

// Helpers ---------------------------------------------------------------------

HoldingSpaceItem::InProgressCommand CreateInProgressCommand(
    HoldingSpaceCommandId command_id) {
  return HoldingSpaceItem::InProgressCommand(command_id, /*label_id=*/-1,
                                             &gfx::kNoneIcon,
                                             /*handler=*/base::DoNothing());
}

std::vector<HoldingSpaceItem::Type> GetHoldingSpaceItemTypes() {
  std::vector<HoldingSpaceItem::Type> types;
  for (int i = 0; i <= static_cast<int>(HoldingSpaceItem::Type::kMaxValue); ++i)
    types.emplace_back(static_cast<HoldingSpaceItem::Type>(i));
  return types;
}

std::unique_ptr<HoldingSpaceImage> CreateFakeHoldingSpaceImage(
    HoldingSpaceItem::Type type,
    const base::FilePath& file_path) {
  return std::make_unique<HoldingSpaceImage>(
      holding_space_util::GetMaxImageSizeForType(type), file_path,
      /*async_bitmap_resolver=*/base::DoNothing());
}

std::unique_ptr<HoldingSpaceItem> CreateItem(HoldingSpaceItem::Type type) {
  return HoldingSpaceItem::CreateFileBackedItem(
      /*type=*/type, base::FilePath("file_path"),
      GURL("filesystem::file_system_url"),
      /*image_resolver=*/base::BindOnce(&CreateFakeHoldingSpaceImage));
}

// ScopedModelObservation ------------------------------------------------------

// A class which observes a `HoldingSpaceModel` within its lifetime. Note that
// this class must not outlive the `model` that it observes.
class ScopedModelObservation : public HoldingSpaceModelObserver {
 public:
  explicit ScopedModelObservation(HoldingSpaceModel* model) {
    observation_.Observe(model);
  }

  ScopedModelObservation(const ScopedModelObservation&) = delete;
  ScopedModelObservation& operator=(const ScopedModelObservation&) = delete;
  ~ScopedModelObservation() override = default;

  // Returns the last updated fields for which `OnHoldingSpaceItemUpdated()`
  // was called, clearing the cached value.
  uint32_t TakeLastUpdatedFields() {
    const uint32_t updated_fields = last_updated_fields_;
    last_updated_fields_ = 0u;
    return updated_fields;
  }

  // Returns the last `HoldingSpaceItem` for which `OnHoldingSpaceItemUpdated()`
  // was called, clearing the cached value.
  const HoldingSpaceItem* TakeLastUpdatedItem() {
    const HoldingSpaceItem* result = last_updated_item_;
    last_updated_item_ = nullptr;
    return result;
  }

  // Returns the count of times for which `OnHoldingSpaceItemUpdated()` was
  // called, clearing the cached value.
  int TakeUpdatedItemCount() {
    const int result = updated_item_count_;
    updated_item_count_ = 0;
    return result;
  }

  // Returns the id's of `HoldingSpaceItem`s for which
  // `OnHoldingSpaceItemRemoved()` was called. Also clears the cached values.
  std::vector<std::string> TakeRemovedItems() {
    std::vector<std::string> result;
    result.swap(removed_item_ids_);
    return result;
  }

 private:
  // HoldingSpaceModel::Observer:
  void OnHoldingSpaceItemUpdated(const HoldingSpaceItem* item,
                                 uint32_t updated_fields) override {
    last_updated_item_ = item;
    last_updated_fields_ = updated_fields;
    ++updated_item_count_;
  }

  void OnHoldingSpaceItemsRemoved(
      const std::vector<const HoldingSpaceItem*>& items) override {
    for (const HoldingSpaceItem* item : items)
      removed_item_ids_.push_back(item->id());
  }

  // The last `HoldingSpaceItem` for which `OnHoldingSpaceItemUpdated()` was
  // called. May be `nullptr` prior to an update event or following a call to
  // `TakeLastUpdatedItem()`.
  const HoldingSpaceItem* last_updated_item_ = nullptr;

  // The last updated fields for which `OnHoldingSpaceItemUpdated()` was called.
  // May be zero prior to an update event or following a call to
  // `TakeLastUpdatedFields()`.
  uint32_t last_updated_fields_ = 0u;

  // The count of times for which `OnHoldingSpaceItemUpdated()` was called. May
  // be reset following a call to `TakeUpdatedItemCount()`.
  int updated_item_count_ = 0;

  // A vector of item id's that have been removed.
  std::vector<std::string> removed_item_ids_;

  base::ScopedObservation<HoldingSpaceModel, HoldingSpaceModelObserver>
      observation_{this};
};

}  // namespace

// Print out the `HoldingSpaceItem::Type` in the test output.
std::ostream& operator<<(std::ostream& os, const HoldingSpaceItem::Type type) {
  return os << holding_space_util::ToString(type);
}

// HoldingSpaceModelTest -------------------------------------------------------

// Base class for `HoldingSpaceModel` tests, parameterized by the set of all
// holding space item types.
class HoldingSpaceModelTest
    : public testing::TestWithParam<std::tuple<HoldingSpaceItem::Type, bool>> {
 public:
  HoldingSpaceModelTest() {
    scoped_feature_list_.InitWithFeatureState(
        features::kHoldingSpacePredictability,
        IsHoldingSpacePredictabilityEnabled());
  }

  // Returns the `HoldingSpaceModel` under test.
  HoldingSpaceModel& model() { return model_; }

  bool IsHoldingSpacePredictabilityEnabled() const {
    return std::get<1>(GetParam());
  }

  HoldingSpaceItem::Type GetHoldingSpaceItemType() {
    return std::get<0>(GetParam());
  }

 private:
  HoldingSpaceModel model_;
  base::test::ScopedFeatureList scoped_feature_list_;
};

INSTANTIATE_TEST_SUITE_P(
    All,
    HoldingSpaceModelTest,
    testing::Combine(testing::ValuesIn(GetHoldingSpaceItemTypes()),
                     testing::Bool()));

// Tests -----------------------------------------------------------------------

// Verifies that updating fields which affect accessible name WAI.
TEST_P(HoldingSpaceModelTest, UpdateItem_AccessibleName) {
  ScopedModelObservation observation(&model());

  // Verify the `model()` is initially empty.
  EXPECT_EQ(model().items().size(), 0u);

  // Create a holding space `item`.
  auto item = HoldingSpaceItem::CreateFileBackedItem(
      /*type=*/GetHoldingSpaceItemType(), base::FilePath("file_path"),
      GURL("filesystem::file_system_url"),
      HoldingSpaceProgress(/*current_bytes=*/0, /*total_bytes=*/100),
      /*image_resolver=*/base::BindOnce(&CreateFakeHoldingSpaceImage));
  auto* item_ptr = item.get();

  // Add `item` to the `model()`.
  model().AddItem(std::move(item));
  EXPECT_EQ(model().items().size(), 1u);
  EXPECT_EQ(model().items()[0].get(), item_ptr);

  // Initially accessible name is the lossy display name of the backing file.
  EXPECT_EQ(item_ptr->GetAccessibleName(), u"file_path");

  // Update text. Because accessible name is not overridden, this should result
  // in an update to the computed accessible name field.
  model().UpdateItem(item_ptr->id())->SetText(u"text");
  EXPECT_EQ(observation.TakeLastUpdatedItem(), item_ptr);
  EXPECT_TRUE(observation.TakeLastUpdatedFields() &
              UpdatedField::kAccessibleName);
  EXPECT_EQ(observation.TakeUpdatedItemCount(), 1);
  EXPECT_EQ(item_ptr->GetAccessibleName(), u"text");

  // Update secondary text. Because accessible name is not overridden, this
  // should result in an update to the computed accessible name field.
  model().UpdateItem(item_ptr->id())->SetSecondaryText(u"secondary_text");
  EXPECT_EQ(observation.TakeLastUpdatedItem(), item_ptr);
  EXPECT_TRUE(observation.TakeLastUpdatedFields() &
              UpdatedField::kAccessibleName);
  EXPECT_EQ(observation.TakeUpdatedItemCount(), 1);
  EXPECT_EQ(item_ptr->GetAccessibleName(), u"text, secondary_text");

  // Update accessible name. Note that accessible name field is now overridden
  // from its previously computed value.
  model().UpdateItem(item_ptr->id())->SetAccessibleName(u"accessible_name");
  EXPECT_EQ(observation.TakeLastUpdatedItem(), item_ptr);
  EXPECT_EQ(observation.TakeLastUpdatedFields(), UpdatedField::kAccessibleName);
  EXPECT_EQ(observation.TakeUpdatedItemCount(), 1);
  EXPECT_EQ(item_ptr->GetAccessibleName(), u"accessible_name");

  // Update text. Because accessible name is overridden, this should *not*
  // result in an update to the computed accessible name field.
  model().UpdateItem(item_ptr->id())->SetText(u"updated_text");
  EXPECT_EQ(observation.TakeLastUpdatedItem(), item_ptr);
  EXPECT_EQ(observation.TakeLastUpdatedFields(), UpdatedField::kText);
  EXPECT_EQ(observation.TakeUpdatedItemCount(), 1);
  EXPECT_EQ(item_ptr->GetAccessibleName(), u"accessible_name");

  // Update secondary text. Because accessible name is overridden, this should
  // *not* result in an update to the computed accessible name field.
  model()
      .UpdateItem(item_ptr->id())
      ->SetSecondaryText(u"updated_secondary_text");
  EXPECT_EQ(observation.TakeLastUpdatedItem(), item_ptr);
  EXPECT_EQ(observation.TakeLastUpdatedFields(), UpdatedField::kSecondaryText);
  EXPECT_EQ(observation.TakeUpdatedItemCount(), 1);
  EXPECT_EQ(item_ptr->GetAccessibleName(), u"accessible_name");

  // Update accessible name. Note that accessible name field is no longer being
  // overridden from its computed value.
  model().UpdateItem(item_ptr->id())->SetAccessibleName(absl::nullopt);
  EXPECT_EQ(observation.TakeLastUpdatedItem(), item_ptr);
  EXPECT_EQ(observation.TakeLastUpdatedFields(), UpdatedField::kAccessibleName);
  EXPECT_EQ(observation.TakeUpdatedItemCount(), 1);
  EXPECT_EQ(item_ptr->GetAccessibleName(),
            u"updated_text, updated_secondary_text");
}

// Verifies that updating multiple item attributes is atomic.
TEST_P(HoldingSpaceModelTest, UpdateItem_Atomic) {
  ScopedModelObservation observation(&model());

  // Verify the `model()` is initially empty.
  EXPECT_EQ(model().items().size(), 0u);

  // Create a holding space `item`.
  auto item = HoldingSpaceItem::CreateFileBackedItem(
      /*type=*/GetHoldingSpaceItemType(), base::FilePath("file_path"),
      GURL("filesystem::file_system_url"),
      HoldingSpaceProgress(/*current_bytes=*/0, /*total_bytes=*/100),
      /*image_resolver=*/base::BindOnce(&CreateFakeHoldingSpaceImage));
  auto* item_ptr = item.get();

  // Add `item` to the `model()`.
  model().AddItem(std::move(item));
  EXPECT_EQ(model().items().size(), 1u);
  EXPECT_EQ(model().items()[0].get(), item_ptr);

  // Update accessible name.
  model().UpdateItem(item_ptr->id())->SetAccessibleName(u"accessible_name");
  EXPECT_EQ(observation.TakeLastUpdatedItem(), item_ptr);
  EXPECT_EQ(observation.TakeLastUpdatedFields(), UpdatedField::kAccessibleName);
  EXPECT_EQ(observation.TakeUpdatedItemCount(), 1);
  EXPECT_EQ(item_ptr->GetAccessibleName(), u"accessible_name");

  // Update backing file.
  base::FilePath updated_file_path("updated_file_path");
  GURL updated_file_system_url("filesystem::updated_file_system_url");
  model()
      .UpdateItem(item_ptr->id())
      ->SetBackingFile(updated_file_path, updated_file_system_url);
  EXPECT_EQ(observation.TakeLastUpdatedItem(), item_ptr);
  EXPECT_EQ(observation.TakeLastUpdatedFields(), UpdatedField::kBackingFile);
  EXPECT_EQ(observation.TakeUpdatedItemCount(), 1);
  EXPECT_EQ(item_ptr->file_path(), updated_file_path);
  EXPECT_EQ(item_ptr->file_system_url(), updated_file_system_url);

  // Update in-progress commands.
  std::vector<HoldingSpaceItem::InProgressCommand> in_progress_commands;
  in_progress_commands.push_back(
      CreateInProgressCommand(HoldingSpaceCommandId::kCancelItem));
  model()
      .UpdateItem(item_ptr->id())
      ->SetInProgressCommands(in_progress_commands);
  EXPECT_EQ(observation.TakeLastUpdatedItem(), item_ptr);
  EXPECT_EQ(observation.TakeLastUpdatedFields(),
            UpdatedField::kInProgressCommands);
  EXPECT_EQ(observation.TakeUpdatedItemCount(), 1);
  EXPECT_EQ(item_ptr->in_progress_commands(), in_progress_commands);

  // Update progress.
  model()
      .UpdateItem(item_ptr->id())
      ->SetProgress(
          HoldingSpaceProgress(/*current_bytes=*/50, /*total_bytes=*/100));
  EXPECT_EQ(observation.TakeLastUpdatedItem(), item_ptr);
  EXPECT_EQ(observation.TakeLastUpdatedFields(), UpdatedField::kProgress);
  EXPECT_EQ(observation.TakeUpdatedItemCount(), 1);
  EXPECT_EQ(item_ptr->progress().GetValue(), 0.5f);

  // Update text.
  model().UpdateItem(item_ptr->id())->SetText(u"text");
  EXPECT_EQ(observation.TakeLastUpdatedItem(), item_ptr);
  EXPECT_EQ(observation.TakeLastUpdatedFields(), UpdatedField::kText);
  EXPECT_EQ(observation.TakeUpdatedItemCount(), 1);
  EXPECT_EQ(item_ptr->GetText(), u"text");

  // Update secondary text.
  model().UpdateItem(item_ptr->id())->SetSecondaryText(u"secondary_text");
  EXPECT_EQ(observation.TakeLastUpdatedItem(), item_ptr);
  EXPECT_EQ(observation.TakeLastUpdatedFields(), UpdatedField::kSecondaryText);
  EXPECT_EQ(observation.TakeUpdatedItemCount(), 1);
  EXPECT_EQ(item_ptr->secondary_text(), u"secondary_text");

  // Update secondary text color.
  model()
      .UpdateItem(item_ptr->id())
      ->SetSecondaryTextColor(cros_styles::ColorName::kTextColorAlert);
  EXPECT_EQ(observation.TakeLastUpdatedItem(), item_ptr);
  EXPECT_EQ(observation.TakeLastUpdatedFields(),
            UpdatedField::kSecondaryTextColor);
  EXPECT_EQ(observation.TakeUpdatedItemCount(), 1);
  EXPECT_EQ(item_ptr->secondary_text_color(),
            cros_styles::ColorName::kTextColorAlert);

  // Update all attributes.
  in_progress_commands.push_back(
      CreateInProgressCommand(HoldingSpaceCommandId::kPauseItem));
  updated_file_path = base::FilePath("again_updated_file_path");
  updated_file_system_url = GURL("filesystem::again_updated_file_system_url");
  model()
      .UpdateItem(item_ptr->id())
      ->SetAccessibleName(u"updated_accessible_name")
      .SetBackingFile(updated_file_path, updated_file_system_url)
      .SetInProgressCommands(in_progress_commands)
      .SetText(u"updated_text")
      .SetSecondaryText(u"updated_secondary_text")
      .SetSecondaryTextColor(cros_styles::ColorName::kTextColorWarning)
      .SetProgress(
          HoldingSpaceProgress(/*current_bytes=*/75, /*total_bytes=*/100));
  EXPECT_EQ(observation.TakeLastUpdatedItem(), item_ptr);
  EXPECT_EQ(observation.TakeLastUpdatedFields(),
            UpdatedField::kAccessibleName | UpdatedField::kBackingFile |
                UpdatedField::kInProgressCommands | UpdatedField::kProgress |
                UpdatedField::kSecondaryText |
                UpdatedField::kSecondaryTextColor | UpdatedField::kText);
  EXPECT_EQ(observation.TakeUpdatedItemCount(), 1);
  EXPECT_EQ(item_ptr->GetAccessibleName(), u"updated_accessible_name");
  EXPECT_EQ(item_ptr->file_path(), updated_file_path);
  EXPECT_EQ(item_ptr->file_system_url(), updated_file_system_url);
  EXPECT_EQ(item_ptr->in_progress_commands(), in_progress_commands);
  EXPECT_EQ(item_ptr->progress().GetValue(), 0.75f);
  EXPECT_EQ(item_ptr->GetText(), u"updated_text");
  EXPECT_EQ(item_ptr->secondary_text(), u"updated_secondary_text");
  EXPECT_EQ(item_ptr->secondary_text_color(),
            cros_styles::ColorName::kTextColorWarning);
}

// Verifies that updating items will no-op appropriately.
TEST_P(HoldingSpaceModelTest, UpdateItem_Noop) {
  ScopedModelObservation observation(&model());

  // Verify the `model()` is initially empty.
  EXPECT_EQ(model().items().size(), 0u);

  // Create a holding space `item`.
  auto item = HoldingSpaceItem::CreateFileBackedItem(
      /*type=*/GetHoldingSpaceItemType(), base::FilePath("file_path"),
      GURL("filesystem::file_system_url"), HoldingSpaceProgress(),
      /*image_resolver=*/base::BindOnce(&CreateFakeHoldingSpaceImage));
  auto* item_ptr = item.get();

  // Add `item` to the `model()`.
  model().AddItem(std::move(item));
  EXPECT_EQ(model().items().size(), 1u);
  EXPECT_EQ(model().items()[0].get(), item_ptr);

  // Perform a no-op update. No observers should be notified.
  model().UpdateItem(item_ptr->id());
  EXPECT_EQ(observation.TakeUpdatedItemCount(), 0);

  // Perform another no-op update. No observers should be notified.
  model()
      .UpdateItem(item_ptr->id())
      ->SetAccessibleName(absl::nullopt)
      .SetBackingFile(item_ptr->file_path(), item_ptr->file_system_url())
      .SetInProgressCommands({})
      .SetText(absl::nullopt)
      .SetSecondaryText(absl::nullopt)
      .SetSecondaryTextColor(absl::nullopt)
      .SetProgress(item_ptr->progress());
  EXPECT_EQ(observation.TakeUpdatedItemCount(), 0);
}

// Verifies that updating item in-progress commands as intended.
TEST_P(HoldingSpaceModelTest, UpdateItem_InProgressCommands) {
  ScopedModelObservation observation(&model());

  // Verify the `model()` is initially empty.
  EXPECT_EQ(model().items().size(), 0u);

  // Create an in-progress holding space `item`.
  auto item = HoldingSpaceItem::CreateFileBackedItem(
      /*type=*/GetHoldingSpaceItemType(), base::FilePath("file_path"),
      GURL("filesystem::file_system_url"),
      HoldingSpaceProgress(/*current_bytes=*/0, /*total_bytes=*/100),
      /*image_resolver=*/base::BindOnce(&CreateFakeHoldingSpaceImage));
  auto* item_ptr = item.get();

  // Add `item` to the `model()`.
  model().AddItem(std::move(item));
  EXPECT_EQ(model().items().size(), 1u);
  EXPECT_EQ(model().items()[0].get(), item_ptr);

  // Verify the item has no in-progress commands.
  EXPECT_TRUE(item_ptr->in_progress_commands().empty());

  // Attempt to update in-progress commands to empty. This should no-op.
  model().UpdateItem(item_ptr->id())->SetInProgressCommands({});
  EXPECT_FALSE(observation.TakeLastUpdatedItem());
  EXPECT_EQ(observation.TakeLastUpdatedFields(), 0u);
  EXPECT_TRUE(item_ptr->in_progress_commands().empty());

  // Update in-progress commands.
  std::vector<HoldingSpaceItem::InProgressCommand> in_progress_commands;
  in_progress_commands.push_back(
      CreateInProgressCommand(HoldingSpaceCommandId::kCancelItem));
  model()
      .UpdateItem(item_ptr->id())
      ->SetInProgressCommands(in_progress_commands);
  EXPECT_EQ(observation.TakeLastUpdatedItem(), item_ptr);
  EXPECT_EQ(observation.TakeLastUpdatedFields(),
            UpdatedField::kInProgressCommands);
  EXPECT_EQ(item_ptr->in_progress_commands(), in_progress_commands);

  // Update in-progress commands again.
  in_progress_commands.push_back(
      CreateInProgressCommand(HoldingSpaceCommandId::kPauseItem));
  model()
      .UpdateItem(item_ptr->id())
      ->SetInProgressCommands(in_progress_commands);
  EXPECT_EQ(observation.TakeLastUpdatedItem(), item_ptr);
  EXPECT_EQ(observation.TakeLastUpdatedFields(),
            UpdatedField::kInProgressCommands);
  EXPECT_EQ(item_ptr->in_progress_commands(), in_progress_commands);

  // Update in-progress commands and progress to completion. Because the item is
  // no longer in progress, in-progress commands should be empty.
  in_progress_commands.push_back(
      CreateInProgressCommand(HoldingSpaceCommandId::kResumeItem));
  model()
      .UpdateItem(item_ptr->id())
      ->SetInProgressCommands(in_progress_commands)
      .SetProgress(
          HoldingSpaceProgress(/*current_bytes=*/100, /*total_bytes=*/100));
  EXPECT_EQ(observation.TakeLastUpdatedItem(), item_ptr);
  EXPECT_EQ(observation.TakeLastUpdatedFields(),
            UpdatedField::kInProgressCommands | UpdatedField::kProgress);
  EXPECT_TRUE(item_ptr->progress().IsComplete());
  EXPECT_TRUE(item_ptr->in_progress_commands().empty());

  // Attempts to update in-progress commands should no-op for completed items.
  model()
      .UpdateItem(item_ptr->id())
      ->SetInProgressCommands(in_progress_commands);
  EXPECT_FALSE(observation.TakeLastUpdatedItem());
  EXPECT_EQ(observation.TakeLastUpdatedFields(), 0u);
  EXPECT_TRUE(item_ptr->in_progress_commands().empty());
}

// Verifies that updating item progress works as intended.
TEST_P(HoldingSpaceModelTest, UpdateItem_Progress) {
  ScopedModelObservation observation(&model());

  // Verify the `model()` is initially empty.
  EXPECT_EQ(model().items().size(), 0u);

  // Create a holding space `item`.
  auto item = HoldingSpaceItem::CreateFileBackedItem(
      /*type=*/GetHoldingSpaceItemType(), base::FilePath("file_path"),
      GURL("filesystem::file_system_url"),
      HoldingSpaceProgress(/*current_bytes=*/absl::nullopt,
                           /*total_bytes=*/100),
      /*image_resolver=*/base::BindOnce(&CreateFakeHoldingSpaceImage));
  auto* item_ptr = item.get();

  // Add `item` to the `model()`.
  model().AddItem(std::move(item));
  EXPECT_EQ(model().items().size(), 1u);
  EXPECT_EQ(model().items()[0].get(), item_ptr);

  // Verify progress is indeterminate.
  EXPECT_TRUE(item_ptr->progress().IsIndeterminate());

  // Update progress to `0.5f`.
  model()
      .UpdateItem(item_ptr->id())
      ->SetProgress(
          HoldingSpaceProgress(/*current_bytes=*/50, /*total_bytes=*/100));
  EXPECT_EQ(observation.TakeLastUpdatedItem(), item_ptr);
  EXPECT_EQ(observation.TakeLastUpdatedFields(), UpdatedField::kProgress);
  EXPECT_EQ(item_ptr->progress().GetValue(), 0.5f);

  // Update progress to `0.5f` again. This should no-op.
  model()
      .UpdateItem(item_ptr->id())
      ->SetProgress(
          HoldingSpaceProgress(/*current_bytes=*/50, /*total_bytes=*/100));
  EXPECT_FALSE(observation.TakeLastUpdatedItem());
  EXPECT_EQ(observation.TakeLastUpdatedFields(), 0u);
  EXPECT_EQ(item_ptr->progress().GetValue(), 0.5f);

  // Update progress to indeterminate.
  model()
      .UpdateItem(item_ptr->id())
      ->SetProgress(HoldingSpaceProgress(/*current_bytes=*/absl::nullopt,
                                         /*total_bytes=*/100));
  EXPECT_EQ(observation.TakeLastUpdatedItem(), item_ptr);
  EXPECT_EQ(observation.TakeLastUpdatedFields(), UpdatedField::kProgress);
  EXPECT_TRUE(item_ptr->progress().IsIndeterminate());

  // Update progress to complete.
  model()
      .UpdateItem(item_ptr->id())
      ->SetProgress(
          HoldingSpaceProgress(/*current_bytes=*/100, /*total_bytes=*/100));
  EXPECT_EQ(observation.TakeLastUpdatedItem(), item_ptr);
  EXPECT_EQ(observation.TakeLastUpdatedFields(), UpdatedField::kProgress);
  EXPECT_TRUE(item_ptr->progress().IsComplete());

  // Update progress to `0.5f`. This should no-op as progress becomes read-only
  // after being marked completed.
  model()
      .UpdateItem(item_ptr->id())
      ->SetProgress(
          HoldingSpaceProgress(/*current_bytes=*/50, /*total_bytes=*/100));
  EXPECT_FALSE(observation.TakeLastUpdatedItem());
  EXPECT_EQ(observation.TakeLastUpdatedFields(), 0u);
  EXPECT_TRUE(item_ptr->progress().IsComplete());
}

TEST_P(HoldingSpaceModelTest,
       AddingItemsPushesOutOldestItemsWhenMaxItemsPerSectionReached) {
  ScopedModelObservation observation(&model());

  // Verify the `model()` is initially empty.
  EXPECT_EQ(model().items().size(), 0u);

  // Add 2 items and store their id's to assert that they were deleted later.
  auto first_item = CreateItem(GetHoldingSpaceItemType());
  std::string first_item_id = first_item.get()->id();
  model().AddItem(std::move(first_item));
  auto second_item = CreateItem(GetHoldingSpaceItemType());
  std::string second_item_id = second_item.get()->id();
  model().AddItem(std::move(second_item));

  // Starting at index 2, add more items up to `kMaxItemsPerSection`.
  for (size_t i = 2; i < kMaxItemsPerSection; ++i) {
    // Add `item` to the `model()`.
    model().AddItem(CreateItem(GetHoldingSpaceItemType()));
  }
  // Verify we've reached the limit of `items` in the model.
  EXPECT_EQ(model().items().size(), kMaxItemsPerSection);

  // Add 2 more `item`s which takes us to `kMaxItemsPerSection` + 2.
  constexpr int kExtraItems = 2;
  for (int i = 0; i < kExtraItems; ++i)
    model().AddItem(CreateItem(GetHoldingSpaceItemType()));

  // If the `type` is contained inside the screen capture or downloads
  // sections and the feature flag is enabled, then assert that we have no more
  // than the `kMaxItemsPerSection` and that the oldest item(s) were deleted.
  if (IsHoldingSpacePredictabilityEnabled() &&
      (holding_space_util::IsDownloadType(GetHoldingSpaceItemType()) ||
       holding_space_util::IsScreenCaptureType(GetHoldingSpaceItemType()))) {
    EXPECT_EQ(model().items().size(), kMaxItemsPerSection);
    EXPECT_EQ(model().GetItem(first_item_id), nullptr);
    EXPECT_EQ(model().GetItem(second_item_id), nullptr);
    EXPECT_THAT(observation.TakeRemovedItems(),
                testing::ElementsAre(first_item_id, second_item_id));
  } else {
    // If the `type` is not contained inside the screen capture or downloads
    // section buckets or the feature flag is disabled then we expect to exceed
    // the `kMaxItemsPerSection` and not delete anything.
    EXPECT_EQ(model().items().size(), kMaxItemsPerSection + kExtraItems);
    EXPECT_TRUE(model().GetItem(first_item_id));
    EXPECT_TRUE(model().GetItem(second_item_id));
    EXPECT_TRUE(observation.TakeRemovedItems().empty());
  }
}

}  // namespace ash


text:
coFORCE_INLINE coFloatx3 coMake_Floatx3(coFloat _a) { return coBitCast<coFloatx3>(_mm_set1_ps(_a)); }
coFORCE_INLINE coFloatx3 coMake_Floatx3(coFloat _x, coFloat _y, coFloat _z) { return coBitCast<coFloatx3>(_mm_set_ps(_z, _z, _y, _x)); }
coFORCE_INLINE coFloatx3 coMake_Floatx3(const coFloatx3& _xxx, const coFloatx3& _yyy, const coFloatx3& _zzz)
{
	const __m128 x = coBitCast<__m128>(_xxx);
	const __m128 y = coBitCast<__m128>(_yyy);
	const __m128 z = coBitCast<__m128>(_zzz);
	return coBitCast<coFloatx3>(_mm_unpacklo_ps(_mm_unpacklo_ps(x, z), _mm_unpacklo_ps(y, y)));
}
coFORCE_INLINE float coMake_Float(const coFloatx3& _a) { return coMake_Float(coBitCast<coFloatx4>(_a)); }
coFORCE_INLINE coInt32 coMake_Int32(const coFloatx3& _a) { return coMake_Int32(coBitCast<coFloatx4>(_a)); }
coFORCE_INLINE coUint32 coMake_Uint32(const coFloatx3& _a) { return coMake_Uint32(coBitCast<coFloatx4>(_a)); }

const coFloatx3 coFloatx3_ONE = coMake_Floatx3(1.0f);
const coFloatx3 coFloatx3_ZERO = coMake_Floatx3(0.0f);
const coFloatx3 coFloatx3_DEGREES_TO_RADIANS = coMake_Floatx3(0.01745329252f);
const coFloatx3 coFloatx3_RADIANS_TO_DEGREES = coMake_Floatx3(57.2957795131f);

coFORCE_INLINE coFloatx3 coFloatx3_XMask() { return coBitCast<coFloatx3>(_mm_set_epi32(0, 0, 0, 0xffffffff)); }
coFORCE_INLINE coFloatx3 coFloatx3_YMask() { return coBitCast<coFloatx3>(_mm_set_epi32(0, 0, 0xffffffff, 0)); }
coFORCE_INLINE coFloatx3 coFloatx3_ZMask() { return coBitCast<coFloatx3>(_mm_set_epi32(0, 0xffffffff, 0, 0)); }

coFORCE_INLINE coBool32x3 operator== (const coFloatx3& _a, const coFloatx3& _b) { return coBitCast<coBool32x3>(_mm_cmpeq_ps(coBitCast<__m128>(_a), coBitCast<__m128>(_b))); }
//coFORCE_INLINE coBool32x3 operator!= (const coFloatx3& _a, const coFloatx3& _b) { return coBitCast<coBool32x3>(_mm_cmpneq_ps(coBitCast<__m128>(_a), coBitCast<__m128>(_b))); } Removed because cast to coBool is not intuitive.
coFORCE_INLINE coBool32x3 operator< (const coFloatx3& _a, const coFloatx3& _b) { return coBitCast<coBool32x3>(_mm_cmplt_ps(coBitCast<__m128>(_a), coBitCast<__m128>(_b))); }
coFORCE_INLINE coBool32x3 operator<= (const coFloatx3& _a, const coFloatx3& _b) { return coBitCast<coBool32x3>(_mm_cmple_ps(coBitCast<__m128>(_a), coBitCast<__m128>(_b))); }
coFORCE_INLINE coBool32x3 operator> (const coFloatx3& _a, const coFloatx3& _b) { return coBitCast<coBool32x3>(_mm_cmpgt_ps(coBitCast<__m128>(_a), coBitCast<__m128>(_b))); }
coFORCE_INLINE coBool32x3 operator>= (const coFloatx3& _a, const coFloatx3& _b) { return coBitCast<coBool32x3>(_mm_cmpge_ps(coBitCast<__m128>(_a), coBitCast<__m128>(_b))); }
coFORCE_INLINE coFloatx3 operator+ (const coFloatx3& _a, const coFloatx3& _b) { return coBitCast<coFloatx3>(_mm_add_ps(coBitCast<__m128>(_a), coBitCast<__m128>(_b))); }
coFORCE_INLINE coFloatx3& operator+= (coFloatx3& _this, const coFloatx3& _b) { return _this = coBitCast<coFloatx3>(_mm_add_ps(coBitCast<__m128>(_this), coBitCast<__m128>(_b))); }
coFORCE_INLINE coFloatx3 operator- (const coFloatx3& _a, const coFloatx3& _b) { return coBitCast<coFloatx3>(_mm_sub_ps(coBitCast<__m128>(_a), coBitCast<__m128>(_b))); }
coFORCE_INLINE coFloatx3 operator- (const coFloatx3& _a) { return coBitCast<coFloatx3>(_mm_sub_ps(_mm_setzero_ps(), coBitCast<__m128>(_a))); }
coFORCE_INLINE coFloatx3 operator+ (const coFloatx3& _a) { return _a; }
coFORCE_INLINE coFloatx3& operator-= (coFloatx3& _this, const coFloatx3& _b) { return _this = coBitCast<coFloatx3>(_mm_sub_ps(coBitCast<__m128>(_this), coBitCast<__m128>(_b))); }
coFORCE_INLINE coFloatx3 operator/ (const coFloatx3& _a, const coFloatx3& _b) { return coBitCast<coFloatx3>(_mm_div_ps(coBitCast<__m128>(_a), coBitCast<__m128>(_b))); }
coFORCE_INLINE coFloatx3& operator/= (coFloatx3& _this, const coFloatx3& _b) { return _this = coBitCast<coFloatx3>(_mm_div_ps(coBitCast<__m128>(_this), coBitCast<__m128>(_b))); }
coFORCE_INLINE coFloatx3 operator* (const coFloatx3& _a, const coFloatx3& _b) { return coBitCast<coFloatx3>(_mm_mul_ps(coBitCast<__m128>(_a), coBitCast<__m128>(_b))); }
coFORCE_INLINE coFloatx3& operator*= (coFloatx3& _this, const coFloatx3& _b) { return _this = coBitCast<coFloatx3>(_mm_mul_ps(coBitCast<__m128>(_this), coBitCast<__m128>(_b))); }
coFORCE_INLINE coFloatx3 operator& (const coFloatx3& _a, const coFloatx3& _b) { return coBitCast<coFloatx3>(_mm_and_ps(coBitCast<__m128>(_a), coBitCast<__m128>(_b))); }
coFORCE_INLINE coFloatx3 operator| (const coFloatx3& _a, const coFloatx3& _b) { return coBitCast<coFloatx3>(_mm_or_ps(coBitCast<__m128>(_a), coBitCast<__m128>(_b))); }
coFORCE_INLINE coFloatx3 coMulAdd(const coFloatx3& a, const coFloatx3& b, const coFloatx3& c) { return a * b + c; }
coFORCE_INLINE coBool32x3 coIsValid(const coFloatx3& _a) { return _a == _a; }
template <coInt8 X, coInt8 Y, coInt8 Z>
coFORCE_INLINE coFloatx3 coShuffle(const coFloatx3& _a, const coFloatx3& _b) { return coBitCast<coFloatx3>(coShuffle<X, Y, Z, 3>(coBitCast<coFloatx4>(_a), coBitCast<coFloatx4>(_b))); }
template <coInt8 X, coInt8 Y, coInt8 Z>
coFORCE_INLINE coFloatx3 coShuffle(const coFloatx3& _a) { return coBitCast<coFloatx3>(coShuffle<X, Y, Z, 3>(coBitCast<coFloatx4>(_a), coBitCast<coFloatx4>(_a))); }
coFORCE_INLINE coFloatx3 coBroadcastX(const coFloatx3& _a) { return coBitCast<coFloatx3>(coShuffle<0, 0, 0, 0>(coBitCast<coFloatx4>(_a))); }
coFORCE_INLINE coFloatx3 coBroadcastY(const coFloatx3& _a) { return coBitCast<coFloatx3>(coShuffle<1, 1, 1, 1>(coBitCast<coFloatx4>(_a))); }
coFORCE_INLINE coFloatx3 coBroadcastZ(const coFloatx3& _a) { return coBitCast<coFloatx3>(coShuffle<2, 2, 2, 2>(coBitCast<coFloatx4>(_a))); }
coFORCE_INLINE coFloatx3 coSelectXY(coFloatx3 a) { a.z = 0.0f; return a; }
coFORCE_INLINE coFloatx3 coAbs(const coFloatx3& _a) { return coBitCast<coFloatx3>(coAbs(coBitCast<coFloatx4>(_a))); }
coFORCE_INLINE coFloatx3 coSquareRoot(const coFloatx3& _a) { return coBitCast<coFloatx3>(coSquareRoot(coBitCast<coFloatx4>(_a))); }
coFORCE_INLINE coFloatx3 coInvert(const coFloatx3& _a) { return coBitCast<coFloatx3>(coInvert(coBitCast<coFloatx4>(_a))); }
coFORCE_INLINE coFloatx3 coInvertFast(const coFloatx3& _a) { return coBitCast<coFloatx3>(coInvertFast(coBitCast<coFloatx4>(_a))); }
coFORCE_INLINE coFloatx3 coInvSquareRoot(const coFloatx3& _a) { return coBitCast<coFloatx3>(coInvSquareRoot(coBitCast<coFloatx4>(_a))); }
coFORCE_INLINE coFloatx3 coInvSqrtFast(const coFloatx3& _a) { return coBitCast<coFloatx3>(coInvSqrtFast(coBitCast<coFloatx4>(_a))); }
coFORCE_INLINE coFloatx3 coPow2(const coFloatx3& _a) { return  _a * _a; }
coFORCE_INLINE coFloatx3 coPow4(const coFloatx3& _a) { return coPow2(_a * _a); }
coFORCE_INLINE coFloatx3 coDenullify(const coFloatx3& _a) { return _a + coMake_Floatx3(+1.0e-037f); }
coFORCE_INLINE coFloatx3 coMin(const coFloatx3& _a, const coFloatx3& _b) { return coBitCast<coFloatx3>(coMin(coBitCast<coFloatx4>(_a), coBitCast<coFloatx4>(_b))); }
coFORCE_INLINE coFloatx3 coMin(const coFloatx3& _a) { return coMin(coBroadcastX(_a), coMin(coBroadcastY(_a), coBroadcastZ(_a))); }
coFORCE_INLINE coFloatx3 coMax(const coFloatx3& _a, const coFloatx3& _b) { return coBitCast<coFloatx3>(coMax(coBitCast<coFloatx4>(_a), coBitCast<coFloatx4>(_b))); }
coFORCE_INLINE coFloatx3 coMax(const coFloatx3& _a) { return coMax(coBroadcastX(_a), coMax(coBroadcastY(_a), coBroadcastZ(_a))); }
coFORCE_INLINE coFloatx3 coMaxWith0(const coFloatx3& _a) { return coBitCast<coFloatx3>(coMaxWith0(coBitCast<coFloatx4>(_a))); }
coFORCE_INLINE coFloatx3 coClamp(const coFloatx3& _a, const coFloatx3& _min, const coFloatx3& _max) { return coMin(coMax(_a, _min), _max); }
coFORCE_INLINE coFloatx3 coClamp01(const coFloatx3& _a) { return coBitCast<coFloatx3>(coClamp01(coBitCast<coFloatx4>(_a))); }
coFORCE_INLINE coBool32x3 coNearEqual(const coFloatx3& _a, const coFloatx3& _b, const coFloatx3& _epsilon = coFloatx3(coFloat_NearEqualDefaultEpsilon)) { return coAbs(_b - _a) < _epsilon; }
coFORCE_INLINE coBool32x3 coNearEqual0(const coFloatx3& _a, const coFloatx3& _epsilon = coFloatx3(coFloat_NearEqualDefaultEpsilon)) { return coAbs(_a) < _epsilon; }
coFORCE_INLINE coBool32x3 coAreXYZEqual(const coFloatx3& _a) { const coFloatx3 x = coBroadcastX(_a); return x == coBroadcastY(_a) && x == coBroadcastZ(_a); }
coFORCE_INLINE coFloatx3 coSin(const coFloatx3& _a) { return coBitCast<coFloatx3>(coSin(coBitCast<coFloatx4>(_a))); }
coFORCE_INLINE coFloatx3 coCos(const coFloatx3& _a) { return coBitCast<coFloatx3>(coCos(coBitCast<coFloatx4>(_a))); }
coFORCE_INLINE coFloatx3 coMod(coFloatx3 _a, coFloatx3 _b) { return coFloatx3(coMod(_a.x, _b.x), coMod(_a.y, _b.y), coMod(_a.z, _b.z)); }
coFORCE_INLINE coFloatx3 coConvertToRad(coFloatx3 degrees) { return degrees * 0.01745329252f; }
coFORCE_INLINE coFloatx3 coConvertToDeg(coFloatx3 radians) { return radians * 57.2957795131f; }
coFORCE_INLINE coFloatx3 coRand01x3(coUint32& seed) { return coFloatx3(coRand01(seed), coRand01(seed), coRand01(seed)); }
coFORCE_INLINE coFloatx3 coRand11x3(coUint32& seed) { return coFloatx3(coRand11(seed), coRand11(seed), coRand11(seed)); }
coFORCE_INLINE coFloatx3 coRound(const coFloatx3& a) { return coBitCast<coFloatx3>(_mm_round_ps(coBitCast<__m128>(a), _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)); }
coFORCE_INLINE coFloatx3 coSelect(const coFloatx3& _a, const coFloatx3& _b, const coInt32x3& _mask)
{
	return coBitCast<coFloatx3>(coBitCast<coInt32x3>(_b) ^ _mask & (coBitCast<coInt32x3>(_a) ^ coBitCast<coInt32x3>(_b)));
}
coFORCE_INLINE coFloatx3 coSign(const coFloatx3& x) { return coSelect(1.0f, -1.0f, coBitCast<coInt32x3>(x >= 0.f)); }
coFORCE_INLINE coBinaryOutputStream& operator<<(coBinaryOutputStream& stream, const coFloatx3& a)
{
	stream.Write(&a, 12);
	return stream;
}
coFORCE_INLINE coBinaryInputStream& operator>>(coBinaryInputStream& stream, coFloatx3& a)
{
	stream.Read(&a, 12);
	return stream;
}
coFORCE_INLINE void coFloatx3::Write(coBinaryOutputStream& stream) const
{
	stream.Write(this, 12);
}
coFORCE_INLINE void coFloatx3::Read(coBinaryInputStream& stream)
{
	stream.Read(this, 12);
}


text:
#!/usr/bin/env python3
"""Fetch dashboards from provided urls into this chart."""
import json
import textwrap
from os import makedirs, path

import requests
import yaml
from yaml.representer import SafeRepresenter

# https://stackoverflow.com/a/20863889/961092
class LiteralStr(str):
    pass

def change_style(style, representer):
    def new_representer(dumper, data):
        scalar = representer(dumper, data)
        scalar.style = style
        return scalar

    return new_representer

# Source files list
charts = [
    {
        'source': 'https://raw.githubusercontent.com/coreos/kube-prometheus/master/manifests/grafana-dashboardDefinitions.yaml',
        'destination': '../templates/grafana/dashboards-1.14',
        'type': 'yaml',
        'min_kubernetes': '1.14.0-0'
    },
    {
        'source': 'https://raw.githubusercontent.com/etcd-io/etcd/master/Documentation/op-guide/grafana.json',
        'destination': '../templates/grafana/dashboards-1.14',
        'type': 'json',
        'min_kubernetes': '1.14.0-0'
    },
    {
        'source': 'https://raw.githubusercontent.com/coreos/kube-prometheus/release-0.1/manifests/grafana-dashboardDefinitions.yaml',
        'destination': '../templates/grafana/dashboards',
        'type': 'yaml',
        'min_kubernetes': '1.10.0-0',
        'max_kubernetes': '1.14.0-0'
    },
    {
        'source': 'https://raw.githubusercontent.com/etcd-io/etcd/master/Documentation/op-guide/grafana.json',
        'destination': '../templates/grafana/dashboards',
        'type': 'json',
        'min_kubernetes': '1.10.0-0',
        'max_kubernetes': '1.14.0-0'
    },
]

# Additional conditions map
condition_map = {
    'grafana-coredns-k8s': ' .Values.coreDns.enabled',
    'etcd': ' .Values.kubeEtcd.enabled',
    'apiserver': ' .Values.kubeApiServer.enabled',
    'controller-manager': ' .Values.kubeControllerManager.enabled',
    'kubelet': ' .Values.kubelet.enabled',
    'proxy': ' .Values.kubeProxy.enabled',
    'scheduler': ' .Values.kubeScheduler.enabled',
    'node-rsrc-use': ' .Values.nodeExporter.enabled',
    'node-cluster-rsrc-use': ' .Values.nodeExporter.enabled',
    'prometheus-remote-write': ' .Values.prometheus.prometheusSpec.remoteWriteDashboards'
}

# standard header
header = '''{{- /*
Generated from '%(name)s' from %(url)s
Do not change in-place! In order to change this file first read following link:
https://github.com/helm/charts/tree/master/stable/prometheus-operator/hack
*/ -}}
{{- $kubeTargetVersion := default .Capabilities.KubeVersion.GitVersion .Values.kubeTargetVersionOverride }}
{{- if and (semverCompare ">=%(min_kubernetes)s" $kubeTargetVersion) (semverCompare "<%(max_kubernetes)s" $kubeTargetVersion) .Values.grafana.enabled .Values.grafana.defaultDashboardsEnabled%(condition)s }}
apiVersion: v1
kind: ConfigMap
metadata:
  namespace: {{ template "prometheus-operator.namespace" . }}
  name: {{ printf "%%s-%%s" (include "prometheus-operator.fullname" $) "%(name)s" | trunc 63 | trimSuffix "-" }}
  annotations:
{{ toYaml .Values.grafana.sidecar.dashboards.annotations | indent 4 }}
  labels:
    {{- if $.Values.grafana.sidecar.dashboards.label }}
    {{ $.Values.grafana.sidecar.dashboards.label }}: "1"
    {{- end }}
    app: {{ template "prometheus-operator.name" $ }}-grafana
{{ include "prometheus-operator.labels" $ | indent 4 }}
data:
'''

def init_yaml_styles():
    represent_literal_str = change_style('|', SafeRepresenter.represent_str)
    yaml.add_representer(LiteralStr, represent_literal_str)

def escape(s):
    return s.replace("{{", "{{`{{").replace("}}", "}}`}}").replace("{{`{{", "{{`{{`}}").replace("}}`}}", "{{`}}`}}")

def yaml_str_repr(struct, indent=2):
    """represent yaml as a string"""
    text = yaml.dump(
        struct,
        width=1000,  # to disable line wrapping
        default_flow_style=False  # to disable multiple items on single line
    )
    text = escape(text)  # escape {{ and }} for helm
    text = textwrap.indent(text, ' ' * indent)
    return text

def write_group_to_file(resource_name, content, url, destination, min_kubernetes, max_kubernetes):
    # initialize header
    lines = header % {
        'name': resource_name,
        'url': url,
        'condition': condition_map.get(resource_name, ''),
        'min_kubernetes': min_kubernetes,
        'max_kubernetes': max_kubernetes
    }

    filename_struct = {resource_name + '.json': (LiteralStr(content))}
    # rules themselves
    lines += yaml_str_repr(filename_struct)

    # footer
    lines += '{{- end }}'

    filename = resource_name + '.yaml'
    new_filename = "%s/%s" % (destination, filename)

    # make sure directories to store the file exist
    makedirs(destination, exist_ok=True)

    # recreate the file
    with open(new_filename, 'w') as f:
        f.write(lines)

    print("Generated %s" % new_filename)

def main():
    init_yaml_styles()
    # read the rules, create a new template file per group
    for chart in charts:
        print("Generating rules from %s" % chart['source'])
        response = requests.get(chart['source'])
        if response.status_code != 200:
            print('Skipping the file, response code %s not equals 200' % response.status_code)
            continue
        raw_text = response.text

        if ('max_kubernetes' not in chart):
            chart['max_kubernetes']="9.9.9-9"

        if chart['type'] == 'yaml':
            yaml_text = yaml.full_load(raw_text)
            groups = yaml_text['items']
            for group in groups:
                for resource, content in group['data'].items():
                    write_group_to_file(resource.replace('.json', ''), content, chart['source'], chart['destination'], chart['min_kubernetes'], chart['max_kubernetes'])
        elif chart['type'] == 'json':
            json_text = json.loads(raw_text)
            # is it already a dashboard structure or is it nested (etcd case)?
            flat_structure = bool(json_text.get('annotations'))
            if flat_structure:
                resource = path.basename(chart['source']).replace('.json', '')
                write_group_to_file(resource, json.dumps(json_text, indent=4), chart['source'], chart['destination'], chart['min_kubernetes'], chart['max_kubernetes'])
            else:
                for resource, content in json_text.items():
                    write_group_to_file(resource.replace('.json', ''), json.dumps(content, indent=4), chart['source'], chart['destination'], chart['min_kubernetes'], chart['max_kubernetes'])
    print("Finished")

if __name__ == '__main__':
    main()