text:
class KBoard
{

public:

	typedef function<void(KBoard*, unsigned char, bool, void*)> KBoardButtonPressCallback;
	typedef function<void(KBoard*, unsigned char, void*)> KBoardBendChangedCallback;

	KBoard();
	~KBoard();

	bool GetIsRunning() { return isRunning; }
	bool Startup(KBoardButtonPressCallback buttonPressCallback, void* buttonPressCallbackUserState, KBoardBendChangedCallback bendChangedCallback, void* bendChangedCallbackUserState);
	void Shutdown();

	bool SetKey(unsigned char keyId, unsigned char value);

private:
	KBoardButtonPressCallback buttonPressCallback;
	KBoardBendChangedCallback bendChangedCallback;
	void* buttonPressCallbackUserState;
	void* bendChangedCallbackUserState;

	shared_ptr<RtMidiIn> midiIn;
	shared_ptr<RtMidiOut> midiOut;
	unsigned int inputDeviceID;
	unsigned int outputDeviceID;
	bool isRunning;

	static void OnMidiInput(double deltaTime, vector<unsigned char> *pMessage, void *userData);
};


text:
<?php

namespace WellCommerce\Bundle\ClientBundle\Entity;

/**
 * Interface ClientContactDetailsInterface
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
interface ClientDetailsInterface
{
    public function getDiscount() : float;

    public function setDiscount(float $discount);

    public function setPassword(string $password);

    public function setHashedPassword(string $password);

    public function setPasswordConfirm($password);

    public function resetPassword();

    public function getUsername() : string;

    public function setUsername(string $username);

    public function setSalt(string $salt);

    public function isConditionsAccepted() : bool;

    public function setConditionsAccepted(bool $conditionsAccepted);

    public function isNewsletterAccepted() : bool;

    public function setNewsletterAccepted(bool $newsletterAccepted);

    public function getResetPasswordHash();

    public function setResetPasswordHash($resetPasswordHash);

    /**
     * @return null|string
     */
    public function getLegacyPassword ();

    /**
     * @param null|string $legacyPassword
     */
    public function setLegacyPassword ($legacyPassword);

    /**
     * @return null|string
     */
    public function getLegacyPasswordEncoder ();

    /**
     * @param null|string $legacyPasswordEncoder
     */
    public function setLegacyPasswordEncoder ($legacyPasswordEncoder);
}

redpajama_set_name: RedPajamaGithub


text:
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">

   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
   <meta name="Author" content="R. Martin">
   <title>Project Suggestions - Electronic Structure of Condensed Matter, Physics 598SCM, University of Illinois</title>

Electronics Structure of Condensed
Matter

Projects Due Monday, May 10

Project Suggestions

Last modified April 30, 2010

This is a very long list of suggestions for projects so that you have many choices.
You may also choose different projects  if you discuss with  Prof. Martin  IN ADVANCE.

Send project reports by email to Prof. Martin.  Please send to BOTH rmartin42@gmail.com
and rmartin@illinois.edu to be sure I get it.  You can also give  me a hard copy report if that
is best for you.

Each project should provide a description of the ideas  and/or methods and conclusions
on the results.   The project report should be at least one typed page (longer if there are equations
 of figures that take up space).

 Some projects are taken from the book "Electronic Structure" by R. Martin.
For other projects you should give at least one source.

Projects taken from the  book -- you may also use other references!

Summarize any one of the chapters:  8, 11, or 13 through 23.

 You may choose Ch. 12, but then you must discuss in some detail parts that we did not do in class, for example, the use of empirical pseudopotentials.

 The ``2n+1'' theorem (not widely known) shows that if the wavefunction
is know to order $n$ in a perturbation expansion, the energy can be calculated
 to order 2n+1.  Work out the details of the formulas in the book and
 do exercise 3.24.

Work out the general form for ``special points'' to any order,  and work
Exercise 4.21.

Exercises 14.23-24.  This uses Harrison's tight-binding approach.

 Bands in nanotubes.  See description below.

Summarize the iterative methods in Appendix M and give a comparison
the approaches used in at least two methods.

 Exercise 3.12 and 3.16 in the book.  The first is very important for
understanding the exchange energy, but it only be stated in class.
The second is a very interesting feature of fermions and bosons.

 Give the expressions for Hartree-Fock approximation for bands
in a metal and work exercises 5.9, 10, 11 in the book.  These are important relations that
illustrate the basic features of bands in metals and the problem in
Hartree-Fock approximation.  The integrals are somewhat tedious and you do not need to
evaluate them in detail but you do need to show that they lead to a
unphysical singularity at the Fermi energy.

Describe the Green's function methods for calculation of phonon
dispersion in Ch. 19.  Contrast this with the "brute force" methods
that require large "supercells".

Describe two of the methods for constructing norm-conserving pseudopotentials.

Work out Exercise 4.22. for bands in a one-dimensional crystal.  This
shows relations among the methods.

Linear scaling "order N" methods. Summarize the general ideas and
discuss methods.  See Ch. 23..

Theory of Atomic Sphere methods in solids.  This is barely covered
in class.  A project could go further to show the usefulness of atomic
sphere approximations to have simple calculations for solids.

Theory of polarization in solids and Berry's phases.

Theory of Wannier Functions: history and recent advances

Bands in interesting systems

 Nanotubes.  Report on one paper that describes the types of nanotubes formed
by ``rolling'' graphene sheets to make tubes.  Give the conditions for metallic
tubes (with zero gap like graphene) or tubes with gaps.  A possible paper is
Hamada, et al., Phys. Rev. Lett. 6, 1579 (1992) or another paper.

Bands for the copper oxide square lattices in the Hi-Tc superconductors.
Describe in  tight binding and discuss the way the second neighbor terms
affects the Fermi surface.  Show the results are different depending on
the sign of these terms.

Physical Properties

Optical properties of materials.  Give theory in terms of transitions between bands
and discussion of results in cases with direct and indirect bands gaps.

Phonons.  Give theory in terms of forces and force constants and discuss
 comparison of theory and experiment for several cases.

Elastic properties.  Give theory in terms of  constants and discuss
 comparison of theory and experiment for several cases.

Magnetism.  Two possibilities: Give theory in terms of magnetic moments and
Weiss mean field theory, or in terms of Kohn-Sham calculations. In either
case discuss magnetism in at least two materials.

Report on various calculations of surface energies that have been reported.
Give at lest 3 references (not in the book) with description of their
conclusions.

Density Functional Theory

Describe the original derivation of the PBE functional (very nice arguments and
construction) and give the form proposed.

Theory and actual recent examples of GGAs

Hybrid functionals.  What are they?  In what ways have they been used?

Theory of van der Waals functional proposed in a recent papers and following ones

Applications of the van der Waals functional, what are tested that have been done
 and uses for interesting problems.

You can discuss with  Prof. Martin  IN ADVANCE about other projects.


text:
#include "config.h"
#include "GPUComputeCommandEncoder.h"

#if ENABLE(WEBGPU)

#include "GPUBuffer.h"
#include "GPUCommandBuffer.h"
#include "GPUComputePipelineState.h"
#include "Logging.h"

namespace WebCore {

RefPtr<GPUComputeCommandEncoder> GPUComputeCommandEncoder::create(GPUCommandBuffer* buffer)
{
    RefPtr<GPUComputeCommandEncoder> encoder = adoptRef(new GPUComputeCommandEncoder(buffer));
    return encoder;
}

GPUComputeCommandEncoder::~GPUComputeCommandEncoder()
{
    LOG(WebGPU, "GPUComputeCommandEncoder::~GPUComputeCommandEncoder()");
}

#if !PLATFORM(COCOA)
void GPUComputeCommandEncoder::setComputePipelineState(GPUComputePipelineState*)
{
}

void GPUComputeCommandEncoder::setBuffer(GPUBuffer*, unsigned, unsigned)
{
}

void GPUComputeCommandEncoder::dispatch(GPUSize threadgroupsPerGrid, GPUSize threadsPerThreadgroup);
{
}

void GPUComputeCommandEncoder::endEncoding()
{
}
#endif

} // namespace WebCore

#endif


text:
package com.shinoow.abyssalcraft.common.blocks.itemblock;

import net.minecraft.block.Block;
import net.minecraft.block.BlockSlab;
import net.minecraft.item.ItemSlab;

import com.shinoow.abyssalcraft.AbyssalCraft;

public class ItemCstonebrickSlab extends ItemSlab {

