text:
from __future__ import print_function
from bcc import BPF
from time import sleep
import argparse
import signal
import errno
from sys import stderr

# arg validation
def positive_int(val):
    dest = []
    # Filter up to 5 pids, arbitrary
    args_list = val.split(",", 5)
    pids_to_add = min(len(args_list), 5)
    for i in range(pids_to_add):
        dest.append(_positive_int(args_list[i]))

    return dest

def _positive_int(val):
    try:
        ival = int(val)
    except ValueError:
        raise argparse.ArgumentTypeError("must be an integer")

    if ival < 0:
        raise argparse.ArgumentTypeError("must be positive")
    return ival

def positive_nonzero_int(val):
    ival = _positive_int(val)
    if ival == 0:
        raise argparse.ArgumentTypeError("must be nonzero")
    return ival

def build_filter(filter_name, values):
    filter_string = "((%s == %d)" % (filter_name, values[0])

    for val in values[1:]:
        filter_string += " || (%s == %d )" % (filter_name , val)

    filter_string += ")"

    return filter_string

def stack_id_err(stack_id):
    # -EFAULT in get_stackid normally means the stack-trace is not available,
    # Such as getting kernel stack trace in userspace code
    return (stack_id < 0) and (stack_id != -errno.EFAULT)

# arguments
examples = """examples:
    ./offwaketime             # trace off-CPU + waker stack time until Ctrl-C
    ./offwaketime 5           # trace for 5 seconds only
    ./offwaketime -f 5        # 5 seconds, and output in folded format
    ./offwaketime -m 1000     # trace only events that last more than 1000 usec
    ./offwaketime -M 9000     # trace only events that last less than 9000 usec
    ./offwaketime -p 185      # only trace threads for PID 185
    ./offwaketime -t 188      # only trace thread 188
    ./offwaketime -u          # only trace user threads (no kernel)
    ./offwaketime -k          # only trace kernel threads (no user)
    ./offwaketime -U          # only show user space stacks (no kernel)
    ./offwaketime -K          # only show kernel space stacks (no user)
"""
parser = argparse.ArgumentParser(
    description="Summarize blocked time by kernel stack trace + waker stack",
    formatter_class=argparse.RawDescriptionHelpFormatter,
    epilog=examples)
thread_group = parser.add_mutually_exclusive_group()
# Note: this script provides --pid and --tid flags but their arguments are
# referred to internally using kernel nomenclature: TGID and PID.
thread_group.add_argument("-p", "--pid", metavar="PIDS", dest="tgid",
     type=positive_int,
     help="trace these PIDS only. Can be a comma separated list of PIDS.")
thread_group.add_argument("-t", "--tid", metavar="TIDS", dest="pid",
    type=positive_int,
    help="trace these TIDS only. Can be a comma separated list of TIDS.")
thread_group.add_argument("-u", "--user-threads-only", action="store_true",
    help="user threads only (no kernel threads)")
thread_group.add_argument("-k", "--kernel-threads-only", action="store_true",
    help="kernel threads only (no user threads)")
stack_group = parser.add_mutually_exclusive_group()
stack_group.add_argument("-U", "--user-stacks-only", action="store_true",
    help="show stacks from user space only (no kernel space stacks)")
stack_group.add_argument("-K", "--kernel-stacks-only", action="store_true",
    help="show stacks from kernel space only (no user space stacks)")
parser.add_argument("-d", "--delimited", action="store_true",
    help="insert delimiter between kernel/user stacks")
parser.add_argument("-f", "--folded", action="store_true",
    help="output folded format")
parser.add_argument("--stack-storage-size", default=1024,
    type=positive_nonzero_int,
    help="the number of unique stack traces that can be stored and "
         "displayed (default 1024)")
parser.add_argument("duration", nargs="?", default=99999999,
    type=positive_nonzero_int,
    help="duration of trace, in seconds")
parser.add_argument("-m", "--min-block-time", default=1,
    type=positive_nonzero_int,
    help="the amount of time in microseconds over which we " +
         "store traces (default 1)")
parser.add_argument("-M", "--max-block-time", default=(1 << 64) - 1,
    type=positive_nonzero_int,
    help="the amount of time in microseconds under which we " +
         "store traces (default U64_MAX)")
parser.add_argument("--state", type=_positive_int,
    help="filter on this thread state bitmask (eg, 2 == TASK_UNINTERRUPTIBLE" +
         ") see include/linux/sched.h")
parser.add_argument("--ebpf", action="store_true",
    help=argparse.SUPPRESS)
args = parser.parse_args()
folded = args.folded
duration = int(args.duration)

# signal handler
def signal_ignore(signal, frame):
    print()

# define BPF program
bpf_text = """
#include <uapi/linux/ptrace.h>
#include <linux/sched.h>

#define MINBLOCK_US    MINBLOCK_US_VALUEULL
#define MAXBLOCK_US    MAXBLOCK_US_VALUEULL

struct key_t {
    char waker[TASK_COMM_LEN];
    char target[TASK_COMM_LEN];
    int w_k_stack_id;
    int w_u_stack_id;
    int t_k_stack_id;
    int t_u_stack_id;
    u32 t_pid;
    u32 t_tgid;
    u32 w_pid;
    u32 w_tgid;
};
BPF_HASH(counts, struct key_t);

// Key of this hash is PID of waiting Process,
// value is timestamp when it went into waiting
BPF_HASH(start, u32);

struct wokeby_t {
    char name[TASK_COMM_LEN];
    int k_stack_id;
    int u_stack_id;
    int w_pid;
    int w_tgid;
};
// Key of the hash is PID of the Process to be waken, value is information
// of the Process who wakes it
BPF_HASH(wokeby, u32, struct wokeby_t);

BPF_STACK_TRACE(stack_traces, STACK_STORAGE_SIZE);

int waker(struct pt_regs *ctx, struct task_struct *p) {
    // PID and TGID of the target Process to be waken
    u32 pid = p->pid;
    u32 tgid = p->tgid;

    if (!((THREAD_FILTER) && (STATE_FILTER))) {
        return 0;
    }

    // Construct information about current (the waker) Process
    struct wokeby_t woke = {};
    bpf_get_current_comm(&woke.name, sizeof(woke.name));
    woke.k_stack_id = KERNEL_STACK_GET;
    woke.u_stack_id = USER_STACK_GET;
    woke.w_pid = bpf_get_current_pid_tgid();
    woke.w_tgid = bpf_get_current_pid_tgid() >> 32;

    wokeby.update(&pid, &woke);
    return 0;
}

int oncpu(struct pt_regs *ctx, struct task_struct *p) {
    // PID and TGID of the previous Process (Process going into waiting)
    u32 pid = p->pid;
    u32 tgid = p->tgid;
    u64 *tsp;
    u64 ts = bpf_ktime_get_ns();

    // Record timestamp for the previous Process (Process going into waiting)
    if ((THREAD_FILTER) && (STATE_FILTER)) {
        start.update(&pid, &ts);
    }

    // Calculate current Process's wait time by finding the timestamp of when
    // it went into waiting.
    // pid and tgid are now the PID and TGID of the current (waking) Process.
    pid = bpf_get_current_pid_tgid();
    tgid = bpf_get_current_pid_tgid() >> 32;
    tsp = start.lookup(&pid);
    if (tsp == 0) {
        // Missed or filtered when the Process went into waiting
        return 0;
    }
    u64 delta = ts - *tsp;
    start.delete(&pid);
    delta = delta / 1000;
    if ((delta < MINBLOCK_US) || (delta > MAXBLOCK_US)) {
        return 0;
    }

    // create map key
    struct key_t key = {};
    struct wokeby_t *woke;

    bpf_get_current_comm(&key.target, sizeof(key.target));
    key.t_pid = pid;
    key.t_tgid = tgid;
    key.t_k_stack_id = KERNEL_STACK_GET;
    key.t_u_stack_id = USER_STACK_GET;

    woke = wokeby.lookup(&pid);
    if (woke) {
        key.w_k_stack_id = woke->k_stack_id;
        key.w_u_stack_id = woke->u_stack_id;
        key.w_pid = woke->w_pid;
        key.w_tgid = woke->w_tgid;
        __builtin_memcpy(&key.waker, woke->name, TASK_COMM_LEN);
        wokeby.delete(&pid);
    }

    counts.increment(key, delta);
    return 0;
}
"""

# set thread filter
if args.tgid is not None:
    thread_filter = build_filter("tgid", args.tgid)
elif args.pid is not None:
    thread_filter = build_filter("pid", args.pid)
elif args.user_threads_only:
    thread_filter = '!(p->flags & PF_KTHREAD)'
elif args.kernel_threads_only:
    thread_filter = 'p->flags & PF_KTHREAD'
else:
    thread_filter = '1'
if args.state == 0:
    state_filter = 'p->state == 0'
elif args.state:
    # these states are sometimes bitmask checked
    state_filter = 'p->state & %d' % args.state
else:
    state_filter = '1'
bpf_text = bpf_text.replace('THREAD_FILTER', thread_filter)
bpf_text = bpf_text.replace('STATE_FILTER', state_filter)

# set stack storage size
bpf_text = bpf_text.replace('STACK_STORAGE_SIZE', str(args.stack_storage_size))
bpf_text = bpf_text.replace('MINBLOCK_US_VALUE', str(args.min_block_time))
bpf_text = bpf_text.replace('MAXBLOCK_US_VALUE', str(args.max_block_time))

# handle stack args
kernel_stack_get = "stack_traces.get_stackid(ctx, 0)"
user_stack_get = "stack_traces.get_stackid(ctx, BPF_F_USER_STACK)"
stack_context = ""
if args.user_stacks_only:
    stack_context = "user"
    kernel_stack_get = "-1"
elif args.kernel_stacks_only:
    stack_context = "kernel"
    user_stack_get = "-1"
else:
    stack_context = "user + kernel"
bpf_text = bpf_text.replace('USER_STACK_GET', user_stack_get)
bpf_text = bpf_text.replace('KERNEL_STACK_GET', kernel_stack_get)
if args.ebpf:
    print(bpf_text)
    exit()

# initialize BPF
b = BPF(text=bpf_text)
b.attach_kprobe(event="finish_task_switch", fn_name="oncpu")
b.attach_kprobe(event="try_to_wake_up", fn_name="waker")
matched = b.num_open_kprobes()
if matched == 0:
    print("0 functions traced. Exiting.")
    exit()

# header
if not folded:
    print("Tracing blocked time (us) by %s off-CPU and waker stack" %
        stack_context, end="")
    if duration < 99999999:
        print(" for %d secs." % duration)
    else:
        print("... Hit Ctrl-C to end.")

try:
    sleep(duration)
except KeyboardInterrupt:
    # as cleanup can take many seconds, trap Ctrl-C:
    # print a newline for folded output on Ctrl-C
    signal.signal(signal.SIGINT, signal_ignore)

if not folded:
    print()

missing_stacks = 0
has_enomem = False
counts = b.get_table("counts")
stack_traces = b.get_table("stack_traces")
need_delimiter = args.delimited and not (args.kernel_stacks_only or
                                         args.user_stacks_only)
