text:
"use strict";
var core_1 = require("@angular/core");
var ng2_auto_complete_component_1 = require("./ng2-auto-complete.component");
var forms_1 = require("@angular/forms");
/**
 * display auto-complete section with input and dropdown list when it is clicked
 */
var Ng2AutoCompleteDirective = (function () {
    function Ng2AutoCompleteDirective(resolver, renderer, viewContainerRef, parentForm) {
        var _this = this;
        this.resolver = resolver;
        this.renderer = renderer;
        this.viewContainerRef = viewContainerRef;
        this.parentForm = parentForm;
        this.loadingText = "Loading";
        this.ngModelChange = new core_1.EventEmitter();
        this.valueChanged = new core_1.EventEmitter();
        //show auto-complete list below the current element
        this.showAutoCompleteDropdown = function (event) {
            var factory = _this.resolver.resolveComponentFactory(ng2_auto_complete_component_1.Ng2AutoCompleteComponent);
            _this.componentRef = _this.viewContainerRef.createComponent(factory);
            var component = _this.componentRef.instance;
            component.showInputTag = false; //Do NOT display autocomplete input tag separately
            component.pathToData = _this.pathToData;
            component.minChars = _this.minChars;
            component.source = _this.source;
            component.placeholder = _this.autoCompletePlaceholder;
            component.acceptUserInput = _this.acceptUserInput;
            component.maxNumList = parseInt(_this.maxNumList, 10);
            component.loadingText = _this.loadingText;
            component.listFormatter = _this.listFormatter;
            component.blankOptionText = _this.blankOptionText;
            component.noMatchFoundText = _this.noMatchFoundText;
            component.valueSelected.subscribe(_this.selectNewValue);
            _this.acDropdownEl = _this.componentRef.location.nativeElement;
            _this.acDropdownEl.style.display = "none";
            // if this element is not an input tag, move dropdown after input tag
            // so that it displays correctly
            if (_this.el.tagName !== "INPUT" && _this.acDropdownEl) {
                _this.inputEl.parentElement.insertBefore(_this.acDropdownEl, _this.inputEl.nextSibling);
            }
            _this.revertValue = typeof _this.ngModel !== "undefined" ? _this.ngModel : _this.inputEl.value;
            setTimeout(function () {
                component.reloadList(_this.inputEl.value);
                _this.styleAutoCompleteDropdown();
                component.dropdownVisible = true;
            });
        };
        this.hideAutoCompleteDropdown = function (event) {
            if (_this.componentRef) {
                var currentItem = void 0;
                var hasRevertValue = (typeof _this.revertValue !== "undefined");
                if (_this.inputEl && hasRevertValue && _this.acceptUserInput === false) {
                    currentItem = _this.componentRef.instance.findItemFromSelectValue(_this.inputEl.value);
                }
                _this.componentRef.destroy();
                _this.componentRef = undefined;
                if (_this.inputEl &&
                    hasRevertValue &&
                    _this.acceptUserInput === false &&
                    currentItem === null) {
                    _this.selectNewValue(_this.revertValue);
                }
            }
        };
        this.styleAutoCompleteDropdown = function () {
            if (_this.componentRef) {
                var component = _this.componentRef.instance;
                /* setting width/height auto complete */
                var thisElBCR = _this.el.getBoundingClientRect();
                var thisInputElBCR = _this.inputEl.getBoundingClientRect();
                var closeToBottom = thisInputElBCR.bottom + 100 > window.innerHeight;
                _this.acDropdownEl.style.width = thisInputElBCR.width + "px";
                _this.acDropdownEl.style.position = "absolute";
                _this.acDropdownEl.style.zIndex = "1";
                _this.acDropdownEl.style.left = "0";
                _this.acDropdownEl.style.display = "inline-block";
                if (closeToBottom) {
                    _this.acDropdownEl.style.bottom = thisInputElBCR.height + "px";
                }
                else {
                    _this.acDropdownEl.style.top = thisInputElBCR.height + "px";
                }
            }
        };
        this.selectNewValue = function (item) {
            // make displayable value
            if (item && typeof item === "object") {
                item = _this.addToStringFunction(item);
            }
            _this.inputEl && (_this.inputEl.value = '' + item);
            // make return value
            var val = item;
            if (_this.selectValueOf && item[_this.selectValueOf]) {
                val = item[_this.selectValueOf];
            }
            if ((_this.parentForm && _this.formControlName) || _this.extFormControl) {
                if (!!val) {
                    _this.formControl.patchValue(val);
                }
            }
            (val !== _this.ngModel) && _this.ngModelChange.emit(val);
            _this.valueChanged.emit(val);
            _this.hideAutoCompleteDropdown();
        };
        this.keydownEventHandler = function (evt) {
            if (_this.componentRef) {
                var component = _this.componentRef.instance;
                component.inputElKeyHandler(evt);
            }
        };
        this.inputEventHandler = function (evt) {
            if (_this.componentRef) {
                var component = _this.componentRef.instance;
                component.dropdownVisible = true;
                component.reloadListInDelay(evt);
            }
            else {
                _this.showAutoCompleteDropdown();
            }
        };
        this.el = this.viewContainerRef.element.nativeElement;
    }
    Ng2AutoCompleteDirective.prototype.ngOnInit = function () {
        // wrap this element with <div class="ng2-auto-complete">
        this.wrapperEl = document.createElement("div");
        this.wrapperEl.className = "ng2-auto-complete-wrapper";
        this.wrapperEl.style.position = "relative";
        this.el.parentElement.insertBefore(this.wrapperEl, this.el.nextSibling);
        this.wrapperEl.appendChild(this.el);
        //Check if we were supplied with a [formControlName] and it is inside a [form]
        //else check if we are supplied with a [FormControl] regardless if it is inside a [form] tag
        if (this.parentForm && this.formControlName) {
            if (this.parentForm['form']) {
                this.formControl = this.parentForm['form'].get(this.formControlName);
            }
            else if (this.parentForm instanceof forms_1.FormGroupName) {
                this.formControl = this.parentForm.control.controls[this.formControlName];
            }
        }
        else if (this.extFormControl) {
            this.formControl = this.extFormControl;
        }
        // apply toString() method for the object
        if (!!this.ngModel) {
            this.selectNewValue(this.ngModel);
        }
        else if (!!this.formControl && this.formControl.value) {
            this.selectNewValue(this.formControl.value[this.displayPropertyName]);
        }
    };
    Ng2AutoCompleteDirective.prototype.ngAfterViewInit = function () {
        var _this = this;
        // if this element is not an input tag, move dropdown after input tag
        // so that it displays correctly
        this.inputEl = this.el.tagName === "INPUT" ?
            this.el : this.el.querySelector("input");
        this.inputEl.addEventListener('focus', function (e) { return _this.showAutoCompleteDropdown(e); });
        this.inputEl.addEventListener('blur', function (e) { return _this.hideAutoCompleteDropdown(e); });
        this.inputEl.addEventListener('keydown', function (e) { return _this.keydownEventHandler(e); });
        this.inputEl.addEventListener('input', function (e) { return _this.inputEventHandler(e); });
    };
    Ng2AutoCompleteDirective.prototype.ngOnDestroy = function () {
        if (this.componentRef) {
            this.componentRef.instance.valueSelected.unsubscribe();
        }
    };
    Ng2AutoCompleteDirective.prototype.ngOnChanges = function (changes) {
        if (changes['ngModel']) {
            this.ngModel = this.addToStringFunction(changes['ngModel'].currentValue);
        }
    };
    Ng2AutoCompleteDirective.prototype.addToStringFunction = function (val) {
        if (val && typeof val === "object") {
            var displayVal_1;
            if (this.displayPropertyName) {
                displayVal_1 = val[this.displayPropertyName];
            }
            else if (this.listFormatter) {
                displayVal_1 = val[this.listFormatter];
            }
            else {
                displayVal_1 = val.value;
            }
            val.toString = function () {
                return displayVal_1;
            };
        }
        return val;
    };
    Ng2AutoCompleteDirective.decorators = [
        { type: core_1.Directive, args: [{
                    selector: "[auto-complete], [ng2-auto-complete]"
                },] },
    ];
    /** @nocollapse */
    Ng2AutoCompleteDirective.ctorParameters = [
        { type: core_1.ComponentFactoryResolver, },
        { type: core_1.Renderer, },
        { type: core_1.ViewContainerRef, },
        { type: forms_1.ControlContainer, decorators: [{ type: core_1.Optional }, { type: core_1.Host }, { type: core_1.SkipSelf },] },
    ];
    Ng2AutoCompleteDirective.propDecorators = {
        'autoCompletePlaceholder': [{ type: core_1.Input, args: ["auto-complete-placeholder",] },],
        'source': [{ type: core_1.Input, args: ["source",] },],
        'pathToData': [{ type: core_1.Input, args: ["path-to-data",] },],
        'minChars': [{ type: core_1.Input, args: ["min-chars",] },],
        'displayPropertyName': [{ type: core_1.Input, args: ["display-property-name",] },],
        'acceptUserInput': [{ type: core_1.Input, args: ["accept-user-input",] },],
        'maxNumList': [{ type: core_1.Input, args: ["max-num-list",] },],
        'selectValueOf': [{ type: core_1.Input, args: ["select-value-of",] },],
        'listFormatter': [{ type: core_1.Input, args: ["list-formatter",] },],
        'loadingText': [{ type: core_1.Input, args: ["loading-text",] },],
        'blankOptionText': [{ type: core_1.Input, args: ["blank-option-text",] },],
        'noMatchFoundText': [{ type: core_1.Input, args: ["no-match-found-text",] },],
        'ngModel': [{ type: core_1.Input },],
        'formControlName': [{ type: core_1.Input, args: ['formControlName',] },],
        'extFormControl': [{ type: core_1.Input, args: ['formControl',] },],
        'ngModelChange': [{ type: core_1.Output },],
        'valueChanged': [{ type: core_1.Output },],
    };
    return Ng2AutoCompleteDirective;
}());
exports.Ng2AutoCompleteDirective = Ng2AutoCompleteDirective;
//# sourceMappingURL=ng2-auto-complete.directive.js.map


text:
<!DOCTYPE html>
getLocale() }}">

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>CMS - @yield('title', 'Dashboard')</title>

    @stack('javascript-head')

            @yield('breadcrumbs')

            @include('cms::layout.partials.flash-messages')

            @section('errors')
                @include('cms::layout.errors')
            @show

            @yield('content')

@stack('javascript-end')

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) 2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <chainparams.h>
#include <consensus/merkle.h>
#include <consensus/validation.h>
#include <core_io.h>
#include <core_memusage.h>
#include <pubkey.h>
#include <primitives/block.h>
#include <streams.h>
#include <test/fuzz/fuzz.h>
#include <validation.h>
#include <version.h>

#include <cassert>
#include <string>

void initialize()
{
    const static auto verify_handle = MakeUnique<ECCVerifyHandle>();
    SelectParams(CBaseChainParams::REGTEST);
}

