text:
package org.apache.derby.client.net;

import org.apache.derby.client.am.DisconnectException;
import org.apache.derby.client.am.ResultSet;
import org.apache.derby.client.am.ResultSetCallbackInterface;
import org.apache.derby.client.am.SqlException;
import org.apache.derby.client.am.ClientMessageId;

import org.apache.derby.shared.common.reference.SQLState;
import org.apache.derby.shared.common.reference.MessageId;

public class NetResultSetReply extends NetStatementReply implements ResultSetReplyInterface {
    public NetResultSetReply(NetAgent netAgent, int bufferSize) {
        super(netAgent, bufferSize);
    }

    //----------------------------- entry points ---------------------------------

    public void readFetch(ResultSetCallbackInterface resultSet) throws DisconnectException {
        startSameIdChainParse();
        parseCNTQRYreply(resultSet, true); // true means we expect row data
        endOfSameIdChainData();
    }

    public void readPositioningFetch(ResultSetCallbackInterface resultSet) throws DisconnectException {
        startSameIdChainParse();
        parseCNTQRYreply(resultSet, false);  // false means return data is not expected
        endOfSameIdChainData();
    }

    public void readScrollableFetch(ResultSetCallbackInterface resultSet) throws DisconnectException {
        startSameIdChainParse();
        parseCNTQRYreply(resultSet, true);   // true means return data is expected
        endOfSameIdChainData();
    }

    public void readCursorClose(ResultSetCallbackInterface resultSet) throws DisconnectException {
        startSameIdChainParse();
        parseCLSQRYreply(resultSet);
        endOfSameIdChainData();
    }

    //----------------------helper methods----------------------------------------

    //------------------parse reply for specific command--------------------------

    // These methods are "private protected", which is not a recognized java privilege,
    // but means that these methods are private to this class and to subclasses,
    // and should not be used as package-wide friendly methods.

    // Parse the reply for the Close Query Command.
    // This method handles the parsing of all command replies and reply data
    // for the clsqry command.
    private void parseCLSQRYreply(ResultSetCallbackInterface resultSet) throws DisconnectException {
        int peekCP = parseTypdefsOrMgrlvlovrs();

        if (peekCP == CodePoint.SQLCARD) {
            NetSqlca netSqlca = parseSQLCARD(null);  //@f48553sxg - null means rowsetSqlca_ is null
            // Set the cursor state if null SQLCA or sqlcode is equal to 0.
            resultSet.completeSqlca(netSqlca);
        } else {
            parseCloseError(resultSet);
        }
    }

    // Parse the reply for the Continue Query Command.
    // This method handles the parsing of all command replies and reply data for the cntqry command.
    // If doCopyQrydta==false, then there is no data, and we're only parsing out the sqlca to get the row count.
    private void parseCNTQRYreply(ResultSetCallbackInterface resultSetI,
                                  boolean doCopyQrydta) throws DisconnectException {
        boolean found = false;
        int peekCP = peekCodePoint();
        if (peekCP == CodePoint.RDBUPDRM) {
            found = true;
            parseRDBUPDRM();
            peekCP = peekCodePoint();
        }

        if (peekCP == CodePoint.QRYDTA) {
            found = true;
            if (!doCopyQrydta) {
                parseLengthAndMatchCodePoint(CodePoint.QRYDTA);
                //we don't need to copy QRYDTA since there is no data
                if (longValueForDecryption_ != null) {
                    longValueForDecryption_ = null;
                }
                if (longBufferForDecryption_ != null) {
                    longBufferForDecryption_ = null;
                }

                int ddmLength = getDdmLength();
                ensureBLayerDataInBuffer(ddmLength);
                ((ResultSet) resultSetI).expandRowsetSqlca();
                NetSqlca sqlca = parseSQLCARDrow(((ResultSet) resultSetI).rowsetSqlca_);
                int daNullIndicator = readFastByte();
                adjustLengths(getDdmLength());
                // define event interface and use the event method
                // only get the rowCount_ if sqlca is not null and rowCount_ is unknown
                if (sqlca != null && sqlca.containsSqlcax()) {
                    ((ResultSet) resultSetI).setRowCountEvent(sqlca.getRowCount(netAgent_.targetTypdef_));
                }

                peekCP = peekCodePoint();
                if (peekCP == CodePoint.RDBUPDRM) {
                    parseRDBUPDRM();
                    peekCP = peekCodePoint();
                }
                if (peekCP == CodePoint.PBSD) {
                    parsePBSD();
                }
                return;
            }
            do {
                parseQRYDTA((NetResultSet) resultSetI);
                peekCP = peekCodePoint();
            } while (peekCP == CodePoint.QRYDTA);
        }

        if (peekCP == CodePoint.EXTDTA) {
            found = true;
            do {
                copyEXTDTA((NetCursor) ((ResultSet) resultSetI).cursor_);
                if (longBufferForDecryption_ != null) {//encrypted EXTDTA
                    buffer_ = longBufferForDecryption_;
                    pos_ = longPosForDecryption_;
                    if (longBufferForDecryption_ != null && count_ > longBufferForDecryption_.length) {
                        count_ = longBufferForDecryption_.length;
                    }
                }

                peekCP = peekCodePoint();
            } while (peekCP == CodePoint.EXTDTA);
        }

        if (peekCP == CodePoint.SQLCARD) {
            found = true;
            ((ResultSet) resultSetI).expandRowsetSqlca();
            NetSqlca netSqlca = parseSQLCARD(((ResultSet) resultSetI).rowsetSqlca_);
            // for an atomic operation, the SQLCA contains the sqlcode for the first (statement
            // terminating)error, the last warning, or zero.  all multi-row fetch operatons are
            // atomic.  (the only operation that is not atomic is multi-row insert).
            if (((ResultSet) resultSetI).sensitivity_ != ResultSet.sensitivity_sensitive_dynamic__) {
                if (netSqlca != null && netSqlca.containsSqlcax() && netSqlca.getRowsetRowCount() == 0) {
                    ((ResultSet) resultSetI).setRowCountEvent(netSqlca.getRowCount(netAgent_.targetTypdef_));
                }
            }
            resultSetI.completeSqlca(netSqlca);
            peekCP = peekCodePoint();
        }

        if (peekCP == CodePoint.ENDQRYRM) {
            found = true;
            parseEndQuery(resultSetI);
            peekCP = peekCodePoint();
        }

        if (peekCP == CodePoint.RDBUPDRM) {
            found = true;
            parseRDBUPDRM();
            peekCP = peekCodePoint();
        }

        if (!found) {
            parseFetchError(resultSetI);
        }

        if (peekCP == CodePoint.PBSD) {
            parsePBSD();
        }

        if (longBufferForDecryption_ != null) {
            // Not a good idea to create a new buffer_
            buffer_ = new byte[DEFAULT_BUFFER_SIZE];
            longBufferForDecryption_ = null;
        }
    }

    void parseCloseError(ResultSetCallbackInterface resultSetI) throws DisconnectException {
        int peekCP = peekCodePoint();
        switch (peekCP) {
        case CodePoint.ABNUOWRM:
            {
                //passing the ResultSetCallbackInterface implementation will
                //help in retrieving the the UnitOfWorkListener that needs to
                //be rolled back
                NetSqlca sqlca = parseAbnormalEndUow(resultSetI);
                resultSetI.completeSqlca(sqlca);
                break;
            }
        case CodePoint.CMDCHKRM:
            parseCMDCHKRM();
            break;
        case CodePoint.QRYNOPRM:
            parseQRYNOPRM(resultSetI);
            break;
        case CodePoint.RDBNACRM:
            parseRDBNACRM();
            break;
        default:
            parseCommonError(peekCP);
        }
    }

    void parseFetchError(ResultSetCallbackInterface resultSetI) throws DisconnectException {
        int peekCP = peekCodePoint();
        switch (peekCP) {
        case CodePoint.ABNUOWRM:
            {
                //passing the ResultSetCallbackInterface implementation will
                //help in retrieving the the UnitOfWorkListener that needs to
                //be rolled back
                NetSqlca sqlca = parseAbnormalEndUow(resultSetI);
                resultSetI.completeSqlca(sqlca);
                break;
            }
        case CodePoint.CMDCHKRM:
            parseCMDCHKRM();
            break;
        case CodePoint.CMDNSPRM:
            parseCMDNSPRM();
            break;
        case CodePoint.QRYNOPRM:
            parseQRYNOPRM(resultSetI);
            break;
        case CodePoint.RDBNACRM:
            parseRDBNACRM();
            break;
        default:
            parseCommonError(peekCP);
        }
    }

    //-----------------------------parse DDM Reply Messages-----------------------

    // Query Not Opened Reply Message is issued if a CNTQRY or CLSQRY
    // command is issued for a query that is not open.  A previous
    // ENDQRYRM, ENDUOWRM, or ABNUOWRM reply message might have
    // terminated the command.
    // PROTOCOL architects the SQLSTATE value depending on SVRCOD
    // SVRCOD 4 -> SQLSTATE is 24501
    // SVRCOD 8 -> SQLSTATE of 58008 or 58009
    //
    // if SVRCOD is 4 then SQLSTATE 24501, SQLCODE -501
    // else SQLSTATE 58009, SQLCODE -30020
    //
    // Messages
    // SQLSTATE : 24501
    //     The identified cursor is not open.
    //     SQLCODE : -501
    //     The cursor specified in a FETCH or CLOSE statement is not open.
    //     The statement cannot be processed.
    // SQLSTATE : 58009
    //     Execution failed due to a distribution protocol error that caused deallocation of the conversation.
    //     SQLCODE : -30020
    //     Execution failed because of a Distributed Protocol
    //         Error that will affect the successful execution of subsequent
    //         commands and SQL statements: Reason Code <reason-code>.
    //     Some possible reason codes include:
    //     121C Indicates that the user is not authorized to perform the requested command.
    //     1232 The command could not be completed because of a permanent error.
    //         In most cases, the server will be in the process of an abend.
    //     220A The target server has received an invalid data description.
    //         If a user SQLDA is specified, ensure that the fields are
    //         initialized correctly. Also, ensure that the length does not exceed
    //         the maximum allowed length for the data type being used.
    //
    //     The command or statement cannot be processed.  The current
    //         transaction is rolled back and the application is disconnected
    //         from the remote database.
    //
    // Returned from Server:
    // SVRCOD - required  (4 - WARNING, 8 - ERROR)
    // RDBNAM - required
    // PKGNAMCSN - required
    //
    private void parseQRYNOPRM(ResultSetCallbackInterface resultSet) throws DisconnectException {
        boolean svrcodReceived = false;
        int svrcod = CodePoint.SVRCOD_INFO;
        boolean rdbnamReceived = false;
        String rdbnam = null;
        boolean pkgnamcsnReceived = false;
        Object pkgnamcsn = null;

        parseLengthAndMatchCodePoint(CodePoint.QRYNOPRM);
        pushLengthOnCollectionStack();
        int peekCP = peekCodePoint();

        while (peekCP != Reply.END_OF_COLLECTION) {

            boolean foundInPass = false;

            if (peekCP == CodePoint.SVRCOD) {
                foundInPass = true;
                svrcodReceived = checkAndGetReceivedFlag(svrcodReceived);
                svrcod = parseSVRCOD(CodePoint.SVRCOD_WARNING, CodePoint.SVRCOD_ERROR);
                peekCP = peekCodePoint();
            }

            if (peekCP == CodePoint.RDBNAM) {
                foundInPass = true;
                rdbnamReceived = checkAndGetReceivedFlag(rdbnamReceived);
                rdbnam = parseRDBNAM(true);
                peekCP = peekCodePoint();
            }

            if (peekCP == CodePoint.PKGNAMCSN) {
                foundInPass = true;
                pkgnamcsnReceived = checkAndGetReceivedFlag(pkgnamcsnReceived);
                pkgnamcsn = parsePKGNAMCSN(true);
                peekCP = peekCodePoint();
            }

            if (!foundInPass) {
                doPrmnsprmSemantics(peekCP);
            }

        }
        popCollectionStack();
        checkRequiredObjects(svrcodReceived, rdbnamReceived, pkgnamcsnReceived);

        // move into a method
        netAgent_.setSvrcod(svrcod);
        if (svrcod == CodePoint.SVRCOD_WARNING) {
            netAgent_.accumulateReadException(new SqlException(netAgent_.logWriter_,
                new ClientMessageId(SQLState.DRDA_CURSOR_NOT_OPEN)));
        } else {
            agent_.accumulateChainBreakingReadExceptionAndThrow(new DisconnectException(agent_,
                new ClientMessageId(SQLState.DRDA_CONNECTION_TERMINATED),
                    SqlException.getMessageUtil().
                    getTextMessage(MessageId.CONN_CURSOR_NOT_OPEN)));
        }
    }
}


