text:
#include "pch.h"
#include "Simple_Instancing_winrt.h"
#include "BasicTimer.h"

using namespace Windows::ApplicationModel;
using namespace Windows::ApplicationModel::Core;
using namespace Windows::ApplicationModel::Activation;
using namespace Windows::UI::Core;
using namespace Windows::System;
using namespace Windows::Foundation;
using namespace Windows::Graphics::Display;
using namespace concurrency;

PFNGLVERTEXATTRIBDIVISORANGLEPROC glVertexAttribDivisorANGLE;
PFNGLDRAWARRAYSINSTANCEDANGLEPROC glDrawArraysInstancedANGLE;
PFNGLDRAWELEMENTSINSTANCEDANGLEPROC glDrawElementsInstancedANGLE;

///
// Create a simple 2x2 texture image with four different colors
//
GLuint CreateSimpleTexture2D( )
{
   // Texture object handle
   GLuint textureId;

   // 2x2 Image, 3 bytes per pixel (R, G, B)
   GLubyte pixels[4 * 3] =
   {
      255,   0,   0, // Red
        0, 255,   0, // Green
        0,   0, 255, // Blue
      255, 255,   0  // Yellow
   };

   // Use tightly packed data
   glPixelStorei ( GL_UNPACK_ALIGNMENT, 1 );

   // Generate a texture object
   glGenTextures ( 1, &textureId );

   // Bind the texture object
   glBindTexture ( GL_TEXTURE_2D, textureId );

   // Load the texture
   glTexImage2D ( GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, GL_RGB, GL_UNSIGNED_BYTE, pixels );

   // Set the filtering mode
   glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
   glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );

   return textureId;

}

///
// Initialize the shader and program object
//
int Init ( ESContext *esContext )
{
    // init instancing functions
    char *extensionString = (char*) glGetString(GL_EXTENSIONS);

   UserData *userData = (UserData*)esContext->userData;
   GLbyte vShaderStr[] =
      "attribute vec3 a_position;   \n"
      "attribute vec2 a_texCoord;   \n"
      "attribute vec3 a_instancePos;\n"
      "varying vec2 v_texCoord;     \n"
      "void main()                  \n"
      "{                            \n"
      "   gl_Position = vec4(a_position.xyz + a_instancePos.xyz, 1.0); \n"
      "   v_texCoord = a_texCoord;  \n"
      "}                            \n";

   GLbyte fShaderStr[] =
      "precision mediump float;                            \n"
      "varying vec2 v_texCoord;                            \n"
      "uniform sampler2D s_texture;                        \n"
      "void main()                                         \n"
      "{                                                   \n"
      "  gl_FragColor = texture2D( s_texture, v_texCoord );\n"
      "}                                                   \n";

    if (strstr(extensionString, "GL_ANGLE_instanced_arrays"))
    {
        glVertexAttribDivisorANGLE = (PFNGLVERTEXATTRIBDIVISORANGLEPROC)eglGetProcAddress("glVertexAttribDivisorANGLE");
        glDrawArraysInstancedANGLE = (PFNGLDRAWARRAYSINSTANCEDANGLEPROC)eglGetProcAddress("glDrawArraysInstancedANGLE");
        glDrawElementsInstancedANGLE = (PFNGLDRAWELEMENTSINSTANCEDANGLEPROC)eglGetProcAddress("glDrawElementsInstancedANGLE");
    }

   // Load the shaders and get a linked program object
   userData->programObject = esLoadProgram ( (const char*)vShaderStr, (const char*)fShaderStr );

   // Get the attribute locations
   userData->positionLoc = glGetAttribLocation ( userData->programObject, "a_position" );
   userData->texCoordLoc = glGetAttribLocation ( userData->programObject, "a_texCoord" );
   userData->instancePosLoc = glGetAttribLocation ( userData->programObject, "a_instancePos" );

   // Get the sampler location
   userData->samplerLoc = glGetUniformLocation ( userData->programObject, "s_texture" );

   // Load the texture
   userData->textureId = CreateSimpleTexture2D ();

   glClearColor ( 0.0f, 0.0f, 0.0f, 0.0f );
   return TRUE;
}

///
// Draw a triangle using the shader pair created in Init()
//
void Draw ( ESContext *esContext )
{
   UserData *userData = (UserData*) esContext->userData;
   GLfloat vVertices[] = { -0.2f,  0.2f, 0.0f,  // Position 0
                            0.0f,  0.0f,        // TexCoord 0
                           -0.2f, -0.2f, 0.0f,  // Position 1
                            0.0f,  1.0f,        // TexCoord 1
                            0.2f, -0.2f, 0.0f,  // Position 2
                            1.0f,  1.0f,        // TexCoord 2
                            0.2f,  0.2f, 0.0f,  // Position 3
                            1.0f,  0.0f         // TexCoord 3
                         };
   GLushort indices[] = { 0, 1, 2, 0, 2, 3 };

   GLfloat instanceVerts [] = { -0.3f, -0.3f, 0.0f, 0.3f, 0.3f, 0.0f };

   // Set the viewport
   glViewport ( 0, 0, esContext->width, esContext->height );

   // Clear the color buffer
   glClear ( GL_COLOR_BUFFER_BIT );

   // Use the program object
   glUseProgram ( userData->programObject );

   // Load the vertex position
   glVertexAttribPointer ( userData->positionLoc, 3, GL_FLOAT,
                           GL_FALSE, 5 * sizeof(GLfloat), vVertices );
   // Load the texture coordinate
   glVertexAttribPointer ( userData->texCoordLoc, 2, GL_FLOAT,
                           GL_FALSE, 5 * sizeof(GLfloat), &vVertices[3] );

   // Load the instance position
   glVertexAttribPointer ( userData->instancePosLoc, 3, GL_FLOAT,
                           GL_FALSE, 3 * sizeof(GLfloat), instanceVerts );

   glEnableVertexAttribArray ( userData->positionLoc );
   glEnableVertexAttribArray ( userData->texCoordLoc );
   glEnableVertexAttribArray ( userData->instancePosLoc );

   // Enable instancing
   //glVertexAttribDivisorANGLE( userData->instancePosLoc, 1 );

   // Bind the texture
   glActiveTexture ( GL_TEXTURE0 );
   glBindTexture ( GL_TEXTURE_2D, userData->textureId );

   // Set the sampler texture unit to 0
   glUniform1i ( userData->samplerLoc, 0 );

   //glDrawElementsInstancedANGLE ( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices, 2 );
   glDrawElements ( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices );

   eglSwapBuffers ( esContext->eglDisplay, esContext->eglSurface );
}

///
// Cleanup
//
void ShutDown ( ESContext *esContext )
{
   UserData *userData = (UserData*) esContext->userData;

   // Delete texture object
   glDeleteTextures ( 1, &userData->textureId );

   // Delete program object
   glDeleteProgram ( userData->programObject );
}

Simple_Instancing_winrt::Simple_Instancing_winrt() :
	m_windowClosed(false),
	m_windowVisible(true)
{
}

void Simple_Instancing_winrt::Initialize(CoreApplicationView^ applicationView)
{
	applicationView->Activated +=
        ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &Simple_Instancing_winrt::OnActivated);

	CoreApplication::Suspending +=
        ref new EventHandler<SuspendingEventArgs^>(this, &Simple_Instancing_winrt::OnSuspending);

	CoreApplication::Resuming +=
        ref new EventHandler<Platform::Object^>(this, &Simple_Instancing_winrt::OnResuming);

	//m_renderer = ref new CubeRenderer();
    esInitContext ( &m_esContext );
    m_esContext.userData = &m_userData;

    //esMainLoop ( &esContext );

    //ShutDown ( &esContext );
}

void Simple_Instancing_winrt::SetWindow(CoreWindow^ window)
{
    window->SizeChanged +=
        ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &Simple_Instancing_winrt::OnWindowSizeChanged);

    window->VisibilityChanged +=
        ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &Simple_Instancing_winrt::OnVisibilityChanged);

    window->Closed +=
        ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &Simple_Instancing_winrt::OnWindowClosed);

    window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);

    window->PointerPressed +=
        ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &Simple_Instancing_winrt::OnPointerPressed);

    window->PointerMoved +=
        ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &Simple_Instancing_winrt::OnPointerMoved);

    // we need to select the correct DirectX feature level depending on the platform
    // default is for WinRT on Windows 8.0
    ANGLE_D3D_FEATURE_LEVEL featureLevel = ANGLE_D3D_FEATURE_LEVEL::ANGLE_D3D_FEATURE_LEVEL_9_1;

    //m_renderer->Initialize(CoreWindow::GetForCurrentThread());
#if (_MSC_VER >= 1800)
    // WinRT on Windows 8.1 can compile shaders at run time so we don't care about the DirectX feature level
    featureLevel = ANGLE_D3D_FEATURE_LEVEL::ANGLE_D3D_FEATURE_LEVEL_ANY;
#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE)
    // Windows Phone 8.0 uses D3D_FEATURE_LEVEL_9_3
    featureLevel = ANGLE_D3D_FEATURE_LEVEL::ANGLE_D3D_FEATURE_LEVEL_9_3;
#endif

    HRESULT result = CreateWinrtEglWindow(WINRT_EGL_IUNKNOWN(CoreWindow::GetForCurrentThread()), featureLevel, m_eglWindow.GetAddressOf());
    if (SUCCEEDED(result))
    {
        m_esContext.hWnd = m_eglWindow;
        //title, width, and height are unused, but included for backwards compatibility
        if (esCreateWindow(&m_esContext, TEXT("Simple Instancing"), 320, 240, ES_WINDOW_RGB) != GL_TRUE)
            return;

        if (!Init(&m_esContext))
            return;

        esRegisterDrawFunc(&m_esContext, Draw);
    }
}

void Simple_Instancing_winrt::Load(Platform::String^ entryPoint)
{
}

void Simple_Instancing_winrt::Run()
{
	BasicTimer^ timer = ref new BasicTimer();

	while (!m_windowClosed)
	{
		if (m_windowVisible)
		{
			timer->Update();
			CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
            if ( m_esContext.updateFunc != NULL )
                m_esContext.updateFunc ( &m_esContext, timer->Delta );
            if ( m_esContext.drawFunc )
                m_esContext.drawFunc ( &m_esContext );
			//m_renderer->Update(timer->Total, timer->Delta);
			//m_renderer->Render();
			//m_renderer->Present(); // This call is synchronized to the display frame rate.
		}
		else
		{
			CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
		}
	}
}

void Simple_Instancing_winrt::Uninitialize()
{
}

void Simple_Instancing_winrt::OnWindowSizeChanged(CoreWindow^ sender, WindowSizeChangedEventArgs^ args)
{
	//m_renderer->UpdateForWindowSizeChange();
}

void Simple_Instancing_winrt::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
{
	m_windowVisible = args->Visible;
}

void Simple_Instancing_winrt::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
{
	m_windowClosed = true;
    ShutDown ( &m_esContext );
}

void Simple_Instancing_winrt::OnPointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
{
	// Insert your code here.
}

void Simple_Instancing_winrt::OnPointerMoved(CoreWindow^ sender, PointerEventArgs^ args)
{
	// Insert your code here.
}

void Simple_Instancing_winrt::OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args)
{
	CoreWindow::GetForCurrentThread()->Activate();
}

