text:
//
// Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

#include "misc/debug.h"
#include "misc/object_tracker.h"
#include "misc/window.h"
#include "wrappers/instance.h"
#include "wrappers/physical_device.h"
#include "wrappers/pipeline_layout.h"
#include "wrappers/rendering_surface.h"
#include "wrappers/queue.h"

/* Please see header for specification */
Anvil::RenderingSurface::RenderingSurface(std::weak_ptr<Anvil::Instance>   in_instance_ptr,
                                          std::weak_ptr<Anvil::BaseDevice> in_device_ptr,
                                          std::shared_ptr<Anvil::Window>   in_window_ptr,
                                          bool*                            out_safe_to_use_ptr)
    :DebugMarkerSupportProvider(in_device_ptr,
                                VK_DEBUG_REPORT_OBJECT_TYPE_SURFACE_KHR_EXT),
     m_device_ptr              (in_device_ptr),
     m_height                  (0),
     m_instance_ptr            (in_instance_ptr),
     m_surface                 (VK_NULL_HANDLE),
     m_type                    (RENDERING_SURFACE_TYPE_GENERAL),
     m_width                   (0),
     m_window_ptr              (in_window_ptr)
{
    *out_safe_to_use_ptr = init();

    /* Register the instance */
    Anvil::ObjectTracker::get()->register_object(Anvil::OBJECT_TYPE_RENDERING_SURFACE,
                                                 this);
}

/* Please see header for specification */
Anvil::RenderingSurface::~RenderingSurface()
{
    if (m_surface != VK_NULL_HANDLE)
    {
        std::shared_ptr<Anvil::Instance> instance_locked_ptr(m_instance_ptr);

        m_instance_ptr->get_extension_khr_surface_entrypoints().vkDestroySurfaceKHR(instance_locked_ptr->get_instance_vk(),
                                                                                m_surface,
                                                                                nullptr /* pAllocator */);

        m_surface = VK_NULL_HANDLE;
    }

    Anvil::ObjectTracker::get()->unregister_object(Anvil::OBJECT_TYPE_RENDERING_SURFACE,
                                                    this);
}

/* Please see header for specification */
void Anvil::RenderingSurface::cache_surface_properties()
{
    std::shared_ptr<Anvil::BaseDevice> device_locked_ptr             (m_device_ptr);
    auto                               khr_surface_entrypoints       (m_instance_ptr->get_extension_khr_surface_entrypoints() );
    bool                               is_offscreen_rendering_enabled(true);
    VkPhysicalDevice                   physical_device_vk            (VK_NULL_HANDLE);
    std::shared_ptr<Anvil::SGPUDevice> sgpu_device_locked_ptr        (std::dynamic_pointer_cast<Anvil::SGPUDevice>(device_locked_ptr));
    std::vector<VkSurfaceFormatKHR>    supported_formats;

    if (m_window_ptr.lock() )
    {
        std::shared_ptr<Anvil::Window> window_locked_ptr(m_window_ptr);
        const WindowPlatform           window_platform  (window_locked_ptr->get_platform() );

        is_offscreen_rendering_enabled = (window_platform == WINDOW_PLATFORM_DUMMY                     ||
                                          window_platform == WINDOW_PLATFORM_DUMMY_WITH_PNG_SNAPSHOTS) &&
                                         (m_type          == RENDERING_SURFACE_TYPE_GENERAL);

        if (is_offscreen_rendering_enabled)
        {
            m_height = window_locked_ptr->get_height();
            m_width  = window_locked_ptr->get_width ();
        }
        else
        {
            /* In this case, width & height may change at run-time */
        }
    }
    else
    {
        /* In this case, width & height may change at run-time */
    }

    /* Retrieve general properties */
    uint32_t            n_supported_formats           (0);
    uint32_t            n_supported_presentation_modes(0);
    VkResult            result                        (VK_ERROR_INITIALIZATION_FAILED);

    ANVIL_REDUNDANT_VARIABLE(result);

    std::shared_ptr<Anvil::PhysicalDevice> physical_device_locked_ptr(sgpu_device_locked_ptr->get_physical_device());

    auto& result_caps = m_physical_device_capabilities[0];

    if (is_offscreen_rendering_enabled)
    {
        result_caps.supported_composite_alpha_flags = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
        result_caps.supported_transformations       = VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
        result_caps.supported_usages                = static_cast<VkImageUsageFlagBits> (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
                                                                                VK_IMAGE_USAGE_TRANSFER_SRC_BIT     |
                                                                                VK_IMAGE_USAGE_TRANSFER_DST_BIT     |
                                                                                VK_IMAGE_USAGE_STORAGE_BIT);

        goto end;
    }

    physical_device_vk = physical_device_locked_ptr->get_physical_device();

    result = khr_surface_entrypoints.vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physical_device_vk,
                                                                               m_surface,
                                                                              &result_caps.capabilities);

    anvil_assert_vk_call_succeeded(result);

    m_height = result_caps.capabilities.currentExtent.height;
    m_width  = result_caps.capabilities.currentExtent.width;

    result_caps.supported_composite_alpha_flags = static_cast<VkCompositeAlphaFlagBitsKHR>  (result_caps.capabilities.supportedCompositeAlpha);
    result_caps.supported_transformations       = static_cast<VkSurfaceTransformFlagBitsKHR>(result_caps.capabilities.supportedTransforms);
    result_caps.supported_usages                = static_cast<VkImageUsageFlagBits>         (result_caps.capabilities.supportedUsageFlags);

    /* Retrieve a list of formats supported by the surface */
    result = khr_surface_entrypoints.vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device_vk,
                                                                          m_surface,
                                                                         &n_supported_formats,
                                                                          nullptr /* pSurfaceFormats */);

    anvil_assert                  (n_supported_formats >  0);
    anvil_assert_vk_call_succeeded(result);

    supported_formats.resize(n_supported_formats);

    result = khr_surface_entrypoints.vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device_vk,
                                                                          m_surface,
                                                                         &n_supported_formats,
                                                                         &supported_formats.at(0) );
    anvil_assert_vk_call_succeeded(result);

    for (unsigned int n_format = 0;
                      n_format < n_supported_formats;
                    ++n_format)
    {
        result_caps.supported_formats.push_back(RenderingSurfaceFormat(supported_formats[n_format]) );
    }

    /* Retrieve a list of supported presentation modes */
    result = khr_surface_entrypoints.vkGetPhysicalDeviceSurfacePresentModesKHR(physical_device_vk,
                                                                               m_surface,
                                                                              &n_supported_presentation_modes,
                                                                               nullptr /* pPresentModes */);

    anvil_assert                  (n_supported_presentation_modes >  0);
    anvil_assert_vk_call_succeeded(result);

    result_caps.supported_presentation_modes.resize(n_supported_presentation_modes);

    result = khr_surface_entrypoints.vkGetPhysicalDeviceSurfacePresentModesKHR(physical_device_vk,
                                                                               m_surface,
                                                                              &n_supported_presentation_modes,
                                                                              &result_caps.supported_presentation_modes[0]);
    anvil_assert_vk_call_succeeded(result);

    if (n_supported_presentation_modes > 0)
    {
        result_caps.supported_presentation_modes.resize(n_supported_presentation_modes);

        result = khr_surface_entrypoints.vkGetPhysicalDeviceSurfacePresentModesKHR(physical_device_vk,
                                                                                m_surface,
                                                                                &n_supported_presentation_modes,
                                                                                &result_caps.supported_presentation_modes.at(0));
        anvil_assert_vk_call_succeeded(result);
    }

end:
    ;
}

/* Please see header for specification */
std::shared_ptr<Anvil::RenderingSurface> Anvil::RenderingSurface::create(std::weak_ptr<Anvil::Instance>   in_instance_ptr,
                                                                         std::weak_ptr<Anvil::BaseDevice> in_device_ptr,
                                                                         std::shared_ptr<Anvil::Window>   in_window_ptr)
{
    std::shared_ptr<Anvil::RenderingSurface> result_ptr;
    bool                                     success    = false;

    result_ptr.reset(
        new Anvil::RenderingSurface(in_instance_ptr,
                                    in_device_ptr,
                                    in_window_ptr,
                                   &success) );

    if (!success)
    {
        result_ptr.reset();
    }

    return result_ptr;
}

