text:
#include <app/server/OnboardingCodesUtil.h>
#include <inttypes.h>
#include <lib/core/CHIPCore.h>
#include <lib/shell/Commands.h>
#include <lib/shell/Engine.h>
#include <lib/shell/commands/Help.h>
#include <lib/support/CHIPArgParser.hpp>
#include <lib/support/CHIPMem.h>
#include <lib/support/CodeUtils.h>
#include <platform/CHIPDeviceLayer.h>
#include <setup_payload/QRCodeSetupPayloadGenerator.h>

#define CHIP_SHELL_MAX_BUFFER_SIZE 128

using chip::DeviceLayer::ConfigurationMgr;

namespace chip {
namespace Shell {

static CHIP_ERROR GetOnboardingQRCode(bool printHeader, chip::RendezvousInformationFlags aRendezvousFlags)
{
    streamer_t * sout = streamer_get();

    // Create buffer for QR code that can fit max size and null terminator.
    char qrCodeBuffer[chip::QRCodeBasicSetupPayloadGenerator::kMaxQRCodeBase38RepresentationLength + 1];
    chip::MutableCharSpan QRCode(qrCodeBuffer);

    if (printHeader)
    {
        streamer_printf(sout, "QRCode:            ");
    }
    ReturnErrorOnFailure(GetQRCode(QRCode, aRendezvousFlags));
    streamer_printf(sout, "%s\r\n", QRCode.data());
    return CHIP_NO_ERROR;
}

static CHIP_ERROR GetOnboardingQRCodeUrl(bool printHeader, chip::RendezvousInformationFlags aRendezvousFlags)
{
    streamer_t * sout = streamer_get();

    // Create buffer for QR code that can fit max size and null terminator.
    char qrCodeBuffer[chip::QRCodeBasicSetupPayloadGenerator::kMaxQRCodeBase38RepresentationLength + 1];
    chip::MutableCharSpan QRCode(qrCodeBuffer);

    if (printHeader)
    {
        streamer_printf(sout, "QRCodeUrl:         ");
    }
    ReturnErrorOnFailure(GetQRCode(QRCode, aRendezvousFlags));

    char qrCodeUrlBuffer[CHIP_SHELL_MAX_BUFFER_SIZE];

    ReturnErrorOnFailure(GetQRCodeUrl(qrCodeUrlBuffer, sizeof(qrCodeUrlBuffer), QRCode));
    streamer_printf(sout, "%s\r\n", qrCodeUrlBuffer);
    return CHIP_NO_ERROR;
}

static CHIP_ERROR GetOnboardingManualPairingCode(bool printHeader, chip::RendezvousInformationFlags aRendezvousFlags)
{
    streamer_t * sout = streamer_get();

    // Create buffer for manual pariting code that can fit max size + check digit + null terminator.
    char manualPairingCodeBuffer[chip::kManualSetupLongCodeCharLength + 1];
    chip::MutableCharSpan manualPairingCode(manualPairingCodeBuffer);

    if (printHeader)
    {
        streamer_printf(sout, "ManualPairingCode: ");
    }
    ReturnErrorOnFailure(GetManualPairingCode(manualPairingCode, aRendezvousFlags));
    streamer_printf(sout, "%s\r\n", manualPairingCode.data());
    return CHIP_NO_ERROR;
}

static CHIP_ERROR PrintAllOnboardingCodes(chip::RendezvousInformationFlags aRendezvousFlags)
{
    ReturnErrorOnFailure(GetOnboardingQRCode(true, aRendezvousFlags));
    ReturnErrorOnFailure(GetOnboardingQRCodeUrl(true, aRendezvousFlags));
    ReturnErrorOnFailure(GetOnboardingManualPairingCode(true, aRendezvousFlags));

    return CHIP_NO_ERROR;
}

static CHIP_ERROR RendezvousStringToFlag(char * str, chip::RendezvousInformationFlags * aRendezvousFlags)
{
    if (str == nullptr)
    {
        return CHIP_ERROR_INVALID_ARGUMENT;
    }
    if (aRendezvousFlags == nullptr)
    {
        return CHIP_NO_ERROR;
    }

    if (strcmp(str, "none") == 0)
    {
        *aRendezvousFlags = chip::RendezvousInformationFlag::kNone;
        return CHIP_NO_ERROR;
    }
    if (strcmp(str, "softap") == 0)
    {
        *aRendezvousFlags = chip::RendezvousInformationFlag::kSoftAP;
        return CHIP_NO_ERROR;
    }
    if (strcmp(str, "ble") == 0)
    {
        *aRendezvousFlags = chip::RendezvousInformationFlag::kBLE;
        return CHIP_NO_ERROR;
    }
    if (strcmp(str, "onnetwork") == 0)
    {
        *aRendezvousFlags = chip::RendezvousInformationFlag::kOnNetwork;
        return CHIP_NO_ERROR;
    }
    return CHIP_ERROR_INVALID_ARGUMENT;
}

static CHIP_ERROR OnboardingHandler(int argc, char ** argv)
{
    chip::RendezvousInformationFlags aRendezvousFlags;

    if (argc == 0)
    {
        return CHIP_ERROR_INVALID_ARGUMENT;
    }

    CHIP_ERROR err = RendezvousStringToFlag(argv[0], &aRendezvousFlags);
    if (err != CHIP_NO_ERROR)
    {
        return err;
    }

    if (argc == 1)
    {
        return PrintAllOnboardingCodes(aRendezvousFlags);
    }

    if (strcmp(argv[1], "qrcode") == 0)
    {
        return GetOnboardingQRCode(false, aRendezvousFlags);
    }
    if (strcmp(argv[1], "qrcodeurl") == 0)
    {
        return GetOnboardingQRCodeUrl(false, aRendezvousFlags);
    }
    if (strcmp(argv[1], "manualpairingcode") == 0)
    {
        return GetOnboardingManualPairingCode(false, aRendezvousFlags);
    }

    return CHIP_ERROR_INVALID_ARGUMENT;
}

void RegisterOnboardingCodesCommands()
{

    static const shell_command_t sDeviceComand = {
        &OnboardingHandler, "onboardingcodes",
        "Dump device onboarding codes. Usage: onboardingcodes none|softap|ble|onnetwork [qrcode|qrcodeurl|manualpairingcode]"
    };

    // Register the root `device` command with the top-level shell.
    Engine::Root().RegisterCommands(&sDeviceComand, 1);
}

} // namespace Shell
} // namespace chip


text:
#include "src/gpu/vk/GrVkRenderPass.h"

#include "src/gpu/GrProcessor.h"
#include "src/gpu/KeyBuilder.h"
#include "src/gpu/vk/GrVkFramebuffer.h"
#include "src/gpu/vk/GrVkGpu.h"
#include "src/gpu/vk/GrVkRenderTarget.h"
#include "src/gpu/vk/GrVkUtil.h"

typedef GrVkRenderPass::AttachmentsDescriptor::AttachmentDesc AttachmentDesc;

void setup_vk_attachment_description(VkAttachmentDescription* attachment,
                                     const AttachmentDesc& desc,
                                     VkImageLayout startLayout,
                                     VkImageLayout endLayout) {
    attachment->flags = 0;
    attachment->format = desc.fFormat;
    SkAssertResult(GrSampleCountToVkSampleCount(desc.fSamples, &attachment->samples));
    switch (startLayout) {
        case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
        case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
        case VK_IMAGE_LAYOUT_GENERAL:
            attachment->loadOp = desc.fLoadStoreOps.fLoadOp;
            attachment->storeOp = desc.fLoadStoreOps.fStoreOp;
            attachment->stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
            attachment->stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
            break;
        case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
            attachment->loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
            attachment->storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
            attachment->stencilLoadOp = desc.fLoadStoreOps.fLoadOp;
            attachment->stencilStoreOp = desc.fLoadStoreOps.fStoreOp;
            break;
        default:
            SK_ABORT("Unexpected attachment layout");
    }

    attachment->initialLayout = startLayout;
    attachment->finalLayout = endLayout == VK_IMAGE_LAYOUT_UNDEFINED ? startLayout : endLayout;
}