void Simple_Instancing_winrt::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args)
{
	// Save app state asynchronously after requesting a deferral. Holding a deferral
	// indicates that the application is busy performing suspending operations. Be
	// aware that a deferral may not be held indefinitely. After about five seconds,
	// the app will be forced to exit.
	SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();

	create_task([this, deferral]()
	{
		// Insert your code here.

		deferral->Complete();
	});
}

void Simple_Instancing_winrt::OnResuming(Platform::Object^ sender, Platform::Object^ args)
{
	// Restore any data or state that was unloaded on suspend. By default, data
	// and state are persisted when resuming from suspend. Note that this event
	// does not occur if the app was previously terminated.
}

IFrameworkView^ Direct3DApplicationSource::CreateView()
{
    return ref new Simple_Instancing_winrt();
}

[Platform::MTAThread]
int main(Platform::Array<Platform::String^>^)
{
	auto direct3DApplicationSource = ref new Direct3DApplicationSource();
	CoreApplication::Run(direct3DApplicationSource);
	return 0;
}


text:
from fontTools.pens.basePen import BasePen

class RemoveOffcurvesPen(BasePen):
    """
    A simple pen drawing a contour without any offcurves.
    """
    def __init__(self, glyphSet):
        BasePen.__init__(self, glyphSet)

        self._contours = []
        self._components = []

    def _moveTo(self, pt):
        self._contours.append([])
        self._contours[-1].append(("moveTo", pt))

    def _lineTo(self, pt):
        self._contours[-1].append(("lineTo", pt))

    def _curveToOne(self, pt1, pt2, pt3):
        self._contours[-1].append(("lineTo", pt3))

    def qCurveTo(self, *points):
        pt = points[-1]
        self._contours[-1].append(("lineTo", pt))

    def _closePath(self):
        self._contours[-1].append(("closePath", None))

    def _endpath(self):
        self._contours[-1].append(("endPath", None))

    def addComponent(self, baseName, transformation):
        self._components.append((baseName, transformation))

    def draw(self, outPen):
        """
        Draw the stored instructions in an other pen.
        """
        for contour in self._contours:
            for penAttr, pt in contour:
                func = getattr(outPen, penAttr)
                if pt is None:
                    func()
                else:
                    func(pt)

        for baseGlyph, transformation in self._components:
            outPen.addComponent(baseGlyph, transformation)

## get the current glyph
g = CurrentGlyph()

## prepare the glyph for undo
g.prepareUndo("Remove All Offcurves")

## create a pen
pen = RemoveOffcurvesPen(g.getParent())

## draw the glyph in the pen
g.draw(pen)

## clear the glyph
g.clear()

## draw the stored contour from the pen into the emtpy glyph
pen.draw(g.getPen())

## tell the glyph undo watching is over
g.performUndo()

redpajama_set_name: RedPajamaGithub


text:
package org.sparklinedata.druid.client.test

class DruidRewriteOrderTest extends BaseTest {

  test("basicAggOrderByDimension",
    "select l_returnflag, l_linestatus, " +
        "count(*), sum(l_extendedprice) as s, max(ps_supplycost) as m, avg(ps_availqty) as a  " +
        "from orderLineItemPartSupplier " +
        "group by l_returnflag, l_linestatus " +
        "order by l_linestatus",
    1,
    true
  )

  test("basicAggOrderByDimensionLimit",
    "select l_returnflag, l_linestatus, " +
        "count(*), sum(l_extendedprice) as s, max(ps_supplycost) as m, avg(ps_availqty) as a," +
        "count(distinct o_orderkey)  " +
        "from orderLineItemPartSupplier " +
        "group by l_returnflag, l_linestatus " +
        "order by l_returnflag " +
        "limit 2",
    2,
    true
  )

  test("basicAggOrderByMetric",
    "select l_returnflag, l_linestatus, " +
        "count(*), sum(l_extendedprice) as s, max(ps_supplycost) as m, avg(ps_availqty) as a  " +
        "from orderLineItemPartSupplier " +
        "group by l_returnflag, l_linestatus " +
        "order by count(*)",
    1,
    true,
    true
  )

  test("basicAggOrderByMetric2",
    "select l_returnflag, l_linestatus, " +
        "count(*), sum(l_extendedprice) as s, max(ps_supplycost) as m, avg(ps_availqty) as a  " +
        "from orderLineItemPartSupplier " +
        "group by l_returnflag, l_linestatus " +
        "order by s",
    1,
    true
  )

  test("basicAggOrderByLimitFull",
    "select l_returnflag as r, l_linestatus as ls, " +
        "count(*), sum(l_extendedprice) as s, max(ps_supplycost) as m, avg(ps_availqty) as a  " +
        "from orderLineItemPartSupplier " +
        "group by l_returnflag, l_linestatus " +
        "order by s, ls, r " +
        "limit 3",
    1,
    true
  )

  test("basicAggOrderByLimitFull2",
    "select l_returnflag as r, l_linestatus as ls, " +
        "count(*), sum(l_extendedprice) as s, max(ps_supplycost) as m, avg(ps_availqty) as a  " +
        "from orderLineItemPartSupplier " +
        "group by l_returnflag, l_linestatus " +
        "order by m desc, s, r " +
        "limit 3",
    1,
    true
  )

  test("sortNotPushed",
    "select l_returnflag as r, l_linestatus as ls, " +
        "count(*) + 1 as c, sum(l_extendedprice) as s, max(ps_supplycost) as m, " +
      "avg(ps_availqty) as a  " +
        "from orderLineItemPartSupplier " +
        "group by l_returnflag, l_linestatus " +
        "order by c " +
        "limit 3",
    1,
    true
  )

}


text:
package com.eway.payment.rapid.sdk.beans.internal;

import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class RefundDetails {

    @JsonProperty("TransactionID")
    private String originalTransactionID;

    @JsonProperty("TotalAmount")
    private int totalAmount;

    @JsonProperty("InvoiceNumber")
    private String invoiceNumber;

    @JsonProperty("InvoiceDescription")
    private String invoiceDescription;

    @JsonProperty("InvoiceReference")
    private String invoiceReference;

    @JsonProperty("CurrencyCode")
    private String currencyCode;

    /**
     * Return the ID of either the transaction to refund, or the authorisation
     * to cancel
     *
     * @return : original transaction id
     */
    public String getOriginalTransactionID() {
        if (StringUtils.isBlank(originalTransactionID)) {
            return "0";
        }
        return originalTransactionID;
    }

    /**
     * Set original transaction id
     *
     * @param originalTransactionID : the ID of either the transaction to
     * refund, or the authorisation to cancel
     */
    public void setOriginalTransactionID(String originalTransactionID) {
        this.originalTransactionID = originalTransactionID;
    }

    /**
     * Return the total amount to charge the card holder in this transaction in
     * cents
     *
     * @return : the total amount to charge the card holder
     */
    public int getTotalAmount() {
        return totalAmount;
    }

    /**
     * @param totalAmount : the total amount to charge the card holder
     */
    public void setTotalAmount(int totalAmount) {
        this.totalAmount = totalAmount;
    }

    /**
     * Return the merchant's invoice number
     *
     * @return : The merchant's invoice number
     */
    public String getInvoiceNumber() {
        return invoiceNumber;
    }

    /**
     * @param invoiceNumber : The merchant's invoice number
     */
    public void setInvoiceNumber(String invoiceNumber) {
        this.invoiceNumber = invoiceNumber;
    }

    /**
     * Return merchants invoice description
     *
     * @return : merchants invoice description
     */
    public String getInvoiceDescription() {
        return invoiceDescription;
    }

    /**
     * @param invoiceDescription : merchants invoice description
     */
    public void setInvoiceDescription(String invoiceDescription) {
        this.invoiceDescription = invoiceDescription;
    }

    /**
     * Return the merchant's invoice reference
     *
     * @return : The merchant's invoice reference
     */
    public String getInvoiceReference() {
        return invoiceReference;
    }

    /**
     * @param invoiceReference : The merchant's currency
     */
    public void setInvoiceReference(String invoiceReference) {
        this.invoiceReference = invoiceReference;
    }

    /**
     * Return the merchant's currency
     *
     * @return : The merchant's currency
     */
    public String getCurrencyCode() {
        return currencyCode;
    }

    /**
     * @param currencyCode : The merchant's currency
     */
    public void setCurrencyCode(String currencyCode) {
        this.currencyCode = currencyCode;
    }
}


text:
mahediazad.github.io
====================

My Resume


text:
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head lang="fr">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
	<link href='http://fonts.googleapis.com/css?family=Josefin+Slab' rel='stylesheet' type='text/css'>
	<link href='http://fonts.googleapis.com/css?family=Merriweather&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
	<link rel="stylesheet" type="text/css" media="screen" href="{% static 'literature/css/style.css' %}" />
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    <div class="row">
        {% block content %}
        {% endblock %}
    </div>

    {% if GOOGLE_ANALYTICS %}
    <script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

      ga('create', '{{ GOOGLE_ANALYTICS }}', 'auto');
      ga('send', 'pageview');
    </script>
    {% endif %}
</body>
</html>


text:
extern "C" void hardware_watchdog_init()
{
    mock().actualCall("hardware_watchdog_init");
}

extern "C" void hardware_watchdog_kick()
{
    mock().actualCall("hardware_watchdog_kick");
}

extern "C" void hardware_watchdog_deinit()
{
    mock().actualCall("hardware_watchdog_deinit");
}


text:
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from pyparsing import (Word, Literal, ZeroOrMore, Optional,
                       Group, StringEnd, alphas)

from celery.utils import is_iterable
from celery.utils.timeutils import (timedelta_seconds, weekday,
                                    remaining, humanize_seconds)

class schedule(object):
    relative = False

    def __init__(self, run_every=None, relative=False):
        self.run_every = run_every
        self.relative = relative

    def remaining_estimate(self, last_run_at):
        """Returns when the periodic task should run next as a timedelta."""
        return remaining(last_run_at, self.run_every, relative=self.relative)

    def is_due(self, last_run_at):
        """Returns tuple of two items `(is_due, next_time_to_run)`,
        where next time to run is in seconds.

        e.g.

        * `(True, 20)`, means the task should be run now, and the next
            time to run is in 20 seconds.

        * `(False, 12)`, means the task should be run in 12 seconds.

        You can override this to decide the interval at runtime,
        but keep in mind the value of :setting:`CELERYBEAT_MAX_LOOP_INTERVAL`,
        which decides the maximum number of seconds celerybeat can sleep
        between re-checking the periodic task intervals.  So if you
        dynamically change the next run at value, and the max interval is
        set to 5 minutes, it will take 5 minutes for the change to take
        effect, so you may consider lowering the value of
        :setting:`CELERYBEAT_MAX_LOOP_INTERVAL` if responsiveness is of
        importance to you.

        """
        rem_delta = self.remaining_estimate(last_run_at)
        rem = timedelta_seconds(rem_delta)
        if rem == 0:
            return True, timedelta_seconds(self.run_every)
        return False, rem

    def __repr__(self):
        return "<freq: %s>" % humanize_seconds(
                timedelta_seconds(self.run_every))

    def __eq__(self, other):
        if isinstance(other, schedule):
            return self.run_every == other.run_every
        return self.run_every == other