/* Please see header for specification */
bool Anvil::RenderingSurface::get_capabilities(std::weak_ptr<Anvil::PhysicalDevice> in_physical_device_ptr,
                                               VkSurfaceCapabilitiesKHR*            out_surface_caps_ptr) const
{
    auto caps_iterator = m_physical_device_capabilities.find(0);
    bool result        = false;

    if (caps_iterator != m_physical_device_capabilities.end() )
    {
        *out_surface_caps_ptr = caps_iterator->second.capabilities;
        result                = true;
    }

    /* All done */
    return result;
}

/* Please see header for specification */
bool Anvil::RenderingSurface::get_queue_families_with_present_support(std::weak_ptr<Anvil::PhysicalDevice> in_physical_device_ptr,
                                                                      const std::vector<uint32_t>**        out_result_ptr) const
{
    auto caps_iterator = m_physical_device_capabilities.find(0);
    bool result        = false;

    if (caps_iterator != m_physical_device_capabilities.end() )
    {
        *out_result_ptr = &caps_iterator->second.present_capable_queue_fams;
        result          = true;
    }

    /* All done */
    return result;
}

/* Please see header for specification */
bool Anvil::RenderingSurface::get_supported_composite_alpha_flags(std::weak_ptr<Anvil::PhysicalDevice> in_physical_device_ptr,
                                                                  VkCompositeAlphaFlagsKHR*            out_result_ptr) const
{
    auto caps_iterator = m_physical_device_capabilities.find(0);
    bool result        = false;

    if (caps_iterator != m_physical_device_capabilities.end() )
    {
        *out_result_ptr = caps_iterator->second.supported_composite_alpha_flags;
        result          = true;
    }

    /* All done */
    return result;
}

/* Please see header for specification */
bool Anvil::RenderingSurface::get_supported_transformations(std::weak_ptr<Anvil::PhysicalDevice> in_physical_device_ptr,
                                                            VkSurfaceTransformFlagsKHR*          out_result_ptr) const
{
    auto caps_iterator = m_physical_device_capabilities.find(0);
    bool result        = false;

    if (caps_iterator != m_physical_device_capabilities.end() )
    {
        *out_result_ptr = caps_iterator->second.supported_transformations;
        result          = true;
    }

    /* All done */
    return result;
}

/* Please see header for specification */
bool Anvil::RenderingSurface::get_supported_usages(std::weak_ptr<Anvil::PhysicalDevice> in_physical_device_ptr,
                                                   VkImageUsageFlags*                   out_result_ptr) const
{
    auto caps_iterator = m_physical_device_capabilities.find(0);
    bool result        = false;

    if (caps_iterator != m_physical_device_capabilities.end() )
    {
        *out_result_ptr = caps_iterator->second.supported_usages;
        result          = true;
    }

    /* All done */
    return result;
}

/* Please see header for specification */
bool Anvil::RenderingSurface::init()
{
    std::shared_ptr<Anvil::BaseDevice> device_locked_ptr       (m_device_ptr);
    bool                               init_successful         (false);
    uint32_t                           n_physical_devices      (1);
    VkResult                           result                  (VK_SUCCESS);
    const WindowPlatform               window_platform         ((m_type == RENDERING_SURFACE_TYPE_GENERAL) ? m_window_ptr.lock()->get_platform()
                                                                                : WINDOW_PLATFORM_UNKNOWN);

    const bool                         is_dummy_window_platform(window_platform == WINDOW_PLATFORM_DUMMY                     ||
                                                                window_platform == WINDOW_PLATFORM_DUMMY_WITH_PNG_SNAPSHOTS);

    for (uint32_t n_physical_device = 0;
                  n_physical_device < n_physical_devices;
                ++n_physical_device)
    {
        m_physical_device_capabilities[n_physical_device] = PhysicalDeviceCapabilities();
    }

    if (!is_dummy_window_platform)
    {
        std::shared_ptr<Anvil::Instance> instance_locked_ptr(m_instance_ptr);

        switch (m_type)
        {
            #if defined(ANVIL_INCLUDE_WIN3264_WINDOW_SYSTEM_SUPPORT) || defined(ANVIL_INCLUDE_XCB_WINDOW_SYSTEM_SUPPORT)
                case RENDERING_SURFACE_TYPE_GENERAL:
                {
                    #ifdef _WIN32
                    {
                        VkWin32SurfaceCreateInfoKHR surface_create_info;

                        surface_create_info.flags     = 0;
                        surface_create_info.hinstance = GetModuleHandle(nullptr);
                        surface_create_info.hwnd      = m_window_ptr.lock()->get_handle();
                        surface_create_info.pNext     = nullptr;
                        surface_create_info.sType     = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;

                        result = m_instance_ptr->get_extension_khr_win32_surface_entrypoints().vkCreateWin32SurfaceKHR(instance_locked_ptr->get_instance_vk(),
                                                                                &surface_create_info,
                                                                                nullptr, /* pAllocator */
                                                                                &m_surface);
                    }
                    #else
                    {
                        VkXcbSurfaceCreateInfoKHR surface_create_info;

                        surface_create_info.flags       = 0;
                        surface_create_info.window      = m_window_ptr.lock()->get_handle();
                        surface_create_info.connection  = static_cast<xcb_connection_t*>(m_window_ptr.lock()->get_connection());
                        surface_create_info.pNext       = nullptr;
                        surface_create_info.sType       = VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR;

                        result = m_instance_ptr->get_extension_khr_xcb_surface_entrypoints().vkCreateXcbSurfaceKHR(instance_locked_ptr->get_instance_vk(),
                                                                                &surface_create_info,
                                                                                nullptr, /* pAllocator */
                                                                                &m_surface);
                    }
                    #endif

                    break;
                }
            #endif

            default:
            {
                anvil_assert_fail();

                goto end;
            }
        }

        anvil_assert_vk_call_succeeded(result);
        if (is_vk_call_successful(result) )
        {
            set_vk_handle(m_surface);
        }
    }
    else
    {
        anvil_assert(window_platform != WINDOW_PLATFORM_UNKNOWN);
    }

    if (is_dummy_window_platform == false)
    {
        /* Is there at least one queue fam that can be used together with at least one physical device associated with
         * the logical device to present using the surface we've just spawned and the physical device user has specified? */
        const auto&                        queue_families        (device_locked_ptr->get_physical_device_queue_families() );
        std::shared_ptr<Anvil::SGPUDevice> sgpu_device_locked_ptr(std::dynamic_pointer_cast<Anvil::SGPUDevice>(device_locked_ptr) );

        for (uint32_t n_physical_device = 0;
                      n_physical_device < n_physical_devices;
                    ++n_physical_device)
        {
            std::shared_ptr<Anvil::PhysicalDevice> physical_device_locked_ptr(sgpu_device_locked_ptr->get_physical_device() );

            auto& result_caps = m_physical_device_capabilities.at(0);

            switch (m_type)
            {
                case Anvil::RENDERING_SURFACE_TYPE_GENERAL:
                {
                    for (uint32_t n_queue_family = 0;
                                  n_queue_family < static_cast<uint32_t>(queue_families.size() );
                                ++n_queue_family)
                    {
                        VkBool32 is_presentation_supported = VK_FALSE;

                        result = vkGetPhysicalDeviceSurfaceSupportKHR(physical_device_locked_ptr->get_physical_device(),
                                                                      n_queue_family,
                                                                      m_surface,
                                                                     &is_presentation_supported);

                        if (is_vk_call_successful(result)         &&
                            is_presentation_supported == VK_TRUE)
                        {
                            result_caps.present_capable_queue_fams.push_back(n_queue_family);
                        }
                    }

                    break;
                }

                default:
                {
                    anvil_assert_fail();
                }
            }
        }
    }
    else
    {
        /* offscreen rendering. Any physical device that offers universal queue can be used to "present" */
        for (uint32_t n_physical_device = 0;
                      n_physical_device < n_physical_devices;
                    ++n_physical_device)
        {
            std::shared_ptr<Anvil::SGPUDevice> sgpu_device_locked_ptr(std::dynamic_pointer_cast<Anvil::SGPUDevice>(device_locked_ptr) );

            if (sgpu_device_locked_ptr->get_n_universal_queues() > 0)
            {
                std::shared_ptr<Anvil::PhysicalDevice> physical_device_locked_ptr = sgpu_device_locked_ptr->get_physical_device().lock();
                auto&                                  result_caps                = m_physical_device_capabilities.at          (0);

                result_caps.present_capable_queue_fams.push_back(sgpu_device_locked_ptr->get_universal_queue(0)->get_queue_family_index() );
            }
        }

        result = VK_SUCCESS;
    }

    if (!is_vk_call_successful(result) )
    {
        anvil_assert_vk_call_succeeded(result);

        init_successful = false;
    }
    else
    {
        /* Retrieve Vulkan object capabilities and cache them */
        cache_surface_properties();

        init_successful = true;
    }

end:
    return init_successful;
}