text:
namespace euphoria::core
{
    struct Viewport
    {
        Viewport(const Recti& r);

        [[nodiscard]] float
        get_aspect_ratio() const;

        [[nodiscard]] Vec2f
        to_clip_coord(const Vec2i& p) const;

        Recti bounds;
    };

    struct CompiledCamera3;

    Ray3f mouse_to_ray
    (
        const CompiledCamera3& camera,
        const Viewport& viewport,
        const Vec2i& position
    );

    UnitRay3f mouse_to_unit_ray
    (
        const CompiledCamera3& camera,
        const Viewport& viewport,
        const Vec2i& position
    );
}

redpajama_set_name: RedPajamaGithub


text: <link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">


text:
layout: post
title:  The Owl
image_path: /images/design-owl.png
banner_path: /images/designs/the-owl/banner.jpg
tagline: As Layout Editor for my high school's newspaper, updated overall design and published six issues
card_color: "#432930"
ending:
  tagline: I worked as The Owl's Layout Editor from September 2016 to May 2017.
  link: https://issuu.com/zacharyespiritu
  link_text: read more issues
filters: design
---

# Overview

From September 2016 to May 2017, I worked as the Layout Editor for *The Owl*, the newspaper of record of Regis High School, my alma mater. While from September 2014 to May 2016 I had worked as the Assistant Layout Editor, this was my first opportunity to design issues myself for publication.

During my tenure as The Owl's Layout Editor, I redesigned overall design elements to ensure each publication had a consistent theme while still improving upon previous issues. Throughout the year, I also advocated for the eventual change from eight-page to twelve-page issues in addition to implementing a new "Student News" column on Page 3 designed to feature student accomplishments that were not included in the main article set.

You can read sample issues that I designed below or view the entirety of Volume 81 of The Owl at [Issuu][issuu-profile].

[issuu-profile]: https://issuu.com/zacharyespiritu


text:
require 'rails_helper'

RSpec.describe ConferencePreference, type: :model do
  describe 'associations' do
    it { is_expected.to belong_to(:team).optional }
    it { is_expected.to belong_to(:first_conference).optional }
    it { is_expected.to belong_to(:second_conference).optional }
  end

  describe 'validates terms of ticket and terms of travel' do
    let(:terms_false)              { { terms_of_ticket: false, terms_of_travel: false } }
    let(:preference_without_terms) { build(:conference_preference, **terms_false) }
    let(:preference_with_terms)    { build(:conference_preference) }

    context 'when both terms are not checked' do
      before { preference_without_terms.validate }

      it 'conference preferences is not valid' do
        expect(preference_without_terms).not_to be_valid
      end

      it 'terms of ticket raise an error' do
        expect(preference_without_terms.errors[:terms_of_ticket]).not_to be_empty
      end

      it 'terms of travel raise an error' do
        expect(preference_without_terms.errors[:terms_of_travel]).not_to be_empty
      end
    end

    context 'when terms of travel are not checked' do
      before do
        preference_without_terms.terms_of_ticket = true
        preference_without_terms.validate
      end

      it 'conference preferences is not valid' do
        expect(preference_without_terms).not_to be_valid
      end

      it 'terms of ticket raise no errors' do
        expect(preference_without_terms.errors[:terms_of_ticket]).to be_empty
      end

      it 'terms of travel raise an error' do
        expect(preference_without_terms.errors[:terms_of_travel]).not_to be_empty
      end
    end

    context 'when terms of ticket are not checked' do
      before do
        preference_without_terms.terms_of_travel = true
        preference_without_terms.validate
      end

      it 'conference preferences is not valid' do
        expect(preference_without_terms).not_to be_valid
      end

      it 'terms of ticket raise an error' do
        expect(preference_without_terms.errors[:terms_of_ticket]).not_to be_empty
      end

      it 'terms of travel raise no errors' do
        expect(preference_without_terms.errors[:terms_of_travel]).to be_empty
      end
    end

    context 'when both terms are checked' do
      it 'saves conference preferences if terms of ticket and terms of travel was checked' do
        expect(preference_with_terms).to be_valid
      end
    end
  end

  describe '.current teams' do
    let(:team) { create(:team, :in_current_season, :with_conference_preferences) }
    let(:old_team) { create(:team, :with_conference_preferences) }

    it 'returns just conference preference from current teams' do
      current_teams = ConferencePreference.current_teams
      expect(current_teams).to contain_exactly(team.conference_preference)
    end
  end

  describe '#terms_accepted?' do
    let(:conference_preference) { build(:conference_preference) }

    it 'returns true when both terms are accepted' do
      conference_preference.terms_of_ticket = true
      conference_preference.terms_of_travel = true
      expect(conference_preference).to be_terms_accepted
    end

    it 'returns false when both terms are not accepted' do
      conference_preference.terms_of_ticket = false
      conference_preference.terms_of_travel = false
      expect(conference_preference).not_to be_terms_accepted
    end

    it 'returns false when one term is not accepted' do
      conference_preference.terms_of_ticket = true
      conference_preference.terms_of_travel = false
      expect(conference_preference).not_to be_terms_accepted
    end
  end

  describe '#has_preference?' do
    let(:conference_preference) { build(:conference_preference) }

    context 'when conference preference has neither first or second choice set' do
      before do
        conference_preference.first_conference_id = nil
        conference_preference.second_conference_id = nil
      end

      it 'returns false' do
        expect(conference_preference).not_to be_has_preference
      end
    end

    context 'when just first conference preference choice is set' do
      before { conference_preference.second_conference_id = nil }

      it 'returns true' do
        expect(conference_preference).to be_has_preference
      end
    end

    context 'when just second conference preference choice is set' do
      before { conference_preference.first_conference_id = nil }

      it 'returns true' do
        expect(conference_preference).to be_has_preference
      end
    end

    context 'when both conference preference choice are set' do
      it 'returns true' do
        expect(conference_preference).to be_has_preference
      end
    end
  end
end


text:
<!doctype html>
<html>

  <head>
    <title>Observable Example: Observables</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
  </head>

  <body>
    <car-key></car-key>
    <car-headlights></car-headlights>

    <!-- riot tags -->
    <script type="riot/tag" src="car-key.tag"></script>
    <script type="riot/tag" src="car-headlights.tag"></script>

    <!-- scripts we need -->
    <script src="https://cdn.jsdelivr.net/g/riot@2.2(riot.min.js+compiler.min.js)"></script>

    <!-- mount this app -->
    <script type="text/javascript">
      function Car(make, model) {
        var self = this
        self.make = make
        self.model = model
        self.started = false
        riot.observable(self)
        self.on('start', function () {
          self.started = true;
        })
      }

      // make a new Car instance
      var car = new Car('Ford', 'Focus')

      riot.mount('*')
    </script>
  </body>

</html>


text:
<!DOCTYPE html>

	<meta charset="utf-8" />

	<link href="css/grid-bootstrap.css" rel="stylesheet" type="text/css" />
	<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" />
	<link href="css/style-bootstrap.css" rel="stylesheet" type="text/css" />

	<title>Gridle | Bootstrap</title>

				<button type="button" class="btn btn-block btn-default">Button</button>

				<button type="button" class="btn btn-block btn-primary">Button</button>

				<button type="button" class="btn btn-block btn-primary">Button</button>

				<button type="button" class="btn btn-block btn-primary">Button</button>

				<button type="button" class="btn btn-block btn-primary">Button</button>

				<button type="button" class="btn btn-block btn-primary">Button</button>

				<button type="button" class="btn btn-block btn-primary">Button</button>

				<button type="button" class="btn btn-block btn-primary">Button</button>

				<button type="button" class="btn btn-block btn-primary">Button</button>

				<button type="button" class="btn btn-block btn-primary">Button</button>

				<button type="button" class="btn btn-block btn-primary">Button</button>

				<button type="button" class="btn btn-block btn-primary">Button</button>

					<input type="text" class="form-control" placeholder=".col-sm-2">

					<input type="text" class="form-control" placeholder=".col-sm-3">

					<input type="text" class="form-control" placeholder=".col-xs-4">

							Post 1

							Ut ligula dui, pellentesque vel tortor a, elementum bibendum justo. Fusce adipiscing nibh non felis feugiat, vel malesuada massa tempor. Nullam gravida sem ut diam mattis rutrum. Donec sit amet.

								More...

							Post 2

							Ut ligula dui, pellentesque vel tortor a, elementum bibendum justo. Fusce adipiscing nibh non felis feugiat, vel malesuada massa tempor. Nullam gravida sem ut diam mattis rutrum. Donec sit amet.

								More...

							Post 3

							Ut ligula dui, pellentesque vel tortor a, elementum bibendum justo. Fusce adipiscing nibh non felis feugiat, vel malesuada massa tempor. Nullam gravida sem ut diam mattis rutrum. Donec sit amet.

								More...

							Post 4

							Ut ligula dui, pellentesque vel tortor a, elementum bibendum justo. Fusce adipiscing nibh non felis feugiat, vel malesuada massa tempor. Nullam gravida sem ut diam mattis rutrum. Donec sit amet.

								More...

								#
								Table heading
								Table heading
								Table heading
								Table heading
								Table heading
								Table heading

								1
								Table cell
								Table cell
								Table cell
								Table cell
								Table cell
								Table cell

								2
								Table cell
								Table cell
								Table cell
								Table cell
								Table cell
								Table cell

								3
								Table cell
								Table cell
								Table cell
								Table cell
								Table cell
								Table cell

				<button type="button" class="btn btn-success btn-block">
					etc...
				</button>


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.ruenzuo.weatherapp.activities.CountriesActivity">
    <fragment
        android:id="@+id/countriesListFragment"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        class="com.ruenzuo.weatherapp.fragments.CountriesListFragment" />