class crontab_parser(object):
    """Parser for crontab expressions. Any expression of the form 'groups'
    (see BNF grammar below) is accepted and expanded to a set of numbers.
    These numbers represent the units of time that the crontab needs to
    run on::

        digit   :: '0'..'9'
        dow     :: 'a'..'z'
        number  :: digit+ | dow+
        steps   :: number
        range   :: number ( '-' number ) ?
        numspec :: '*' | range
        expr    :: numspec ( '/' steps ) ?
        groups  :: expr ( ',' expr ) *

    The parser is a general purpose one, useful for parsing hours, minutes and
    day_of_week expressions.  Example usage::

        >>> minutes = crontab_parser(60).parse("*/15")
        [0, 15, 30, 45]
        >>> hours = crontab_parser(24).parse("*/4")
        [0, 4, 8, 12, 16, 20]
        >>> day_of_week = crontab_parser(7).parse("*")
        [0, 1, 2, 3, 4, 5, 6]

    """

    def __init__(self, max_=60):
        # define the grammar structure
        digits = "0123456789"
        star = Literal('*')
        number = Word(digits) | Word(alphas)
        steps = number
        range_ = number + Optional(Literal('-') + number)
        numspec = star | range_
        expr = Group(numspec) + Optional(Literal('/') + steps)
        extra_groups = ZeroOrMore(Literal(',') + expr)
        groups = expr + extra_groups + StringEnd()

        # define parse actions
        star.setParseAction(self._expand_star)
        number.setParseAction(self._expand_number)
        range_.setParseAction(self._expand_range)
        expr.setParseAction(self._filter_steps)
        extra_groups.setParseAction(self._ignore_comma)
        groups.setParseAction(self._join_to_set)

        self.max_ = max_
        self.parser = groups

    @staticmethod
    def _expand_number(toks):
        try:
            i = int(toks[0])
        except ValueError:
            try:
                i = weekday(toks[0])
            except KeyError:
                raise ValueError("Invalid weekday literal '%s'." % toks[0])
        return [i]

    @staticmethod
    def _expand_range(toks):
        if len(toks) > 1:
            return range(toks[0], int(toks[2]) + 1)
        else:
            return toks[0]

    def _expand_star(self, toks):
        return range(self.max_)

    @staticmethod
    def _filter_steps(toks):
        numbers = toks[0]
        if len(toks) > 1:
            steps = toks[2]
            return [n for n in numbers if n % steps == 0]
        else:
            return numbers

    @staticmethod
    def _ignore_comma(toks):
        return [x for x in toks if x != ',']

    @staticmethod
    def _join_to_set(toks):
        return set(toks.asList())

    def parse(self, cronspec):
        return self.parser.parseString(cronspec).pop()

class crontab(schedule):
    """A crontab can be used as the `run_every` value of a
    :class:`PeriodicTask` to add cron-like scheduling.

    Like a :manpage:`cron` job, you can specify units of time of when
    you would like the task to execute. It is a reasonably complete
    implementation of cron's features, so it should provide a fair
    degree of scheduling needs.

    You can specify a minute, an hour, and/or a day of the week in any
    of the following formats:

    .. attribute:: minute

        - A (list of) integers from 0-59 that represent the minutes of
          an hour of when execution should occur; or
        - A string representing a crontab pattern.  This may get pretty
          advanced, like `minute="*/15"` (for every quarter) or
          `minute="1,13,30-45,50-59/2"`.

    .. attribute:: hour

        - A (list of) integers from 0-23 that represent the hours of
          a day of when execution should occur; or
        - A string representing a crontab pattern.  This may get pretty
          advanced, like `hour="*/3"` (for every three hours) or
          `hour="0,8-17/2"` (at midnight, and every two hours during
          office hours).

    .. attribute:: day_of_week

        - A (list of) integers from 0-6, where Sunday = 0 and Saturday =
          6, that represent the days of a week that execution should
          occur.
        - A string representing a crontab pattern.  This may get pretty
          advanced, like `day_of_week="mon-fri"` (for weekdays only).
          (Beware that `day_of_week="*/2"` does not literally mean
          "every two days", but "every day that is divisible by two"!)

    """

    @staticmethod
    def _expand_cronspec(cronspec, max_):
        """Takes the given cronspec argument in one of the forms::

            int         (like 7)
            basestring  (like '3-5,*/15', '*', or 'monday')
            set         (like set([0,15,30,45]))
            list        (like [8-17])

        And convert it to an (expanded) set representing all time unit
        values on which the crontab triggers.  Only in case of the base
        type being 'basestring', parsing occurs.  (It is fast and
        happens only once for each crontab instance, so there is no
        significant performance overhead involved.)

        For the other base types, merely Python type conversions happen.

        The argument `max_` is needed to determine the expansion of '*'.

        """
        if isinstance(cronspec, int):
            result = set([cronspec])
        elif isinstance(cronspec, basestring):
            result = crontab_parser(max_).parse(cronspec)
        elif isinstance(cronspec, set):
            result = cronspec
        elif is_iterable(cronspec):
            result = set(cronspec)
        else:
            raise TypeError(
                    "Argument cronspec needs to be of any of the "
                    "following types: int, basestring, or an iterable type. "
                    "'%s' was given." % type(cronspec))

        # assure the result does not exceed the max
        for number in result:
            if number >= max_:
                raise ValueError(
                        "Invalid crontab pattern. Valid "
                        "range is 0-%d. '%d' was found." % (max_ - 1, number))

        return result

    def __init__(self, minute='*', hour='*', day_of_week='*',
            nowfun=datetime.now):
        self._orig_minute = minute
        self._orig_hour = hour
        self._orig_day_of_week = day_of_week
        self.hour = self._expand_cronspec(hour, 24)
        self.minute = self._expand_cronspec(minute, 60)
        self.day_of_week = self._expand_cronspec(day_of_week, 7)
        self.nowfun = nowfun

    def __repr__(self):
        return "<crontab: %s %s %s (m/h/d)>" % (self._orig_minute or "*",
                                                self._orig_hour or "*",
                                                self._orig_day_of_week or "*")

    def __reduce__(self):
        return (self.__class__, (self._orig_minute,
                                 self._orig_hour,
                                 self._orig_day_of_week), None)

    def remaining_estimate(self, last_run_at):
        """Returns when the periodic task should run next as a timedelta."""
        weekday = last_run_at.isoweekday()
        if weekday == 7:    # Sunday is day 0, not day 7.
            weekday = 0

        execute_this_hour = (weekday in self.day_of_week and
                                last_run_at.hour in self.hour and
                                last_run_at.minute < max(self.minute))

        if execute_this_hour:
            next_minute = min(minute for minute in self.minute
                                        if minute > last_run_at.minute)
            delta = relativedelta(minute=next_minute,
                                  second=0,
                                  microsecond=0)
        else:
            next_minute = min(self.minute)

            execute_today = (weekday in self.day_of_week and
                                 last_run_at.hour < max(self.hour))

            if execute_today:
                next_hour = min(hour for hour in self.hour
                                        if hour > last_run_at.hour)
                delta = relativedelta(hour=next_hour,
                                      minute=next_minute,
                                      second=0,
                                      microsecond=0)
            else:
                next_hour = min(self.hour)
                next_day = min([day for day in self.day_of_week
                                    if day > weekday] or
                               self.day_of_week)
                add_week = next_day == weekday

                delta = relativedelta(weeks=add_week and 1 or 0,
                                      weekday=(next_day - 1) % 7,
                                      hour=next_hour,
                                      minute=next_minute,
                                      second=0,
                                      microsecond=0)

        return remaining(last_run_at, delta, now=self.nowfun())

    def is_due(self, last_run_at):
        """Returns tuple of two items `(is_due, next_time_to_run)`,
        where next time to run is in seconds.

        See :meth:`celery.schedules.schedule.is_due` for more information.

        """
        rem_delta = self.remaining_estimate(last_run_at)
        rem = timedelta_seconds(rem_delta)
        due = rem == 0
        if due:
            rem_delta = self.remaining_estimate(last_run_at=self.nowfun())
            rem = timedelta_seconds(rem_delta)
        return due, rem

    def __eq__(self, other):
        if isinstance(other, crontab):
            return (other.day_of_week == self.day_of_week and
                    other.hour == self.hour and
                    other.minute == self.minute)
        return other is self

def maybe_schedule(s, relative=False):
    if isinstance(s, int):
        s = timedelta(seconds=s)
    if isinstance(s, timedelta):
        return schedule(s, relative)
    return s


text:
package com.cohesiva.deserialize.web;

import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 *
 * @author Mariusz
 */
@SpringBootApplication
public class ApplicationConfig {

}


text:
// The MIT License
//
// Copyright (c) 2012-2015 Jordan E. Terrell
//
// 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.

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using NUnit.Framework;
using iSynaptic.Commons.Linq;

namespace iSynaptic.Commons
{
    [MaybeMonadContractTestFixture(typeof(Result<,>), typeof(Result))]
    [MaybeMonadContractTestFixture(typeof(Maybe<>), typeof(Maybe))]
    public class MaybeMonadContractTests : MonadicLawsTestFixture
    {
        public MaybeMonadContractTests(Type monadType, Type extensionType)
            : base(monadType, extensionType)
        {
            ValueType = typeof (string);

            ClosedMonadType = MonadType.MakeGenericType(GetTypeArguments(ValueType));
        }

        public Type ClosedMonadType { get; private set; }

        public Type ValueType { get; private set; }

        #region Core Type Contract

        [Test]
        public void HasPublicConstructor_ThatTakesValue()
        {
            MonadType.GetConstructorsWithParameters()
                .Single(x => x.Parameters.Count == 1 &&
                             x.Parameters[0].ParameterType == OpenValueType);
        }

        [Test]
        public void HasPublicConstructor_ThatTakesAFunctionThatYieldsTheClosedMonadType()
        {
            MonadType.GetConstructorsWithParameters()
                .Single(x => x.Parameters.Count == 1 &&
                             x.Parameters[0].ParameterType == typeof (Func<>).MakeGenericType(MonadType));
        }

        [Test]
        public void HasValue_ReturnsFalse_WhenProvidedWithNullValue()
        {
            var c = ClosedMonadType.GetConstructorsWithParameters()
                .Single(x => x.Parameters.Count == 1 &&
                             x.Parameters[0].ParameterType == ValueType)
                .Method;

            IMaybe maybe = c.Invoke(new object[]{null}) as IMaybe;

            Assert.IsNotNull(maybe);
            Assert.IsFalse(maybe.HasValue);
        }

        [Test]
        public void Value_ThrowsInvalidOperationException_WhenConstructedWithNullValue()
        {
            var c = ClosedMonadType.GetConstructorsWithParameters()
                .Single(x => x.Parameters.Count == 1 &&
                             x.Parameters[0].ParameterType == ValueType)
                .Method;

            IMaybe maybe = c.Invoke(new object[] { null }) as IMaybe;

            Assert.IsNotNull(maybe);
            Assert.Throws<InvalidOperationException>(() => { object value = maybe.Value; });
        }

        [Test]
        public void Constructor_ThrowsArgumentNullException_WhenConstructedWithNullComputationFunction()
        {
            var c = ClosedMonadType.GetConstructorsWithParameters()
                .Single(x => x.Parameters.Count == 1 &&
                             x.Parameters[0].ParameterType == typeof(Func<>).MakeGenericType(ClosedMonadType))
                .Method;

            var ex = Assert.Throws<TargetInvocationException>(() => c.Invoke(new object[] {null}));
            var anex = ex.InnerException as ArgumentNullException;

            Assert.IsNotNull(anex);
            Assert.AreEqual("computation", anex.ParamName);
        }

        [Test]
        public void HasValue_ReturnsFalse_WhenConstructedWithParameterlessConstructor()
        {
            IMaybe maybe = Activator.CreateInstance(ClosedMonadType) as IMaybe;

            Assert.IsNotNull(maybe);
            Assert.IsFalse(maybe.HasValue);
        }