/* Please see header for specification */
bool Anvil::RenderingSurface::is_compatible_with_image_format(std::weak_ptr<Anvil::PhysicalDevice> in_physical_device_ptr,
                                                              VkFormat                             in_image_format,
                                                              bool*                                out_result_ptr) const
{
    auto caps_iterator = m_physical_device_capabilities.find(0);
    bool result        = false;

    if (caps_iterator != m_physical_device_capabilities.end() )
    {
        *out_result_ptr = std::find(caps_iterator->second.supported_formats.begin(),
                                    caps_iterator->second.supported_formats.end(),
                                    in_image_format) != caps_iterator->second.supported_formats.end();
        result          = true;
    }

    return result;
}

/* Please see header for specification */
bool Anvil::RenderingSurface::supports_presentation_mode(std::weak_ptr<Anvil::PhysicalDevice> in_physical_device_ptr,
                                                         VkPresentModeKHR                     in_presentation_mode,
                                                         bool*                                out_result_ptr) const
{
    auto caps_iterator = m_physical_device_capabilities.find(0);
    bool result        = false;

    if (caps_iterator != m_physical_device_capabilities.end() )
    {
        *out_result_ptr = std::find(caps_iterator->second.supported_presentation_modes.begin(),
                                    caps_iterator->second.supported_presentation_modes.end(),
                                    in_presentation_mode) != caps_iterator->second.supported_presentation_modes.end();
        result          = true;
    }

    return result;
}


text:
module Dragon
  module Events
    class PlayerDodgedAttackEvent < Event
      attr_reader :enemy

      def initialize(enemy: nil)
        @enemy = enemy
      end

      def describe
        "you dodge #{enemy.label}'s attack"
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Rev. n. -amer. Astragalus 208, t. 46. 1923 "martini"

#### Original name
null

### Remarks
null


text:
package com.fsck.k9.mail.internet;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.LinkedList;
import java.util.Locale;
import java.util.Set;
import java.util.UUID;

import org.apache.commons.io.IOUtils;
import org.apache.james.mime4j.MimeException;
import org.apache.james.mime4j.dom.field.DateTimeField;
import org.apache.james.mime4j.field.DefaultFieldParser;
import org.apache.james.mime4j.io.EOLConvertingInputStream;
import org.apache.james.mime4j.parser.ContentHandler;
import org.apache.james.mime4j.parser.MimeStreamParser;
import org.apache.james.mime4j.stream.BodyDescriptor;
import org.apache.james.mime4j.stream.Field;
import org.apache.james.mime4j.stream.MimeConfig;
import org.apache.james.mime4j.util.MimeUtil;

import com.fsck.k9.mail.Address;
import com.fsck.k9.mail.Body;
import com.fsck.k9.mail.BodyPart;
import com.fsck.k9.mail.CompositeBody;
import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.Multipart;
import com.fsck.k9.mail.Part;

/**
 * An implementation of Message that stores all of it's metadata in RFC 822 and
 * RFC 2045 style headers.
 */
public class MimeMessage extends Message {
    private MimeHeader mHeader = new MimeHeader();
    protected Address[] mFrom;
    protected Address[] mTo;
    protected Address[] mCc;
    protected Address[] mBcc;
    protected Address[] mReplyTo;

    protected String mMessageId;
    private String[] mReferences;
    private String[] mInReplyTo;

    private Date mSentDate;
    private SimpleDateFormat mDateFormat;

    private Body mBody;
    protected int mSize;
    private String serverExtra;

    public MimeMessage() {
    }

    /**
     * Parse the given InputStream using Apache Mime4J to build a MimeMessage.
     *
     * @param in
     * @param recurse A boolean indicating to recurse through all nested MimeMessage subparts.
     * @throws IOException
     * @throws MessagingException
     */
    public MimeMessage(InputStream in, boolean recurse) throws IOException, MessagingException {
        parse(in, recurse);
    }

    /**
     * Parse the given InputStream using Apache Mime4J to build a MimeMessage.
     * Does not recurse through nested bodyparts.
     */
    public final void parse(InputStream in) throws IOException, MessagingException {
        parse(in, false);
    }

    private void parse(InputStream in, boolean recurse) throws IOException, MessagingException {
        mHeader.clear();
        mFrom = null;
        mTo = null;
        mCc = null;
        mBcc = null;
        mReplyTo = null;

        mMessageId = null;
        mReferences = null;
        mInReplyTo = null;

        mSentDate = null;

        mBody = null;

        MimeConfig parserConfig  = new MimeConfig();
        parserConfig.setMaxHeaderLen(-1); // The default is a mere 10k
        parserConfig.setMaxLineLen(-1); // The default is 1000 characters. Some MUAs generate
        // REALLY long References: headers
        parserConfig.setMaxHeaderCount(-1); // Disable the check for header count.
        MimeStreamParser parser = new MimeStreamParser(parserConfig);
        parser.setContentHandler(new MimeMessageBuilder());
        if (recurse) {
            parser.setRecurse();
        }
        try {
            parser.parse(new EOLConvertingInputStream(in));
        } catch (MimeException me) {
            //TODO wouldn't a MessagingException be better?
            throw new Error(me);
        }
    }

    @Override
    public Date getSentDate() {
        if (mSentDate == null) {
            try {
                DateTimeField field = (DateTimeField)DefaultFieldParser.parse("Date: "
                                      + MimeUtility.unfoldAndDecode(getFirstHeader("Date")));
                mSentDate = field.getDate();
            } catch (Exception e) {

            }
        }
        return mSentDate;
    }

    /**
     * Sets the sent date object member as well as *adds* the 'Date' header
     * instead of setting it (for performance reasons).
     *
     * @see #mSentDate
     * @param sentDate
     * @throws com.fsck.k9.mail.MessagingException
     */
    public void addSentDate(Date sentDate, boolean hideTimeZone) throws MessagingException {
        if (mDateFormat == null) {
            mDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);
        }

        if (hideTimeZone) {
            mDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        }