	public ItemCstonebrickSlab(Block block) {
		super(block, (BlockSlab)AbyssalCraft.cstonebrickslab1, (BlockSlab)AbyssalCraft.cstonebrickslab2, false);
		this.setMaxDamage(0);
		this.setHasSubtypes(true);
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Tracker!</string>
    <string name="app_name">Tracker</string>
	<string name="settings">Settings</string>
	<string name="cancel">Cancel</string>
	<string name="clear">Clear</string>
	<string name="done">Done</string>
	<string name="name">Name</string>
	<string name="first_last">Name</string>
	<string name="resort">Ski Area</string>
	<string name="email">Email</string>
	<string name="email_confirm">Confirm Email</string>
	<string name="welcome_user">Enter your information below to get started!</string>
	<string name="password">Password</string>
	<string name="dob">Birthdate</string>
	<string name="headline">Headline</string>
	<string name="description">Description</string>
	<string name="create_advert">Create Geolocation Advert...</string>
	<string name="create_user">Create User</string>
	<string name="multipoint">Multi-point Advert</string>
	<string name="plot_point">Plot point</string>
</resources>


text:
package main

import (
	"flag"
	"fmt"
	"github.com/APTrust/exchange/context"
	"github.com/APTrust/exchange/models"
	"github.com/APTrust/exchange/workers"
	"os"
)

// apt_file_restore moves individual files from a preservation bucket
// into a depositor's restoration bucket.
func main() {
	pathToConfigFile := parseCommandLine()
	config, err := models.LoadConfigFile(pathToConfigFile)
	if err != nil {
		fmt.Fprintf(os.Stderr, err.Error())
		os.Exit(1)
	}
	_context := context.NewContext(config)
	_context.MessageLog.Info("Connecting to NSQLookupd at %s", _context.Config.NsqLookupd)
	_context.MessageLog.Info("NSQDHttpAddress is %s", _context.Config.NsqdHttpAddress)
	consumer, err := workers.CreateNsqConsumer(_context.Config, &_context.Config.FileRestoreWorker)
	if err != nil {
		_context.MessageLog.Fatalf(err.Error())
	}
	_context.MessageLog.Info("apt_file_restore started")

	restorer := workers.NewAPTFileRestorer(_context)
	consumer.AddHandler(restorer)
	consumer.ConnectToNSQLookupd(_context.Config.NsqLookupd)

	// This reader blocks until we get an interrupt, so our program does not exit.
	<-consumer.StopChan
}

func parseCommandLine() (configFile string) {
	var pathToConfigFile string
	flag.StringVar(&pathToConfigFile, "config", "", "Path to APTrust config file")
	flag.Parse()
	if pathToConfigFile == "" {
		printUsage()
		os.Exit(1)
	}
	return pathToConfigFile
}

// Tell the user about the program.
func printUsage() {
	message := `
apt_file_restore moves individual files from a preservation bucket
into a depositor's restoration bucket.

Usage: apt_file_restore -config=<path to APTrust config file>

Param -config is required.
`
	fmt.Println(message)
}


text:
from django import template

register = template.Library()

@register.tag
def title(parser, token):
    """
    Create a title string.

    It's used in the following way:

        {% title "About" user.username "Lol" %}

    Which would produce the string: "Lol - matachi - About - MaTachi.se"
    """
    args = token.split_contents()
    values = [parser.compile_filter(arg) for arg in args[1:]]
    return TitleNode(values)

class TitleNode(template.Node):
    def __init__(self, titles):
        self.titles = titles
        self.titles.reverse()

    def render(self, context):
        return "{} | {}".format(
            " | ".join(t.resolve(context) for t in self.titles),
            "MaTachi.se"
        )


text:
var arDrone = require('ar-drone');
var Chewbacopter = require('chewbacopter');

var client = arDrone.createClient();

var chewie = new Chewbacopter();
chewie.use(client, [
		'batteryPercentage',
		'altitudeMeters'
		]).monitor();

client.takeoff();

client
	.after(10000, function() {
		this.stop();
		this.land();
	});


text:
exports.commands = {
    //commands for score and such
    resetleaderboard: function(arg, by, room) {
        if (!Bot.hasRank(by, '#~')) return false;
        Economy.clear(room, by);
        Bot.say(by, room, 'The leaderboard has been reset.');
    },
    registerroom: function(arg, by, room) {
        if (room.charAt(0) === ',' || !Bot.rankFrom(by, '~')) return false;
        if (Economy.addRoom(room)) {
            return Bot.say(by, room, 'An individual leaderboard has been enabled for this room.');
        }
        else {
            return Bot.say(by, room, 'An individual leaderboard already exists for this room.');
        }
    },
    deregisterroom: function(arg, by, room) {
        if (room.charAt(0) === ',' || !Bot.rankFrom(by, '~')) return false;
        if (Economy.deleteRoom(room)) {
            return Bot.say(by, room, 'The individual leaderboard has been deleted for this room.');
        }
        else {
            return Bot.say(by, room, 'An individual leaderboard does not exist for this room.');
        }
    },
    takepoints: 'givepoints',
    givepoints: function(arg, by, room, cmd) {
        if (!Bot.canUse('givepoints', room, by) || !arg) return false;
        if (!Economy.isRegistered(room) && !Bot.rankFrom(by, '@')) return false;
        arg = arg.split(',');
        var target = toId(arg[0]);
        var amount = toId(arg[1]).replace(/[^0-9]/g, '');
        if (!amount) return;
        if (cmd === 'takepoints') amount = amount * -1;
        Economy.give(target, amount * 1, room);
        if (amount < 0) {
            return Bot.say(by, room, target + ' has lost ' + amount * -1 + ' ' + Economy.currency(room));
        }
        return Bot.say(by, room, target + ' has been given ' + amount + ' ' + Economy.currency(room));
    },
    points: 'atm',
    score: 'atm',
    wallet: 'atm',
    atm: function(arg, by, room) {
        if (!Bot.hasRank(by, '+%@#&~')) {
            var targetRoom = ',' + by;
        }
        else {
            targetRoom = room;
        }
        if (arg) {
            var user = arg.split(',')[0];
            if (arg.split(',')[1]) {
                room = toId(arg.split(',')[1]);
            }
        }
        var target = user || by;
        return Bot.say(by, targetRoom, '(' + (Economy.isRegistered(room) ? room : 'global') + ') ' + target + ' has ' + Economy.getPoints(target, room) + ' ' + Economy.currency(room));
    },
    top: function(arg, by, room) {
        if (!Bot.hasRank(by, '+%@#&~')) {
            var targetRoom = ',' + by;
        }
        else {
            targetRoom = room;
        }
        if (arg) {
            room = toId(arg);
        }
        Bot.say(by, targetRoom, Economy.getTop(room));
    },
    leaderboard: function(arg, by, room) {
        if (!Bot.hasRank(by, '+%@#&~')) {
            var targetRoom = ',' + by;
        }
        else {
            targetRoom = room;
        }
        if (arg) {
            room = toId(arg);
        }
        var text = Economy.getHastebinLeaderboard(room);
        Tools.uploadToHastebin(text, function(link) {
            return Bot.say(by, targetRoom, link);
        }.bind(this));
    },
    config: 'cp',
    cp: function(arg, by, room) {
        if (!Bot.hasRank(by, '#~') || !arg) return false;
        if (!Economy.isRegistered(room) && !Bot.rankFrom(by, '~')) return false;
        arg = arg.split(',');
        if (arg.length !== 2) return false;
        var param = toId(arg[0]);
        var value = arg[1].trim();
        if (!param || !value) return false;
        if (Economy.isRegistered(room)) {
            var economyCP = Economy.economy.rooms[room].cp;
        }
        else {
            economyCP = Economy.economy.global.cp;
        }
        switch (param) {
            case 'currency':
            case 'name':
            case 'points':
                economyCP.currency = value;
                Bot.say(by, room, '"Points" renamed to ' + value);
                break;
            case 'factor':
            case 'payout':
                value = toId(value);
                if (/[^0-9]/i.test(value)) {
                    return Bot.say(by, room, 'Invalid value.');
                }
                economyCP.factor = value * 1;
                Bot.say(by, room, 'Payout factor for winning games is: ' + value);
                break;
        }
        Economy.write();
    },
    lbhelp: 'leaderboardhelp',
    leaderboardhelp: function(arg, by, room) {
        if (!Bot.hasRank(by, '@#&~')) room = ',' + by;
        Bot.say(by, room, 'http://pastebin.com/am4FgVCH');
    }
};

/****************************
*       For C9 Users        *
*****************************/
// Yes, sadly it can't be done in one huge chunk w/o undoing it / looking ugly :(

/* globals toId */
/* globals Bot */
/* globals Tools */
/* globals Economy */


text:
#pragma once
#include <aws/pinpoint/Pinpoint_EXPORTS.h>
#include <aws/pinpoint/model/AttributesResource.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace Pinpoint
{
namespace Model
{
  class AWS_PINPOINT_API RemoveAttributesResult
  {
  public:
    RemoveAttributesResult();
    RemoveAttributesResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    RemoveAttributesResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    inline const AttributesResource& GetAttributesResource() const{ return m_attributesResource; }

    inline void SetAttributesResource(const AttributesResource& value) { m_attributesResource = value; }

    inline void SetAttributesResource(AttributesResource&& value) { m_attributesResource = std::move(value); }

    inline RemoveAttributesResult& WithAttributesResource(const AttributesResource& value) { SetAttributesResource(value); return *this;}

    inline RemoveAttributesResult& WithAttributesResource(AttributesResource&& value) { SetAttributesResource(std::move(value)); return *this;}

  private:

    AttributesResource m_attributesResource;
  };

} // namespace Model
} // namespace Pinpoint
} // namespace Aws


text:
package com.intellij.openapi.editor.impl;

import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.actionSystem.ActionPlan;
import com.intellij.util.text.ImmutableCharSequence;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class EditorActionPlan implements ActionPlan {
  private ImmutableCharSequence myText;
  private final Editor myEditor;
  private int myCaretOffset;
  private final List<Replacement> myReplacements = new ArrayList<>();

  EditorActionPlan(@NotNull Editor editor) {
    myEditor = editor;
    myText = (ImmutableCharSequence)editor.getDocument().getImmutableCharSequence();
    myCaretOffset = editor.getCaretModel().getOffset();
  }

  @NotNull
  @Override
  public ImmutableCharSequence getText() {
    return myText;
  }

  @Override
  public void replace(int begin, int end, String s) {
    myText = myText.replace(begin, end, s);
    myReplacements.add(new Replacement(begin, end, s));
    if (myCaretOffset == end) {
      myCaretOffset += s.length() - (end - begin);
    }
  }

  @Override
  public int getCaretOffset() {
    return myCaretOffset;
  }

  @Override
  public void setCaretOffset(int offset) {
    myCaretOffset = offset;
  }

  public List<Replacement> getReplacements() {
    return Collections.unmodifiableList(myReplacements);
  }

  public int getCaretShift() {
    return myCaretOffset - myEditor.getCaretModel().getOffset();
  }

  static class Replacement {
    private final int myBegin;
    private final int myEnd;
    private final String myText;

    Replacement(int begin, int end, String text) {
      myBegin = begin;
      myEnd = end;
      myText = text;
    }

    public int getBegin() {
      return myBegin;
    }

    public int getEnd() {
      return myEnd;
    }

    public String getText() {
      return myText;
    }
  }
}


text:
<template name="authenticateAndComment">

