text:
namespace Gek
{
    namespace Implementation
    {
        GEK_CONTEXT_USER(Filter, Engine::Core *, std::string)
            , public Engine::Filter
        {
        public:
            struct PassData
            {
                std::string name;
                bool enabled = true;
                Pass::Mode mode = Pass::Mode::Deferred;
                Math::Float4 blendFactor = Math::Float4::Zero;
                BlendStateHandle blendState;
                std::vector<ResourceHandle> resourceList;
                std::vector<ResourceHandle> unorderedAccessList;
                std::vector<ResourceHandle> renderTargetList;
                ProgramHandle program;
                uint32_t dispatchWidth = 0;
                uint32_t dispatchHeight = 0;
                uint32_t dispatchDepth = 0;

                std::unordered_map<ResourceHandle, ClearData> clearResourceMap;
                std::vector<ResourceHandle> generateMipMapsList;
                std::unordered_map<ResourceHandle, ResourceHandle> copyResourceMap;
                std::unordered_map<ResourceHandle, ResourceHandle> resolveSampleMap;
            };

        private:
            Engine::Core *core = nullptr;
            Video::Device *videoDevice = nullptr;
            Engine::Resources *resources = nullptr;
            Plugin::Population *population = nullptr;

            std::string filterName;

            DepthStateHandle depthState;
            RenderStateHandle renderState;
            std::vector<PassData> passList;

        public:
            Filter(Context *context, Engine::Core *core, std::string filterName)
                : ContextRegistration(context)
                , core(core)
                , videoDevice(core->getVideoDevice())
                , resources(core->getFullResources())
                , population(core->getPopulation())
                , filterName(filterName)
            {
                assert(videoDevice);
                assert(resources);
                assert(population);

                reload();
            }

            void reload(void)
            {
                LockedWrite{ std::cout } << "Loading filter: " << filterName;

                passList.clear();

                std::unordered_map<std::string, ResourceHandle> resourceMap;
                std::unordered_map<std::string, std::string> resourceSemanticsMap;

                auto backBuffer = videoDevice->getBackBuffer();
                auto &backBufferDescription = backBuffer->getDescription();
                depthState = resources->createDepthState(Video::DepthState::Description());
                renderState = resources->createRenderState(Video::RenderState::Description());

                JSON rootNode;
                rootNode.load(getContext()->findDataPath(FileSystem::CombinePaths("filters", filterName).withExtension(".json")));

                ShuntingYard shuntingYard(population->getShuntingYard());
                const auto &coreOptionsNode = core->getOption("filters", filterName);
                for (auto &coreValuePair : coreOptionsNode.asType(JSON::EmptyObject))
                {
                    shuntingYard.setVariable(coreValuePair.first, coreValuePair.second.convert(0.0f));
                }

                auto rootOptionsNode = rootNode.getMember("options"sv);
                auto &rootOptionsObject = rootOptionsNode.asType(JSON::EmptyObject);
                for (auto &coreValuePair : coreOptionsNode.asType(JSON::EmptyObject))
                {
                    rootOptionsObject[coreValuePair.first] = coreValuePair.second;
                }

                auto importSearch = rootOptionsObject.find("#import");
                if (importSearch != std::end(rootOptionsObject))
                {
                    auto importExternal = [&](std::string_view importName) -> void
                    {
                        JSON importOptions;
                        importOptions.load(getContext()->findDataPath(FileSystem::CombinePaths("shaders", importName).withExtension(".json")));
                        for (auto &importPair : importOptions.asType(JSON::EmptyObject))
                        {
                            if (rootOptionsObject.count(importPair.first) == 0)
                            {
                                rootOptionsObject[importPair.first] = importPair.second;
                            }
                        }
                    };

                    importSearch->second.visit(
                        [&](std::string const &importName)
                    {
                        importExternal(importName);
                    },
                        [&](JSON::Array const &importArray)
                    {
                        for (auto &importName : importArray)
                        {
                            importExternal(importName.convert(String::Empty));
                        }
                    },
                        [&](auto const &)
                    {
                    });

                    rootOptionsObject.erase(importSearch);
                }

                for (auto &requiredNode : rootNode.getMember("requires"sv).asType(JSON::EmptyArray))
                {
                    resources->getShader(requiredNode.convert(String::Empty), MaterialHandle());
                }

                for (auto &rootTexturesPair : rootNode.getMember("textures"sv).asType(JSON::EmptyObject))
                {
                    std::string textureName(rootTexturesPair.first);
                    if (resourceMap.count(textureName) > 0)
                    {
                        LockedWrite{ std::cout } << "Texture name same as already listed resource: " << textureName;
                        continue;
                    }

                    ResourceHandle resource;
                    auto textureNode = rootTexturesPair.second;
                    auto textureMap = textureNode.asType(JSON::EmptyObject);
                    if (textureMap.count("file"))
                    {
                        std::string fileName(textureNode.getMember("file"sv).convert(String::Empty));
                        uint32_t flags = getTextureLoadFlags(textureNode.getMember("flags"sv).convert(String::Empty));
                        resource = resources->loadTexture(fileName, flags);
                    }
                    else if (textureMap.count("format"))
                    {
                        Video::Texture::Description description(backBufferDescription);
                        description.format = Video::GetFormat(textureNode.getMember("format"sv).convert(String::Empty));
                        auto &sizeNode = textureNode.getMember("size"sv);
                        if (sizeNode.isType<JSON::Array>())
                        {
                            auto sizeArray = sizeNode.asType(JSON::EmptyArray);
                            if (sizeArray.size() == 3)
                            {
                                description.depth = sizeArray.at(2).evaluate(shuntingYard, 1);
                                description.height = sizeArray.at(1).evaluate(shuntingYard, 1);
                                description.width = sizeArray.at(0).evaluate(shuntingYard, 1);
                            }
                        }
                        else
                        {
                            description.width = description.height = sizeNode.evaluate(shuntingYard, 1);
                        };

                        description.sampleCount = textureNode.getMember("sampleCount"sv).convert(1);
                        description.flags = getTextureFlags(textureNode.getMember("flags"sv).convert(String::Empty));
                        description.mipMapCount = textureNode.getMember("mipmaps"sv).evaluate(shuntingYard, 1);
                        resource = resources->createTexture(textureName, description, true);
                    }

                    auto description = resources->getTextureDescription(resource);
                    if (description)
                    {
                        resourceMap[textureName] = resource;
                        if (description->depth > 1)
                        {
                            resourceSemanticsMap[textureName] = String::Format("Texture3D<{}>", getFormatSemantic(description->format));
                        }
                        else if (description->height > 1 || description->width == 1)
                        {
                            resourceSemanticsMap[textureName] = String::Format("Texture2D<{}>", getFormatSemantic(description->format));
                        }
                        else
                        {
                            resourceSemanticsMap[textureName] = String::Format("Texture1D<{}>", getFormatSemantic(description->format));
                        }
                    }
                }

                for (auto &bufferPair : rootNode.getMember("buffers"sv).asType(JSON::EmptyObject))
                {
                    std::string bufferName(bufferPair.first);
                    if (resourceMap.count(bufferName) > 0)
                    {
                        LockedWrite{ std::cout } << "Texture name same as already listed resource: " << bufferName;
                        continue;
                    }

                    auto &bufferNode = bufferPair.second;
                    auto &bufferObject = bufferNode.asType(JSON::EmptyObject);

                    Video::Buffer::Description description;
                    description.count = bufferNode.getMember("count"sv).evaluate(shuntingYard, 0);
                    description.flags = getBufferFlags(bufferNode.getMember("flags"sv).convert(String::Empty));
                    if (bufferObject.count("format"))
                    {
                        description.type = Video::Buffer::Type::Raw;
                        description.format = Video::GetFormat(bufferNode.getMember("format"sv).convert(String::Empty));
                    }
                    else
                    {
                        description.type = Video::Buffer::Type::Structured;
                        description.stride = bufferNode.getMember("stride"sv).evaluate(shuntingYard, 0);
                    }

                    auto resource = resources->createBuffer(bufferName, description, true);
                    if (resource)
                    {
                        resourceMap[bufferName] = resource;
                        if (bufferNode.getMember("byteaddress"sv).convert(false))
                        {
                            resourceSemanticsMap[bufferName] = "ByteAddressBuffer";
                        }
                        else
                        {
                            auto description = resources->getBufferDescription(resource);
                            if (description != nullptr)
                            {
                                auto structure = bufferNode.getMember("structure"sv).convert(String::Empty);
                                resourceSemanticsMap[bufferName] += String::Format("Buffer<{}>", structure.empty() ? getFormatSemantic(description->format) : structure);
                            }
                        }
                    }
                }

                auto &passesNode = rootNode.getMember("passes"sv);
                passList.resize(passesNode.asType(JSON::EmptyArray).size());
                auto passData = std::begin(passList);
                for (auto &passNode : passesNode.asType(JSON::EmptyArray))
                {
                    PassData &pass = *passData++;
                    std::string entryPoint(passNode.getMember("entry"sv).convert(String::Empty));
                    auto programName = passNode.getMember("program"sv).convert(String::Empty);
                    pass.name = programName;

                    auto enableOption = passNode.getMember("enable"sv).convert(String::Empty);
                    if (!enableOption.empty())
                    {
                        String::Replace(enableOption, "::", "|");
                        auto nameList = String::Split(enableOption, '|');
                        const JSON *nameNode = &rootOptionsNode;
                        for (auto &name : nameList)
                        {
                            nameNode = &nameNode->getMember(name);
                        }

                        pass.enabled = nameNode->convert(true);
                        if (!pass.enabled)
                        {
                            continue;
                        }
                    }

                    JSON passOptions(std::cref(rootOptionsNode).get());
                    for (auto &overridePair : passNode.getMember("options"sv).asType(JSON::EmptyObject))
                    {
                        std::function<void(JSON &, std::string_view, JSON const &)> insertOptions;
                        insertOptions = [&](JSON &options, std::string_view name, JSON const &node) -> void
                        {
                            node.visit(
                                [&](JSON::Object const &object)
                            {
                                auto &localOptions = options[name];
                                for (auto &objectPair : object)
                                {
                                    insertOptions(localOptions, objectPair.first, objectPair.second);
                                }
                            },
                                [&](auto const &value)
                            {
                                options[name] = value;
                            });
                        };

                        insertOptions(passOptions, overridePair.first, overridePair.second);
                    }

                    std::function<std::string(JSON const &)> addOptions;
                    addOptions = [&](JSON const &options) -> std::string
                    {
                        std::string optionsData;
                        for (auto &optionPair : options.asType(JSON::EmptyObject))
                        {
                            auto optionName = optionPair.first;
                            auto &optionNode = optionPair.second;
                            optionNode.visit(
                                [&](JSON::Object const &optionObject)
                            {
                                if (optionObject.count("options"))
                                {
                                    optionsData += String::Format("    namespace {}\r\n", optionName);
                                    optionsData += String::Format("    {\r\n");

                                    std::vector<std::string> choices;
                                    for (auto &choice : optionNode.getMember("options"sv).asType(JSON::EmptyArray))
                                    {
                                        auto name = choice.convert(String::Empty);
                                        optionsData += String::Format("        static const int {} = {};\r\n", name, choices.size());
                                        choices.push_back(name);
                                    }

                                    int selection = 0;
                                    auto &selectionNode = optionNode.getMember("selection"sv);
                                    if (selectionNode.isType<std::string>())
                                    {
                                        auto selectedName = selectionNode.convert(String::Empty);
                                        auto optionsSearch = std::find_if(std::begin(choices), std::end(choices), [selectedName](std::string const &choice) -> bool
                                        {
                                            return (selectedName == choice);
                                        });

                                        if (optionsSearch != std::end(choices))
                                        {
                                            selection = std::distance(std::begin(choices), optionsSearch);
                                        }
                                    }
                                    else
                                    {
                                        selection = selectionNode.convert(0U);
                                    }

                                    optionsData += String::Format("        static const int Selection = {};\r\n", selection);
                                    optionsData += String::Format("    };\r\n");
                                }
                                else
                                {
                                    auto optionData = addOptions(optionNode);
                                    if (!optionData.empty())
                                    {
                                        optionsData += String::Format(
                                            "namespace {}\r\n" \
                                            "{\r\n" \
                                            "{}" \
                                            "};\r\n" \
                                            "\r\n", optionName, optionData);
                                    }
                                }
                            },
                                [&](JSON::Array const &optionArray)
                            {
                                switch (optionArray.size())
                                {
                                case 1:
                                    optionsData += String::Format("    static const float {} = {};\r\n", optionName,
                                        optionArray[0].convert(0.0f));
                                    break;

                                case 2:
                                    optionsData += String::Format("    static const float2 {} = float2({}, {});\r\n", optionName,
                                        optionArray[0].convert(0.0f),
                                        optionArray[1].convert(0.0f));
                                    break;

                                case 3:
                                    optionsData += String::Format("    static const float3 {} = float3({}, {}, {});\r\n", optionName,
                                        optionArray[0].convert(0.0f),
                                        optionArray[1].convert(0.0f),
                                        optionArray[2].convert(0.0f));
                                    break;

                                case 4:
                                    optionsData += String::Format("    static const float4 {} = float4({}, {}, {}, {})\r\n", optionName,
                                        optionArray[0].convert(0.0f),
                                        optionArray[1].convert(0.0f),
                                        optionArray[2].convert(0.0f),
                                        optionArray[3].convert(0.0f));
                                    break;
                                };
                            },
                                [&](std::nullptr_t const &)
                            {
                            },
                                [&](bool optionBoolean)
                            {
                                optionsData += String::Format("    static const bool {} = {};\r\n", optionName, optionBoolean);
                            },
                                [&](float optionFloat)
                            {
                                optionsData += String::Format("    static const float {} = {};\r\n", optionName, optionFloat);
                            },
                                [&](auto const &optionValue)
                            {
                                optionsData += String::Format("    static const int {} = {};\r\n", optionName, optionValue);
                            });
                        }

                        return optionsData;
                    };

                    std::string engineData;
                    auto optionsData = addOptions(passOptions);
                    if (!optionsData.empty())
                    {
                        engineData += String::Format(
                            "namespace Options\r\n" \
                            "{\r\n" \
                            "{}" \
                            "};\r\n" \
                            "\r\n", optionsData);
                    }

                    std::string mode(String::GetLower(passNode.getMember("mode"sv).convert(String::Empty)));
                    if (mode == "compute")
                    {
                        pass.mode = Pass::Mode::Compute;
                    }
                    else
                    {
                        pass.mode = Pass::Mode::Deferred;
                    }

                    if (pass.mode == Pass::Mode::Compute)
                    {
                        auto &dispatchNode = passNode.getMember("dispatch"sv);
                        if (dispatchNode.isType<JSON::Array>())
                        {
                            auto &dispatchArray = dispatchNode.asType(JSON::EmptyArray);
                            if (dispatchArray.size() == 3)
                            {
                                pass.dispatchWidth = dispatchArray.at(0).evaluate(shuntingYard, 1);
                                pass.dispatchHeight = dispatchArray.at(1).evaluate(shuntingYard, 1);
                                pass.dispatchDepth = dispatchArray.at(2).evaluate(shuntingYard, 1);
                            }
                        }
                        else
                        {
                            pass.dispatchWidth = pass.dispatchHeight = pass.dispatchDepth = dispatchNode.evaluate(shuntingYard, 1);
                        }
                    }
                    else
                    {
                        engineData +=
                            "struct InputPixel\r\n" \
                            "{\r\n" \
                            "    float4 screen : SV_POSITION;\r\n" \
                            "    float2 texCoord : TEXCOORD0;\r\n" \
                            "};\r\n" \
                            "\r\n";

                        std::string outputData;
                        uint32_t nextTargetStage = 0;
                        std::unordered_map<std::string, std::string> renderTargetsMap = getAliasedMap(passNode.getMember("targets"sv));
                        if (!renderTargetsMap.empty())
                        {
                            for (auto &renderTarget : renderTargetsMap)
                            {
                                uint32_t currentStage = nextTargetStage++;
                                if (renderTarget.first == "outputBuffer")
                                {
                                    pass.renderTargetList.push_back(ResourceHandle());
                                    outputData += String::Format("    Texture2D<float3> {} : SV_TARGET{};\r\n", renderTarget.second, currentStage);
                                }
                                else
                                {
                                    auto resourceSearch = resourceMap.find(renderTarget.first);
                                    if (resourceSearch == std::end(resourceMap))
                                    {
                                        LockedWrite{ std::cerr } << "Unable to find render target for pass: " << renderTarget.first;
                                    }
                                    else
                                    {
                                        auto description = resources->getTextureDescription(resourceSearch->second);
                                        if (description)
                                        {
                                            pass.renderTargetList.push_back(resourceSearch->second);
                                            outputData += String::Format("    {} {} : SV_TARGET{};\r\n", getFormatSemantic(description->format), renderTarget.second, currentStage);
                                        }
                                        else
                                        {
                                            LockedWrite{ std::cerr } << "Unable to get description for render target: " << renderTarget.first;
                                        }
                                    }
                                }
                            }
                        }

                        if (!outputData.empty())
                        {
                            engineData += String::Format(
                                "struct OutputPixel\r\n" \
                                "{\r\n" \
                                "{}" \
                                "};\r\n" \
                                "\r\n", outputData);
                        }

                        Video::BlendState::Description blendStateInformation;
                        blendStateInformation.load(passNode.getMember("blendState"sv));
                        pass.blendState = resources->createBlendState(blendStateInformation);
                    }

                    for (auto &baseClearTargetNode : passNode.getMember("clear"sv).asType(JSON::EmptyObject))
                    {
                        auto resourceName = baseClearTargetNode.first;
                        auto resourceSearch = resourceMap.find(resourceName);
                        if (resourceSearch != std::end(resourceMap))
                        {
                            JSON clearTargetNode(baseClearTargetNode.second);
                            auto clearType = getClearType(clearTargetNode.getMember("type"sv).convert(String::Empty));
                            auto clearValue = clearTargetNode.getMember("value"sv).convert(String::Empty);
                            pass.clearResourceMap.insert(std::make_pair(resourceSearch->second, ClearData(clearType, clearValue)));
                        }
                        else
                        {
                            LockedWrite{ std::cerr } << "Missing clear target encountered: " << resourceName;
                        }
                    }

                    for (auto &baseGenerateMipMapsNode : passNode.getMember("generateMipMaps"sv).asType(JSON::EmptyArray))
                    {
                        JSON generateMipMapNode(baseGenerateMipMapsNode);
                        auto resourceName = generateMipMapNode.convert(String::Empty);
                        auto resourceSearch = resourceMap.find(resourceName);
                        if (resourceSearch != std::end(resourceMap))
                        {
                            pass.generateMipMapsList.push_back(resourceSearch->second);
                        }
                        else
                        {
                            LockedWrite{ std::cerr } << "Missing mipmap generation target encountered: " << resourceName;
                        }
                    }

                    for (auto &baseCopyNode : passNode.getMember("copy"sv).asType(JSON::EmptyObject))
                    {
                        auto targetResourceName = baseCopyNode.first;
                        auto nameSearch = resourceMap.find(targetResourceName);
                        if (nameSearch != std::end(resourceMap))
                        {
                            JSON copyNode(baseCopyNode.second);
                            auto sourceResourceName = copyNode.convert(String::Empty);
                            auto valueSearch = resourceMap.find(sourceResourceName);
                            if (valueSearch != std::end(resourceMap))
                            {
                                pass.copyResourceMap[nameSearch->second] = valueSearch->second;
                            }
                            else
                            {
                                LockedWrite{ std::cerr } << "Missing copy source encountered: " << sourceResourceName;
                            }
                        }
                        else
                        {
                            LockedWrite{ std::cerr } << "Missing copy target encountered: " << targetResourceName;
                        }
                    }

                    for (auto &baseResolveNode : passNode.getMember("resolve"sv).asType(JSON::EmptyObject))
                    {
                        auto targetResourceName = baseResolveNode.first;
                        auto nameSearch = resourceMap.find(targetResourceName);
                        if (nameSearch != std::end(resourceMap))
                        {
                            JSON resolveNode(baseResolveNode.second);
                            auto sourceResourceName = resolveNode.convert(String::Empty);
                            auto valueSearch = resourceMap.find(sourceResourceName);
                            if (valueSearch != std::end(resourceMap))
                            {
                                pass.resolveSampleMap[nameSearch->second] = valueSearch->second;
                            }
                            else
                            {
                                LockedWrite{ std::cerr } << "Missing resolve source encountered: " << sourceResourceName;
                            }
                        }
                        else
                        {
                            LockedWrite{ std::cerr } << "Missing resolve target encountered: " << targetResourceName;
                        }
                    }

                    std::string resourceData;
                    uint32_t nextResourceStage = 0;
                    std::unordered_map<std::string, std::string> resourceAliasMap = getAliasedMap(passNode.getMember("resources"sv));
                    for (auto &resourcePair : resourceAliasMap)
                    {
                        uint32_t currentStage = nextResourceStage++;
                        if (resourcePair.first == "inputBuffer")
                        {
                            pass.resourceList.push_back(ResourceHandle());
                            resourceData += String::Format("    Texture2D<float3> {} : register(t{});\r\n", resourcePair.second, currentStage);
                        }
                        else
                        {
                            auto resourceSearch = resourceMap.find(resourcePair.first);
                            if (resourceSearch != std::end(resourceMap))
                            {
                                pass.resourceList.push_back(resourceSearch->second);
                            }

                            auto semanticsSearch = resourceSemanticsMap.find(resourcePair.first);
                            if (semanticsSearch != std::end(resourceSemanticsMap))
                            {
                                resourceData += String::Format("    {} {} : register(t{});\r\n", semanticsSearch->second, resourcePair.second, currentStage);
                            }
                        }
                    }

                    if (!resourceData.empty())
                    {
                        engineData += String::Format(
                            "namespace Resources\r\n" \
                            "{\r\n" \
                            "{}" \
                            "};\r\n" \
                            "\r\n", resourceData);
                    }

                    std::string unorderedAccessData;
                    uint32_t nextUnorderedStage = 0;
                    if (pass.mode != Pass::Mode::Compute)
                    {
                        nextUnorderedStage = pass.renderTargetList.size();
                    }

                    std::unordered_map<std::string, std::string> unorderedAccessAliasMap = getAliasedMap(passNode.getMember("unorderedAccess"sv));
                    for (auto &resourcePair : unorderedAccessAliasMap)
                    {
                        auto resourceSearch = resourceMap.find(resourcePair.first);
                        if (resourceSearch != std::end(resourceMap))
                        {
                            pass.unorderedAccessList.push_back(resourceSearch->second);
                        }

                        uint32_t currentStage = nextUnorderedStage++;
                        auto semanticsSearch = resourceSemanticsMap.find(resourcePair.first);
                        if (semanticsSearch != std::end(resourceSemanticsMap))
                        {
                            unorderedAccessData += String::Format("    RW{} {} : register(u{});\r\n", semanticsSearch->second, resourcePair.second, currentStage);
                        }
                    }

                    if (!unorderedAccessData.empty())
                    {
                        engineData += String::Format(
                            "namespace UnorderedAccess\r\n" \
                            "{\r\n" \
                            "{}" \
                            "};\r\n" \
                            "\r\n", unorderedAccessData);
                    }

                    std::string fileName(FileSystem::CombinePaths(filterName, programName).withExtension(".hlsl").getString());
                    Video::Program::Type pipelineType = (pass.mode == Pass::Mode::Compute ? Video::Program::Type::Compute : Video::Program::Type::Pixel);
                    pass.program = resources->loadProgram(pipelineType, fileName, entryPoint, engineData);
				}

				core->setOption("filters", filterName, std::move(rootOptionsNode));
				LockedWrite{ std::cout } << "Filter loaded successfully: " << filterName;
			}

            ~Filter(void)
            {
            }

            // Filter
			Hash getIdentifier(void) const
			{
				return GetHash(this);
			}

			std::string_view getName(void) const
			{
                return filterName;
            }

            Pass::Mode preparePass(Video::Device::Context *videoContext, ResourceHandle input, ResourceHandle output, PassData const &pass)
            {
                if (!pass.enabled)
                {
                    return Pass::Mode::None;
                }

                for (auto const &clearTarget : pass.clearResourceMap)
                {
                    switch (clearTarget.second.type)
                    {
                    case ClearType::Target:
                        resources->clearRenderTarget(videoContext, clearTarget.first, clearTarget.second.floats);
                        break;

                    case ClearType::Float:
                        resources->clearUnorderedAccess(videoContext, clearTarget.first, clearTarget.second.floats);
                        break;

                    case ClearType::UInt:
                        resources->clearUnorderedAccess(videoContext, clearTarget.first, clearTarget.second.integers);
                        break;
                    };
                }

                for (auto const &resource : pass.generateMipMapsList)
                {
                    resources->generateMipMaps(videoContext, resource);
                }

                for (auto const &copyResource : pass.copyResourceMap)
                {
                    resources->copyResource(copyResource.first, copyResource.second);
                }

                Video::Device::Context::Pipeline *videoPipeline = (pass.mode == Pass::Mode::Compute ? videoContext->computePipeline() : videoContext->pixelPipeline());
                if (!pass.resourceList.empty())
                {
                    auto resourceList(pass.resourceList);
                    for (auto &resource : resourceList)
                    {
                        resource = (resource ? resource : input);
                    }

                    resources->setResourceList(videoPipeline, resourceList, 0);
                }

                if (!pass.unorderedAccessList.empty())
                {
                    uint32_t firstUnorderedAccessStage = 0;
                    if (pass.mode != Pass::Mode::Compute)
                    {
                        firstUnorderedAccessStage = pass.renderTargetList.size();
                    }

                    resources->setUnorderedAccessList(videoPipeline, pass.unorderedAccessList, firstUnorderedAccessStage);
                }

                resources->setProgram(videoPipeline, pass.program);

                switch (pass.mode)
                {
                case Pass::Mode::Compute:
                    resources->dispatch(videoContext, pass.dispatchWidth, pass.dispatchHeight, pass.dispatchDepth);
                    break;

                default:
                    resources->setDepthState(videoContext, depthState, 0x0);
                    resources->setRenderState(videoContext, renderState);
                    resources->setBlendState(videoContext, pass.blendState, pass.blendFactor, 0xFFFFFFFF);
                    if (!pass.renderTargetList.empty())
                    {
                        auto renderTargetList(pass.renderTargetList);
                        for (auto &resource : renderTargetList)
                        {
                            resource = (resource ? resource : output);
                        }

                        resources->setRenderTargetList(videoContext, renderTargetList, nullptr);
                    }

                    break;
                };

                return pass.mode;
            }

            void clearPass(Video::Device::Context *videoContext, PassData const &pass)
            {
                if (!pass.enabled)
                {
                    return;
                }

                Video::Device::Context::Pipeline *videoPipeline = (pass.mode == Pass::Mode::Compute ? videoContext->computePipeline() : videoContext->pixelPipeline());
                if (!pass.resourceList.empty())
                {
                    resources->clearResourceList(videoPipeline,  pass.resourceList.size(), 0);
                }

                if (!pass.unorderedAccessList.empty())
                {
                    uint32_t firstUnorderedAccessStage = 0;
                    if (pass.mode != Pass::Mode::Compute)
                    {
                        firstUnorderedAccessStage = pass.renderTargetList.size();
                    }

                    resources->clearUnorderedAccessList(videoPipeline, pass.unorderedAccessList.size(), firstUnorderedAccessStage);
                }

                if (!pass.renderTargetList.empty())
                {
                    resources->clearRenderTargetList(videoContext, pass.renderTargetList.size(), true);
                }

                for (auto &resolveResource : pass.resolveSampleMap)
                {
                    resources->resolveSamples(videoContext, resolveResource.first, resolveResource.second);
                }
            }

            class PassImplementation
                : public Pass
            {
            public:
                Video::Device::Context *videoContext;
                ResourceHandle input, output;
                Filter *filterNode;
                std::vector<Filter::PassData>::iterator current, end;

            public:
                PassImplementation(Video::Device::Context *videoContext, ResourceHandle input, ResourceHandle output, Filter *filterNode, std::vector<Filter::PassData>::iterator current, std::vector<Filter::PassData>::iterator end)
                    : videoContext(videoContext)
                    , input(input)
                    , output(output)
                    , filterNode(filterNode)
                    , current(current)
                    , end(end)
                {
                }

                Iterator next(void)
                {
                    auto next = current;
                    return Iterator(++next == end ? nullptr : new PassImplementation(videoContext, input, output, filterNode, next, end));
                }

                Mode prepare(void)
                {
                    return filterNode->preparePass(videoContext, input, output, (*current));
                }

                void clear(void)
                {
                    filterNode->clearPass(videoContext, (*current));
                }

                bool isEnabled(void) const
                {
                    return (*current).enabled;
                }

                Hash getIdentifier(void) const
				{
					return (*current).program.identifier;
				}

				std::string_view getName(void) const
				{
                    return (*current).name;
                }
            };

            Pass::Iterator begin(Video::Device::Context *videoContext, ResourceHandle input, ResourceHandle output)
            {
                assert(videoContext);
                return Pass::Iterator(passList.empty() ? nullptr : new PassImplementation(videoContext, input, output, this, std::begin(passList), std::end(passList)));
            }
        };