        addHeader("Date", mDateFormat.format(sentDate));
        setInternalSentDate(sentDate);
    }

    @Override
    public void setSentDate(Date sentDate, boolean hideTimeZone) throws MessagingException {
        removeHeader("Date");
        addSentDate(sentDate, hideTimeZone);
    }

    public void setInternalSentDate(Date sentDate) {
        this.mSentDate = sentDate;
    }

    @Override
    public String getContentType() {
        String contentType = getFirstHeader(MimeHeader.HEADER_CONTENT_TYPE);
        return (contentType == null) ? "text/plain" : contentType;
    }

    @Override
    public String getDisposition() throws MessagingException {
        return getFirstHeader(MimeHeader.HEADER_CONTENT_DISPOSITION);
    }

    @Override
    public String getContentId() {
        return null;
    }

    @Override
    public String getMimeType() {
        return MimeUtility.getHeaderParameter(getContentType(), null);
    }

    @Override
    public boolean isMimeType(String mimeType) throws MessagingException {
        return getMimeType().equalsIgnoreCase(mimeType);
    }

    @Override
    public int getSize() {
        return mSize;
    }

    /**
     * Returns a list of the given recipient type from this message. If no addresses are
     * found the method returns an empty array.
     */
    @Override
    public Address[] getRecipients(RecipientType type) throws MessagingException {
        if (type == RecipientType.TO) {
            if (mTo == null) {
                mTo = Address.parse(MimeUtility.unfold(getFirstHeader("To")));
            }
            return mTo;
        } else if (type == RecipientType.CC) {
            if (mCc == null) {
                mCc = Address.parse(MimeUtility.unfold(getFirstHeader("CC")));
            }
            return mCc;
        } else if (type == RecipientType.BCC) {
            if (mBcc == null) {
                mBcc = Address.parse(MimeUtility.unfold(getFirstHeader("BCC")));
            }
            return mBcc;
        } else {
            throw new MessagingException("Unrecognized recipient type.");
        }
    }

    @Override
    public void setRecipients(RecipientType type, Address[] addresses) throws MessagingException {
        if (type == RecipientType.TO) {
            if (addresses == null || addresses.length == 0) {
                removeHeader("To");
                this.mTo = null;
            } else {
                setHeader("To", Address.toEncodedString(addresses));
                this.mTo = addresses;
            }
        } else if (type == RecipientType.CC) {
            if (addresses == null || addresses.length == 0) {
                removeHeader("CC");
                this.mCc = null;
            } else {
                setHeader("CC", Address.toEncodedString(addresses));
                this.mCc = addresses;
            }
        } else if (type == RecipientType.BCC) {
            if (addresses == null || addresses.length == 0) {
                removeHeader("BCC");
                this.mBcc = null;
            } else {
                setHeader("BCC", Address.toEncodedString(addresses));
                this.mBcc = addresses;
            }
        } else {
            throw new MessagingException("Unrecognized recipient type.");
        }
    }

    /**
     * Returns the unfolded, decoded value of the Subject header.
     */
    @Override
    public String getSubject() {
        return MimeUtility.unfoldAndDecode(getFirstHeader("Subject"), this);
    }

    @Override
    public void setSubject(String subject) throws MessagingException {
        setHeader("Subject", subject);
    }

    @Override
    public Address[] getFrom() {
        if (mFrom == null) {
            String list = MimeUtility.unfold(getFirstHeader("From"));
            if (list == null || list.length() == 0) {
                list = MimeUtility.unfold(getFirstHeader("Sender"));
            }
            mFrom = Address.parse(list);
        }
        return mFrom;
    }

    @Override
    public void setFrom(Address from) throws MessagingException {
        if (from != null) {
            setHeader("From", from.toEncodedString());
            this.mFrom = new Address[] {
                from
            };
        } else {
            this.mFrom = null;
        }
    }

    @Override
    public Address[] getReplyTo() {
        if (mReplyTo == null) {
            mReplyTo = Address.parse(MimeUtility.unfold(getFirstHeader("Reply-to")));
        }
        return mReplyTo;
    }

    @Override
    public void setReplyTo(Address[] replyTo) throws MessagingException {
        if (replyTo == null || replyTo.length == 0) {
            removeHeader("Reply-to");
            mReplyTo = null;
        } else {
            setHeader("Reply-to", Address.toEncodedString(replyTo));
            mReplyTo = replyTo;
        }
    }

    @Override
    public String getMessageId() throws MessagingException {
        if (mMessageId == null) {
            mMessageId = getFirstHeader("Message-ID");
        }
        return mMessageId;
    }

    public void generateMessageId() throws MessagingException {
        String hostname = null;

        if (mFrom != null && mFrom.length >= 1) {
            hostname = mFrom[0].getHostname();
        }

        if (hostname == null && mReplyTo != null && mReplyTo.length >= 1) {
            hostname = mReplyTo[0].getHostname();
        }

        if (hostname == null) {
            hostname = "email.android.com";
        }

        /* We use upper case here to match Apple Mail Message-ID format (for privacy) */
        String messageId = "<" + UUID.randomUUID().toString().toUpperCase(Locale.US) + "@" + hostname + ">";

        setMessageId(messageId);
    }

    public void setMessageId(String messageId) throws MessagingException {
        setHeader("Message-ID", messageId);
        mMessageId = messageId;
    }

    @Override
    public void setInReplyTo(String inReplyTo) throws MessagingException {
        setHeader("In-Reply-To", inReplyTo);
    }

    @Override
    public String[] getReferences() throws MessagingException {
        if (mReferences == null) {
            mReferences = getHeader("References");
        }
        return mReferences;
    }

    @Override
    public void setReferences(String references) throws MessagingException {
        /*
         * Make sure the References header doesn't exceed the maximum header
         * line length and won't get (Q-)encoded later. Otherwise some clients
         * will break threads apart.
         *
         * For more information see issue 1559.
         */

        // Make sure separator is SPACE to prevent Q-encoding when TAB is encountered
        references = references.replaceAll("\\s+", " ");

        /*
         * NOTE: Usually the maximum header line is 998 + CRLF = 1000 characters.
         * But at least one implementations seems to have problems with 998
         * characters, so we adjust for that fact.
         */
        final int limit = 1000 - 2 /* CRLF */ - 12 /* "References: " */ - 1 /* Off-by-one bugs */;
        final int originalLength = references.length();
        if (originalLength >= limit) {
            // Find start of first reference
            final int start = references.indexOf('<');

            // First reference + SPACE
            final String firstReference = references.substring(start,
                                          references.indexOf('<', start + 1));

            // Find longest tail
            final String tail = references.substring(references.indexOf('<',
                                firstReference.length() + originalLength - limit));

            references = firstReference + tail;
        }
        setHeader("References", references);
    }

    @Override
    public Body getBody() {
        return mBody;
    }

    @Override
    public void setBody(Body body) {
        this.mBody = body;
    }

    private String getFirstHeader(String name) {
        return mHeader.getFirstHeader(name);
    }

    @Override
    public void addHeader(String name, String value) throws MessagingException {
        mHeader.addHeader(name, value);
    }

    @Override
    public void addRawHeader(String name, String raw) {
        mHeader.addRawHeader(name, raw);
    }

    @Override
    public void setHeader(String name, String value) throws MessagingException {
        mHeader.setHeader(name, value);
    }

    @Override
    public String[] getHeader(String name) throws MessagingException {
        return mHeader.getHeader(name);
    }

    @Override
    public void removeHeader(String name) throws MessagingException {
        mHeader.removeHeader(name);
    }

    @Override
    public Set<String> getHeaderNames() throws MessagingException {
        return mHeader.getHeaderNames();
    }

    @Override
    public void writeTo(OutputStream out) throws IOException, MessagingException {

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out), 1024);
        mHeader.writeTo(out);
        writer.write("\r\n");
        writer.flush();
        if (mBody != null) {
            mBody.writeTo(out);
        }
    }

    @Override
    public void writeHeaderTo(OutputStream out) throws IOException, MessagingException {
        mHeader.writeTo(out);
    }

    @Override
    public InputStream getInputStream() throws MessagingException {
        return null;
    }

    @Override
    public void setEncoding(String encoding) throws MessagingException {
        if (mBody != null) {
            mBody.setEncoding(encoding);
        }
        setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, encoding);
    }

    @Override
    public void setCharset(String charset) throws MessagingException {
        mHeader.setCharset(charset);
        if (mBody instanceof Multipart) {
            ((Multipart)mBody).setCharset(charset);
        } else if (mBody instanceof TextBody) {
            CharsetSupport.setCharset(charset, this);
            ((TextBody)mBody).setCharset(charset);
        }
    }

    private class MimeMessageBuilder implements ContentHandler {
        private final LinkedList<Object> stack = new LinkedList<Object>();

        public MimeMessageBuilder() {
        }

        private void expect(Class<?> c) {
            if (!c.isInstance(stack.peek())) {
                throw new IllegalStateException("Internal stack error: " + "Expected '"
                                                + c.getName() + "' found '" + stack.peek().getClass().getName() + "'");
            }
        }

        @Override
        public void startMessage() {
            if (stack.isEmpty()) {
                stack.addFirst(MimeMessage.this);
            } else {
                expect(Part.class);
                Part part = (Part) stack.peek();

                MimeMessage m = new MimeMessage();
                part.setBody(m);
                stack.addFirst(m);
            }
        }

        @Override
        public void endMessage() {
            expect(MimeMessage.class);
            stack.removeFirst();
        }

        @Override
        public void startHeader() {
            expect(Part.class);
        }

        @Override
        public void endHeader() {
            expect(Part.class);
        }

        @Override
        public void startMultipart(BodyDescriptor bd) {
            expect(Part.class);

            Part e = (Part)stack.peek();
            try {
                String contentType = e.getContentType();
                String mimeType = MimeUtility.getHeaderParameter(contentType, null);
                String boundary = MimeUtility.getHeaderParameter(contentType, "boundary");
                MimeMultipart multiPart = new MimeMultipart(mimeType, boundary);
                e.setBody(multiPart);
                stack.addFirst(multiPart);
            } catch (MessagingException me) {
                throw new Error(me);
            }
        }

        @Override
        public void body(BodyDescriptor bd, InputStream in) throws IOException {
            expect(Part.class);
            try {
                Body body = MimeUtility.createBody(in, bd.getTransferEncoding(), bd.getMimeType());
                ((Part)stack.peek()).setBody(body);
            } catch (MessagingException me) {
                throw new Error(me);
            }
        }

        @Override
        public void endMultipart() {
            expect(Multipart.class);
            Multipart multipart = (Multipart) stack.removeFirst();

            boolean hasNoBodyParts = multipart.getCount() == 0;
            boolean hasNoEpilogue = multipart.getEpilogue() == null;
            if (hasNoBodyParts && hasNoEpilogue) {
                /*
                 * The parser is calling startMultipart(), preamble(), and endMultipart() when all we have is
                 * headers of a "multipart/*" part. But there's really no point in keeping a Multipart body if all
                 * of the content is missing.
                 */
                expect(Part.class);
                Part part = (Part) stack.peek();
                part.setBody(null);
            }
        }

        @Override
        public void startBodyPart() {
            expect(MimeMultipart.class);

            try {
                MimeBodyPart bodyPart = new MimeBodyPart();
                ((MimeMultipart)stack.peek()).addBodyPart(bodyPart);
                stack.addFirst(bodyPart);
            } catch (MessagingException me) {
                throw new Error(me);
            }
        }

        @Override
        public void endBodyPart() {
            expect(BodyPart.class);
            stack.removeFirst();
        }

        @Override
        public void preamble(InputStream is) throws IOException {
            expect(MimeMultipart.class);
            ByteArrayOutputStream preamble = new ByteArrayOutputStream();
            IOUtils.copy(is, preamble);
            ((MimeMultipart)stack.peek()).setPreamble(preamble.toByteArray());
        }

        @Override
        public void epilogue(InputStream is) throws IOException {
            expect(MimeMultipart.class);
            ByteArrayOutputStream epilogue = new ByteArrayOutputStream();
            IOUtils.copy(is, epilogue);
            ((MimeMultipart) stack.peek()).setEpilogue(epilogue.toByteArray());
        }

        @Override
        public void raw(InputStream is) throws IOException {
            throw new UnsupportedOperationException("Not supported");
        }

        @Override
        public void field(Field parsedField) throws MimeException {
            expect(Part.class);
            try {
                String name = parsedField.getName();
                String raw = parsedField.getRaw().toString();
                ((Part) stack.peek()).addRawHeader(name, raw);
            } catch (MessagingException me) {
                throw new Error(me);
            }
        }
    }

    /**
     * Copy the contents of this object into another {@code MimeMessage} object.
     *
     * @param destination The {@code MimeMessage} object to receive the contents of this instance.
     */
    protected void copy(MimeMessage destination) {
        super.copy(destination);

        destination.mHeader = mHeader.clone();

        destination.mBody = mBody;
        destination.mMessageId = mMessageId;
        destination.mSentDate = mSentDate;
        destination.mDateFormat = mDateFormat;
        destination.mSize = mSize;

        // These arrays are not supposed to be modified, so it's okay to reuse the references
        destination.mFrom = mFrom;
        destination.mTo = mTo;
        destination.mCc = mCc;
        destination.mBcc = mBcc;
        destination.mReplyTo = mReplyTo;
        destination.mReferences = mReferences;
        destination.mInReplyTo = mInReplyTo;
    }

    @Override
    public MimeMessage clone() {
        MimeMessage message = new MimeMessage();
        copy(message);
        return message;
    }

    @Override
    public long getId() {
        return Long.parseLong(mUid); //or maybe .mMessageId?
    }

    @Override
    public String getPreview() {
        return "";
    }

    @Override
    public boolean hasAttachments() {
        return false;
    }

    @Override
    public void setUsing7bitTransport() throws MessagingException {
        String type = getFirstHeader(MimeHeader.HEADER_CONTENT_TYPE);
        /*
         * We don't trust that a multipart/* will properly have an 8bit encoding
         * header if any of its subparts are 8bit, so we automatically recurse
         * (as long as its not multipart/signed).
         */
        if (mBody instanceof CompositeBody && !MimeUtility.isSameMimeType(type, "multipart/signed")) {
            setEncoding(MimeUtil.ENC_7BIT);
            // recurse
            ((CompositeBody) mBody).setUsing7bitTransport();
        } else if (!MimeUtil.ENC_8BIT
                .equalsIgnoreCase(getFirstHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING))) {
            return;
        } else if (type != null &&
                (MimeUtility.isSameMimeType(type, "multipart/signed") || MimeUtility.isMessage(type))) {
            /*
             * This shouldn't happen. In any case, it would be wrong to convert
             * them to some other encoding for 7bit transport.
             *
             * RFC 1847 says multipart/signed must be 7bit. It also says their
             * bodies must be treated as opaque, so we must not change the
             * encoding.
             *
             * We've dealt with (CompositeBody) type message/rfc822 above. Here
             * we must deal with all other message/* types. RFC 2045 says
             * message/* can only be 7bit or 8bit. RFC 2046 says unknown
             * message/* types must be treated as application/octet-stream,
             * which means we can't recurse into them. It also says that
             * existing subtypes message/partial and message/external must only
             * be 7bit, and that future subtypes "should be" 7bit.
             */
            throw new MessagingException(
                    "Unable to convert 8bit body part to 7bit");
        } else {
            setEncoding(MimeUtil.ENC_QUOTED_PRINTABLE);
        }
    }

    @Override
    public String getServerExtra() {
        return serverExtra;
    }

    @Override
    public void setServerExtra(String serverExtra) {
        this.serverExtra = serverExtra;
    }

}