</LinearLayout>


text:
sap.ui.define([
	"sap/m/Image",
	"./Adaptation",
	"../Utils",
	"sap/base/Log"
],
function(
	Image,
	Adaptation,
	Utils,
	Log
) {
	"use strict";

	/**
	 * This class is being assigned to the original Fiori Header Toolbar when RTA Toolbar shows
	 * @type {string}
	 */
	var FIORI_HIDDEN_CLASS = "sapUiRtaFioriHeaderInvisible";

	/**
	 * Constructor for a new sap.ui.rta.toolbar.Fiori control
	 *
	 * @class
	 * Contains implementation of Fiori specific toolbar
	 * @extends sap.ui.rta.toolbar.Adaptation
	 *
	 * @author SAP SE
	 * @version ${version}
	 *
	 * @constructor
	 * @private
	 * @since 1.48
	 * @alias sap.ui.rta.toolbar.Fiori
	 * @experimental Since 1.48. This class is experimental. API might be changed in future.
	 */
	var Fiori = Adaptation.extend("sap.ui.rta.toolbar.Fiori", {
		metadata: {
			library: "sap.ui.rta"
		},
		renderer: "sap.ui.rta.toolbar.AdaptationRenderer",
		type: "fiori"
	});

	Fiori.prototype.init = function () {
		this._oRenderer = Utils.getFiori2Renderer();
		this._oFioriHeader = this._oRenderer.getRootControl().getOUnifiedShell().getHeader();
		Adaptation.prototype.init.apply(this, arguments);
	};

	Fiori.prototype.show = function () {
		this._oFioriHeader.addStyleClass(FIORI_HIDDEN_CLASS);
		return Adaptation.prototype.show.apply(this, arguments);
	};

	Fiori.prototype.buildControls = function () {
		return Adaptation.prototype.buildControls.apply(this, arguments).then(function (aControls) {
			var sLogoPath = this._oFioriHeader.getLogo();

			if (this._oFioriHeader.getShowLogo() && sLogoPath) {
				// Unstable: if FLP changes ID of <img> element, logo could be not found
				// $() is still needed because this._oFioriHeader does not offer a getDomRef method
				var oLogo = this._oFioriHeader.$().find("#shell-header-icon").get(0);
				var iWidth;
				var iHeight;

				if (oLogo) {
					iWidth = oLogo.getBoundingClientRect().width;
					iHeight = oLogo.getBoundingClientRect().height;
					this._checkLogoSize(oLogo, iWidth, iHeight);
				}

				this.getControl("iconSpacer").setWidth("10%");

				// first control is the left HBox
				this.getControl("iconBox").addItem(
					new Image(this.getId() + "_fragment--sapUiRta_icon", {
						src: sLogoPath,
						width: iWidth ? iWidth + "px" : iWidth,
						height: iHeight ? iHeight + "px" : iHeight
					})
				);
			}
			return aControls;
		}.bind(this));
	};

	Fiori.prototype.hide = function () {
		return Adaptation.prototype.hide.apply(this, arguments)
		.then(function () {
			this._oFioriHeader.removeStyleClass(FIORI_HIDDEN_CLASS);
		}.bind(this));
	};

	Fiori.prototype._checkLogoSize = function(oLogo, iWidth, iHeight) {
		var iNaturalWidth = oLogo.naturalWidth;
		var iNaturalHeight = oLogo.naturalHeight;

		if (iWidth !== iNaturalWidth || iHeight !== iNaturalHeight) {
			Log.error([
				"sap.ui.rta: please check Fiori Launchpad logo, expected size is",
				iWidth + "x" + iHeight + ",",
				"but actual is " + iNaturalWidth + "x" + iNaturalHeight
			].join(" "));
		}
	};

	Fiori.prototype.destroy = function () {
		// In case of destroy() without normal hide() call.
		this._oFioriHeader.removeStyleClass(FIORI_HIDDEN_CLASS);

		delete this._oRenderer;
		delete this._oFioriHeader;

		Adaptation.prototype.destroy.apply(this, arguments);
	};

	return Fiori;
});


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Class RedirectResponse
   | Titanium Web Proxy </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Class RedirectResponse
   | Titanium Web Proxy ">
    <meta name="generator" content="docfx 2.55.0.0">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="">
    <meta property="docfx:tocrel" content="toc.html">

    <meta property="docfx:rel" content="../">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Class RedirectResponse

The http redirect response.

Inheritance

Object

RequestResponseBase

Response

RedirectResponse

Inherited Members

      Response.StatusCode

      Response.StatusDescription

      Response.HasBody

      Response.KeepAlive

      Response.HeaderText

      RequestResponseBase.BodyInternal

      RequestResponseBase.KeepBody

      RequestResponseBase.HttpVersion

      RequestResponseBase.Headers

      RequestResponseBase.ContentLength

      RequestResponseBase.ContentEncoding

      RequestResponseBase.Encoding

      RequestResponseBase.ContentType

      RequestResponseBase.IsChunked

      RequestResponseBase.Body

      RequestResponseBase.BodyString

      RequestResponseBase.IsBodyRead

      RequestResponseBase.ToString()

      Object.Equals(Object)

      Object.Equals(Object, Object)

      Object.ReferenceEquals(Object, Object)

      Object.GetHashCode()

      Object.GetType()

      Object.MemberwiseClone()

Namespace: Titanium.Web.Proxy.Http.Responses

Assembly: Titanium.Web.Proxy.dll

Syntax

public sealed class RedirectResponse : Response

Constructors

    |
    Improve this Doc

    View Source

RedirectResponse()

Initializes a new instance of the RedirectResponse class.

Declaration

public RedirectResponse()

                    Improve this Doc

                    View Source

              Back to top

            Generated by DocFX


text:
angular.module('cms.admin.posts', [
    'cms.admin.posts.services',
    'cms.admin.posts.controllers'
]);


text:
define([
  'angular',
  'app',
  'underscore'
],
function (angular, app, _) {
  'use strict';

  angular
    .module('kibana.directives')
    .directive('addPanel', function($compile) {
      return {
        restrict: 'A',
        link: function($scope, elem) {

          $scope.$on("$destroy",function() {
            elem.remove();
          });

          $scope.$watch('panel.type', function() {
            var _type = $scope.panel.type;
            $scope.reset_panel(_type);
            if(!_.isUndefined($scope.panel.type)) {
              $scope.panel.loadingEditor = true;
              $scope.require(['panels/'+$scope.panel.type.replace(".","/") +'/module'], function () {
                var template = '

';
                elem.html($compile(angular.element(template))($scope));
                $scope.panel.loadingEditor = false;
              });
            }
          });
        }
      };
    });
});


text:
<form name="form" novalidate>

Path already exists

    The path ({{path}}) already exists.

    <button type="button" class="btn btn-default pull-left" ng-click="skip()">Skip</button>
    <button type="submit" class="btn btn-primary" ng-click="keep()">Keep Both</button>
    <button type="submit" class="btn btn-primary" ng-click="replace()">Replace</button>

</form>


text:
package p1;

public abstract class U2 extends U1 {
    void f() {}
}


text:
/**
 * Created by Administrator on 2015/6/10.
 */

var React = require('react/addons');

import Auth from '../services/AuthService.js';
import objectAssign from 'object-assign';

var LoginStore = require('../stores/login-store');

export default class Login extends React.Component {

    static willTransitionTo(transition){
        if(LoginStore.isLoggedIn()){
            transition.redirect('/');
        }
    }

    constructor(){
        super();
        this.state = {
            user: '',
            password: '',
            extra: ''
        };
    }

    signup(e){
        e.preventDefault();
        Auth.signup(this.state.user, this.state.password)
            .catch(err => {
                alert("There's an error logging in");
                console.log('Error logging in', err);
            });
    }

    render(){
        return (

Signup

                <form role="form">

                        Username
                        <input type="text" valueLink={this.linkState('user')} className="form-control" placeholder="Username" id="username"  />

                        Password
                        <input type="password" valueLink={this.linkState('password')} className="form-control" placeholder="Username" id="password" />

                    <button type="submit" className="btn btn-default" onClick={this.signup.bind(this)}>Submit</button>
                </form>

        );
    }
}

objectAssign(Login.prototype, React.addons.LinkedStateMixin);


text:
<?php

namespace mageekguy\atoum\cli\command;

use mageekguy\atoum\exceptions;

class exception extends exceptions\runtime
{
}


text:
/**
***********************************************************************************************************************
* @file  palVector.h
* @brief PAL utility collection Vector and VectorIterator class declarations.
***********************************************************************************************************************
*/

#pragma once

#include "palUtil.h"
#include "palAssert.h"
#include "palSysMemory.h"
#include <type_traits>

namespace Util
{

// Forward declarations.
template<typename T, uint32 defaultCapacity, typename Allocator> class Vector;

/**
 ***********************************************************************************************************************
 * @brief  Iterator for traversal of elements in Vector.
 *
 * Supports forward traversal.
 ***********************************************************************************************************************
 */
template<typename T, uint32 defaultCapacity, typename Allocator>
class VectorIterator
{
public:
    ~VectorIterator() { }

    /// Checks if the current index is within bounds of the number of elements in the vector.
    ///
    /// @returns True if the current element this iterator is pointing to is within the permitted range.
    bool IsValid() const { return (m_curIndex < m_srcVector.m_numElements); }

    /// Returns the element the iterator is currently pointing to as a reference.
    ///
    /// @warning This may cause an access violation if the iterator is not valid.
    ///
    /// @returns The element the iterator is currently pointing to.
    T& Get() const
    {
        PAL_ASSERT(IsValid());
        return (*(m_srcVector.m_pData + m_curIndex));
    }

    /// Advances the iterator to point to the next element.
    ///
    /// @warning Does not do bounds checking.
    void Next() { ++m_curIndex; }

    /// Retrieves the current vector position of this iterator.
    ///
    /// @returns The location in the vector of the element the iterator is currently pointing to.
    uint32 Position() const { return m_curIndex; }

private:
    VectorIterator(uint32 index, const Vector<T, defaultCapacity, Allocator>& srcVec);

    uint32                                        m_curIndex;  // The current index of the vector iterator.
    const Vector<T, defaultCapacity, Allocator>&  m_srcVector; // The vector container this iterator is used for.

    PAL_DISALLOW_DEFAULT_CTOR(VectorIterator);