for k, v in sorted(counts.items(), key=lambda counts: counts[1].value):
    # handle get_stackid errors
    if not args.user_stacks_only:
        missing_stacks += int(stack_id_err(k.w_k_stack_id))
        missing_stacks += int(stack_id_err(k.t_k_stack_id))
        has_enomem = has_enomem or (k.w_k_stack_id == -errno.ENOMEM) or \
                     (k.t_k_stack_id == -errno.ENOMEM)
    if not args.kernel_stacks_only:
        missing_stacks += int(stack_id_err(k.w_u_stack_id))
        missing_stacks += int(stack_id_err(k.t_u_stack_id))
        has_enomem = has_enomem or (k.w_u_stack_id == -errno.ENOMEM) or \
                     (k.t_u_stack_id == -errno.ENOMEM)

    waker_user_stack = [] if k.w_u_stack_id < 1 else \
        reversed(list(stack_traces.walk(k.w_u_stack_id))[1:])
    waker_kernel_stack = [] if k.w_k_stack_id < 1 else \
        reversed(list(stack_traces.walk(k.w_k_stack_id))[1:])
    target_user_stack = [] if k.t_u_stack_id < 1 else \
        stack_traces.walk(k.t_u_stack_id)
    target_kernel_stack = [] if k.t_k_stack_id < 1 else \
        stack_traces.walk(k.t_k_stack_id)

    if folded:
        # print folded stack output
        line = [k.target.decode('utf-8', 'replace')]
        if not args.kernel_stacks_only:
            if stack_id_err(k.t_u_stack_id):
                line.append("[Missed User Stack] %d" % k.t_u_stack_id)
            else:
                line.extend([b.sym(addr, k.t_tgid).decode('utf-8', 'replace')
                    for addr in reversed(list(target_user_stack)[1:])])
        if not args.user_stacks_only:
            line.extend(["-"] if (need_delimiter and k.t_k_stack_id > 0 and k.t_u_stack_id > 0) else [])
            if stack_id_err(k.t_k_stack_id):
                line.append("[Missed Kernel Stack]")
            else:
                line.extend([b.ksym(addr).decode('utf-8', 'replace')
                    for addr in reversed(list(target_kernel_stack)[1:])])
        line.append("--")
        if not args.user_stacks_only:
            if stack_id_err(k.w_k_stack_id):
                line.append("[Missed Kernel Stack]")
            else:
                line.extend([b.ksym(addr).decode('utf-8', 'replace')
                    for addr in reversed(list(waker_kernel_stack))])
        if not args.kernel_stacks_only:
            line.extend(["-"] if (need_delimiter and k.w_u_stack_id > 0 and k.w_k_stack_id > 0) else [])
            if stack_id_err(k.w_u_stack_id):
                line.append("[Missed User Stack]")
            else:
                line.extend([b.sym(addr, k.w_tgid).decode('utf-8', 'replace')
                    for addr in reversed(list(waker_user_stack))])
        line.append(k.waker.decode('utf-8', 'replace'))
        print("%s %d" % (";".join(line), v.value))
    else:
        # print wakeup name then stack in reverse order
        print("    %-16s %s %s" % ("waker:", k.waker.decode('utf-8', 'replace'), k.w_pid))
        if not args.kernel_stacks_only:
            if stack_id_err(k.w_u_stack_id):
                print("    [Missed User Stack] %d" % k.w_u_stack_id)
            else:
                for addr in waker_user_stack:
                    print("    %s" % b.sym(addr, k.w_tgid))
        if not args.user_stacks_only:
            if need_delimiter and k.w_u_stack_id > 0 and k.w_k_stack_id > 0:
                print("    -")
            if stack_id_err(k.w_k_stack_id):
                print("    [Missed Kernel Stack]")
            else:
                for addr in waker_kernel_stack:
                    print("    %s" % b.ksym(addr))

        # print waker/wakee delimiter
        print("    %-16s %s" % ("--", "--"))

        if not args.user_stacks_only:
            if stack_id_err(k.t_k_stack_id):
                print("    [Missed Kernel Stack]")
            else:
                for addr in target_kernel_stack:
                    print("    %s" % b.ksym(addr))
        if not args.kernel_stacks_only:
            if need_delimiter and k.t_u_stack_id > 0 and k.t_k_stack_id > 0:
                print("    -")
            if stack_id_err(k.t_u_stack_id):
                print("    [Missed User Stack]")
            else:
                for addr in target_user_stack:
                    print("    %s" % b.sym(addr, k.t_tgid))
        print("    %-16s %s %s" % ("target:", k.target.decode('utf-8', 'replace'), k.t_pid))
        print("        %d\n" % v.value)

if missing_stacks > 0:
    enomem_str = " Consider increasing --stack-storage-size."
    print("WARNING: %d stack traces lost and could not be displayed.%s" %
        (missing_stacks, (enomem_str if has_enomem else "")),
        file=stderr)


text:
<!DOCTYPE html>

<?php
    include 'header.php';
?>
    <title>Applications</title>

<?php
    include 'header_menu.php';
?>

Applications

Applications

               Application software is programs that run under the operating system. Applications can be anything from office
               applications to CAD software. The Internet browser Internet Explorer (IE) on Windows is an application.
               Games, video players, and photo viewers are applications.

                 Computer applications are written by computer programmers or developers. Several languages are available
                 for use in development, such as C, C++, C#, BASIC, and Java to name a few. Internet web development is also
                 done by developers. Web development is done in HTML5, Javascript, PHP, Pearl, and Python to name a few.
                Click here to learn more on applications.

<?php
    include 'footing.php';
?>

redpajama_set_name: RedPajamaGithub


text: X


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>ActionView::Template::Handlers::ERB</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../../../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../../css/github.css" type="text/css" media="screen" />

            Ruby on Rails 4.1.6

            Class
            ActionView::Template::Handlers::ERB

                <

                    Object

/Users/Sean/.rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/gems/actionview-4.1.6/lib/action_view/template/handlers/erb.rb

Methods

C

                call,

                call

H

                handles_encoding?

S

                supports_streaming?

Constants

            ENCODING_TAG
            =
            Regexp.new("\\A(<%#{ENCODING_FLAG}-?%>)[ \\t]*")

Class Public methods

              call(template)

            Link

                Source:
                show

# File ../../.rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/gems/actionview-4.1.6/lib/action_view/template/handlers/erb.rb, line 92
def self.call(template)
  new.call(template)
end

Instance Public methods

              call(template)

            Link

                Source:
                show

# File ../../.rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/gems/actionview-4.1.6/lib/action_view/template/handlers/erb.rb, line 104
def call(template)
  # First, convert to BINARY, so in case the encoding is
  # wrong, we can still find an encoding tag
  # (<%# encoding %>) inside the String using a regular
  # expression
  template_source = template.source.dup.force_encoding(Encoding::ASCII_8BIT)

  erb = template_source.gsub(ENCODING_TAG, '')
  encoding = $2

  erb.force_encoding valid_encoding(template.source.dup, encoding)

  # Always make sure we return a String in the default_internal
  erb.encode!

  self.class.erb_implementation.new(
    erb,
    :escape => (self.class.escape_whitelist.include? template.type),
    :trim => (self.class.erb_trim_mode == "-")
  ).src
end

              handles_encoding?()

            Link

                Source:
                show

# File ../../.rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/gems/actionview-4.1.6/lib/action_view/template/handlers/erb.rb, line 100
def handles_encoding?
  true
end

              supports_streaming?()

            Link

                Source:
                show

# File ../../.rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/gems/actionview-4.1.6/lib/action_view/template/handlers/erb.rb, line 96
def supports_streaming?
  true
end


text:
<?php

namespace Google\Cloud\Core\Report;

/**
 * MetadataProvider for GAE.
 */
abstract class GAEMetadataProvider implements MetadataProviderInterface
{
    abstract protected function getTraceValue($server);

    /** @var array */
    private $data;

    /**
     * @param array $server An array for holding the values. Normally just use
     *              $_SERVER.
     */
    public function __construct(array $server)
    {
        $projectId = isset($server['GOOGLE_CLOUD_PROJECT'])
            ? $server['GOOGLE_CLOUD_PROJECT']
            : 'unknown-projectid';
        $serviceId = isset($server['GAE_SERVICE'])
            ? $server['GAE_SERVICE']
            : 'unknown-service';
        $versionId = isset($server['GAE_VERSION'])
            ? $server['GAE_VERSION']
            : 'unknown-version';
        $labels = isset($server['HTTP_X_CLOUD_TRACE_CONTEXT'])
            ? ['appengine.googleapis.com/trace_id' =>
               $this->getTraceValue($server)]
            : [];
        $this->data =
            [
                'resource' => [
                    'type' => 'gae_app',
                    'labels' => [
                        'project_id' => $projectId,
                        'version_id' => $versionId,
                        'module_id' => $serviceId
                    ]
                ],
                'projectId' => $projectId,
                'serviceId' => $serviceId,
                'versionId' => $versionId,
                'labels' => $labels
            ];
    }

    /**
     * Return an array representing MonitoredResource.
     * {@see https://cloud.google.com/logging/docs/reference/v2/rest/v2/MonitoredResource}
     *
     * @return array
     */
    public function monitoredResource()
    {
        return $this->data['resource'];
    }

    /**
     * Return the project id.
     * @return string
     */
    public function projectId()
    {
        return $this->data['projectId'];
    }

    /**
     * Return the service id.
     * @return string
     */
    public function serviceId()
    {
        return $this->data['serviceId'];
    }

    /**
     * Return the version id.
     * @return string
     */
    public function versionId()
    {
        return $this->data['versionId'];
    }

    /**
     * Return the labels. We need to evaluate $_SERVER for each request.
     * @return array
     */
    public function labels()
    {
        return $this->data['labels'];
    }
}


text:
#include "core/dom/ChildListMutationScope.h"

#include "core/dom/MutationObserverInterestGroup.h"
#include "core/dom/MutationRecord.h"
#include "core/dom/StaticNodeList.h"
#include "wtf/HashMap.h"
#include "wtf/StdLibExtras.h"

namespace blink {

// The accumulator map is used to make sure that there is only one mutation
// accumulator for a given node even if there are multiple ChildListMutationScopes
// on the stack. The map is always empty when there are no ChildListMutationScopes
// on the stack.
typedef HeapHashMap<Member<Node>, Member<ChildListMutationAccumulator>> AccumulatorMap;

static AccumulatorMap& accumulatorMap()
{
    DEFINE_STATIC_LOCAL(AccumulatorMap, map, (new AccumulatorMap));
    return map;
}

ChildListMutationAccumulator::ChildListMutationAccumulator(RawPtr<Node> target, RawPtr<MutationObserverInterestGroup> observers)
    : m_target(target)
    , m_lastAdded(nullptr)
    , m_observers(observers)
    , m_mutationScopes(0)
{
}

void ChildListMutationAccumulator::leaveMutationScope()
{
    DCHECK_GT(m_mutationScopes, 0u);
    if (!--m_mutationScopes) {
        if (!isEmpty())
            enqueueMutationRecord();
        accumulatorMap().remove(m_target.get());
    }
}

RawPtr<ChildListMutationAccumulator> ChildListMutationAccumulator::getOrCreate(Node& target)
{
    AccumulatorMap::AddResult result = accumulatorMap().add(&target, nullptr);
    RawPtr<ChildListMutationAccumulator> accumulator;
    if (!result.isNewEntry) {
        accumulator = result.storedValue->value;
    } else {
        accumulator = new ChildListMutationAccumulator(RawPtr<Node>(target), MutationObserverInterestGroup::createForChildListMutation(target));
        result.storedValue->value = accumulator.get();
    }
    return accumulator.release();
}

inline bool ChildListMutationAccumulator::isAddedNodeInOrder(Node* child)
{
    return isEmpty() || (m_lastAdded == child->previousSibling() && m_nextSibling == child->nextSibling());
}

void ChildListMutationAccumulator::childAdded(RawPtr<Node> prpChild)
{
    DCHECK(hasObservers());

    RawPtr<Node> child = prpChild;

    if (!isAddedNodeInOrder(child.get()))
        enqueueMutationRecord();

    if (isEmpty()) {
        m_previousSibling = child->previousSibling();
        m_nextSibling = child->nextSibling();
    }

    m_lastAdded = child.get();
    m_addedNodes.append(child.release());
}

inline bool ChildListMutationAccumulator::isRemovedNodeInOrder(Node* child)
{
    return isEmpty() || m_nextSibling == child;
}

void ChildListMutationAccumulator::willRemoveChild(RawPtr<Node> prpChild)
{
    DCHECK(hasObservers());

    RawPtr<Node> child = prpChild;

    if (!m_addedNodes.isEmpty() || !isRemovedNodeInOrder(child.get()))
        enqueueMutationRecord();

    if (isEmpty()) {
        m_previousSibling = child->previousSibling();
        m_nextSibling = child->nextSibling();
        m_lastAdded = child->previousSibling();
    } else {
        m_nextSibling = child->nextSibling();
    }

    m_removedNodes.append(child.release());
}

void ChildListMutationAccumulator::enqueueMutationRecord()
{
    DCHECK(hasObservers());
    DCHECK(!isEmpty());

    RawPtr<StaticNodeList> addedNodes = StaticNodeList::adopt(m_addedNodes);
    RawPtr<StaticNodeList> removedNodes = StaticNodeList::adopt(m_removedNodes);
    RawPtr<MutationRecord> record = MutationRecord::createChildList(m_target, addedNodes.release(), removedNodes.release(), m_previousSibling.release(), m_nextSibling.release());
    m_observers->enqueueMutationRecord(record.release());
    m_lastAdded = nullptr;
    DCHECK(isEmpty());
}

bool ChildListMutationAccumulator::isEmpty()
{
    bool result = m_removedNodes.isEmpty() && m_addedNodes.isEmpty();
#if DCHECK_IS_ON()
    if (result) {
        DCHECK(!m_previousSibling);
        DCHECK(!m_nextSibling);
        DCHECK(!m_lastAdded);
    }
#endif
    return result;
}

DEFINE_TRACE(ChildListMutationAccumulator)
{
    visitor->trace(m_target);
    visitor->trace(m_removedNodes);
    visitor->trace(m_addedNodes);
    visitor->trace(m_previousSibling);
    visitor->trace(m_nextSibling);
    visitor->trace(m_lastAdded);
    visitor->trace(m_observers);
}

} // namespace blink