text:
package io.fabric8.kubernetes.api.model;

import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import io.sundr.builder.annotations.Buildable;
import lombok.EqualsAndHashCode;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

@JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
    "apiVersion",
    "kind",
    "metadata",
    "fsType",
    "readOnly",
    "secretRef",
    "volumeName",
    "volumeNamespace"
})
@ToString
@EqualsAndHashCode
@Setter
@Accessors(prefix = {
    "_",
    ""
})
@Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = true, lazyCollectionInitEnabled = false, builderPackage = "io.fabric8.kubernetes.api.builder")
public class StorageOSPersistentVolumeSource implements KubernetesResource
{

    @JsonProperty("fsType")
    private String fsType;
    @JsonProperty("readOnly")
    private Boolean readOnly;
    @JsonProperty("secretRef")
    private ObjectReference secretRef;
    @JsonProperty("volumeName")
    private String volumeName;
    @JsonProperty("volumeNamespace")
    private String volumeNamespace;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    /**
     * No args constructor for use in serialization
     *
     */
    public StorageOSPersistentVolumeSource() {
    }

    /**
     *
     * @param volumeNamespace
     * @param volumeName
     * @param secretRef
     * @param readOnly
     * @param fsType
     */
    public StorageOSPersistentVolumeSource(String fsType, Boolean readOnly, ObjectReference secretRef, String volumeName, String volumeNamespace) {
        super();
        this.fsType = fsType;
        this.readOnly = readOnly;
        this.secretRef = secretRef;
        this.volumeName = volumeName;
        this.volumeNamespace = volumeNamespace;
    }

    @JsonProperty("fsType")
    public String getFsType() {
        return fsType;
    }

    @JsonProperty("fsType")
    public void setFsType(String fsType) {
        this.fsType = fsType;
    }

    @JsonProperty("readOnly")
    public Boolean getReadOnly() {
        return readOnly;
    }