    // Although this is a transgression of coding standards, it means that Vector does not need to have a public
    // interface specifically to implement this class. The added encapsulation this provides is worthwhile.
    friend class Vector<T, defaultCapacity, Allocator>;
};

/**
 ***********************************************************************************************************************
 * @brief Vector container.
 *
 * Vector is a templated array based storage that starts with a default-size allocation in the stack. If more space is
 * needed it then resorts to dynamic allocation by doubling the size every time the capacity is exceeded.
 * Operations which this class supports are:
 *
 * - Insertion at the end of the array.
 * - Forward iteration.
 * - Random access.
 *
 * @warning This class is not thread-safe.
 ***********************************************************************************************************************
 */
template<typename T, uint32 defaultCapacity, typename Allocator>
class Vector
{
public:
    /// A convenient shorthand for VectorIterator.
    typedef VectorIterator<T, defaultCapacity, Allocator> Iter;

    /// Constructor.
    ///
    /// @param [in] pAllocator The allocator that will allocate memory if required.
    Vector(Allocator*const pAllocator);

    /// Destructor.
    virtual ~Vector();

    /// Move constructor.
    ///
    /// @param [in] vector Reference to a dying vector, from which resources will be stolen.
    Vector(Vector&& vector);

    /// Increases maximal capacity to value grater or equal to the newCapacity.
    /// If newCapacity is greater than the maximal capacity, new storage is allocated,
    /// otherwise the method does nothing.
    ///
    /// @note All existing iterators will not get invalidated, even in case new storage is allocated,
    ///       because iterators are referencing vector, rather than elements of that vector.
    ///
    /// @warning All pointers and references to elements of a vector will be invalidated,
    ///          in case new storage is allocated.
    ///
    /// @param [in] newCapacity The new capacity of a vector, which is lower limit of the maximal capacity.
    ///
    /// @returns Result ErrorOutOfMemory if the operation failed.
    Result Reserve(uint32 newCapacity);

    /// Set size to newSize.
    /// If size is decreased, elements at the end of the vector will be removed.
    /// If size is increased, new elements will be set to newVal.
    /// If newSize requires a higher capacity, a new allocation is made.  See notes on Reserve.
    ///
    /// @note If size is decreased, any iterators referencing removed elements will become invalid.  All other
    ///       iterators will remain valid.  Otherwise, all iterators will still be valid.
    ///
    /// @warning All pointers and references to elements of a vector will be invalidated,
    ///          in case new storage is allocated.
    ///
    /// @param [in] newSize The new size of a vector.
    ///
    /// @returns Result ErrorOutOfMemory if the operation failed.
    Result Resize(uint32 newSize, const T& newVal = T());

    /// Copy an element to end of the vector. If not enough space is available, new space will be allocated and the old
    /// data will be copied to the new space.
    ///
    /// @param [in] data The element to be pushed to the vector. The element will become the last element.
    ///
    /// @returns Result ErrorOutOfMemory if the operation failed.
    Result PushBack(const T& data);

    /// Returns the element at the end of the vector and destroys it.
    ///
    /// @param [out] pData The element at the end of the vector
    void PopBack(T* pData);

    /// Destroys all elements stored in the vector. All dynamically allocated memory will be saved for reuse.
    void Clear();

    ///@{
    /// Returns the element at the location specified.
    ///
    /// @warning Calling this function with an out-of-bounds index will cause an access violation!
    ///
    /// @param [in] index Integer location of the element needed.
    ///
    /// @returns The element at location specified by index by reference
    T& At(uint32 index)
    {
        PAL_ASSERT(index < m_numElements);
        return *(m_pData + index);
    }

    const T& At(uint32 index) const
    {
        PAL_ASSERT(index < m_numElements);
        return *(m_pData + index);
    }

    T&       operator[](uint32 index) noexcept       { return At(index); }
    const T& operator[](uint32 index) const noexcept { return At(index); }
    ///@}

    /// Returns the data at the front of the vector.
    ///
    /// @warning Calling this function on an empty vector will cause an access violation!
    ///
    /// @returns The data at the front of the vector.
    T& Front() const
    {
        PAL_ASSERT(IsEmpty() == false);
        return *m_pData;
    }

    /// Returns the data at the back of the vector.
    ///
    /// @warning Calling this function on an empty vector will cause an access violation!
    ///
    /// @returns The data at the back of the vector.
    T& Back() const
    {
        PAL_ASSERT(IsEmpty() == false);
        return *(m_pData + (m_numElements - 1));
    }

    /// Returns an iterator to the first element of the vector.
    ///
    /// @warning Accessing an element using an iterator of an empty vector will cause an access violation!
    ///
    /// @returns An iterator to first element of the vector.
    Iter Begin() const { return Iter(0, *this); }

    /// Returns an iterator to the last element of the vector.
    ///
    /// @warning Accessing an element using an iterator of an empty vector will cause an access violation!
    ///
    /// @returns VectorIterator An iterator to last element of the vector.
    Iter End() const { return Iter((m_numElements - 1), *this); }

    /// Returns pointer to the underlying buffer serving as data storage.
    /// The returned pointer defines always valid range [Data(), Data() + NumElements()),
    /// even if the container is empty (Data() is not dereferenceable in that case).
    ///
    /// @warning Dereferencing pointer returned by Data() from an empty vector will cause an access violation!
    ///
    /// @returns Pointer to the underlying data storage for read & write access.
    ///          For a non-empty vector, the returned pointer contains address of the first element.
    ///          For an empty vector, the returned pointer may or may not be a null pointer.
    T* Data() { return m_pData; }

    /// Returns pointer to the underlying buffer serving as data storage.
    /// The returned pointer defines always valid range [Data(), Data() + NumElements()),
    /// even if the container is empty (Data() is not dereferenceable in that case).
    ///
    /// @warning Dereferencing pointer returned by Data() from an empty vector will cause an access violation!
    ///
    /// @returns Pointer to the underlying data storage for read only access.
    ///          For a non-empty vector, the returned pointer contains address of the first element.
    ///          For an empty vector, the returned pointer may or may not be a null pointer.
    const T* Data() const { return m_pData; }

    /// Returns the size of the vector.
    ///
    /// @returns An unsigned integer equal to the number of elements currently present in the vector.
    uint32 NumElements() const { return m_numElements; }

    /// Returns true if the number of elements present in the vector is equal to zero.
    ///
    /// @returns True if the vector is empty.
    bool IsEmpty() const { return (m_numElements == 0); }

    ///@{
    /// @internal Satisfies concept `range_expression`, using T* as `iterator` and 32-bit size and difference types
    ///
    /// @note - These are a convenience intended to be used by c++ language features such as `range for`.
    ///         These should not be called directly as they do not adhere to PAL coding standards.
    using value_type      = T;
    using reference       = T&;
    using const_reference = const T&;
    using iterator        = T*;
    using const_iterator  = const T*;
    using difference_type = int32;
    using size_type       = uint32;

    iterator           begin()  noexcept       { return m_pData; }
    iterator           end()    noexcept       { return (m_pData + m_numElements); }
    const_iterator     begin()  const noexcept { return m_pData; }
    const_iterator     end()    const noexcept { return (m_pData + m_numElements); }
    const_iterator     cbegin() const noexcept { return m_pData; }
    const_iterator     cend()   const noexcept { return (m_pData + m_numElements); }
    PAL_NODISCARD bool empty()  const noexcept { return IsEmpty(); }
    size_type          size()   const noexcept { return m_numElements; }
    ///@}

private:
    // This is a POD-type that exactly fits one T value.
    typedef typename std::aligned_storage<sizeof(T), alignof(T)>::type ValueStorage;

    ValueStorage     m_data[defaultCapacity];  // The initial data buffer stored within the vector object.
    T*               m_pData;                  // Pointer to the current data buffer.
    uint32           m_numElements;            // Number of elements present.
    uint32           m_maxCapacity;            // Maximum size it can hold.
    Allocator*const  m_pAllocator;             // Allocator for this Vector.

    PAL_DISALLOW_COPY_AND_ASSIGN(Vector);

    // Although this is a transgression of coding standards, it prevents VectorIterator requiring a public constructor;
    // constructing a 'bare' VectorIterator (i.e. without calling Vector::GetIterator) can never be a legal operation,
    // so this means that these two classes are much safer to use.
    friend class VectorIterator<T, defaultCapacity, Allocator>;
};

// =====================================================================================================================
template<typename T, uint32 defaultCapacity, typename Allocator>
VectorIterator<T, defaultCapacity, Allocator>::VectorIterator(
    uint32                                       index,
    const Vector<T, defaultCapacity, Allocator>& srcVec)
    :
    m_curIndex(index),
    m_srcVector(srcVec)
 {
 }

// =====================================================================================================================
template<typename T, uint32 defaultCapacity, typename Allocator>
Vector<T, defaultCapacity, Allocator>::Vector(
    Allocator*const pAllocator)
    :
    m_pData(reinterpret_cast<T*>(m_data)),
    m_numElements(0),
    m_maxCapacity(defaultCapacity),
    m_pAllocator(pAllocator)
 {
 }

// =====================================================================================================================
template<typename T, uint32 defaultCapacity, typename Allocator>
Vector<T, defaultCapacity, Allocator>::~Vector()
{
    // Explicitly destroy all non-trivial types.
    if (!std::is_pod<T>::value)
    {
        for (uint32 idx = 0; idx < m_numElements; ++idx)
        {
            m_pData[idx].~T();
        }
    }

    // Check if we have dynamically allocated memory.
    if (m_pData != reinterpret_cast<T*>(m_data))
    {
        // Free the memory that was allocated dynamically.
        PAL_FREE(m_pData, m_pAllocator);
    }
}

// =====================================================================================================================
// Steals allocation from a dying vector, if data buffer uses storage from heap allocation.
// Moves objects between local buffers of new and dying vectors (for non-trivial types) or
// copies local buffer from a dying vector to a new vector (for trivial types),
// if data buffer uses storage from local buffer.
template<typename T, uint32 defaultCapacity, typename Allocator>
Vector<T, defaultCapacity, Allocator>::Vector(
    Vector&& vector)
    :
    m_numElements(vector.m_numElements),
    m_maxCapacity(vector.m_maxCapacity),
    m_pAllocator(vector.m_pAllocator)
{
    if (vector.m_pData == reinterpret_cast<T*>(vector.m_data)) // Local buffer
    {
        // Data buffer will be using storage from local buffer.
        m_pData = reinterpret_cast<T*>(m_data);

        if (std::is_pod<T>::value)
        {
            // Optimize trivial types by copying local buffer.
            std::memcpy(m_pData, vector.m_pData, sizeof(T) * m_numElements);
        }
        else
        {
            // Move objects from local buffer of a dying vector to local buffer of a new vector.
            for (uint32 idx = 0; idx < m_numElements; ++idx)
            {
                PAL_PLACEMENT_NEW(m_pData + idx) T(Move(vector.m_pData[idx]));
            }
        }
    }
    else // Heap allocation
    {
        // Steal heap allocation from dying vector.
        m_pData = vector.m_pData;

        // After the allocation has been stolen, dying vector is just an empty shell.
        vector.m_pData = nullptr;
        vector.m_numElements = 0;
        vector.m_maxCapacity = 0;
    }
}

} // Util