text:
package provingground.learning
import provingground.HoTT._
import provingground.{FiniteDistribution => _, _}
import shapeless._
import induction._
import provingground.learning.GeneratorNode.Map

import GeneratorNode._
import scala.util._

import TermGeneratorNodes._
import provingground.learning.Sort.All
import provingground.learning.Sort.Filter
import provingground.learning.Sort.Restrict
import provingground.interface.ContextJson

object TermRandomVars {

  case object TypOpt extends (Term => Option[Typ[Term]]) {
    def apply(t: Term): Option[Typ[Term]] = typOpt(t)

    override def toString = "TypOpt"
  }

  case object TypAsTermOpt extends (Typ[Term] => Option[Term]) {
    def apply(t: Typ[Term]): Option[Term] = Some(t)

    override def toString = "TypAsTermOpt"
  }

  case object FuncOpt extends (Term => Option[ExstFunc]) {
    def apply(t: Term): Option[ExstFunc] = ExstFunc.opt(t)

    override def toString = "FuncOpt"
  }

  case object TypFamilyOpt extends (Term => Option[ExstFunc]) {
    def apply(t: Term): Option[ExstFunc] =
      ExstFunc.opt(t).filter((fn) => isTypFamily(fn.func))

    override def toString = "TypFamilyOpt"
  }

  case class FuncWithDom(dom: Typ[Term]) extends (Term => Option[ExstFunc]) {
    def apply(t: Term): Option[ExstFunc] =
      ExstFunc.opt(t).filter((fn) => fn.dom == dom)

    override def toString = s"FuncWithDom($dom)"
  }

  case class FuncWithDomFilter(dom: Typ[Term]) extends (ExstFunc => Boolean) {
    def apply(v1: HoTT.ExstFunc): Boolean = v1.dom == dom

    override def toString = s"FuncWithDomFilter($dom)"
  }

  case class WithTyp(typ: Typ[Term]) extends (Term => Boolean) {
    def apply(t: Term): Boolean = t.typ == typ

    override def toString = s"$WithTyp(typ)"
  }

  case object TypFn extends (Term => Typ[Term]) {
    def apply(tp: Term): Typ[Term] = tp.typ

    override def toString = "typeOf(_)"
  }

  case object DomFn extends (ExstFunc => Typ[Term]) {
    def apply(fn: ExstFunc): Typ[Term] = fn.dom

    override def toString = "domOf"
  }

  /**
    * distribution of terms
    */
  case object Terms extends RandomVar[Term]

  /**
    * distribution of types
    */
  case object Typs extends RandomVar[Typ[Term]]

  /**
    * distribution of functions : as existentials (wrapping terms), not as terms
    */
  case object Funcs extends RandomVar[ExstFunc]

  /**
    * family of distributions of terms with specified type
    */
  case object TermsWithTyp
      extends RandomVar.SimpleFamily[Typ[Term], Term](
        Typs,
        (typ: Typ[Term]) => Sort.Filter[Term](WithTyp(typ))
      ) {
    def unapply(x: Any): Option[Typ[Term]] = x match {
      case RandomVar.AtCoord(fmly, (typ: Typ[Term]) :: HNil)
          if fmly == TermsWithTyp =>
        Some(typ)
      case _ => None
    }
  }

  /**
    * distribution of terms with a specific type
    *
    * @param typ the type
    * @return distribution at type
    */
  def termsWithTyp(typ: Typ[Term]): RandomVar[Term] =
    RandomVar.AtCoord(TermsWithTyp, typ :: HNil)

  /**
    * Wrapper for terms with type family to allow equality and  `toString` to work.
    */
  case object TermsWithTypFn extends (Typ[Term] => RandomVar[Term]) {
    def apply(typ: Typ[Term]) = RandomVar.AtCoord(TermsWithTyp, typ :: HNil)

    override def toString = "TermsWithTypFn"
  }

  /**
    * distribution of type families
    */
  case object TypFamilies extends RandomVar[ExstFunc]

  val typFamilySort: Sort[Term, ExstFunc] =
    Sort.Restrict[Term, ExstFunc](TypFamilyOpt)

  /**
    * distribution of types and type families
    */
  case object TypsAndFamilies extends RandomVar[Term] {
    lazy val fromTyp: Map[Typ[Term], Term] =
      Map[Typ[Term], Term](Idty(), Typs, TypsAndFamilies)

    lazy val fromFamilies: Map[ExstFunc, Term] =
      Map[ExstFunc, Term](ExstFunc.GetFunc, TypFamilies, TypsAndFamilies)
  }

  case object Negate extends (Typ[Term] => Typ[Term]) {
    def apply(v1: HoTT.Typ[HoTT.Term]): HoTT.Typ[HoTT.Term] = negate(v1)

    override def toString(): String = "Negate"
  }

  /**
    * distribution of types to target for generating terms; either a generated type or a goal.
    */
  case object TargetTyps extends RandomVar[Typ[Term]] {
    def fromGoal: Map[Typ[Term], Typ[Term]] = Map(Idty(), Goals, TargetTyps)

    def fromTyp: Map[Typ[Term], Typ[Term]] = Map(Idty(), Typs, TargetTyps)

    def fromNegTyp: Map[Typ[Term], Typ[Term]] = Map(Negate, Typs, TargetTyps)
  }

  case object IsleDomains extends RandomVar[Typ[Term]]

  val typSort: Sort[Term, Typ[Term]] = Sort.Restrict[Term, Typ[Term]](TypOpt)

  case object Goals extends RandomVar[Typ[Term]]

  case class ContextTerms(ctx: Context) extends RandomVar[Term]

  case class ContextTyps(ctx: Context) extends RandomVar[Typ[Term]]

  def contextTermNode(ctx: Context): GeneratorNode[Term] =
    Island[Term, TermState, Term, Unit](
      ContextTerms(ctx),
      (_) => Terms,
      ts => (varWeight: Double) => (ts.contextInit(ctx, varWeight), ()),
      { case (_, term) => ctx.export(term) },
      { case (_, ts)   => ts.contextImport(ctx) }
    )

  case class PiOutput[U <: Term with Subs[U], V <: Term with Subs[V]](
      pd: PiDefn[U, V]
  ) extends (Term => RandomVar[Term]) {
    def apply(x: Term): RandomVar[Term] =
      termsWithTyp(pd.fibers(x.asInstanceOf[U]))

    override def toString(): String = s"PiOutput($pd)"
  }

  def withTypSort(typ: Typ[Term]): Sort[Term, Term] =
    Sort.Filter[Term](WithTyp(typ))

  case object WithTypSort extends (Typ[Term] => Sort[Term, Term]) {
    def apply(v1: HoTT.Typ[HoTT.Term]): Sort[HoTT.Term, HoTT.Term] =
      withTypSort(v1)

    override def toString(): String = "WithTypSort"
  }

  def withTypNode(
      node: GeneratorNode[Term]
  ): GeneratorNodeFamily[Typ[Term] :: HNil, Term] =
    node.pi(WithTypSort, TermsWithTyp)

  /**
    * family of distribution of (existential) functions with specifed domain.
    */
  case object FuncsWithDomain
      extends RandomVar.SimpleFamily[Typ[Term], ExstFunc](
        Typs,
        (typ: Typ[Term]) => Sort.Filter[ExstFunc](FuncWithDomFilter(typ))
      )

  // def funcWithDomSort(dom: Typ[Term]): Sort.Filter[ExstFunc] =
  //   Sort.Filter[ExstFunc](_.dom == dom)

  // def funcWithDomNode(
  //     node: GeneratorNode[ExstFunc]
  // ): GeneratorNodeFamily[Typ[Term] :: HNil, ExstFunc] =
  //   node.pi(funcWithDomSort, FuncsWithDomain)

  case object RestrictFuncWithDom
      extends (Typ[Term] => Sort.Restrict[Term, ExstFunc]) {
    def apply(v1: HoTT.Typ[HoTT.Term]): Restrict[HoTT.Term, HoTT.ExstFunc] =
      Sort.Restrict[Term, ExstFunc](FuncWithDom(v1))

    override def toString(): String = "RestrictFuncWithDom"
  }

  def funcWithDomTermNode(
      node: GeneratorNode[Term]
  ): GeneratorNodeFamily[::[Typ[Term], HNil], ExstFunc] =
    node.pi(
      RestrictFuncWithDom,
      FuncsWithDomain
    )

  /**
    * distribution of functions with a specified domain
    *
    * @param typ the domain
    * @return distribution at domain
    */
  def funcsWithDomain(typ: Typ[Term]): RandomVar[ExstFunc] =
    RandomVar.AtCoord(FuncsWithDomain, typ :: HNil)

  case object FuncsWithDomainFn extends (Typ[Term] => RandomVar[ExstFunc]) {
    def apply(typ: Typ[Term]) = RandomVar.AtCoord(FuncsWithDomain, typ :: HNil)

    override def toString = "FuncsWithDomainFn"
  }

  case object DomForInduc
      extends RandomVar.SimpleFamily[ExstInducDefn, Term](
        InducDefns
      )

  def domForInduc(defn: ExstInducDefn) =
    RandomVar.AtCoord(DomForInduc, defn :: HNil)

  case object FuncForCod
      extends RandomVar.SimpleFamily[Typ[Term], Term](
        Typs
      )

  def funcForCod(cod: Typ[Term]) =
    RandomVar.AtCoord(FuncForCod, cod :: HNil)

  /**
    * distribution of existential inductive structures
    */
  case object InducStrucs extends RandomVar[ExstInducStrucs]

  /**
    * distribution of existential inductive definitions
    */
  case object InducDefns extends RandomVar[ExstInducDefn]

  case class AtomVar[U](atom: U) extends RandomVar[U]

  case class FuncFoldVar(func: Term, depth: Int) extends RandomVar[Term]

  /**
    * distribution of introduction rules for an inductive type
    *
    * @param inductiveTyp the inductive type being defined
    */
  case class IntroRuleTypes(inductiveTyp: Typ[Term])
      extends RandomVar[Typ[Term]]

  /**
    * the introduction with just the target type
    *
    * @param inductiveTyp the inductive type being defined
    * @return node for inclusion
    */
  def inducHeadNode(inductiveTyp: Typ[Term]): Atom[Typ[Term]] =
    just(inductiveTyp, IntroRuleTypes(inductiveTyp))

  /**
    * distribution of `f`, `f(x)`, `f(x)(y)` etc
    *
    * @param func the function to apply
    */
  case class PartiallyApplied(func: Term) extends RandomVar[Term]

  /**
    * atomic distribution `f` for partial application
    *
    * @param f the function
    * @return node to include
    */
  def partiallyApplySelf(f: Term): Atom[Term] =
    just(f, PartiallyApplied(f))

  /**
    * iterated function types targeting a given type, typically used in introduction rules
    *
    * @param typ the final type
    */
  case class IterFuncTypTo(typ: Typ[Term]) extends RandomVar[Typ[Term]]

  /**
    * type family types, e.g. `A -> Type`, for indexed induction
    */
  val typFamilyTypes: RandomVar[Term] = IterFuncTypTo(Type)

  /**
    * distribution of types obtained by full application in a type family
    *
    * @param typF the type family
    */
  case class TypsFromFamily(typF: Term) extends RandomVar[Typ[Term]]

  /**
    * distribution of introduction rules for an indexed inductive type
    *
    * @param typF the type family
    */
  case class IndexedIntroRuleTyps(typF: Term) extends RandomVar[Typ[Term]]

  /**
    * iterated function type targetting a fully applied type family
    *
    * @param typF the type family
    */
  case class IndexedIterFuncTypTo(typF: Term) extends RandomVar[Typ[Term]]

  import shapeless._, GeneratorVariables._
  // Substituting terms in variables
  def valueSubs[U](x: Term, y: Term)(value: U): U = value match {
    case t: Term      => t.replace(x, y).asInstanceOf[U]
    case fn: ExstFunc => ExstFunc(fn.func.replace(x, y)).asInstanceOf[U]
    case l: HList =>
      l match {
        case head :: tail =>
          (valueSubs(x, y)(head) :: valueSubs(x, y)(tail)).asInstanceOf[U]
        case HNil => HNil.asInstanceOf[U]
      }
    case u => u
  }