    <button type="button" class="close" aria-hidden="true">×</button>
    <form class="authenticate-and-comment" role="form">
      {{#unless currentUser}}
        {{> addInfoOrSignIn action="comment"}}
      {{/unless}}

        <input class="form-control comment"
               type="text"
               placeholder="Add comment or question"
               value="{{SGet 'unauth-comment'}}">

      {{> alerts where="authenticateAndComment"}}
      <button type="submit" class="btn add-comment">Add Comment</button>
    </form>

</template>


text:
namespace Dropbox.Api.Files
{
    using sys = System;
    using col = System.Collections.Generic;
    using re = System.Text.RegularExpressions;

    using enc = Dropbox.Api.Stone;

    /// <summary>
    /// <para>The save url result object</para>
    /// </summary>
    public class SaveUrlResult
    {
        #pragma warning disable 108

        /// <summary>
        /// <para>The encoder instance.</para>
        /// </summary>
        internal static enc.StructEncoder<SaveUrlResult> Encoder = new SaveUrlResultEncoder();

        /// <summary>
        /// <para>The decoder instance.</para>
        /// </summary>
        internal static enc.StructDecoder<SaveUrlResult> Decoder = new SaveUrlResultDecoder();

        /// <summary>
        /// <para>Initializes a new instance of the <see cref="SaveUrlResult" /> class.</para>
        /// </summary>
        public SaveUrlResult()
        {
        }

        /// <summary>
        /// <para>Gets a value indicating whether this instance is Complete</para>
        /// </summary>
        public bool IsComplete
        {
            get
            {
                return this is Complete;
            }
        }

        /// <summary>
        /// <para>Gets this instance as a Complete, or <c>null</c>.</para>
        /// </summary>
        public Complete AsComplete
        {
            get
            {
                return this as Complete;
            }
        }

        /// <summary>
        /// <para>Gets a value indicating whether this instance is AsyncJobId</para>
        /// </summary>
        public bool IsAsyncJobId
        {
            get
            {
                return this is AsyncJobId;
            }
        }

        /// <summary>
        /// <para>Gets this instance as a AsyncJobId, or <c>null</c>.</para>
        /// </summary>
        public AsyncJobId AsAsyncJobId
        {
            get
            {
                return this as AsyncJobId;
            }
        }

        #region Encoder class

        /// <summary>
        /// <para>Encoder for  <see cref="SaveUrlResult" />.</para>
        /// </summary>
        private class SaveUrlResultEncoder : enc.StructEncoder<SaveUrlResult>
        {
            /// <summary>
            /// <para>Encode fields of given value.</para>
            /// </summary>
            /// <param name="value">The value.</param>
            /// <param name="writer">The writer.</param>
            public override void EncodeFields(SaveUrlResult value, enc.IJsonWriter writer)
            {
                if (value is Complete)
                {
                    WriteProperty(".tag", "complete", writer, enc.StringEncoder.Instance);
                    Complete.Encoder.EncodeFields((Complete)value, writer);
                    return;
                }
                if (value is AsyncJobId)
                {
                    WriteProperty(".tag", "async_job_id", writer, enc.StringEncoder.Instance);
                    AsyncJobId.Encoder.EncodeFields((AsyncJobId)value, writer);
                    return;
                }
                throw new sys.InvalidOperationException();
            }
        }

        #endregion

        #region Decoder class

        /// <summary>
        /// <para>Decoder for  <see cref="SaveUrlResult" />.</para>
        /// </summary>
        private class SaveUrlResultDecoder : enc.UnionDecoder<SaveUrlResult>
        {
            /// <summary>
            /// <para>Create a new instance of type <see cref="SaveUrlResult" />.</para>
            /// </summary>
            /// <returns>The struct instance.</returns>
            protected override SaveUrlResult Create()
            {
                return new SaveUrlResult();
            }

            /// <summary>
            /// <para>Decode based on given tag.</para>
            /// </summary>
            /// <param name="tag">The tag.</param>
            /// <param name="reader">The json reader.</param>
            /// <returns>The decoded object.</returns>
            protected override SaveUrlResult Decode(string tag, enc.IJsonReader reader)
            {
                switch (tag)
                {
                    case "complete":
                        return Complete.Decoder.DecodeFields(reader);
                    case "async_job_id":
                        return AsyncJobId.Decoder.DecodeFields(reader);
                    default:
                        throw new sys.InvalidOperationException();
                }
            }
        }

        #endregion

        /// <summary>
        /// <para>Metadata of the file where the URL is saved to.</para>
        /// </summary>
        public sealed class Complete : SaveUrlResult
        {
            #pragma warning disable 108

            /// <summary>
            /// <para>The encoder instance.</para>
            /// </summary>
            internal static enc.StructEncoder<Complete> Encoder = new CompleteEncoder();

            /// <summary>
            /// <para>The decoder instance.</para>
            /// </summary>
            internal static enc.StructDecoder<Complete> Decoder = new CompleteDecoder();

            /// <summary>
            /// <para>Initializes a new instance of the <see cref="Complete" /> class.</para>
            /// </summary>
            /// <param name="value">The value</param>
            public Complete(FileMetadata value)
            {
                this.Value = value;
            }
            /// <summary>
            /// <para>Initializes a new instance of the <see cref="Complete" /> class.</para>
            /// </summary>
            private Complete()
            {
            }

            /// <summary>
            /// <para>Gets the value of this instance.</para>
            /// </summary>
            public FileMetadata Value { get; private set; }

            #region Encoder class

            /// <summary>
            /// <para>Encoder for  <see cref="Complete" />.</para>
            /// </summary>
            private class CompleteEncoder : enc.StructEncoder<Complete>
            {
                /// <summary>
                /// <para>Encode fields of given value.</para>
                /// </summary>
                /// <param name="value">The value.</param>
                /// <param name="writer">The writer.</param>
                public override void EncodeFields(Complete value, enc.IJsonWriter writer)
                {
                    WriteProperty("complete", value.Value, writer, global::Dropbox.Api.Files.FileMetadata.Encoder);
                }
            }

            #endregion

            #region Decoder class

            /// <summary>
            /// <para>Decoder for  <see cref="Complete" />.</para>
            /// </summary>
            private class CompleteDecoder : enc.StructDecoder<Complete>
            {
                /// <summary>
                /// <para>Create a new instance of type <see cref="Complete" />.</para>
                /// </summary>
                /// <returns>The struct instance.</returns>
                protected override Complete Create()
                {
                    return new Complete();
                }

                /// <summary>
                /// <para>Decode fields without ensuring start and end object.</para>
                /// </summary>
                /// <param name="reader">The json reader.</param>
                /// <returns>The decoded object.</returns>
                public override Complete DecodeFields(enc.IJsonReader reader)
                {
                    return new Complete(global::Dropbox.Api.Files.FileMetadata.Decoder.DecodeFields(reader));
                }
            }

            #endregion
        }

        /// <summary>
        /// <para>This response indicates that the processing is asynchronous. The string is an
        /// id that can be used to obtain the status of the asynchronous job.</para>
        /// </summary>
        public sealed class AsyncJobId : SaveUrlResult
        {
            #pragma warning disable 108

            /// <summary>
            /// <para>The encoder instance.</para>
            /// </summary>
            internal static enc.StructEncoder<AsyncJobId> Encoder = new AsyncJobIdEncoder();

            /// <summary>
            /// <para>The decoder instance.</para>
            /// </summary>
            internal static enc.StructDecoder<AsyncJobId> Decoder = new AsyncJobIdDecoder();

            /// <summary>
            /// <para>Initializes a new instance of the <see cref="AsyncJobId" /> class.</para>
            /// </summary>
            /// <param name="value">The value</param>
            public AsyncJobId(string value)
            {
                this.Value = value;
            }
            /// <summary>
            /// <para>Initializes a new instance of the <see cref="AsyncJobId" /> class.</para>
            /// </summary>
            private AsyncJobId()
            {
            }

            /// <summary>
            /// <para>Gets the value of this instance.</para>
            /// </summary>
            public string Value { get; private set; }

            #region Encoder class

            /// <summary>
            /// <para>Encoder for  <see cref="AsyncJobId" />.</para>
            /// </summary>
            private class AsyncJobIdEncoder : enc.StructEncoder<AsyncJobId>
            {
                /// <summary>
                /// <para>Encode fields of given value.</para>
                /// </summary>
                /// <param name="value">The value.</param>
                /// <param name="writer">The writer.</param>
                public override void EncodeFields(AsyncJobId value, enc.IJsonWriter writer)
                {
                    WriteProperty("async_job_id", value.Value, writer, enc.StringEncoder.Instance);
                }
            }

            #endregion

            #region Decoder class

            /// <summary>
            /// <para>Decoder for  <see cref="AsyncJobId" />.</para>
            /// </summary>
            private class AsyncJobIdDecoder : enc.StructDecoder<AsyncJobId>
            {
                /// <summary>
                /// <para>Create a new instance of type <see cref="AsyncJobId" />.</para>
                /// </summary>
                /// <returns>The struct instance.</returns>
                protected override AsyncJobId Create()
                {
                    return new AsyncJobId();
                }

                /// <summary>
                /// <para>Set given field.</para>
                /// </summary>
                /// <param name="value">The field value.</param>
                /// <param name="fieldName">The field name.</param>
                /// <param name="reader">The json reader.</param>
                protected override void SetField(AsyncJobId value, string fieldName, enc.IJsonReader reader)
                {
                    switch (fieldName)
                    {
                        case "async_job_id":
                            value.Value = enc.StringDecoder.Instance.Decode(reader);
                            break;
                        default:
                            reader.Skip();
                            break;
                    }
                }
            }

            #endregion
        }
    }
}


text:
/**
* ## Action Wrapper ##
*
* - Author: Amin Meyghani
* - Date: 11/4/2014
* - Description: The Action Wrapper
*
**/

/**
* ##`Action Wrapper`
*
* ### Description ###
*
* Simple wrapper for the commander program object. Acts as an API and can be used for creating custom actions.
*
* ### Methods: ###
*
* 1. __add__ : Used to add/register tasks/actions.
*/

var program = require("commander");

var action = {
// add
// -------------
	/**
	* ##`add(options, callback)`
	*
	* ### Description ###
	*
	* Adds/creates tasks on the commander module/program.
	*
	* ### Parameters: ###
	* 1. __options__ : *object* The configuration object that contains the following:

	*   - name: *string* (required): The name of the task/action/keyword
	*   - arg: *string* The argument that refers to the the value that is immediately followed by the keyword/action.
	*   - params: *string* The argument that refers to the array of arguments followed by the `arg` argument.
	*   - description: *string* The action/task description.
	* 2. __callback__ : *function* The function that does the heavy lifting. This callback takes three parameters:
	*
	*   - [data]: the first parameter references the tasks/program object.
	*   - [arg]: the second parameter refers to the argument that is followed by the keyword/task name.
	*   - [params]: the third argument references the array of arguments passed after the `arg`.
	*
	* ### Usage ###
	*   You can use the add method to register tasks or commands with a keyword and a parameter. Then pass it a callback to do whatever you like to do.
	*
	* ### Examples ###
	*
	*   Example1: Creating/adding a command that prints "Salute [name]" given a string
	*
	*     var action = require("./action");
	*     action.add({name: "hello", arg: "name"}, function(d, name) {
	*     	console.log("Salute " + name);
	*     });
	*
	*     use: boiler hello amino -> Salute amino
	*
	*    Example 2: Create/add a command/action that prints a list of names, and name it helloall
	*
	*     var action = require("./action");
	*     action.add({name: "helloall", arg: "dummy", params: "names"}, function(d, what, nms) {
	*     nms.forEach(function(n) {
	*     	console.log("hello " + n);
	*     });
	*
	*     // note: we need the dummy placeholder for the correct parsing of the parameters. Limitation of the underlying module.
	*
	*     use: boiler helloall x n1 n2 n3 //-> hello n1 \n hello n2 \n hello n3
	*/

	add: function(options, callback) {
		var cmdString = options.name;
		if(options.arg) { cmdString += " <" + options.arg + ">"; }
		if(options.params)  { cmdString +=" ["+options.params+"...]"; }
		try {
			if(!options.name) {
				throw new Error("All Task/action definitions need to have a name. i.e. action.add({ name: 'taskname', .... })")
			} else {
				program
					.command(cmdString)
					.description(options.description)
					.action(function(arg, params) {
						callback(program, arg, params);
					});
			}
		} catch(e) {
			__blogger.error(e.stack);
		}
		return program;
	}
}

module.exports = action;


text:
from __future__ import unicode_literals

import pytest
from stack import Stack

def test_initialization():
    stack = Stack()
    assert isinstance(stack, Stack)
    assert stack.list.head is None

def test_push():
    stack = Stack()
    stack.push(5)
    assert stack.list.head.value == 5

def test_pop():
    stack = Stack()
    stack.push(5)
    assert stack.pop() == 5

def test_initialization_list():
    stack = Stack([5, 10, 'string'])
    assert stack.pop() == 'string'
    assert stack.pop() == 10
    assert stack.pop() == 5

def test_pop_empty():
    stack = Stack()
    with pytest.raises(IndexError):
        stack.pop()


text:
<?php

/**
 *
 * @package CRM
 * @copyright CiviCRM LLC (c) 2004-2015
 * $Id$
 *
 */
class CRM_Import_DataSource_SQL extends CRM_Import_DataSource {

  /**
   * Provides information about the data source.
   *
   * @return array
   *   collection of info about this data source
   */
  public function getInfo() {
    return array('title' => ts('SQL Query'));
  }

  /**
   * Set variables up before form is built.
   *
   * @param CRM_Core_Form $form
   */
  public function preProcess(&$form) {
  }

  /**
   * This is function is called by the form object to get the DataSource's
   * form snippet. It should add all fields necesarry to get the data
   * uploaded to the temporary table in the DB.
   *
   * @param CRM_Core_Form $form
   *
   * @return void
   *   (operates directly on form argument)
   */
  public function buildQuickForm(&$form) {
    $form->add('hidden', 'hidden_dataSource', 'CRM_Import_DataSource_SQL');
    $form->add('textarea', 'sqlQuery', ts('Specify SQL Query'), 'rows=10 cols=45', TRUE);
    $form->addFormRule(array('CRM_Import_DataSource_SQL', 'formRule'), $form);
  }

  /**
   * @param $fields
   * @param $files
   * @param CRM_Core_Form $form
   *
   * @return array|bool
   */
  public static function formRule($fields, $files, $form) {
    $errors = array();

    // poor man's query validation (case-insensitive regex matching on word boundaries)
    $forbidden = array('ALTER', 'CREATE', 'DELETE', 'DESCRIBE', 'DROP', 'SHOW', 'UPDATE', 'information_schema');
    foreach ($forbidden as $pattern) {
      if (preg_match("/\\b$pattern\\b/i", $fields['sqlQuery'])) {
        $errors['sqlQuery'] = ts('The query contains the forbidden %1 command.', array(1 => $pattern));
      }
    }

    return $errors ? $errors : TRUE;
  }

  /**
   * Process the form submission.
   */
  public function postProcess(&$params, &$db, &$form) {
    $importJob = new CRM_Contact_Import_ImportJob(
      CRM_Utils_Array::value('import_table_name', $params),
      $params['sqlQuery'], TRUE
    );

    $form->set('importTableName', $importJob->getTableName());
  }

}


text:
#include "server/http/admin.h"

#include <algorithm>
#include <cstdint>
#include <fstream>
#include <regex>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

#include "envoy/admin/v2alpha/certs.pb.h"
#include "envoy/admin/v2alpha/clusters.pb.h"
#include "envoy/admin/v2alpha/config_dump.pb.h"
#include "envoy/admin/v2alpha/memory.pb.h"
#include "envoy/admin/v2alpha/mutex_stats.pb.h"
#include "envoy/admin/v2alpha/server_info.pb.h"
#include "envoy/filesystem/filesystem.h"
#include "envoy/runtime/runtime.h"
#include "envoy/server/hot_restart.h"
#include "envoy/server/instance.h"
#include "envoy/server/options.h"
#include "envoy/stats/scope.h"
#include "envoy/stats/stats.h"
#include "envoy/upstream/cluster_manager.h"
#include "envoy/upstream/upstream.h"

#include "common/access_log/access_log_formatter.h"
#include "common/access_log/access_log_impl.h"
#include "common/buffer/buffer_impl.h"
#include "common/common/assert.h"
#include "common/common/empty_string.h"
#include "common/common/enum_to_int.h"
#include "common/common/fmt.h"
#include "common/common/mutex_tracer_impl.h"
#include "common/common/utility.h"
#include "common/common/version.h"
#include "common/html/utility.h"
#include "common/http/codes.h"
#include "common/http/conn_manager_utility.h"
#include "common/http/header_map_impl.h"
#include "common/http/headers.h"
#include "common/json/json_loader.h"
#include "common/memory/stats.h"
#include "common/network/listen_socket_impl.h"
#include "common/network/utility.h"
#include "common/profiler/profiler.h"
#include "common/router/config_impl.h"
#include "common/stats/histogram_impl.h"
#include "common/upstream/host_utility.h"

#include "extensions/access_loggers/file/file_access_log_impl.h"

#include "absl/strings/str_join.h"
#include "absl/strings/str_replace.h"
#include "absl/strings/string_view.h"

// TODO(mattklein123): Switch to JSON interface methods and remove rapidjson dependency.
#include "rapidjson/document.h"
#include "rapidjson/error/en.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/reader.h"
#include "rapidjson/schema.h"
#include "rapidjson/stream.h"
#include "rapidjson/stringbuffer.h"
#include "spdlog/spdlog.h"

using namespace rapidjson;

namespace Envoy {
namespace Server {

namespace {

/**
 * Favicon base64 image was harvested by screen-capturing the favicon from a Chrome tab
 * while visiting https://www.envoyproxy.io/. The resulting PNG was translated to base64
 * by dropping it into https://www.base64-image.de/ and then pasting the resulting string
 * below.
 *
 * The actual favicon source for that, https://www.envoyproxy.io/img/favicon.ico is nicer
 * because it's transparent, but is also 67646 bytes, which is annoying to inline. We could
 * just reference that rather than inlining it, but then the favicon won't work when visiting
 * the admin page from a network that can't see the internet.
 */
const char EnvoyFavicon[] =
    "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1"
    "BAACxjwv8YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAAH9SURBVEhL7ZRdTttAFIUrUFaAX5w9gIhgUfzshFRK+gIbaVbA"
    "zwaqCly1dSpKk5A485/YCdXpHTB4BsdgVe0bD0cZ3Xsm38yZ8byTUuJ/6g3wqqoBrBhPTzmmLfptMbAzttJTpTKAF2MWC"
    "7ADCdNIwXZpvMMwayiIwwS874CcOc9VuQPR1dBBChPMITpFXXU45hukIIH6kHhzVqkEYB8F5HYGvZ5B7EvwmHt9K/59Cr"
    "U3QbY2RNYaQPYmJc+jPIBICNCcg20ZsAsCPfbcrFlRF+cJZpvXSJt9yMTxO/IAzJrCOfhJXiOgFEX/SbZmezTWxyNk4Q9"
    "anHMmjnzAhEyhAW8LCE6wl26J7ZFHH1FMYQxh567weQBOO1AW8D7P/UXAQySq/QvL8Fu9HfCEw4SKALm5BkC3bwjwhSKr"
    "A5hYAMXTJnPNiMyRBVzVjcgCyHiSm+8P+WGlnmwtP2RzbCMiQJ0d2KtmmmPorRHEhfMROVfTG5/fYrF5iWXzE80tfy9WP"
    "sCqx5Buj7FYH0LvDyHiqd+3otpsr4/fa5+xbEVQPfrYnntylQG5VGeMLBhgEfyE7o6e6qYzwHIjwl0QwXSvvTmrVAY4D5"
    "ddvT64wV0jRrr7FekO/XEjwuwwhuw7Ef7NY+dlfXpLb06EtHUJdVbsxvNUqBrwj/QGeEUSfwBAkmWHn5Bb/gAAAABJRU5"
    "ErkJggg==";

const char AdminHtmlStart[] = R"(

  <title>Envoy Admin</title>
  <link rel='shortcut icon' type='image/png' href='@FAVICON@'/>

      Command
      Description

)";

const char AdminHtmlEnd[] = R"(

)";

const std::regex PromRegex("[^a-zA-Z0-9_]");

void populateFallbackResponseHeaders(Http::Code code, Http::HeaderMap& header_map) {
  header_map.insertStatus().value(std::to_string(enumToInt(code)));
  const auto& headers = Http::Headers::get();
  if (header_map.ContentType() == nullptr) {
    // Default to text-plain if unset.
    header_map.insertContentType().value().setReference(headers.ContentTypeValues.TextUtf8);
  }
  // Default to 'no-cache' if unset, but not 'no-store' which may break the back button.
  if (header_map.CacheControl() == nullptr) {
    header_map.insertCacheControl().value().setReference(headers.CacheControlValues.NoCacheMaxAge0);
  }

  // Under no circumstance should browsers sniff content-type.
  header_map.addReference(headers.XContentTypeOptions, headers.XContentTypeOptionValues.Nosniff);
}

// Helper method that ensures that we've setting flags based on all the health flag values on the
// host.
void setHealthFlag(Upstream::Host::HealthFlag flag, const Upstream::Host& host,
                   envoy::admin::v2alpha::HostHealthStatus& health_status) {
  switch (flag) {
  case Upstream::Host::HealthFlag::FAILED_ACTIVE_HC:
    health_status.set_failed_active_health_check(
        host.healthFlagGet(Upstream::Host::HealthFlag::FAILED_ACTIVE_HC));
    break;
  case Upstream::Host::HealthFlag::FAILED_OUTLIER_CHECK:
    health_status.set_failed_outlier_check(
        host.healthFlagGet(Upstream::Host::HealthFlag::FAILED_OUTLIER_CHECK));
    break;
  case Upstream::Host::HealthFlag::FAILED_EDS_HEALTH:
  case Upstream::Host::HealthFlag::DEGRADED_EDS_HEALTH:
    if (host.healthFlagGet(Upstream::Host::HealthFlag::FAILED_EDS_HEALTH)) {
      health_status.set_eds_health_status(envoy::api::v2::core::HealthStatus::UNHEALTHY);
    } else if (host.healthFlagGet(Upstream::Host::HealthFlag::DEGRADED_EDS_HEALTH)) {
      health_status.set_eds_health_status(envoy::api::v2::core::HealthStatus::DEGRADED);
    } else {
      health_status.set_eds_health_status(envoy::api::v2::core::HealthStatus::HEALTHY);
    }
    break;
  case Upstream::Host::HealthFlag::DEGRADED_ACTIVE_HC:
    health_status.set_failed_active_degraded_check(
        host.healthFlagGet(Upstream::Host::HealthFlag::DEGRADED_ACTIVE_HC));
    break;
  }
}
} // namespace

AdminFilter::AdminFilter(AdminImpl& parent) : parent_(parent) {}

Http::FilterHeadersStatus AdminFilter::decodeHeaders(Http::HeaderMap& headers, bool end_stream) {
  request_headers_ = &headers;
  if (end_stream) {
    onComplete();
  }

  return Http::FilterHeadersStatus::StopIteration;
}

Http::FilterDataStatus AdminFilter::decodeData(Buffer::Instance& data, bool end_stream) {
  // Currently we generically buffer all admin request data in case a handler wants to use it.
  // If we ever support streaming admin requests we may need to revisit this. Note, we must use
  // addDecodedData() here since we might need to perform onComplete() processing if end_stream is
  // true.
  callbacks_->addDecodedData(data, false);

  if (end_stream) {
    onComplete();
  }

  return Http::FilterDataStatus::StopIterationNoBuffer;
}

Http::FilterTrailersStatus AdminFilter::decodeTrailers(Http::HeaderMap&) {
  onComplete();
  return Http::FilterTrailersStatus::StopIteration;
}

void AdminFilter::onDestroy() {
  for (const auto& callback : on_destroy_callbacks_) {
    callback();
  }
}

void AdminFilter::addOnDestroyCallback(std::function<void()> cb) {
  on_destroy_callbacks_.push_back(std::move(cb));
}

Http::StreamDecoderFilterCallbacks& AdminFilter::getDecoderFilterCallbacks() const {
  ASSERT(callbacks_ != nullptr);
  return *callbacks_;
}

const Buffer::Instance* AdminFilter::getRequestBody() const { return callbacks_->decodingBuffer(); }

const Http::HeaderMap& AdminFilter::getRequestHeaders() const {
  ASSERT(request_headers_ != nullptr);
  return *request_headers_;
}

bool AdminImpl::changeLogLevel(const Http::Utility::QueryParams& params) {
  if (params.size() != 1) {
    return false;
  }

  std::string name = params.begin()->first;
  std::string level = params.begin()->second;

  // First see if the level is valid.
  size_t level_to_use = std::numeric_limits<size_t>::max();
  for (size_t i = 0; i < ARRAY_SIZE(spdlog::level::level_string_views); i++) {
    if (level == spdlog::level::level_string_views[i]) {
      level_to_use = i;
      break;
    }
  }

  if (level_to_use == std::numeric_limits<size_t>::max()) {
    return false;
  }

  // Now either change all levels or a single level.
  if (name == "level") {
    ENVOY_LOG(debug, "change all log levels: level='{}'", level);
    for (Logger::Logger& logger : Logger::Registry::loggers()) {
      logger.setLevel(static_cast<spdlog::level::level_enum>(level_to_use));
    }
  } else {
    ENVOY_LOG(debug, "change log level: name='{}' level='{}'", name, level);
    Logger::Logger* logger_to_change = nullptr;
    for (Logger::Logger& logger : Logger::Registry::loggers()) {
      if (logger.name() == name) {
        logger_to_change = &logger;
        break;
      }
    }

    if (!logger_to_change) {
      return false;
    }

    logger_to_change->setLevel(static_cast<spdlog::level::level_enum>(level_to_use));
  }

  return true;
}

void AdminImpl::addOutlierInfo(const std::string& cluster_name,
                               const Upstream::Outlier::Detector* outlier_detector,
                               Buffer::Instance& response) {
  if (outlier_detector) {
    response.add(fmt::format("{}::outlier::success_rate_average::{}\n", cluster_name,
                             outlier_detector->successRateAverage()));
    response.add(fmt::format("{}::outlier::success_rate_ejection_threshold::{}\n", cluster_name,
                             outlier_detector->successRateEjectionThreshold()));
  }
}

void AdminImpl::addCircuitSettings(const std::string& cluster_name, const std::string& priority_str,
                                   Upstream::ResourceManager& resource_manager,
                                   Buffer::Instance& response) {
  response.add(fmt::format("{}::{}_priority::max_connections::{}\n", cluster_name, priority_str,
                           resource_manager.connections().max()));
  response.add(fmt::format("{}::{}_priority::max_pending_requests::{}\n", cluster_name,
                           priority_str, resource_manager.pendingRequests().max()));
  response.add(fmt::format("{}::{}_priority::max_requests::{}\n", cluster_name, priority_str,
                           resource_manager.requests().max()));
  response.add(fmt::format("{}::{}_priority::max_retries::{}\n", cluster_name, priority_str,
                           resource_manager.retries().max()));
}

void AdminImpl::writeClustersAsJson(Buffer::Instance& response) {
  envoy::admin::v2alpha::Clusters clusters;
  for (auto& cluster_pair : server_.clusterManager().clusters()) {
    const Upstream::Cluster& cluster = cluster_pair.second.get();
    Upstream::ClusterInfoConstSharedPtr cluster_info = cluster.info();

    envoy::admin::v2alpha::ClusterStatus& cluster_status = *clusters.add_cluster_statuses();
    cluster_status.set_name(cluster_info->name());

    const Upstream::Outlier::Detector* outlier_detector = cluster.outlierDetector();
    if (outlier_detector != nullptr && outlier_detector->successRateEjectionThreshold() > 0.0) {
      cluster_status.mutable_success_rate_ejection_threshold()->set_value(
          outlier_detector->successRateEjectionThreshold());
    }

    cluster_status.set_added_via_api(cluster_info->addedViaApi());

    for (auto& host_set : cluster.prioritySet().hostSetsPerPriority()) {
      for (auto& host : host_set->hosts()) {
        envoy::admin::v2alpha::HostStatus& host_status = *cluster_status.add_host_statuses();
        Network::Utility::addressToProtobufAddress(*host->address(),
                                                   *host_status.mutable_address());
        std::vector<Stats::CounterSharedPtr> sorted_counters;
        for (const Stats::CounterSharedPtr& counter : host->counters()) {
          sorted_counters.push_back(counter);
        }
        std::sort(
            sorted_counters.begin(), sorted_counters.end(),
            [](const Stats::CounterSharedPtr& counter1, const Stats::CounterSharedPtr& counter2) {
              return counter1->name() < counter2->name();
            });

        for (const Stats::CounterSharedPtr& counter : sorted_counters) {
          auto& metric = *host_status.add_stats();
          metric.set_name(counter->name());
          metric.set_value(counter->value());
          metric.set_type(envoy::admin::v2alpha::SimpleMetric::COUNTER);
        }

        std::vector<Stats::GaugeSharedPtr> sorted_gauges;
        for (const Stats::GaugeSharedPtr& gauge : host->gauges()) {
          sorted_gauges.push_back(gauge);
        }
        std::sort(sorted_gauges.begin(), sorted_gauges.end(),
                  [](const Stats::GaugeSharedPtr& gauge1, const Stats::GaugeSharedPtr& gauge2) {
                    return gauge1->name() < gauge2->name();
                  });

        for (const Stats::GaugeSharedPtr& gauge : sorted_gauges) {
          auto& metric = *host_status.add_stats();
          metric.set_name(gauge->name());
          metric.set_value(gauge->value());
          metric.set_type(envoy::admin::v2alpha::SimpleMetric::GAUGE);
        }

        envoy::admin::v2alpha::HostHealthStatus& health_status =
            *host_status.mutable_health_status();

// Invokes setHealthFlag for each health flag.
#define SET_HEALTH_FLAG(name, notused)                                                             \
  setHealthFlag(Upstream::Host::HealthFlag::name, *host, health_status);
        HEALTH_FLAG_ENUM_VALUES(SET_HEALTH_FLAG)
#undef SET_HEALTH_FLAG

        double success_rate = host->outlierDetector().successRate();
        if (success_rate >= 0.0) {
          host_status.mutable_success_rate()->set_value(success_rate);
        }

        host_status.set_weight(host->weight());
      }
    }
  }
  response.add(MessageUtil::getJsonStringFromMessage(clusters, true)); // pretty-print
}

void AdminImpl::writeClustersAsText(Buffer::Instance& response) {
  for (auto& cluster : server_.clusterManager().clusters()) {
    addOutlierInfo(cluster.second.get().info()->name(), cluster.second.get().outlierDetector(),
                   response);

    addCircuitSettings(
        cluster.second.get().info()->name(), "default",
        cluster.second.get().info()->resourceManager(Upstream::ResourcePriority::Default),
        response);
    addCircuitSettings(
        cluster.second.get().info()->name(), "high",
        cluster.second.get().info()->resourceManager(Upstream::ResourcePriority::High), response);

    response.add(fmt::format("{}::added_via_api::{}\n", cluster.second.get().info()->name(),
                             cluster.second.get().info()->addedViaApi()));
    for (auto& host_set : cluster.second.get().prioritySet().hostSetsPerPriority()) {
      for (auto& host : host_set->hosts()) {
        std::map<std::string, uint64_t> all_stats;
        for (const Stats::CounterSharedPtr& counter : host->counters()) {
          all_stats[counter->name()] = counter->value();
        }

        for (const Stats::GaugeSharedPtr& gauge : host->gauges()) {
          all_stats[gauge->name()] = gauge->value();
        }

        for (auto stat : all_stats) {
          response.add(fmt::format("{}::{}::{}::{}\n", cluster.second.get().info()->name(),
                                   host->address()->asString(), stat.first, stat.second));
        }

        response.add(fmt::format("{}::{}::health_flags::{}\n", cluster.second.get().info()->name(),
                                 host->address()->asString(),
                                 Upstream::HostUtility::healthFlagsToString(*host)));
        response.add(fmt::format("{}::{}::weight::{}\n", cluster.second.get().info()->name(),
                                 host->address()->asString(), host->weight()));
        response.add(fmt::format("{}::{}::region::{}\n", cluster.second.get().info()->name(),
                                 host->address()->asString(), host->locality().region()));
        response.add(fmt::format("{}::{}::zone::{}\n", cluster.second.get().info()->name(),
                                 host->address()->asString(), host->locality().zone()));
        response.add(fmt::format("{}::{}::sub_zone::{}\n", cluster.second.get().info()->name(),
                                 host->address()->asString(), host->locality().sub_zone()));
        response.add(fmt::format("{}::{}::canary::{}\n", cluster.second.get().info()->name(),
                                 host->address()->asString(), host->canary()));
        response.add(fmt::format("{}::{}::success_rate::{}\n", cluster.second.get().info()->name(),
                                 host->address()->asString(),
                                 host->outlierDetector().successRate()));
      }
    }
  }
}

Http::Code AdminImpl::handlerClusters(absl::string_view url, Http::HeaderMap& response_headers,
                                      Buffer::Instance& response, AdminStream&) {
  Http::Utility::QueryParams query_params = Http::Utility::parseQueryString(url);
  auto it = query_params.find("format");

  if (it != query_params.end() && it->second == "json") {
    writeClustersAsJson(response);
    response_headers.insertContentType().value().setReference(
        Http::Headers::get().ContentTypeValues.Json);
  } else {
    writeClustersAsText(response);
  }

  return Http::Code::OK;
}

// TODO(jsedgwick) Use query params to list available dumps, selectively dump, etc
Http::Code AdminImpl::handlerConfigDump(absl::string_view, Http::HeaderMap& response_headers,
                                        Buffer::Instance& response, AdminStream&) const {
  envoy::admin::v2alpha::ConfigDump dump;
  for (const auto& key_callback_pair : config_tracker_.getCallbacksMap()) {
    ProtobufTypes::MessagePtr message = key_callback_pair.second();
    RELEASE_ASSERT(message, "");
    auto& any_message = *(dump.add_configs());
    any_message.PackFrom(*message);
  }

  response_headers.insertContentType().value().setReference(
      Http::Headers::get().ContentTypeValues.Json);
  response.add(MessageUtil::getJsonStringFromMessage(dump, true)); // pretty-print
  return Http::Code::OK;
}

// TODO(ambuc) Export this as a server (?) stat for monitoring.
Http::Code AdminImpl::handlerContention(absl::string_view, Http::HeaderMap& response_headers,
                                        Buffer::Instance& response, AdminStream&) {

  if (server_.options().mutexTracingEnabled() && server_.mutexTracer() != nullptr) {
    response_headers.insertContentType().value().setReference(
        Http::Headers::get().ContentTypeValues.Json);

    envoy::admin::v2alpha::MutexStats mutex_stats;
    mutex_stats.set_num_contentions(server_.mutexTracer()->numContentions());
    mutex_stats.set_current_wait_cycles(server_.mutexTracer()->currentWaitCycles());
    mutex_stats.set_lifetime_wait_cycles(server_.mutexTracer()->lifetimeWaitCycles());
    response.add(MessageUtil::getJsonStringFromMessage(mutex_stats, true, true));
  } else {
    response.add("Mutex contention tracing is not enabled. To enable, run Envoy with flag "
                 "--enable-mutex-tracing.");
  }
  return Http::Code::OK;
}

Http::Code AdminImpl::handlerCpuProfiler(absl::string_view url, Http::HeaderMap&,
                                         Buffer::Instance& response, AdminStream&) {
  Http::Utility::QueryParams query_params = Http::Utility::parseQueryString(url);
  if (query_params.size() != 1 || query_params.begin()->first != "enable" ||
      (query_params.begin()->second != "y" && query_params.begin()->second != "n")) {
    response.add("?enable=<y|n>\n");
    return Http::Code::BadRequest;
  }

  bool enable = query_params.begin()->second == "y";
  if (enable && !Profiler::Cpu::profilerEnabled()) {
    if (!Profiler::Cpu::startProfiler(profile_path_)) {
      response.add("failure to start the profiler");
      return Http::Code::InternalServerError;
    }

  } else if (!enable && Profiler::Cpu::profilerEnabled()) {
    Profiler::Cpu::stopProfiler();
  }

  response.add("OK\n");
  return Http::Code::OK;
}

Http::Code AdminImpl::handlerHeapProfiler(absl::string_view url, Http::HeaderMap&,
                                          Buffer::Instance& response, AdminStream&) {
  if (!Profiler::Heap::profilerEnabled()) {
    response.add("The current build does not support heap profiler");
    return Http::Code::NotImplemented;
  }

  Http::Utility::QueryParams query_params = Http::Utility::parseQueryString(url);
  if (query_params.size() != 1 || query_params.begin()->first != "enable" ||
      (query_params.begin()->second != "y" && query_params.begin()->second != "n")) {
    response.add("?enable=<y|n>\n");
    return Http::Code::BadRequest;
  }

  Http::Code res = Http::Code::OK;
  bool enable = query_params.begin()->second == "y";
  if (enable) {
    if (Profiler::Heap::isProfilerStarted()) {
      response.add("Fail to start heap profiler: already started");
      res = Http::Code::BadRequest;
    } else if (!Profiler::Heap::startProfiler(profile_path_)) {
      // GCOVR_EXCL_START
      // TODO(silentdai) remove the GCOVR when startProfiler is better implemented
      response.add("Fail to start the heap profiler");
      res = Http::Code::InternalServerError;
      // GCOVR_EXCL_END
    } else {
      response.add("Starting heap profiler");
      res = Http::Code::OK;
    }
  } else {
    // !enable
    if (!Profiler::Heap::isProfilerStarted()) {
      response.add("Fail to stop heap profiler: not started");
      res = Http::Code::BadRequest;
    } else {
      Profiler::Heap::stopProfiler();
      response.add(
          fmt::format("Heap profiler stopped and data written to {}. See "
                      "http://goog-perftools.sourceforge.net/doc/heap_profiler.html for details.",
                      profile_path_));
      res = Http::Code::OK;
    }
  }
  return res;
}

Http::Code AdminImpl::handlerHealthcheckFail(absl::string_view, Http::HeaderMap&,
                                             Buffer::Instance& response, AdminStream&) {
  server_.failHealthcheck(true);
  response.add("OK\n");
  return Http::Code::OK;
}

Http::Code AdminImpl::handlerHealthcheckOk(absl::string_view, Http::HeaderMap&,
                                           Buffer::Instance& response, AdminStream&) {
  server_.failHealthcheck(false);
  response.add("OK\n");
  return Http::Code::OK;
}

Http::Code AdminImpl::handlerHotRestartVersion(absl::string_view, Http::HeaderMap&,
                                               Buffer::Instance& response, AdminStream&) {
  response.add(server_.hotRestart().version());
  return Http::Code::OK;
}

Http::Code AdminImpl::handlerLogging(absl::string_view url, Http::HeaderMap&,
                                     Buffer::Instance& response, AdminStream&) {
  Http::Utility::QueryParams query_params = Http::Utility::parseQueryString(url);

  Http::Code rc = Http::Code::OK;
  if (!query_params.empty() && !changeLogLevel(query_params)) {
    response.add("usage: /logging?<name>=<level> (change single level)\n");
    response.add("usage: /logging?level=<level> (change all levels)\n");
    response.add("levels: ");
    for (size_t i = 0; i < ARRAY_SIZE(spdlog::level::level_string_views); i++) {
      response.add(fmt::format("{} ", spdlog::level::level_string_views[i]));
    }

    response.add("\n");
    rc = Http::Code::NotFound;
  }

  response.add("active loggers:\n");
  for (const Logger::Logger& logger : Logger::Registry::loggers()) {
    response.add(fmt::format("  {}: {}\n", logger.name(), logger.levelString()));
  }

  response.add("\n");
  return rc;
}

// TODO(ambuc): Add more tcmalloc stats, export proto details based on allocator.
Http::Code AdminImpl::handlerMemory(absl::string_view, Http::HeaderMap& response_headers,
                                    Buffer::Instance& response, AdminStream&) {
  response_headers.insertContentType().value().setReference(
      Http::Headers::get().ContentTypeValues.Json);
  envoy::admin::v2alpha::Memory memory;
  memory.set_allocated(Memory::Stats::totalCurrentlyAllocated());
  memory.set_heap_size(Memory::Stats::totalCurrentlyReserved());
  memory.set_total_thread_cache(Memory::Stats::totalThreadCacheBytes());
  memory.set_pageheap_unmapped(Memory::Stats::totalPageHeapUnmapped());
  memory.set_pageheap_free(Memory::Stats::totalPageHeapFree());
  response.add(MessageUtil::getJsonStringFromMessage(memory, true, true)); // pretty-print
  return Http::Code::OK;
}

Http::Code AdminImpl::handlerResetCounters(absl::string_view, Http::HeaderMap&,
                                           Buffer::Instance& response, AdminStream&) {
  for (const Stats::CounterSharedPtr& counter : server_.stats().counters()) {
    counter->reset();
  }

  response.add("OK\n");
  return Http::Code::OK;
}

Http::Code AdminImpl::handlerServerInfo(absl::string_view, Http::HeaderMap& headers,
                                        Buffer::Instance& response, AdminStream&) {
  time_t current_time = time(nullptr);
  envoy::admin::v2alpha::ServerInfo server_info;
  server_info.set_version(VersionInfo::version());

  switch (server_.initManager().state()) {
  case Init::Manager::State::Uninitialized:
    server_info.set_state(envoy::admin::v2alpha::ServerInfo::PRE_INITIALIZING);
    break;
  case Init::Manager::State::Initializing:
    server_info.set_state(envoy::admin::v2alpha::ServerInfo::INITIALIZING);
    break;
  default:
    server_info.set_state(server_.healthCheckFailed() ? envoy::admin::v2alpha::ServerInfo::DRAINING
                                                      : envoy::admin::v2alpha::ServerInfo::LIVE);
  }
  server_info.mutable_uptime_current_epoch()->set_seconds(current_time -
                                                          server_.startTimeCurrentEpoch());
  server_info.mutable_uptime_all_epochs()->set_seconds(current_time -
                                                       server_.startTimeFirstEpoch());
  envoy::admin::v2alpha::CommandLineOptions* command_line_options =
      server_info.mutable_command_line_options();
  *command_line_options = *server_.options().toCommandLineOptions();
  response.add(MessageUtil::getJsonStringFromMessage(server_info, true, true));
  headers.insertContentType().value().setReference(Http::Headers::get().ContentTypeValues.Json);
  return Http::Code::OK;
}

Http::Code AdminImpl::handlerStats(absl::string_view url, Http::HeaderMap& response_headers,
                                   Buffer::Instance& response, AdminStream& admin_stream) {
  Http::Code rc = Http::Code::OK;
  const Http::Utility::QueryParams params = Http::Utility::parseQueryString(url);

  const bool used_only = params.find("usedonly") != params.end();
  const bool has_format = !(params.find("format") == params.end());
  const absl::optional<std::regex> regex =
      (params.find("filter") != params.end())
          ? absl::optional<std::regex>{std::regex(params.at("filter"))}
          : absl::nullopt;

  std::map<std::string, uint64_t> all_stats;
  for (const Stats::CounterSharedPtr& counter : server_.stats().counters()) {
    if (shouldShowMetric(counter, used_only, regex)) {
      all_stats.emplace(counter->name(), counter->value());
    }
  }

  for (const Stats::GaugeSharedPtr& gauge : server_.stats().gauges()) {
    if (shouldShowMetric(gauge, used_only, regex)) {
      all_stats.emplace(gauge->name(), gauge->value());
    }
  }

  if (has_format) {
    const std::string format_value = params.at("format");
    if (format_value == "json") {
      response_headers.insertContentType().value().setReference(
          Http::Headers::get().ContentTypeValues.Json);
      response.add(
          AdminImpl::statsAsJson(all_stats, server_.stats().histograms(), used_only, regex));
    } else if (format_value == "prometheus") {
      return handlerPrometheusStats(url, response_headers, response, admin_stream);
    } else {
      response.add("usage: /stats?format=json  or /stats?format=prometheus \n");
      response.add("\n");
      rc = Http::Code::NotFound;
    }
  } else { // Display plain stats if format query param is not there.
    for (auto stat : all_stats) {
      response.add(fmt::format("{}: {}\n", stat.first, stat.second));
    }
    // TODO(ramaraochavali): See the comment in ThreadLocalStoreImpl::histograms() for why we use a
    // multimap here. This makes sure that duplicate histograms get output. When shared storage is
    // implemented this can be switched back to a normal map.
    std::multimap<std::string, std::string> all_histograms;
    for (const Stats::ParentHistogramSharedPtr& histogram : server_.stats().histograms()) {
      if (shouldShowMetric(histogram, used_only, regex)) {
        all_histograms.emplace(histogram->name(), histogram->quantileSummary());
      }
    }
    for (auto histogram : all_histograms) {
      response.add(fmt::format("{}: {}\n", histogram.first, histogram.second));
    }
  }
  return rc;
}

Http::Code AdminImpl::handlerPrometheusStats(absl::string_view path_and_query, Http::HeaderMap&,
                                             Buffer::Instance& response, AdminStream&) {
  const Http::Utility::QueryParams params = Http::Utility::parseQueryString(path_and_query);
  const bool used_only = params.find("usedonly") != params.end();
  PrometheusStatsFormatter::statsAsPrometheus(server_.stats().counters(), server_.stats().gauges(),
                                              server_.stats().histograms(), response, used_only);
  return Http::Code::OK;
}

std::string PrometheusStatsFormatter::sanitizeName(const std::string& name) {
  // The name must match the regex [a-zA-Z_][a-zA-Z0-9_]* as required by
  // prometheus. Refer to https://prometheus.io/docs/concepts/data_model/.
  std::string stats_name = std::regex_replace(name, PromRegex, "_");
  if (stats_name[0] >= '0' && stats_name[0] <= '9') {
    return fmt::format("_{}", stats_name);
  } else {
    return stats_name;
  }
}

std::string PrometheusStatsFormatter::formattedTags(const std::vector<Stats::Tag>& tags) {
  std::vector<std::string> buf;
  for (const Stats::Tag& tag : tags) {
    buf.push_back(fmt::format("{}=\"{}\"", sanitizeName(tag.name_), tag.value_));
  }
  return StringUtil::join(buf, ",");
}

std::string PrometheusStatsFormatter::metricName(const std::string& extractedName) {
  // Add namespacing prefix to avoid conflicts, as per best practice:
  // https://prometheus.io/docs/practices/naming/#metric-names
  // Also, naming conventions on https://prometheus.io/docs/concepts/data_model/
  return sanitizeName(fmt::format("envoy_{0}", extractedName));
}

uint64_t PrometheusStatsFormatter::statsAsPrometheus(
    const std::vector<Stats::CounterSharedPtr>& counters,
    const std::vector<Stats::GaugeSharedPtr>& gauges,
    const std::vector<Stats::ParentHistogramSharedPtr>& histograms, Buffer::Instance& response,
    const bool used_only) {
  std::unordered_set<std::string> metric_type_tracker;
  for (const auto& counter : counters) {
    if (!shouldShowMetric(counter, used_only)) {
      continue;
    }

    const std::string tags = formattedTags(counter->tags());
    const std::string metric_name = metricName(counter->tagExtractedName());
    if (metric_type_tracker.find(metric_name) == metric_type_tracker.end()) {
      metric_type_tracker.insert(metric_name);
      response.add(fmt::format("# TYPE {0} counter\n", metric_name));
    }
    response.add(fmt::format("{0}{{{1}}} {2}\n", metric_name, tags, counter->value()));
  }

  for (const auto& gauge : gauges) {
    if (!shouldShowMetric(gauge, used_only)) {
      continue;
    }

    const std::string tags = formattedTags(gauge->tags());
    const std::string metric_name = metricName(gauge->tagExtractedName());
    if (metric_type_tracker.find(metric_name) == metric_type_tracker.end()) {
      metric_type_tracker.insert(metric_name);
      response.add(fmt::format("# TYPE {0} gauge\n", metric_name));
    }
    response.add(fmt::format("{0}{{{1}}} {2}\n", metric_name, tags, gauge->value()));
  }

  for (const auto& histogram : histograms) {
    if (!shouldShowMetric(histogram, used_only)) {
      continue;
    }

    const std::string tags = formattedTags(histogram->tags());
    const std::string hist_tags = histogram->tags().empty() ? EMPTY_STRING : (tags + ",");

    const std::string metric_name = metricName(histogram->tagExtractedName());
    if (metric_type_tracker.find(metric_name) == metric_type_tracker.end()) {
      metric_type_tracker.insert(metric_name);
      response.add(fmt::format("# TYPE {0} histogram\n", metric_name));
    }

    const Stats::HistogramStatistics& stats = histogram->cumulativeStatistics();
    const std::vector<double>& supported_buckets = stats.supportedBuckets();
    const std::vector<uint64_t>& computed_buckets = stats.computedBuckets();
    for (size_t i = 0; i < supported_buckets.size(); ++i) {
      double bucket = supported_buckets[i];
      uint64_t value = computed_buckets[i];
      // We want to print the bucket in a fixed point (non-scientific) format. The fmt library
      // doesn't have a specific modifier to format as a fixed-point value only so we use the
      // 'g' operator which prints the number in general fixed point format or scientific format
      // with precision 50 to round the number up to 32 significant digits in fixed point format
      // which should cover pretty much all cases
      response.add(fmt::format("{0}_bucket{{{1}le=\"{2:.32g}\"}} {3}\n", metric_name, hist_tags,
                               bucket, value));
    }

    response.add(fmt::format("{0}_bucket{{{1}le=\"+Inf\"}} {2}\n", metric_name, hist_tags,
                             stats.sampleCount()));
    response.add(fmt::format("{0}_sum{{{1}}} {2:.32g}\n", metric_name, tags, stats.sampleSum()));
    response.add(fmt::format("{0}_count{{{1}}} {2}\n", metric_name, tags, stats.sampleCount()));
  }

  return metric_type_tracker.size();
}

std::string
AdminImpl::statsAsJson(const std::map<std::string, uint64_t>& all_stats,
                       const std::vector<Stats::ParentHistogramSharedPtr>& all_histograms,
                       const bool used_only, const absl::optional<std::regex> regex,
                       const bool pretty_print) {
  rapidjson::Document document;
  document.SetObject();
  rapidjson::Value stats_array(rapidjson::kArrayType);
  rapidjson::Document::AllocatorType& allocator = document.GetAllocator();
  for (auto stat : all_stats) {
    Value stat_obj;
    stat_obj.SetObject();
    Value stat_name;
    stat_name.SetString(stat.first.c_str(), allocator);
    stat_obj.AddMember("name", stat_name, allocator);
    Value stat_value;
    stat_value.SetInt(stat.second);
    stat_obj.AddMember("value", stat_value, allocator);
    stats_array.PushBack(stat_obj, allocator);
  }

  Value histograms_container_obj;
  histograms_container_obj.SetObject();

  Value histograms_obj;
  histograms_obj.SetObject();

  bool found_used_histogram = false;
  rapidjson::Value histogram_array(rapidjson::kArrayType);

  for (const Stats::ParentHistogramSharedPtr& histogram : all_histograms) {
    if (shouldShowMetric(histogram, used_only, regex)) {
      if (!found_used_histogram) {
        // It is not possible for the supported quantiles to differ across histograms, so it is ok
        // to send them once.
        Stats::HistogramStatisticsImpl empty_statistics;
        rapidjson::Value supported_quantile_array(rapidjson::kArrayType);
        for (double quantile : empty_statistics.supportedQuantiles()) {
          Value quantile_type;
          quantile_type.SetDouble(quantile * 100);
          supported_quantile_array.PushBack(quantile_type, allocator);
        }
        histograms_obj.AddMember("supported_quantiles", supported_quantile_array, allocator);
        found_used_histogram = true;
      }
      Value histogram_obj;
      histogram_obj.SetObject();
      Value histogram_name;
      histogram_name.SetString(histogram->name().c_str(), allocator);
      histogram_obj.AddMember("name", histogram_name, allocator);

      rapidjson::Value computed_quantile_array(rapidjson::kArrayType);

      for (size_t i = 0; i < histogram->intervalStatistics().supportedQuantiles().size(); ++i) {
        Value quantile_obj;
        quantile_obj.SetObject();
        Value interval_value;
        if (!std::isnan(histogram->intervalStatistics().computedQuantiles()[i])) {
          interval_value.SetDouble(histogram->intervalStatistics().computedQuantiles()[i]);
        }
        quantile_obj.AddMember("interval", interval_value, allocator);
        Value cumulative_value;
        // We skip nan entries to put in the {null, null} entry to keep other data aligned.
        if (!std::isnan(histogram->cumulativeStatistics().computedQuantiles()[i])) {
          cumulative_value.SetDouble(histogram->cumulativeStatistics().computedQuantiles()[i]);
        }
        quantile_obj.AddMember("cumulative", cumulative_value, allocator);
        computed_quantile_array.PushBack(quantile_obj, allocator);
      }
      histogram_obj.AddMember("values", computed_quantile_array, allocator);
      histogram_array.PushBack(histogram_obj, allocator);
    }
  }
  if (found_used_histogram) {
    histograms_obj.AddMember("computed_quantiles", histogram_array, allocator);
    histograms_container_obj.AddMember("histograms", histograms_obj, allocator);
    stats_array.PushBack(histograms_container_obj, allocator);
  }
  document.AddMember("stats", stats_array, allocator);
  rapidjson::StringBuffer strbuf;
  if (pretty_print) {
    rapidjson::PrettyWriter<StringBuffer> writer(strbuf);
    document.Accept(writer);
  } else {
    rapidjson::Writer<StringBuffer> writer(strbuf);
    document.Accept(writer);
  }
  return strbuf.GetString();
}

Http::Code AdminImpl::handlerQuitQuitQuit(absl::string_view, Http::HeaderMap&,
                                          Buffer::Instance& response, AdminStream&) {
  server_.shutdown();
  response.add("OK\n");
  return Http::Code::OK;
}

Http::Code AdminImpl::handlerListenerInfo(absl::string_view, Http::HeaderMap& response_headers,
                                          Buffer::Instance& response, AdminStream&) {
  response_headers.insertContentType().value().setReference(
      Http::Headers::get().ContentTypeValues.Json);
  std::list<std::string> listeners;
  for (auto listener : server_.listenerManager().listeners()) {
    listeners.push_back(listener.get().socket().localAddress()->asString());
  }
  response.add(Json::Factory::listAsJsonString(listeners));
  return Http::Code::OK;
}

Http::Code AdminImpl::handlerCerts(absl::string_view, Http::HeaderMap& response_headers,
                                   Buffer::Instance& response, AdminStream&) {
  // This set is used to track distinct certificates. We may have multiple listeners, upstreams, etc
  // using the same cert.
  response_headers.insertContentType().value().setReference(
      Http::Headers::get().ContentTypeValues.Json);
  envoy::admin::v2alpha::Certificates certificates;
  server_.sslContextManager().iterateContexts([&](const Ssl::Context& context) -> void {
    envoy::admin::v2alpha::Certificate& certificate = *certificates.add_certificates();
    if (context.getCaCertInformation() != nullptr) {
      envoy::admin::v2alpha::CertificateDetails* ca_certificate = certificate.add_ca_cert();
      *ca_certificate = *context.getCaCertInformation();
    }
    for (const auto& cert_details : context.getCertChainInformation()) {
      envoy::admin::v2alpha::CertificateDetails* cert_chain = certificate.add_cert_chain();
      *cert_chain = *cert_details;
    }
  });
  response.add(MessageUtil::getJsonStringFromMessage(certificates, true, true));
  return Http::Code::OK;
}

Http::Code AdminImpl::handlerRuntime(absl::string_view url, Http::HeaderMap& response_headers,
                                     Buffer::Instance& response, AdminStream&) {
  const Http::Utility::QueryParams params = Http::Utility::parseQueryString(url);
  response_headers.insertContentType().value().setReference(
      Http::Headers::get().ContentTypeValues.Json);

  // TODO(jsedgwick) Use proto to structure this output instead of arbitrary JSON
  rapidjson::Document document;
  document.SetObject();
  auto& allocator = document.GetAllocator();
  std::map<std::string, rapidjson::Value> entry_objects;
  rapidjson::Value layer_names{rapidjson::kArrayType};
  const auto& layers = server_.runtime().snapshot().getLayers();

  for (const auto& layer : layers) {
    rapidjson::Value layer_name;
    layer_name.SetString(layer->name().c_str(), allocator);
    layer_names.PushBack(std::move(layer_name), allocator);
    for (const auto& kv : layer->values()) {
      rapidjson::Value entry_object{rapidjson::kObjectType};
      const auto it = entry_objects.find(kv.first);
      if (it == entry_objects.end()) {
        rapidjson::Value entry_object{rapidjson::kObjectType};
        entry_object.AddMember("layer_values", rapidjson::Value{kArrayType}, allocator);
        entry_object.AddMember("final_value", "", allocator);
        entry_objects.emplace(kv.first, std::move(entry_object));
      }
    }
  }
  document.AddMember("layers", std::move(layer_names), allocator);

  for (const auto& layer : layers) {
    for (auto& kv : entry_objects) {
      const auto it = layer->values().find(kv.first);
      const auto& entry_value = it == layer->values().end() ? "" : it->second.raw_string_value_;
      rapidjson::Value entry_value_object;
      entry_value_object.SetString(entry_value.c_str(), allocator);
      if (!entry_value.empty()) {
        kv.second["final_value"] = rapidjson::Value{entry_value_object, allocator};
      }
      kv.second["layer_values"].PushBack(entry_value_object, allocator);
    }
  }

  rapidjson::Value value_arrays_obj{rapidjson::kObjectType};
  for (auto& kv : entry_objects) {
    value_arrays_obj.AddMember(rapidjson::StringRef(kv.first.c_str()), std::move(kv.second),
                               allocator);
  }

  document.AddMember("entries", std::move(value_arrays_obj), allocator);

  rapidjson::StringBuffer strbuf;
  rapidjson::PrettyWriter<StringBuffer> writer(strbuf);
  document.Accept(writer);
  response.add(strbuf.GetString());
  return Http::Code::OK;
}

std::string AdminImpl::runtimeAsJson(
    const std::vector<std::pair<std::string, Runtime::Snapshot::Entry>>& entries) {
  rapidjson::Document document;
  document.SetObject();
  rapidjson::Value entries_array(rapidjson::kArrayType);
  rapidjson::Document::AllocatorType& allocator = document.GetAllocator();
  for (const auto& entry : entries) {
    Value entry_obj;
    entry_obj.SetObject();

    entry_obj.AddMember("name", {entry.first.c_str(), allocator}, allocator);

    Value entry_value;
    if (entry.second.uint_value_) {
      entry_value.SetUint64(entry.second.uint_value_.value());
    } else {
      entry_value.SetString(entry.second.raw_string_value_.c_str(), allocator);
    }
    entry_obj.AddMember("value", entry_value, allocator);

    entries_array.PushBack(entry_obj, allocator);
  }
  document.AddMember("runtime", entries_array, allocator);
  rapidjson::StringBuffer strbuf;
  rapidjson::PrettyWriter<StringBuffer> writer(strbuf);
  document.Accept(writer);
  return strbuf.GetString();
}

Http::Code AdminImpl::handlerRuntimeModify(absl::string_view url, Http::HeaderMap&,
                                           Buffer::Instance& response, AdminStream&) {
  const Http::Utility::QueryParams params = Http::Utility::parseQueryString(url);
  if (params.empty()) {
    response.add("usage: /runtime_modify?key1=value1&key2=value2&keyN=valueN\n");
    response.add("use an empty value to remove a previously added override");
    return Http::Code::BadRequest;
  }
  std::unordered_map<std::string, std::string> overrides;
  overrides.insert(params.begin(), params.end());
  server_.runtime().mergeValues(overrides);
  response.add("OK\n");
  return Http::Code::OK;
}

ConfigTracker& AdminImpl::getConfigTracker() { return config_tracker_; }

void AdminFilter::onComplete() {
  absl::string_view path = request_headers_->Path()->value().getStringView();
  ENVOY_STREAM_LOG(debug, "request complete: path: {}", *callbacks_, path);

  Buffer::OwnedImpl response;
  Http::HeaderMapPtr header_map{new Http::HeaderMapImpl};
  RELEASE_ASSERT(request_headers_, "");
  Http::Code code = parent_.runCallback(path, *header_map, response, *this);
  populateFallbackResponseHeaders(code, *header_map);
  callbacks_->encodeHeaders(std::move(header_map),
                            end_stream_on_complete_ && response.length() == 0);

  if (response.length() > 0) {
    callbacks_->encodeData(response, end_stream_on_complete_);
  }
}

AdminImpl::NullRouteConfigProvider::NullRouteConfigProvider(TimeSource& time_source)
    : config_(new Router::NullConfigImpl()), time_source_(time_source) {}

void AdminImpl::startHttpListener(const std::string& access_log_path,
                                  const std::string& address_out_path,
                                  Network::Address::InstanceConstSharedPtr address,
                                  Stats::ScopePtr&& listener_scope) {
  // TODO(mattklein123): Allow admin to use normal access logger extension loading and avoid the
  // hard dependency here.
  access_logs_.emplace_back(new Extensions::AccessLoggers::File::FileAccessLog(
      access_log_path, {}, AccessLog::AccessLogFormatUtils::defaultAccessLogFormatter(),
      server_.accessLogManager()));
  socket_ = std::make_unique<Network::TcpListenSocket>(address, nullptr, true);
  listener_ = std::make_unique<AdminListener>(*this, std::move(listener_scope));
  if (!address_out_path.empty()) {
    std::ofstream address_out_file(address_out_path);
    if (!address_out_file) {
      ENVOY_LOG(critical, "cannot open admin address output file {} for writing.",
                address_out_path);
    } else {
      address_out_file << socket_->localAddress()->asString();
    }
  }
}

AdminImpl::AdminImpl(const std::string& profile_path, Server::Instance& server)
    : server_(server), profile_path_(profile_path),
      stats_(Http::ConnectionManagerImpl::generateStats("http.admin.", server_.stats())),
      tracing_stats_(
          Http::ConnectionManagerImpl::generateTracingStats("http.admin.", no_op_store_)),
      route_config_provider_(server.timeSource()),
      // TODO(jsedgwick) add /runtime_reset endpoint that removes all admin-set values
      handlers_{
          {"/", "Admin home page", MAKE_ADMIN_HANDLER(handlerAdminHome), false, false},
          {"/certs", "print certs on machine", MAKE_ADMIN_HANDLER(handlerCerts), false, false},
          {"/clusters", "upstream cluster status", MAKE_ADMIN_HANDLER(handlerClusters), false,
           false},
          {"/config_dump", "dump current Envoy configs (experimental)",
           MAKE_ADMIN_HANDLER(handlerConfigDump), false, false},
          {"/contention", "dump current Envoy mutex contention stats (if enabled)",
           MAKE_ADMIN_HANDLER(handlerContention), false, false},
          {"/cpuprofiler", "enable/disable the CPU profiler",
           MAKE_ADMIN_HANDLER(handlerCpuProfiler), false, true},
          {"/heapprofiler", "enable/disable the heap profiler",
           MAKE_ADMIN_HANDLER(handlerHeapProfiler), false, true},
          {"/healthcheck/fail", "cause the server to fail health checks",
           MAKE_ADMIN_HANDLER(handlerHealthcheckFail), false, true},
          {"/healthcheck/ok", "cause the server to pass health checks",
           MAKE_ADMIN_HANDLER(handlerHealthcheckOk), false, true},
          {"/help", "print out list of admin commands", MAKE_ADMIN_HANDLER(handlerHelp), false,
           false},
          {"/hot_restart_version", "print the hot restart compatibility version",
           MAKE_ADMIN_HANDLER(handlerHotRestartVersion), false, false},
          {"/logging", "query/change logging levels", MAKE_ADMIN_HANDLER(handlerLogging), false,
           true},
          {"/memory", "print current allocation/heap usage", MAKE_ADMIN_HANDLER(handlerMemory),
           false, false},
          {"/quitquitquit", "exit the server", MAKE_ADMIN_HANDLER(handlerQuitQuitQuit), false,
           true},
          {"/reset_counters", "reset all counters to zero",
           MAKE_ADMIN_HANDLER(handlerResetCounters), false, true},
          {"/server_info", "print server version/status information",
           MAKE_ADMIN_HANDLER(handlerServerInfo), false, false},
          {"/stats", "print server stats", MAKE_ADMIN_HANDLER(handlerStats), false, false},
          {"/stats/prometheus", "print server stats in prometheus format",
           MAKE_ADMIN_HANDLER(handlerPrometheusStats), false, false},
          {"/listeners", "print listener addresses", MAKE_ADMIN_HANDLER(handlerListenerInfo), false,
           false},
          {"/runtime", "print runtime values", MAKE_ADMIN_HANDLER(handlerRuntime), false, false},
          {"/runtime_modify", "modify runtime values", MAKE_ADMIN_HANDLER(handlerRuntimeModify),
           false, true},
      },
      date_provider_(server.dispatcher().timeSource()),
      admin_filter_chain_(std::make_shared<AdminFilterChain>()) {}

Http::ServerConnectionPtr AdminImpl::createCodec(Network::Connection& connection,
                                                 const Buffer::Instance& data,
                                                 Http::ServerConnectionCallbacks& callbacks) {
  return Http::ConnectionManagerUtility::autoCreateCodec(
      connection, data, callbacks, server_.stats(), Http::Http1Settings(), Http::Http2Settings(),
      maxRequestHeadersKb());
}

bool AdminImpl::createNetworkFilterChain(Network::Connection& connection,
                                         const std::vector<Network::FilterFactoryCb>&) {
  // Don't pass in the overload manager so that the admin interface is accessible even when
  // the envoy is overloaded.
  connection.addReadFilter(Network::ReadFilterSharedPtr{new Http::ConnectionManagerImpl(
      *this, server_.drainManager(), server_.random(), server_.httpContext(), server_.runtime(),
      server_.localInfo(), server_.clusterManager(), nullptr, server_.timeSource())});
  return true;
}

void AdminImpl::createFilterChain(Http::FilterChainFactoryCallbacks& callbacks) {
  callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterSharedPtr{new AdminFilter(*this)});
}

Http::Code AdminImpl::runCallback(absl::string_view path_and_query,
                                  Http::HeaderMap& response_headers, Buffer::Instance& response,
                                  AdminStream& admin_stream) {
  Http::Code code = Http::Code::OK;
  bool found_handler = false;

  std::string::size_type query_index = path_and_query.find('?');
  if (query_index == std::string::npos) {
    query_index = path_and_query.size();
  }

  for (const UrlHandler& handler : handlers_) {
    if (path_and_query.compare(0, query_index, handler.prefix_) == 0) {
      found_handler = true;
      if (handler.mutates_server_state_) {
        const absl::string_view method =
            admin_stream.getRequestHeaders().Method()->value().getStringView();
        if (method != Http::Headers::get().MethodValues.Post) {
          ENVOY_LOG(error, "admin path \"{}\" mutates state, method={} rather than POST",
                    handler.prefix_, method);
          code = Http::Code::MethodNotAllowed;
          response.add(fmt::format("Method {} not allowed, POST required.", method));
          break;
        }
      }
      code = handler.handler_(path_and_query, response_headers, response, admin_stream);
      break;
    }
  }

  if (!found_handler) {
    // Extra space is emitted below to have "invalid path." be a separate sentence in the
    // 404 output from "admin commands are:" in handlerHelp.
    response.add("invalid path. ");
    handlerHelp(path_and_query, response_headers, response, admin_stream);
    code = Http::Code::NotFound;
  }

  return code;
}

std::vector<const AdminImpl::UrlHandler*> AdminImpl::sortedHandlers() const {
  std::vector<const UrlHandler*> sorted_handlers;
  for (const UrlHandler& handler : handlers_) {
    sorted_handlers.push_back(&handler);
  }
  // Note: it's generally faster to sort a vector with std::vector than to construct a std::map.
  std::sort(sorted_handlers.begin(), sorted_handlers.end(),
            [](const UrlHandler* h1, const UrlHandler* h2) { return h1->prefix_
prefix_; });
  return sorted_handlers;
}

Http::Code AdminImpl::handlerHelp(absl::string_view, Http::HeaderMap&, Buffer::Instance& response,
                                  AdminStream&) {
  response.add("admin commands are:\n");

  // Prefix order is used during searching, but for printing do them in alpha order.
  for (const UrlHandler* handler : sortedHandlers()) {
    response.add(fmt::format("  {}: {}\n", handler->prefix_, handler->help_text_));
  }
  return Http::Code::OK;
}

Http::Code AdminImpl::handlerAdminHome(absl::string_view, Http::HeaderMap& response_headers,
                                       Buffer::Instance& response, AdminStream&) {
  response_headers.insertContentType().value().setReference(
      Http::Headers::get().ContentTypeValues.Html);

  response.add(absl::StrReplaceAll(AdminHtmlStart, {{"@FAVICON@", EnvoyFavicon}}));

  // Prefix order is used during searching, but for printing do them in alpha order.
  for (const UrlHandler* handler : sortedHandlers()) {
    absl::string_view path = handler->prefix_;

    if (path == "/") {
      continue; // No need to print self-link to index page.
    }

    // Remove the leading slash from the link, so that the admin page can be
    // rendered as part of another console, on a sub-path.
    //
    // E.g. consider a downstream dashboard that embeds the Envoy admin console.
    // In that case, the "/stats" endpoint would be at
    // https://DASHBOARD/envoy_admin/stats. If the links we present on the home
    // page are absolute (e.g. "/stats") they won't work in the context of the
    // dashboard. Removing the leading slash, they will work properly in both
    // the raw admin console and when embedded in another page and URL
    // hierarchy.
    ASSERT(!path.empty());
    ASSERT(path[0] == '/');
    path = path.substr(1);

    // For handlers that mutate state, render the link as a button in a POST form,
    // rather than an anchor tag. This should discourage crawlers that find the /
    // page from accidentally mutating all the server state by GETting all the hrefs.
    const char* link_format =
        handler->mutates_server_state_
            ? "<form action='{}' method='post' class='home-form'><button>{}</button></form>"
            : "{}";
    const std::string link = fmt::format(link_format, path, path);

    // Handlers are all specified by statically above, and are thus trusted and do
    // not require escaping.
    response.add(fmt::format("
{}	"
                             "{}
\n",
                             link, Html::Utility::sanitize(handler->help_text_)));
  }
  response.add(AdminHtmlEnd);
  return Http::Code::OK;
}

const Network::Address::Instance& AdminImpl::localAddress() {
  return *server_.localInfo().address();
}

bool AdminImpl::addHandler(const std::string& prefix, const std::string& help_text,
                           HandlerCb callback, bool removable, bool mutates_state) {
  ASSERT(prefix.size() > 1);
  ASSERT(prefix[0] == '/');

  // Sanitize prefix and help_text to ensure no XSS can be injected, as
  // we are injecting these strings into HTML that runs in a domain that
  // can mutate Envoy server state. Also rule out some characters that
  // make no sense as part of a URL path: ? and :.
  const std::string::size_type pos = prefix.find_first_of("&\"'<>?:");
  if (pos != std::string::npos) {
    ENVOY_LOG(error, "filter \"{}\" contains invalid character '{}'", prefix, prefix[pos]);
    return false;
  }

  auto it = std::find_if(handlers_.cbegin(), handlers_.cend(),
                         [&prefix](const UrlHandler& entry) { return prefix == entry.prefix_; });
  if (it == handlers_.end()) {
    handlers_.push_back({prefix, help_text, callback, removable, mutates_state});
    return true;
  }
  return false;
}

bool AdminImpl::removeHandler(const std::string& prefix) {
  const uint size_before_removal = handlers_.size();
  handlers_.remove_if(
      [&prefix](const UrlHandler& entry) { return prefix == entry.prefix_ && entry.removable_; });
  if (handlers_.size() != size_before_removal) {
    return true;
  }
  return false;
}

Http::Code AdminImpl::request(absl::string_view path_and_query, absl::string_view method,
                              Http::HeaderMap& response_headers, std::string& body) {
  AdminFilter filter(*this);
  Http::HeaderMapImpl request_headers;
  request_headers.insertMethod().value(method.data(), method.size());
  filter.decodeHeaders(request_headers, false);
  Buffer::OwnedImpl response;

  Http::Code code = runCallback(path_and_query, response_headers, response, filter);
  populateFallbackResponseHeaders(code, response_headers);
  body = response.toString();
  return code;
}

void AdminImpl::closeSocket() {
  if (socket_) {
    socket_->close();
  }
}

void AdminImpl::addListenerToHandler(Network::ConnectionHandler* handler) {
  if (listener_) {
    handler->addListener(*listener_);
  }
}

} // namespace Server
} // namespace Envoy