text:
require 'rails_helper'

RSpec.describe "profiles/new", type: :view do
  before(:each) do
    assign(:profile, FactoryGirl.build(:profile))
  end

  it "renders new profile form" do
    render

    assert_select "form[action=?][method=?]", profiles_path, "post" do
      assert_select "input#profile_first_name[name=?]", "profile[first_name]"
    end
  end
end


text:
/*
 * driver.h
 *
 *  Created on: Jan 23, 2013
 *      Author: fraser
 */

#ifndef DRIVER_H_
#define DRIVER_H_

#include "systemc.h"
#include <cstdlib>		// for srand and rand
using namespace sc_core;
using namespace sc_dt;

#ifndef __SBSC_PARMS__
	#define __SBSC_PARMS__
	const static int WIDTH = 16;	// width of words passing thru conduit
	const static int DELAY = 5;		// SC_NS to wait between operations
	const static int LENGTH = 1;
	const static int DEPTH = 32;
#endif

namespace sbsc {
class driver : public sc_module {

public:

	driver(sc_module_name);
	~driver();

	void driver_thread(void);

	int rv;
	sc_in<bool> clock;
	sc_in<sc_logic> clken;
	sc_out<sc_lv<WIDTH> > driver_port;
	sc_lv<WIDTH> tval;
	SC_HAS_PROCESS(driver);

};

}

#endif /* DRIVER_H_ */


text:
package hse.thesis.eusuilang.expression.typesystem;

/*Generated by MPS */

import jetbrains.mps.lang.typesystem.runtime.AbstractInferenceRule_Runtime;
import jetbrains.mps.lang.typesystem.runtime.InferenceRule_Runtime;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.typesystem.inference.TypeCheckingContext;
import jetbrains.mps.lang.typesystem.runtime.IsApplicableStatus;
import jetbrains.mps.typesystem.inference.EquationInfo;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
import org.jetbrains.mps.openapi.language.SAbstractConcept;

public class typeof_MathVarReference_InferenceRule extends AbstractInferenceRule_Runtime implements InferenceRule_Runtime {
  public typeof_MathVarReference_InferenceRule() {
  }
  public void applyRule(final SNode reference, final TypeCheckingContext typeCheckingContext, IsApplicableStatus status) {
    {
      SNode _nodeToCheck_1029348928467 = reference;
      EquationInfo _info_12389875345 = new EquationInfo(_nodeToCheck_1029348928467, null, "r:e1395c80-87e9-42f4-a177-ce7747c8d20b(hse.thesis.eusuilang.expression.typesystem)", "3428160356732630529", 0, null);
      typeCheckingContext.createEquation((SNode) typeCheckingContext.typeOf(_nodeToCheck_1029348928467, "r:e1395c80-87e9-42f4-a177-ce7747c8d20b(hse.thesis.eusuilang.expression.typesystem)", "3428160356732626392", true), (SNode) typeCheckingContext.typeOf(SLinkOperations.getTarget(reference, MetaAdapterFactory.getReferenceLink(0x803eb20bd0744b77L, 0xa6bafeb2b2f284caL, 0x2f9345ae681eb24eL, 0x2f9345ae681fbf1bL, "declaration")), "r:e1395c80-87e9-42f4-a177-ce7747c8d20b(hse.thesis.eusuilang.expression.typesystem)", "3428160356732630553", true), _info_12389875345);
    }
  }
  public SAbstractConcept getApplicableConcept() {
    return MetaAdapterFactory.getConcept(0x803eb20bd0744b77L, 0xa6bafeb2b2f284caL, 0x2f9345ae681eb24eL, "hse.thesis.eusuilang.expression.structure.MathVarReference");
  }
  public IsApplicableStatus isApplicableAndPattern(SNode argument) {
    return new IsApplicableStatus(argument.getConcept().isSubConceptOf(getApplicableConcept()), null);
  }
  public boolean overrides() {
    return false;
  }
}


text:
#include <aws/kinesisanalyticsv2/model/AddApplicationReferenceDataSourceRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::KinesisAnalyticsV2::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

AddApplicationReferenceDataSourceRequest::AddApplicationReferenceDataSourceRequest() :
    m_applicationNameHasBeenSet(false),
    m_currentApplicationVersionId(0),
    m_currentApplicationVersionIdHasBeenSet(false),
    m_referenceDataSourceHasBeenSet(false)
{
}

Aws::String AddApplicationReferenceDataSourceRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_applicationNameHasBeenSet)
  {
   payload.WithString("ApplicationName", m_applicationName);

  }

  if(m_currentApplicationVersionIdHasBeenSet)
  {
   payload.WithInt64("CurrentApplicationVersionId", m_currentApplicationVersionId);

  }

  if(m_referenceDataSourceHasBeenSet)
  {
   payload.WithObject("ReferenceDataSource", m_referenceDataSource.Jsonize());

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection AddApplicationReferenceDataSourceRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "KinesisAnalytics_20180523.AddApplicationReferenceDataSource"));
  return headers;

}


text:
<?

require_once dirname(__FILE__) . '/object.php';

class SSList extends SSObject
{

	function class_name () { return 'List'; }
	function uri ()        { return '/audiences/:audience_id/lists'; }

	function find ($type, $options = array())
	{
		$res = &SSResource::resource();
		return $res->find('List', $type, $options);
	}

}

?>


text:
import unittest

import requests_mock

from canvasapi import Canvas
from tests import settings
from tests.util import register_uris

@requests_mock.Mocker()
class TestExternalFeed(unittest.TestCase):
    def setUp(self):
        self.canvas = Canvas(settings.BASE_URL, settings.API_KEY)

        with requests_mock.Mocker() as m:
            register_uris({"course": ["get_by_id", "list_external_feeds"]}, m)

            self.course = self.canvas.get_course(1)
            self.external_feed = self.course.get_external_feeds()[0]

    # __str__()
    def test__str__(self, m):
        string = str(self.external_feed)
        self.assertIsInstance(string, str)


text:
var db = require('../db.js')
var Promise = require('knex/node_modules/bluebird')

var Questions = module.exports = {

	find: function (uid) {
    return db('questions').select('*').where({ uid: uid }).limit(1)
      .then(function(rows) {
        return (rows.length === 0) ? Promise.reject(new Error('not_found')) : rows[0]
      })
  },

  create: function (attrs) {
    attrs.created_at = new Date()
    return db('questions').insert(attrs).return(attrs)
  },

  retrieveAll: function (callback) {
    return db('questions').select('*')
    .then(function(rows){
     return (rows.length === 0) ? callback({title:'Questions WIll Be here!!!!'}) : callback(rows)
    })
  },

  update: function (attrs) {
    attrs.updated_at = new Date()
    console.log(attrs.uid)
    return db('questions').update(attrs).where({ uid: attrs.uid })
      .then(function(affectedCount) {
        return (affectedCount === 0) ? Promise.reject(new Error('not_found')) : attrs
      })
  },
  updateOrCreate: function (attrs) {
    return Questions.update(attrs).catch(Questions.create.papp(attrs))
  }

}


text:
from django.http import Http404
from django.shortcuts import get_object_or_404, render, redirect
from django.utils.encoding import force_text
from django.utils.text import capfirst
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from wagtail.wagtailadmin.edit_handlers import ObjectList, extract_panel_definitions_from_model_class

from wagtail.wagtailsnippets.models import get_snippet_content_types
from wagtail.wagtailsnippets.permissions import user_can_edit_snippet_type
from wagtail.wagtailadmin import messages

# == Helper functions ==

def get_snippet_type_name(content_type):
    """ e.g. given the 'advert' content type, return ('Advert', 'Adverts') """
    # why oh why is this so convoluted?
    opts = content_type.model_class()._meta
    return (
        force_text(opts.verbose_name),
        force_text(opts.verbose_name_plural)
    )

def get_snippet_type_description(content_type):
    """ return the meta description of the class associated with the given content type """
    opts = content_type.model_class()._meta
    try:
        return force_text(opts.description)
    except:
        return ''

def get_content_type_from_url_params(app_name, model_name):
    """
    retrieve a content type from an app_name / model_name combo.
    Throw Http404 if not a valid snippet type
    """
    try:
        content_type = ContentType.objects.get_by_natural_key(app_name, model_name)
    except ContentType.DoesNotExist:
        raise Http404
    if content_type not in get_snippet_content_types():
        # don't allow people to hack the URL to edit content types that aren't registered as snippets
        raise Http404

    return content_type

SNIPPET_EDIT_HANDLERS = {}

def get_snippet_edit_handler(model):
    if model not in SNIPPET_EDIT_HANDLERS:
        panels = extract_panel_definitions_from_model_class(model)
        edit_handler = ObjectList(panels).bind_to_model(model)

        SNIPPET_EDIT_HANDLERS[model] = edit_handler

    return SNIPPET_EDIT_HANDLERS[model]

# == Views ==

def index(request):
    snippet_types = [
        (
            get_snippet_type_name(content_type)[1],
            get_snippet_type_description(content_type),
            content_type
        )
        for content_type in get_snippet_content_types()
        if user_can_edit_snippet_type(request.user, content_type)
    ]
    return render(request, 'wagtailsnippets/snippets/index.html', {
        'snippet_types': sorted(snippet_types, key=lambda x: x[0].lower()),
    })

def list(request, content_type_app_name, content_type_model_name):
    content_type = get_content_type_from_url_params(content_type_app_name, content_type_model_name)
    if not user_can_edit_snippet_type(request.user, content_type):
        raise PermissionDenied

    model = content_type.model_class()
    snippet_type_name, snippet_type_name_plural = get_snippet_type_name(content_type)

    items = model.objects.all()

    # Pagination
    p = request.GET.get('p', 1)
    paginator = Paginator(items, 20)

    try:
        paginated_items = paginator.page(p)
    except PageNotAnInteger:
        paginated_items = paginator.page(1)
    except EmptyPage:
        paginated_items = paginator.page(paginator.num_pages)

    return render(request, 'wagtailsnippets/snippets/type_index.html', {
        'content_type': content_type,
        'snippet_type_name': snippet_type_name,
        'snippet_type_name_plural': snippet_type_name_plural,
        'items': paginated_items,
    })

def create(request, content_type_app_name, content_type_model_name):
    content_type = get_content_type_from_url_params(content_type_app_name, content_type_model_name)
    if not user_can_edit_snippet_type(request.user, content_type):
        raise PermissionDenied

    model = content_type.model_class()
    snippet_type_name = get_snippet_type_name(content_type)[0]

    instance = model()
    edit_handler_class = get_snippet_edit_handler(model)
    form_class = edit_handler_class.get_form_class(model)

    if request.POST:
        form = form_class(request.POST, request.FILES, instance=instance)

        if form.is_valid():
            form.save()

            messages.success(
                request,
                _("{snippet_type} '{instance}' created.").format(
                    snippet_type=capfirst(get_snippet_type_name(content_type)[0]),
                    instance=instance
                ),
                buttons=[
                    messages.button(reverse('wagtailsnippets_edit', args=(content_type_app_name, content_type_model_name, instance.id)), _('Edit'))
                ]
            )
            return redirect('wagtailsnippets_list', content_type.app_label, content_type.model)
        else:
            messages.error(request, _("The snippet could not be created due to errors."))
            edit_handler = edit_handler_class(instance=instance, form=form)
    else:
        form = form_class(instance=instance)
        edit_handler = edit_handler_class(instance=instance, form=form)

    return render(request, 'wagtailsnippets/snippets/create.html', {
        'content_type': content_type,
        'snippet_type_name': snippet_type_name,
        'edit_handler': edit_handler,
    })