        [Test]
        public void Value_ViaNonGenericInterface_ThrowsInvalidOperationException_WhenConstructedWithParameterlessConstructor()
        {
            IMaybe maybe = Activator.CreateInstance(ClosedMonadType) as IMaybe;

            Assert.IsNotNull(maybe);
            Assert.Throws<InvalidOperationException>(() => { object value = maybe.Value; });
        }

        [Test]
        public void Value_ViaGenericInterface_ThrowsInvalidOperationException_WhenConstructedWithParameterlessConstructor()
        {
            IMaybe<string> maybe = Activator.CreateInstance(ClosedMonadType) as IMaybe<string>;

            Assert.IsNotNull(maybe);
            Assert.Throws<InvalidOperationException>(() => { object value = maybe.Value; });
        }

        [Test]
        public void Value_ViaNonGenericInterface_ThrowsInvalidOperationException_WhenUninitializedObjectCreated()
        {
            IMaybe maybe = FormatterServices.GetSafeUninitializedObject(ClosedMonadType) as IMaybe;

            Assert.IsNotNull(maybe);
            Assert.Throws<InvalidOperationException>(() => { object value = maybe.Value; });
        }

        [Test]
        public void Value_ViaGenericInterface_ThrowsInvalidOperationException_WhenUninitializedObjectCreated()
        {
            IMaybe<string> maybe = FormatterServices.GetSafeUninitializedObject(ClosedMonadType) as IMaybe<string>;

            Assert.IsNotNull(maybe);
            Assert.Throws<InvalidOperationException>(() => { object value = maybe.Value; });
        }

        [Test]
        public void ReturnsValue_ProvidedThroughConstructor()
        {
            const string expected = "Monads rocks!";

            IMaybe maybe = Activator.CreateInstance(ClosedMonadType, expected) as IMaybe;

            Assert.IsNotNull(maybe);
            Assert.IsTrue(maybe.HasValue);
            Assert.AreEqual(expected, maybe.Value);
        }

        [Test]
        public void ReturnsNoValue_ProvidedThroughComputation()
        {
            object computationValue = Activator.CreateInstance(ClosedMonadType);
            object computation = Expression.Lambda(typeof(Func<>).MakeGenericType(ClosedMonadType), Expression.Constant(computationValue))
                .Compile();

            IMaybe maybe = Activator.CreateInstance(ClosedMonadType, computation) as IMaybe;

            Assert.IsNotNull(maybe);
            Assert.IsFalse(maybe.HasValue);
        }

        [Test]
        public void ReturnsValue_ProvidedThroughComputation()
        {
            const string expected = "Monads rocks!";

            object computationValue = Activator.CreateInstance(ClosedMonadType, expected);
            object computation = Expression.Lambda(typeof(Func<>).MakeGenericType(ClosedMonadType), Expression.Constant(computationValue))
                .Compile();

            IMaybe maybe = Activator.CreateInstance(ClosedMonadType, computation) as IMaybe;

            Assert.IsNotNull(maybe);
            Assert.IsTrue(maybe.HasValue);
            Assert.AreEqual(expected, maybe.Value);
        }

        [Test]
        public void ReturnsValue_IfTypeIsUnit()
        {
            IMaybe maybe = FormatterServices.GetSafeUninitializedObject(MonadType.MakeGenericType(GetTypeArguments(typeof(Unit)))) as IMaybe;

            Assert.IsNotNull(maybe);
            Assert.IsTrue(maybe.HasValue);
            Assert.AreEqual(new Unit(), maybe.Value);
        }

        [Test]
        public void ImplementsNonGenericIMaybeInterface()
        {
            Assert.IsTrue(typeof(IMaybe).IsAssignableFrom(ClosedMonadType));
        }

        [Test]
        public void ImplementsGenericIMaybeInterface()
        {
            Assert.IsTrue(typeof(IMaybe<string>).IsAssignableFrom(ClosedMonadType));
        }

        [Test]
        public void ImplementsIEquatableOfValueType()
        {
            Assert.IsTrue(typeof(IEquatable<string>).IsAssignableFrom(ClosedMonadType));
        }

        [Test]
        public void ImplementsIEquatableOfMonadType()
        {
            Assert.IsTrue(typeof(IEquatable<>).MakeGenericType(ClosedMonadType).IsAssignableFrom(ClosedMonadType));
        }

        [Test]
        public void NoMethods_OnMonadType_ContainOptionalArguments()
        {
            var methods = ClosedMonadType.GetMethodsWithParameters().ToArray();

            Assert.IsTrue(methods.Length > 0);

            var outcome = methods.SelectMany(x => x.Parameters.Select(y =>
                    Outcome.FailIf(y.IsDefined(typeof(OptionalAttribute), true), String.Format("{0}.{1}.{2} is optional.", ClosedMonadType.Name, x.Method.Name, y.Name))))
                .Combine();

            Assert.IsTrue(outcome.WasSuccessful, outcome.Observations.Delimit("\r\n"));
        }

        //TODO: Refactor extension method to remove optional arguments

        //[Test]
        //public void NoMethods_OnExtensionType_ContainOptionalArguments()
        //{
        //    var methods = ExtensionType.GetMethodsWithParameters().ToArray();

        //    Assert.IsTrue(methods.Length > 0);

        //    var outcome = methods.SelectMany(x => x.Parameters.Select(y =>
        //            Outcome.FailIf(y.IsDefined(typeof(OptionalAttribute), true), String.Format("{0}.{1}.{2} is optional.", ClosedMonadType.Name, x.Method.Name, y.Name))))
        //        .Combine();

        //    Assert.IsTrue(outcome.WasSuccessful, outcome.Observations.Delimit("\r\n"));
        //}

        [Test]
        public void OverridesObjectEquals()
        {
            var equals = ClosedMonadType.GetMethodsWithParameters()
                .Where(x => x.Method.Name == "Equals")
                .Single(x => x.Parameters.Count == 1 && x.Parameters[0].ParameterType == typeof (object));

            Assert.IsTrue(equals.Method.DeclaringType == ClosedMonadType);
        }

        [Test]
        public void OverridesObjectGetHashCode()
        {
            var equals = ClosedMonadType.GetMethodsWithParameters()
                .Where(x => x.Method.Name == "GetHashCode")
                .Single(x => x.Parameters.Count == 0);

            Assert.IsTrue(equals.Method.DeclaringType == ClosedMonadType);
        }

        [Test]
        public void ImplementsEqualityOperator_WithLeftAndRightArgumentsAreMonadTypes()
        {
            Assert.IsNotNull(ClosedMonadType.GetMethodsWithParameters()
                .Where(x => x.Method.Name == "op_Equality")
                .Where(x => x.Parameters.Count == 2)
                .Where(x => x.Parameters[0].ParameterType == ClosedMonadType)
                .Single(x => x.Parameters[1].ParameterType == ClosedMonadType));
        }

        [Test]
        public void ImplementsInequalityOperator_WithLeftAndRightArgumentsAreMonadTypes()
        {
            Assert.IsNotNull(ClosedMonadType.GetMethodsWithParameters()
                .Where(x => x.Method.Name == "op_Inequality")
                .Where(x => x.Parameters.Count == 2)
                .Where(x => x.Parameters[0].ParameterType == ClosedMonadType)
                .Single(x => x.Parameters[1].ParameterType == ClosedMonadType));
        }

        [Test]
        public void ImplementsEqualityOperator_WithLeftAsMonadTypeAndRightAsValueType()
        {
            Assert.IsNotNull(ClosedMonadType.GetMethodsWithParameters()
                .Where(x => x.Method.Name == "op_Equality")
                .Where(x => x.Parameters.Count == 2)
                .Where(x => x.Parameters[0].ParameterType == ClosedMonadType)
                .Single(x => x.Parameters[1].ParameterType == ValueType));
        }

        [Test]
        public void ImplementsInequalityOperator_WithLeftAsMonadTypeAndRightAsValueType()
        {
            Assert.IsNotNull(ClosedMonadType.GetMethodsWithParameters()
                .Where(x => x.Method.Name == "op_Inequality")
                .Where(x => x.Parameters.Count == 2)
                .Where(x => x.Parameters[0].ParameterType == ClosedMonadType)
                .Single(x => x.Parameters[1].ParameterType == ValueType));
        }

        [Test]
        public void ImplementsEqualityOperator_WithLeftAsValueTypeAndRightAsMonadType()
        {
            Assert.IsNotNull(ClosedMonadType.GetMethodsWithParameters()
                .Where(x => x.Method.Name == "op_Equality")
                .Where(x => x.Parameters.Count == 2)
                .Where(x => x.Parameters[0].ParameterType == ValueType)
                .Single(x => x.Parameters[1].ParameterType == ClosedMonadType));
        }

        [Test]
        public void ImplementsInequalityOperator_WithLeftAsValueTypeAndRightAsMonadType()
        {
            Assert.IsNotNull(ClosedMonadType.GetMethodsWithParameters()
                .Where(x => x.Method.Name == "op_Inequality")
                .Where(x => x.Parameters.Count == 2)
                .Where(x => x.Parameters[0].ParameterType == ValueType)
                .Single(x => x.Parameters[1].ParameterType == ClosedMonadType));
        }

        [Test]
        public void MonadType_ImplementsExplicitConversionOperatorToValueType()
        {
            Assert.IsNotNull(ClosedMonadType.GetMethodsWithParameters()
                .Where(x => x.Method.Name == "op_Explicit")
                .Where(x => x.Parameters.Count == 1)
                .Where(x => x.Parameters[0].ParameterType == ClosedMonadType)
                .Single(x => x.Method.ReturnType == ValueType));
        }

        [Test]
        public void MonadType_ImplementsImplicitConversionOperatorToValueType()
        {
            Assert.IsNotNull(MonadType.GetMethodsWithParameters()
                .Where(x => x.Method.Name == "op_Implicit")
                .Where(x => x.Parameters.Count == 1)
                .Where(x => x.Parameters[0].ParameterType == MonadType.MakeGenericType(GetTypeArguments(typeof(Unit))))
                .Single(x => x.Method.ReturnType == MonadType));
        }

        #endregion

        #region Defer

        [Test]
        public void Defer_WithFunctionThatReturnsValue()
        {
            // public static M<T> Defer<T>(Func<T> computation)
            var spec = MethodSpecificationBuilder
                .Named("Defer")
                .IsPublic()
                .IsStatic()
                .IsNotExtensionMethod()
                .HasGenericArguments(1)
                .HasParameters(1)

                .GenericArgument(ga => ga
                    .Named("T")
                    .AtIndex(0)
                    .CanBeReferenceType()
                    .CanBeValueType())

                .Parameter((m, p) => p
                    .Named("computation")
                    .AtIndex(0)
                    .Type(t => t
                        .IsEqualTo(typeof(Func<>).MakeGenericType(m.GetGenericArguments()[0]))))

                .Returns((m, t) => t
                    .IsEqualTo(MonadType.MakeGenericType(m.ReturnType.GetGenericArguments())));

            Assert.IsNotNull(ExtensionType.GetMethods().Single(spec.ToFunc()));
        }