text:
#ifndef _ALTOVA_INCLUDED_AIMXML_ALTOVA__ALTOVA_CImagingObservationCharacteristic
#define _ALTOVA_INCLUDED_AIMXML_ALTOVA__ALTOVA_CImagingObservationCharacteristic

namespace AIMXML
{

class CImagingObservationCharacteristic : public TypeBase
{
public:
	AIMXML_EXPORT CImagingObservationCharacteristic(xercesc::DOMNode* const& init);
	AIMXML_EXPORT CImagingObservationCharacteristic(CImagingObservationCharacteristic const& init);
	void operator=(CImagingObservationCharacteristic const& other) { m_node = other.m_node; }
	static altova::meta::ComplexType StaticInfo() { return altova::meta::ComplexType(types + _altova_ti_altova_CImagingObservationCharacteristic); }
	MemberElement<iso::CCD, _altova_mi_altova_CImagingObservationCharacteristic_altova_typeCode> typeCode;
	struct typeCode { typedef Iterator<iso::CCD> iterator; };
	MemberElement<iso::CCD, _altova_mi_altova_CImagingObservationCharacteristic_altova_questionTypeCode> questionTypeCode;
	struct questionTypeCode { typedef Iterator<iso::CCD> iterator; };
	MemberElement<iso::CREAL, _altova_mi_altova_CImagingObservationCharacteristic_altova_annotatorConfidence> annotatorConfidence;
	struct annotatorConfidence { typedef Iterator<iso::CREAL> iterator; };
	MemberElement<iso::CST, _altova_mi_altova_CImagingObservationCharacteristic_altova_label> label;
	struct label { typedef Iterator<iso::CST> iterator; };
	MemberElement<iso::CST, _altova_mi_altova_CImagingObservationCharacteristic_altova_comment> comment;
	struct comment { typedef Iterator<iso::CST> iterator; };
	MemberElement<iso::CINT, _altova_mi_altova_CImagingObservationCharacteristic_altova_questionIndex> questionIndex;
	struct questionIndex { typedef Iterator<iso::CINT> iterator; };
	MemberElement<CcharacteristicQuantificationCollectionType, _altova_mi_altova_CImagingObservationCharacteristic_altova_characteristicQuantificationCollection> characteristicQuantificationCollection;
	struct characteristicQuantificationCollection { typedef Iterator<CcharacteristicQuantificationCollectionType> iterator; };
	AIMXML_EXPORT void SetXsiType();
};

}	// namespace AIMXML

#endif // _ALTOVA_INCLUDED_AIMXML_ALTOVA__ALTOVA_CImagingObservationCharacteristic