    @JsonProperty("readOnly")
    public void setReadOnly(Boolean readOnly) {
        this.readOnly = readOnly;
    }

    @JsonProperty("secretRef")
    public ObjectReference getSecretRef() {
        return secretRef;
    }

    @JsonProperty("secretRef")
    public void setSecretRef(ObjectReference secretRef) {
        this.secretRef = secretRef;
    }

    @JsonProperty("volumeName")
    public String getVolumeName() {
        return volumeName;
    }

    @JsonProperty("volumeName")
    public void setVolumeName(String volumeName) {
        this.volumeName = volumeName;
    }

    @JsonProperty("volumeNamespace")
    public String getVolumeNamespace() {
        return volumeNamespace;
    }

    @JsonProperty("volumeNamespace")
    public void setVolumeNamespace(String volumeNamespace) {
        this.volumeNamespace = volumeNamespace;
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

}


text:
<?php

namespace spec\Knp\Rad\AutoRegistration\DefinitionBuilder;

use Doctrine\Common\Persistence\ManagerRegistry;
use Doctrine\Common\Persistence\ObjectManager;
use Knp\Rad\AutoRegistration\Finder\BundleFinder;
use Knp\Rad\AutoRegistration\Kernel\KernelWrapper;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class DoctrineObjectRepositoryBuilderSpec extends ObjectBehavior
{
    function let(KernelWrapper $kernel, BundleFinder $finder, ManagerRegistry $doctrine, ObjectManager $om)
    {
        $this->beConstructedWith($kernel, $finder, $doctrine);

        $doctrine->getManagerForClass('Bundle\Entity\Class1')->willReturn($om);
        $doctrine->getManagerForClass('Bundle\Entity\Class2')->willReturn(null);
        $doctrine->getManagerForClass('Bundle\Entity\Class3')->willReturn($om);

        $finder->findClasses(Argument::cetera())->willReturn([
            'Bundle\Entity\Class1',
            'Bundle\Entity\Class2',
            'Bundle\Entity\Class3',
        ]);
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('Knp\Rad\AutoRegistration\DefinitionBuilder\DoctrineObjectRepositoryBuilder');
    }

    function it_load_entities_definitions()
    {
        $definitions = $this->buildDefinitions(['public' => false]);

        $definition = $definitions['Bundle\Entity\Class1Repository'];
        $definition->shouldHaveType('Symfony\Component\DependencyInjection\Definition');
        $definition->getClass()->shouldReturn('Doctrine\Common\Persistence\ObjectRepository');
        $definition->isPublic()->shouldReturn(false);
        $factory = $definition->getFactory();
        expect(strval($factory[0]->getWrappedObject()))->toBe('doctrine');
        $factory[1]->shouldReturn('getRepository');
        $definition->getArguments()->shouldReturn(['Bundle\Entity\Class1']);

        $definition = $definitions['Bundle\Entity\Class3Repository'];
        $definition->shouldHaveType('Symfony\Component\DependencyInjection\Definition');
        $definition->getClass()->shouldReturn('Doctrine\Common\Persistence\ObjectRepository');
        $definition->isPublic()->shouldReturn(false);
        $factory = $definition->getFactory();
        expect(strval($factory[0]->getWrappedObject()))->toBe('doctrine');
        $factory[1]->shouldReturn('getRepository');
        $definition->getArguments()->shouldReturn(['Bundle\Entity\Class3']);

        expect(array_key_exists('Bundle\Entity\Class2Repository', $definition))->toBe(false);
    }
}


text:
namespace Selly.DataLayer
{
    using System;
    using System.Collections.Generic;
    using Selly.DataLayer.Interfaces;

    public partial class OrderItem : Interfaces.ISinglePkDataAccessObject
    {
        public System.Guid Id { get; set; }
        public System.Guid OrderId { get; set; }
        public System.Guid ProductId { get; set; }
        public double Quantity { get; set; }
        public double Price { get; set; }

        public virtual Order Order { get; set; }
        public virtual Product Product { get; set; }
    }
}


text:
from app.notify_client import NotifyAdminAPIClient

class LetterJobsClient(NotifyAdminAPIClient):

    def __init__(self):
        super().__init__("a" * 73, "b")

    def init_app(self, app):
        self.base_url = app.config['API_HOST_NAME']
        self.service_id = app.config['ADMIN_CLIENT_USER_NAME']
        self.api_key = app.config['ADMIN_CLIENT_SECRET']

    def get_letter_jobs(self):
        return self.get(url='/letter-jobs')['data']

    def send_letter_jobs(self, job_ids):
        return self.post(
            url='/send-letter-jobs',
            data={"job_ids": job_ids}
        )['data']


text:
		<button type="button" class="btn btn-default btn-sm" ng-click="onSkipPreviousClick()">

		</button>

		<button type="button" class="btn btn-default btn-sm" ng-click="onRewindClick()">

		</button>

		<button type="button" class="btn btn-default btn-sm" ng-click="onStopClick()">

		</button>

		<button type="button" class="btn btn-default btn-sm" ng-click="onPlayPauseClick()">

		</button>

		<button type="button" class="btn btn-default btn-sm" ng-click="onFastForwardClick()">

		</button>

		<button type="button" class="btn btn-default btn-sm" ng-click="onSkipNextClick()">

		</button>

	<audio-volume-control ng-show="!hideVolume"></audio-volume-control>

			{{currentTimeFormatted}}

			{{durationFormatted}}

		{{description}}


text:
import { kovats } from '../kovats';

export function appendKovats(peaks) {
  const result = [];
  for (let peak of peaks) {
    result.push({ ...peak, kovats: kovats(peak.ms) });
  }
  return result;
}


text:
from django import template
import datetime

register = template.Library()

# Turn a datetime.timedelta into a string
@register.filter(name='timedelta')
def timedelta(value):
    if not value:
        return "0"
    time = int(value / 1000000)
    delta = datetime.timedelta(0, time)
    return str(delta)


text:
/*
 * Hibernate Validator, declare and validate application constraints
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
 */
package org.hibernate.validator.internal.util;

import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;

import org.hibernate.validator.internal.engine.valueextraction.AnnotatedObject;
import org.hibernate.validator.internal.engine.valueextraction.ArrayElement;
import org.hibernate.validator.internal.util.logging.Log;
import org.hibernate.validator.internal.util.logging.LoggerFactory;

/**
 * Provides some utility methods for TypeVariables.
 *
 * @author Guillaume Smet
 */
public class TypeVariables {

	private static final Log LOG = LoggerFactory.make();

	private TypeVariables() {
	}

	public static Class<?> getContainerClass(TypeVariable<?> typeParameter) {
		if ( isAnnotatedObject( typeParameter ) ) {
			return null;
		}
		else if ( isArrayElement( typeParameter ) ) {
			return ( (ArrayElement) typeParameter ).getContainerClass();
		}
		else {
			return getDeclaringClass( typeParameter );
		}
	}

	public static TypeVariable<?> getActualTypeParameter(TypeVariable<?> typeParameter) {
		if ( isInternal( typeParameter ) ) {
			return null;
		}
		else {
			return typeParameter;
		}
	}

	public static boolean isInternal(TypeVariable<?> typeParameter) {
		return isAnnotatedObject( typeParameter ) || isArrayElement( typeParameter );
	}

	public static boolean isAnnotatedObject(TypeVariable<?> typeParameter) {
		return typeParameter == AnnotatedObject.INSTANCE;
	}

	public static boolean isArrayElement(TypeVariable<?> typeParameter) {
		return typeParameter instanceof ArrayElement;
	}

	public static String getTypeParameterName(Class<?> clazz, int typeParameterIndex) {
		if ( typeParameterIndex >= clazz.getTypeParameters().length ) {
			throw LOG.getUnableToFindTypeParameterInClass( clazz, typeParameterIndex );
		}
		return clazz.getTypeParameters()[typeParameterIndex].getName();
	}