GrVkRenderPass* GrVkRenderPass::CreateSimple(GrVkGpu* gpu,
                                             AttachmentsDescriptor* attachmentsDescriptor,
                                             AttachmentFlags attachmentFlags,
                                             SelfDependencyFlags selfDepFlags,
                                             LoadFromResolve loadFromResolve) {
    static const GrVkRenderPass::LoadStoreOps kBasicLoadStoreOps(VK_ATTACHMENT_LOAD_OP_LOAD,
                                                                 VK_ATTACHMENT_STORE_OP_STORE);
    switch (loadFromResolve) {
        case LoadFromResolve::kNo:
            return Create(gpu, attachmentFlags, attachmentsDescriptor, kBasicLoadStoreOps,
                          kBasicLoadStoreOps, kBasicLoadStoreOps, selfDepFlags, loadFromResolve);
        case LoadFromResolve::kLoad: {
            static const GrVkRenderPass::LoadStoreOps kDiscardLoadStoreOps(
                    VK_ATTACHMENT_LOAD_OP_DONT_CARE, VK_ATTACHMENT_STORE_OP_DONT_CARE);
            return Create(gpu, attachmentFlags, attachmentsDescriptor, kDiscardLoadStoreOps,
                          kBasicLoadStoreOps, kBasicLoadStoreOps, selfDepFlags, loadFromResolve);
        }
    }
    SkUNREACHABLE;
}

GrVkRenderPass* GrVkRenderPass::Create(GrVkGpu* gpu,
                                       const GrVkRenderPass& compatibleRenderPass,
                                       const LoadStoreOps& colorOp,
                                       const LoadStoreOps& resolveOp,
                                       const LoadStoreOps& stencilOp) {
    AttachmentFlags attachmentFlags = compatibleRenderPass.fAttachmentFlags;
    AttachmentsDescriptor attachmentsDescriptor = compatibleRenderPass.fAttachmentsDescriptor;
    SelfDependencyFlags selfDepFlags = compatibleRenderPass.fSelfDepFlags;
    LoadFromResolve loadFromResolve = compatibleRenderPass.fLoadFromResolve;
    return Create(gpu, attachmentFlags, &attachmentsDescriptor, colorOp, resolveOp, stencilOp,
                  selfDepFlags, loadFromResolve);
}