        [Test]
        public void Defer_WithFunctionThatReturnsNullableStructValue() // M<T> Defer(Func<T?>)
        {
            var spec = MethodSpecificationBuilder
                .Named("Defer")
                .IsPublic()
                .IsStatic()
                .IsNotExtensionMethod()
                .IsOpenGeneric()

                .HasGenericArguments(1)
                .GenericArgument(ga => ga
                    .Named("T")
                    .AtIndex(0)
                    .MustBeValueType())

                .HasParameters(1)
                .Parameter((m, p) => p
                    .Named("computation")
                    .AtIndex(0)
                    .Type(t => t
                        .IsEqualTo(typeof(Func<>).MakeGenericType(typeof(Nullable<>).MakeGenericType(m.GetGenericArguments()[0])))))

                .Returns((m, t) => t
                    .IsEqualTo(MonadType.MakeGenericType(m.ReturnType.GetGenericArguments())));

            Assert.IsNotNull(ExtensionType.GetMethods().Single(spec.ToFunc()));
        }

        [Test]
        public void Defer_WithFunctionThatReturnsMonadType() // M<T> Defer<T>(Func<M<T>>)
        {
            var spec = MethodSpecificationBuilder
                .Named("Defer")
                .IsStatic()
                .IsNotExtensionMethod()
                .IsPublic()
                .IsOpenGeneric()

                .GenericArgument(ga => ga
                    .Named("T")
                    .AtIndex(0)
                    .CanBeReferenceType()
                    .CanBeValueType())

                .HasParameters(1)
                .Parameter((m, p) => p
                    .Named("computation")
                    .AtIndex(0)
                    .Type(t => t.IsEqualTo(typeof(Func<>).MakeGenericType(m.ReturnType))))

                .Returns((m, t) => t
                    .IsEqualTo(MonadType.MakeGenericType(m.ReturnType.GetGenericArguments())));

            Assert.IsNotNull(ExtensionType.GetMethods().Single(spec.ToFunc()));
        }

        #endregion

        [Test]
        public void If_WithBooleanAndThenMonadType() // M<T> If<T>(Boolean, M<T>)
        {
            var spec = MethodSpecificationBuilder
                .Named("If")
                .IsStatic()
                .IsPublic()
                .IsNotExtensionMethod()
                .IsOpenGeneric()

                .GenericArgument(ga => ga
                    .Named("T")
                    .AtIndex(0)
                    .CanBeReferenceType()
                    .CanBeValueType())

                .HasParameters(2)
                .Parameter((m, p) => p
                    .Named("predicate")
                    .AtIndex(0)
                    .Type(t => t.IsEqualTo(typeof(bool))))

                .Parameter((m, p) => p
                    .Named("then")
                    .AtIndex(1)
                    .Type(t => t.IsEqualTo(m.ReturnType)))

                    .Returns((m, t) => t
                    .IsEqualTo(MonadType.MakeGenericType(m.ReturnType.GetGenericArguments())));

            Assert.IsNotNull(ExtensionType.GetMethods().Single(spec.ToFunc()));
        }

        [Test]
        public void If_WithFuncOfBooleanAndThenMonadType() // M<T> If<T>(Func<Boolean>, M<T>)
        {
            var spec = MethodSpecificationBuilder
                .Named("If")
                .IsStatic()
                .IsPublic()
                .IsNotExtensionMethod()
                .IsOpenGeneric()

                .GenericArgument(ga => ga
                    .Named("T")
                    .AtIndex(0)
                    .CanBeReferenceType()
                    .CanBeValueType())

                .HasParameters(2)
                .Parameter((m, p) => p
                    .Named("predicate")
                    .AtIndex(0)
                    .Type(t => t.IsEqualTo(typeof(Func<bool>))))

                .Parameter((m, p) => p
                    .Named("then")
                    .AtIndex(1)
                    .Type(t => t.IsEqualTo(m.ReturnType)))

                    .Returns((m, t) => t
                    .IsEqualTo(MonadType.MakeGenericType(m.ReturnType.GetGenericArguments())));

            Assert.IsNotNull(ExtensionType.GetMethods().Single(spec.ToFunc()));
        }

        [Test]
        public void If_WithBooleanAndThenAndElseMonadType() // M<T> If<T>(Boolean, M<T>, M<T>)
        {
            var spec = MethodSpecificationBuilder
                .Named("If")
                .IsStatic()
                .IsPublic()
                .IsNotExtensionMethod()
                .IsOpenGeneric()

                .GenericArgument(ga => ga
                    .Named("T")
                    .AtIndex(0)
                    .CanBeReferenceType()
                    .CanBeValueType())

                .HasParameters(3)
                .Parameter((m, p) => p
                    .Named("predicate")
                    .AtIndex(0)
                    .Type(t => t.IsEqualTo(typeof(bool))))

                .Parameter((m, p) => p
                    .Named("then")
                    .AtIndex(1)
                    .Type(t => t.IsEqualTo(m.ReturnType)))

                .Parameter((m, p) => p
                    .Named("else")
                    .AtIndex(2)
                    .Type(t => t.IsEqualTo(m.ReturnType)))

                .Returns((m, t) => t
                    .IsEqualTo(MonadType.MakeGenericType(m.ReturnType.GetGenericArguments())));

            Assert.IsNotNull(ExtensionType.GetMethods().Single(spec.ToFunc()));
        }

        [Test]
        public void If_WithFuncOfBooleanAndThenAndElseMondadType() // M<T> If<T>(Func<Boolean>, M<T>, M<T>)
        {
            var spec = MethodSpecificationBuilder
                .Named("If")
                .IsStatic()
                .IsPublic()
                .IsNotExtensionMethod()
                .IsOpenGeneric()

                .GenericArgument(ga => ga
                    .Named("T")
                    .AtIndex(0)
                    .CanBeReferenceType()
                    .CanBeValueType())

                .HasParameters(3)
                .Parameter((m, p) => p
                    .Named("predicate")
                    .AtIndex(0)
                    .Type(t => t.IsEqualTo(typeof(Func<bool>))))

                .Parameter((m, p) => p
                    .Named("then")
                    .AtIndex(1)
                    .Type(t => t.IsEqualTo(m.ReturnType)))

                .Parameter((m, p) => p
                    .Named("else")
                    .AtIndex(2)
                    .Type(t => t.IsEqualTo(m.ReturnType)))

                .Returns((m, t) => t
                    .IsEqualTo(MonadType.MakeGenericType(m.ReturnType.GetGenericArguments())));

            Assert.IsNotNull(ExtensionType.GetMethods().Single(spec.ToFunc()));
        }
    }

    public abstract class MonadicLawsTestFixture
    {
        protected MonadicLawsTestFixture(Type monadType, Type extensionType)
        {
            MonadType = Guard.NotNull(monadType, "monadType");
            ExtensionType = Guard.NotNull(extensionType, "extensionType");

            OpenValueType = MonadType.GetGenericArguments()[0];
        }

        //private MethodInfo GetReturn()
        //{
        //    return ExtensionType.GetMethodsWithParameters()
        //        .Where(x => x.Method.Name == "Return")
        //        .Where(x => x.Method.IsStatic)
        //        .Where(x => x.Method.IsGenericMethodDefinition)
        //        .Where(x => !x.GenericArguments[0].GenericParameterAttributes.Contains(GenericParameterAttributes.NotNullableValueTypeConstraint))
        //        .Where(x => x.Parameters.Count == 1)
        //        .Where(x => x.Method.ReturnType == MonadType.MakeGenericType(x.Method.ReturnType.GetGenericArguments()))
        //        .Select(x => x.Method)
        //        .Single();
        //}

        //private MethodInfo GetBind()
        //{
        //    return ExtensionType.GetMethodsWithParameters()
        //        .Where(x => x.Method.Name == "Bind")
        //        .Where(x => x.Method.IsStatic)
        //        .Where(x => x.Method.IsGenericMethodDefinition)
        //        .Where(x => x.Parameters.Count == 2)
        //        .Where(x => x.Parameters[0].ParameterType == MonadType.MakeGenericType(x.Parameters[0].ParameterType.GetGenericArguments()))
        //        .Where(x => x.Parameters[1].ParameterType == typeof(Func<,>).MakeGenericType(new[]{x.Parameters[0].ParameterType.GetGenericArguments()[0]}.Concat(new [] {MonadType.MakeGenericType(x.Method.ReturnType.GetGenericArguments().ToArray())}).ToArray()))
        //        .Where(x => x.Method.ReturnType == MonadType.MakeGenericType(x.Method.ReturnType.GetGenericArguments()))
        //        .Select(x => x.Method)
        //        .Single();
        //}

        //[Test]
        //public void Monadic_Law_1()
        //{
        //    var @return = GetReturn();
        //    var bind = GetBind();

        //    Assert.Inconclusive();
        //}

        [Test]
        public void MonadType_IsNotNull()
        {
            Assert.IsNotNull(MonadType);
        }

        [Test]
        public void ExtensionType_IsNotNull()
        {
            Assert.IsNotNull(ExtensionType);
        }

        [Test]
        public void MonadType_IsGenericTypeDefinition()
        {
            Assert.IsTrue(MonadType.IsGenericTypeDefinition);
        }

        [Test]
        public void MonadType_IsAStruct()
        {
            Assert.IsTrue(MonadType.IsValueType);
        }

        [Test]
        public void MonadType_FirstTypeArgument_IsTypeOfUnderlyingValue()
        {
            // First argument of the type of the underlying Value
            var method = MonadType.GetMethodsWithParameters()
                .Where(x => x.Method.IsSpecialName && x.Method.Name == "get_Value")
                .Single(x => x.Parameters.Count == 0)
                .Method;

            Assert.IsTrue(method.ReturnType == OpenValueType);
        }

        [Test]
        public void ExtensionType_IsStaticClass()
        {
            Assert.IsTrue(ExtensionType.IsSealed);
            Assert.IsTrue(ExtensionType.IsAbstract);
            Assert.IsTrue(ExtensionType.IsClass);
        }

        [Test]
        public void ExtensionType_IsNotGenericType()
        {
            Assert.IsFalse(ExtensionType.IsGenericType);
            Assert.IsFalse(ExtensionType.IsGenericTypeDefinition);
        }

        protected Type[] GetTypeArguments(Type firstTypeArgument)
        {
            Guard.NotNull(firstTypeArgument, "firstTypeArgument");

            return new[] { firstTypeArgument }.Concat(Enumerable.Repeat(typeof(Unit), MonadType.GetGenericArguments().Length - 1)).ToArray();
        }

        public Type MonadType { get; private set; }
        public Type ExtensionType { get; private set; }

        public Type OpenValueType { get; private set; }
    }

    internal class MaybeMonadContractTestFixtureAttribute : TestFixtureAttribute
    {
        public MaybeMonadContractTestFixtureAttribute(Type monadType, Type extensionType)
            : base(monadType, extensionType)
        {
            TypeArgs = new Type[0];
        }
    }
}


text:
@interface FTJSONRequestOperation : AFJSONRequestOperation

@property (nonatomic, strong) id <FTAPIDataAbstractObject> dataObject;

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<BuildSequence>
    <Change hash="d812da5af0d0bb0cd81fe499fa0cd3b630d2cafb" upgrade="true" drop="false" snapshot="false"/>
</BuildSequence>


text:
// <auto-generated></auto-generated>