  def randomVarSubs[U](x: Term, y: Term)(rv: RandomVar[U]): RandomVar[U] =
    rv match {
      case RandomVar.AtCoord(family, fullArg) =>
        RandomVar.AtCoord(family, valueSubs(x, y)(fullArg))
      case rv => rv
    }

  def sortSubs[U, V](x: Term, y: Term)(sort: Sort[U, V]): Sort[U, V] =
    sort match {
      case All() => sort
      case filter: Filter[U] =>
        val newPred =
          filter.pred match {
            case WithTyp(typ) =>
              WithTyp(typ.replace(x, y)).asInstanceOf[U => Boolean]
            case _ => (z: U) => filter.pred(valueSubs(y, x)(z))
          }
        Filter[U](newPred)
          .asInstanceOf[Sort[U, V]]
      case Restrict(optMap) =>
        val newOptMap = optMap match {
          case TypOpt       => TypOpt.asInstanceOf[U => Option[V]]
          case TypAsTermOpt => TypAsTermOpt.asInstanceOf[U => Option[V]]
          case FuncOpt      => FuncOpt.asInstanceOf[U => Option[V]]
          case TypFamilyOpt => TypFamilyOpt.asInstanceOf[U => Option[V]]
          case FuncWithDom(typ) =>
            FuncWithDom(typ.replace(x, y)).asInstanceOf[U => Option[V]]
          case _ =>
            (z: U) => optMap(valueSubs(y, x)(z)).map(w => valueSubs(x, y)(w))
        }
        Restrict(
          newOptMap
        )
    }

  def isleSub[c, d](x: Term, y: Term)(
      isle: Island[c, TermState, d, Term],
      boat: Term
  ): Island[c, TermState, d, Term] = {
    val newInit =
      AddVar(boat.typ.replace(x, y))
    val newIsleOutput = isle.islandOutput match {
      case ConstRandVar(randomVar) =>
        ConstRandVar(randomVarSubs(x, y)(randomVar))
      case PiOutput(pd: PiDefn[u, v]) =>
        PiOutput(pd.replace(x, y)).asInstanceOf[Term => RandomVar[d]]
      case _ =>
        Utils.baseLogger.warn(
          s"creating lambda random variable by substitution  for ${isle.islandOutput} in $isle; $boat gives ${isle
            .islandOutput(boat)}"
        )
        (z: Term) => randomVarSubs(x, y)(isle.islandOutput(z))
    }
    Island[c, TermState, d, Term](
      randomVarSubs(x, y)(isle.output),
      newIsleOutput,
      newInit,
      isle.export,
      isle.finalMap
    )

  }

  def variableSubs[Y](
      x: Term,
      y: Term
  )(v: Variable[Y]): Variable[Y] =
    if (x == y) v
    else
      (v: Variable[Y]) match {
        case Elem(element, randomVar) =>
          Elem(valueSubs(x, y)(element), randomVarSubs(x, y)(randomVar))
        case ev: Event[a, b] =>
          val newBase             = randomVarSubs(x, y)(ev.base)
          val newSort: Sort[a, b] = sortSubs(x, y)(ev.sort)
          Event(newBase, newSort)
        case inIsleFull: InIsle[c, cc, _, d, _] =>
          val inIsleTry =
            Try(inIsleFull.asInstanceOf[InIsle[c, cc, TermState, d, Term]])
          inIsleTry.fold(
            fa => inIsleFull,
            inIsle => {
              import inIsle._
              val newBoat    = boat.replace(x, y)
              val newIsleVar = variableSubs(x, y)(isleVar)
              val newIsle    = isleSub(x, y)(isle, boat)
              InIsle(newIsleVar, newBoat, newIsle)
            }
          )

        case PairEvent(base1, base2, sort) =>
          PairEvent(
            randomVarSubs(x, y)(base1),
            randomVarSubs(x, y)(base2),
            sortSubs(x, y)(sort)
          )
      }

  def isleNormalizeVars[Y](
      v: GeneratorVariables.Variable[Y],
      vars: Vector[Term]
  ): GeneratorVariables.Variable[Y] =
    v match {
      case Elem(element, randomVar) => v
      case Event(base, sort)        => v
      case inIsleFull: InIsle[c, y, _, d, _] =>
        val inIsleTry =
          Try(inIsleFull.asInstanceOf[InIsle[c, Y, TermState, d, Term]])
        inIsleTry.fold(
          fa => inIsleFull,
          inIsle => {
            import inIsle._
            val newBoat = nextVar(boat.typ, vars)
            val newIsleVar = variableSubs(boat, newBoat)(
              isleNormalizeVars(isleVar, vars :+ newBoat)
            )
            val newIsle = isleSub(boat, newBoat)(isle, boat)
            InIsle(newIsleVar, newBoat, newIsle)
          }
        )
      case PairEvent(base1, base2, sort) => v
    }

  import Expression._

  def expressionMapVars(
      fn: VariableMap
  )(exp: Expression): Expression = exp match {
    case FinalVal(variable)   => FinalVal(fn(variable))
    case InitialVal(variable) => InitialVal(fn(variable))
    case Sum(xs) =>
      Sum(
        xs.map(x => expressionMapVars(fn)(x))
      )
    case IsleScale(boat: Term) =>
      val newBoat = "%boat" :: boat.typ
      IsleScale(
        newBoat
      )
    case IsleScale(boat) => IsleScale(boat)
    case Log(exp)        => Log(expressionMapVars(fn)(exp))
    case Literal(value)  => Literal(value)
    case Exp(exp)        => Exp(expressionMapVars(fn)(exp))
    case Coeff(node)     => Coeff(node)
    case Quotient(x, y) =>
      Quotient(
        expressionMapVars(fn)(x),
        expressionMapVars(fn)(y)
      )
    case provingground.learning.Expression.Product(x, y) =>
      Product(
        expressionMapVars(fn)(x),
        expressionMapVars(fn)(y)
      )
  }

  def expressionSubs(x: Term, y: Term)(exp: Expression): Expression =
    if (x == y) exp
    else
      exp match {
        case FinalVal(variable)   => FinalVal(variableSubs(x, y)(variable))
        case InitialVal(variable) => InitialVal(variableSubs(x, y)(variable))
        case Product(a, b) =>
          Product(
            expressionSubs(x, y)(a),
            expressionSubs(x, y)(b)
          )
        case Quotient(a, b) =>
          Quotient(
            expressionSubs(x, y)(a),
            expressionSubs(x, y)(b)
          )
        case Exp(exp) =>
          Exp(expressionSubs(x, y)(exp))
        case Literal(value) => Literal(value)
        case Log(exp) =>
          Log(expressionSubs(x, y)(exp))
        case sc: IsleScale[u, v] =>
          IsleScale(
            valueSubs(x, y)(sc.boat)
          )
        case cf @ Coeff(node) => cf
        case Sum(xs) =>
          Sum(
            xs.map(a => expressionSubs(x, y)(a))
          )
      }

  def isleNormalizeVarExp[Y](
      v: GeneratorVariables.Variable[Y],
      rhs: Expression,
      vars: Vector[Term]
  ): (GeneratorVariables.Variable[Y], Expression) =
    v match {
      case Elem(element, randomVar) =>
        val fn =
          new Expression.VariableMap {
            def apply[Y](
                arg: GeneratorVariables.Variable[Y]
            ): GeneratorVariables.Variable[Y] =
              TermRandomVars.isleNormalizeVars(arg, Vector())
          }
        // (v: GeneratorVariables.Variable[Y])  => TermRandomVars.isleNormalizeVars(v,Vector())
        v -> expressionMapVars(fn)(rhs)
      case Event(base, sort) =>
        val fn =
          new Expression.VariableMap {
            def apply[Y](
                arg: GeneratorVariables.Variable[Y]
            ): GeneratorVariables.Variable[Y] =
              TermRandomVars.isleNormalizeVars(arg, Vector())
          }
        v -> expressionMapVars(fn)(rhs)
      case inIsleFull: InIsle[c, cc, _, d, _] =>
        val inIsleTry =
          Try(inIsleFull.asInstanceOf[InIsle[c, cc, TermState, d, Term]])
        inIsleTry.fold(
          fa => inIsleFull -> rhs,
          inIsle => {
            import inIsle._
            val newBoat = nextVar(boat.typ, vars)
            val (recIsleVar, recRhs) =
              isleNormalizeVarExp(isleVar, rhs, vars :+ newBoat)
            val newIsleVar = variableSubs(boat, newBoat)(recIsleVar)
            val newRhs =
              expressionSubs(boat, newBoat)(recRhs)
            val newIsle = isleSub(boat, newBoat)(isle, boat)
            InIsle(newIsleVar, newBoat, newIsle) -> newRhs
          }
        )
      case PairEvent(base1, base2, sort) =>
        val fn =
          new Expression.VariableMap {
            def apply[Y](
                arg: GeneratorVariables.Variable[Y]
            ): GeneratorVariables.Variable[Y] =
              TermRandomVars.isleNormalizeVars(arg, Vector())
          }
        v -> expressionMapVars(fn)(rhs)
    }

  def isleNormalize(eq: EquationNode, varWeight: Double = 0.3): EquationNode = {
    val fn =
      new Expression.VariableMap {
        def apply[Y](
            arg: GeneratorVariables.Variable[Y]
        ): GeneratorVariables.Variable[Y] =
          TermRandomVars.isleNormalizeVars(arg, Vector())
      }
    eq.lhs match {
      case InitialVal(variable) =>
        val (newVar, newRhs) = isleNormalizeVarExp(variable, eq.rhs, Vector())
        EquationNode(InitialVal(newVar), newRhs)
      case FinalVal(variable) =>
        val (newVar, newRhs) = isleNormalizeVarExp(variable, eq.rhs, Vector())
        EquationNode(FinalVal(newVar), newRhs)
      case _ =>
        EquationNode(
          expressionMapVars(fn)(eq.lhs),
          expressionMapVars(fn)(eq.rhs)
        )
    }

  }

  def varDepends(t: Term)(v: Variable[_]): Boolean =
    v match {
      case Elem(element: Term, randomVar) => element.dependsOn(t)
      case Elem(fn: ExstFunc, _)          => fn.func.dependsOn(t)
      case Elem(element, randomVar)       => false
      case Event(base, sort)              => false
      case InIsle(isleVar, boat, isle)    => varDepends(t)(isleVar)
      case PairEvent(base1, base2, sort)  => false
    }

  def equationDepends(t: Term)(eq: Equation): Boolean = {
    import Expression.varVals
    val genvars = varVals(eq.lhs).map(_.variable) union varVals(eq.lhs)
      .map(_.variable)
    genvars.exists(v => varDepends(t)(v))
  }

  def equationNodeDepends(t: Term)(eq: EquationNode): Boolean = {
    import Expression.varVals
    val genvars = varVals(eq.lhs).map(_.variable) union varVals(eq.rhs)
      .map(_.variable)
    genvars.exists(v => varDepends(t)(v))
  }

  val randomVarStrings: Vector[(RandomVar[_], String, String)] =
    Vector(
      (Funcs, "funcs", "func"),
      (Terms, "terms", "term"),
      (Typs, "types", "typ"),
      (TargetTyps, "target-types", "typ"),
      (Goals, "goals", "typ"),
      (TypFamilies, "type-families", "term"),
      (TypsAndFamilies, "types-and-families", "term"),
      (InducDefns, "induc-defns", "induc-defn"),
      (InducStrucs, "induc-structs", "induc-struc"),
      (IsleDomains, "isle-domains", "typs")
    )

  val rvStrMap = randomVarStrings.map { case (x, y, _) => (x, y) }.toMap

  val rvElemMap = randomVarStrings.map { case (x, _, y) => (x, y) }.toMap

  val strRvMap = randomVarStrings.map { case (x, y, _) => y -> x }.toMap

  import ujson._, provingground.interface.TermJson.{termToJson, jsonToTerm}
  import provingground.interface.InducJson._

  def randomVarToJson[X](rv: RandomVar[X]): ujson.Value =
    rv match {
      case AtomVar(atom: Term) =>
        Obj(
          "family"    -> Str("atom"),
          "atom"      -> termToJson(atom).get,
          "elem-type" -> "term"
        )
      case ContextTerms(ctx) =>
        Obj(
          "family"    -> "context-terms",
          "ctx"       -> ContextJson.toJson(ctx),
          "elem-type" -> "term"
        )
      case ContextTyps(ctx) =>
        Obj(
          "family"    -> "context-typs",
          "ctx"       -> ContextJson.toJson(ctx),
          "elem-type" -> "term"
        )
      case FuncFoldVar(func, depth) =>
        Obj(
          "family"    -> "func-fold-var",
          "func"      -> termToJson(func),
          "depth"     -> Num(depth),
          "elem-type" -> "term"
        )
      case IndexedIntroRuleTyps(typF) =>
        Obj(
          "family"    -> "indexed-intro-rules-typ",
          "typF"      -> termToJson(typF),
          "elem-type" -> "typ"
        )
      case IndexedIterFuncTypTo(typF) =>
        Obj(
          "family"    -> "indexed-iter-func-typ-to",
          "typF"      -> termToJson(typF),
          "elem-type" -> "typ"
        )
      case IntroRuleTypes(inductiveTyp) =>
        Obj(
          "family"        -> "intro-rules-typ",
          "inductive-typ" -> termToJson(inductiveTyp),
          "elem-type"     -> "typ"
        )
      case IterFuncTypTo(typ) =>
        Obj(
          "family"    -> "iter-func-typ-to",
          "typF"      -> termToJson(typ),
          "elem-type" -> "typ"
        )
      case PartiallyApplied(func) =>
        Obj(
          "family"    -> "partially-applied",
          "func"      -> termToJson(func),
          "elem-type" -> "term"
        )
      case TypsFromFamily(typF) =>
        Obj(
          "family"    -> "types-from-family",
          "typF"      -> termToJson(typF),
          "elem-type" -> "typ"
        )
      case RandomVector(base) =>
        Obj(
          "family"    -> "vector",
          "base"      -> randomVarToJson(base),
          "elem-type" -> "vector"
        )
      case RandomVar
            .AtCoord(rvF: RandomVarFamily[v, u], (head: Term) :: tail) =>
        rvF match {
          case TermsWithTyp =>
            Obj(
              "family"    -> "terms-with-type",
              "coord"     -> termToJson(head),
              "elem-type" -> "term"
            )
          case FuncsWithDomain =>
            Obj(
              "family"    -> "funcs-with-domain",
              "coord"     -> termToJson(head),
              "elem-type" -> "func"
            )
          case FuncForCod =>
            Obj(
              "family"    -> "funcs-for-cod",
              "coord"     -> termToJson(head),
              "elem-type" -> "term"
            )

        }
      case RandomVar.AtCoord(rvF, (head: ExstInducDefn) :: tail)
          if rvF == DomForInduc =>
        Obj(
          "family" -> "dom-for-induc",
          "coord"  -> upickle.default.write(head)
        )

      case randVar =>
        Obj("family" -> "single", "value" -> Str(rvStrMap(randVar)))
    }

  def jsonToRandomVar(json: ujson.Value): RandomVar[_] = {
    val obj               = json.obj
    val family            = obj("family").str
    def termAt(s: String) = jsonToTerm()(obj(s)).get
    family match {
      case "atom"          => jsonToRandomVar(obj("atom"))
      case "context-terms" => ContextTerms(ContextJson.fromJson(obj("ctx")))
      case "context-typs"  => ContextTyps(ContextJson.fromJson(obj("ctx")))
      case "func-fold-var" =>
        FuncFoldVar(termAt("func"), obj("depth").num.toInt)
      case "indexed-intro-rules-typ"  => IndexedIntroRuleTyps(termAt("typF"))
      case "indexed-iter-func-typ-to" => IndexedIterFuncTypTo(termAt("typF"))
      case "intro-rules-typ"          => IntroRuleTypes(toTyp(termAt("inductive-typ")))
      case "iter-func-typ-to"         => IterFuncTypTo(toTyp(termAt("typF")))
      case "partially-applied"        => PartiallyApplied(termAt("func"))
      case "types-from-family"        => TypsFromFamily(termAt("typF"))
      case "vector"                   => RandomVector(jsonToRandomVar(obj("base")))
      case "terms-with-type"          => termsWithTyp(toTyp(termAt("coord")))
      case "funcs-with-domain"        => funcsWithDomain(toTyp(termAt("coord")))
      case "funcs-for-cod"            => funcForCod(toTyp(termAt("coord")))
      case "dom-for-induc" =>
        domForInduc(upickle.default.read[ExstInducDefn](obj("coord")))
      case "single" => strRvMap(obj("value").str)

    }
  }

  def variableToTermInContext[Y](
      v: Variable[Y],
      baseCondition: RandomVar[_] => Boolean
  ): Option[(Term, Vector[Term])] =
    v match {
      case Elem(element: Term, randomVar) =>
        if (baseCondition(randomVar)) Some((element, Vector())) else None
      case Event(base, sort)             => None
      case PairEvent(base1, base2, sort) => None
      case InIsle(isleVar, boat: Term, isle) =>
        variableToTermInContext(isleVar, baseCondition).map {
          case (t, ctx) => (t, boat +: ctx)
        }
      case _ => None
    }

}