void test_one_input(const std::vector<uint8_t>& buffer)
{
    CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION);
    CBlock block;
    try {
        int nVersion;
        ds >> nVersion;
        ds.SetVersion(nVersion);
        ds >> block;
    } catch (const std::ios_base::failure&) {
        return;
    }
    const Consensus::Params& consensus_params = Params().GetConsensus();
    BlockValidationState validation_state_pow_and_merkle;
    const bool valid_incl_pow_and_merkle = CheckBlock(block, validation_state_pow_and_merkle, consensus_params, /* fCheckPOW= */ true, /* fCheckMerkleRoot= */ true);
    BlockValidationState validation_state_pow;
    const bool valid_incl_pow = CheckBlock(block, validation_state_pow, consensus_params, /* fCheckPOW= */ true, /* fCheckMerkleRoot= */ false);
    BlockValidationState validation_state_merkle;
    const bool valid_incl_merkle = CheckBlock(block, validation_state_merkle, consensus_params, /* fCheckPOW= */ false, /* fCheckMerkleRoot= */ true);
    BlockValidationState validation_state_none;
    const bool valid_incl_none = CheckBlock(block, validation_state_none, consensus_params, /* fCheckPOW= */ false, /* fCheckMerkleRoot= */ false);
    if (valid_incl_pow_and_merkle) {
        assert(valid_incl_pow && valid_incl_merkle && valid_incl_none);
    } else if (valid_incl_merkle || valid_incl_pow) {
        assert(valid_incl_none);
    }
    (void)block.GetHash();
    (void)block.ToString();
    (void)BlockMerkleRoot(block);
    if (!block.vtx.empty()) {
        // TODO: Avoid array index out of bounds error in BlockWitnessMerkleRoot
        //       when block.vtx.empty().
        (void)BlockWitnessMerkleRoot(block);
    }
    (void)GetBlockWeight(block);
    (void)GetWitnessCommitmentIndex(block);
    (void)RecursiveDynamicUsage(block);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<cronentries>
    <cron>
        <url>/refresh</url>
        <description>Repopulate activation time</description>
        <schedule>every 5 minutes</schedule>
    </cron>
    <cron>
        <url>/activation</url>
        <description>Activate all days, every 15 minutes</description>
        <schedule>every 15 minutes</schedule>
        <timezone>Europe/Paris</timezone>
    </cron>
</cronentries>


text:
<?php

class App_Controller extends Controller
{
    public $layout;
    public $content;

    public function invoke_action($action, $params)
    {
        try {
            parent::invoke_action($action, $params);
        } catch (ExpectedException $e) {
            throw new ProgrammerException('An ExpectedException failed to be'
                . ' caught in application code', $e);
        } catch (UserException $e) {
            $this->error($e->getMessage());
            return;
        }
    }

    public function before()
    {
        parent::before();

        $this->layout = new View('/layouts/default.php');
        $this->layout->title = Roy::config('app.longname');
        $this->layout->stylesheets = array();
        $this->layout->scripts = array();

        // Use /[controller]/[action] as the default content view
        $route = $this->request->route();
        $default_view = Path::concat('/', $route->controller(),
            $route->action());

        $this->content = new View($default_view);
        $this->content->set_layout($this->layout);
    }

    public function after()
    {
        parent::after();
    }
}


text:
from __future__ import unicode_literals

import swapper

from accelerator_abstract.models.base_file_page import BaseFilePage

class FilePage(BaseFilePage):
    class Meta(BaseFilePage.Meta):
        swappable = swapper.swappable_setting(
            BaseFilePage.Meta.app_label, "FilePage")


text:
"""@@@

  Program:        FileTools.py

  Classes:        FileTools

  Functions:      getHeadExt

  Author:         Wayne Dawson
  Version:        0.0
  Creation Date:  140221 (derived from SimRNATools c 140515)
  Last Update:    200210 (upgrade to python3)

I eventually found that Python has a lot of useful file manipulation
tools already available, so this is only a marginally useful set of
tools. The main tools that I still use from this module are

getHeadExt()

and

check_ext(testfile, [ext1, ext2, ...], program_name):

"""

import re
import sys

debug = False # True #

def getHeadExt(testfile):
    debug_getHeadExt = False
    """@

    output: file_header + _extension

    Obviously, this assumes that you don't think multiple dots in your
    private extension definition are ok. If this is not your way of
    thinking, then this will only read the stuff following the last
    dot.

       >>> flnm = "test.txt"
       >>> flhd, ext = getHeadExt(flnm)
       >>> print (flhd, ext)
       test txt

    """
    if debug_getHeadExt:
        print ("getHeadExt: ", testfile)
    #

    splf = testfile.split('.')
    ext = ''
    flhd = testfile
    if len(splf) > 1:
        ext = splf[len(splf)-1]
        flhd = testfile[:len(testfile)-len(ext)-1]
    #

    return flhd, ext
#

#############################
###   class Definitions   ###
#############################

class FileTools:
    def __init__(self):
        self.flnm = ''
        self.flhd = ''
        self.ext  = ''
    #

    def check_ext(self, testfile, allowed_exts, program=''):
        """@

        Checks the input file <testfile> extension <allowed_exts>.  The
        variable <allowed_exts> can either be a single string (e.g.,
        'trafl') or a list of strings (e.g., ['trafl', 'dGrnk']). This
        version of check_ext() should be the one that is used from now
        on, though the old_check_ext() works basically the same.

        Example code:

        vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
        >>> flnm = "file.trafl"
        >>> ft = FileTools()
        >>> file_passed = ft.check_ext(flnm, ['trafl', 'dGrnk'], "myprogram")
        True
        >>> flnm = "file.txt"
        >>> file_passed = ft.check_ext(flnm, ['trafl', 'dGrnk'], "myprogram")
        [program: myprogram]:
        ERROR: file must have one of these extensions '*.trafl' or '*.dGrnk'.
               input file 'file.txt' --> extension: 'txt')
        >>> if not file_passed:
        >>>     print ("ERROR: terminated"); sys.exit(1)
        >>> #
        $

        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

        output: True/False # True when extension matches expected input file type

        """

        #
        self.flnm = testfile
        splf = testfile.split('.')
        self.ext = splf[len(splf)-1]
        if len(self.ext) == 1:
            print ("ERROR: file (%s) should have one of the following extensions: " \
                % (self.flnm), allowed_exts)
            sys.exit(1)
        #

        self.flhd = testfile[:len(testfile)-len(self.ext)-1]

        flag_pass = False
        if type(allowed_exts) is list:
            # print ('more than one extension found')
            for ext in allowed_exts:
                if ext == self.ext:
                    flag_pass = True
                    break
                #

            #|endfor

        else:
            if allowed_exts == self.ext:
                flag_pass = True
            #

        #

        if not flag_pass:
            xtnsn = ''
            print ("[program: %s]:" % program)
            if type(allowed_exts) is list: # need to know if it is a list or a string
                xtnsn = '\'*.%s\'' % allowed_exts[0]
                for i in range(1,len(allowed_exts)):
                    xtnsn += ' or \'*.%s\'' % allowed_exts[i]
                #
                xtnsn += '.'
                if len(allowed_exts) == 1:
                    print ("ERROR: file must have the extension %s" % xtnsn)
                else:
                    print ("ERROR: file must have one of these extensions %s" % xtnsn)
                #

                print ("       input file '%s' --> (extension: '%s')" \
                    % (self.flnm, self.ext))

            else:
                xtnsn = '\'*.%s\'' % allowed_exts
                print ("ERROR: file must have the extension %s" % xtnsn)
                print ("       input file '%s' --> (extension: '%s')" \
                    % (self.flnm, self.ext))
            #

        #

        return flag_pass
    #

    # ##########################################################
    # ######  Obsolete code that I cannot seem to delete  ######
    # ##########################################################
    # vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv

    def clean_split(self, st):
        """@

        161118wkd: This was evidently an early tool I wrote and I
        don't think this one is so useful now. In fact, if you only
        need to divide out the data items from an initially
        indeterminate number of spaces (' ') in a string (st), then it
        is better to use

           >>> st.split()

        Indeed, it is better to write

           >>> st.strip().split()

        This operation removes all ' ' characters and the '\n'
        character as well.  So st.strip().split() is a better strategy
        and then, if you want to extract some other things out of it,
        then do the same procedure -- i.e., strip() -- on each item in
        the resulting list.

        """

        ssv = st.split(' ')
        vlist = []
        # remove blank spaces
        for ssv_k in ssv:
            if not ssv_k == '':
                vlist += [ssv_k]
            #

        #|endfor

        return vlist
    #

    def hollerith(self, n, slen):
        """@

        generates a hollerith

        161118wkd: This does work, and I have used it a lot in the
        past. However, I found this task can also be done using the
        package "string". For example, to produce a hollerith string
        with up to 5 zeros and a positive integer k, you can generate
        this same output with the following command

           >>> k = 25
           >>> string.zfill(k, 5)
           00025

        """

        sn = str(n)
        hn = ''
        for i in range(0,slen-len(sn)):
            hn += '0'
        #

        hn += sn
        return hn
    #

    def old_check_ext(self, testfile, allowed_exts):
        """@

        This program is now obsolete!

        Checks the input file <testfile> extension <extset>.  The
        variable <extset> can either be a single string (e.g.,
        'trafl') or a list of strings (e.g., ['trafl', 'dGrnk']). The
        difference between the old version (here) and the new version
        (above) is simply that I shifted from analyzing with a regular
        expression to just comparing the arguments in the list. It
        seems that the new way works, but I left this old approach
        here anyway. It is slightly more cumbersome. It is basically
        obsolete, and I no longer use it and so I don't tend to update
        it.

        """

        self.flnm = testfile
        ss = testfile.split('.')
        self.ext = ss[len(ss)-1]

        if len(self.ext) == 1:
            print ("ERROR: file (%s) requires an extension: " % (self.flnm), allowed_exts)
            sys.exit(1)
        #

        self.flhd = testfile[:len(testfile)-len(self.ext)-1]

        flag_pass = False
        if type(allowed_exts) is list:
            # (print 'more than one extension found')
            for ext in allowed_exts:
                testext='.' + ext + '$'
                p = re.compile(testext)
                a = p.findall(testfile)
                if (len(a) > 0):
                    flag_pass = True
                #

            #|endfor

        else:
            # (print 'only one extension found')
            testext='.' + allowed_exts + '$'
            p = re.compile(testext)
            a = p.findall(testfile)
            if (len(a) > 0):
                flag_pass = True
            #

        #

        if not flag_pass:
            xtnsn = ''
            if type(allowed_exts) is list:
                xtnsn = '\'*.%s\'' % allowed_exts[0]
                for i in range(1,len(allowed_exts)):
                    xtnsn += ' or \'*.%s\'' % allowed_exts[i]
                #

                xtnsn += '.'

                if len(allowed_exts) == 1:
                    print ("ERROR: file must have the extension %s" % xtnsn)
                else:
                    print ("ERROR: file must have one of these extensions %s" % xtnsn)
                #

            else:
                xtnsn = '\'*.%s\'' % allowed_exts
                print ("ERROR: file must have the extension %s" % xtnsn)
            #

        #

        return flag_pass
    #

    # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    # ##########################################################
    # ######  Obsolete code that I cannot seem to delete  ######
    # ##########################################################
#


text:
package dumbcaslib

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"sort"
)

// CasTable describes the interface to a content-addressed-storage.
type CasTable interface {
	Table
	// AddEntry adds a node to the table.
	AddEntry(source io.Reader, name string) error
	// SetFsckBit sets the bit that the table needs to be checked for consistency.
	SetFsckBit()
	// GetFsckBit returns if the fsck bit is set.
	GetFsckBit() bool
	// ClearFsckBit clears the fsck bit.
	ClearFsckBit()
}

// EnumerateCasAsList returns a sorted list of all the entries in a CasTable.
// It is meant to be used in test.
func EnumerateCasAsList(cas CasTable) ([]string, error) {
	items := []string{}
	for v := range cas.Enumerate() {
		if v.Error != nil {
			return nil, v.Error
		}
		items = append(items, v.Item)
	}
	sort.Strings(items)
	return items, nil
}