def edit(request, content_type_app_name, content_type_model_name, id):
    content_type = get_content_type_from_url_params(content_type_app_name, content_type_model_name)
    if not user_can_edit_snippet_type(request.user, content_type):
        raise PermissionDenied

    model = content_type.model_class()
    snippet_type_name = get_snippet_type_name(content_type)[0]

    instance = get_object_or_404(model, id=id)
    edit_handler_class = get_snippet_edit_handler(model)
    form_class = edit_handler_class.get_form_class(model)

    if request.POST:
        form = form_class(request.POST, request.FILES, instance=instance)

        if form.is_valid():
            form.save()

            messages.success(
                request,
                _("{snippet_type} '{instance}' updated.").format(
                    snippet_type=capfirst(snippet_type_name),
                    instance=instance
                ),
                buttons=[
                    messages.button(reverse('wagtailsnippets_edit', args=(content_type_app_name, content_type_model_name, instance.id)), _('Edit'))
                ]
            )
            return redirect('wagtailsnippets_list', content_type.app_label, content_type.model)
        else:
            messages.error(request, _("The snippet could not be saved due to errors."))
            edit_handler = edit_handler_class(instance=instance, form=form)
    else:
        form = form_class(instance=instance)
        edit_handler = edit_handler_class(instance=instance, form=form)

    return render(request, 'wagtailsnippets/snippets/edit.html', {
        'content_type': content_type,
        'snippet_type_name': snippet_type_name,
        'instance': instance,
        'edit_handler': edit_handler
    })

def delete(request, content_type_app_name, content_type_model_name, id):
    content_type = get_content_type_from_url_params(content_type_app_name, content_type_model_name)
    if not user_can_edit_snippet_type(request.user, content_type):
        raise PermissionDenied

    model = content_type.model_class()
    snippet_type_name = get_snippet_type_name(content_type)[0]

    instance = get_object_or_404(model, id=id)

    if request.POST:
        instance.delete()
        messages.success(
            request,
            _("{snippet_type} '{instance}' deleted.").format(
                snippet_type=capfirst(snippet_type_name),
                instance=instance
            )
        )
        return redirect('wagtailsnippets_list', content_type.app_label, content_type.model)

    return render(request, 'wagtailsnippets/snippets/confirm_delete.html', {
        'content_type': content_type,
        'snippet_type_name': snippet_type_name,
        'instance': instance,
    })

def usage(request, content_type_app_name, content_type_model_name, id):
    content_type = get_content_type_from_url_params(content_type_app_name, content_type_model_name)
    model = content_type.model_class()
    instance = get_object_or_404(model, id=id)

    # Pagination
    p = request.GET.get('p', 1)
    paginator = Paginator(instance.get_usage(), 20)

    try:
        used_by = paginator.page(p)
    except PageNotAnInteger:
        used_by = paginator.page(1)
    except EmptyPage:
        used_by = paginator.page(paginator.num_pages)

    return render(request, "wagtailsnippets/snippets/usage.html", {
        'instance': instance,
        'used_by': used_by
    })


text:
class Spree::Chimpy::OrderSource < ActiveRecord::Base
  self.table_name = :spree_chimpy_order_sources
  belongs_to :order, class_name: 'Spree::Order'
end


text:
Navigation

                        <?php
                            if(isset($menu)){
                                echo $menu;
                            }
                        ?>


text:
CoderClicker.IO
===============

Coder Clicker done with Socket.IO.


text:
package com.wut.resources.common;

// TODO this shouldn't be in common!!!
public class MissingParameterException extends Exception {
	private static final long serialVersionUID = 23452461254L;
	public MissingParameterException(String name) {
		super("Missing Parameter " + name);
	}
	public MissingParameterException(String dependency, String[] names) {
		super("If parameter " + dependency + " is present you must also send the following parameters: " + String.join(", ", names));
	}
}


text:
it("should define global object with property", function () {
	require("./module");
	expect(MyLibrary["answer"]).toEqual(42);
});

export const answer = 42;


text:
package strategicpatch

import (
	"encoding/json"
	"fmt"
	"reflect"
	"testing"

	"github.com/davecgh/go-spew/spew"
	"github.com/ghodss/yaml"
)

type SortMergeListTestCases struct {
	TestCases []SortMergeListTestCase
}

type SortMergeListTestCase struct {
	Description string
	Original    map[string]interface{}
	Sorted      map[string]interface{}
}

type StrategicMergePatchTestCases struct {
	TestCases []StrategicMergePatchTestCase
}

type StrategicMergePatchTestCase struct {
	Description string
	StrategicMergePatchTestCaseData
}

type StrategicMergePatchTestCaseData struct {
	Original map[string]interface{}
	TwoWay   map[string]interface{}
	Modified map[string]interface{}
	Current  map[string]interface{}
	ThreeWay map[string]interface{}
	Result   map[string]interface{}
}

type MergeItem struct {
	Name              string
	Value             string
	Other             string
	MergingList       []MergeItem `patchStrategy:"merge" patchMergeKey:"name"`
	NonMergingList    []MergeItem
	MergingIntList    []int `patchStrategy:"merge"`
	NonMergingIntList []int
	MergeItemPtr      *MergeItem `patchStrategy:"merge" patchMergeKey:"name"`
	SimpleMap         map[string]string
}

var mergeItem MergeItem

// These are test cases for SortMergeList, used to assert that it (recursively)
// sorts both merging and non merging lists correctly.
var sortMergeListTestCaseData = []byte(`
testCases:
  - description: sort one list of maps
    original:
      mergingList:
        - name: 1
        - name: 3
        - name: 2
    sorted:
      mergingList:
        - name: 1
        - name: 2
        - name: 3
  - description: sort lists of maps but not nested lists of maps
    original:
      mergingList:
        - name: 2
          nonMergingList:
            - name: 1
            - name: 3
            - name: 2
        - name: 1
          nonMergingList:
            - name: 2
            - name: 1
    sorted:
      mergingList:
        - name: 1
          nonMergingList:
            - name: 2
            - name: 1
        - name: 2
          nonMergingList:
            - name: 1
            - name: 3
            - name: 2
  - description: sort lists of maps and nested lists of maps
    fieldTypes:
    original:
      mergingList:
        - name: 2
          mergingList:
            - name: 1
            - name: 3
            - name: 2
        - name: 1
          mergingList:
            - name: 2
            - name: 1
    sorted:
      mergingList:
        - name: 1
          mergingList:
            - name: 1
            - name: 2
        - name: 2
          mergingList:
            - name: 1
            - name: 2
            - name: 3
  - description: merging list should NOT sort when nested in non merging list
    original:
      nonMergingList:
        - name: 2
          mergingList:
            - name: 1
            - name: 3
            - name: 2
        - name: 1
          mergingList:
            - name: 2
            - name: 1
    sorted:
      nonMergingList:
        - name: 2
          mergingList:
            - name: 1
            - name: 3
            - name: 2
        - name: 1
          mergingList:
            - name: 2
            - name: 1
  - description: sort very nested list of maps
    fieldTypes:
    original:
      mergingList:
        - mergingList:
            - mergingList:
                - name: 2
                - name: 1
    sorted:
      mergingList:
        - mergingList:
            - mergingList:
                - name: 1
                - name: 2
  - description: sort nested lists of ints
    original:
      mergingList:
        - name: 2
          mergingIntList:
            - 1
            - 3
            - 2
        - name: 1
          mergingIntList:
            - 2
            - 1
    sorted:
      mergingList:
        - name: 1
          mergingIntList:
            - 1
            - 2
        - name: 2
          mergingIntList:
            - 1
            - 2
            - 3
  - description: sort nested pointers of ints
    original:
      mergeItemPtr:
        - name: 2
          mergingIntList:
            - 1
            - 3
            - 2
        - name: 1
          mergingIntList:
            - 2
            - 1
    sorted:
      mergeItemPtr:
        - name: 1
          mergingIntList:
            - 1
            - 2
        - name: 2
          mergingIntList:
            - 1
            - 2
            - 3
  - description: sort merging list by pointer
    original:
      mergeItemPtr:
        - name: 1
        - name: 3
        - name: 2
    sorted:
      mergeItemPtr:
        - name: 1
        - name: 2
        - name: 3
`)

func TestSortMergeLists(t *testing.T) {
	tc := SortMergeListTestCases{}
	err := yaml.Unmarshal(sortMergeListTestCaseData, &tc)
	if err != nil {
		t.Errorf("can't unmarshal test cases:%s\n", err)
		return
	}

	for _, c := range tc.TestCases {
		original := testObjectToJSONOrFail(t, c.Original, c.Description)
		sorted := testObjectToJSONOrFail(t, c.Sorted, c.Description)
		if !reflect.DeepEqual(original, sorted) {
			t.Errorf("error in test case: %s\ncannot sort object:\n%s\n%sexpected:\n%s\ngot:\n%s\n",
				c.Description, toYAMLOrError(c.Original), toYAMLOrError(c.Sorted), jsonToYAMLOrError(original))
		}
	}
}

// These are test cases for StrategicMergePatch that cannot be generated using
// CreateTwoWayMergePatch because it doesn't use the replace directive, generate
// duplicate integers for a merging list patch, or generate empty merging lists.
var customStrategicMergePatchTestCaseData = []byte(`
testCases:
  - description: unique scalars when merging lists
    original:
      mergingIntList:
        - 1
        - 2
    twoWay:
      mergingIntList:
        - 2
        - 3
    modified:
      mergingIntList:
        - 1
        - 2
        - 3
  - description: delete all items from merging list
    original:
      mergingList:
        - name: 1
        - name: 2
    twoWay:
      mergingList:
        - $patch: replace
    modified:
      mergingList: []
  - description: merge empty merging lists
    original:
      mergingList: []
    twoWay:
      mergingList: []
    modified:
      mergingList: []
  - description: delete all keys from map
    original:
      name: 1
      value: 1
    twoWay:
      $patch: replace
    modified: {}
  - description: add key and delete all keys from map
    original:
      name: 1
      value: 1
    twoWay:
      other: a
      $patch: replace
    modified:
      other: a
`)

func TestCustomStrategicMergePatch(t *testing.T) {
	tc := StrategicMergePatchTestCases{}
	err := yaml.Unmarshal(customStrategicMergePatchTestCaseData, &tc)
	if err != nil {
		t.Errorf("can't unmarshal test cases:%v\n", err)
		return
	}

	for _, c := range tc.TestCases {
		original, twoWay, modified := twoWayTestCaseToJSONOrFail(t, c)
		testPatchApplication(t, original, twoWay, modified, c.Description)
	}
}