GrVkRenderPass* GrVkRenderPass::Create(GrVkGpu* gpu,
                                       AttachmentFlags attachmentFlags,
                                       AttachmentsDescriptor* attachmentsDescriptor,
                                       const LoadStoreOps& colorOp,
                                       const LoadStoreOps& resolveOp,
                                       const LoadStoreOps& stencilOp,
                                       SelfDependencyFlags selfDepFlags,
                                       LoadFromResolve loadFromResolve) {
    SkASSERT(!SkToBool(selfDepFlags & SelfDependencyFlags::kForNonCoherentAdvBlend) ||
             gpu->caps()->advancedBlendEquationSupport());
    SkASSERT(!SkToBool(selfDepFlags & SelfDependencyFlags::kForInputAttachment) ||
             gpu->caps()->textureBarrierSupport());

    // If we have a resolve attachment, we will always do a resolve into it. Thus it doesn't make
    // sense not to store the resolve attachment at the end of the render pass.
    //
    // Currently today (when not using discardable msaa images) we load and store the the msaa image
    // and then use the copy resolve command to handle the resolving. If instead we moved to doing
    // the resolving at the end of the last render pass, we would probably want a separate flag
    // for having a resolve attachment versus actually doing the resolving. This would allow us to
    // use the same VkPiplines for render passes where we resolve and those we don't since each will
    // always have the resolve attachment. The actual resolving or not does not affect render pass
    // compatibility if there is only one sub pass, just the presence of the attachment or not.
    SkASSERT(!SkToBool(attachmentFlags & kResolve_AttachmentFlag) ||
             resolveOp.fStoreOp == VK_ATTACHMENT_STORE_OP_STORE);

    SkASSERT(loadFromResolve == LoadFromResolve::kNo ||
             (SkToBool(attachmentFlags & kColor_AttachmentFlag) &&
              SkToBool(attachmentFlags & kResolve_AttachmentFlag)));

#ifdef SK_DEBUG
    if (loadFromResolve == LoadFromResolve::kLoad) {
        // If we are loading the resolve image into the msaa color attachment then we should not be
        // loading or storing the msaa attachment. Additionally we need to make sure we are loading
        // the resolve so it can be copied into the msaa color attachment.
        SkASSERT(colorOp.fLoadOp == VK_ATTACHMENT_LOAD_OP_DONT_CARE);
        SkASSERT(colorOp.fStoreOp == VK_ATTACHMENT_STORE_OP_DONT_CARE);
        SkASSERT(resolveOp.fLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD);
    }
#endif

    uint32_t numAttachments = attachmentsDescriptor->fAttachmentCount;
    // Attachment descriptions to be set on the render pass
    SkTArray<VkAttachmentDescription> attachments(numAttachments);
    attachments.reset(numAttachments);
    memset(attachments.begin(), 0, numAttachments * sizeof(VkAttachmentDescription));

    // Refs to attachments on the render pass (as described by the VkAttachmentDescription above),
    // that are used by the subpass.
    VkAttachmentReference colorRef;
    VkAttachmentReference resolveRef;
    VkAttachmentReference resolveLoadInputRef;
    VkAttachmentReference stencilRef;
    uint32_t currentAttachment = 0;

    // Go through each of the attachment types (color, stencil) and set the necessary
    // on the various Vk structs.
    VkSubpassDescription subpassDescs[2];
    memset(subpassDescs, 0, 2*sizeof(VkSubpassDescription));
    const int mainSubpass = loadFromResolve == LoadFromResolve::kLoad ? 1 : 0;
    VkSubpassDescription& subpassDescMain = subpassDescs[mainSubpass];
    subpassDescMain.flags = 0;
    subpassDescMain.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
    subpassDescMain.inputAttachmentCount = 0;
    subpassDescMain.pInputAttachments = nullptr;
    subpassDescMain.pResolveAttachments = nullptr;

    uint32_t clearValueCount = 0;

    VkSubpassDependency dependencies[2];
    int currentDependency = 0;

    if (attachmentFlags & kColor_AttachmentFlag) {
        // set up color attachment
        bool needsGeneralLayout = SkToBool(selfDepFlags & SelfDependencyFlags::kForInputAttachment);
        VkImageLayout layout = needsGeneralLayout ? VK_IMAGE_LAYOUT_GENERAL
                                                  : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;

        attachmentsDescriptor->fColor.fLoadStoreOps = colorOp;

        setup_vk_attachment_description(&attachments[currentAttachment],
                                        attachmentsDescriptor->fColor,
                                        layout, layout);
        // setup subpass use of attachment
        colorRef.attachment = currentAttachment++;
        colorRef.layout = layout;
        subpassDescMain.colorAttachmentCount = 1;

        if (selfDepFlags != SelfDependencyFlags::kNone) {
            VkSubpassDependency& dependency = dependencies[currentDependency++];
            dependency.srcSubpass = mainSubpass;
            dependency.dstSubpass = mainSubpass;
            dependency.dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
            dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
            dependency.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
            dependency.dstStageMask = 0;
            dependency.dstAccessMask = 0;

            if (selfDepFlags & SelfDependencyFlags::kForNonCoherentAdvBlend) {
                // If we have coherent support we shouldn't be needing a self dependency
                SkASSERT(!gpu->caps()->advancedCoherentBlendEquationSupport());
                dependency.dstStageMask |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
                dependency.dstAccessMask |= VK_ACCESS_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT;
            }
            if (selfDepFlags & SelfDependencyFlags::kForInputAttachment) {
                SkASSERT(gpu->vkCaps().maxInputAttachmentDescriptors());

                subpassDescMain.inputAttachmentCount = 1;
                subpassDescMain.pInputAttachments = &colorRef;

                dependency.dstStageMask |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
                dependency.dstAccessMask |= VK_ACCESS_INPUT_ATTACHMENT_READ_BIT;
            }
        }

        if (VK_ATTACHMENT_LOAD_OP_CLEAR == colorOp.fLoadOp) {
            clearValueCount = colorRef.attachment + 1;
        }
    } else {
        // I don't think there should ever be a time where we don't have a color attachment
        SkASSERT(false);
        SkASSERT(selfDepFlags == SelfDependencyFlags::kNone);
        colorRef.attachment = VK_ATTACHMENT_UNUSED;
        colorRef.layout = VK_IMAGE_LAYOUT_UNDEFINED;
        subpassDescMain.colorAttachmentCount = 0;
    }

    subpassDescMain.pColorAttachments = &colorRef;

    if (attachmentFlags & kResolve_AttachmentFlag) {
        attachmentsDescriptor->fResolve.fLoadStoreOps = resolveOp;

        VkImageLayout layout = loadFromResolve == LoadFromResolve::kLoad
                                       ? VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL
                                       : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;

        setup_vk_attachment_description(&attachments[currentAttachment],
                                        attachmentsDescriptor->fResolve,
                                        layout,
                                        VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);

        // setup main subpass use of attachment
        resolveRef.attachment = currentAttachment++;
        resolveRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;

        subpassDescMain.pResolveAttachments = &resolveRef;

        // Setup the load subpass and set subpass dependendcies
        if (loadFromResolve == LoadFromResolve::kLoad) {
            resolveLoadInputRef.attachment = resolveRef.attachment;
            resolveLoadInputRef.layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;

            // The load subpass will always be the first
            VkSubpassDescription& subpassDescLoad = subpassDescs[0];
            subpassDescLoad.flags = 0;
            subpassDescLoad.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
            subpassDescLoad.inputAttachmentCount = 1;
            subpassDescLoad.pInputAttachments = &resolveLoadInputRef;
            subpassDescLoad.colorAttachmentCount = 1;
            subpassDescLoad.pColorAttachments = &colorRef;
            subpassDescLoad.pResolveAttachments = nullptr;
            subpassDescLoad.pDepthStencilAttachment = nullptr;
            subpassDescLoad.preserveAttachmentCount = 0;
            subpassDescLoad.pPreserveAttachments = nullptr;

            VkSubpassDependency& dependency = dependencies[currentDependency++];
            dependency.srcSubpass = 0;
            dependency.dstSubpass = mainSubpass;
            dependency.dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
            dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
            dependency.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
            dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
            dependency.dstAccessMask =
                    VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
        }
    }

    if (attachmentFlags & kStencil_AttachmentFlag) {
        // set up stencil attachment
        attachmentsDescriptor->fStencil.fLoadStoreOps = stencilOp;
        setup_vk_attachment_description(&attachments[currentAttachment],
                                        attachmentsDescriptor->fStencil,
                                        VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
                                        VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
        // setup subpass use of attachment
        stencilRef.attachment = currentAttachment++;
        stencilRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
        if (VK_ATTACHMENT_LOAD_OP_CLEAR == stencilOp.fLoadOp) {
            clearValueCount = std::max(clearValueCount, stencilRef.attachment + 1);
        }
    } else {
        stencilRef.attachment = VK_ATTACHMENT_UNUSED;
        stencilRef.layout = VK_IMAGE_LAYOUT_UNDEFINED;
    }
    subpassDescMain.pDepthStencilAttachment = &stencilRef;

    subpassDescMain.preserveAttachmentCount = 0;
    subpassDescMain.pPreserveAttachments = nullptr;

    SkASSERT(numAttachments == currentAttachment);

    uint32_t subpassCount = loadFromResolve == LoadFromResolve::kLoad ? 2 : 1;

    // Create the VkRenderPass compatible with the attachment descriptions above
    VkRenderPassCreateInfo createInfo;
    memset(&createInfo, 0, sizeof(VkRenderPassCreateInfo));
    createInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
    createInfo.pNext = nullptr;
    createInfo.flags = 0;
    createInfo.attachmentCount = numAttachments;
    createInfo.pAttachments = attachments.begin();
    createInfo.subpassCount = subpassCount;
    createInfo.pSubpasses = subpassDescs;
    createInfo.dependencyCount = currentDependency;
    createInfo.pDependencies = dependencies;

    VkResult result;
    VkRenderPass renderPass;
    GR_VK_CALL_RESULT(gpu, result, CreateRenderPass(gpu->device(),
                                                    &createInfo,
                                                    nullptr,
                                                    &renderPass));
    if (result != VK_SUCCESS) {
        return nullptr;
    }

    VkExtent2D granularity;
    // Get granularity for this render pass
    GR_VK_CALL(gpu->vkInterface(), GetRenderAreaGranularity(gpu->device(),
                                                            renderPass,
                                                            &granularity));

    return new GrVkRenderPass(gpu, renderPass, attachmentFlags, *attachmentsDescriptor,
                              selfDepFlags, loadFromResolve, granularity, clearValueCount);
}

GrVkRenderPass::GrVkRenderPass(const GrVkGpu* gpu, VkRenderPass renderPass, AttachmentFlags flags,
                               const AttachmentsDescriptor& descriptor,
                               SelfDependencyFlags selfDepFlags,
                               LoadFromResolve loadFromResolve,
                               const VkExtent2D& granularity, uint32_t clearValueCount)
        : INHERITED(gpu)
        , fRenderPass(renderPass)
        , fAttachmentFlags(flags)
        , fAttachmentsDescriptor(descriptor)
        , fSelfDepFlags(selfDepFlags)
        , fLoadFromResolve(loadFromResolve)
        , fGranularity(granularity)
        , fClearValueCount(clearValueCount) {
}

void GrVkRenderPass::freeGPUData() const {
    if (!(fAttachmentFlags & kExternal_AttachmentFlag)) {
        GR_VK_CALL(fGpu->vkInterface(), DestroyRenderPass(fGpu->device(), fRenderPass, nullptr));
    }
}

bool GrVkRenderPass::colorAttachmentIndex(uint32_t* index) const {
    *index = fColorAttachmentIndex;
    if ((fAttachmentFlags & kColor_AttachmentFlag) ||
        (fAttachmentFlags & kExternal_AttachmentFlag)) {
        return true;
    }
    return false;
}

// Works under the assumption that stencil attachment will always be after the color and resolve
// attachments.
bool GrVkRenderPass::stencilAttachmentIndex(uint32_t* index) const {
    *index = 0;
    if (fAttachmentFlags & kColor_AttachmentFlag) {
        ++(*index);
    }
    if (fAttachmentFlags & kStencil_AttachmentFlag) {
        return true;
    }
    return false;
}

bool GrVkRenderPass::isCompatible(const AttachmentsDescriptor& desc,
                                  const AttachmentFlags& flags,
                                  SelfDependencyFlags selfDepFlags,
                                  LoadFromResolve loadFromResolve) const {
    SkASSERT(!(fAttachmentFlags & kExternal_AttachmentFlag));
    if (flags != fAttachmentFlags) {
        return false;
    }

    if (fAttachmentFlags & kColor_AttachmentFlag) {
        if (!fAttachmentsDescriptor.fColor.isCompatible(desc.fColor)) {
            return false;
        }
    }
    if (fAttachmentFlags & kResolve_AttachmentFlag) {
        if (!fAttachmentsDescriptor.fResolve.isCompatible(desc.fResolve)) {
            return false;
        }
    }
    if (fAttachmentFlags & kStencil_AttachmentFlag) {
        if (!fAttachmentsDescriptor.fStencil.isCompatible(desc.fStencil)) {
            return false;
        }
    }

    if (fSelfDepFlags != selfDepFlags) {
        return false;
    }

    if (fLoadFromResolve != loadFromResolve) {
        return false;
    }

    return true;
}

bool GrVkRenderPass::isCompatible(GrVkRenderTarget* target,
                                  SelfDependencyFlags selfDepFlags,
                                  LoadFromResolve loadFromResolve) const {
    SkASSERT(!(fAttachmentFlags & kExternal_AttachmentFlag));

    AttachmentsDescriptor desc;
    AttachmentFlags flags;
    target->getAttachmentsDescriptor(&desc, &flags, this->hasResolveAttachment(),
                                     this->hasStencilAttachment());

    return this->isCompatible(desc, flags, selfDepFlags, loadFromResolve);
}

bool GrVkRenderPass::isCompatible(const GrVkRenderPass& renderPass) const {
    SkASSERT(!(fAttachmentFlags & kExternal_AttachmentFlag));
    return this->isCompatible(renderPass.fAttachmentsDescriptor, renderPass.fAttachmentFlags,
                              renderPass.fSelfDepFlags, renderPass.fLoadFromResolve);
}

bool GrVkRenderPass::isCompatibleExternalRP(VkRenderPass renderPass) const {
    SkASSERT(fAttachmentFlags & kExternal_AttachmentFlag);
    return fRenderPass == renderPass;
}

bool GrVkRenderPass::equalLoadStoreOps(const LoadStoreOps& colorOps,
                                       const LoadStoreOps& resolveOps,
                                       const LoadStoreOps& stencilOps) const {
    SkASSERT(!(fAttachmentFlags & kExternal_AttachmentFlag));
    if (fAttachmentFlags & kColor_AttachmentFlag) {
        if (fAttachmentsDescriptor.fColor.fLoadStoreOps != colorOps) {
            return false;
        }
    }
    if (fAttachmentFlags & kResolve_AttachmentFlag) {
        if (fAttachmentsDescriptor.fResolve.fLoadStoreOps != resolveOps) {
            return false;
        }
    }
    if (fAttachmentFlags & kStencil_AttachmentFlag) {
        if (fAttachmentsDescriptor.fStencil.fLoadStoreOps != stencilOps) {
            return false;
        }
    }
    return true;
}

void GrVkRenderPass::genKey(skgpu::KeyBuilder* b) const {
    GenKey(b, fAttachmentFlags, fAttachmentsDescriptor, fSelfDepFlags,
           fLoadFromResolve, (uint64_t)fRenderPass);
}

void GrVkRenderPass::GenKey(skgpu::KeyBuilder* b,
                            AttachmentFlags attachmentFlags,
                            const AttachmentsDescriptor& attachmentsDescriptor,
                            SelfDependencyFlags selfDepFlags,
                            LoadFromResolve loadFromResolve,
                            uint64_t externalRenderPass) {
    b->add32(attachmentFlags);
    if (attachmentFlags & kColor_AttachmentFlag) {
        b->add32(attachmentsDescriptor.fColor.fFormat);
        b->add32(attachmentsDescriptor.fColor.fSamples);
    }
    if (attachmentFlags & kResolve_AttachmentFlag) {
        b->add32(attachmentsDescriptor.fResolve.fFormat);
        b->add32(attachmentsDescriptor.fResolve.fSamples);
    }
    if (attachmentFlags & kStencil_AttachmentFlag) {
        b->add32(attachmentsDescriptor.fStencil.fFormat);
        b->add32(attachmentsDescriptor.fStencil.fSamples);
    }

    uint32_t extraFlags = (uint32_t)selfDepFlags;
    SkASSERT(extraFlags < (1 << 30));
    SkASSERT((uint32_t)loadFromResolve <= 2);
    extraFlags |= ((uint32_t)loadFromResolve << 30);

    b->add32(extraFlags);

    if (attachmentFlags & kExternal_AttachmentFlag) {
        SkASSERT(!(attachmentFlags & ~kExternal_AttachmentFlag));
        b->add32((uint32_t)(externalRenderPass & 0xFFFFFFFF));
        b->add32((uint32_t)(externalRenderPass>>32));
    }
}

redpajama_set_name: RedPajamaGithub


text:
require_relative 'spec_helper'
require_relative 'matchers'

describe 'ruby_app::default' do
  before do
    stub_resources
    stub_command('git --version >/dev/null').and_return('1.8.2')
  end

  describe 'ubuntu' do
    let(:chef_run) { ChefSpec::Runner.new(UBUNTU_OPTS).converge(described_recipe) }
    let(:default_rubies) { ['2.0.0-p353'] }
    let(:bundler_version) { '1.5.2' }

    it 'should install chruby' do
      expect(chef_run).to include_recipe('chruby::default')
      expect(chef_run).to include_recipe('ruby_build::default')
      expect(chef_run).to render_file('/etc/profile.d/chruby.sh')
    end

    it 'should install rubies' do
      default_rubies.each do |ruby_version|
        expect(chef_run).to install_ruby_build_ruby(ruby_version)
      end
    end

    it 'should install bundler' do
      default_rubies.each do |ruby_version|
        expect(chef_run).to install_gem_package("ruby-#{ruby_version}-bundler")
      end
    end

  end

end


text:
using CSharpGuidelinesAnalyzer.Rules.Maintainability;
using CSharpGuidelinesAnalyzer.Test.TestDataBuilders;
using Microsoft.CodeAnalysis.Diagnostics;
using Xunit;

// @formatter:keep_existing_linebreaks true

namespace CSharpGuidelinesAnalyzer.Test.Specs.Maintainability;

public sealed class DoNotAssignToParameterSpecs : CSharpGuidelinesAnalysisTestFixture
{
    protected override string DiagnosticId => DoNotAssignToParameterAnalyzer.DiagnosticId;

    [Fact]
    internal async Task When_method_is_abstract_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new TypeSourceCodeBuilder()
            .InGlobalScope(@"
                public abstract class C
                {
                    public abstract void M(string p);
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_method_is_partial_without_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new TypeSourceCodeBuilder()
            .InGlobalScope(@"
                partial class C
                {
                    partial void M(string p);
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_bool_parameter_is_read_from_in_method_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M(bool p)
                {
                    var x = p.ToString(null);
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_bool_parameter_is_written_to_in_method_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M(bool [|p|])
                {
                    p = true;
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_int_parameter_is_read_from_in_method_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M(int p)
                {
                    var x = p.GetHashCode();
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_int_parameter_is_written_to_in_method_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M(int [|p|])
                {
                    p += 5;
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_unsigned_short_parameter_is_read_from_in_method_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M(ushort p)
                {
                    var x = p.GetHashCode();
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_unsigned_short_parameter_is_written_to_in_method_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M(ushort [|p|])
                {
                    p += 5;
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_decimal_parameter_is_read_from_in_method_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M(decimal p)
                {
                    var x = p.ToString(null, null);
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_decimal_parameter_is_written_to_in_method_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M(decimal [|p|])
                {
                    p += 5m;
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_double_parameter_is_read_from_in_method_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M(double p)
                {
                    var x = p.ToString(null, null);
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_double_parameter_is_written_to_in_method_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M(double [|p|])
                {
                    p += 5.0;
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_DateTime_parameter_is_read_from_in_method_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M(DateTime p)
                {
                    var x = p.Year;
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_DateTime_parameter_is_written_to_in_method_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M(DateTime [|p|])
                {
                    p = DateTime.UtcNow;
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_nullable_parameter_is_read_from_in_method_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M(int? p)
                {
                    var x = p.Value.ToString(null, null);
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_nullable_parameter_is_written_to_in_method_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M(int? [|p|])
                {
                    p += 5;
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_enum_parameter_is_read_from_in_method_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public enum E
                {
                    A, B
                }

                void M(E p)
                {
                    var x = p.HasFlag(E.A);
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_enum_parameter_is_written_to_in_method_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public enum E
                {
                    A, B
                }

                void M(E [|p|])
                {
                    p = E.B;
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_struct_parameter_is_read_from_in_method_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public struct S
                {
                    public int Value;
                }

                void M(S p)
                {
                    var x = p.Value;
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_struct_parameter_is_invoked_on_in_method_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public struct S
                {
                    public void M()
                    {
                    }
                }

                class C
                {
                    public C(S s = default(S))
                    {
                        s.M();
                    }
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_struct_parameter_is_reassigned_in_method_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public struct S
                {
                }

                void M(S [|p|])
                {
                    p = new S();
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_struct_parameter_is_compound_reassigned_in_method_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public struct S
                {
                    public static S operator +(S p, int i)
                    {
                        throw null;
                    }
                }

                void M(S [|p|])
                {
                    p += 5;
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_struct_parameter_is_pre_incremented_in_method_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public struct S
                {
                    public static S operator ++(S p)
                    {
                        throw null;
                    }
                }

                void M(S [|p|])
                {
                    ++p;
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_struct_parameter_is_post_incremented_in_method_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public struct S
                {
                    public static S operator ++(S p)
                    {
                        throw null;
                    }
                }

                void M(S [|p|])
                {
                    p++;
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_struct_parameter_is_pre_decremented_in_method_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public struct S
                {
                    public static S operator --(S p)
                    {
                        throw null;
                    }
                }

                void M(S [|p|])
                {
                    --p;
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_struct_parameter_is_post_decremented_in_method_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public struct S
                {
                    public static S operator --(S p)
                    {
                        throw null;
                    }
                }

                void M(S [|p|])
                {
                    p--;
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_struct_parameter_is_overwritten_by_deconstruction_in_method_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new TypeSourceCodeBuilder()
            .InGlobalScope(@"
                class C
                {
                    public void Deconstruct(out int i, out S s) => throw null;

                    public struct S
                    {
                    }

                    void M(S [|s|], C c)
                    {
                        int i;
                        (i, s) = c;
                    }
                }

            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 's' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_struct_parameter_is_passed_by_ref_in_method_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public struct S
                {
                }

                void M(S [|p|])
                {
                    N(ref p);
                }

                void N(ref S s) => throw null;
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_struct_parameter_is_passed_by_out_in_method_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public struct S
                {
                }

                void M(S [|p|])
                {
                    N(out p);
                }

                void N(out S s) => throw null;
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_struct_parameter_is_passed_by_in_in_method_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public struct S
                {
                }

                void M(S p)
                {
                    N(in p);
                }

                void N(in S s) => throw null;
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_ref_struct_parameter_is_reassigned_in_method_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public struct S
                {
                }

                void M(ref S p)
                {
                    p = new S();
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_out_struct_parameter_is_reassigned_in_method_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public struct S
                {
                }

                void M(out S p)
                {
                    p = new S();
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_in_struct_parameter_is_invoked_in_method_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                struct S
                {
                    public void M() => throw null;
                }

                void M(in S p)
                {
                    p.M();
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_string_parameter_is_read_from_in_method_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M(string p)
                {
                    string x = p;
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_string_parameter_is_written_to_in_method_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M(string [|p|])
                {
                    p += ""X"";
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_ref_string_parameter_is_written_to_in_method_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M(ref string p)
                {
                    p += ""X"";
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_out_string_parameter_is_written_to_in_method_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M(out string p)
                {
                    p = ""X"";
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_in_string_parameter_is_invoked_in_method_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M(in string p)
                {
                    p.ToString();
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_string_parameter_is_read_from_in_method_expression_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M(string p) => N(p);

                void N(string s)
                {
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_string_parameter_is_written_to_in_method_expression_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M(string [|p|]) => N(ref p);

                void N(ref string s)
                {
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_string_parameter_is_read_from_in_lambda_expression_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M()
                {
                    N(p =>
                    {
                        Console.WriteLine(p);
                        return true;
                    });
                }

                void N(Func<string, bool> f)
                {
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_string_parameter_is_written_to_in_lambda_expression_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M()
                {
                    N([|p|] =>
                    {
                        p = ""A"";
                        return true;
                    });
                }

                void N(Func<string, bool> f)
                {
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_string_parameter_is_read_from_in_anonymous_method_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M()
                {
                    N(delegate(string p)
                    {
                        Console.WriteLine(p);
                        return true;
                    });
                }

                void N(Func<string, bool> f)
                {
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_string_parameter_is_written_to_in_anonymous_method_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M()
                {
                    N(delegate(string [|p|])
                    {
                        p = ""A"";
                        return true;
                    });
                }

                void N(Func<string, bool> f)
                {
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_string_parameter_is_read_from_in_constructor_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new TypeSourceCodeBuilder()
            .InGlobalScope(@"
                class C
                {
                    public C(string p)
                    {
                        string s = p;
                    }
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_string_parameter_is_written_to_in_constructor_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new TypeSourceCodeBuilder()
            .InGlobalScope(@"
                class C
                {
                    public C(string [|p|])
                    {
                        p += ""X"";
                    }
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_string_parameter_is_read_from_in_constructor_expression_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new TypeSourceCodeBuilder()
            .InGlobalScope(@"
                class C
                {
                    public C(string p) => N(p);

                    void N(string s)
                    {
                    }
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_string_parameter_is_written_to_in_constructor_expression_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new TypeSourceCodeBuilder()
            .InGlobalScope(@"
                class C
                {
                    public C(string [|p|]) => N(ref p);

                    void N(ref string s)
                    {
                    }
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_string_parameter_is_read_from_in_conversion_operator_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new TypeSourceCodeBuilder()
            .InGlobalScope(@"
                class C
                {
                    int Value;

                    public static implicit operator int(C p)
                    {
                        return p.Value;
                    }
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_string_parameter_is_written_to_in_conversion_operator_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new TypeSourceCodeBuilder()
            .InGlobalScope(@"
                class C
                {
                    int Value;

                    public static implicit operator int(C [|p|])
                    {
                        p = new C();
                        throw null;
                    }
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_string_parameter_is_read_from_in_conversion_operator_expression_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new TypeSourceCodeBuilder()
            .InGlobalScope(@"
                class C
                {
                    int Value;

                    public static implicit operator int(C p) => p.Value;
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_string_parameter_is_written_to_in_conversion_operator_expression_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new TypeSourceCodeBuilder()
            .InGlobalScope(@"
                class C
                {
                    int Value;

                    public static implicit operator int(C [|p|]) => M(ref p);

                    static int M(ref C p) => throw null;
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_value_parameter_is_read_from_in_property_setter_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public int Value
                {
                    set
                    {
                        var str = value.ToString();
                    }
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_value_parameter_is_written_to_in_property_setter_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public int Value
                {
                    [|set|]
                    {
                        value += 3;
                    }
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'value' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_value_parameter_is_read_from_in_property_setter_expression_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public int Value
                {
                    set => value.ToString();
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_value_parameter_is_written_to_in_property_setter_expression_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public int Value
                {
                    [|set|] => Math.Min(value += 4, 1);
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'value' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_string_parameter_is_read_from_in_indexer_getter_setter_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public int this[string key]
                {
                    get
                    {
                        return int.Parse(key);
                    }
                    set
                    {
                        string copy = key;
                    }
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_string_parameter_is_written_to_in_indexer_getter_setter_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public int this[string [|key|]]
                {
                    get
                    {
                        key = string.Empty;
                        throw null;
                    }
                    set
                    {
                        key += new string('x', 10);
                    }
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'key' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_string_parameters_are_written_to_in_indexer_getter_setter_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public int this[string [|key1|], string [|key2|]]
                {
                    get
                    {
                        key1 = string.Empty;
                        throw null;
                    }
                    set
                    {
                        key2 += new string('x', 10);
                    }
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'key1' is overwritten in its method body",
            "The value of parameter 'key2' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_string_parameter_is_read_from_in_indexer_getter_setter_expression_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public int this[string key]
                {
                    get => int.Parse(key);
                    set => key.GetHashCode();
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_string_parameter_is_written_to_in_indexer_getter_setter_expression_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public int this[string [|key|]]
                {
                    get => int.Parse(key = string.Empty);
                    set => int.Parse(key = string.Empty);
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'key' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_string_parameter_is_read_from_in_event_adder_remover_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public event EventHandler Started
                {
                    add
                    {
                        var x = value;
                    }
                    remove
                    {
                        var x = value;
                    }
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_string_parameter_is_written_to_in_event_adder_remover_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public event EventHandler Started
                {
                    [|add|]
                    {
                        value = null;
                        throw null;
                    }
                    [|remove|]
                    {
                        value = null;
                        throw null;
                    }
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'value' is overwritten in its method body",
            "The value of parameter 'value' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_string_parameter_is_read_from_in_event_adder_remover_expression_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public event EventHandler Started
                {
                    add => value.ToString();
                    remove => value.ToString();
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_string_parameter_is_written_to_in_event_adder_remover_expression_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                public event EventHandler Started
                {
                    [|add|] => value = null;
                    [|remove|] => value = null;
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'value' is overwritten in its method body",
            "The value of parameter 'value' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_string_parameter_is_read_from_in_local_function_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M()
                {
                    void L(string p)
                    {
                        string x = p;
                    }
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_string_parameter_is_written_to_in_local_function_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M()
                {
                    void L(string [|p|])
                    {
                        p += ""X"";
                    }
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    [Fact]
    internal async Task When_string_parameter_is_read_from_in_local_function_expression_body_it_must_be_skipped()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M()
                {
                    void L(string p) => N(p);
                }

                void N(string s)
                {
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source);
    }

    [Fact]
    internal async Task When_string_parameter_is_written_to_in_local_function_expression_body_it_must_be_reported()
    {
        // Arrange
        ParsedSourceCode source = new MemberSourceCodeBuilder()
            .InDefaultClass(@"
                void M()
                {
                    void L(string [|p|]) => N(ref p);
                }

                void N(ref string s)
                {
                }
            ")
            .Build();

        // Act and assert
        await VerifyGuidelineDiagnosticAsync(source,
            "The value of parameter 'p' is overwritten in its method body");
    }

    protected override DiagnosticAnalyzer CreateAnalyzer()
    {
        return new DoNotAssignToParameterAnalyzer();
    }
}


text:
'''
Module containing some predefined form converters - objects designed to
convert and validate form field's data.
'''

import re
from ..utils import weakproxy, replace_nontext
from datetime import datetime
from collections import OrderedDict
from ..utils.dt import strftime
from ..utils.deprecation import deprecated
try:
    from ..utils.html import Cleaner
    from lxml import html
    from lxml.etree import XMLSyntaxError
except ImportError:
    # lxml is required for Html conv, therefore you can use forms without this
    # functionality
    Cleaner = None

from ..utils import N_, M_, cached_property

_all2 = locals().keys()

class ValidationError(Exception):
    '''
    Error raised from inside of `Converter.to_python` or validator function.

    :param unicode message: error message for current validating
        field, for most cases.
    :param dict by_field: contains {field-name: error message} pairs.
    :param dict format_args: used to format error message.
    '''

    default_message = N_('Something is wrong')

    def __init__(self, message=None, by_field=None, format_args=None):
        if not (message or by_field):
            message = self.default_message
        self.message = message
        self.by_field = by_field or {}
        self.format_args = format_args or {}

    def translate(self, env, message):
        format_args = self.format_args
        if isinstance(message, M_):
            trans = env.ngettext(unicode(message.single),
                                 unicode(message.plural),
                                 message.count)
            format_args = dict(format_args,
                               **message.format_args)
        else:
            trans = env.gettext(message)
        return trans % format_args

    def fill_errors(self, field):
        form = field.form
        if self.message is not None:
            form.errors[field.input_name] = self.translate(form.env, self.message)
        for name, message in self.by_field.items():
            if name.startswith('.'):
                nm, f = name.lstrip('.'), field
                for i in xrange(len(name) - len(nm) - 1):
                    f = f.parent
                rel_field = f.get_field(nm)
                name = rel_field.input_name
            else:
                rel_field = form.get_field(name)
            form.errors[name] = self.translate(form.env, message)

    def __repr__(self):
        return "{}({!r}, {!r})".format(self.__class__, self.message,
                                       self.by_field)

class Converter(object):
    '''
    :meth:`accept` method takes value from field
    and converts it to python type.

    Subclasses must redefine :meth:`to_python` method to make their
    own convertation and validation.

    :meth:`from_python` method takes value as python
    object and converts it to string or something
    else widget can display.

    Accepts a list of validators as **\*args**.
    '''

    # obsolete parameters from previous versions
    _obsolete = frozenset(['max_length', 'min_length', 'null', 'min', 'max',
                           'multiple', 'initial'])
    #: Flag of whether perform require check after :meth:`to_python` method or not.
    #: The resulting value is checked to be non-empty (`[]`, `None`).
    required = False
    multiple = False

    #: An ordered list of validator functions. Are passed as position args
    #: to the converter::
    #:
    #:     Int(validator1, validator2)
    #:
    #: When a converter is copied, new validators are added to existing ones.
    validators = ()

    #: Values are not accepted by Required validator
    error_required = N_('required field')

    def __init__(self, *args, **kwargs):
        if self._obsolete & set(kwargs):
            raise TypeError(
                    'Obsolete parameters are used: {}'.format(
                                list(self._obsolete & set(kwargs))))
        self.field = weakproxy(kwargs.get('field'))
        self._init_kwargs = kwargs
        self.__dict__.update(kwargs)
        self.validators = tuple(self.validators) + args

    @property
    def env(self):
        '''A shortcut for `form.env`'''
        return self.field.env

    def _is_empty(self, value):
        return value in ('', [], {}, None)

    def accept(self, value, silent=False):
        '''
        Accepts a value from the form, calls :meth:`to_python` method,
        checks `required` condition, applies filters and validators,
        catches ValidationError.

        :param value: a value to be accepted
        :param silent=False: write errors to `form.errors` or not
        '''
        try:
            value = self.to_python(value)
            for v in self.validators:
                value = v(self, value)

            if self.required and self._is_empty(value):
                raise ValidationError(self.error_required)
        except ValidationError, e:
            if not silent:
                e.fill_errors(self.field)
            #NOTE: by default value for field is in python_data,
            #      but this is not true for FieldList where data
            #      is dynamic, so we set value to None for absent value.
            value = self._existing_value
        return value

    def to_python(self, value):
        """
        Converts value and validates it.
        Custom converters should override this
        """
        if value == '':
            return None # XXX is this right?
        return value

    def from_python(self, value):
        """
        Serializes value.
        Custom converters should override this
        """
        if value is None:
            value = ''
        return value

    def __call__(self, *args, **kwargs):
        '''
        Creates current object's copy with extra constructor arguments
        (including validators) passed.
        '''
        kwargs = dict(self._init_kwargs, **kwargs)
        kwargs.setdefault('field', self.field)
        validators = tuple(self.validators) + args
        return self.__class__(*validators, **kwargs)

    def assert_(self, expression, msg):
        'Shortcut for assertions of certain type'
        if not expression:
            raise ValidationError(msg)

    @property
    def _existing_value(self):
        if self.field is not None:
            return self.field.parent.python_data.get(self.field.name)
        return [] if self.multiple else None

    def __repr__(self):
        args = ', '.join([k+'='+repr(v) for
                          k, v in self._init_kwargs.items()
                          if k!='parent'])
        return '{}({})'.format(self.__class__.__name__, args)

class validator(object):
    'Function decorator'
    def __init__(self, message):
        self.message = message
    def __call__(self, func):
        def wrapper(conv, value):
            if not func(conv, value):
                raise ValidationError(self.message)
            return value
        return wrapper

# Some useful validators

def length(min_length, max_length):
    'String length constraint'

    format_args = dict(min=min_length, max=max_length)

    if min_length == max_length:
        message = M_(u'length of value must be exactly %(max)d symbol',
                     u'length of value must be exactly %(max)d symbols',
                     count_field="max",
                     format_args=format_args)
    else:
        message = N_('length should be between %(min)d and %(max)d symbols')

    def check_length(conv, value):
        if value and not (min_length <= len(value) <= max_length):
            raise ValidationError(message, format_args=format_args)
        return value

    return check_length

@deprecated('Use length(min, max) instead.')
def limit(min_length, max_length):
    return length(min_length, max_length) # pragma: no cover

def between(min_value, max_value):
    'Numerical values limit'
    message = N_('value should be between %(min)d and %(max)d') % \
                    dict(min=min_value, max=max_value)

    @validator(message)
    def wrapper(conv, value):
        if value is None:
            # it meens that this value is not required
            return True
        if value < min_value:
            return False
        if value > max_value:
            return False
        return True
    return wrapper

@deprecated('Use between(min, max) instead.')
def num_limit(min_value, max_value):
    return between(min_value, max_value) # pragma: no cover

class CharBased(Converter):

    nontext_replacement = u'\uFFFD' # Set None to disable and empty string to
                                    # remove.
                                    # Default value is u"�"
    #: Whether strip value before convertation or not
    strip = True

    def clean_value(self, value):
        '''
        Additional clean action to preprocess value before :meth:`to_python`
        method.

        Subclasses may define own clean_value method to allow additional clean
        actions like html cleanup, etc.
        '''
        # We have to clean before checking min/max length. It's done in
        # separate method to allow additional clean action in subclasses.
        if self.nontext_replacement is not None:
            value = replace_nontext(value, self.nontext_replacement)
        if self.strip:
            value = value.strip()
        return value

class Char(CharBased):

    '''Converts and validates strings'''

    #: Regexp to match input string
    regex = None
    #: Error message for the case self.regex does not match
    error_regex = N_('field should match %(regex)s')
    #: Whether strip value before convertation or not
    strip = True

    def to_python(self, value):
        # converting
        value = self.clean_value(value)
        if value and self.regex:
            regex = self.regex
            if isinstance(self.regex, basestring):
                regex = re.compile(self.regex, re.U)
            if not regex.match(value):
                error = self.error_regex % {'regex': self.regex}
                raise ValidationError(error)
        return value

    def from_python(self, value):
        if value is None:
            return ''
        return unicode(value)

class Int(Converter):
    """
    Converts digital sequences to `int`
    """

    #: Error message for the case value can not be converted to int
    error_notvalid = N_('it is not valid integer')

    def to_python(self, value):
        if value == '':
            return None
        try:
            value = int(value)
        except ValueError:
            raise ValidationError(self.error_notvalid)
        return value

    def from_python(self, value):
        if value is None:
            return ''
        return unicode(value)

class Bool(Converter):
    """
    Converts to `True`/`False`
    """
    required = False

    def to_python(self, value):
        return bool(value)

    def from_python(self, value):
        if value:
            return 'checked'
        return ''

class EnumChoice(Converter):
    '''
    In addition to Converter interface it must provide
    :meth:`options` and :meth:`get_label` methods.
    '''

    #: converter for value, before it is tested to be in a set of acceptable
    #: values
    conv = Char()

    #: acceptable choices list::
    #:
    #:     EnumChoice(choices=[(python_value, label), ...])
    choices = ()
    error_required = N_('you must select a value')

    def from_python(self, value):
        conv = self.conv
        return conv.from_python(value)

    def to_python(self, value):
        value = self.conv.accept(value, silent=True)
        if value not in dict(self.choices):
            return None
        return value

    def options(self):
        '''
        Yields `(raw_value, label)` pairs for all acceptable choices.
        '''
        conv = self.conv
        for python_value, label in self.choices:
            yield conv.from_python(python_value), label

    def get_label(self, value):
        '''
        Returns a label for given value
        '''
        # XXX comment needed
        value = self.conv.accept(value, silent=True)
        return dict(self.choices).get(value)

class BaseDatetime(CharBased):
    '''
    A base class for `Datetime`, `Date` and `Time` converters.
    '''

    #: format used to convert from string by `strptime`
    #: and to convert to string by `strftime`.
    format = None
    #: format used in error message. By default, generated automatically
    #: based `format` and `replacements` attributes
    readable_format = None
    replacements = (('%H', 'HH'), ('%M', 'MM'), ('%d', 'DD'),
                    ('%m', 'MM'), ('%Y', 'YYYY'))
    #: error message for wrong format.
    error_wrong_format = N_('Wrong format (%(readable_format)s)')
    nontext_replacement = ''

    def __init__(self, *args, **kwargs):
        if not 'readable_format' in kwargs or 'format' in kwargs:
            replacements = self.replacements # XXX make language-dependent
            fmt = kwargs.get('format', self.format)
            for repl in replacements:
                fmt = fmt.replace(*repl)
            kwargs['readable_format'] = fmt
        Converter.__init__(self, *args, **kwargs)

    def from_python(self, value):
        if value is None:
            return ''
        # carefull to years before 1900
        return strftime(value, self.format)

    def to_python(self, value):
        value = self.clean_value(value)
        if not value:
            return None
        try:
            return self.convert_datetime(value)
        except ValueError:
            format_args = dict(readable_format=self.readable_format)
            raise ValidationError(self.error_wrong_format,
                                  format_args=format_args)

class Datetime(BaseDatetime):
    '''
    Subclass of `BaseDatetime` for `datetime.datetime`
    '''

    format = '%d.%m.%Y, %H:%M'

    def convert_datetime(self, value):
        return datetime.strptime(value, self.format)

class Date(BaseDatetime):
    '''
    Subclass of `BaseDatetime` for `datetime.date`
    '''

    format = '%d.%m.%Y'

    def convert_datetime(self, value):
        return datetime.strptime(value, self.format).date()

class Time(BaseDatetime):
    '''
    Subclass of `BaseDatetime` for `datetime.time`
    '''

    format = '%H:%M'

    def from_python(self, value):
        if value is None:
            return ''
        # we don't care about year in time converter, so use native strftime
        return value.strftime(self.format)

    def convert_datetime(self, value):
        return datetime.strptime(value, self.format).time()

class DisplayOnly(Converter):
    """
    Does nothing, always returns a value of field before validation
    """

    def from_python(self, value):
        return value

    def to_python(self, value):
        return self._existing_value

class SplitDateTime(Converter):
    '''
    Converter for FieldSet, allowing get a single `datetime.datetime`
    object from two fields: date and time.
    '''

    def from_python(self, value):
        if value is None:
            return {'date': None, 'time': None}
        else:
            return {'date': value.date(), 'time': value.time()}

    def to_python(self, value):
        if value['date'] is None or value['time'] is None:
            return None
        res = datetime.combine(value['date'], value['time'])
        return res

class Html(Char):
    '''
    Converter for flexible cleanup of HTML document fragments.
    A subclass of :class:`Char<iktomi.forms.convs.Char>`.

    Uses :class:`utils.html.Sanitizer<iktomi.utils.html.Sanitizer>`
    instance to sanitize input HTML.

    Construtor collects from given kwargs all of
    :class:`Sanitizer<iktomi.utils.html.Sanitizer>`
    options and passes them into Sanitizer's constructor.

    For list properties there is :meth:`add_*` interface::

        Html(add_allowed_elements=['span'], add_dom_callbacks=[myfunc])
    '''

    #: A list of allowed HTML elements
    allowed_elements = frozenset(('a', 'p', 'br', 'li', 'ul', 'ol', 'hr', 'u',
                                  'i', 'b', 'blockquote', 'sub', 'sup'))
    #: A list of allowed HTML attributes
    allowed_attributes = frozenset(('href', 'src', 'alt', 'title', 'class',
                                    'rel'))
    #: A list of tags to be dropped if they are empty
    drop_empty_tags = frozenset(('p', 'a', 'u', 'i', 'b', 'sub', 'sup'))
    allowed_protocols = frozenset(['ftp', 'http', 'https', 'mailto',
                                   'tel', 'webcal', 'callto'])
    #: A dict containing an element name as a key and class test as value.
    #: Test can be a set of strings (for simple strict match) or callable
    #: accepting class name and returning True/False.
    #: Set to `None` to allow all classes.
    allowed_classes = {}
    #: A list of callbacks applied to DOM tree before it is
    #: rendered back to HTML.
    dom_callbacks = []
    wrap_inline_tags = None
    split_paragraphs_by_br = True
    # Tags to wrap in paragraphs on top
    tags_to_wrap = ['b', 'big', 'i', 'small', 'tt',
                    'abbr', 'acronym', 'cite', 'code',
                    'dfn', 'em', 'kbd', 'strong', 'samp',
                    'var', 'a', 'bdo', 'br', 'map', 'object',
                    'q', 'span', 'sub', 'sup']
    #: Function returning object marked safe for template engine.
    #: For example, `jinja2.Markup` object.
    Markup = lambda s, x: x
    #: A Cleaner class. Be default, 'iktomi.utils.html.Cleaner' is used.
    #: It is a `lxml.html.clean.Cleaner` subclass
    Cleaner = Cleaner
    class Nothing: pass

    PROPERTIES = ['allowed_elements', 'allowed_attributes', 'allowed_protocols',
                  'allowed_classes', 'dom_callbacks', 'drop_empty_tags',
                  'wrap_inline_tags', 'split_paragraphs_by_br']

    LIST_PROPERTIES = ['allowed_elements', 'allowed_attributes',
                       'allowed_protocols', 'dom_callbacks',
                       'drop_empty_tags', 'tags_to_wrap']

    @classmethod
    def _load_arg(cls, opt):
        assert hasattr(cls, opt)
        # XXX very complicated merges for rare cases
        #     not sure if they are necessary
        if opt in cls.__dict__:
            result = getattr(cls, opt)
        else:
            for base in cls.__bases__:
                if hasattr(base, '_load_arg'):
                    result = base._load_arg(opt)
                    if not result is cls.Nothing:
                        break
            else:
                result = cls.Nothing

        if 'add_' + opt in cls.__dict__:
            add = getattr(cls, 'add_' + opt)
            if result is cls.Nothing:
                result = add
            else:
                result = set(result)
                result.update(add)
        return result

    def __init__(self, *args, **kwargs):
        assert self.Cleaner is not None, \
                'Install lxml or implement your own html cleaner'
        for opt in self.PROPERTIES:
            if not opt in kwargs:
               result = self._load_arg(opt)
               if not result is self.Nothing:
                   kwargs[opt] = result

        for opt in self.LIST_PROPERTIES:
            add_key = 'add_' + opt
            if add_key in kwargs:
                opt_value = kwargs.get(opt, [])
                # XXX sometimes set must be ordered
                kwargs[opt] = set(opt_value)
                kwargs[opt].update(kwargs.pop(add_key))
        Char.__init__(self, *args, **kwargs)

    def clean_value(self, value):
        value = Char.clean_value(self, value)
        try:
            doc = html.fragment_fromstring(value, create_parent=True)
        except XMLSyntaxError:
            raise ValidationError(N_(u'Error parsing HTML'))
        self.cleaner(doc)
        clean = html.tostring(doc, encoding='utf-8').decode('utf-8')
        clean = clean.split('>', 1)[1].rsplit('<', 1)[0]
        return self.Markup(clean)

    @cached_property
    def cleaner(self):
        return self.Cleaner(allow_tags=self.allowed_elements,
                            safe_attrs=self.allowed_attributes,
                            allow_classes=self.allowed_classes,
                            allowed_protocols=self.allowed_protocols,
                            drop_empty_tags=self.drop_empty_tags,
                            dom_callbacks=self.dom_callbacks,
                            wrap_inline_tags=self.wrap_inline_tags,
                            split_paragraphs_by_br=self.split_paragraphs_by_br,
                            tags_to_wrap=self.tags_to_wrap,
                            )

class List(Converter):
    '''
    Converter for FieldList'''

    _obsolete = Converter._obsolete | set(['filter'])

    def from_python(self, value):
        if value is None:
            value = []
        result = OrderedDict()
        for index, item in enumerate(value):
            result[str(index+1)] = item
        return result

    def to_python(self, value):
        return value.values()

class ListOf(Converter):
    '''
    Converter for scalar Fields, applies nested converter to each value
    of the field (i.e. for each value from MultiDict) and returns a list of
    resulting values.

    Usage::

        ListOf(Converter(), *validators, **kwargs)
    '''

    multiple = True

    def __init__(self, *args, **kwargs):
        if args and (isinstance(args[0], Converter) or \
                     (isinstance(args[0], type) and \
                      issubclass(args[0], Converter))):
            conv = args[0]
            args = args[1:]
        else:
            conv = kwargs['conv']
        if 'field' in kwargs:
            conv = conv(field=kwargs['field'])
        kwargs['conv'] = conv
        Converter.__init__(self, *args, **kwargs)

    def to_python(self, value):
        result = []
        for val in value or []:
            val = self.conv.accept(val)
            if val is not None:
                # XXX is it right to ignore None?
                result.append(val)
        return result

    def from_python(self, value):
        return [self.conv.from_python(item) for item in value or []]

class FieldBlockConv(Converter):

    @property
    def _existing_value(self):
        if self.field is not None:
            return self.field.python_data
        return {} # XXX

class SimpleFile(Converter):
    '''
    Simpliest converter for files. Returns a file from webob Request.POST
    "as is".
    '''

    def _is_empty(self, file):
        return file == u'' or file is None #XXX WEBOB ONLY !!!

    def to_python(self, file):
        if not self._is_empty(file):
            return file

    def from_python(self, value):
        return None

# Expose all variables defined after imports
__all__ = [x for x
           in set(locals().keys()) - set(_all2)
           if not x.startswith('_')]
del _all2


text:
package godm

import (
	"io/ioutil"
	"testing"

	"os"
	"path"

	"github.com/hectorj/godm/git"
	"github.com/stretchr/testify/assert"
)

func newProjectNoVCLProject(t *testing.T) (project *ProjectNoVCL) {
	tmpDirPath, err := ioutil.TempDir("", "godm-project_no_vcl_test")
	assert.Nil(t, err, "Failed creating a temp dir for ProjectNoVCL tests.")

	project = NewProjectNoVCL(tmpDirPath)
	assert.Equal(t, tmpDirPath, project.GetBaseDir(), "Fresh ProjectNoVCL from temp dir has a wrong base dir.")

	return
}

var testCases = map[string]struct {
	prepare             func(t *testing.T, project *ProjectNoVCL, failMessageAndArgs ...interface{})
	expectedImportPaths map[string]LocalProject
}{
	"none": {
		prepare:             func(_ *testing.T, _ *ProjectNoVCL, _ ...interface{}) {},
		expectedImportPaths: nil,
	},
	"1 NoVCL vendor": {
		prepare: func(t *testing.T, project *ProjectNoVCL, failMessageAndArgs ...interface{}) {
			targetDirPath := path.Join(project.GetBaseDir(), "vendor", "test1") + "/"
			err := os.MkdirAll(targetDirPath, os.ModeDir|os.ModePerm)
			assert.Nil(t, err, failMessageAndArgs...)

			targetFilePath := path.Join(targetDirPath, "whatever.go")
			file, err := os.Create(targetFilePath)
			assert.Nil(t, err, failMessageAndArgs...)

			_, err = file.WriteString("package test1\n")
			assert.Nil(t, err, failMessageAndArgs...)

			git.Service = git.NewGitStub()
		},
		expectedImportPaths: map[string]LocalProject{
			"test1": &ProjectNoVCL{},
		},
	},
	"1 Git vendor": {
		prepare: func(t *testing.T, project *ProjectNoVCL, failMessageAndArgs ...interface{}) {
			targetDirPath := path.Join(project.GetBaseDir(), "vendor", "test1") + "/"
			err := os.MkdirAll(targetDirPath, os.ModeDir|os.ModePerm)
			assert.Nil(t, err, failMessageAndArgs...)

			targetFilePath := path.Join(targetDirPath, "whatever.go")
			file, err := os.Create(targetFilePath)
			assert.Nil(t, err, failMessageAndArgs...)

			_, err = file.WriteString("package test1\n")
			assert.Nil(t, err, failMessageAndArgs...)

			gitStub := git.NewGitStub()

			gitStub.Repos[targetDirPath] = git.NewGitRepoStub()

			git.Service = gitStub
		},
		expectedImportPaths: map[string]LocalProject{
			"test1": &localGitProject{},
		},
	},
}

func TestProjectNoVCL_GetVendors(t *testing.T) {
testCasesLoop:
	for caseName, testCase := range testCases {
		failMessageAndArgs := []interface{}{"Test case %q failed.", caseName}
		project := newProjectNoVCLProject(t)
		defer os.RemoveAll(project.GetBaseDir())

		testCase.prepare(t, project, failMessageAndArgs...)

		vendors, err := project.GetVendors()
		if !assert.Nil(t, err, failMessageAndArgs...) {
			continue testCasesLoop
		}

		if !assert.Len(t, vendors, len(testCase.expectedImportPaths), failMessageAndArgs...) {
			continue testCasesLoop
		}

	vendorsLoop:
		for importPath, projectType := range testCase.expectedImportPaths {
			vendor, exists := vendors[importPath]

			specificFailMessageAndArgs := make([]interface{}, len(failMessageAndArgs)+1)
			copy(specificFailMessageAndArgs, failMessageAndArgs)
			specificFailMessageAndArgs[0] = specificFailMessageAndArgs[0].(string) + " (vendor %q)"
			specificFailMessageAndArgs[len(failMessageAndArgs)] = importPath

			if !assert.True(t, exists, specificFailMessageAndArgs...) {
				continue vendorsLoop
			}

			if !assert.NotNil(t, vendor, specificFailMessageAndArgs...) {
				continue vendorsLoop
			}

			if !assert.IsType(t, projectType, vendor.GetProject(), specificFailMessageAndArgs...) {
				continue vendorsLoop
			}
		}
	}

}

func TestProjectNoVCL_RemoveVendor(t *testing.T) {
	//testCasesLoop:
	for caseName, testCase := range testCases {
		failMessageAndArgs := []interface{}{"Test case %q failed.", caseName}
		project := newProjectNoVCLProject(t)
		defer os.RemoveAll(project.GetBaseDir())

		testCase.prepare(t, project, failMessageAndArgs...)

	vendorsLoop:
		for importPath, _ := range testCase.expectedImportPaths {
			specificFailMessageAndArgs := make([]interface{}, len(failMessageAndArgs)+1)
			copy(specificFailMessageAndArgs, failMessageAndArgs)
			specificFailMessageAndArgs[0] = specificFailMessageAndArgs[0].(string) + " (vendor %q)"
			specificFailMessageAndArgs[len(failMessageAndArgs)] = importPath

			vendorPath := path.Join(project.GetBaseDir(), "vendor", importPath)

			// Check that vendor's dir exists
			_, err := os.Stat(vendorPath)

			if !assert.Nil(t, err, specificFailMessageAndArgs...) {
				continue vendorsLoop
			}

			// Remove vendor
			err = project.RemoveVendor(importPath)

			if !assert.Nil(t, err, specificFailMessageAndArgs...) {
				continue vendorsLoop
			}

			// Check that vendor's dir doesn't exist anymore
			_, err = os.Stat(vendorPath)

			if !assert.True(t, os.IsNotExist(err), specificFailMessageAndArgs...) {
				continue vendorsLoop
			}
		}

		// Check that PROJECTPATH/vendor is empty or doesn't exists
		fileInfos, err := ioutil.ReadDir(path.Join(project.GetBaseDir(), "vendor"))

		if os.IsNotExist(err) || assert.Nil(t, err, failMessageAndArgs...) {
			assert.Len(t, fileInfos, 0)
		}
	}

}

func TestProjectNoVCL_AddVendor(t *testing.T) {
	project := newProjectNoVCLProject(t)
	defer os.RemoveAll(project.GetBaseDir())

	futureVendor := newProjectNoVCLProject(t)
	defer os.RemoveAll(futureVendor.GetBaseDir())

	importPath := "completely/madeup/importpath"
	actualVendor, err := project.AddVendor(importPath, futureVendor)

	assert.Nil(t, err)

	assert.Equal(t, path.Join(project.GetBaseDir(), "vendor", importPath), actualVendor.GetBaseDir())

	fileInfo, err := os.Stat(actualVendor.GetBaseDir())

	assert.Nil(t, err)
	assert.True(t, fileInfo.IsDir())
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Fl. Neotrop. , Monogr. 17: 117 (1976)

#### Original name
Marasmius tetrachrous Singer

### Remarks
null