namespace NewtonsoftFork.Json.Serialization
{
    /// <summary>
    /// The default naming strategy. Property names and dictionary keys are unchanged.
    /// </summary>
    [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
    [System.CodeDom.Compiler.GeneratedCode("OBeautifulCode.Serialization.Json", "See package version number")]
    public class DefaultNamingStrategy : NamingStrategy
    {
        /// <summary>
        /// Resolves the specified property name.
        /// </summary>
        /// <param name="name">The property name to resolve.</param>
        /// <returns>The resolved property name.</returns>
        protected override string ResolvePropertyName(string name)
        {
            return name;
        }
    }
}


text:
layout: docs
title: Clearfix
description: Quickly and easily clear floated content within a container by adding a clearfix utility.
group: utilities
toc: true
---

Easily clear `float`s by adding `.clearfix` **to the parent element**. Utilizes [the micro clearfix](http://nicolasgallagher.com/micro-clearfix-hack/) as popularized by Nicolas Gallagher. Can also be used as a mixin.

{% highlight html %}

...

{% endhighlight %}

{% highlight scss %}
// Mixin itself
@mixin clearfix() {
  &::after {
    display: block;
    content: "";
    clear: both;
  }
}

// Usage as a mixin
.element {
  @include clearfix;
}
{% endhighlight %}

The following example shows how the clearfix can be used. Without the clearfix the wrapping div would not span around the buttons which would cause a broken layout.

{% example html %}

  <button class="btn btn-secondary float-left">Example Button floated left</button>
  <button class="btn btn-secondary float-right">Example Button floated right</button>

{% endexample %}


text: require 'InactiveFootballPlayers'


text:
Add mercury-regions to a view and save the content to the database.

## Installation

Add this line to your application's Gemfile:

    gem 'mercury_rails_regions'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install mercury_rails_regions

Run the rails generator to add the page model

    $ rails generate mercury_regions:install:pages_model
    $ rails db:migrate

## Usage

    To add an editable region to your view use the following code

``` erb
<h1>About</h1>
<%= mercury_region "about-introduction" %>
<aside>
	<%= mercury_region "about-aside" %>
</aside>
```

When current_admin_user.signed_in? and you go to `/editor/about` this will render as follows:
``` html
<h1>About</h1>
<div class="mercury-region" data-mercury="full" id="about-introduction" contenteditable="true">
	contents intro
</div>
<aside>
	<div class="mercury-region" data-mercury="full" id="about-aside" contenteditable="true">
	contents aside
</div>
</aside>
```

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
Add this mixin to a view to override `get_queryset` to automatically filter
records by `ids[]=1&ids[]=2` in URL query params.

## rest_framework_json_api.renderers.JSONRenderer

The `JSONRenderer` exposes a number of methods that you may override if you need
highly custom rendering control.

#### extract_attributes

`extract_attributes(fields, resource)`

Builds the `attributes` object of the JSON API resource object.

#### extract_relationships(fields, resource, resource_instance)

Builds the `relationships` top level object based on related serializers.

#### extract_included(fields, resource, resource_instance, included_resources)

Adds related data to the top level `included` key when the request includes `?include=example,example_field2`

#### extract_meta(serializer, resource)

Gathers the data from serializer fields specified in `meta_fields` and adds it to the `meta` object.

#### extract_root_meta(serializer, resource, meta)

Calls a `get_root_meta` function on a serializer, if it exists.

#### build_json_resource_obj(fields, resource, resource_instance, resource_name)

Builds the resource object (type, id, attributes) and extracts relationships.


text:
function CoreModule::onCreate(%this)
{

   // ----------------------------------------------------------------------------
   // Initialize core sub system functionality such as audio, the Canvas, PostFX,
   // rendermanager, light managers, etc.
   //
   // Note that not all of these need to be initialized before the client, although
   // the audio should and the canvas definitely needs to be.  I've put things here
   // to distinguish between the purpose and functionality of the various client
   // scripts.  Game specific script isn't needed until we reach the shell menus
   // and start a game or connect to a server. We get the various subsystems ready
   // to go, and then use initClient() to handle the rest of the startup sequence.
   //
   // If this is too convoluted we can reduce this complexity after futher testing
   // to find exactly which subsystems should be readied before kicking things off.
   // ----------------------------------------------------------------------------

   ModuleDatabase.LoadExplicit( "Core_Rendering" );
   ModuleDatabase.LoadExplicit( "Core_Utility" );
   ModuleDatabase.LoadExplicit( "Core_GUI" );
   ModuleDatabase.LoadExplicit( "CoreModule" );
   ModuleDatabase.LoadExplicit( "Core_Lighting" );
   ModuleDatabase.LoadExplicit( "Core_SFX" );
   ModuleDatabase.LoadExplicit( "Core_PostFX" );
   ModuleDatabase.LoadExplicit( "Core_ClientServer" );

   %prefPath = getPrefpath();
   if ( isFile( %prefPath @ "/clientPrefs.cs" ) )
      exec( %prefPath @ "/clientPrefs.cs" );
   else
      exec("data/defaults.cs");

   %der = $pref::Video::displayDevice;

   //We need to hook the missing/warn material stuff early, so do it here
   /*$Core::MissingTexturePath = "core/images/missingTexture";
   $Core::UnAvailableTexturePath = "core/images/unavailable";
   $Core::WarningTexturePath = "core/images/warnMat";
   $Core::CommonShaderPath = "core/shaders";

   /*%classList = enumerateConsoleClasses( "Component" );

   foreach$( %componentClass in %classList )
   {
      echo("Native Component of type: " @ %componentClass);
   }*/

   //exec("./helperFunctions.cs");

   // We need some of the default GUI profiles in order to get the canvas and
   // other aspects of the GUI system ready.
   //exec("./profiles.cs");

   //This is a bit of a shortcut, but we'll load the client's default settings to ensure all the prefs get initialized correctly

   // Initialization of the various subsystems requires some of the preferences
   // to be loaded... so do that first.
   /*exec("./globals.cs");

   exec("./canvas.cs");
   exec("./cursor.cs");

   exec("./renderManager.cs");
   exec("./lighting.cs");

   exec("./audio.cs");
   exec("./sfx/audioAmbience.cs");
   exec("./sfx/audioData.cs");
   exec("./sfx/audioDescriptions.cs");
   exec("./sfx/audioEnvironments.cs");
   exec("./sfx/audioStates.cs");

   exec("./parseArgs.cs");

   // Materials and Shaders for rendering various object types
   exec("./gfxData/commonMaterialData.cs");
   exec("./gfxData/shaders.cs");
   exec("./gfxData/terrainBlock.cs");
   exec("./gfxData/water.cs");
   exec("./gfxData/scatterSky.cs");
   exec("./gfxData/clouds.cs");

   // Initialize all core post effects.
   exec("./postFx.cs");

   //VR stuff
   exec("./oculusVR.cs");*/

   // Seed the random number generator.
   setRandomSeed();

   // Parse the command line arguments
   echo("\n--------- Parsing Arguments ---------");
   parseArgs();

   // The canvas needs to be initialized before any gui scripts are run since
   // some of the controls assume that the canvas exists at load time.
   createCanvas($appName);

   //load canvas
   //exec("./console/main.cs");

   ModuleDatabase.LoadExplicit( "Core_Console" );

   // Init the physics plugin.
   physicsInit();

   sfxStartup();

   // Set up networking.
   setNetPort(0);

   // Start processing file change events.
   startFileChangeNotifications();

   // If we have editors, initialize them here as well
   if (isToolBuild())
   {
      if(isFile("tools/main.cs") && !$isDedicated)
         exec("tools/main.cs");

      ModuleDatabase.scanModules( "tools", false );
      ModuleDatabase.LoadGroup( "Tools" );
   }
}

function CoreModule::onDestroy(%this)
{

}

//-----------------------------------------------------------------------------
// Called when the engine is shutting down.
function onExit()
{
   // Stop file change events.
   stopFileChangeNotifications();

   ModuleDatabase.UnloadExplicit( "Game" );
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>

	<meta charset="utf-8">
	<title>KenhGiaiTri360</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <meta http-equiv="content-language" content="vi" />
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />

    <meta property="og:url" content="http://tinvui360.com/" />
    <meta property="og:image" content="http://tinvui360.com/thumb.jpg" />
    <meta property="og:title" content="Tin tức online giới trẻ hay nhất, hot nhất | clip hay nhất" />
    <meta property="og:description" content="Tổng hợp tin tức xã hội hot nhất ,Tin tức giới trẻ hay nhất" />

	<link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/css/style.css');?>">
	<link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/css/xstyle.css');?>">

    <meta http-equiv="REFRESH" content="1800" />

							<img src="<?php echo base_url('assets/images/gocfunny_logo.png')?>" />

<a href="<?php echo base_url(); ?>index.php/tintuc" tppabs="http://tinvui360.com/tin-tuc">Tin tức

<a href="<?php echo base_url(); ?>index.php/giaitri" tppabs="http://tinvui360.com/giai-tri">Giải trí

<a href="<?php echo base_url(); ?>index.php/gioitre" tppabs="http://tinvui360.com/gioi-tre">Giới trẻ

<a href="<?php echo base_url(); ?>index.php/thoitrang" tppabs="http://tinvui360.com/thoi-trang">Thời trang

<a href="<?php echo base_url(); ?>index.php/congnghe" tppabs="http://tinvui360.com/cong-nghe">Công nghệ

<a href="<?php echo base_url(); ?>index.php/thethao" tppabs="http://tinvui360.com/the-thao">Thể thao

<a href="<?php echo base_url(); ?>index.php/tamsu" tppabs="http://tinvui360.com/tam-su">Tâm sự

<a href="<?php echo base_url(); ?>index.php/docla" tppabs="http://tinvui360.com/doc-la">Độc lạ

<a href="<?php echo base_url(); ?>index.php/gioitinh" tppabs="http://tinvui360.com/gioi-tinh">Giới Tính

<a href="<?php echo base_url(); ?>index.php/gocyeu" tppabs="http://tinvui360.com/goc-yeu">Góc yêu

<a href="<?php echo base_url(); ?>index.php/anhhai" tppabs="http://tinvui360.com/anh-hai">Ảnh hài

<a href="<?php echo base_url(); ?>index.php/video" tppabs="http://tinvui360.com/video">Video


text:
frontEnd.controller('LoginCtrl', ['$scope', function($scope) {

}]);


text:
Rails.application.config.to_prepare do
  Alchemy.register_ability Ability
  Alchemy.user_class_name = "DummyUser"
  Alchemy.signup_path = "/admin/pages" unless Rails.env.test?
  Alchemy::Modules.register_module(
    name: "events",
    navigation: {
      name: "Events",
      controller: "/admin/events",
      action: "index",
      icon: "calendar-alt",
      sub_navigation: [{
        name: "Events",
        controller: "/admin/events",
        action: "index",
      }, {
        name: "Locations",
        controller: "/admin/locations",
        action: "index",
      }, {
        name: "Series",
        controller: "/admin/series",
        action: "index",
      }, {
        name: "Bookings",
        controller: "/admin/bookings",
        action: "index",
      }],
    },
  )
end


text:
module Dropbox
  class Client

    attr_accessor :date_string

    def public_dest_path(filename)
      File.join("/","quotidie", @date_string, filename)
    end

    def private_dest_path(filename)
      File.join("/","zeitungen", filename)
    end

    def exist_in_public_dest?(filename)
      exists?(public_dest_path(filename))
    end

    def exist_in_private_dest?(filename)
      exists?(private_dest_path(filename))
    end

    def mv_file_in_public_dest(filename, file)
      f = open(file)
      upload(public_dest_path(filename), f)
    end

    def mv_file_in_private_dest(filename, file)
      f = open(file)
      upload(private_dest_path(filename), f)
    end

    def include?(dir, file)
      r = get_metadata(dir)
      r["contents"].map{|e| File.basename(e["path"])}.include?(file)
    end

    def dir?(path) # valid: "/a/b",  not valid: "a/b" or "/a/b/"
      path = "/#{path}" unless path[0]=="/"
      r = get_metadata(path)
      r.is_a? Dropbox::FolderMetadata
    end

    # path can be a dir or a file
    def exists?(path)
      path = "/#{path}" unless path[0]=="/"
      r = get_metadata(path)
      return !r["is_deleted"]
    rescue ClientError => e
      false
    rescue ApiError => e
      puts "Error thrown on checking existence of '#{path}'"
      false
    end
  end
end


text:
package org.apache.commons.lang3.builder;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;

import org.apache.commons.lang3.ArrayUtils;
import org.junit.Test;

/**
 * Unit tests {@link DiffBuilder}.
 *
 * @version $Id: DiffBuilderTest.java 1561225 2014-01-24 23:17:29Z djones $
 */
public class DiffBuilderTest {

    private static final ToStringStyle SHORT_STYLE = ToStringStyle.SHORT_PREFIX_STYLE;

    private static class TypeTestClass implements Diffable<TypeTestClass> {
        private ToStringStyle style = SHORT_STYLE;
        private boolean booleanField = true;
        private boolean[] booleanArrayField = {true};
        private byte byteField = (byte) 0xFF;
        private byte[] byteArrayField = {(byte) 0xFF};
        private char charField = 'a';
        private char[] charArrayField = {'a'};
        private double doubleField = 1.0;
        private double[] doubleArrayField = {1.0};
        private float floatField = 1.0f;
        private float[] floatArrayField = {1.0f};
        private int intField = 1;
        private int[] intArrayField = {1};
        private long longField = 1L;
        private long[] longArrayField = {1L};
        private short shortField = 1;
        private short[] shortArrayField = {1};
        private Object objectField = null;
        private Object[] objectArrayField = {null};

        @Override
        public DiffResult diff(TypeTestClass obj) {
            return new DiffBuilder(this, obj, style)
                .append("boolean", booleanField, obj.booleanField)
                .append("booleanArray", booleanArrayField, obj.booleanArrayField)
                .append("byte", byteField, obj.byteField)
                .append("byteArray", byteArrayField, obj.byteArrayField)
                .append("char", charField, obj.charField)
                .append("charArray", charArrayField, obj.charArrayField)
                .append("double", doubleField, obj.doubleField)
                .append("doubleArray", doubleArrayField, obj.doubleArrayField)
                .append("float", floatField, obj.floatField)
                .append("floatArray", floatArrayField, obj.floatArrayField)
                .append("int", intField, obj.intField)
                .append("intArray", intArrayField, obj.intArrayField)
                .append("long", longField, obj.longField)
                .append("longArray", longArrayField, obj.longArrayField)
                .append("short", shortField, obj.shortField)
                .append("shortArray", shortArrayField, obj.shortArrayField)
                .append("objectField", objectField, obj.objectField)
                .append("objectArrayField", objectArrayField, obj.objectArrayField)
                .build();
        }

        @Override
        public int hashCode() {
            return HashCodeBuilder.reflectionHashCode(this, false);
        }

        @Override
        public boolean equals(Object obj) {
            return EqualsBuilder.reflectionEquals(this, obj, false);
        }
    }

    @Test
    public void testBoolean() {
        TypeTestClass class1 = new TypeTestClass();
        TypeTestClass class2 = new TypeTestClass();
        class2.booleanField = false;
        DiffResult list = class1.diff(class2);
        assertEquals(1, list.getNumberOfDiffs());
        Diff<?> diff = list.getDiffs().get(0);
        assertEquals(Boolean.class, diff.getType());
        assertEquals(Boolean.TRUE, diff.getLeft());
        assertEquals(Boolean.FALSE, diff.getRight());
    }

    @Test
    public void testBooleanArray() throws Exception {
        TypeTestClass class1 = new TypeTestClass();
        TypeTestClass class2 = new TypeTestClass();
        class2.booleanArrayField = new boolean[] {false, false};
        DiffResult list = class1.diff(class2);
        assertEquals(1, list.getNumberOfDiffs());
        Diff<?> diff = list.getDiffs().get(0);
        assertArrayEquals(ArrayUtils.toObject(class1.booleanArrayField),
                (Object[]) diff.getLeft());
        assertArrayEquals(ArrayUtils.toObject(class2.booleanArrayField),
                (Object[]) diff.getRight());
    }

    @Test
    public void testByte() {
        TypeTestClass class1 = new TypeTestClass();
        TypeTestClass class2 = new TypeTestClass();
        class2.byteField = 0x01;
        DiffResult list = class1.diff(class2);
        assertEquals(1, list.getNumberOfDiffs());
        Diff<?> diff = list.getDiffs().get(0);
        assertEquals(Byte.valueOf(class1.byteField), diff.getLeft());
        assertEquals(Byte.valueOf(class2.byteField), diff.getRight());
    }

    @Test
    public void testByteArray() throws Exception {
        TypeTestClass class1 = new TypeTestClass();
        TypeTestClass class2 = new TypeTestClass();
        class2.byteArrayField= new byte[] {0x01, 0x02};
        DiffResult list = class1.diff(class2);
        assertEquals(1, list.getNumberOfDiffs());
        Diff<?> diff = list.getDiffs().get(0);
        assertArrayEquals(ArrayUtils.toObject(class1.byteArrayField),
                (Object[]) diff.getLeft());
        assertArrayEquals(ArrayUtils.toObject(class2.byteArrayField),
                (Object[]) diff.getRight());
    }

    @Test
    public void testChar() {
        TypeTestClass class1 = new TypeTestClass();
        TypeTestClass class2 = new TypeTestClass();
        class2.charField = 'z';
        DiffResult list = class1.diff(class2);
        assertEquals(1, list.getNumberOfDiffs());
        Diff<?> diff = list.getDiffs().get(0);
        assertEquals(Character.valueOf(class1.charField), diff.getLeft());
        assertEquals(Character.valueOf(class2.charField), diff.getRight());
    }

    @Test
    public void testCharArray() throws Exception {
        TypeTestClass class1 = new TypeTestClass();
        TypeTestClass class2 = new TypeTestClass();
        class2.charArrayField = new char[] {'f', 'o', 'o'};
        DiffResult list = class1.diff(class2);
        assertEquals(1, list.getNumberOfDiffs());
        Diff<?> diff = list.getDiffs().get(0);
        assertArrayEquals(ArrayUtils.toObject(class1.charArrayField),
                (Object[]) diff.getLeft());
        assertArrayEquals(ArrayUtils.toObject(class2.charArrayField),
                (Object[]) diff.getRight());
    }

    @Test
    public void testDouble() {
        TypeTestClass class1 = new TypeTestClass();
        TypeTestClass class2 = new TypeTestClass();
        class2.doubleField = 99.99;
        DiffResult list = class1.diff(class2);
        assertEquals(1, list.getNumberOfDiffs());
        Diff<?> diff = list.getDiffs().get(0);
        assertEquals(Double.valueOf(class1.doubleField), diff.getLeft());
        assertEquals(Double.valueOf(class2.doubleField), diff.getRight());
    }

    @Test
    public void testDoubleArray() throws Exception {
        TypeTestClass class1 = new TypeTestClass();
        TypeTestClass class2 = new TypeTestClass();
        class2.doubleArrayField = new double[] {3.0, 2.9, 2.8};
        DiffResult list = class1.diff(class2);
        assertEquals(1, list.getNumberOfDiffs());
        Diff<?> diff = list.getDiffs().get(0);
        assertArrayEquals(ArrayUtils.toObject(class1.doubleArrayField),
                (Object[]) diff.getLeft());
        assertArrayEquals(ArrayUtils.toObject(class2.doubleArrayField),
                (Object[]) diff.getRight());
    }

    @Test
    public void testFloat() {
        TypeTestClass class1 = new TypeTestClass();
        TypeTestClass class2 = new TypeTestClass();
        class2.floatField = 99.99F;
        DiffResult list = class1.diff(class2);
        assertEquals(1, list.getNumberOfDiffs());
        Diff<?> diff = list.getDiffs().get(0);
        assertEquals(Float.valueOf(class1.floatField), diff.getLeft());
        assertEquals(Float.valueOf(class2.floatField), diff.getRight());
    }

    @Test
    public void testFloatArray() throws Exception {
        TypeTestClass class1 = new TypeTestClass();
        TypeTestClass class2 = new TypeTestClass();
        class2.floatArrayField = new float[] {3.0F, 2.9F, 2.8F};
        DiffResult list = class1.diff(class2);
        assertEquals(1, list.getNumberOfDiffs());
        Diff<?> diff = list.getDiffs().get(0);
        assertArrayEquals(ArrayUtils.toObject(class1.floatArrayField),
                (Object[]) diff.getLeft());
        assertArrayEquals(ArrayUtils.toObject(class2.floatArrayField),
                (Object[]) diff.getRight());
    }

    @Test
    public void testInt() {
        TypeTestClass class1 = new TypeTestClass();
        TypeTestClass class2 = new TypeTestClass();
        class2.intField = 42;
        DiffResult list = class1.diff(class2);
        assertEquals(1, list.getNumberOfDiffs());
        Diff<?> diff = list.getDiffs().get(0);
        assertEquals(Integer.valueOf(class1.intField), diff.getLeft());
        assertEquals(Integer.valueOf(class2.intField), diff.getRight());
    }

    @Test
    public void testIntArray() throws Exception {
        TypeTestClass class1 = new TypeTestClass();
        TypeTestClass class2 = new TypeTestClass();
        class2.intArrayField = new int[] {3, 2, 1};
        DiffResult list = class1.diff(class2);
        assertEquals(1, list.getNumberOfDiffs());
        Diff<?> diff = list.getDiffs().get(0);
        assertArrayEquals(ArrayUtils.toObject(class1.intArrayField),
                (Object[]) diff.getLeft());
        assertArrayEquals(ArrayUtils.toObject(class2.intArrayField),
                (Object[]) diff.getRight());
    }

    @Test
    public void testLong() {
        TypeTestClass class1 = new TypeTestClass();
        TypeTestClass class2 = new TypeTestClass();
        class2.longField = 42L;
        DiffResult list = class1.diff(class2);
        assertEquals(1, list.getNumberOfDiffs());
        Diff<?> diff = list.getDiffs().get(0);
        assertEquals(Long.valueOf(class1.longField), diff.getLeft());
        assertEquals(Long.valueOf(class2.longField), diff.getRight());
    }

    @Test
    public void testLongArray() throws Exception {
        TypeTestClass class1 = new TypeTestClass();
        TypeTestClass class2 = new TypeTestClass();
        class2.longArrayField = new long[] {3L, 2L, 1L};
        DiffResult list = class1.diff(class2);
        assertEquals(1, list.getNumberOfDiffs());
        Diff<?> diff = list.getDiffs().get(0);
        assertArrayEquals(ArrayUtils.toObject(class1.longArrayField),
                (Object[]) diff.getLeft());
        assertArrayEquals(ArrayUtils.toObject(class2.longArrayField),
                (Object[]) diff.getRight());
    }

    @Test
    public void testShort() {
        TypeTestClass class1 = new TypeTestClass();
        TypeTestClass class2 = new TypeTestClass();
        class2.shortField = 42;
        DiffResult list = class1.diff(class2);
        assertEquals(1, list.getNumberOfDiffs());
        Diff<?> diff = list.getDiffs().get(0);
        assertEquals(Short.valueOf(class1.shortField), diff.getLeft());
        assertEquals(Short.valueOf(class2.shortField), diff.getRight());
    }

    @Test
    public void testShortArray() throws Exception {
        TypeTestClass class1 = new TypeTestClass();
        TypeTestClass class2 = new TypeTestClass();
        class2.shortArrayField = new short[] {3, 2, 1};
        DiffResult list = class1.diff(class2);
        assertEquals(1, list.getNumberOfDiffs());
        Diff<?> diff = list.getDiffs().get(0);
        assertArrayEquals(ArrayUtils.toObject(class1.shortArrayField),
                (Object[]) diff.getLeft());
        assertArrayEquals(ArrayUtils.toObject(class2.shortArrayField),
                (Object[]) diff.getRight());
    }

    @Test
    public void testObject() throws Exception {
        TypeTestClass class1 = new TypeTestClass();
        TypeTestClass class2 = new TypeTestClass();
        class2.objectField = "Some string";
        DiffResult list = class1.diff(class2);
        assertEquals(1, list.getNumberOfDiffs());
        Diff<?> diff = list.getDiffs().get(0);
        assertEquals(class1.objectField, diff.getLeft());
        assertEquals(class2.objectField, diff.getRight());
    }

    @Test
    public void testObjectsEqual() throws Exception {
        TypeTestClass class1 = new TypeTestClass();
        TypeTestClass class2 = new TypeTestClass();
        class1.objectField = "Some string";
        class2.objectField = "Some string";
        DiffResult list = class1.diff(class2);
        assertEquals(0, list.getNumberOfDiffs());
    }

    @Test
    public void testObjectArray() throws Exception {
        TypeTestClass class1 = new TypeTestClass();
        TypeTestClass class2 = new TypeTestClass();
        class2.objectArrayField = new Object[] {"string", 1, 2};
        DiffResult list = class1.diff(class2);
        assertEquals(1, list.getNumberOfDiffs());
        Diff<?> diff = list.getDiffs().get(0);
        assertArrayEquals(class1.objectArrayField, (Object[]) diff.getLeft());
        assertArrayEquals(class2.objectArrayField, (Object[]) diff.getRight());
    }

    @Test
    public void testObjectArrayEqual() throws Exception {
        TypeTestClass class1 = new TypeTestClass();
        TypeTestClass class2 = new TypeTestClass();
        class1.objectArrayField = new Object[] {"string", 1, 2};
        class2.objectArrayField = new Object[] {"string", 1, 2};
        DiffResult list = class1.diff(class2);
        assertEquals(0, list.getNumberOfDiffs());
    }

    @Test
    public void testByteArrayEqualAsObject() throws Exception {
        DiffResult list = new DiffBuilder("String1", "String2", SHORT_STYLE)
            .append("foo", (Object) new boolean[] {false}, (Object) new boolean[] {false})
            .append("foo", (Object) new byte[] {0x01}, (Object) new byte[] {0x01})
            .append("foo", (Object) new char[] {'a'}, (Object) new char[] {'a'})
            .append("foo", (Object) new double[] {1.0}, (Object) new double[] {1.0})
            .append("foo", (Object) new float[] {1.0F}, (Object) new float[] {1.0F})
            .append("foo", (Object) new int[] {1}, (Object) new int[] {1})
            .append("foo", (Object) new long[] {1L}, (Object) new long[] {1L})
            .append("foo", (Object) new short[] {1}, (Object) new short[] {1})
            .append("foo", (Object) new Object[] {1, "two"}, (Object) new Object[] {1, "two"})
            .build();

        assertEquals(0, list.getNumberOfDiffs());
    }

    @Test(expected=IllegalArgumentException.class)
    public void testNullLhs() {
        new DiffBuilder(null, this, ToStringStyle.DEFAULT_STYLE);
    }

    @Test(expected=IllegalArgumentException.class)
    public void testNullRhs() {
        new DiffBuilder(this, null, ToStringStyle.DEFAULT_STYLE);
    }

    @Test
    public void testSameObjectIgnoresAppends() {
        TypeTestClass testClass = new TypeTestClass();
        DiffResult list = new DiffBuilder(testClass, testClass, SHORT_STYLE)
            .append("ignored", false, true)
            .build();
        assertEquals(0, list.getNumberOfDiffs());
    }

    @Test
    public void testSimilarObjectIgnoresAppends() {
        TypeTestClass testClass1 = new TypeTestClass();
        TypeTestClass testClass2 = new TypeTestClass();
        DiffResult list = new DiffBuilder(testClass1, testClass2, SHORT_STYLE)
            .append("ignored", false, true)
            .build();
        assertEquals(0, list.getNumberOfDiffs());
    }

    @Test
    public void testStylePassedToDiffResult() {
        TypeTestClass class1 = new TypeTestClass();
        DiffResult list = class1.diff(class1);
        assertEquals(SHORT_STYLE, list.getToStringStyle());

        class1.style = ToStringStyle.MULTI_LINE_STYLE;
        list = class1.diff(class1);
        assertEquals(ToStringStyle.MULTI_LINE_STYLE, list.getToStringStyle());
    }
}


text:
class VertexBufferRenderDataBgfx : public DeviceBufferRenderDataBgfx
{
public:
	VertexBufferRenderDataBgfx()
	{
		m_isIndexBuffer = false;
	}

	~VertexBufferRenderDataBgfx() override
	{
		bgfx::destroy(m_vertexBuffer);
		bgfx::destroy(m_dynamicVertexBuffer);
	}

	bgfx::VertexBufferHandle m_vertexBuffer = BGFX_INVALID_HANDLE;
	bgfx::DynamicVertexBufferHandle m_dynamicVertexBuffer = BGFX_INVALID_HANDLE;

	bgfx::VertexLayout m_vertexLayout;
};


text:
package org.jfree.chart.plot;

import java.util.HashMap;
import java.util.Map;

/**
 * Records information about the state of a plot during the drawing process.
 */
public class PlotState {

    /** The shared axis states. */
    private Map sharedAxisStates;

    /**
     * Creates a new state object.
     */
    public PlotState() {
        this.sharedAxisStates = new HashMap();
    }

    /**
     * Returns a map containing the shared axis states.
     *
     * @return A map.
     */
    public Map getSharedAxisStates() {
        return this.sharedAxisStates;
    }

}


text:
@interface MVVMDataSourceFetchedResults ()

@property (nonatomic, strong) NSFetchedResultsController *fetchedResultsController;

@end

@implementation MVVMDataSourceFetchedResults

#pragma mark - Init Methods

- (instancetype)initWithController:(NSFetchedResultsController *)fetchedResultsController {
  self = [super init];
  if (!self) return nil;
  self.fetchedResultsController = fetchedResultsController;
  return self;
}

#pragma mark - MVVMListViewModelDataSource Methods

- (NSInteger)numberOfSections {
  return self.fetchedResultsController.sections.count;
}

- (NSInteger)numberOfRowsInSection:(NSInteger)section {
  id <NSFetchedResultsSectionInfo> sectionInfo =
    self.fetchedResultsController.sections[(NSUInteger) section];
  return sectionInfo.numberOfObjects;
}

- (NSIndexPath *)indexPathForModel:(MVVMModel *)model {
  return [self.fetchedResultsController indexPathForObject:model];
}

- (NSArray *)indexPathsForModels:(NSArray *)models {
  __typeof(self) __weak weakSelf = self;
  return [models map:^id(id model) {
    return [weakSelf indexPathForModel:model];
  }];
}

- (MVVMModel *)modelAtIndexPath:(NSIndexPath *)indexPath {
  return [self.fetchedResultsController objectAtIndexPath:indexPath];
}

- (NSArray *)modelsAtIndexPaths:(NSArray *)indexPaths {
  __typeof(self) __weak weakSelf = self;
  return [indexPaths map:^id(NSIndexPath *indexPath) {
    return [weakSelf modelAtIndexPath:indexPath];
  }];
}

- (AnyPromise *)reloadWithModels:(NSArray *)models {
  __typeof(self) __weak weakSelf = self;
  return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) {
    NSError *error = nil;
    if ([weakSelf.fetchedResultsController performFetch:&error]) {
      resolve(nil);
    } else {
      resolve(error);
    }
  }];
}

- (NSArray *)allModels {
  return self.fetchedResultsController.fetchedObjects;
}

@end


text:
<?php

namespace DrSlump\Protobuf\Compiler;

use google\protobuf as proto;

abstract class AbstractGenerator
{
    /** @var \DrSlump\Protobuf\Compiler */
    protected $compiler;
    /** @var \google\protobuf\FileDescriptorProto */
    protected $proto;