// These are test cases for StrategicMergePatch, to assert that applying  a patch
// yields the correct outcome. They are also test cases for CreateTwoWayMergePatch
// and CreateThreeWayMergePatch, to assert that they both generate the correct patch
// for the given set of input documents.
//
var createStrategicMergePatchTestCaseData = []byte(`
testCases:
  - description: add field to map
    original:
      name: 1
    twoWay:
      value: 1
    modified:
      name: 1
      value: 1
    current:
      name: 1
      other: a
    threeWay:
      value: 1
    result:
      name: 1
      value: 1
      other: a
  - description: add field to map with conflict
    original:
      name: 1
    twoWay:
      value: 1
    modified:
      name: 1
      value: 1
    current:
      name: a
      other: a
    threeWay:
      name: 1
      value: 1
    result:
      name: 1
      value: 1
      other: a
  - description: add field and delete field from map
    original:
      name: 1
    twoWay:
      name: null
      value: 1
    modified:
      value: 1
    current:
      name: 1
      other: a
    threeWay:
      name: null
      value: 1
    result:
      value: 1
      other: a
  - description: delete field from nested map
    original:
      simpleMap:
        key1: 1
        key2: 1
    twoWay:
      simpleMap:
        key2: null
    modified:
      simpleMap:
        key1: 1
    current:
      simpleMap:
        key1: 1
        key2: 1
        other: a
    threeWay:
      simpleMap:
        key2: null
    result:
      simpleMap:
        key1: 1
        other: a
  - description: delete field from nested map with conflict
    original:
      simpleMap:
        key1: 1
        key2: 1
    twoWay:
      simpleMap:
        key2: null
    modified:
      simpleMap:
        key1: 1
    current:
      simpleMap:
        key1: a
        key2: 1
        other: a
    threeWay:
      simpleMap:
        key1: 1
        key2: null
    result:
      simpleMap:
        key1: 1
        other: a
  - description: delete all fields from map
    original:
      name: 1
      value: 1
    twoWay:
      name: null
      value: null
    modified: {}
    current:
      name: 1
      value: 1
      other: a
    threeWay:
      name: null
      value: null
    result:
      other: a
  - description: add field and delete all fields from map
    original:
      name: 1
      value: 1
    twoWay:
      name: null
      value: null
      other: a
    modified:
      other: a
    current:
      name: 1
      value: a
      other: b
    threeWay:
      name: null
      value: null
      other: a
    result:
      other: a
  - description: replace list of scalars
    original:
      nonMergingIntList:
        - 1
        - 2
    twoWay:
      nonMergingIntList:
        - 2
        - 3
    modified:
      nonMergingIntList:
        - 2
        - 3
    current:
      nonMergingIntList:
        - 1
    threeWay:
      nonMergingIntList:
        - 2
        - 3
    result:
      nonMergingIntList:
        - 2
        - 3
  - description: merge lists of scalars
    original:
      mergingIntList:
        - 1
        - 2
    twoWay:
      mergingIntList:
        - 3
    modified:
      mergingIntList:
        - 1
        - 2
        - 3
    current:
      mergingIntList:
        - 1
        - 2
        - 4
    threeWay:
      mergingIntList:
        - 3
    result:
      mergingIntList:
        - 1
        - 2
        - 3
        - 4
  - description: merge lists of maps
    original:
      mergingList:
        - name: 1
        - name: 2
          value: 2
    twoWay:
      mergingList:
        - name: 3
          value: 3
    modified:
      mergingList:
        - name: 1
        - name: 2
          value: 2
        - name: 3
          value: 3
    current:
      mergingList:
        - name: 1
          other: a
        - name: 2
          value: 2
          other: b
    threeWay:
      mergingList:
        - name: 3
          value: 3
    result:
      mergingList:
        - name: 1
          other: a
        - name: 2
          value: 2
          other: b
        - name: 3
          value: 3
  - description: add field to map in merging list
    original:
      mergingList:
        - name: 1
        - name: 2
          value: 2
    twoWay:
      mergingList:
        - name: 1
          value: 1
    modified:
      mergingList:
        - name: 1
          value: 1
        - name: 2
          value: 2
    current:
      mergingList:
        - name: 1
          other: a
        - name: 2
          value: 2
          other: b
    threeWay:
      mergingList:
        - name: 1
          value: 1
    result:
      mergingList:
        - name: 1
          value: 1
          other: a
        - name: 2
          value: 2
          other: b
  - description: add duplicate field to map in merging list
    original:
      mergingList:
        - name: 1
        - name: 2
          value: 2
    twoWay:
      mergingList:
        - name: 1
          value: 1
    modified:
      mergingList:
        - name: 1
          value: 1
        - name: 2
          value: 2
    current:
      mergingList:
        - name: 1
          value: 1
          other: a
        - name: 2
          value: 2
          other: b
    threeWay:
      {}
    result:
      mergingList:
        - name: 1
          value: 1
          other: a
        - name: 2
          value: 2
          other: b
  - description: replace map field value in merging list
    original:
      mergingList:
        - name: 1
          value: 1
        - name: 2
          value: 2
    twoWay:
      mergingList:
        - name: 1
          value: a
    modified:
      mergingList:
        - name: 1
          value: a
        - name: 2
          value: 2
    current:
      mergingList:
        - name: 1
          value: 1
          other: a
        - name: 2
          value: 2
          other: b
    threeWay:
      mergingList:
        - name: 1
          value: a
    result:
      mergingList:
        - name: 1
          value: a
          other: a
        - name: 2
          value: 2
          other: b
  - description: replace map field value in merging list with conflict
    original:
      mergingList:
        - name: 1
          value: 1
        - name: 2
          value: 2
    twoWay:
      mergingList:
        - name: 1
          value: a
    modified:
      mergingList:
        - name: 1
          value: a
        - name: 2
          value: 2
    current:
      mergingList:
        - name: 1
          value: 1
          other: a
        - name: 2
          value: b
          other: b
    threeWay:
      mergingList:
        - name: 1
          value: a
        - name: 2
          value: 2
    result:
      mergingList:
        - name: 1
          value: a
          other: a
        - name: 2
          value: 2
          other: b
  - description: delete map from merging list
    original:
      mergingList:
        - name: 1
        - name: 2
    twoWay:
      mergingList:
        - name: 1
          $patch: delete
    modified:
      mergingList:
        - name: 2
    current:
      mergingList:
        - name: 1
          other: a
        - name: 2
          other: b
    threeWay:
      mergingList:
        - name: 1
          $patch: delete
    result:
      mergingList:
        - name: 2
          other: b
  - description: delete missing map from merging list
    original:
      mergingList:
        - name: 1
        - name: 2
    twoWay:
      mergingList:
        - name: 1
          $patch: delete
    modified:
      mergingList:
        - name: 2
    current:
      mergingList:
        - name: 2
          other: b
    threeWay:
      mergingList:
        - name: 1
          $patch: delete
    result:
      mergingList:
        - name: 2
          other: b
  - description: delete map from merging list with conflict
    original:
      mergingList:
        - name: 1
        - name: 2
    twoWay:
      mergingList:
        - name: 1
          $patch: delete
    modified:
      mergingList:
        - name: 2
    current:
      mergingList:
        - name: 1
          other: a
    threeWay:
      mergingList:
        - name: 1
          $patch: delete
        - name: 2
    result:
      mergingList:
        - name: 2
  - description: add map and delete map from merging list
    original:
      merginglist:
        - name: 1
        - name: 2
    twoWay:
      merginglist:
        - name: 1
          $patch: delete
        - name: 3
    modified:
      merginglist:
        - name: 2
        - name: 3
    current:
      merginglist:
        - name: 1
          other: a
        - name: 2
          other: b
        - name: 4
          other: c
    threeWay:
      merginglist:
        - name: 1
          $patch: delete
        - name: 3
    result:
      merginglist:
        - name: 2
          other: b
        - name: 3
        - name: 4
          other: c
  - description: add map and delete map from merging list with conflict
    original:
      merginglist:
        - name: 1
        - name: 2
    twoWay:
      merginglist:
        - name: 1
          $patch: delete
        - name: 3
    modified:
      merginglist:
        - name: 2
        - name: 3
    current:
      merginglist:
        - name: 1
          other: a
        - name: 4
          other: c
    threeWay:
      merginglist:
        - name: 1
          $patch: delete
        - name: 2
        - name: 3
    result:
      merginglist:
        - name: 2
        - name: 3
        - name: 4
          other: c
  - description: delete all maps from merging list
    original:
      mergingList:
        - name: 1
        - name: 2
    twoWay:
      mergingList:
        - name: 1
          $patch: delete
        - name: 2
          $patch: delete
    modified:
      mergingList: []
    current:
      mergingList:
        - name: 1
          other: a
        - name: 2
          other: b
    threeWay:
      mergingList:
        - name: 1
          $patch: delete
        - name: 2
          $patch: delete
    result:
      mergingList: []
  - description: delete all maps from partially empty merging list
    original:
      mergingList:
        - name: 1
        - name: 2
    twoWay:
      mergingList:
        - name: 1
          $patch: delete
        - name: 2
          $patch: delete
    modified:
      mergingList: []
    current:
      mergingList:
        - name: 1
          other: a
    threeWay:
      mergingList:
        - name: 1
          $patch: delete
        - name: 2
          $patch: delete
    result:
      mergingList: []
  - description: delete all maps from empty merging list
    original:
      mergingList:
        - name: 1
        - name: 2
    twoWay:
      mergingList:
        - name: 1
          $patch: delete
        - name: 2
          $patch: delete
    modified:
      mergingList: []
    current:
      mergingList: []
    threeWay:
      mergingList:
        - name: 1
          $patch: delete
        - name: 2
          $patch: delete
    result:
      mergingList: []
  - description: delete field from map in merging list
    original:
      mergingList:
        - name: 1
          value: 1
        - name: 2
          value: 2
    twoWay:
      mergingList:
        - name: 1
          value: null
    modified:
      mergingList:
        - name: 1
        - name: 2
          value: 2
    current:
      mergingList:
        - name: 1
          value: 1
          other: a
        - name: 2
          other: b
    threeWay:
      mergingList:
        - name: 1
          value: null
        - name: 2
          value: 2
    result:
      mergingList:
        - name: 1
          other: a
        - name: 2
          value: 2
          other: b
  - description: delete field from map in merging list with conflict
    original:
      mergingList:
        - name: 1
          value: 1
        - name: 2
          value: 2
    twoWay:
      mergingList:
        - name: 1
          value: null
    modified:
      mergingList:
        - name: 1
        - name: 2
          value: 2
    current:
      mergingList:
        - name: 1
          value: a
          other: a
    threeWay:
      mergingList:
        - name: 1
          value: null
        - name: 2
          value: 2
    result:
      mergingList:
        - name: 1
          other: a
        - name: 2
          value: 2
  - description: replace non merging list nested in merging list
    original:
      mergingList:
        - name: 1
          nonMergingList:
            - name: 1
            - name: 2
              value: 2
        - name: 2
    twoWay:
      mergingList:
        - name: 1
          nonMergingList:
            - name: 1
              value: 1
    modified:
      mergingList:
        - name: 1
          nonMergingList:
            - name: 1
              value: 1
        - name: 2
    current:
      mergingList:
        - name: 1
          other: a
          nonMergingList:
            - name: 1
            - name: 2
              value: 2
        - name: 2
          other: b
    threeWay:
      mergingList:
        - name: 1
          nonMergingList:
            - name: 1
              value: 1
    result:
      mergingList:
        - name: 1
          other: a
          nonMergingList:
            - name: 1
              value: 1
        - name: 2
          other: b
  - description: add field to map in merging list nested in merging list
    original:
      mergingList:
        - name: 1
          mergingList:
            - name: 1
            - name: 2
              value: 2
        - name: 2
    twoWay:
      mergingList:
        - name: 1
          mergingList:
            - name: 1
              value: 1
    modified:
      mergingList:
        - name: 1
          mergingList:
            - name: 1
              value: 1
            - name: 2
              value: 2
        - name: 2
    current:
      mergingList:
        - name: 1
          other: a
          mergingList:
            - name: 1
            - name: 2
              value: 2
        - name: 2
          other: b
    threeWay:
      mergingList:
        - name: 1
          mergingList:
            - name: 1
              value: 1
    result:
      mergingList:
        - name: 1
          other: a
          mergingList:
            - name: 1
              value: 1
            - name: 2
              value: 2
        - name: 2
          other: b
  - description: add field to map in merging list nested in merging list with value conflict
    original:
      mergingList:
        - name: 1
          mergingList:
            - name: 1
            - name: 2
              value: 2
        - name: 2
    twoWay:
      mergingList:
        - name: 1
          mergingList:
            - name: 1
              value: 1
    modified:
      mergingList:
        - name: 1
          mergingList:
            - name: 1
              value: 1
            - name: 2
              value: 2
        - name: 2
    current:
      mergingList:
        - name: 1
          other: a
          mergingList:
            - name: 1
              value: a
            - name: 2
              value: b
        - name: 2
          other: b
    threeWay:
      mergingList:
        - name: 1
          mergingList:
            - name: 1
              value: 1
            - name: 2
              value: 2
    result:
      mergingList:
        - name: 1
          other: a
          mergingList:
            - name: 1
              value: 1
            - name: 2
              value: 2
        - name: 2
          other: b
  - description: add field to map in merging list nested in merging list with deletion conflict
    original:
      mergingList:
        - name: 1
          mergingList:
            - name: 1
            - name: 2
              value: 2
        - name: 2
    twoWay:
      mergingList:
        - name: 1
          mergingList:
            - name: 1
              value: 1
    modified:
      mergingList:
        - name: 1
          mergingList:
            - name: 1
              value: 1
            - name: 2
              value: 2
        - name: 2
    current:
      mergingList:
        - name: 1
          other: a
          mergingList:
            - name: 2
              value: 2
        - name: 2
          other: b
    threeWay:
      mergingList:
        - name: 1
          mergingList:
            - name: 1
              value: 1
    result:
      mergingList:
        - name: 1
          other: a
          mergingList:
            - name: 1
              value: 1
            - name: 2
              value: 2
        - name: 2
          other: b
  - description: merge empty merging lists
    original:
      mergingList: []
    twoWay:
      {}
    modified:
      mergingList: []
    current:
      mergingList: []
    threeWay:
      {}
    result:
      mergingList: []
  - description: add map to merging list by pointer
    original:
      mergeItemPtr:
        - name: 1
    twoWay:
      mergeItemPtr:
        - name: 2
    modified:
      mergeItemPtr:
        - name: 1
        - name: 2
    current:
      mergeItemPtr:
        - name: 1
          other: a
        - name: 3
    threeWay:
      mergeItemPtr:
        - name: 2
    result:
      mergeItemPtr:
        - name: 1
          other: a
        - name: 2
        - name: 3
  - description: add field to map in merging list by pointer
    original:
      mergeItemPtr:
        - name: 1
          mergeItemPtr:
            - name: 1
            - name: 2
              value: 2
        - name: 2
    twoWay:
      mergeItemPtr:
        - name: 1
          mergeItemPtr:
            - name: 1
              value: 1
    modified:
      mergeItemPtr:
        - name: 1
          mergeItemPtr:
            - name: 1
              value: 1
            - name: 2
              value: 2
        - name: 2
    current:
      mergeItemPtr:
        - name: 1
          other: a
          mergeItemPtr:
            - name: 1
              other: a
            - name: 2
              value: 2
              other: b
        - name: 2
          other: b
    threeWay:
      mergeItemPtr:
        - name: 1
          mergeItemPtr:
            - name: 1
              value: 1
    result:
      mergeItemPtr:
        - name: 1
          other: a
          mergeItemPtr:
            - name: 1
              value: 1
              other: a
            - name: 2
              value: 2
              other: b
        - name: 2
          other: b
`)