text:
function logger(label, data, level) {
    level || (level = "debug");
    "debug" === level ? Ti.API.debug("[URBANAIRPORT] " + label + (data ? ": " + JSON.stringify(data, null, "	") : "")) : Ti.API.error("[URBANAIRPORT] " + label + (data ? ": " + JSON.stringify(data, null, "	") : ""));
}

function caller(e) {
    _.isFunction(callback) && callback(e);
}

var _ = _ || require("alloy")._, OS_IOS = true, OS_ANDROID = !OS_IOS && false;

var urbanairship = require("ti.urbanairship");

Ti.API.info("module is => " + urbanairship);

var callback, sound = true, debug = true;

if (OS_ANDROID) var pendingTags = null, pendingAlias = null, compatibility = false, compatibilityStack = [], vibrate = true;

if (OS_IOS) var alert = true, badge = true;

urbanairship.register = function(config) {
    if (config) {
        (debug || false !== config.debug) && logger("INIT", config);
        var that = this;
        _.each(config, function(val, key) {
            switch (key) {
              case "callback":
                callback = val;
                break;

              case "debug":
                debug = !!val;
                break;

              case "compatibility":
                if (OS_ANDROID) {
                    compatibility = !!val;
                    "undefined" == typeof config.showOnAppClick && (that.showOnAppClick = compatibility);
                }
                break;

              case "options":
                OS_IOS && (that.options = val);
                break;

              case "tags":
                that.resetTags(val);
                break;

              case "alias":
                that.resetAlias(val);
                break;

              case "sound":
                sound = !!val;
                break;

              case "vibrate":
                OS_ANDROID && (vibrate = !!val);
                break;

              case "badge":
                OS_IOS && (badge = !!val);
                break;

              case "alert":
                OS_IOS && (alert = !!val);
                break;

              default:
                if ("undefined" != typeof that[key]) if (_.isFunction(that[key])) {
                    that[key](val);
                    logger("calling " + key, val);
                } else {
                    that[key] = val;
                    logger("setting " + key, val);
                }
            }
        });
    }
    this.enable();
    return this;
};

urbanairship.resetTags = function(tags) {
    "string" == typeof tags && (tags = [ tags ]);
    if (OS_ANDROID && !this.isFlying) {
        pendingTags = tags;
        return;
    }
    this.tags = tags;
    return this;
};

urbanairship.addTags = function(tags) {
    "string" == typeof tags && (tags = [ tags ]);
    if (OS_ANDROID && !this.isFlying) {
        pendingTags = _.union(pendingTags || [], tags);
        return;
    }
    this.tags = _.union(this.tags || [], tags);
    return this;
};

urbanairship.removeTags = function(tags) {
    "string" == typeof tags && (tags = [ tags ]);
    if (OS_ANDROID && !this.isFlying) {
        pendingTags = _.difference(pendingTags || [], tags);
        return;
    }
    this.tags = _.difference(this.tags || [], tags);
    return this;
};

urbanairship.resetAlias = function(alias) {
    if (OS_ANDROID && !this.isFlying) {
        pendingAlias = alias;
        return;
    }
    this.alias = alias;
    return this;
};

urbanairship.enable = function() {
    var that = this;
    if (OS_IOS) {
        var types = [];
        badge && types.push(Ti.Network.NOTIFICATION_TYPE_BADGE);
        alert && types.push(Ti.Network.NOTIFICATION_TYPE_ALERT);
        sound && types.push(Ti.Network.NOTIFICATION_TYPE_SOUND);
        Ti.Network.registerForPushNotifications({
            types: types,
            success: function(e) {
                logger("SUCCESS", e);
                that.registerDevice(e.deviceToken);
                e.type = "success";
                e.valid = e.success;
                caller(e);
            },
            error: function(e) {
                logger("ERROR", e);
                e.type = "error";
                e.valid = e.success;
                caller(e);
            },
            callback: function(e) {
                logger("CALLBACK", e);
                that.handleNotification(e.data);
                e.type = "callback";
                e.clicked = e.inBackground;
                e.message = e.data.aps.alert;
                e.payload = e.data.aps;
                caller(e);
            }
        });
    }
    OS_ANDROID && (that.pushEnabled = true);
    return this;
};

urbanairship.disable = function() {
    OS_IOS && this.unregisterDevice();
    OS_ANDROID && (this.pushEnabled = false);
    return this;
};

if (OS_ANDROID) {
    urbanairship.addEventListener(urbanairship.EVENT_URBAN_AIRSHIP_SUCCESS, function(e) {
        logger("SUCCESS", e);
        if (null !== pendingAlias) {
            urbanairship.alias = pendingAlias;
            pendingAlias = null;
        }
        if (null !== pendingTags) {
            urbanairship.tags = pendingTags;
            pendingTags = null;
        }
        e.type = "success";
        e.success = e.valid;
        caller(e);
    });
    urbanairship.addEventListener(urbanairship.EVENT_URBAN_AIRSHIP_ERROR, function(e) {
        logger("ERROR", e);
        e.type = "error";
        e.success = e.valid;
        caller(e);
    });
    urbanairship.addEventListener(urbanairship.EVENT_URBAN_AIRSHIP_CALLBACK, function(e) {
        logger("CALLBACK", e);
        if (compatibility) {
            var hash = Ti.Utils.sha1(JSON.stringify([ e.payload, e.message ]));
            if (-1 !== compatibilityStack.indexOf(hash)) return;
            compatibilityStack.push(hash);
        }
        e.type = "callback";
        if (e.payload) try {
            var json = e.payload.replace(/\{/g, '{"').replace(/=/g, '":"').replace(/, /g, '","').replace(/\}/g, '"}');
            e.payload = JSON.parse(json);
        } catch (err) {
            logger("CALLBACK PAYLOAD", err, "error");
            e.payload = {};
        }
        e.inBackground = null;
        e.data = e.payload || {};
        e.data.alert = e.message;
        e.data.aps = e.data;
        caller(e);
    });
}

module.exports = urbanairship;


text:
from mwclientcli.libs.command import Command

class Upload(Command):

    def __init__(self):
        Command.__init__(self)

        self.name = 'upload'
        self.help = 'Upload a file'

    def init_parser(self, subparsers):
        Command.init_parser(self, subparsers)

        self.parser.add_argument('file', nargs='?', help='Path to the local file')
        self.parser.add_argument('description', nargs='?', help='File description')

    def process(self):
        self.site.upload(self.args.file, self.args.description)


text:
import React from 'react';
import { mount } from 'enzyme';
import renderer from 'react-test-renderer';
import SimpleWrapper from './SimpleWrapper';

describe('SimpleWrapper', () => {
  let wrapper;
  beforeEach(() => {
    wrapper = mount(<SimpleWrapper key={Date.now()}>
Dummy
</SimpleWrapper>);
  });
  it('Render the component', () => {
    expect(wrapper.find('div').length).toEqual(1);
  });
  it('Matchs snapshot', () => {
    const tree = renderer.create(wrapper).toJSON();
    expect(tree).toMatchSnapshot();
  });
});


text:
package org.wildfly.security;

import java.security.GeneralSecurityException;

/**
 * A factory for preconfigured security objects.
 *
 * @author David M. Lloyd
 */
public interface SecurityFactory<T> {

    /**
     * Create an instance.
     *
     * @return the new instance
     * @throws GeneralSecurityException if instantiation fails for some reason
     */
    T create() throws GeneralSecurityException;
}


text:
r"""*Nonlocal CLI tests for* ``sphobjinv``.

``sphobjinv`` is a toolkit for manipulation and inspection of
Sphinx |objects.inv| files.

**Author**
    Brian Skinn (brian.skinn@gmail.com)

**File Created**
    20 Mar 2019

**Copyright**
    \(c) Brian Skinn 2016-2022

**Source Repository**
    http://www.github.com/bskinn/sphobjinv

**Documentation**
    https://sphobjinv.readthedocs.io/en/stable

**License**
    Code: `MIT License`_

    Docs & Docstrings: |CC BY 4.0|_

    See |license_txt|_ for full license terms.

**Members**

"""