        GEK_REGISTER_CONTEXT_USER(Filter);
    }; // namespace Implementation
}; // namespace Gek


text:
html{height: 100%;}
body{*height:100%;height:100%\0;height:100%\9;font:13px/1.5 "Helvetica Neue",Helvetica,Arial,'Microsoft YaHei',sans-serif;padding: 0px;color: #666;background-image: -moz-linear-gradient(center top, #687586, #323A45);background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#687586), to(#323A45));background-image: -webkit-linear-gradient(top, #687586, #323A45);background-image: -o-linear-gradient(top, #687586, #323A45);background-image: linear-gradient(to bottom, #687586, #323A45);background-repeat: repeat;filter:  progid:DXImageTransform.Microsoft.gradient(startColorstr='#687586', endColorstr='#323A45', GradientType='0');}
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
   /* IE10-specific styles go here */
   body{height: auto;}
}
h1, h2, h3, h4, h5, h6{font-size:100%;color: #333;}
a{cursor: pointer;}
a:hover{text-decoration: none;}
ul, ol{list-style: none;}
ul{margin:0;padding:0;}
input, textarea{font-family: "Helvetica Neue",Helvetica,Arial,'Microsoft YaHei',sans-serif !important;}
input{padding:6px !important;}
.btn-inverse{background: #444444;color: #fff;}
.btn-inverse:hover, .label-inverse:hover, .btn-inverse:focus,  .label-inverse:focus{background: #333333;color: #fff;}
.btn-normal.btn-inverse{padding:4px 40px;box-shadow: none;}
.alert{padding:8px 35px 8px 14px;}
.alert-error{background: #F2DEDE;border:1px solid #EED3D7;color: #B94A48;}

.login-box{position:relative;width:450px;margin:10% auto 0;background: #fff;border-radius:4px;box-shadow: 0 0 12px rgba(0, 0, 0, 0.3);}
.login-box h1{position: absolute;top:-65px;color: #fff;font-size: 22px;font-family: sans-serif; }
.login-box h1 img{margin-right: 20px;}
.login-box form{margin: 0;}
.login-box .aw-mod-body{padding: 40px 70px;}
.login-box .aw-mod-body ul li{margin-top: 30px;}
.login-box .aw-mod-body ul li:first-child{margin-top:0px;}
.login-box .aw-mod-body span{display:inline-block;width: 60px;margin-right:10px;text-align: right;}
.login-box .aw-mod-body input{display:inline;width:215px;margin:0;}
.login-box .aw-mod-footer{padding:20px 10px;background: #E7EDF2;border-top:1px solid #d0dce6;border-radius: 0 0 4px 4px;text-align: center;}
.login-box .vercode{margin-bottom: 0px !important;}
.login-box .vercode label{float: left;width: 150px;}
.login-box .vercode img{float:left;width: 100px;height: 30px;cursor: pointer;}
.login-box .vercode input{width: 70px;}
.login-box .vercode a{display:inline-block;margin-top:5px;font-size: 12px;color: #999;}
.login-box .error-message{position: relative;}

redpajama_set_name: RedPajamaGithub


text:
/**
* Package.
* В этом пакете User и Role расширяют класс Base. А UserStore и RoleStore расширяют класс AbstractStore,
* который реализует интерфейс Store.
* @author Vitaly Vasilyev (rav.energ@rambler.ru)
* @version $Id$
* @since 0.1
*/
package ru.job4j.h2generic.t2store;


text:
/**
 * A network library for processing which supports UDP, TCP and Multicast.
 *
 * (c) 2004-2011
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 *
 * @author		Andreas Schlegel http://www.sojamo.de/libraries/oscP5
 * @modified	12/19/2011
 * @version		0.9.8
 */

package netP5;

import java.net.Socket;

/**
 * @author andreas schlegel
 */
public class TcpClient
    extends AbstractTcpClient {

  protected final static int NULL = -1;

  protected final static int LISTENER = 0;

  protected final static int EVENT = 1;

  private int _myMode = NULL;

  private Object _myParent;

  private NetPlug _myNetPlug;

  private String _myName = "";

  /**
   *
   * @param theAddress String
   * @param thePort int
   */

  public TcpClient(final Object theObject,
                   final String theAddress,
                   final int thePort) {
    super(theAddress, thePort);
    _myParent = theObject;
    initEvent();
  }

  /**
   *
   * @param theObject Object
   * @param theAddress String
   * @param thePort int
   * @param theMode int
   */
  public TcpClient(final Object theObject,
                   final String theAddress,
                   final int thePort,
                   final int theMode
      ) {
    super(theAddress, thePort, theMode);
    _myParent = theObject;
    initEvent();
  }

  /**
   *
   * @param theListener TcpPacketListener
   * @param theServerAddress String
   * @param theServerPort int
   * @param theMode int
   */
  public TcpClient(TcpPacketListener theListener,
                   String theServerAddress,
                   int theServerPort,
                   int theMode) {
    super(theListener, theServerAddress, theServerPort, theMode);
    _myMode = LISTENER;
  }

  /**
   *
   * @param theNetAddress NetAddress
   */
  public TcpClient(final Object theObject,
                   final NetAddress theNetAddress) {
    super(theNetAddress.address(), theNetAddress.port());
    _myParent = theObject;
    initEvent();
  }

  /**
   *
   * @param theNetAddress NetAddress
   */
  public TcpClient(final NetAddress theNetAddress) {
    super(theNetAddress.address(), theNetAddress.port());
  }

  /**
   *
   * @param theAddress String
   * @param thePort int
   */
  public TcpClient(final String theAddress,
                   final int thePort) {
    super(theAddress, thePort);
  }

  /**
   * @invisible
   */
  public TcpClient(AbstractTcpServer theTcpServer,
                   Socket theSocket,
                   TcpPacketListener theTcpPacketListener,
                   int theServerPort,
                   int theMode) {
    super(theTcpServer,
          theSocket,
          theTcpPacketListener,
          theServerPort,
          theMode);
    _myMode = LISTENER;
  }

  private void initEvent() {
    _myMode = EVENT;
    _myNetPlug = new NetPlug(_myParent);
  }

  /**
   * @invisible
   * @param theIndex int
   */
  public void handleStatus(int theIndex) {
    switch (_myMode) {
      case (EVENT):
        _myNetPlug.status(theIndex);
        break;
      case (LISTENER):
        _myTcpPacketListener.status(theIndex);
        break;
      case (NULL):
        Logger.printDebug("TcpClient.handleStatus()","net status id " + theIndex);
        break;
    }
  }

  /**
   * @invisible
   */
  public void handleInput() {
    switch (_myMode) {
      case (EVENT):
        _myNetPlug.process(new TcpPacket(this, _myStringBuffer, _myBytes),_myServerPort);
        break;
      case (LISTENER):
        _myTcpPacketListener.process(new TcpPacket(this, _myStringBuffer, _myBytes),_myServerPort);
        break;
      case (NULL):
    	  Logger.printDebug("TcpClient.handleInput()","received a message : " + _myStringBuffer.toString());
        break;
    }
  }

  /**
   *
   * @return String
   */
  public String name() {
    return _myName;
  }

  /**
   *
   * @param theName String
   */
  public void setName(String theName) {
    _myName = theName;
  }

}


text:
#include "common.h"
#include "memcached_io.h"
#include "memcached_constants.h"

memcached_return memcached_purge(memcached_server_st *ptr)
{
  uint32_t x;
  memcached_return ret= MEMCACHED_SUCCESS;

  if (ptr->root->purging || /* already purging */
      (memcached_server_response_count(ptr) < ptr->root->io_msg_watermark &&
      ptr->io_bytes_sent < ptr->root->io_bytes_watermark) ||
      (ptr->io_bytes_sent > ptr->root->io_bytes_watermark &&
      memcached_server_response_count(ptr) < 2))
  {
    return MEMCACHED_SUCCESS;
  }

  /* memcached_io_write and memcached_response may call memcached_purge
     so we need to be able stop any recursion.. */
  ptr->root->purging= 1;

  WATCHPOINT_ASSERT(ptr->fd != -1);
  /* Force a flush of the buffer to ensure that we don't have the n-1 pending
     requests buffered up.. */
  if (memcached_io_write(ptr, NULL, 0, 1) == -1)
  {
    ptr->root->purging= 0;
    return MEMCACHED_WRITE_FAILURE;
  }
  WATCHPOINT_ASSERT(ptr->fd != -1);

  int no_msg= memcached_server_response_count(ptr) - 1;
  if (no_msg > 0)
  {
    memcached_result_st result;
    memcached_result_st *result_ptr;
    char buffer[SMALL_STRING_LEN];

    /*
     * We need to increase the timeout, because we might be waiting for
     * data to be sent from the server (the commands was in the output buffer
     * and just flushed
     */
    long timeo= ptr->root->poll_timeout;
    ptr->root->poll_timeout= 2000;

    result_ptr= memcached_result_create(ptr->root, &result);
    WATCHPOINT_ASSERT(result_ptr);

    for (x= 0; x < no_msg; x++)
    {
      memcached_result_reset(result_ptr);
      memcached_return rc= memcached_read_one_response(ptr, buffer,
                                                       sizeof (buffer),
                                                       result_ptr);
      /*
       * Purge doesn't care for what kind of command results that is received.
       * The only kind of errors I care about if is I'm out of sync with the
       * protocol or have problems reading data from the network..
       */
      if (rc== MEMCACHED_PROTOCOL_ERROR || rc == MEMCACHED_UNKNOWN_READ_FAILURE)
      {
        WATCHPOINT_ERROR(rc);
        ret = rc;
        memcached_io_reset(ptr);
      }
    }

    memcached_result_free(result_ptr);
    ptr->root->poll_timeout=timeo;
  }
  ptr->root->purging= 0;

  return ret;
}


text:
from __future__ import annotations
from dataclasses import asdict
from datetime import date, timedelta
import json
import logging
import traceback
from typing import Any, Dict, List

from django.apps import apps
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models
from django.db.models.functions import Trunc
from django.utils import timezone
from dqm.apps import DqmConfig
from dqm.check_bricks import Check as BaseCheck, GaLevel, Platform, Result
from dqm.errors import CheckClassNotFoundError

logger = logging.getLogger(__name__)

class Status(models.IntegerChoices):
  Created = 0
  Running = 1
  Done = 2
  Failed = 3

class SingletonModel(models.Model):
  class Meta:
    abstract = True

  @classmethod
  def load(cls) -> SingletonModel:
    obj, _ = cls.objects.get_or_create(pk=1)
    return obj

  @classmethod
  def update(cls, **kwargs) -> SingletonModel:
    try:
      obj = cls.objects.get(pk=1)
      cls.objects.update(**kwargs)
    except cls.DoesNotExist:
      obj = cls.objects.create(**kwargs)
    return obj

class AppSettings(SingletonModel):
  ga_service_account = models.CharField(max_length=255)
  authorized_emails = models.TextField(null=True, blank=True)

class ApiCache(SingletonModel):
  ga_accounts_json = models.TextField(null=True, blank=True)

  @property
  def ga_accounts(self) -> List[Any]:
    return json.loads(
      self.ga_accounts_json) if self.ga_accounts_json else []

class Suite(models.Model):
  name = models.CharField(max_length=100)

  created = models.DateTimeField(auto_now_add=True)
  updated = models.DateTimeField(auto_now=True)

  def __str__(self) -> str:
    return self.name

  def execute(self) -> SuiteExecution:
    se = SuiteExecution.objects.create(suite=self, executed=timezone.now())

    for c in self.checks.filter(active=True):
      check_class = c.check_class()
      check_metadata = check_class.get_metadata()
      specific_params = {}

      # If Google Analytics related, we attach GA params
      if check_metadata['platform'] == Platform.Ga.value:
        ga_scope = self.ga_params.scope

        # Scope dict should be updated if check is at 'property' or 'account'
        # level:
        if check_metadata['ga_level'] == GaLevel.Property.value:
          for item in ga_scope:
            del item['viewId']
          ga_scope = [dict(t) for t in {tuple(d.items()) for d in ga_scope}]
        elif check_metadata['ga_level'] == GaLevel.Account.value:
          ga_scope = [{'accountId': item} for item in list(
            set([item['accountId'] for item in ga_scope]))]

        for scope_dict in ga_scope:
          specific_params = dict(scope_dict, **{
            'startDate': self.ga_params.start_date,
            'endDate': self.ga_params.end_date})

      c.execute(suite_execution=se, extra_params=specific_params)

    return se

class GaParams(models.Model):
  """
  >>> ga_params = GaParams.objects.create(
        scope_json='[
          {
            "viewId":"123456",
            "webPropertyId":"123456",
            "accountId":"12346",
          },
        ]'
      )
  """
  suite = models.OneToOneField(Suite, related_name='ga_params',
    on_delete=models.CASCADE)
  scope_json = models.TextField(default='[]')
  start_date = models.DateField(default=timezone.now() - timedelta(days=30))
  end_date = models.DateField(auto_now_add=True)

  created = models.DateTimeField(auto_now_add=True)
  updated = models.DateTimeField(auto_now=True)

  def to_dict(self) -> Dict:
    return {
      'scope': self.scope,
      'startDate': self.start_date,
      'endDate': self.end_date
    }

  @property
  def scope(self) -> List[Any]:
    return json.loads(self.scope_json) if self.scope_json else []

  @property
  def views(self) -> List[str]:
    return [s['viewId'] for s in json.loads(self.scope_json)]

class SuiteExecution(models.Model):
  suite = models.ForeignKey(Suite, on_delete=models.CASCADE,
    related_name='executions')
  status = models.IntegerField(choices=Status.choices, default=Status.Created)
  success = models.BooleanField(null=True, blank=True)
  executed = models.DateTimeField(null=True, blank=True)

  created = models.DateTimeField(auto_now_add=True)
  updated = models.DateTimeField(auto_now=True)

  def __str__(self) -> str:
    return '{}, {}'.format(self.suite, self.executed)

  def update_after_check_execution(self, check_execution) -> None:
    """
    This method if called after every check execution.

    It updates the status of the SuiteExecution object so that it can reflect
    the actual status (even if checks a executed asynchronously).
    """
    nbr_active_checks = self.suite.checks.filter(active=True).count()
    check_executions = self.check_executions.all()
    checks_finished = [ce.status == Status.Done for ce in check_executions]
    results = [ce.success == True for ce in check_executions]

    # If we have the same number of finished checks than the total number of
    # active checks in the suite, then we are done.
    if len(checks_finished) == nbr_active_checks:
      self.status = Status.Done
      self.success = all(results)
    else:
      # ...else, we're still running, and success is still undefinied (None).
      self.status = Status.Running

    self.save()

  @classmethod
  def get_stats(cls) -> List:
    query = SuiteExecution.objects.filter(
      executed__gte=timezone.now()-timedelta(days=10)).annotate(
      day=Trunc('executed', 'day', output_field=models.DateField()))

    results = [['day', 'executions', 'successes', 'fails']]
    results = results + [[
      date(day.year, day.month, day.day),
      len([se for se in query if date(se.day.year, se.day.month,
        se.day.day) == date(day.year, day.month, day.day)]),
      len([se for se in query if se.success and date(se.day.year,
        se.day.month, se.day.day) == date(day.year, day.month, day.day)]),
      len([se for se in query if not se.success and date(se.day.year,
        se.day.month, se.day.day) == date(day.year, day.month, day.day)]),
    ] for day in (
      timezone.now() - timedelta(days=10) + timedelta(n) for n in range(11))]

    return results

class Check(models.Model):
  """The Django model for a check.

  Please note that we thus have 2 different `Check` classes in the application:
  - This class, used internally for persistence and runtime execution.
  - The `check_bricks.Check` class, used by developpers as a base class to build
    new checks (see `/checks/` for examples of checks implementations).
  """
  suite = models.ForeignKey(Suite, on_delete=models.CASCADE,
    related_name='checks')
  name = models.CharField(max_length=50, choices=DqmConfig.checks)
  params_json = models.TextField(null=True, blank=True)
  comments = models.TextField(null=True, blank=True)
  active = models.BooleanField(default=True)

  created = models.DateTimeField(auto_now_add=True)
  updated = models.DateTimeField(auto_now=True)

  def __str__(self) -> str:
    return self.name

  @classmethod
  def get_checks_metadata(cls) -> List[Dict]:
    """Build a list of dictonnaries describing the metadata for all available
    checks. Relies on the `get_metadata` class method from base `Check` class.

    Example of result:
    [
      {
        'name': 'MyCheck',
        'title': 'My super check',
        'description': 'The description of my check',
        'theme': 'trustful',
        'platform': 'ga',
        'ga_level': 'view',
        'parameters': [{
          'name': 'viewId',
          'data_type': 'str',
          'title': '',
          'default': None, 'delegate': True}],
        'resultFields': [{'name': 'url', 'title': 'URL', 'data_type': 'str'}]
      },
      # ...
    ]
    """
    checks_registry = apps.get_app_config('dqm').checks
    check_classes = [cc for name, cc in checks_registry.items()]
    checks_metadata = [c.get_metadata() for c in check_classes]
    return checks_metadata

  @property
  def params(self) -> Dict:
    return json.loads(self.params_json) if self.params_json else {}

  @property
  def check_class(self) -> BaseCheck:
    """Returns the actual check class (BaseCheck) for the current check object.
    """
    checks_registry = apps.get_app_config('dqm').checks
    try:
      check_class = checks_registry[self.name]
    except:
      raise CheckClassNotFoundError(check_name=self.name)

    return check_class

  def execute(self,
    suite_execution: SuiteExecution,
    extra_params: Dict = None) -> CheckExecution:
    """Execute the check and return a CheckExecution object by execution the
    `run`method of the base check class of this check object.

    A CheckExecution is created and persisted in database.

    Note that every `CheckExecution` is part of a `SuiteExecution`, the related
    `SuiteExecution`object is thus also updated in this method.
    """

    ce = CheckExecution.objects.create(suite_execution=suite_execution,
      check_ref=self)
    params = {**self.params, **extra_params} if extra_params else self.params

    try:
      result: Result = self.check_class().run(params=params)

      ce.input_data_json = json.dumps(params, cls=DjangoJSONEncoder)
      ce.result_json = json.dumps(asdict(result), cls=DjangoJSONEncoder)
      ce.status = Status.Done
      ce.success = ce.result['success']
    except Exception as e:
      logger.error(traceback.format_exc())
      ce.result_json = json.dumps({'exception': str(e)}, cls=DjangoJSONEncoder)
      ce.status = Status.Failed
    finally:
      ce.save()
      suite_execution.update_after_check_execution(check_execution=ce)

    return ce

class CheckExecution(models.Model):
  check_ref = models.ForeignKey(Check, on_delete=models.CASCADE)
  suite_execution = models.ForeignKey(SuiteExecution, on_delete=models.CASCADE,
    related_name='check_executions', null=True, blank=True)
  status = models.IntegerField(choices=Status.choices, default=Status.Created)
  success = models.BooleanField(null=True, blank=True)
  input_data_json = models.TextField(null=True, blank=True)
  result_json = models.TextField(null=True, blank=True)

  created = models.DateTimeField(auto_now_add=True)
  updated = models.DateTimeField(auto_now=True)

  def __str__(self) -> str:
    return '{} - {}'.format(self.check_ref, self.get_status_display())

  @property
  def result(self) -> List[Any]:
    return json.loads(self.result_json) if self.result_json else []

  @classmethod
  def get_stats(cls) -> List:
    query = CheckExecution.objects.filter(
      created__gte=timezone.now()-timedelta(days=10)).annotate(
      day=Trunc('created', 'day', output_field=models.DateField()))

    results = [['day', 'executions', 'successes', 'fails']]
    results = results + [[
      date(day.year, day.month, day.day),
      len([se for se in query if date(se.day.year, se.day.month,
        se.day.day) == date(day.year, day.month, day.day)]),
      len([se for se in query if se.success and date(se.day.year, se.day.month,
        se.day.day) == date(day.year, day.month, day.day)]),
      len([se for se in query if not se.success and date(se.day.year,
        se.day.month, se.day.day) == date(day.year, day.month, day.day)]),
    ] for day in (
      timezone.now() - timedelta(days=10) + timedelta(n) for n in range(11))]

    return results


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.wpi.first.wpilibj.templates.testmode;

import edu.wpi.first.wpilibj.networktables.NetworkTable;
import edu.wpi.first.wpilibj.templates.Devices;
import edu.wpi.first.wpilibj.templates.IStep;
import edu.wpi.first.wpilibj.templates.autonomous.Chain;
import edu.wpi.first.wpilibj.templates.autonomous.Action;
import edu.wpi.first.wpilibj.templates.autonomous.autoactions.*;
import edu.wpi.first.wpilibj.templates.Constants;
import edu.wpi.first.wpilibj.templates.IntakeArm;

/**
 *
 * @author aaroneline
 */
public class TestMode implements IStep {

    private boolean doneAllActs;
    private boolean doneRunDrive;
    private boolean doneRunKicker;
    private boolean doneRunIntakeArm;
    private Chain runDrive;
    private Chain runKicker;
    private Chain runIntakeArm;
    static double testNumber;

    //Constants
    private final int NO_TEST = 0;
    private final int ALL_TEST = 1;
    private final int DRIVE_TEST = 2;
    private final int KICKER_TEST = 3;
    private final int INTAKE_TEST = 4;
    private final int ARM_DOWN_WAIT = 1;

    public void step() {
        if (!doneAllActs && testNumber != NO_TEST) {
            if (testNumber == ALL_TEST) {//Run all tests
                if (!doneRunDrive) {
                    doneRunDrive = runDrive.doAct();
                }else if(!doneRunKicker){
                    doneRunKicker = runKicker.doAct();
                }else if(!doneRunIntakeArm){
                    //Use doneAllActs for final act instead of corresponding
                    //    boolean (in this case, instead of doneRunIntakeArm)
                    doneAllActs = runIntakeArm.doAct();
                }
            } else if (testNumber == DRIVE_TEST) {
                doneAllActs = runDrive.doAct();
            } else if(testNumber == KICKER_TEST) {
                doneAllActs = runKicker.doAct();
            } else if(testNumber == INTAKE_TEST) {
                doneAllActs = runIntakeArm.doAct();
            }
        }
    }

    public void init() {
        TestResults acc = new TestResults();

        //Create the chain for drive system actions
        runKicker = new Chain(new Action[]{
            new KickerAction()
        });
        runIntakeArm = new Chain(new Action[]{
            new IntakeDown(),
            new TimerWaitAction(ARM_DOWN_WAIT),
            new IntakeUp()
        });

        runDrive = new Chain(new Action[]{
            new TestEncoderAction(Devices.wheelEncoder1, 0, Constants.EQUAL, "LeftWheelStopped", acc),
            new TestEncoderAction(Devices.wheelEncoder2, 0, Constants.EQUAL, "RightWheelStopped", acc),
            new ArcadeDriveAction(0.75, 0, 1500),
            new TimerWaitAction(3),//Wait
//            new TestEncoderAction("Forwards"),//Read the encoder when moving forwards
            new ArcadeDriveAction(0, 0, 1500),//Stop
            new TimerWaitAction(1),//Wait 1 sec
            new ArcadeDriveAction(-0.75, 0, 1500),//Drive backwards at 75% speed
            new TimerWaitAction(3),//Wait for 3 secs
//            new TestEncoderAction("Backwards"),//Read encoder when moving backwards
            new ArcadeDriveAction(0, 0, 1500),//Stop
            new TimerWaitAction(1),//Wait 1 sec
            new ArcadeDriveAction(0, 1, 1500),//Turn right
            new TimerWaitAction(3),//Wait 3 secs
//            new TestEncoderAction("Turning right"),//Read encoder when turning right
            new ArcadeDriveAction(0, 0, 1500),//Stop
            new TimerWaitAction(1),//Wait 1 sec
            new ArcadeDriveAction(0, -1, 1500),//Turn left
            new TimerWaitAction(3),//Wait 3 secs
//            new TestEncoderAction("Turning left"),//Read encoder when turning left
            new ArcadeDriveAction(0, 0, 1500),//Stop
            new TimerWaitAction(5),//Wait 5 secs
            new GearShiftAction(false),
            new ArcadeDriveAction(0.75, 0, 1500),
            new TimerWaitAction(5),
//            new TestEncoderAction("High Gear"),
            new ArcadeDriveAction(0.75, 0, 1500),
            new GearShiftAction(true)
        });
        doneAllActs = false;
    }
    private boolean isIntakeDown = false;
    IntakeArm intakeArm =  new IntakeArm();

    public static void setTestNumber(double number) {
        testNumber = number;
    }
}


text:
package serving

import (
	"context"
	"testing"

	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/util/intstr"
	"knative.dev/pkg/kmp"
	"knative.dev/pkg/ptr"
	"knative.dev/serving/pkg/apis/config"
)

func TestVolumeMask(t *testing.T) {
	want := &corev1.Volume{
		Name:         "foo",
		VolumeSource: corev1.VolumeSource{},
	}
	in := want

	got := VolumeMask(context.Background(), in)

	if &want == &got {
		t.Error("Input and output share addresses. Want different addresses")
	}

	if diff, err := kmp.SafeDiff(want, got); err != nil {
		t.Error("Got error comparing output, err =", err)
	} else if diff != "" {
		t.Error("VolumeMask (-want, +got):", diff)
	}

	if got = VolumeMask(context.Background(), nil); got != nil {
		t.Errorf("VolumeMask(nil) = %v, want: nil", got)
	}
}

func TestVolumeSourceMask(t *testing.T) {
	want := &corev1.VolumeSource{
		Secret:    &corev1.SecretVolumeSource{},
		ConfigMap: &corev1.ConfigMapVolumeSource{},
	}
	in := &corev1.VolumeSource{
		Secret:    &corev1.SecretVolumeSource{},
		ConfigMap: &corev1.ConfigMapVolumeSource{},
		NFS:       &corev1.NFSVolumeSource{},
	}

	got := VolumeSourceMask(context.Background(), in)

	if &want == &got {
		t.Error("Input and output share addresses. Want different addresses")
	}

	if diff, err := kmp.SafeDiff(want, got); err != nil {
		t.Error("Got error comparing output, err =", err)
	} else if diff != "" {
		t.Error("VolumeSourceMask (-want, +got):", diff)
	}

	if got = VolumeSourceMask(context.Background(), nil); got != nil {
		t.Errorf("VolumeSourceMask(nil) = %v, want: nil", got)
	}
}

func TestPodSpecMask(t *testing.T) {
	want := &corev1.PodSpec{
		ServiceAccountName: "default",
		ImagePullSecrets: []corev1.LocalObjectReference{{
			Name: "foo",
		}},
		Containers: []corev1.Container{{
			Image: "helloworld",
		}},
		Volumes: []corev1.Volume{{
			Name: "the-name",
			VolumeSource: corev1.VolumeSource{
				Secret: &corev1.SecretVolumeSource{
					SecretName: "foo",
				},
			},
		}},
	}
	in := &corev1.PodSpec{
		ServiceAccountName: "default",
		ImagePullSecrets: []corev1.LocalObjectReference{{
			Name: "foo",
		}},
		Containers: []corev1.Container{{
			Image: "helloworld",
		}},
		Volumes: []corev1.Volume{{
			Name: "the-name",
			VolumeSource: corev1.VolumeSource{
				Secret: &corev1.SecretVolumeSource{
					SecretName: "foo",
				},
			},
		}},
		// Stripped out.
		InitContainers: []corev1.Container{{
			Image: "busybox",
		}},
	}

	ctx := context.Background()
	got := PodSpecMask(ctx, in)

	if &want == &got {
		t.Error("Input and output share addresses. Want different addresses")
	}

	if diff, err := kmp.SafeDiff(want, got); err != nil {
		t.Error("Got error comparing output, err =", err)
	} else if diff != "" {
		t.Error("PodSpecMask (-want, +got):", diff)
	}

	if got = PodSpecMask(ctx, nil); got != nil {
		t.Errorf("PodSpecMask(nil) = %v, want: nil", got)
	}
}

func TestContainerMask(t *testing.T) {
	want := &corev1.Container{
		Name:                     "foo",
		Args:                     []string{"hello"},
		Command:                  []string{"world"},
		Env:                      []corev1.EnvVar{{}},
		EnvFrom:                  []corev1.EnvFromSource{{}},
		Image:                    "python",
		ImagePullPolicy:          corev1.PullAlways,
		LivenessProbe:            &corev1.Probe{},
		Ports:                    []corev1.ContainerPort{{}},
		ReadinessProbe:           &corev1.Probe{},
		Resources:                corev1.ResourceRequirements{},
		SecurityContext:          &corev1.SecurityContext{},
		TerminationMessagePath:   "/",
		TerminationMessagePolicy: corev1.TerminationMessageReadFile,
		VolumeMounts:             []corev1.VolumeMount{{}},
	}
	in := &corev1.Container{
		Args:                     []string{"hello"},
		Command:                  []string{"world"},
		Env:                      []corev1.EnvVar{{}},
		EnvFrom:                  []corev1.EnvFromSource{{}},
		Image:                    "python",
		ImagePullPolicy:          corev1.PullAlways,
		LivenessProbe:            &corev1.Probe{},
		Ports:                    []corev1.ContainerPort{{}},
		ReadinessProbe:           &corev1.Probe{},
		Resources:                corev1.ResourceRequirements{},
		SecurityContext:          &corev1.SecurityContext{},
		TerminationMessagePath:   "/",
		TerminationMessagePolicy: corev1.TerminationMessageReadFile,
		VolumeMounts:             []corev1.VolumeMount{{}},
		Name:                     "foo",
		Stdin:                    true,
		StdinOnce:                true,
		TTY:                      true,
	}

	got := ContainerMask(in)

	if &want == &got {
		t.Error("Input and output share addresses. Want different addresses")
	}

	if diff, err := kmp.SafeDiff(want, got); err != nil {
		t.Error("Got error comparing output, err =", err)
	} else if diff != "" {
		t.Error("ContainerMask (-want, +got):", diff)
	}

	if got = ContainerMask(nil); got != nil {
		t.Errorf("ContainerMask(nil) = %v, want: nil", got)
	}
}

func TestVolumeMountMask(t *testing.T) {
	mode := corev1.MountPropagationBidirectional

	want := &corev1.VolumeMount{
		Name:      "foo",
		ReadOnly:  true,
		MountPath: "/foo/bar",
		SubPath:   "baz",
	}
	in := &corev1.VolumeMount{
		Name:             "foo",
		ReadOnly:         true,
		MountPath:        "/foo/bar",
		SubPath:          "baz",
		MountPropagation: &mode,
	}

	got := VolumeMountMask(in)

	if &want == &got {
		t.Error("Input and output share addresses. Want different addresses")
	}

	if diff, err := kmp.SafeDiff(want, got); err != nil {
		t.Error("Got error comparing output, err =", err)
	} else if diff != "" {
		t.Error("VolumeMountMask (-want, +got):", diff)
	}

	if got = VolumeMountMask(nil); got != nil {
		t.Errorf("VolumeMountMask(nil) = %v, want: nil", got)
	}
}

func TestProbeMask(t *testing.T) {
	want := &corev1.Probe{
		ProbeHandler:        corev1.ProbeHandler{},
		InitialDelaySeconds: 42,
		TimeoutSeconds:      42,
		PeriodSeconds:       42,
		SuccessThreshold:    42,
		FailureThreshold:    42,
	}
	in := want

	got := ProbeMask(in)

	if &want == &got {
		t.Error("Input and output share addresses. Want different addresses")
	}

	if diff, err := kmp.SafeDiff(want, got); err != nil {
		t.Error("Got error comparing output, err =", err)
	} else if diff != "" {
		t.Error("ProbeMask (-want, +got):", diff)
	}

	if got = ProbeMask(nil); got != nil {
		t.Errorf("ProbeMask(nil) = %v, want: nil", got)
	}
}

func TestHandlerMask(t *testing.T) {
	want := &corev1.ProbeHandler{
		Exec:      &corev1.ExecAction{},
		HTTPGet:   &corev1.HTTPGetAction{},
		TCPSocket: &corev1.TCPSocketAction{},
	}
	in := want

	got := HandlerMask(in)

	if &want == &got {
		t.Error("Input and output share addresses. Want different addresses")
	}

	if diff, err := kmp.SafeDiff(want, got); err != nil {
		t.Error("Got error comparing output, err =", err)
	} else if diff != "" {
		t.Error("HandlerMask (-want, +got):", diff)
	}

	if got = HandlerMask(nil); got != nil {
		t.Errorf("HandlerMask(nil) = %v, want: nil", got)
	}
}

func TestExecActionMask(t *testing.T) {
	want := &corev1.ExecAction{
		Command: []string{"foo", "bar"},
	}
	in := want

	got := ExecActionMask(in)

	if &want == &got {
		t.Error("Input and output share addresses. Want different addresses")
	}

	if diff, err := kmp.SafeDiff(want, got); err != nil {
		t.Error("Got error comparing output, err =", err)
	} else if diff != "" {
		t.Error("ExecActionMask (-want, +got):", diff)
	}

	if got = ExecActionMask(nil); got != nil {
		t.Errorf("ExecActionMask(nil) = %v, want: nil", got)
	}
}

func TestHTTPGetActionMask(t *testing.T) {
	want := &corev1.HTTPGetAction{
		Host:        "foo",
		Path:        "/bar",
		Scheme:      corev1.URISchemeHTTP,
		HTTPHeaders: []corev1.HTTPHeader{{}},
		Port:        intstr.FromInt(8080),
	}
	in := &corev1.HTTPGetAction{
		Host:        "foo",
		Path:        "/bar",
		Scheme:      corev1.URISchemeHTTP,
		HTTPHeaders: []corev1.HTTPHeader{{}},
		Port:        intstr.FromInt(8080),
	}

	got := HTTPGetActionMask(in)

	if &want == &got {
		t.Error("Input and output share addresses. Want different addresses")
	}

	if diff, err := kmp.SafeDiff(want, got); err != nil {
		t.Error("Got error comparing output, err =", err)
	} else if diff != "" {
		t.Error("HTTPGetActionMask (-want, +got):", diff)
	}

	if got = HTTPGetActionMask(nil); got != nil {
		t.Errorf("HTTPGetActionMask(nil) = %v, want: nil", got)
	}
}

func TestTCPSocketActionMask(t *testing.T) {
	want := &corev1.TCPSocketAction{
		Host: "foo",
		Port: intstr.FromString("https"),
	}
	in := &corev1.TCPSocketAction{
		Host: "foo",
		Port: intstr.FromString("https"),
	}

	got := TCPSocketActionMask(in)

	if &want == &got {
		t.Error("Input and output share addresses. Want different addresses")
	}

	if diff, err := kmp.SafeDiff(want, got); err != nil {
		t.Error("Got error comparing output, err =", err)
	} else if diff != "" {
		t.Error("TCPSocketActionMask (-want, +got):", diff)
	}

	if got = TCPSocketActionMask(nil); got != nil {
		t.Errorf("TCPSocketActionMask(nil) = %v, want: nil", got)
	}
}

func TestContainerPortMask(t *testing.T) {
	want := &corev1.ContainerPort{
		ContainerPort: 42,
		Name:          "foo",
		Protocol:      corev1.ProtocolTCP,
	}
	in := &corev1.ContainerPort{
		ContainerPort: 42,
		Name:          "foo",
		Protocol:      corev1.ProtocolTCP,
		HostIP:        "10.0.0.1",
		HostPort:      43,
	}

	got := ContainerPortMask(in)

	if &want == &got {
		t.Error("Input and output share addresses. Want different addresses")
	}

	if diff, err := kmp.SafeDiff(want, got); err != nil {
		t.Error("Got error comparing output, err =", err)
	} else if diff != "" {
		t.Error("ContainerPortMask (-want, +got):", diff)
	}

	if got = ContainerPortMask(nil); got != nil {
		t.Errorf("ContainerPortMask(nil) = %v, want: nil", got)
	}
}

func TestEnvVarMask(t *testing.T) {
	want := &corev1.EnvVar{
		Name:      "foo",
		Value:     "bar",
		ValueFrom: &corev1.EnvVarSource{},
	}
	in := want

	got := EnvVarMask(in)

	if &want == &got {
		t.Error("Input and output share addresses. Want different addresses")
	}

	if diff, err := kmp.SafeDiff(want, got); err != nil {
		t.Error("Got error comparing output, err =", err)
	} else if diff != "" {
		t.Error("EnvVarMask (-want, +got):", diff)
	}

	if got = EnvVarMask(nil); got != nil {
		t.Errorf("EnvVarMask(nil) = %v, want: nil", got)
	}
}

func TestEnvVarSourceMask(t *testing.T) {
	tests := []struct {
		name     string
		fieldRef bool
		in       *corev1.EnvVarSource
		want     *corev1.EnvVarSource
	}{{
		name:     "FieldRef false",
		fieldRef: false,
		in: &corev1.EnvVarSource{
			ConfigMapKeyRef:  &corev1.ConfigMapKeySelector{},
			SecretKeyRef:     &corev1.SecretKeySelector{},
			FieldRef:         &corev1.ObjectFieldSelector{},
			ResourceFieldRef: &corev1.ResourceFieldSelector{},
		},
		want: &corev1.EnvVarSource{
			ConfigMapKeyRef: &corev1.ConfigMapKeySelector{},
			SecretKeyRef:    &corev1.SecretKeySelector{},
		},
	}, {
		name:     "FieldRef true",
		fieldRef: true,
		in: &corev1.EnvVarSource{
			ConfigMapKeyRef:  &corev1.ConfigMapKeySelector{},
			SecretKeyRef:     &corev1.SecretKeySelector{},
			FieldRef:         &corev1.ObjectFieldSelector{},
			ResourceFieldRef: &corev1.ResourceFieldSelector{},
		},
		want: &corev1.EnvVarSource{
			ConfigMapKeyRef:  &corev1.ConfigMapKeySelector{},
			SecretKeyRef:     &corev1.SecretKeySelector{},
			FieldRef:         &corev1.ObjectFieldSelector{},
			ResourceFieldRef: &corev1.ResourceFieldSelector{},
		},
	}}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			got := EnvVarSourceMask(test.in, test.fieldRef)

			if &test.want == &got {
				t.Error("Input and output share addresses. Want different addresses")
			}

			if diff, err := kmp.SafeDiff(test.want, got); err != nil {
				t.Error("Got error comparing output, err =", err)
			} else if diff != "" {
				t.Error("EnvVarSourceMask (-want, +got):", diff)
			}

			if got = EnvVarSourceMask(nil, test.fieldRef); got != nil {
				t.Errorf("EnvVarSourceMask(nil) = %v, want: nil", got)
			}
		})
	}
}

func TestLocalObjectReferenceMask(t *testing.T) {
	want := &corev1.LocalObjectReference{
		Name: "foo",
	}
	in := want

	got := LocalObjectReferenceMask(in)

	if &want == &got {
		t.Error("Input and output share addresses. Want different addresses")
	}

	if diff, err := kmp.SafeDiff(want, got); err != nil {
		t.Error("Got error comparing output, err =", err)
	} else if diff != "" {
		t.Error("LocalObjectReferenceMask (-want, +got):", diff)
	}

	if got = LocalObjectReferenceMask(nil); got != nil {
		t.Errorf("LocalObjectReferenceMask(nil) = %v, want: nil", got)
	}
}

func TestConfigMapKeySelectorMask(t *testing.T) {
	want := &corev1.ConfigMapKeySelector{
		LocalObjectReference: corev1.LocalObjectReference{},
		Key:                  "foo",
		Optional:             ptr.Bool(true),
	}
	in := want

	got := ConfigMapKeySelectorMask(in)

	if &want == &got {
		t.Error("Input and output share addresses. Want different addresses")
	}

	if diff, err := kmp.SafeDiff(want, got); err != nil {
		t.Error("Got error comparing output, err =", err)
	} else if diff != "" {
		t.Error("ConfigMapKeySelectorMask (-want, +got):", diff)
	}

	if got = ConfigMapKeySelectorMask(nil); got != nil {
		t.Errorf("ConfigMapKeySelectorMask(nil) = %v, want: nil", got)
	}
}

func TestSecretKeySelectorMask(t *testing.T) {
	want := &corev1.SecretKeySelector{
		LocalObjectReference: corev1.LocalObjectReference{},
		Key:                  "foo",
		Optional:             ptr.Bool(true),
	}
	in := want

	got := SecretKeySelectorMask(in)

	if &want == &got {
		t.Error("Input and output share addresses. Want different addresses")
	}

	if diff, err := kmp.SafeDiff(want, got); err != nil {
		t.Error("Got error comparing output, err =", err)
	} else if diff != "" {
		t.Error("SecretKeySelectorMask (-want, +got):", diff)
	}

	if got = SecretKeySelectorMask(nil); got != nil {
		t.Errorf("SecretKeySelectorMask(nil) = %v, want: nil", got)
	}
}

func TestConfigMapEnvSourceMask(t *testing.T) {
	want := &corev1.ConfigMapEnvSource{
		LocalObjectReference: corev1.LocalObjectReference{},
		Optional:             ptr.Bool(true),
	}
	in := want

	got := ConfigMapEnvSourceMask(in)

	if &want == &got {
		t.Error("Input and output share addresses. Want different addresses")
	}

	if diff, err := kmp.SafeDiff(want, got); err != nil {
		t.Error("Got error comparing output, err =", err)
	} else if diff != "" {
		t.Error("ConfigMapEnvSourceMask (-want, +got):", diff)
	}

	if got = ConfigMapEnvSourceMask(nil); got != nil {
		t.Errorf("ConfigMapEnvSourceMask(nil) = %v, want: nil", got)
	}
}

func TestSecretEnvSourceMask(t *testing.T) {
	want := &corev1.SecretEnvSource{
		LocalObjectReference: corev1.LocalObjectReference{},
		Optional:             ptr.Bool(true),
	}
	in := want

	got := SecretEnvSourceMask(in)

	if &want == &got {
		t.Error("Input and output share addresses. Want different addresses")
	}

	if diff, err := kmp.SafeDiff(want, got); err != nil {
		t.Error("Got error comparing output, err =", err)
	} else if diff != "" {
		t.Error("SecretEnvSourceMask (-want, +got):", diff)
	}

	if got = SecretEnvSourceMask(nil); got != nil {
		t.Errorf("SecretEnvSourceMask(nil) = %v, want: nil", got)
	}
}

func TestEnvFromSourceMask(t *testing.T) {
	want := &corev1.EnvFromSource{
		Prefix:       "foo",
		ConfigMapRef: &corev1.ConfigMapEnvSource{},
		SecretRef:    &corev1.SecretEnvSource{},
	}
	in := want

	got := EnvFromSourceMask(in)

	if &want == &got {
		t.Error("Input and output share addresses. Want different addresses")
	}

	if diff, err := kmp.SafeDiff(want, got); err != nil {
		t.Error("Got error comparing output, err =", err)
	} else if diff != "" {
		t.Error("EnvFromSourceMask (-want, +got):", diff)
	}

	if got = EnvFromSourceMask(nil); got != nil {
		t.Errorf("EnvFromSourceMask(nil) = %v, want: nil", got)
	}
}

func TestResourceRequirementsMask(t *testing.T) {
	want := &corev1.ResourceRequirements{
		Limits:   make(corev1.ResourceList),
		Requests: make(corev1.ResourceList),
	}
	in := want

	got := ResourceRequirementsMask(in)

	if &want == &got {
		t.Error("Input and output share addresses. Want different addresses")
	}

	if diff, err := kmp.SafeDiff(want, got); err != nil {
		t.Error("Got error comparing output, err =", err)
	} else if diff != "" {
		t.Error("ResourceRequirementsMask (-want, +got):", diff)
	}

	if got = ResourceRequirementsMask(nil); got != nil {
		t.Errorf("ResourceRequirementsMask(nil) = %v, want: nil", got)
	}
}

func TestPodSecurityContextMask(t *testing.T) {
	in := &corev1.PodSecurityContext{
		SELinuxOptions:     &corev1.SELinuxOptions{},
		WindowsOptions:     &corev1.WindowsSecurityContextOptions{},
		SupplementalGroups: []int64{},
		Sysctls:            []corev1.Sysctl{},
		RunAsUser:          ptr.Int64(1),
		RunAsGroup:         ptr.Int64(1),
		RunAsNonRoot:       ptr.Bool(true),
		FSGroup:            ptr.Int64(1),
		SeccompProfile: &corev1.SeccompProfile{
			Type: corev1.SeccompProfileTypeRuntimeDefault,
		},
	}

	want := &corev1.PodSecurityContext{}
	ctx := context.Background()

	got := PodSecurityContextMask(ctx, in)

	if &want == &got {
		t.Error("Input and output share addresses. Want different addresses")
	}

	if diff, err := kmp.SafeDiff(want, got); err != nil {
		t.Error("Got error comparing output, err =", err)
	} else if diff != "" {
		t.Error("PostSecurityContextMask (-want, +got):", diff)
	}

	if got = PodSecurityContextMask(ctx, nil); got != nil {
		t.Errorf("PodSecurityContextMask(nil) = %v, want: nil", got)
	}
}

func TestPodSecurityContextMask_FeatureEnabled(t *testing.T) {
	in := &corev1.PodSecurityContext{
		SELinuxOptions:     &corev1.SELinuxOptions{},
		WindowsOptions:     &corev1.WindowsSecurityContextOptions{},
		SupplementalGroups: []int64{1},
		Sysctls:            []corev1.Sysctl{},
		RunAsUser:          ptr.Int64(1),
		RunAsGroup:         ptr.Int64(1),
		RunAsNonRoot:       ptr.Bool(true),
		FSGroup:            ptr.Int64(1),
		SeccompProfile: &corev1.SeccompProfile{
			Type: corev1.SeccompProfileTypeRuntimeDefault,
		},
	}

	want := &corev1.PodSecurityContext{
		RunAsUser:          ptr.Int64(1),
		RunAsGroup:         ptr.Int64(1),
		RunAsNonRoot:       ptr.Bool(true),
		FSGroup:            ptr.Int64(1),
		SupplementalGroups: []int64{1},
		SeccompProfile: &corev1.SeccompProfile{
			Type: corev1.SeccompProfileTypeRuntimeDefault,
		},
	}

	ctx := config.ToContext(context.Background(),
		&config.Config{
			Features: &config.Features{
				PodSpecSecurityContext: config.Enabled,
			},
		},
	)

	got := PodSecurityContextMask(ctx, in)

	if &want == &got {
		t.Error("Input and output share addresses. Want different addresses")
	}

	if diff, err := kmp.SafeDiff(want, got); err != nil {
		t.Error("Got error comparing output, err =", err)
	} else if diff != "" {
		t.Error("PostSecurityContextMask (-want, +got):", diff)
	}
}

func TestSecurityContextMask(t *testing.T) {
	mtype := corev1.UnmaskedProcMount
	want := &corev1.SecurityContext{
		Capabilities:             &corev1.Capabilities{},
		RunAsUser:                ptr.Int64(1),
		RunAsGroup:               ptr.Int64(2),
		RunAsNonRoot:             ptr.Bool(true),
		ReadOnlyRootFilesystem:   ptr.Bool(true),
		AllowPrivilegeEscalation: ptr.Bool(false),
		SeccompProfile: &corev1.SeccompProfile{
			Type: corev1.SeccompProfileTypeRuntimeDefault,
		},
	}
	in := &corev1.SecurityContext{
		RunAsUser:                ptr.Int64(1),
		Capabilities:             &corev1.Capabilities{},
		Privileged:               ptr.Bool(true),
		SELinuxOptions:           &corev1.SELinuxOptions{},
		RunAsGroup:               ptr.Int64(2),
		RunAsNonRoot:             ptr.Bool(true),
		ReadOnlyRootFilesystem:   ptr.Bool(true),
		AllowPrivilegeEscalation: ptr.Bool(false),
		ProcMount:                &mtype,
		SeccompProfile: &corev1.SeccompProfile{
			Type: corev1.SeccompProfileTypeRuntimeDefault,
		},
		WindowsOptions: &corev1.WindowsSecurityContextOptions{},
	}

	got := SecurityContextMask(context.Background(), in)

	if &want == &got {
		t.Error("Input and output share addresses. Want different addresses")
	}

	if diff, err := kmp.SafeDiff(want, got); err != nil {
		t.Error("Got error comparing output, err =", err)
	} else if diff != "" {
		t.Error("SecurityContextMask (-want, +got):", diff)
	}

	if got = SecurityContextMask(context.Background(), nil); got != nil {
		t.Errorf("SecurityContextMask(nil) = %v, want: nil", got)
	}
}

func TestSecurityContextMask_FeatureEnabled(t *testing.T) {
	mtype := corev1.UnmaskedProcMount
	want := &corev1.SecurityContext{
		AllowPrivilegeEscalation: ptr.Bool(false),
		Capabilities:             &corev1.Capabilities{},
		RunAsGroup:               ptr.Int64(2),
		RunAsNonRoot:             ptr.Bool(true),
		RunAsUser:                ptr.Int64(1),
		ReadOnlyRootFilesystem:   ptr.Bool(true),
		SeccompProfile: &corev1.SeccompProfile{
			Type: corev1.SeccompProfileTypeRuntimeDefault,
		},
	}
	in := &corev1.SecurityContext{
		AllowPrivilegeEscalation: ptr.Bool(false),
		Capabilities:             &corev1.Capabilities{},
		Privileged:               ptr.Bool(true),
		ProcMount:                &mtype,
		ReadOnlyRootFilesystem:   ptr.Bool(true),
		RunAsGroup:               ptr.Int64(2),
		RunAsNonRoot:             ptr.Bool(true),
		RunAsUser:                ptr.Int64(1),
		SELinuxOptions:           &corev1.SELinuxOptions{},
		SeccompProfile: &corev1.SeccompProfile{
			Type: corev1.SeccompProfileTypeRuntimeDefault,
		},
		WindowsOptions: &corev1.WindowsSecurityContextOptions{},
	}

	ctx := config.ToContext(context.Background(),
		&config.Config{
			Features: &config.Features{
				PodSpecSecurityContext: config.Enabled,
			},
		},
	)

	got := SecurityContextMask(ctx, in)

	if &want == &got {
		t.Error("Input and output share addresses. Want different addresses")
	}

	if diff, err := kmp.SafeDiff(want, got); err != nil {
		t.Error("Got error comparing output, err =", err)
	} else if diff != "" {
		t.Error("SecurityContextMask (-want, +got):", diff)
	}
}


text:
namespace faint{

constexpr utf8_char utf8_null(0x00);
constexpr utf8_char backslash(0x5c); // aka "reverse solidus"
constexpr utf8_char bullet(0x2022);
constexpr utf8_char comma(0x2c);
constexpr utf8_char degree_sign(0xb0);
constexpr utf8_char double_prime(0x2033);
constexpr utf8_char downwards_arrow_with_tip_leftwards(0x21b2);
constexpr utf8_char eol(0x0a);
constexpr utf8_char euro_sign(0x20ac);
constexpr utf8_char exclamation_mark(0x21);
constexpr utf8_char full_stop(0x2e);
constexpr utf8_char greek_capital_letter_delta(0x394);
constexpr utf8_char greek_small_letter_pi(0x3c0);
constexpr utf8_char hyphen(0x2D);
constexpr utf8_char left_parenthesis(0x28);
constexpr utf8_char middle_dot(0x00b7);
constexpr utf8_char no_break_space(0xc2a0);
constexpr utf8_char pilcrow_sign(0x00b6);
constexpr utf8_char prime(0x2032);
constexpr utf8_char question_mark(0x3f);
constexpr utf8_char replacement_character(0xfffd);
constexpr utf8_char right_parenthesis(0x29);
constexpr utf8_char snowman(0x2603);
constexpr utf8_char space(0x20);
constexpr utf8_char superscript_two(0xb2);
constexpr utf8_char tab(0x9);
constexpr utf8_char triple_prime(0x2034);

inline bool is_punctuation(const utf8_char& ch){
  return ch == comma ||
    ch == exclamation_mark ||
    ch == full_stop ||
    ch == question_mark;
}

} // namespace

#endif


text:
Overview
========
A paper covering CoolProp has been published in the journal Industrial & Engineering Chemistry Research (`link to paper <http://pubs.acs.org/doi/abs/10.1021/ie4033999>`_).

As CoolProp is free to all users, we simply ask that if you use CoolProp in your academic work that you make a reference to CoolProp.

If you use CoolProp, please cite the article (open-access) cited below, and the domain www.coolprop.org

BibTeX
======

BibTeX citation::

    @article{doi:10.1021/ie4033999,
        author = {Bell, Ian H. and Wronski, Jorrit and Quoilin, Sylvain and Lemort, Vincent},
        title = {Pure and Pseudo-pure Fluid Thermophysical Property Evaluation and the Open-Source Thermophysical Property Library CoolProp},
        journal = {Industrial \& Engineering Chemistry Research},
        volume = {53},
        number = {6},
        pages = {2498-2508},
        year = {2014},
        doi = {10.1021/ie4033999},

        URL = {http://pubs.acs.org/doi/abs/10.1021/ie4033999},
        eprint = {http://pubs.acs.org/doi/pdf/10.1021/ie4033999}
        }

See Also
========
www.coolprop.org


text:
package org.apache.activemq.artemis.jms.tests;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.IllegalStateException;
import javax.jms.JMSSecurityException;
import javax.jms.Session;

import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
import org.apache.activemq.artemis.jms.client.DefaultConnectionProperties;
import org.apache.activemq.artemis.jms.tests.util.ProxyAssertSupport;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

/**
 * Test JMS Security.
 * <br>
 * This test must be run with the Test security config. on the server
 */
public class SecurityTest extends JMSTestCase {
   private String originalAmqUser;
   private String originalAmqPassword;
   private String originalBrokerBindUrl;

   @Before
   public void setupProperty() {
      originalAmqUser = System.getProperty(DefaultConnectionProperties.AMQ_USER);
      originalAmqPassword = System.getProperty(DefaultConnectionProperties.AMQ_PASSWORD);
      originalBrokerBindUrl = System.getProperty(DefaultConnectionProperties.BROKER_BIND_URL);
   }

   @After
   public void clearProperty() {
      if (originalAmqUser == null) {
         System.clearProperty(DefaultConnectionProperties.AMQ_USER);
      } else {
         System.setProperty(DefaultConnectionProperties.AMQ_USER, originalAmqUser);
      }
      if (originalAmqPassword == null) {
         System.clearProperty(DefaultConnectionProperties.AMQ_PASSWORD);
      } else {
         System.setProperty(DefaultConnectionProperties.AMQ_PASSWORD, originalAmqPassword);
      }
      if (originalBrokerBindUrl == null) {
         System.clearProperty(DefaultConnectionProperties.BROKER_BIND_URL);
      } else {
         System.setProperty(DefaultConnectionProperties.BROKER_BIND_URL, originalBrokerBindUrl);
      }
   }

      /**
       * Login with no user, no password Should allow login (equivalent to guest)
       */
   @Test
   public void testLoginNoUserNoPassword() throws Exception {
      createConnection();
      createConnection(null, null);
   }

   /**
    * Login with no user, no password
    * Should allow login (equivalent to guest)
    */
   @Test
   public void testLoginNoUserNoPasswordWithNoGuest() throws Exception {
      createConnection();
      createConnection(null, null);
   }

   /**
    * Login with valid user and password
    * Should allow
    */
   @Test
   public void testLoginValidUserAndPassword() throws Exception {
      createConnection("guest", "guest");
   }

   /**
    * Login with valid user and password
    * Should allow
    */
   @Test
   public void testLoginValidUserAndPasswordSystemProperty() throws Exception {
      System.setProperty(DefaultConnectionProperties.AMQ_USER, "guest");
      System.setProperty(DefaultConnectionProperties.AMQ_PASSWORD, "guest");
      DefaultConnectionProperties.initialize();
      ConnectionFactory cf = new ActiveMQConnectionFactory();
      Connection conn = addConnection(cf.createConnection());
   }

   /**
    * Login with valid user and password
    * Should allow
    */
   @Test
   public void testLoginValidUserAndPasswordSystemPropertyWithAdditionalProperties() throws Exception {
      System.setProperty(DefaultConnectionProperties.AMQ_USER, "guest");
      System.setProperty(DefaultConnectionProperties.AMQ_PASSWORD, "guest");
      System.setProperty(DefaultConnectionProperties.BROKER_BIND_URL, "tcp://localhost:61616?compressLargeMessage=true");
      DefaultConnectionProperties.initialize();
      ConnectionFactory cf = new ActiveMQConnectionFactory();
      Connection conn = addConnection(cf.createConnection());
      Assert.assertTrue(((ActiveMQConnectionFactory) cf).isCompressLargeMessage());
   }

   /**
    * Login with valid user and invalid password
    * Should allow
    */
   @Test
   public void testLoginValidUserInvalidPassword() throws Exception {
      try {
         Connection conn1 = createConnection("guest", "not.the.valid.password");
         ProxyAssertSupport.fail();
      } catch (JMSSecurityException e) {
         // Expected
      }
   }

   /**
    * Login with valid user and invalid password
    * Should allow
    */
   @Test
   public void testLoginValidUserInvalidPasswordSystemProperty() throws Exception {
      System.setProperty(DefaultConnectionProperties.AMQ_USER, "guest");
      System.setProperty(DefaultConnectionProperties.AMQ_PASSWORD, "not.the.valid.password");
      DefaultConnectionProperties.initialize();
      try {
         ConnectionFactory cf = new ActiveMQConnectionFactory();
         Connection conn1 = addConnection(cf.createConnection());
         ProxyAssertSupport.fail();
      } catch (JMSSecurityException e) {
         // Expected
      }
   }

   /**
    * Login with invalid user and invalid password
    * Should allow
    */
   @Test
   public void testLoginInvalidUserInvalidPassword() throws Exception {
      try {
         Connection conn1 = createConnection("not.the.valid.user", "not.the.valid.password");
         ProxyAssertSupport.fail();
      } catch (JMSSecurityException e) {
         // Expected
      }
   }

   /* Now some client id tests */

   /**
    * user/pwd with preconfigured clientID, should return preconf
    */
   @Test
   public void testPreConfClientID() throws Exception {
      Connection conn = null;
      try {
         ActiveMQServerTestCase.deployConnectionFactory("dilbert-id", "preConfcf", "preConfcf");
         ConnectionFactory cf = (ConnectionFactory) getInitialContext().lookup("preConfcf");
         conn = cf.createConnection("guest", "guest");
         String clientID = conn.getClientID();
         ProxyAssertSupport.assertEquals("Invalid ClientID", "dilbert-id", clientID);
      } finally {
         if (conn != null) {
            conn.close();
         }
         ActiveMQServerTestCase.undeployConnectionFactory("preConfcf");
      }
   }

   /**
    * Try setting client ID
    */
   @Test
   public void testSetClientID() throws Exception {
      Connection conn = createConnection();
      conn.setClientID("myID");
      String clientID = conn.getClientID();
      ProxyAssertSupport.assertEquals("Invalid ClientID", "myID", clientID);
   }

   /**
    * Try setting client ID on preconfigured connection - should throw exception
    */
   @Test
   public void testSetClientIDPreConf() throws Exception {
      Connection conn = null;
      try {
         ActiveMQServerTestCase.deployConnectionFactory("dilbert-id", "preConfcf", "preConfcf");
         ConnectionFactory cf = (ConnectionFactory) getInitialContext().lookup("preConfcf");
         conn = cf.createConnection("guest", "guest");
         conn.setClientID("myID");
         ProxyAssertSupport.fail();
      } catch (IllegalStateException e) {
         // Expected
      } finally {
         if (conn != null) {
            conn.close();
         }
         ActiveMQServerTestCase.undeployConnectionFactory("preConfcf");
      }
   }

   /*
    * Try setting client ID after an operation has been performed on the connection
    */
   @Test
   public void testSetClientIDAfterOp() throws Exception {
      Connection conn = createConnection();
      conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      try {
         conn.setClientID("myID");
         ProxyAssertSupport.fail();
      } catch (IllegalStateException e) {
         // Expected
      }
   }
}