func TestStrategicMergePatch(t *testing.T) {
	tc := StrategicMergePatchTestCases{}
	err := yaml.Unmarshal(createStrategicMergePatchTestCaseData, &tc)
	if err != nil {
		t.Errorf("can't unmarshal test cases:%s\n", err)
		return
	}

	for _, c := range tc.TestCases {
		testTwoWayPatch(t, c)
		testThreeWayPatch(t, c)
	}
}

func testTwoWayPatch(t *testing.T, c StrategicMergePatchTestCase) {
	original, expected, modified := twoWayTestCaseToJSONOrFail(t, c)

	actual, err := CreateTwoWayMergePatch(original, modified, mergeItem)
	if err != nil {
		t.Errorf("error: %s in test case: %s\ncannot create two way patch:%s:\n%s\n",
			err, c.Description, toYAMLOrError(c.StrategicMergePatchTestCaseData))
	}

	testPatchCreation(t, expected, actual, c.Description)
	testPatchApplication(t, original, actual, modified, c.Description)
}

func twoWayTestCaseToJSONOrFail(t *testing.T, c StrategicMergePatchTestCase) ([]byte, []byte, []byte) {
	return testObjectToJSONOrFail(t, c.Original, c.Description),
		testObjectToJSONOrFail(t, c.TwoWay, c.Description),
		testObjectToJSONOrFail(t, c.Modified, c.Description)
}

func testThreeWayPatch(t *testing.T, c StrategicMergePatchTestCase) {
	original, modified, current, expected, result := threeWayTestCaseToJSONOrFail(t, c)

	actual, err := CreateThreeWayMergePatch(original, modified, current, mergeItem, false)
	if err != nil {
		if IsConflict(err) {
			if len(c.Result) > 0 {
				t.Errorf("error in test case: %s\nunexpected conflict occurred:\n%s\n",
					c.Description, toYAMLOrError(c.StrategicMergePatchTestCaseData))
			}

			return
		}

		t.Errorf("error: %s in test case: %s\ncannot create three way patch:\n%s\n",
			err, c.Description, toYAMLOrError(c.StrategicMergePatchTestCaseData))
	}

	if len(c.Result) < 1 {
		t.Errorf("error in test case: %s\nexpected conflict did not occur:\n%s\n",
			c.Description, toYAMLOrError(c.StrategicMergePatchTestCaseData))
	}

	testPatchCreation(t, expected, actual, c.Description)
	testPatchApplication(t, current, actual, result, c.Description)
}

func threeWayTestCaseToJSONOrFail(t *testing.T, c StrategicMergePatchTestCase) ([]byte, []byte, []byte, []byte, []byte) {
	return testObjectToJSONOrFail(t, c.Original, c.Description),
		testObjectToJSONOrFail(t, c.Modified, c.Description),
		testObjectToJSONOrFail(t, c.Current, c.Description),
		testObjectToJSONOrFail(t, c.ThreeWay, c.Description),
		testObjectToJSONOrFail(t, c.Result, c.Description)
}

func testPatchCreation(t *testing.T, expected, actual []byte, description string) {
	sorted, err := sortMergeListsByName(actual, mergeItem)
	if err != nil {
		t.Errorf("error: %s in test case: %s\ncannot sort patch:\n%s\n",
			err, description, jsonToYAMLOrError(actual))
	}

	if !reflect.DeepEqual(sorted, expected) {
		t.Errorf("error in test case: %s\nexpected patch:\n%s\ngot:\n%s\n",
			description, jsonToYAMLOrError(expected), jsonToYAMLOrError(sorted))
	}
}

func testPatchApplication(t *testing.T, original, patch, expected []byte, description string) {
	result, err := StrategicMergePatch(original, patch, mergeItem)
	if err != nil {
		t.Errorf("error: %s in test case: %s\ncannot apply patch:\n%s\nto original:\n%s\n",
			err, description, jsonToYAMLOrError(patch), jsonToYAMLOrError(original))
	}

	sorted, err := sortMergeListsByName(result, mergeItem)
	if err != nil {
		t.Errorf("error: %s in test case: %s\ncannot sort result object:\n%s\n",
			err, description, jsonToYAMLOrError(result))
	}

	if !reflect.DeepEqual(sorted, expected) {
		format := "error in test case: %s\npatch application failed:\noriginal:\n%s\npatch:\n%s\nexpected:\n%s\ngot:\n%s\n"
		t.Errorf(format, description,
			jsonToYAMLOrError(original), jsonToYAMLOrError(patch),
			jsonToYAMLOrError(expected), jsonToYAMLOrError(sorted))
	}
}

func testObjectToJSONOrFail(t *testing.T, o map[string]interface{}, description string) []byte {
	j, err := toJSON(o)
	if err != nil {
		t.Error(err)
	}

	r, err := sortMergeListsByName(j, mergeItem)
	if err != nil {
		t.Errorf("error: %s in test case: %s\ncannot sort object:\n%s\n", err, description, j)
	}

	return r
}

func toYAMLOrError(v interface{}) string {
	y, err := toYAML(v)
	if err != nil {
		return err.Error()
	}

	return y
}

func jsonToYAMLOrError(j []byte) string {
	y, err := jsonToYAML(j)
	if err != nil {
		return err.Error()
	}

	return string(y)
}

func toYAML(v interface{}) (string, error) {
	y, err := yaml.Marshal(v)
	if err != nil {
		return "", fmt.Errorf("yaml marshal failed:%v\n%v\n", err, spew.Sdump(v))
	}

	return string(y), nil
}

func toJSON(v interface{}) ([]byte, error) {
	j, err := json.Marshal(v)
	if err != nil {
		return nil, fmt.Errorf("json marshal failed:%v\n%v\n", err, spew.Sdump(v))
	}

	return j, nil
}

func jsonToYAML(j []byte) ([]byte, error) {
	y, err := yaml.JSONToYAML(j)
	if err != nil {
		return nil, fmt.Errorf("json to yaml failed:%v\n%v\n", err, j)
	}

	return y, nil
}