// MakeMemoryCasTable returns a CasTable implementation that keeps all the data
// in memory. Is it useful for testing.
func MakeMemoryCasTable() CasTable {
	return &memoryCasTable{make(map[string][]byte), false}
}

type memoryCasTable struct {
	entries  map[string][]byte
	needFsck bool
}

func (m *memoryCasTable) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	_, _ = w.Write(m.entries[r.URL.Path[1:]])
}

func (m *memoryCasTable) Enumerate() <-chan EnumerationEntry {
	// First make a copy of the keys.
	keys := make([]string, len(m.entries))
	i := 0
	for k := range m.entries {
		keys[i] = k
		i++
	}
	c := make(chan EnumerationEntry)
	go func() {
		for _, k := range keys {
			c <- EnumerationEntry{Item: k}
		}
		close(c)
	}()
	return c
}

func (m *memoryCasTable) AddEntry(source io.Reader, item string) error {
	if _, ok := m.entries[item]; ok {
		return os.ErrExist
	}
	data, err := ioutil.ReadAll(source)
	if err == nil {
		m.entries[item] = data
	}
	return err
}

func (m *memoryCasTable) Open(item string) (ReadSeekCloser, error) {
	data, ok := m.entries[item]
	if !ok {
		return nil, fmt.Errorf("Missing: %s", item)
	}
	return closableBuffer{bytes.NewReader(data)}, nil
}

func (m *memoryCasTable) Remove(item string) error {
	if _, ok := m.entries[item]; !ok {
		return os.ErrNotExist
	}
	delete(m.entries, item)
	return nil
}

func (m *memoryCasTable) SetFsckBit() {
	m.needFsck = true
}

func (m *memoryCasTable) GetFsckBit() bool {
	return m.needFsck
}

func (m *memoryCasTable) ClearFsckBit() {
	m.needFsck = false
}

func (m *memoryCasTable) Corrupt() {
	m.entries[Sha1Bytes([]byte{0, 1})] = []byte("content5")
}


text: fiddle faddle


text:
import * as should from "should";
import * as fs from "fs";
import * as path from "path";

import { TempPath } from "../../src/helpers/temp-path";

describe('TempPath', function() {
    describe('deleteAsync', function() {
        it('executes callback', async function() {
            // Arrange
            let callbackExecuted = false;
            const tempPath = new TempPath('file.md', () => callbackExecuted = true)

            // Act
            await tempPath.deleteAsync();

            // Assert
            should(callbackExecuted).be.true();
        });

        it('does not execute callback if nothing defined', async function() {
            // Arrange
            const tempPath = new TempPath('file.md');

            // Act
            await tempPath.deleteAsync();
        });
    });
});


text:
//
//  LeavesViewController.m
//  CoreAnimation
//
//  Created by Shui on 2017/9/9.
//
//

#import "LeavesViewController.h"

@interface LeavesViewController ()

@property (nonatomic, strong) UILabel * label1;
@property (nonatomic, strong) UILabel * label2;

@end

@implementation LeavesViewController