import json
import re

import pytest
from stdio_mgr import stdio_mgr

from sphobjinv import Inventory

CLI_TEST_TIMEOUT = 5

p_instance_of = re.compile("^.*instance_of.*$", re.M)
p_inventory = re.compile("^.*nventory.*$", re.I | re.M)

pytestmark = [pytest.mark.cli, pytest.mark.nonloc]

@pytest.fixture(scope="module", autouse=True)
def skip_if_no_nonloc(pytestconfig):
    """Skip test if --nonloc not provided.

    Auto-applied to all functions in module, since module is nonlocal.

    """
    if not pytestconfig.getoption("--nonloc"):
        pytest.skip("'--nonloc' not specified")  # pragma: no cover

class TestConvert:
    """Test nonlocal CLI convert mode functionality."""

    @pytest.mark.timeout(CLI_TEST_TIMEOUT * 4)
    def test_cli_convert_from_url_with_dest(
        self, scratch_path, misc_info, run_cmdline_test, monkeypatch
    ):
        """Confirm CLI URL D/L, convert works w/outfile supplied."""
        monkeypatch.chdir(scratch_path)

        dest_path = scratch_path / (misc_info.FNames.MOD + misc_info.Extensions.DEC)
        run_cmdline_test(
            [
                "convert",
                "plain",
                "-u",
                misc_info.remote_url.format("attrs"),
                str(dest_path),
            ]
        )

        assert dest_path.is_file()

    @pytest.mark.timeout(CLI_TEST_TIMEOUT * 4)
    def test_cli_convert_from_url_no_dest(
        self, scratch_path, misc_info, run_cmdline_test, monkeypatch
    ):
        """Confirm CLI URL D/L, convert works w/o outfile supplied."""
        monkeypatch.chdir(scratch_path)
        dest_path = scratch_path / (misc_info.FNames.INIT + misc_info.Extensions.DEC)
        dest_path.unlink()
        run_cmdline_test(
            ["convert", "plain", "-u", misc_info.remote_url.format("attrs")]
        )
        assert dest_path.is_file()

    @pytest.mark.timeout(CLI_TEST_TIMEOUT * 4)
    def test_cli_url_in_json(
        self, scratch_path, misc_info, run_cmdline_test, monkeypatch
    ):
        """Confirm URL is present when using CLI URL mode."""
        monkeypatch.chdir(scratch_path)
        dest_path = scratch_path / (misc_info.FNames.MOD + misc_info.Extensions.JSON)
        run_cmdline_test(
            [
                "convert",
                "json",
                "-u",
                misc_info.remote_url.format("attrs"),
                str(dest_path.resolve()),
            ]
        )

        d = json.loads(dest_path.read_text())

        assert "objects" in d.get("metadata", {}).get("url", {})

    @pytest.mark.timeout(CLI_TEST_TIMEOUT * 4)
    def test_clifail_bad_url(self, run_cmdline_test, misc_info, scratch_path):
        """Confirm proper error behavior when a bad URL is passed."""
        with stdio_mgr() as (in_, out_, err_):
            run_cmdline_test(
                [
                    "convert",
                    "plain",
                    "-u",
                    misc_info.remote_url.format("blarghers"),
                    str(scratch_path),
                ],
                expect=1,
            )
            assert "HTTP error: 404 Not Found." in err_.getvalue()

    @pytest.mark.timeout(CLI_TEST_TIMEOUT * 4)
    def test_clifail_url_no_leading_http(self, run_cmdline_test, scratch_path):
        """Confirm proper error behavior when a URL w/o leading 'http://' is passed."""
        with stdio_mgr() as (in_, out_, err_):
            run_cmdline_test(
                [
                    "convert",
                    "plain",
                    "-u",
                    "sphobjinv.readthedocs.io/en/latest",
                    str(scratch_path),
                ],
                expect=1,
            )
            assert "file found but inventory could not be loaded" in err_.getvalue()

    def test_cli_json_export_import(
        self, res_cmp, scratch_path, misc_info, run_cmdline_test, sphinx_load_test
    ):
        """Confirm JSON sent to stdout from local source imports ok."""
        inv_url = misc_info.remote_url.format("attrs")
        mod_path = scratch_path / (misc_info.FNames.MOD + misc_info.Extensions.CMP)

        with stdio_mgr() as (in_, out_, err_):
            run_cmdline_test(["convert", "json", "-u", inv_url, "-"])

            data = out_.getvalue()

        with stdio_mgr(data) as (in_, out_, err_):
            run_cmdline_test(["convert", "zlib", "-", str(mod_path.resolve())])

        assert Inventory(json.loads(data))
        assert Inventory(mod_path)
        sphinx_load_test(mod_path)

class TestSuggest:
    """Test nonlocal CLI suggest mode functionality."""

    @pytest.mark.timeout(CLI_TEST_TIMEOUT * 4)
    def test_cli_suggest_from_url(self, misc_info, run_cmdline_test):
        """Confirm reST-only suggest output works from URL."""
        with stdio_mgr() as (in_, out_, err_):
            run_cmdline_test(
                [
                    "suggest",
                    "-u",
                    misc_info.remote_url.format("attrs"),
                    "instance",
                    "-t",
                    "50",
                ]
            )
            assert p_instance_of.search(out_.getvalue())

    @pytest.mark.parametrize(
        "url",
        [
            "http://sphobjinv.readthedocs.io/en/v2.0/modules/",
            "http://sphobjinv.readthedocs.io/en/v2.0/modules/cmdline.html",
            (
                "http://sphobjinv.readthedocs.io/en/v2.0/modules/"
                "cmdline.html#sphobjinv.cmdline.do_convert"
            ),
        ],
    )
    @pytest.mark.timeout(CLI_TEST_TIMEOUT * 4)
    def test_cli_suggest_from_docset_urls(self, url, run_cmdline_test, check):
        """Confirm reST-only suggest output works from URLs within a docset."""
        with stdio_mgr() as (in_, out_, err_):
            run_cmdline_test(["suggest", "-u", url, "inventory", "-at", "50"])

            check.is_true(p_inventory.search(out_.getvalue()))
            check.is_in("LIKELY", err_.getvalue())
            check.is_in(
                "(http://sphobjinv.readthedocs.io/en/v2.0/, None)", err_.getvalue()
            )

    @pytest.mark.timeout(CLI_TEST_TIMEOUT * 4)
    def test_cli_suggest_from_typical_objinv_url(self, run_cmdline_test, check):
        """Confirm reST-only suggest works for direct objects.inv URL."""
        url = "http://sphobjinv.readthedocs.io/en/v2.0/objects.inv"
        with stdio_mgr() as (in_, out_, err_):
            run_cmdline_test(["suggest", "-u", url, "inventory", "-at", "50"])

            check.is_true(p_inventory.search(out_.getvalue()))
            check.is_in("PROBABLY", err_.getvalue())
            check.is_in(
                "(http://sphobjinv.readthedocs.io/en/v2.0/, None)", err_.getvalue()
            )

    @pytest.mark.timeout(CLI_TEST_TIMEOUT * 4)
    def test_cli_suggest_from_django_objinv_url(self, run_cmdline_test, check):
        """Confirm reST-only suggest works for direct objects.inv URL."""
        url = "https://docs.djangoproject.com/en/4.1/_objects/"
        with stdio_mgr() as (in_, out_, err_):
            run_cmdline_test(["suggest", "-u", url, "route", "-a"])

            check.is_true(re.search("DATABASE_ROUTERS", out_.getvalue()))
            check.is_in("Cannot infer intersphinx_mapping", err_.getvalue())