	public static Integer getTypeParameterIndex(TypeVariable<?> typeParameter) {
		if ( isArrayElement( typeParameter ) ) {
			return null;
		}

		TypeVariable<?>[] typeParameters = typeParameter.getGenericDeclaration().getTypeParameters();
		for ( int i = 0; i < typeParameters.length; i++ ) {
			if ( typeParameter.getName().equals( typeParameters[i].getName() ) ) {
				return i;
			}
		}
		throw LOG.getUnableToFindTypeParameterInClass( (Class<?>) typeParameter.getGenericDeclaration(), typeParameter.getName() );
	}

	public static Type getContainerElementType(Type type, TypeVariable<?> typeParameter) {
		if ( type instanceof ParameterizedType ) {
			Type[] typeArguments = ( (ParameterizedType) type ).getActualTypeArguments();

			return typeArguments[getTypeParameterIndex( typeParameter )];
		}
		else if ( type instanceof GenericArrayType ) {
			return ( (GenericArrayType) type ).getGenericComponentType();
		}
		else {
			return null;
		}
	}

	private static Class<?> getDeclaringClass(TypeVariable<?> typeParameter) {
		return (Class<?>) typeParameter.getGenericDeclaration();
	}
}


text:
package cmd

import (
	"fmt"
	hwinfo "github.com/PiScale/hwinfo-lib"
	"github.com/spf13/cobra"
)

// chassisCmd represents the chassis command
var chassisCmd = &cobra.Command{
	Use:   "chassis",
	Short: "Show information about CHASSIS",
	Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
	Run: func(cmd *cobra.Command, args []string) {
		// TODO: Work your own magic here
		chassis, err := hwinfo.Get_chassis()
		if err == nil {
			fmt.Println("Chassis Manufacturer:", chassis.Manufacturer)
			fmt.Println("Chassis Serial-number:", chassis.SerialNumber)
		} else {
			fmt.Println("Permission denied (you must be root)!", err)
		}
	},
}

func init() {
	showCmd.AddCommand(chassisCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// chassisCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// chassisCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")

}


text:
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="nav_header_vertical_spacing">16dp</dimen>
    <dimen name="nav_header_height">164dp</dimen>

    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>

    <dimen name="header_layout_height">164dp</dimen>
    <dimen name="header_layout_text_padding">16dp</dimen>

    <dimen name="fab_elevation">6dp</dimen>
    <dimen name="fab_border_width">0dp</dimen>
    <dimen name="fab_margin">16dp</dimen>

    <dimen name="recycler_padding_top">8dp</dimen>
    <dimen name="recycler_item_height">72dp</dimen>
    <dimen name="recycler_item_margin_left">16dp</dimen>
    <dimen name="recycler_item_margin_right">16dp</dimen>
    <dimen name="recycler_item_padding">8dp</dimen>
    <dimen name="recycler_item_fav_button_size">16dp</dimen>
    <dimen name="recycler_item_textview_padding_top">16dp</dimen>
    <dimen name="recycler_item_textview_padding_bottom">16dp</dimen>
    <dimen name="profile_photo_height">64dp</dimen>
    <dimen name="profile_photo_width">64dp</dimen>
    <dimen name="app_standard_margin">16dp</dimen>
    <dimen name="nav_drawer_avatar_size">64dp</dimen>
</resources>


text:
define(['backbone', 'mu/cache', 'mu/common'], function(Backbone, cache) {

    var view = Backbone.View.extend({

        initialize: function(options) {
            this.insertDOM = options.insertDOM;
            _.bindAll(this, 'init');
            cache.gets([{
                src: '/app/template/ui_elements/typography.html'
            }], this.init);
        },

        init: function(results) {
            this.tpl = results[0];
            this.render();
        },

        render: function() {
            this.$el.html(this.tpl);
            this.$el.appendTo(this.insertDOM);
            return this;
        }

    });
    return view;
});


text:
package KataRubenToni.CookingSocialNetwork.model;

import java.util.ArrayList;
import java.util.Date;

/**
 * Created by Ruben on 06/12/2015.
 */
public class Recipe implements Likeable{
    private int id;
    private String name;
    private User user;
    private ArrayList<Picture> pictures;
    private ArrayList<Ingredient> ingredients;
    private Date time;
    private String description;
    private ArrayList<Comment> comments;
    private ArrayList<Like> likes;

    public int getId() { return id; }
    public void setId(int id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public User getUser() { return user; }
    public void setUser(User user) { this.user = user; }

    public ArrayList<Picture> getPictures() { return pictures;}
    public void setPictures(ArrayList<Picture> pictures) { this.pictures = pictures; }

    public ArrayList<Ingredient> getIngredients() { return ingredients; }
    public void setIngredients(ArrayList<Ingredient> ingredients) { this.ingredients = ingredients; }

    public Date getTime() { return time; }
    public void setTime(Date time) { this.time = time; }

    public String getDescription() { return description; }
    public void setDescription(String description) { this.description = description; }

    public ArrayList<Comment> getComments() { return comments; }
    public void setComments(ArrayList<Comment> comments) { this.comments = comments; }

    public ArrayList<Like> getLikes() { return likes; }
    public void setLikes(ArrayList<Like> likes) { this.likes = likes; }

    public void like(User u){
        this.likes.add(new Like(u, this));
    }
    public void unlike(User u){
        this.likes.remove(new Like(u,this));
    }

    public boolean equals(Object o) {
        if (o instanceof Recipe) {
            Recipe other = (Recipe) o;
            return this.id == other.id;
        } else return false;
    }
}


text:
package main

import (
	"fmt"
	"math"
)

type Shaper interface {
	Area() float64
}

// Square
type Square struct {
	side float64
}

func (s *Square) Area() float64 { // pointer
	return s.side * s.side
}

// Recangle
type Recangle struct {
	Width, Height float64
}

func (r Recangle) Area() float64 { // non-pointer
	return r.Width * r.Height
}

// Circle
type Circle struct {
	radius float64
}

func (c *Circle) Area() float64 {
	return c.radius * c.radius * math.Pi
}

type Stringer interface {
	String() string
}

func main() {
	basic_try()
	try_to_identify_interface_value_type()
	try_pointer_value_call_methods()

	// 帶入 sort 函數
	// try_sort_MyData()
}

func basic_try() {
	var shapers []Shaper
	shapers = append(shapers, &Square{12.88})   // pointer
	shapers = append(shapers, Recangle{10, 20}) // it's a value
	shapers = append(shapers, &Circle{6})       // pointer

	for i, _ := range shapers {
		showArea(shapers[i])
	}
}

func showArea(shaper Shaper) {
	// interface switch by type(test interface imper's type)
	switch t := shaper.(type) {
	// pointer
	case *Square:
		fmt.Println("Good Square pointer... ")
	case *Circle:
		fmt.Println("Nice Circle pointer... ")
	case *Recangle:
		fmt.Println("Suck Recangle pointer")

	case Recangle: // value
		fmt.Println("Suck Recangle value")

	default:
		fmt.Println("unknow type %T", t)
	}

	// call Area()
	fmt.Println(shaper.Area())
}

func try_to_identify_interface_value_type() {
	// test value(interface value) has implement interface?
	v := &Square{33.77}
	var vInt Shaper
	vInt = v
	if sv, ok := vInt.(Shaper); ok {
		fmt.Printf("YES, imp the Shaper, Area()=%f", sv.Area())
	}

	fmt.Println("")
}

// Methods set with interface 的注意事項
// * Pointer methods 可以被 Pointer 呼叫
// * Value methods 可以被 Value 呼叫
// * Value-Receiver 可以被 Pointer-Value 呼叫, 因為會先 dereferenced
// * Pointer-Receiver 不可以被 Value 呼叫, 因為因為存在 interface-value 中的 value 沒有其 address
type TestInterface interface {
	CallByValue()
	CallByPointer()
}

type TestStruct struct {
}

func (ts TestStruct) RecvIsValue() {
	fmt.Println("RecvIsValue")
}

func (ts *TestStruct) RecvIsPointer() {
	fmt.Println("RecvIsPointer")
}

func (ts TestStruct) CallByValue() {
	fmt.Println("Call by value")
}

func (ts *TestStruct) CallByPointer() {
	fmt.Println("Call by pointer")
}

func try_pointer_value_call_methods() {
	// 以下皆 ok
	fmt.Println("Value: ")
	ts := TestStruct{}
	ts.RecvIsValue()
	ts.RecvIsPointer()

	fmt.Println("Pointer: ")
	p_ts := &TestStruct{}
	p_ts.RecvIsValue()
	p_ts.RecvIsPointer()

	// 使用 varI 來呼叫
	var varI TestInterface
	// varI = ts // ... (no)
	// varI = &ts // ... (ok)
	varI = p_ts
	varI.CallByValue()
	varI.CallByPointer()
}

// 應用 Compare Function as Sort
// type 要提供"比較"和"交換"兩種實作
type Comparee interface {
	Less(another Comparee) bool
}

type MyData struct {
	number int
	id     string
}

func (self *MyData) Less(another Comparee) bool {
	if anotherMyData, ok := another.(*MyData); ok {
		return self.number < anotherMyData.number
	}
	return false
}

func try_sort_MyData() {
	var comparees []Comparee
	comparees = append(comparees, &MyData{5, "five"})
	comparees = append(comparees, &MyData{3, "three"})
	comparees = append(comparees, &MyData{1, "one"})
	comparees = append(comparees, &MyData{2, "two"})
	comparees = append(comparees, &MyData{4, "four"})

	// DoSortWithoutLessFunc(comparees)

	// var lessFunc func(x, y Comparee) bool = func(x, y Comparee) bool {
	// 	myData_x, _ := x.(*MyData)
	// 	myData_y, _ := y.(*MyData)

	// 	return myData_x.number < myData_y.number
	// }
	// DoSortWithLessFunc(comparees, leeFunc)

	DoSortWithLessFunc(comparees,
		func(x, y Comparee) bool { // 直接 define lessFunc
			myData_x, _ := x.(*MyData)
			myData_y, _ := y.(*MyData)

			return myData_x.number < myData_y.number
		})

	for _, c := range comparees {
		if o, ok := c.(*MyData); ok {
			fmt.Println(o.number, ":", o.id)
		}
	}
}

func DoSortWithoutLessFunc(comparees []Comparee) {
	for pass := 1; pass < len(comparees); pass++ {
		for i := 0; i < len(comparees)-pass; i++ {
			if comparees[i+1].Less(comparees[i]) == false {
				comparees[i+1], comparees[i] = comparees[i], comparees[i+1]
			}
		}
	}
}

func DoSortWithLessFunc(comparees []Comparee, lessFunc func(c1, c2 Comparee) bool) {
	for pass := 1; pass < len(comparees); pass++ {
		for i := 0; i < len(comparees)-pass; i++ {
			if lessFunc(comparees[i], comparees[i+1]) {
				comparees[i+1], comparees[i] = comparees[i], comparees[i+1]
			}
		}
	}
}


text:
using UnityEngine;
using UnityEditor;
using System.Collections;

public interface IAnimationWindowImpl
{
	int frame { get; set; }
	bool recording { get; set; }
	AnimationClip activeAnimationClip { get; }
	GameObject activeGameObject { get; }
	GameObject rootGameObject { get; }
	int refresh { get; }
	float currentTime { get; }
	bool playing { get; }

	void InitializeReflection();
	float FrameToTime(int frame);
	float TimeToFrame(float time);
	void CreateDefaultCurve(EditorCurveBinding binding);
	void AddKey(EditorCurveBinding binding, float time);
}


text:
<component name="libraryTable">
  <library name="Maven: com.fasterxml.jackson.core:jackson-annotations:2.5.1">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/core/jackson-annotations/2.5.1/jackson-annotations-2.5.1.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/core/jackson-annotations/2.5.1/jackson-annotations-2.5.1-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/core/jackson-annotations/2.5.1/jackson-annotations-2.5.1-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
<?php

namespace Symfony\Component\Cache\Tests\Adapter;

use Doctrine\DBAL\DriverManager;
use Symfony\Component\Cache\Adapter\PdoAdapter;

/**
 * @group time-sensitive
 */
class PdoDbalAdapterTest extends AdapterTestCase
{
    protected static $dbFile;

    public static function setupBeforeClass()
    {
        if (!extension_loaded('pdo_sqlite')) {
            throw new \PHPUnit_Framework_SkippedTestError('Extension pdo_sqlite required.');
        }

        self::$dbFile = tempnam(sys_get_temp_dir(), 'sf_sqlite_cache');

        $pool = new PdoAdapter(DriverManager::getConnection(array('driver' => 'pdo_sqlite', 'path' => self::$dbFile)));
        $pool->createTable();
    }

    public static function tearDownAfterClass()
    {
        @unlink(self::$dbFile);
    }

    public function createCachePool($defaultLifetime = 0)
    {
        return new PdoAdapter(DriverManager::getConnection(array('driver' => 'pdo_sqlite', 'path' => self::$dbFile)), '', $defaultLifetime);
    }
}


text:
<?php
/**
 * Created by JetBrains PhpStorm.
 * User: cristi
 * Date: 3/27/12
 * Time: 3:55 PM
 */

namespace Rainbow\FileSystemBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class FileSystemController extends Controller
{
    public function loadNodesAction()
    {
        $parent = intval($this->getRequest()->query->get('node'));

        $files = $this->getDoctrine()->getRepository('RainbowFileSystemBundle:Directory')->getFileNodes($parent);
        $dirs = $this->getDoctrine()->getRepository('RainbowFileSystemBundle:Directory')->getDirectoryNodes($parent);

        $nodes = array_merge($files, $dirs);

        return new Response(json_encode($nodes), 200, array(
            'Content-Type' => 'application/json'
        ));
    }
}


text:
extern crate log;

use std::env;
use std::process;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use log::LevelFilter;
use mio::Events;
use simple_logger::SimpleLogger;

use roughenough::config;
use roughenough::config::ServerConfig;
use roughenough::roughenough_version;
use roughenough::server::Server;

fn polling_loop(config: Box<dyn ServerConfig>) {
    let mut server = Server::new(config.as_ref());
    let keep_running = Arc::new(AtomicBool::new(true));

    display_config(&server, config.as_ref());

    let kr_clone = keep_running.clone();
    ctrlc::set_handler(move || kr_clone.store(false, Ordering::Release))
        .expect("failed setting Ctrl-C handler");

    let mut events = Events::with_capacity(1024);

    loop {
        server.process_events(&mut events);

        if !keep_running.load(Ordering::Acquire) {
            warn!("Ctrl-C caught, exiting...");
            return;
        }
    }
}

fn display_config(server: &Server, cfg: &dyn ServerConfig) {
    info!("Long-term public key       : {}", server.get_public_key());
    info!("Max response batch size    : {}", cfg.batch_size());
    info!(
        "Status updates every       : {} seconds",
        cfg.status_interval().as_secs()
    );
    info!(
        "Server listening on        : {}:{}",
        cfg.interface(),
        cfg.port()
    );
    if let Some(hc_port) = cfg.health_check_port() {
        info!(
            "TCP health check           : {}:{}",
            cfg.interface(),
            hc_port
        );
    } else {
        info!("TCP health check           : disabled");
    }
    info!(
        "Client req/resp tracking   : {}",
        if cfg.client_stats_enabled() {
            "per-client"
        } else {
            "aggregated"
        }
    );
    if cfg.fault_percentage() > 0 {
        info!("Deliberate response errors : ~{}%", cfg.fault_percentage());
    } else {
        info!("Deliberate response errors : disabled");
    }
}

pub fn main() {
    SimpleLogger::new()
        .with_level(LevelFilter::Info)
        .with_utc_timestamps()
        .init()
        .unwrap();

    info!("Roughenough server v{} starting", roughenough_version());

    let mut args = env::args();
    if args.len() != 2 {
        error!("Usage: server <ENV | /path/to/config.yaml>");
        process::exit(1);
    }

    let arg1 = args.nth(1).unwrap();
    let config = match config::make_config(&arg1) {
        Err(e) => {
            error!("{:?}", e);
            process::exit(1)
        }
        Ok(ref cfg) if !config::is_valid_config(cfg.as_ref()) => process::exit(1),
        Ok(cfg) => cfg,
    };

    polling_loop(config);

    info!("Done.");
    process::exit(0);
}


text:
package environment

import (
	"github.com/juju/errgo"
)

var (
	maskAny = errgo.MaskFunc(errgo.Any)
)