    /** @var array */
    protected $extensions = array();

    public function __construct(\DrSlump\Protobuf\Compiler $compiler)
    {
        $this->compiler = $compiler;
    }

    public function getNamespace(proto\FileDescriptorProto $proto = NULL)
    {
        return NULL === $proto
               ? $this->proto->getPackage()
               : $proto->getPackage();
    }

    public function generate(proto\FileDescriptorProto $proto)
    {
        $this->proto = $proto;
    }

    abstract protected function compileEnum(proto\EnumDescriptorProto $enum, $namespace);

    abstract protected function compileMessage(proto\DescriptorProto $msg, $namespace);

    abstract protected function compileExtension(proto\FieldDescriptorProto $field, $ns, $indent);
}


text:
Health Checks

    <jhi-route-selector></jhi-route-selector>

                    Service Name
                    Status
                    Details

                    {{ baseName(health.name) }} {{subSystemName(health.name)}}

                            {{health.status}}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >
    </ListView>

</RelativeLayout>


text:
package org.zaproxy.zap.extension.ascan;

import org.parosproxy.paros.core.scanner.ScannerParam;
import org.zaproxy.zap.extension.ascan.AttackModeScanner.AttackModeScannerThread;
import org.zaproxy.zap.extension.ruleconfig.RuleConfigParam;
import org.zaproxy.zap.model.Target;

/**
 * A 'dummy' ActiveScan class just used for recording the Attack mode scan results.
 *
 * @author simon
 */
public class AttackScan extends ActiveScan {