text:
{-# LANGUAGE CPP #-}

module Main where

import Control.Monad (unless)
import System.IO (hSetBuffering, BufferMode(NoBuffering), stdout)
import Text.Read (readMaybe)

#ifdef SOLUTION
import Solution (Hand, Score, score)
#else
import Codelab  (Hand, Score, score)
#endif

main :: IO ()
main = hSetBuffering stdout NoBuffering >> printHelp >> play

play :: IO ()
play = playTurn [] []

-- We play up to 3.
gameOver :: Score -> Bool
gameOver (s1, s2) = s1 >= 3 || s2 >= 3

-- Below is the impure IO code that lets us read hands from the standard
-- input and play the game!
-- Beware: Haskell 102 spoilers!
readHand :: String -> IO Hand
readHand prompt = do
  putStr prompt                         -- prints the prompt
  handText <- getLine                   -- reads one line of input
  case readMaybe handText of            -- tries to convert it to Hand
     Just h  -> return h                -- success: our result is h
     Nothing -> badMove prompt handText -- failure: we try again

playTurn :: [Hand] -> [Hand] -> IO ()
playTurn p1 p2 = do
  h1 <- readHand "p1: "
  h2 <- readHand "p2: "
  let p1' = h1 : p1
      p2' = h2 : p2
      newScore = score p1' p2'
  print newScore
  unless (gameOver newScore) $ playTurn p1' p2'

-- Helpers, again using Haskell 102 spoilers!
printHelp :: IO ()
printHelp = printHeader >> printMoves

printHeader :: IO ()
printHeader = do
  putStrLn "Welcome to Rock-Paper-Scissors!"
  putStrLn "-------------------------------"

printMoves :: IO ()
printMoves = do
  putStr "Each move is one of "
  putStrLn (show [minBound :: Hand ..])

badMove :: String -> String -> IO Hand
badMove prompt move = do
  putStr "Bad move: "
  putStrLn move
  printMoves
  readHand prompt


text:
+++
comments = true
date = "2016-09-26T22:17:00+00:00"
draft = false
noauthor = true
share = false

image = "media/eu.jpg"
backgroundposition = "top"

type = "about"

title = "About"

menu = "main"
menucolor = "black"
onehundredpercent = true
postfooter = false

+++

Hello, my name is Jon. I'm a software developer from Portugal. Here's a link to my [GitHub profile.](https://github.com/jongomez) Here's a link to my [Kaggle profile.](https://www.kaggle.com/jongomez)

This blog is mainly about coding, but I'll probably write about other stuff as well.

[Home](/)


text:
**References:**
- https://code.kx.com/q/ref/save/

Write a global variable to file.
writes global variable/s v etc. to file and returns the filename/s.

**Remarks:**
- **File path.**
    If a file
    - exists, it is overwritten
    - does not exist, it is created, with any required parent directories.
- **Format of the output file**

    The format used depends on the file extension:
    - `(none)`binary
    - `csv` comma-separated values
    - `txt` plain text
    - `xls` Excel spreadsheet
    - `xml` Extensible Markup Language (XML)

----------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------

~~~~
save x     save[x]
~~~~

Where `x` is a symbol atom or vector of the form `[path/to/]v[.ext]` in which
- `v` is the name of a global variable
- `path/to/` is a file path (optional)
- `.ext` is a file extension (optional)

----------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------

## Examples

t:([]x:2 3 5; y:`ibm`amd`intel; z:"npn")


text:
START_ATF_NAMESPACE
    typedef unsigned int DBCONVERTFLAGS;
END_ATF_NAMESPACE


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.run.v1.model;

/**
 * Cloud Run fully managed: not supported Cloud Run for Anthos: supported TCPSocketAction describes
 * an action based on opening a socket
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Cloud Run Admin API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class TCPSocketAction extends com.google.api.client.json.GenericJson {

  /**
   * (Optional) Cloud Run fully managed: not supported Cloud Run for Anthos: supported Optional:
   * Host name to connect to, defaults to the pod IP.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String host;

  /**
   * Cloud Run fully managed: not supported Cloud Run for Anthos: supported Number or name of the
   * port to access on the container. Number must be in the range 1 to 65535. Name must be an
   * IANA_SVC_NAME. This field is currently limited to integer types only because of proto's
   * inability to properly support the IntOrString golang type.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Integer port;

  /**
   * (Optional) Cloud Run fully managed: not supported Cloud Run for Anthos: supported Optional:
   * Host name to connect to, defaults to the pod IP.
   * @return value or {@code null} for none
   */
  public java.lang.String getHost() {
    return host;
  }

  /**
   * (Optional) Cloud Run fully managed: not supported Cloud Run for Anthos: supported Optional:
   * Host name to connect to, defaults to the pod IP.
   * @param host host or {@code null} for none
   */
  public TCPSocketAction setHost(java.lang.String host) {
    this.host = host;
    return this;
  }

  /**
   * Cloud Run fully managed: not supported Cloud Run for Anthos: supported Number or name of the
   * port to access on the container. Number must be in the range 1 to 65535. Name must be an
   * IANA_SVC_NAME. This field is currently limited to integer types only because of proto's
   * inability to properly support the IntOrString golang type.
   * @return value or {@code null} for none
   */
  public java.lang.Integer getPort() {
    return port;
  }

  /**
   * Cloud Run fully managed: not supported Cloud Run for Anthos: supported Number or name of the
   * port to access on the container. Number must be in the range 1 to 65535. Name must be an
   * IANA_SVC_NAME. This field is currently limited to integer types only because of proto's
   * inability to properly support the IntOrString golang type.
   * @param port port or {@code null} for none
   */
  public TCPSocketAction setPort(java.lang.Integer port) {
    this.port = port;
    return this;
  }

  @Override
  public TCPSocketAction set(String fieldName, Object value) {
    return (TCPSocketAction) super.set(fieldName, value);
  }

  @Override
  public TCPSocketAction clone() {
    return (TCPSocketAction) super.clone();
  }

}


text:
<?php

namespace Ardent\Collection;

use Iterator;

trait OuterIteratorTrait {

    /**
     * @return Iterator
     */
    abstract function getInnerIterator();

    /**
     * @link http://php.net/manual/en/iterator.current.php
     * @return mixed
     */
    function current() {
        return $this->getInnerIterator()->current();
    }

    /**
     * @link http://php.net/manual/en/iterator.next.php
     * @return void
     */
    function next() {
        $this->getInnerIterator()->next();
    }

    /**
     * @link http://php.net/manual/en/iterator.key.php
     * @return mixed
     */
    function key() {
        return $this->getInnerIterator()->key();
    }

    /**
     * @link http://php.net/manual/en/iterator.valid.php
     * @return bool
     */
    function valid() {
        return $this->getInnerIterator()->valid();
    }

    /**
     * @link http://php.net/manual/en/iterator.rewind.php
     * @return void
     */
    function rewind() {
        $this->getInnerIterator()->rewind();
    }

}


text:
package com.izforge.izpack.installer.language;

import static org.hamcrest.MatcherAssert.assertThat;

import org.hamcrest.core.Is;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;

import com.izforge.izpack.api.data.InstallData;
import com.izforge.izpack.api.installer.InstallerRequirementDisplay;
import com.izforge.izpack.api.rules.RulesEngine;
import com.izforge.izpack.compiler.container.TestGUIInstallationContainer;
import com.izforge.izpack.core.resource.ResourceManager;
import com.izforge.izpack.test.Container;
import com.izforge.izpack.test.InstallFile;
import com.izforge.izpack.test.junit.PicoRunner;

/**
 * Test installerRequirements
 *
 * @author Anthonin Bonnefoy
 */
@RunWith(PicoRunner.class)
@Container(TestGUIInstallationContainer.class)
public class ConditionCheckTest
{

    private ConditionCheck conditionCheck;

    public ConditionCheckTest(InstallData installData, ResourceManager resourceManager,
                              RulesEngine rules)
    {
        this.conditionCheck = new ConditionCheck(installData, resourceManager, rules);
    }

    @Test
    @InstallFile("samples/checkRequirement.xml")
    public void testCheckInstallerRequirements() throws Exception
    {
        InstallerRequirementDisplay requirementDisplay = Mockito.mock(InstallerRequirementDisplay.class);
        assertThat(conditionCheck.checkInstallerRequirements(requirementDisplay), Is.is(false));
        Mockito.verify(requirementDisplay).showMissingRequirementMessage("42");
    }
}


text:
import Vue from 'vue';
import MockAdapter from 'axios-mock-adapter';
import axios from '~/lib/utils/axios_utils';
import contentViewer from '~/vue_shared/components/content_viewer/content_viewer.vue';
import mountComponent from 'spec/helpers/vue_mount_component_helper';
import { GREEN_BOX_IMAGE_URL } from 'spec/test_constants';

describe('ContentViewer', () => {
  let vm;
  let mock;

  function createComponent(props) {
    const ContentViewer = Vue.extend(contentViewer);
    vm = mountComponent(ContentViewer, props);
  }

  afterEach(() => {
    vm.$destroy();
    if (mock) mock.restore();
  });

  it('markdown preview renders + loads rendered markdown from server', done => {
    mock = new MockAdapter(axios);
    mock.onPost(`${gon.relative_url_root}/testproject/preview_markdown`).reply(200, {
      body: '<b>testing</b>',
    });

    createComponent({
      path: 'test.md',
      content: '*  Test',
      projectPath: 'testproject',
    });

    const previewContainer = vm.$el.querySelector('.md-previewer');

    setTimeout(() => {
      expect(previewContainer.textContent).toContain('testing');

      done();
    });
  });

  it('renders image preview', done => {
    createComponent({
      path: GREEN_BOX_IMAGE_URL,
      fileSize: 1024,
    });

    setTimeout(() => {
      expect(vm.$el.querySelector('img').getAttribute('src')).toBe(GREEN_BOX_IMAGE_URL);

      done();
    });
  });

  it('renders fallback download control', done => {
    createComponent({
      path: 'test.abc',
      fileSize: 1024,
    });

    setTimeout(() => {
      expect(vm.$el.querySelector('.file-info').textContent.trim()).toContain('test.abc');
      expect(vm.$el.querySelector('.file-info').textContent.trim()).toContain('(1.00 KiB)');
      expect(vm.$el.querySelector('.btn.btn-default').textContent.trim()).toContain('Download');

      done();
    });
  });
});


text:
package pl.luxdev.lol.listeners;

import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;

import pl.luxdev.lol.basic.TabTitle;
import pl.luxdev.lol.basic.Title;
import pl.luxdev.lol.basic.User;
import pl.luxdev.lol.managers.UserManager;
import pl.luxdev.lol.types.ChampType;
import pl.luxdev.lol.utils.ItemCrafter;

public class PlayerJoinList implements Listener{

	public static ItemStack BlueTeamPicker = ItemCrafter.createItem(Material.INK_SACK, 1, (short) 12, ("§8[§6Wybierz TeamType§8]"), ("§7Team: §bBLUE"));
	public static ItemStack RedTeamPicker = ItemCrafter.createItem(Material.INK_SACK, 1, (short) 1, ("§8[§6Wybierz TeamType§8]"), ("§7Team: §cRED"));

	@EventHandler
	public void onJoin(PlayerJoinEvent e){
		Player p = e.getPlayer();
		User u = new User(p);
		UserManager.addUser(u);
		u.setChampion(ChampType.NONE);
		if(u.getChampion() == ChampType.NONE) p.sendMessage("Witaj " + p.getName() + "! Nie wybrales/as klasy.");
		else p.sendMessage("Witaj " + p.getName() + " Twoja klasa zostala ustawiona na: " + u.getChampion());
		addItems(p);

//		TitleAPI.sendTabTitle(p, "§7» Witaj na serwerze", "§6League Of Legends !");
//		TitleAPI.sendFullTitle(p, 20*3, 20*20, 20*4, "§6%player% Witaj na serwerze Lola!", "§aWklad Prac: 35 KB, 28 Godzin, 3 Kawy, 3k lini kodu, Mapa: 3% Plugin: 15%");
		TabTitle tabtitle = new TabTitle("§7» Witaj na serwerze", "§6League Of Legends!");
		tabtitle.send(p);
		Title title = new Title("§6%player% Witaj na serwerze Lola!", "§aWklad Prac: 35 GB, 28 Godzin, 3 Kawy, 3k lini kodu, Mapa: 3% Plugin: 15%", 3, 20, 4);
		title.send(p);

	}
	private void addItems(Player p){
		Inventory inv = p.getInventory();
		inv.clear();
		inv.setItem(0, BlueTeamPicker);
		inv.setItem(8, RedTeamPicker);

	}

}


text:
using appfactum.core;
using System.Data.SqlClient;

namespace appfactum.azure
{
    /// <summary>
    /// Configuration for an AzureSQL database
    /// </summary>
    public class AzureSQLConfiguration : IConfiguration
    {
        private SqlConnectionStringBuilder _builder = new SqlConnectionStringBuilder();

        public SqlConnectionStringBuilder Builder { get => _builder; }

        public string ConnectionString { get => _builder.ConnectionString; set => _builder.ConnectionString = value; }

        /// <summary>
        /// Conflict Handling of the Database
        /// Used for the DataBaseObject.Save method and determines how conflicts are handled.
        /// </summary>
        public eConflictMode ConflictMode { get; set; } = eConflictMode.LastWins;

        /// <summary>
        /// Typ of Database...
        /// </summary>
        public eDatabaseType DatabaseType => eDatabaseType.AzureSQL;

        /// <summary>
        /// Allow drop columns from table which have no representation in a property of persistent class
        /// </summary>
        public bool AllowDropColumns { get; set; }
    }
}


text:
using System;
using System.Xml.Serialization;
using Aop.Api.Domain;

namespace Aop.Api.Response
{
    /// <summary>
    /// ZhimaCreditEpInfoGetResponse.
    /// </summary>
    public class ZhimaCreditEpInfoGetResponse : AopResponse
    {
        /// <summary>
        /// 芝麻信用对于每一次请求返回的业务号。后续可以通过此业务号进行对账
        /// </summary>
        [XmlElement("biz_no")]
        public string BizNo { get; set; }

        /// <summary>
        /// 企业工商综合信息
        /// </summary>
        [XmlElement("company_info")]
        public CompanyInfo CompanyInfo { get; set; }
    }
}


text:
/**
 * Created by Administrator on 2015/6/11.
 */

var RiceError = function RiceError(code, message) {
    this.code = code;
    this.message = message;
}

RiceError.prototype = new Error();

RiceError.prototype.toString = function () {
    return this.code + "|" + this.message;
}

module.exports = RiceError;


text:
package org.apache.geode.internal.cache.tx;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Set;

import org.apache.logging.log4j.Logger;

import org.apache.geode.DataSerializer;
import org.apache.geode.cache.CacheException;
import org.apache.geode.distributed.internal.ClusterDistributionManager;
import org.apache.geode.distributed.internal.DirectReplyProcessor;
import org.apache.geode.distributed.internal.DistributionManager;
import org.apache.geode.distributed.internal.DistributionMessage;
import org.apache.geode.distributed.internal.DistributionStats;
import org.apache.geode.distributed.internal.InternalDistributedSystem;
import org.apache.geode.distributed.internal.ReplyMessage;
import org.apache.geode.distributed.internal.ReplyProcessor21;
import org.apache.geode.distributed.internal.ReplySender;
import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.internal.Assert;
import org.apache.geode.internal.cache.LocalRegion;
import org.apache.geode.internal.cache.PartitionedRegion;
import org.apache.geode.internal.cache.RemoteOperationException;
import org.apache.geode.internal.logging.LogService;
import org.apache.geode.internal.logging.log4j.LogMarker;

/**
 * This message is used be a replicate region to send a contains key/value request to another peer.
 *
 * @since GemFire 6.5
 */
public class RemoteContainsKeyValueMessage extends RemoteOperationMessageWithDirectReply {
  private static final Logger logger = LogService.getLogger();

  private boolean valueCheck;

  private Object key;

  protected static final short VALUE_CHECK = UNRESERVED_FLAGS_START;

  public RemoteContainsKeyValueMessage() {}

  public RemoteContainsKeyValueMessage(InternalDistributedMember recipient, String regionPath,
      DirectReplyProcessor processor, Object key, boolean valueCheck) {
    super(recipient, regionPath, processor);
    this.valueCheck = valueCheck;
    this.key = key;
  }

  /**
   * Sends a ReplicateRegion message for either
   * {@link org.apache.geode.cache.Region#containsKey(Object)}or
   * {@link org.apache.geode.cache.Region#containsValueForKey(Object)} depending on the
   * valueCheck argument
   *
   * @param recipient the member that the contains keys/value message is sent to
   * @param r the LocalRegion
   * @param key the key to be queried
   * @param valueCheck true if {@link org.apache.geode.cache.Region#containsValueForKey(Object)} is
   *        desired, false if {@link org.apache.geode.cache.Region#containsKey(Object)}is desired
   * @return the processor used to read the returned keys
   */
  public static RemoteContainsKeyValueResponse send(InternalDistributedMember recipient,
      LocalRegion r, Object key, boolean valueCheck) throws RemoteOperationException {
    Assert.assertTrue(recipient != null, "recipient can not be NULL");

    RemoteContainsKeyValueResponse p =
        new RemoteContainsKeyValueResponse(r.getSystem(), recipient, key);
    RemoteContainsKeyValueMessage m =
        new RemoteContainsKeyValueMessage(recipient, r.getFullPath(), p, key, valueCheck);

    Set<?> failures = r.getDistributionManager().putOutgoing(m);
    if (failures != null && failures.size() > 0) {
      throw new RemoteOperationException(String.format("Failed sending < %s >", m));
    }
    return p;
  }

  @Override
  protected boolean operateOnRegion(ClusterDistributionManager dm, LocalRegion r, long startTime)
      throws CacheException, RemoteOperationException {
    if (logger.isTraceEnabled(LogMarker.DM_VERBOSE)) {
      logger.trace(LogMarker.DM_VERBOSE,
          "DistributedRemoteContainsKeyValueMessage operateOnRegion: {}", r.getFullPath());
    }

    if (!(r instanceof PartitionedRegion)) { // prs already wait on initialization
      r.waitOnInitialization(); // bug #43371 - accessing a region before it's initialized
    }

    final boolean replyVal;
    if (this.valueCheck) {
      replyVal = r.containsValueForKey(this.key);
    } else {
      replyVal = r.containsKey(this.key);
    }

    if (logger.isTraceEnabled(LogMarker.DM_VERBOSE)) {
      logger.trace(
          "DistributedRemoteContainsKeyValueMessage sending reply back using processorId: {}",
          getProcessorId());
    }

    RemoteContainsKeyValueReplyMessage.send(getSender(), getProcessorId(), getReplySender(dm),
        replyVal);

    // Unless there was an exception thrown, this message handles sending the
    // response
    return false;
  }

  @Override
  protected void appendFields(StringBuffer buff) {
    super.appendFields(buff);
    buff.append("; valueCheck=").append(this.valueCheck).append("; key=").append(this.key);
  }

  @Override
  public int getDSFID() {
    return R_CONTAINS_MESSAGE;
  }

  @Override
  public void fromData(DataInput in) throws IOException, ClassNotFoundException {
    super.fromData(in);
    this.key = DataSerializer.readObject(in);
    this.valueCheck = (flags & VALUE_CHECK) != 0;
  }

  @Override
  public void toData(DataOutput out) throws IOException {
    super.toData(out);
    DataSerializer.writeObject(this.key, out);
  }

  @Override
  protected short computeCompressedShort() {
    short flags = super.computeCompressedShort();
    if (this.valueCheck)
      flags |= VALUE_CHECK;
    return flags;
  }

  public static class RemoteContainsKeyValueReplyMessage extends ReplyMessage {

    /** Propagated exception from remote node to operation initiator */
    private boolean containsKeyValue;

    /**
     * Empty constructor to conform to DataSerializable interface
     */
    public RemoteContainsKeyValueReplyMessage() {}

    private RemoteContainsKeyValueReplyMessage(int processorId, boolean containsKeyValue) {
      this.processorId = processorId;
      this.containsKeyValue = containsKeyValue;
    }

    /** Send an ack */
    public static void send(InternalDistributedMember recipient, int processorId,
        ReplySender replySender, boolean containsKeyValue) {
      Assert.assertTrue(recipient != null, "ContainsKeyValueReplyMessage NULL reply message");
      RemoteContainsKeyValueReplyMessage m =
          new RemoteContainsKeyValueReplyMessage(processorId, containsKeyValue);
      m.setRecipient(recipient);
      replySender.putOutgoing(m);
    }

    /**
     * Processes this message. This method is invoked by the receiver of the message.
     *
     * @param dm the distribution manager that is processing the message.
     */
    @Override
    public void process(final DistributionManager dm, ReplyProcessor21 processor) {
      final long startTime = getTimestamp();

      if (processor == null) {
        if (logger.isTraceEnabled(LogMarker.DM_VERBOSE)) {
          logger.trace(LogMarker.DM_VERBOSE, "ContainsKeyValueReplyMessage processor not found");
        }
        return;
      }
      processor.process(this);

      dm.getStats().incReplyMessageTime(DistributionStats.getStatTime() - startTime);
    }

    @Override
    public int getDSFID() {
      return R_CONTAINS_REPLY_MESSAGE;
    }

    @Override
    public void fromData(DataInput in) throws IOException, ClassNotFoundException {
      super.fromData(in);
      this.containsKeyValue = in.readBoolean();
    }

    @Override
    public void toData(DataOutput out) throws IOException {
      super.toData(out);
      out.writeBoolean(this.containsKeyValue);
    }

    @Override
    public String toString() {
      StringBuffer sb = new StringBuffer();
      sb.append("ContainsKeyValueReplyMessage ").append("processorid=").append(this.processorId)
          .append(" reply to sender ").append(this.getSender())
          .append(" returning containsKeyValue=").append(doesItContainKeyValue());
      return sb.toString();
    }

    public boolean doesItContainKeyValue() {
      return this.containsKeyValue;
    }
  }

  /**
   * A processor to capture the value returned by
   * {@link org.apache.geode.internal.cache.tx.RemoteContainsKeyValueMessage.RemoteContainsKeyValueReplyMessage}
   *
   * @since GemFire 6.5
   */
  public static class RemoteContainsKeyValueResponse extends RemoteOperationResponse {
    private volatile boolean returnValue;
    private volatile boolean returnValueReceived;
    final Object key;

    public RemoteContainsKeyValueResponse(InternalDistributedSystem ds,
        InternalDistributedMember recipient, Object key) {
      super(ds, recipient, false);
      this.key = key;
    }

    @Override
    public void process(DistributionMessage msg) {
      try {
        if (msg instanceof RemoteContainsKeyValueReplyMessage) {
          RemoteContainsKeyValueReplyMessage reply = (RemoteContainsKeyValueReplyMessage) msg;
          this.returnValue = reply.doesItContainKeyValue();
          this.returnValueReceived = true;
          if (logger.isTraceEnabled(LogMarker.DM_VERBOSE)) {
            logger.trace(LogMarker.DM_VERBOSE, "ContainsKeyValueResponse return value is {}",
                this.returnValue);
          }
        }
      } finally {
        super.process(msg);
      }
    }

    /**
     * @return Set the keys associated with the ReplicateRegion of the
     *         {@link RemoteContainsKeyValueMessage}
     */
    public boolean waitForContainsResult() throws RemoteOperationException {
      try {
        waitForRemoteResponse();
      } catch (CacheException ce) {
        logger.debug("ContainsKeyValueResponse got remote CacheException", ce);
        throw new RemoteOperationException(
            "RemoteContainsKeyResponse got remote CacheException; triggering RemoteOperationException.",
            ce);
      }
      if (!this.returnValueReceived) {
        throw new RemoteOperationException(
            "no return value received");
      }
      return this.returnValue;
    }
  }

}


text:
/*
 _______________________________________________________________________
 ______________  S I L I C O N   G R A P H I C S   I N C .  ____________
 |
 |   $Revision: 1.1.1.1 $
 |
 |   Classes	: TsViewer
 |
 |   Author(s)	: Dave Immel
 |
 ______________  S I L I C O N   G R A P H I C S   I N C .  ____________
 _______________________________________________________________________
 */

#ifndef  _SIMPLE_VIEWER_
#define  _SIMPLE_VIEWER_

#include <Inventor/Xt/viewers/SoXtViewer.h>
#include <Inventor/SbLinear.h>

//
// Class: TsViewer
//
// Drop Viewer - viewer which only operates in viewing mode.  Used with
// the drop game.
//
class TsViewer : public SoXtViewer {
 public:
    // constructor/destructor
    TsViewer(
        Widget parent = NULL,
        const char *name = NULL);
    ~TsViewer();

 protected:
    // redefine this to process the events
    virtual void	processEvent(XAnyEvent *anyevent);

    // redefine this to cache the renderArea size
    virtual void	sizeChanged(const SbVec2s &newSize);

 private:
    // viewer state variables
    int		    mode;
    SbBool	    createdCursors;
    Cursor	    vwrCursor, seekCursor;
    SbVec2s	    locator;    // mouse position
    SbVec2s	    movement;   // mouse movement
    SbVec2s	    windowSize; // cached size of the window

    // camera translation vars
    SbVec3f	    locator3D;
    SbPlane	    focalplane;
    float	    transXspeed, transYspeed;

    void	    switchMode(int newMode);
    void	    defineCursors();
    void	    translateCamera();
    void            rotateCamera();
    void	    computeTranslateValues();
    static void	    transWheelStartCB(void *v, float);
};

#endif  /* _TS_VIEWER_ */


text:
title: Supported webhooks
---

A newly created or modified Function CR is first updated by the defaulting webhook and then verified by the validation webhook before the Function Controller starts to process it.

## Defaulting webhook

>**NOTE:** It only applies to the [Function custom resource (CR)](./00-custom-resources/svls-01-function.md).

The defaulting webhook:

- Sets default values for CPU and memory requests and limits for a Function.
- Sets default values for CPU and memory requests and limits for a Kubernetes Job responsible for building the Function's image.
- Adds the maximum and the minimum number of replicas, if not specified already in the Function CR.
- Sets the default `nodejs14` runtime unless specified otherwise.

   | Parameter       | Default value |
   | ----------------- | ------------- |
   | **resources.requests.cpu**    | `50m`         |
   | **resources.requests.memory** | `64Mi`        |
   | **resources.limits.cpu**     | `100m`        |
   | **resources.limits.memory**  | `128Mi`       |
   | **buildResources.requests.cpu**    | `700m`         |
   | **buildResources.requests.memory** | `700Mi`        |
   | **buildResources.limits.cpu**     | `1100m`        |
   | **buildResources.limits.memory**  | `1100Mi`       |
   | **minReplicas**   | `1`           |
   | **maxReplicas**   | `1`           |
   | **runtime**       | `nodejs14`    |

>**NOTE:** Function's resources and replicas as well as resources for a Kubernetes Job are based on presets. Read about all [available presets](./svls-09-available-presets.md) to find out more.

## Validation webhook

It checks the following conditions for these CRs:

1. [Function CR](./00-custom-resources/svls-01-function.md)

   - Minimum values requested for a Function (CPU, memory, and replicas) and a Kubernetes Job (CPU and memory) responsible for building the Function's image must not be lower than the required ones:

   | Parameter            | Required value |
   | -------------------- | -------------- |
   | **minReplicas** | `1`            |
   | **resources.requests.cpu**    | `10m`          |
   | **resources.requests.memory** | `16Mi`         |
   | **buildResources.requests.cpu**    | `200m`          |
   | **buildResources.requests.memory** | `200Mi`         |

   - Requests are lower than or equal to limits, and the minimum number of replicas is lower than or equal to the maximum one.
   - The Function CR contains all the required parameters.
   - If you decide to set a Git repository as the source of your Function's code and dependencies (**spec.type** set to `git`), the **spec.reference** and **spec.baseDir** fields must contain values.
   - The format of deps, envs, labels, and the Function name ([RFC 1035](https://tools.ietf.org/html/rfc1035)) is correct.
   - The Function CR contains any envs reserved for the Deployment: `FUNC_RUNTIME`, `FUNC_HANDLER`, `FUNC_PORT`, `MOD_NAME`, `NODE_PATH`, `PYTHONPATH`.

2. [GitRepository CR](./00-custom-resources/svls-02-gitrepository.md)

   - The **spec.url** parameter must:

      - Not be empty
      - Start with the `http(s)`, `git`, or `ssh` prefix
      - End with the `.git` suffix

   - If you use SSH to authenticate to the repository:

     - **spec.auth.type** must be set to `key`
     - **spec.auth.secretName** must not be empty

   - If you use HTTP(S) to point to the repository that requires authentication (**spec.auth**):

      - **spec.auth.type** must be set to either `key` (SSH key) or `basic` (password or token)
      - **spec.auth.secretName** must not be empty

## Admission webhook

There is also the admission webhook that is only triggered in the scenario when you switch at runtime from one registry to another.

To switch registries at runtime, you must create or update a Secret CR that complies with [specific requirements](./svls-03-switching-registries.md). This Secret CR, among other details, contains a username and password to the registry. The admission webhook encodes these credentials to base64, a format that is required by Kaniko - the Function's job building tool - to access the registry and push a Function's image to it. These encoded credentials also allow Kubernetes to pull images of deployed Functions from the registry. The admission webhook adds these credentials to the created Secret CR. They take the form of the `.dockerconfigjson` entry with a valid value. The admission webhook also updates this entry's value each time the username and password change.

### Requirements

This admission webhook is triggered every time you `CREATE` or `UPDATE` a Secret in any Namespace, as long as the Secret contains the `serverless.kyma-project.io/remote-registry: config` label.