+ (NSString *)displayName {
    return @"Leaves flipper";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.label1 = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 50)];
    _label1.text = @"Shuizhu";
    [self.view addSubview:self.label1];

    self.label2 = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 50)];
    _label2.text = @"Mardegebi";
    [self.view addSubview:self.label2];

    self.view.backgroundColor = [UIColor whiteColor];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    _label1.transform = CGAffineTransformMakeScale(1, 0);
    _label1.alpha = 0;
    _label2.alpha = 1;
    [UIView animateWithDuration: 2. animations: ^ {
        _label1.transform = CGAffineTransformMakeScale(1, 1);
        _label2.transform = CGAffineTransformMakeScale(1, 0.1);
        _label1.alpha = 1;
        _label2.alpha = 0;
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
package com.example.zhongjw.coolweather.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;

import com.example.zhongjw.coolweather.db.CoolWeatherDB;
import com.example.zhongjw.coolweather.model.City;
import com.example.zhongjw.coolweather.model.County;
import com.example.zhongjw.coolweather.model.Province;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Created by zhongjw on 2016/1/29.
 */
public class Utility {
    public synchronized static boolean handlerProvincesResponse(CoolWeatherDB coolWeatherDB, String response) {
        if (!TextUtils.isEmpty(response)) {
            String[] allProvinces = response.split(",");
            if (allProvinces != null && allProvinces.length > 0) {
                for (String p : allProvinces) {
                    String[] array = p.split("\\|");
                    Province province = new Province();
                    province.setProvinceCode(array[0]);
                    province.setProvinceName(array[1]);
                    coolWeatherDB.savedProvince(province);
                }
                return true;
            }
        }
        return false;
    }
    public static boolean handlerCitiesResponse(CoolWeatherDB coolWeatherDB,String response,int provinceId){
        if(!TextUtils.isEmpty(response)){
            String [] allCities = response.split(",");
            if(allCities!=null&&allCities.length>0){
                for (String c:allCities){
                    String [] array = c.split("\\|");
                    City city = new City();
                    city.setCityCode(array[0]);
                    city.setCityName(array[1]);
                    city.setProvinceId(provinceId);
                    coolWeatherDB.savedCity(city);
                }
                return true;
            }
        }
        return false;
    }
    public static boolean handlerCountiesResponse(CoolWeatherDB coolWeatherDB,String response,int CityId){
        if(!TextUtils.isEmpty(response)){
            String [] allCounties = response.split(",");
            if(allCounties!=null&&allCounties.length>0){
                for (String c:allCounties){
                    String [] array = c.split("\\|");
                    County county = new County();
                    county.setCountyCode(array[0]);
                    county.setCountyName(array[1]);
                    county.setCityId(CityId);
                    coolWeatherDB.savedCounty(county);
                }
                return  true;
            }
        }
        return false;
    }

    //deal with json数据,并解析出的数据存储到本地
    public static void handleWeatherResponse(Context context,String response){
        try{
            JSONObject jsonObject = new JSONObject(response);
            JSONObject weatherinfo = jsonObject.getJSONObject("weatherinfo");
            String cityName = weatherinfo.getString("city");
            String weatherCode = weatherinfo.getString("cityid");
            String temp1 = weatherinfo.getString("temp1");
            String temp2 = weatherinfo.getString("temp2");
            String weatherDesp = weatherinfo.getString("weather");
            String publishTime = weatherinfo.getString("ptime");
            saveWeatherInfo(context ,cityName,weatherCode,temp1,temp2,weatherDesp,publishTime);
        }catch (JSONException e){
            e.printStackTrace();
        }
    }

    public static void saveWeatherInfo(Context  context,String cityName,String weatherCode,
                                       String temp1,String temp2,String weatherDesp,String publishTime){
        SimpleDateFormat sdf = new SimpleDateFormat("yyy年M月d日", Locale.CHINA);
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
        editor.putBoolean("city_selected", true);
        editor.putString("city_name", cityName);
        editor.putString("weather_code", weatherCode);
        editor.putString("temp1", temp1);
        editor.putString("temp2", temp2);
        editor.putString("weather_desp", weatherDesp);
        editor.putString("publish_time", publishTime);
        Date date = new Date();
        editor.putString("current_date",sdf.format(date));
        editor.commit();
    }
}


text:
/*
 * This file was generated - do not edit it directly !!
 * Generated by AuDAO tool, a product of Spolecne s.r.o.
 * For more information please visit http://www.spoledge.com
 */
package database.dao.mysql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;

import com.spoledge.audao.db.dao.AbstractDaoImpl;
import com.spoledge.audao.db.dao.DBException;
import com.spoledge.audao.db.dao.DaoException;

import database.dao.RettighederDao;
import database.dto.Rettigheder;

/**
 * This is the DAO imlementation class.
 *
 * @author generated
 */
public class RettighederDaoImpl extends AbstractDaoImpl<Rettigheder> implements RettighederDao {

    private static final String TABLE_NAME = "rettigheder";

    protected static final String SELECT_COLUMNS = "rettigheds_id, bruger_id, rettighed";

    protected static final String PK_CONDITION = "rettigheds_id=?";

    private static final String SQL_INSERT = "INSERT INTO rettigheder (bruger_id,rettighed) VALUES (?,?)";
    private static final Rettigheder.Rettighed[] _Rettigheder_Rettigheds = { null, Rettigheder.Rettighed.ADMIN, Rettigheder.Rettighed.BOOKING, Rettigheder.Rettighed.ASSESSOR, Rettigheder.Rettighed.REQUEST };

    public RettighederDaoImpl( Connection conn ) {
        super( conn );
    }

    /**
     * Finds a record identified by its primary key.
     * @return the record found or null
     */
    public Rettigheder findByPrimaryKey( int rettighedsId ) {
        return findOne( PK_CONDITION, rettighedsId);
    }

    /**
     * Finds records.
     */
    public Rettigheder[] findDynamic( String cond, int offset, int count, Object... params ) {
        return findManyArray( cond, offset, count, params);
    }

    /**
     * Inserts a new record.
     * @return the generated primary key - rettighedsId
     */
    public int insert( Rettigheder dto ) throws DaoException {
        PreparedStatement stmt = null;
        ResultSet rs = null;

        debugSql( SQL_INSERT, dto );

        try {
            stmt = conn.prepareStatement( SQL_INSERT, PreparedStatement.RETURN_GENERATED_KEYS );

            if ( dto.getBrugerId() == null ) {
                throw new DaoException("Value of column 'bruger_id' cannot be null");
            }
            stmt.setInt( 1, dto.getBrugerId() );

            if ( dto.getRettighed() == null ) {
                stmt.setNull( 2, Types.SMALLINT );
            }
            else {
                stmt.setShort( 2, (short) (dto.getRettighed().ordinal() + 1) );
            }

            int n = stmt.executeUpdate();

            rs = stmt.getGeneratedKeys();
            rs.next();

            dto.setRettighedsId( rs.getInt( 1 ));

            return dto.getRettighedsId();
        }
        catch (SQLException e) {
            errorSql( e, SQL_INSERT, dto );
            handleException( e );
            throw new DBException( e );
        }
        finally {
            if (rs != null) try { rs.close(); } catch (SQLException e) {}
            if (stmt != null) try { stmt.close(); } catch (SQLException e) {}
        }
    }

    /**
     * Updates one record found by primary key.
     * @return true iff the record was really updated (=found and any change was really saved)
     */
    public boolean update( int rettighedsId, Rettigheder dto ) throws DaoException {
        StringBuffer sb = new StringBuffer();
        ArrayList<Object> params = new ArrayList<Object>();

        if ( dto.isRettighedModified()) {
            if ( dto.getRettighed() == null ) {
                sb.append( "rettighed=NULL" );
            }
            else {
                sb.append( "rettighed=?" );
                params.add( dto.getRettighed().ordinal() + 1);
            }
        }

        if (sb.length() == 0) {
            return false;
        }

        params.add( rettighedsId );

        Object[] oparams = new Object[ params.size() ];

        return updateOne( sb.toString(), PK_CONDITION, params.toArray( oparams ));
    }

    /**
     * Returns the table name.
     */
    public String getTableName() {
        return TABLE_NAME;
    }

    protected String getSelectColumns() {
        return SELECT_COLUMNS;
    }

    protected Rettigheder fetch( ResultSet rs ) throws SQLException {
        Rettigheder dto = new Rettigheder();
        dto.setRettighedsId( rs.getInt( 1 ));
        dto.setBrugerId( rs.getInt( 2 ));
        dto.setRettighed( _Rettigheder_Rettigheds[ rs.getShort( 3 ) ]);

        if ( rs.wasNull()) {
            dto.setRettighed( null );
        }

        return dto;
    }

    protected Rettigheder[] toArray(ArrayList<Rettigheder> list ) {
        Rettigheder[] ret = new Rettigheder[ list.size() ];
        return list.toArray( ret );
    }

}


text:
package solr.posters;

import solr.util.ConsoleLogger;
import solr.walker.Walker;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Posts to Solr recursively through directories
 * @author greensxayu
 */
public class DirectoryPoster implements Poster {

	private Poster poster;

	public DirectoryPoster(Poster poster) {
	    this.poster = poster;
    }

	public void postFiles(String pathStr) {
		Path path = Paths.get(pathStr);
		try {
			Files.walkFileTree(path, new Walker(poster));
		} catch (IOException e) {
			ConsoleLogger.fatal("Read/Write error while traversing file system", e);
		}

	}
}


text:
using atom::ContentSettingsManager;
using blink::WebContentSettingCallbacks;
using blink::WebDocument;
using blink::WebFrame;
using blink::WebSecurityOrigin;
using blink::WebString;
using blink::WebURL;
using blink::WebView;
using content::DocumentState;
using content::NavigationState;

ContentSettingsObserver::ContentSettingsObserver(
    content::RenderFrame* render_frame,
    extensions::Dispatcher* extension_dispatcher,
    bool should_whitelist,
    service_manager::BinderRegistry* registry)
    : content::RenderFrameObserver(render_frame),
      content::RenderFrameObserverTracker<ContentSettingsObserver>(
          render_frame),
#if BUILDFLAG(ENABLE_EXTENSIONS)
      extension_dispatcher_(extension_dispatcher),
#endif
      content_settings_manager_(NULL),
      allow_running_insecure_content_(false),
      is_interstitial_page_(false),
      current_request_id_(0),
      should_whitelist_(should_whitelist) {
  ClearBlockedContentSettings();
  render_frame->GetWebFrame()->SetContentSettingsClient(this);

  content::RenderFrame* main_frame =
      render_frame->GetRenderView()->GetMainRenderFrame();
  // TODO(nasko): The main frame is not guaranteed to be in the same process
  // with this frame with --site-per-process. This code needs to be updated
  // to handle this case. See https://crbug.com/496670.
  if (main_frame && main_frame != render_frame) {
    // Copy all the settings from the main render frame to avoid race conditions
    // when initializing this data. See https://crbug.com/333308.
    ContentSettingsObserver* parent = ContentSettingsObserver::Get(main_frame);
    allow_running_insecure_content_ = parent->allow_running_insecure_content_;
    temporarily_allowed_plugins_ = parent->temporarily_allowed_plugins_;
    is_interstitial_page_ = parent->is_interstitial_page_;
  }
}

ContentSettingsObserver::~ContentSettingsObserver() {
}

void ContentSettingsObserver::SetContentSettingRules(
    const RendererContentSettingRules* content_setting_rules) {
  content_setting_rules_ = content_setting_rules;
}

void ContentSettingsObserver::SetContentSettingsManager(
    atom::ContentSettingsManager* content_settings_manager) {
  content_settings_manager_ = content_settings_manager;
}

bool ContentSettingsObserver::IsPluginTemporarilyAllowed(
    const std::string& identifier) {
  // If the empty string is in here, it means all plugins are allowed.
  // TODO(bauerb): Remove this once we only pass in explicit identifiers.
  return (temporarily_allowed_plugins_.find(identifier) !=
          temporarily_allowed_plugins_.end()) ||
         (temporarily_allowed_plugins_.find(std::string()) !=
          temporarily_allowed_plugins_.end());
}

void ContentSettingsObserver::DidBlockContentType(
    ContentSettingsType settings_type, const base::string16& details) {
  std::string settings_type_string = "unknown";
  switch (settings_type) {
    case CONTENT_SETTINGS_TYPE_COOKIES:
      settings_type_string = "cookies";
      break;
    case CONTENT_SETTINGS_TYPE_IMAGES:
      settings_type_string = "images";
      break;
    case CONTENT_SETTINGS_TYPE_JAVASCRIPT:
      settings_type_string = "javascript";
      break;
    case CONTENT_SETTINGS_TYPE_PLUGINS:
      settings_type_string = "plugins";
      break;
    case CONTENT_SETTINGS_TYPE_POPUPS:
      settings_type_string = "popups";
      break;
    case CONTENT_SETTINGS_TYPE_GEOLOCATION:
      settings_type_string = "geo";
      break;
    case CONTENT_SETTINGS_TYPE_NOTIFICATIONS:
      settings_type_string = "notifications";
      break;
    case CONTENT_SETTINGS_TYPE_AUTO_SELECT_CERTIFICATE:
      settings_type_string = "auto_select_certificate";
      break;
    case CONTENT_SETTINGS_TYPE_MIXEDSCRIPT:
      settings_type_string = "runInsecureContent";
      break;
    case CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC:
      settings_type_string = "mediastream_mic";
      break;
    case CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA:
      settings_type_string = "mediastream_camera";
      break;
    case CONTENT_SETTINGS_TYPE_PROTOCOL_HANDLERS:
      settings_type_string = "protocol_handlers";
      break;
    case CONTENT_SETTINGS_TYPE_PPAPI_BROKER:
      settings_type_string = "ppapi_broker";
      break;
    case CONTENT_SETTINGS_TYPE_AUTOMATIC_DOWNLOADS:
      settings_type_string = "automatic_downloads";
      break;
    case CONTENT_SETTINGS_TYPE_MIDI_SYSEX:
      settings_type_string = "midi_sysex";
      break;
    case CONTENT_SETTINGS_TYPE_SSL_CERT_DECISIONS:
      settings_type_string = "ssl_cert_decisions";
      break;
    case CONTENT_SETTINGS_TYPE_PROTECTED_MEDIA_IDENTIFIER:
      settings_type_string = "protected_media_identifiers";
      break;
    case CONTENT_SETTINGS_TYPE_SITE_ENGAGEMENT:
      settings_type_string = "site_engagement";
      break;
    case CONTENT_SETTINGS_TYPE_DURABLE_STORAGE:
      settings_type_string = "durable_storage";
      break;
    case CONTENT_SETTINGS_TYPE_USB_CHOOSER_DATA:
      settings_type_string = "usb_chooser_data";
      break;
    case CONTENT_SETTINGS_TYPE_BLUETOOTH_GUARD:
      settings_type_string = "bluetooth_guard";
      break;
    case CONTENT_SETTINGS_TYPE_BACKGROUND_SYNC:
      settings_type_string = "background_sync";
      break;
    case CONTENT_SETTINGS_TYPE_AUTOPLAY:
      settings_type_string = "autoplay";
      break;
    // do nothing
    case CONTENT_SETTINGS_TYPE_DEFAULT:
      FALLTHROUGH;
    case CONTENT_SETTINGS_TYPE_APP_BANNER:
      FALLTHROUGH;
    case CONTENT_SETTINGS_TYPE_IMPORTANT_SITE_INFO:
      FALLTHROUGH;
    case CONTENT_SETTINGS_TYPE_PERMISSION_AUTOBLOCKER_DATA:
      FALLTHROUGH;
    case CONTENT_SETTINGS_TYPE_ADS:
      FALLTHROUGH;
    case CONTENT_SETTINGS_TYPE_ADS_DATA:
      FALLTHROUGH;
    case CONTENT_SETTINGS_TYPE_MIDI:
      FALLTHROUGH;
    case CONTENT_SETTINGS_TYPE_PASSWORD_PROTECTION:
      FALLTHROUGH;
    case CONTENT_SETTINGS_TYPE_MEDIA_ENGAGEMENT:
      FALLTHROUGH;
    case CONTENT_SETTINGS_TYPE_SOUND:
      FALLTHROUGH;
    case CONTENT_SETTINGS_TYPE_CLIENT_HINTS:
      FALLTHROUGH;
    case CONTENT_SETTINGS_TYPE_SENSORS:
      FALLTHROUGH;
    case CONTENT_SETTINGS_TYPE_ACCESSIBILITY_EVENTS:
      FALLTHROUGH;
    case CONTENT_SETTINGS_TYPE_CLIPBOARD_READ:
      FALLTHROUGH;
    case CONTENT_SETTINGS_TYPE_CLIPBOARD_WRITE:
      FALLTHROUGH;
    case CONTENT_SETTINGS_TYPE_PLUGINS_DATA:
      FALLTHROUGH;
    case CONTENT_SETTINGS_TYPE_PAYMENT_HANDLER:
      FALLTHROUGH;
    case CONTENT_SETTINGS_TYPE_USB_GUARD:
      FALLTHROUGH;
    case CONTENT_SETTINGS_NUM_TYPES:
      break;
  }
  DidBlockContentType(settings_type_string, base::UTF16ToUTF8(details));
}

void ContentSettingsObserver::DidBlockContentType(
    ContentSettingsType settings_type) {
  DidBlockContentType(settings_type, base::string16());
}

void ContentSettingsObserver::DidBlockContentType(
    const std::string& settings_type) {
  DidBlockContentType(settings_type,
      blink::WebStringToGURL(render_frame()->GetWebFrame()->
          GetSecurityOrigin().ToString()).spec());
}

void ContentSettingsObserver::DidBlockContentType(
    const std::string& settings_type,
    const std::string& details) {
  base::ListValue args;
  args.AppendString(settings_type);
  args.AppendString(details);

  auto rf = render_frame();
  rf->Send(new AtomViewHostMsg_Message(
    rf->GetRoutingID(), base::UTF8ToUTF16("content-blocked"), args));
}

bool ContentSettingsObserver::OnMessageReceived(const IPC::Message& message) {
  // Don't swallow LoadBlockedPlugins messages, as they're sent to every
  // blocked plugin.
  IPC_BEGIN_MESSAGE_MAP(ContentSettingsObserver, message)
    IPC_MESSAGE_HANDLER(ChromeViewMsg_LoadBlockedPlugins, OnLoadBlockedPlugins)
  IPC_END_MESSAGE_MAP()

  return false;
}

void ContentSettingsObserver::DidCommitProvisionalLoad(
    bool is_new_navigation,
    bool is_same_page_navigation) {
  WebFrame* frame = render_frame()->GetWebFrame();
  if (frame->Parent())
    return;  // Not a top-level navigation.

  if (!is_same_page_navigation) {
    ClearBlockedContentSettings();
    temporarily_allowed_plugins_.clear();
  }
}

void ContentSettingsObserver::OnDestruct() {
  delete this;
}

bool ContentSettingsObserver::AllowDatabase(const WebString& name,
                                          const WebString& display_name,
                                          unsigned estimated_size) {  // NOLINT
  WebFrame* frame = render_frame()->GetWebFrame();
  if (frame->GetSecurityOrigin().IsUnique() ||
      frame->Top()->GetSecurityOrigin().IsUnique())
    return false;

  bool allow = true;
  GURL secondary_url(
      blink::WebStringToGURL(frame->GetSecurityOrigin().ToString()));
  if (content_settings_manager_->content_settings()) {
    allow =
        content_settings_manager_->GetSetting(
          ContentSettingsManager::GetOriginOrURL(frame),
          secondary_url,
          "cookies",
          allow) != CONTENT_SETTING_BLOCK;
  }

  if (!allow)
    DidBlockContentType("database", secondary_url.spec());
  return allow;
}

void ContentSettingsObserver::RequestFileSystemAccessAsync(
        const WebContentSettingCallbacks& callbacks) {
  WebFrame* frame = render_frame()->GetWebFrame();
  WebContentSettingCallbacks permissionCallbacks(callbacks);
  if (frame->GetSecurityOrigin().IsUnique() ||
      frame->Top()->GetSecurityOrigin().IsUnique()) {
      permissionCallbacks.DoDeny();
      return;
  }

  bool allow = true;
  GURL secondary_url(
      blink::WebStringToGURL(frame->GetSecurityOrigin().ToString()));
  if (content_settings_manager_->content_settings()) {
    allow =
        content_settings_manager_->GetSetting(
          ContentSettingsManager::GetOriginOrURL(frame),
          secondary_url,
          "cookies",
          allow) != CONTENT_SETTING_BLOCK;
  }
  if (!allow) {
      DidBlockContentType("filesystem", secondary_url.spec());
      permissionCallbacks.DoDeny();
  } else {
      permissionCallbacks.DoAllow();
  }
}

bool ContentSettingsObserver::AllowImage(bool enabled_per_settings,
                                         const WebURL& image_url) {
  if (enabled_per_settings && IsWhitelistedForContentSettings())
    return true;

  bool allow = enabled_per_settings;
  GURL secondary_url(image_url);
  if (content_settings_manager_->content_settings()) {
    allow =
        content_settings_manager_->GetSetting(
            ContentSettingsManager::GetOriginOrURL(
                render_frame()->GetWebFrame()),
            secondary_url,
            "images",
            allow) != CONTENT_SETTING_BLOCK;
  }

  if (!allow)
    DidBlockContentType("images", secondary_url.spec());
  return allow;
}

bool ContentSettingsObserver::AllowIndexedDB(const WebString& name,
                                             const WebSecurityOrigin& origin) {
  WebFrame* frame = render_frame()->GetWebFrame();
  if (frame->GetSecurityOrigin().IsUnique() ||
      frame->Top()->GetSecurityOrigin().IsUnique())
    return false;

  bool allow = true;
  GURL secondary_url(
      blink::WebStringToGURL(frame->GetSecurityOrigin().ToString()));
  if (content_settings_manager_->content_settings()) {
    allow =
        content_settings_manager_->GetSetting(
            ContentSettingsManager::GetOriginOrURL(frame),
            secondary_url,
            "cookies",
            allow) != CONTENT_SETTING_BLOCK;
  }

  if (!allow)
    DidBlockContentType("indexedDB", secondary_url.spec());
  return allow;
}

GURL GetOriginOrURL(const WebFrame* frame) {
  url::Origin top_origin = url::Origin(frame->Top()->GetSecurityOrigin());
  // The |top_origin| is unique ("null") e.g., for file:// URLs. Use the
  // document URL as the primary URL in those cases.
  // TODO(alexmos): This is broken for --site-per-process, since top() can be a
  // WebRemoteFrame which does not have a document(), and the WebRemoteFrame's
  // URL is not replicated.  See https://crbug.com/628759.
  if (top_origin.unique() && frame->Top()->IsWebLocalFrame())
    return frame->Top()->ToWebLocalFrame()->GetDocument().Url();
  return top_origin.GetURL();
}

// Allow passing both WebURL and GURL here, so that we can early return without
// allocating a new backing string if only the default rule matches.
template <typename URL>
ContentSetting GetContentSettingFromRules(
    const ContentSettingsForOneType& rules,
    const WebFrame* frame,
    const URL& secondary_url) {
  // If there is only one rule, it's the default rule and we don't need to match
  // the patterns.
  if (rules.size() == 1) {
    DCHECK(rules[0].primary_pattern == ContentSettingsPattern::Wildcard());
    DCHECK(rules[0].secondary_pattern == ContentSettingsPattern::Wildcard());
    return rules[0].GetContentSetting();
  }
  const GURL& primary_url = GetOriginOrURL(frame);
  const GURL& secondary_gurl = secondary_url;
  for (const auto& rule : rules) {
    if (rule.primary_pattern.Matches(primary_url) &&
        rule.secondary_pattern.Matches(secondary_gurl)) {
      return rule.GetContentSetting();
    }
  }
  NOTREACHED();
  return CONTENT_SETTING_DEFAULT;
}

bool IsScriptDisabledForPreview(const content::RenderFrame* render_frame) {
  return render_frame->GetPreviewsState() & content::NOSCRIPT_ON;
}

bool ContentSettingsObserver::AllowScript(bool enabled_per_settings) {
  if (!enabled_per_settings)
    return false;
  if (IsScriptDisabledForPreview(render_frame()))
    return false;
  if (is_interstitial_page_)
    return true;

  blink::WebLocalFrame* frame = render_frame()->GetWebFrame();
  const auto it = cached_script_permissions_.find(frame);
  if (it != cached_script_permissions_.end())
    return it->second;

  // Evaluate the content setting rules before
  // IsWhitelistedForContentSettings(); if there is only the default rule
  // allowing all scripts, it's quicker this way.
  bool allow = true;
  if (content_setting_rules_) {
    ContentSetting setting = GetContentSettingFromRules(
        content_setting_rules_->script_rules, frame,
        url::Origin(frame->GetDocument().GetSecurityOrigin()).GetURL());
    allow = setting != CONTENT_SETTING_BLOCK;
  }
  allow = allow || IsWhitelistedForContentSettings();

  cached_script_permissions_[frame] = allow;
  return allow;
}

bool ContentSettingsObserver::AllowScriptFromSource(
    bool enabled_per_settings,
    const blink::WebURL& script_url) {
  if (IsWhitelistedForContentSettings())
    return true;

  bool allow = enabled_per_settings;
  GURL secondary_url(script_url);
  if (content_settings_manager_->content_settings()) {
    allow =
        content_settings_manager_->GetSetting(
          ContentSettingsManager::GetOriginOrURL(render_frame()->GetWebFrame()),
          secondary_url,
          "javascript",
          allow) != CONTENT_SETTING_BLOCK;
  }

  allow = allow || IsWhitelistedForContentSettings();
  if (!allow)
    DidBlockContentType("javascript", secondary_url.spec());
  return allow;
}

bool ContentSettingsObserver::AllowStorage(bool local) {
  if (IsWhitelistedForContentSettings())
    return true;

  WebFrame* frame = render_frame()->GetWebFrame();
  if (frame->GetSecurityOrigin().IsUnique() ||
      frame->Top()->GetSecurityOrigin().IsUnique())
    return false;

  StoragePermissionsKey key(
      blink::WebStringToGURL(frame->ToWebLocalFrame()->GetDocument().GetSecurityOrigin().ToString()),
      local);
  std::map<StoragePermissionsKey, bool>::const_iterator permissions =
      cached_storage_permissions_.find(key);
  if (permissions != cached_storage_permissions_.end())
    return permissions->second;

  bool allow = true;
  if (content_settings_manager_->content_settings()) {
    allow =
        content_settings_manager_->GetSetting(
          ContentSettingsManager::GetOriginOrURL(frame),
          blink::WebStringToGURL(frame->GetSecurityOrigin().ToString()),
          "cookies",
          allow) != CONTENT_SETTING_BLOCK;
  }

  cached_storage_permissions_[key] = allow;
  if (!allow)
    DidBlockContentType("storage");
  return allow;
}

bool ContentSettingsObserver::AllowReadFromClipboard(bool default_value) {
  bool allowed = default_value;
#if BUILDFLAG(ENABLE_EXTENSIONS)
  extensions::ScriptContext* current_context =
      extension_dispatcher_->script_context_set().GetCurrent();
  if (current_context) {
    allowed |= current_context->HasAPIPermission(
        extensions::APIPermission::kClipboardRead);
  }
#endif
  return allowed;
}

bool ContentSettingsObserver::AllowWriteToClipboard(bool default_value) {
  bool allowed = default_value;
#if BUILDFLAG(ENABLE_EXTENSIONS)
  // All blessed extension pages could historically write to the clipboard, so
  // preserve that for compatibility.
  extensions::ScriptContext* current_context =
      extension_dispatcher_->script_context_set().GetCurrent();
  if (current_context) {
    if (current_context->effective_context_type() ==
        extensions::Feature::BLESSED_EXTENSION_CONTEXT) {
      allowed = true;
    } else {
      allowed |= current_context->HasAPIPermission(
          extensions::APIPermission::kClipboardWrite);
    }
  }
#endif
  return allowed;
}

bool ContentSettingsObserver::AllowMutationEvents(bool default_value) {
  if (IsWhitelistedForContentSettings())
    return true;

  bool allow = default_value;
  if (content_settings_manager_->content_settings()) {
    allow =
        content_settings_manager_->GetSetting(
            ContentSettingsManager::GetOriginOrURL(
                render_frame()->GetWebFrame()),
            GURL(),
            "mutation",
            allow) != CONTENT_SETTING_BLOCK;
  }

  if (!allow)
    DidBlockContentType("mutation");
  return allow;
}

bool ContentSettingsObserver::AllowRunningInsecureContent(
    bool allowed_per_settings,
    const blink::WebSecurityOrigin& origin,
    const blink::WebURL& resource_url) {
  // TODO(bridiver) is origin different than web frame top origin?
  bool allow = allowed_per_settings;
  GURL secondary_url(resource_url);
  if (content_settings_manager_->content_settings()) {
    allow =
        content_settings_manager_->GetSetting(
            ContentSettingsManager::GetOriginOrURL(
                render_frame()->GetWebFrame()),
            secondary_url,
            "runInsecureContent",
            allow) != CONTENT_SETTING_BLOCK;
  }

  if (allow)
    DidRunInsecureContent(GURL(resource_url));
  else
    DidBlockRunInsecureContent(GURL(resource_url));
  return allow;
}

bool ContentSettingsObserver::AllowAutoplay(bool default_value) {
  bool allow = default_value;
  if (content_settings_manager_->content_settings()) {
    WebFrame* frame = render_frame()->GetWebFrame();
    auto origin = frame->ToWebLocalFrame()->GetDocument().GetSecurityOrigin();
    allow =
        content_settings_manager_->GetSetting(
            ContentSettingsManager::GetOriginOrURL(frame),
            blink::WebStringToGURL(origin.ToString()),
            "autoplay",
            allow) != CONTENT_SETTING_BLOCK;
  }

  if (!allow)
    DidBlockContentType(CONTENT_SETTINGS_TYPE_AUTOPLAY);
  return allow;
}

void ContentSettingsObserver::DidNotAllowPlugins() {
  DidBlockContentType(CONTENT_SETTINGS_TYPE_PLUGINS);
}

void ContentSettingsObserver::DidNotAllowScript() {
  DidBlockContentType(CONTENT_SETTINGS_TYPE_JAVASCRIPT);
}

void ContentSettingsObserver::OnLoadBlockedPlugins(
    const std::string& identifier) {
  temporarily_allowed_plugins_.insert(identifier);
}

void ContentSettingsObserver::DidRunInsecureContent(GURL resouce_url) {
  base::ListValue args;
    args.AppendString(resouce_url.spec());

    auto rf = render_frame();
    rf->Send(new AtomViewHostMsg_Message(rf->GetRoutingID(),
        base::UTF8ToUTF16("did-run-insecure-content"), args));
}

void ContentSettingsObserver::DidBlockRunInsecureContent(GURL resouce_url) {
  base::ListValue args;
    args.AppendString(resouce_url.spec());

    auto rf = render_frame();
    rf->Send(new AtomViewHostMsg_Message(rf->GetRoutingID(),
        base::UTF8ToUTF16("did-block-run-insecure-content"), args));
}

void ContentSettingsObserver::ClearBlockedContentSettings() {
  cached_storage_permissions_.clear();
  cached_script_permissions_.clear();
}

bool ContentSettingsObserver::IsWhitelistedForContentSettings() const {
  // Whitelist ftp directory listings, as they require JavaScript to function
  // properly.
  if (!render_frame()) {
    return false;
  }

  if (render_frame()->IsFTPDirectoryListing())
    return true;

  WebFrame* web_frame = render_frame()->GetWebFrame();

  if (!web_frame) {
    return false;
  }

  return IsWhitelistedForContentSettings(
      web_frame->ToWebLocalFrame()->GetDocument().GetSecurityOrigin(),
      web_frame->ToWebLocalFrame()->GetDocument().Url());
}

bool ContentSettingsObserver::IsWhitelistedForContentSettings(
    const WebSecurityOrigin& origin,
    const GURL& document_url) {
  if (document_url == GURL(content::kUnreachableWebDataURL))
    return true;

  if (origin.IsUnique())
    return false;  // Uninitialized document?

  base::string16 protocol = origin.Protocol().Utf16();
  if (base::EqualsASCII(protocol, content::kChromeUIScheme))
    return true;  // Browser UI elements should still work.

  if (base::EqualsASCII(protocol, content::kChromeDevToolsScheme))
    return true;  // DevTools UI elements should still work.

#if BUILDFLAG(ENABLE_EXTENSIONS)
  if (base::EqualsASCII(protocol, extensions::kExtensionScheme))
    return true;
#endif

  // If the scheme is file:, an empty file name indicates a directory listing,
  // which requires JavaScript to function properly.
  if (base::EqualsASCII(protocol, url::kFileScheme)) {
    return document_url.SchemeIs(url::kFileScheme) &&
           document_url.ExtractFileName().empty();
  }

  return false;
}


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

package org.chromium.android_webview.test;

import android.content.Context;
import android.content.Intent;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.lifecycle.Stage;
import android.util.AndroidRuntimeException;
import android.util.Base64;
import android.view.ViewGroup;

import org.junit.Assert;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

import org.chromium.android_webview.AwBrowserContext;
import org.chromium.android_webview.AwBrowserProcess;
import org.chromium.android_webview.AwContents;
import org.chromium.android_webview.AwContents.DependencyFactory;
import org.chromium.android_webview.AwContents.InternalAccessDelegate;
import org.chromium.android_webview.AwContents.NativeDrawFunctorFactory;
import org.chromium.android_webview.AwContentsClient;
import org.chromium.android_webview.AwSettings;
import org.chromium.android_webview.test.util.GraphicsTestUtils;
import org.chromium.android_webview.test.util.JSUtils;
import org.chromium.base.Log;
import org.chromium.base.test.BaseActivityTestRule;
import org.chromium.base.test.util.ApplicationTestUtils;
import org.chromium.base.test.util.CallbackHelper;
import org.chromium.base.test.util.CriteriaHelper;
import org.chromium.base.test.util.InMemorySharedPreferences;
import org.chromium.base.test.util.ScalableTimeout;
import org.chromium.content_public.browser.LoadUrlParams;
import org.chromium.content_public.browser.test.util.TestCallbackHelperContainer.OnPageFinishedHelper;
import org.chromium.content_public.browser.test.util.TestThreadUtils;
import org.chromium.net.test.util.TestWebServer;

import java.lang.annotation.Annotation;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/** Custom ActivityTestRunner for WebView instrumentation tests */
public class AwActivityTestRule extends BaseActivityTestRule<AwTestRunnerActivity> {
    public static final long WAIT_TIMEOUT_MS = 15000L;

    // Only use scaled timeout if you are certain it's not being called further up the call stack.
    public static final long SCALED_WAIT_TIMEOUT_MS = ScalableTimeout.scaleTimeout(15000L);

    public static final int CHECK_INTERVAL = 100;

    private static final String TAG = "AwActivityTestRule";

    private static final Pattern MAYBE_QUOTED_STRING = Pattern.compile("^(\"?)(.*)\\1$");

    private static boolean sBrowserProcessStarted;

    /**
     * An interface to call onCreateWindow(AwContents).
     */
    public interface OnCreateWindowHandler {
        /** This will be called when a new window pops up from the current webview. */
        public boolean onCreateWindow(AwContents awContents);
    }

    private Description mCurrentTestDescription;

    // The browser context needs to be a process-wide singleton.
    private AwBrowserContext mBrowserContext;

    private List<WeakReference<AwContents>> mAwContentsDestroyedInTearDown = new ArrayList<>();

    public AwActivityTestRule() {
        super(AwTestRunnerActivity.class);
    }

    @Override
    public Statement apply(final Statement base, Description description) {
        mCurrentTestDescription = description;
        return super.apply(new Statement() {
            @Override
            public void evaluate() throws Throwable {
                setUp();
                base.evaluate();
                tearDown();
            }
        }, description);
    }

    public void setUp() {
        if (needsAwBrowserContextCreated()) {
            createAwBrowserContext();
        }
        if (needsBrowserProcessStarted()) {
            startBrowserProcess();
        } else {
            assert !sBrowserProcessStarted
                : "needsBrowserProcessStarted false and @Batch are incompatible";
        }
    }

    public void tearDown() {
        if (!needsAwContentsCleanup()) return;

        TestThreadUtils.runOnUiThreadBlocking(() -> {
            for (WeakReference<AwContents> awContentsRef : mAwContentsDestroyedInTearDown) {
                AwContents awContents = awContentsRef.get();
                if (awContents == null) continue;
                awContents.destroy();
            }
        });
        // Flush the UI queue since destroy posts again to UI thread.
        TestThreadUtils.runOnUiThreadBlocking(() -> { mAwContentsDestroyedInTearDown.clear(); });
    }

    public boolean needsHideActionBar() {
        return false;
    }

    private Intent getLaunchIntent() {
        if (needsHideActionBar()) {
            Intent intent = getActivityIntent();
            intent.putExtra(AwTestRunnerActivity.FLAG_HIDE_ACTION_BAR, true);
            return intent;
        }
        return null;
    }

    @Override
    public void launchActivity(Intent intent) {
        if (getActivity() != null) return;
        super.launchActivity(intent);
        ApplicationTestUtils.waitForActivityState(getActivity(), Stage.RESUMED);
    }

    public AwTestRunnerActivity launchActivity() {
        launchActivity(getLaunchIntent());
        return getActivity();
    }

    public AwBrowserContext createAwBrowserContextOnUiThread(InMemorySharedPreferences prefs) {
        // Native pointer is initialized later in startBrowserProcess if needed.
        return new AwBrowserContext(prefs, 0, true);
    }

    public TestDependencyFactory createTestDependencyFactory() {
        return new TestDependencyFactory();
    }

    /**
     * Override this to return false if the test doesn't want to create an
     * AwBrowserContext automatically.
     */
    public boolean needsAwBrowserContextCreated() {
        return true;
    }

    /**
     * Override this to return false if the test doesn't want the browser
     * startup sequence to be run automatically.
     *
     * @return Whether the instrumentation test requires the browser process to
     *         already be started.
     */
    public boolean needsBrowserProcessStarted() {
        return true;
    }

    /**
     * Override this to return false if test doesn't need all AwContents to be
     * destroyed explicitly after the test.
     */
    public boolean needsAwContentsCleanup() {
        return true;
    }

    public void createAwBrowserContext() {
        if (mBrowserContext != null) {
            throw new AndroidRuntimeException("There should only be one browser context.");
        }
        launchActivity(); // The Activity must be launched in order to load native code
        final InMemorySharedPreferences prefs = new InMemorySharedPreferences();
        TestThreadUtils.runOnUiThreadBlockingNoException(
                () -> mBrowserContext = createAwBrowserContextOnUiThread(prefs));
    }

    public void startBrowserProcess() {
        doStartBrowserProcess(false);
    }

    public void startBrowserProcessWithVulkan() {
        doStartBrowserProcess(true);
    }

    private void doStartBrowserProcess(boolean useVulkan) {
        // The Activity must be launched in order for proper webview statics to be setup.
        launchActivity();
        if (!sBrowserProcessStarted) {
            sBrowserProcessStarted = true;
            TestThreadUtils.runOnUiThreadBlocking(() -> {
                AwTestContainerView.installDrawFnFunctionTable(useVulkan);
                AwBrowserProcess.start();
            });
        }
        if (mBrowserContext != null) {
            TestThreadUtils.runOnUiThreadBlocking(
                    () -> mBrowserContext.setNativePointer(
                            AwBrowserContext.getDefault().getNativePointer()));
        }
    }

    public void runOnUiThread(Runnable r) {
        TestThreadUtils.runOnUiThreadBlocking(r);
    }

    public static void enableJavaScriptOnUiThread(final AwContents awContents) {
        TestThreadUtils.runOnUiThreadBlocking(
                () -> awContents.getSettings().setJavaScriptEnabled(true));
    }

    public static boolean getJavaScriptEnabledOnUiThread(final AwContents awContents)
            throws ExecutionException {
        return TestThreadUtils.runOnUiThreadBlocking(
                () -> awContents.getSettings().getJavaScriptEnabled());
    }

    public static void setNetworkAvailableOnUiThread(
            final AwContents awContents, final boolean networkUp) {
        TestThreadUtils.runOnUiThreadBlocking(() -> awContents.setNetworkAvailable(networkUp));
    }

    /**
     * Loads url on the UI thread and blocks until onPageFinished is called.
     */
    public void loadUrlSync(final AwContents awContents, CallbackHelper onPageFinishedHelper,
            final String url) throws Exception {
        loadUrlSync(awContents, onPageFinishedHelper, url, null);
    }

    public void loadUrlSync(final AwContents awContents, CallbackHelper onPageFinishedHelper,
            final String url, final Map<String, String> extraHeaders) throws Exception {
        int currentCallCount = onPageFinishedHelper.getCallCount();
        loadUrlAsync(awContents, url, extraHeaders);
        onPageFinishedHelper.waitForCallback(
                currentCallCount, 1, WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    }

    public void loadUrlSyncAndExpectError(final AwContents awContents,
            CallbackHelper onPageFinishedHelper, CallbackHelper onReceivedError2Helper,
            final String url) throws Exception {
        int onReceivedError2Count = onReceivedError2Helper.getCallCount();
        int onFinishedCallCount = onPageFinishedHelper.getCallCount();
        loadUrlAsync(awContents, url);
        onReceivedError2Helper.waitForCallback(
                onReceivedError2Count, 1, WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
        onPageFinishedHelper.waitForCallback(
                onFinishedCallCount, 1, WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    }

    /**
     * Loads url on the UI thread but does not block.
     */
    public void loadUrlAsync(final AwContents awContents, final String url) {
        loadUrlAsync(awContents, url, null);
    }

    public void loadUrlAsync(
            final AwContents awContents, final String url, final Map<String, String> extraHeaders) {
        TestThreadUtils.runOnUiThreadBlocking(() -> awContents.loadUrl(url, extraHeaders));
    }

    /**
     * Posts url on the UI thread and blocks until onPageFinished is called.
     */
    public void postUrlSync(final AwContents awContents, CallbackHelper onPageFinishedHelper,
            final String url, byte[] postData) throws Exception {
        int currentCallCount = onPageFinishedHelper.getCallCount();
        postUrlAsync(awContents, url, postData);
        onPageFinishedHelper.waitForCallback(
                currentCallCount, 1, WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    }

    /**
     * Loads url on the UI thread but does not block.
     */
    public void postUrlAsync(final AwContents awContents, final String url, byte[] postData) {
        class PostUrl implements Runnable {
            byte[] mPostData;
            public PostUrl(byte[] postData) {
                mPostData = postData;
            }
            @Override
            public void run() {
                awContents.postUrl(url, mPostData);
            }
        }
        TestThreadUtils.runOnUiThreadBlocking(new PostUrl(postData));
    }

    /**
     * Loads data on the UI thread and blocks until onPageFinished is called.
     */
    public void loadDataSync(final AwContents awContents, CallbackHelper onPageFinishedHelper,
            final String data, final String mimeType, final boolean isBase64Encoded)
            throws Exception {
        int currentCallCount = onPageFinishedHelper.getCallCount();
        loadDataAsync(awContents, data, mimeType, isBase64Encoded);
        onPageFinishedHelper.waitForCallback(
                currentCallCount, 1, WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    }

    public void loadHtmlSync(final AwContents awContents, CallbackHelper onPageFinishedHelper,
            final String html) throws Throwable {
        int currentCallCount = onPageFinishedHelper.getCallCount();
        final String encodedData = Base64.encodeToString(html.getBytes(), Base64.NO_PADDING);
        loadDataSync(awContents, onPageFinishedHelper, encodedData, "text/html", true);
    }

    public void loadDataSyncWithCharset(final AwContents awContents,
            CallbackHelper onPageFinishedHelper, final String data, final String mimeType,
            final boolean isBase64Encoded, final String charset) throws Exception {
        int currentCallCount = onPageFinishedHelper.getCallCount();
        TestThreadUtils.runOnUiThreadBlocking(
                () -> awContents.loadUrl(LoadUrlParams.createLoadDataParams(
                                data, mimeType, isBase64Encoded, charset)));
        onPageFinishedHelper.waitForCallback(
                currentCallCount, 1, WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    }

    /**
     * Loads data on the UI thread but does not block.
     */
    public void loadDataAsync(final AwContents awContents, final String data, final String mimeType,
            final boolean isBase64Encoded) {
        TestThreadUtils.runOnUiThreadBlocking(
                () -> awContents.loadData(data, mimeType, isBase64Encoded ? "base64" : null));
    }

    public void loadDataWithBaseUrlSync(final AwContents awContents,
            CallbackHelper onPageFinishedHelper, final String data, final String mimeType,
            final boolean isBase64Encoded, final String baseUrl, final String historyUrl)
            throws Throwable {
        int currentCallCount = onPageFinishedHelper.getCallCount();
        loadDataWithBaseUrlAsync(awContents, data, mimeType, isBase64Encoded, baseUrl, historyUrl);
        onPageFinishedHelper.waitForCallback(
                currentCallCount, 1, WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    }

    public void loadDataWithBaseUrlAsync(final AwContents awContents, final String data,
            final String mimeType, final boolean isBase64Encoded, final String baseUrl,
            final String historyUrl) throws Throwable {
        runOnUiThread(() -> awContents.loadDataWithBaseURL(baseUrl, data, mimeType,
                                      isBase64Encoded ? "base64" : null, historyUrl));
    }

    /**
     * Reloads the current page synchronously.
     */
    public void reloadSync(final AwContents awContents, CallbackHelper onPageFinishedHelper)
            throws Exception {
        int currentCallCount = onPageFinishedHelper.getCallCount();
        TestThreadUtils.runOnUiThreadBlocking(
                () -> awContents.getNavigationController().reload(true));
        onPageFinishedHelper.waitForCallback(
                currentCallCount, 1, WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    }

    /**
     * Stops loading on the UI thread.
     */
    public void stopLoading(final AwContents awContents) {
        TestThreadUtils.runOnUiThreadBlocking(() -> awContents.stopLoading());
    }

    public void waitForVisualStateCallback(final AwContents awContents) throws Exception {
        final CallbackHelper ch = new CallbackHelper();
        final int chCount = ch.getCallCount();
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            final long requestId = 666;
            awContents.insertVisualStateCallback(requestId, new AwContents.VisualStateCallback() {
                @Override
                public void onComplete(long id) {
                    Assert.assertEquals(requestId, id);
                    ch.notifyCalled();
                }
            });
        });
        ch.waitForCallback(chCount);
    }

    public void insertVisualStateCallbackOnUIThread(final AwContents awContents,
            final long requestId, final AwContents.VisualStateCallback callback) {
        TestThreadUtils.runOnUiThreadBlocking(
                () -> awContents.insertVisualStateCallback(requestId, callback));
    }

    // Waits for the pixel at the center of AwContents to color up into expectedColor.
    // Note that this is a stricter condition that waiting for a visual state callback,
    // as visual state callback only indicates that *something* has appeared in WebView.
    public void waitForPixelColorAtCenterOfView(final AwContents awContents,
            final AwTestContainerView testContainerView, final int expectedColor) {
        pollUiThread(() -> GraphicsTestUtils.getPixelColorAtCenterOfView(
                    awContents, testContainerView) == expectedColor);
    }

    public AwTestContainerView createAwTestContainerView(final AwContentsClient awContentsClient) {
        return createAwTestContainerView(awContentsClient, false, null);
    }

    public AwTestContainerView createAwTestContainerView(final AwContentsClient awContentsClient,
            boolean supportsLegacyQuirks, final TestDependencyFactory testDependencyFactory) {
        AwTestContainerView testContainerView = createDetachedAwTestContainerView(
                awContentsClient, supportsLegacyQuirks, testDependencyFactory);
        getActivity().addView(testContainerView);
        testContainerView.requestFocus();
        return testContainerView;
    }

    public AwBrowserContext getAwBrowserContext() {
        return mBrowserContext;
    }

    public AwTestContainerView createDetachedAwTestContainerView(
            final AwContentsClient awContentsClient) {
        return createDetachedAwTestContainerView(awContentsClient, false, null);
    }

    public AwTestContainerView createDetachedAwTestContainerView(
            final AwContentsClient awContentsClient, boolean supportsLegacyQuirks,
            TestDependencyFactory testDependencyFactory) {
        if (testDependencyFactory == null) {
            testDependencyFactory = createTestDependencyFactory();
        }
        boolean allowHardwareAcceleration = isHardwareAcceleratedTest();
        final AwTestContainerView testContainerView =
                testDependencyFactory.createAwTestContainerView(
                        getActivity(), allowHardwareAcceleration);

        AwSettings awSettings =
                testDependencyFactory.createAwSettings(getActivity(), supportsLegacyQuirks);
        AwContents awContents = testDependencyFactory.createAwContents(mBrowserContext,
                testContainerView, testContainerView.getContext(),
                testContainerView.getInternalAccessDelegate(),
                testContainerView.getNativeDrawFunctorFactory(), awContentsClient, awSettings,
                testDependencyFactory);
        testContainerView.initialize(awContents);
        mAwContentsDestroyedInTearDown.add(new WeakReference<>(awContents));
        return testContainerView;
    }

    public boolean isHardwareAcceleratedTest() {
        return !testMethodHasAnnotation(DisableHardwareAccelerationForTest.class);
    }

    public AwTestContainerView createAwTestContainerViewOnMainSync(final AwContentsClient client) {
        return createAwTestContainerViewOnMainSync(client, false, null);
    }

    public AwTestContainerView createAwTestContainerViewOnMainSync(
            final AwContentsClient client, final boolean supportsLegacyQuirks) {
        return createAwTestContainerViewOnMainSync(client, supportsLegacyQuirks, null);
    }

    public AwTestContainerView createAwTestContainerViewOnMainSync(final AwContentsClient client,
            final boolean supportsLegacyQuirks, final TestDependencyFactory testDependencyFactory) {
        return TestThreadUtils.runOnUiThreadBlockingNoException(
                () -> createAwTestContainerView(
                                client, supportsLegacyQuirks, testDependencyFactory));
    }

    public void destroyAwContentsOnMainSync(final AwContents awContents) {
        if (awContents == null) return;
        TestThreadUtils.runOnUiThreadBlocking(() -> awContents.destroy());
    }

    public String getTitleOnUiThread(final AwContents awContents) throws Exception {
        return TestThreadUtils.runOnUiThreadBlocking(() -> awContents.getTitle());
    }

    public AwSettings getAwSettingsOnUiThread(final AwContents awContents) throws Exception {
        return TestThreadUtils.runOnUiThreadBlocking(() -> awContents.getSettings());
    }

    /**
     * Verify double quotes in both sides of the raw string. Strip the double quotes and
     * returns rest of the string.
     */
    public String maybeStripDoubleQuotes(String raw) {
        Assert.assertNotNull(raw);
        Matcher m = MAYBE_QUOTED_STRING.matcher(raw);
        Assert.assertTrue(m.matches());
        return m.group(2);
    }

    /**
     * Executes the given snippet of JavaScript code within the given ContentView. Returns the
     * result of its execution in JSON format.
     */
    public String executeJavaScriptAndWaitForResult(final AwContents awContents,
            TestAwContentsClient viewClient, final String code) throws Exception {
        return executeJavaScriptAndWaitForResult(
                awContents, viewClient, code, /*shouldCheckSettings=*/true);
    }

    /**
     * Like {@link #executeJavaScriptAndWaitForResult} but with a parameter to skip the call to
     * {@link checkJavaScriptEnabled}. This is useful if your test expects JavaScript to be disabled
     * (in which case the underlying executeJavaScriptAndWaitForResult() is expected to be a NOOP).
     */
    public String executeJavaScriptAndWaitForResult(final AwContents awContents,
            TestAwContentsClient viewClient, final String code, boolean shouldCheckSettings)
            throws Exception {
        if (shouldCheckSettings) {
            checkJavaScriptEnabled(awContents);
        }
        return JSUtils.executeJavaScriptAndWaitForResult(
                InstrumentationRegistry.getInstrumentation(), awContents,
                viewClient.getOnEvaluateJavaScriptResultHelper(), code);
    }

    public static void checkJavaScriptEnabled(AwContents awContents) throws Exception {
        boolean javaScriptEnabled = AwActivityTestRule.getJavaScriptEnabledOnUiThread(awContents);
        if (!javaScriptEnabled) {
            throw new IllegalStateException(
                    "JavaScript is disabled in this AwContents; did you forget to call "
                    + "AwActivityTestRule.enableJavaScriptOnUiThread()?");
        }
    }

    /**
     * Executes JavaScript code within the given ContentView to get the text content in
     * document body. Returns the result string without double quotes.
     */
    public String getJavaScriptResultBodyTextContent(
            final AwContents awContents, final TestAwContentsClient viewClient) throws Exception {
        String raw = executeJavaScriptAndWaitForResult(
                awContents, viewClient, "document.body.textContent");
        return maybeStripDoubleQuotes(raw);
    }

    /**
     * Adds a JavaScript interface to the AwContents. Does its work synchronously on the UI thread,
     * and can be called from any thread. All the rules of {@link
     * android.webkit.WebView#addJavascriptInterface} apply to this method (ex. you must call this
     * <b>prior</b> to loading the frame you intend to load the JavaScript interface into).
     *
     * @param awContents the AwContents in which to insert the JavaScript interface.
     * @param objectToInject the JavaScript interface to inject.
     * @param javascriptIdentifier the name with which to refer to {@code objectToInject} from
     *        JavaScript code.
     */
    public static void addJavascriptInterfaceOnUiThread(final AwContents awContents,
            final Object objectToInject, final String javascriptIdentifier) throws Exception {
        checkJavaScriptEnabled(awContents);
        TestThreadUtils.runOnUiThreadBlocking(
                () -> awContents.addJavascriptInterface(objectToInject, javascriptIdentifier));
    }

    /**
     * Wrapper around CriteriaHelper.pollInstrumentationThread. This uses AwActivityTestRule-specifc
     * timeouts and treats timeouts and exceptions as test failures automatically.
     */
    public static void pollInstrumentationThread(final Callable<Boolean> callable) {
        CriteriaHelper.pollInstrumentationThread(() -> {
            try {
                return callable.call();
            } catch (Throwable e) {
                Log.e(TAG, "Exception while polling.", e);
                return false;
            }
        }, WAIT_TIMEOUT_MS, CHECK_INTERVAL);
    }

    /**
     * Wrapper around {@link AwActivityTestRule#pollInstrumentationThread()} but runs the
     * callable on the UI thread.
     */
    public void pollUiThread(final Callable<Boolean> callable) {
        pollInstrumentationThread(() -> TestThreadUtils.runOnUiThreadBlocking(callable));
    }

    /**
     * Waits for {@code future} and returns its value (or times out). If {@code future} has an
     * associated Exception, this will re-throw that Exception on the instrumentation thread
     * (wrapping with an unchecked Exception if necessary, to avoid requiring callers to declare
     * checked Exceptions).
     *
     * @param future the {@link Future} representing a value of interest.
     * @return the value {@code future} represents.
     */
    public static <T> T waitForFuture(Future<T> future) {
        try {
            return future.get(SCALED_WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
        } catch (ExecutionException e) {
            // ExecutionException means this Future has an associated Exception that we should
            // re-throw on the current thread. We throw the cause instead of ExecutionException,
            // since ExecutionException itself isn't interesting, and might mislead those debugging
            // test failures to suspect this method is the culprit (whereas the root cause is from
            // another thread).
            Throwable cause = e.getCause();
            // If the cause is an unchecked Throwable type, re-throw as-is.
            if (cause instanceof Error) throw(Error) cause;
            if (cause instanceof RuntimeException) throw(RuntimeException) cause;
            // Otherwise, wrap this in an unchecked Exception so callers don't need to declare
            // checked Exceptions.
            throw new RuntimeException(cause);
        } catch (InterruptedException | TimeoutException e) {
            // Don't call e.getCause() for either of these. Unlike ExecutionException, these don't
            // wrap the root cause, but rather are themselves interesting. Again, we wrap these
            // checked Exceptions with an unchecked Exception for the caller's convenience.
            //
            // Although we might be tempted to handle InterruptedException by calling
            // Thread.currentThread().interrupt(), this is not correct in this case. The interrupted
            // thread was likely a different thread than the current thread, so there's nothing
            // special we need to do.
            throw new RuntimeException(e);
        }
    }

    /**
     * Takes an element out of the {@link BlockingQueue} (or times out).
     */
    public static <T> T waitForNextQueueElement(BlockingQueue<T> queue) throws Exception {
        T value = queue.poll(SCALED_WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
        if (value == null) {
            // {@code null} is the special value which means {@link BlockingQueue#poll} has timed
            // out (also: there's no risk for collision with real values, because BlockingQueue does
            // not allow null entries). Instead of returning this special value, let's throw a
            // proper TimeoutException.
            throw new TimeoutException(
                    "Timeout while trying to take next entry from BlockingQueue");
        }
        return value;
    }

    /**
     * Clears the resource cache. Note that the cache is per-application, so this will clear the
     * cache for all WebViews used.
     */
    public void clearCacheOnUiThread(final AwContents awContents, final boolean includeDiskFiles) {
        TestThreadUtils.runOnUiThreadBlocking(() -> awContents.clearCache(includeDiskFiles));
    }

    /**
     * Returns pure page scale.
     */
    public float getScaleOnUiThread(final AwContents awContents) throws Exception {
        return TestThreadUtils.runOnUiThreadBlocking(() -> awContents.getPageScaleFactor());
    }

    /**
     * Returns page scale multiplied by the screen density.
     */
    public float getPixelScaleOnUiThread(final AwContents awContents) throws Exception {
        return TestThreadUtils.runOnUiThreadBlocking(() -> awContents.getScale());
    }

    /**
     * Returns whether a user can zoom the page in.
     */
    public boolean canZoomInOnUiThread(final AwContents awContents) throws Exception {
        return TestThreadUtils.runOnUiThreadBlocking(() -> awContents.canZoomIn());
    }

    /**
     * Returns whether a user can zoom the page out.
     */
    public boolean canZoomOutOnUiThread(final AwContents awContents) throws Exception {
        return TestThreadUtils.runOnUiThreadBlocking(() -> awContents.canZoomOut());
    }

    /**
     * Loads the main html then triggers the popup window.
     */
    public void triggerPopup(final AwContents parentAwContents,
            TestAwContentsClient parentAwContentsClient, TestWebServer testWebServer,
            String mainHtml, String popupHtml, String popupPath, String triggerScript)
            throws Exception {
        enableJavaScriptOnUiThread(parentAwContents);
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            parentAwContents.getSettings().setSupportMultipleWindows(true);
            parentAwContents.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        });

        final String parentUrl = testWebServer.setResponse("/popupParent.html", mainHtml, null);
        if (popupHtml != null) {
            testWebServer.setResponse(popupPath, popupHtml, null);
        } else {
            testWebServer.setResponseWithNoContentStatus(popupPath);
        }

        parentAwContentsClient.getOnCreateWindowHelper().setReturnValue(true);
        loadUrlSync(parentAwContents, parentAwContentsClient.getOnPageFinishedHelper(), parentUrl);

        TestAwContentsClient.OnCreateWindowHelper onCreateWindowHelper =
                parentAwContentsClient.getOnCreateWindowHelper();
        int currentCallCount = onCreateWindowHelper.getCallCount();
        TestThreadUtils.runOnUiThreadBlocking(
                () -> parentAwContents.evaluateJavaScriptForTests(triggerScript, null));
        onCreateWindowHelper.waitForCallback(
                currentCallCount, 1, WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    }

    /**
     * Supplies the popup window with AwContents then waits for the popup window to finish loading.
     * @param parentAwContents Parent webview's AwContents.
     */
    public PopupInfo connectPendingPopup(AwContents parentAwContents) throws Exception {
        PopupInfo popupInfo = createPopupContents(parentAwContents);
        loadPopupContents(parentAwContents, popupInfo, null);
        return popupInfo;
    }

    /**
     * Creates a popup window with AwContents.
     */
    public PopupInfo createPopupContents(final AwContents parentAwContents) {
        TestAwContentsClient popupContentsClient;
        AwTestContainerView popupContainerView;
        final AwContents popupContents;
        popupContentsClient = new TestAwContentsClient();
        popupContainerView = createAwTestContainerViewOnMainSync(popupContentsClient);
        popupContents = popupContainerView.getAwContents();
        enableJavaScriptOnUiThread(popupContents);
        return new PopupInfo(popupContentsClient, popupContainerView, popupContents);
    }

    /**
     * Waits for the popup window to finish loading.
     * @param parentAwContents Parent webview's AwContents.
     * @param info The PopupInfo.
     * @param onCreateWindowHandler An instance of OnCreateWindowHandler. null if there isn't.
     */
    public void loadPopupContents(final AwContents parentAwContents, PopupInfo info,
            OnCreateWindowHandler onCreateWindowHandler) throws Exception {
        TestAwContentsClient popupContentsClient = info.popupContentsClient;
        AwTestContainerView popupContainerView = info.popupContainerView;
        final AwContents popupContents = info.popupContents;
        OnPageFinishedHelper onPageFinishedHelper = popupContentsClient.getOnPageFinishedHelper();
        int finishCallCount = onPageFinishedHelper.getCallCount();

        if (onCreateWindowHandler != null) onCreateWindowHandler.onCreateWindow(popupContents);

        TestAwContentsClient.OnReceivedTitleHelper onReceivedTitleHelper =
                popupContentsClient.getOnReceivedTitleHelper();
        int titleCallCount = onReceivedTitleHelper.getCallCount();

        TestThreadUtils.runOnUiThreadBlocking(
                () -> parentAwContents.supplyContentsForPopup(popupContents));

        onPageFinishedHelper.waitForCallback(
                finishCallCount, 1, WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
        onReceivedTitleHelper.waitForCallback(
                titleCallCount, 1, WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    }

    private boolean testMethodHasAnnotation(Class<? extends Annotation> clazz) {
        return mCurrentTestDescription.getAnnotation(clazz) != null ? true : false;
    }

    /**
     * Factory class used in creation of test AwContents instances. Test cases
     * can provide subclass instances to the createAwTest* methods in order to
     * create an AwContents instance with injected test dependencies.
     */
    public static class TestDependencyFactory extends AwContents.DependencyFactory {
        public AwTestContainerView createAwTestContainerView(
                AwTestRunnerActivity activity, boolean allowHardwareAcceleration) {
            return new AwTestContainerView(activity, allowHardwareAcceleration);
        }

        public AwSettings createAwSettings(Context context, boolean supportsLegacyQuirks) {
            return new AwSettings(context, false /* isAccessFromFileURLsGrantedByDefault */,
                    supportsLegacyQuirks, false /* allowEmptyDocumentPersistence */,
                    true /* allowGeolocationOnInsecureOrigins */,
                    false /* doNotUpdateSelectionOnMutatingSelectionRange */);
        }

        public AwContents createAwContents(AwBrowserContext browserContext, ViewGroup containerView,
                Context context, InternalAccessDelegate internalAccessAdapter,
                NativeDrawFunctorFactory nativeDrawFunctorFactory, AwContentsClient contentsClient,
                AwSettings settings, DependencyFactory dependencyFactory) {
            return new AwContents(browserContext, containerView, context, internalAccessAdapter,
                    nativeDrawFunctorFactory, contentsClient, settings, dependencyFactory);
        }
    }

    /**
     * POD object for holding references to helper objects of a popup window.
     */
    public static class PopupInfo {
        public final TestAwContentsClient popupContentsClient;
        public final AwTestContainerView popupContainerView;
        public final AwContents popupContents;

        public PopupInfo(TestAwContentsClient popupContentsClient,
                AwTestContainerView popupContainerView, AwContents popupContents) {
            this.popupContentsClient = popupContentsClient;
            this.popupContainerView = popupContainerView;
            this.popupContents = popupContents;
        }
    }
}


text:
def parse_config_yaml(yaml_data):
    # Initialize to default options.
    quantization_options = {
        "n_centroids": {
            "Linear": ["in_features", {"*": 256}],
            "Embedding": ["embedding_dim", {"*": 256}],
        },
        "block_sizes": {
            "Linear": ["fuzzy_name", {"fc": 8, "attn": 4, "emb": 4}],
            "Embedding": ["fuzzy_name", {"emb": 8}],
        },
        "layers_to_quantize": [
            "decoder\\.layers\\.\\d+\\.fc[12]",
            "decoder\\.embed_tokens\\.embeddings\\.[012]\\.[01]",
            "decoder\\.layers\\.\\d+\\.self_attn\\.(k_proj|v_proj|q_proj|out_proj)",
        ],
    }

    if "n_centroids" in yaml_data:
        quantization_options["n_centroids"] = {
            layer: convert_yaml_to_tuple(layer_data)
            for layer, layer_data in yaml_data["n_centroids"].items()
        }
    if "block_sizes" in yaml_data:
        quantization_options["block_sizes"] = {
            layer: convert_yaml_to_tuple(layer_data)
            for layer, layer_data in yaml_data["block_sizes"].items()
        }
    if "layers_to_quantize" in yaml_data:
        quantization_options["layers_to_quantize"] = yaml_data["layers_to_quantize"]

    return quantization_options

def convert_yaml_to_tuple(yaml_dictionary):
    """Converts a yaml dictionary with two keys: `key` and `value` into a two
    argument tuple of those values."""
    return (yaml_dictionary["key"], yaml_dictionary["value"])