    private final AttackModeScannerThread attackModeScannerThread;

    @SuppressWarnings("deprecation")
    public AttackScan(
            String displayName,
            ScannerParam scannerParam,
            org.parosproxy.paros.network.ConnectionParam param,
            ScanPolicy scanPolicy,
            RuleConfigParam ruleConfigParam) {
        this(displayName, scannerParam, scanPolicy, ruleConfigParam, null);
    }

    AttackScan(
            String displayName,
            ScannerParam scannerParam,
            ScanPolicy scanPolicy,
            RuleConfigParam ruleConfigParam,
            AttackModeScannerThread attackModeScannerThread) {
        super(displayName, scannerParam, scanPolicy, ruleConfigParam);
        this.attackModeScannerThread = attackModeScannerThread;
    }

    @Override
    public void start(Target target) {
        // Do nothing
    }

    @Override
    public void stopScan() {}

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

    @Override
    public int getProgress() {
        return 0;
    }

    @Override
    public int getMaximum() {
        return 100;
    }

    @Override
    public void pauseScan() {
        // Do nothing
    }

    @Override
    public void resumeScan() {
        // Do nothing
    }

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

    @Override
    public boolean isRunning() {
        return true;
    }

    boolean isDone() {
        if (attackModeScannerThread == null) {
            return false;
        }
        return !attackModeScannerThread.isRunning() || !attackModeScannerThread.isActive();
    }
}