text:
using System;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using EPiServer.Core;
using EPiServer.Globalization;
using EPiServer.Web;
using EPiServer.XForms.WebControls;
using Label = System.Web.UI.WebControls.Label;

namespace EPiServer.Templates
{
	public class Global : EPiServer.Global
	{
		protected void Application_Start(Object sender, EventArgs e)
		{
            XFormControl.ControlSetup += new EventHandler(XForm_ControlSetup);
        }

        #region Global XForm Events

        /// <summary>
        /// Sets up events for each new instance of the XFormControl control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <remarks>As the ControlSetup event is triggered for each instance of the XFormControl control
        /// you need to take into consideration that any event handlers will affect all XForms for the entire
        /// application. If the EPiServer UI is running in the same application this might also be affected depending
        /// on which events you attach to and what is done in the event handlers.</remarks>
        public void XForm_ControlSetup(object sender, EventArgs e)
        {
            XFormControl control = (XFormControl)sender;

            control.BeforeLoadingForm += new LoadFormEventHandler(XForm_BeforeLoadingForm);
            control.ControlsCreated += new EventHandler(XForm_ControlsCreated);
            control.BeforeSubmitPostedData += new SaveFormDataEventHandler(XForm_BeforeSubmitPostedData);
            control.AfterSubmitPostedData += new SaveFormDataEventHandler(XForm_AfterSubmitPostedData);
        }

        /// <summary>
        /// Handles the BeforeLoadingForm event of the XFormControl.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EPiServer.XForms.WebControls.LoadFormEventArgs"/> instance containing the event data.</param>
        public void XForm_BeforeLoadingForm(object sender, LoadFormEventArgs e)
        {
            XFormControl formControl = (XFormControl)sender;

            if (String.IsNullOrEmpty(formControl.ValidationGroup))
            {
                //We set the validation group of the form to match our global validation group in the master page if no group has been defined.
                formControl.ValidationGroup = "XForm";
            }
        }

        /// <summary>
        /// Handles the ControlsCreated event of the XFormControl.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        public void XForm_ControlsCreated(object sender, EventArgs e)
        {
            XFormControl formControl = (XFormControl)sender;

            //We set the inline error validation text to "*" as we use a
            //validation summary in the master page to display the detailed error message.
            foreach (BaseValidator validator in formControl.Controls.Cast<Control>().Where(ctrl => ctrl is BaseValidator))
            {
                validator.Text = "*";
            }

            if (formControl.Page.User.Identity.IsAuthenticated)
            {
                formControl.Data.UserName = formControl.Page.User.Identity.Name;
            }
        }

        /// <summary>
        /// Handles the BeforeSubmitPostedData event of the XFormControl.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EPiServer.XForms.WebControls.SaveFormDataEventArgs"/> instance containing the event data.</param>
        public void XForm_BeforeSubmitPostedData(object sender, SaveFormDataEventArgs e)
        {
            XFormControl control = (XFormControl)sender;

            PageBase currentPage = control.Page as PageBase;

            if (currentPage == null)
            {
                return;
            }

            //We set the current page that the form has been posted from
            //This might differ from the actual page that the form property exists on.
            e.FormData.PageGuid = currentPage.CurrentPage.PageGuid;
        }

        /// <summary>
        /// Handles the AfterSubmitPostedData event of the XFormControl.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EPiServer.XForms.WebControls.SaveFormDataEventArgs"/> instance containing the event data.</param>
        public void XForm_AfterSubmitPostedData(object sender, SaveFormDataEventArgs e)
        {
            XFormControl control = (XFormControl)sender;

            if (control.FormDefinition.PageGuidAfterPost != Guid.Empty)
            {
                PermanentPageLinkMap pageMap = PermanentLinkMapStore.Find(control.FormDefinition.PageGuidAfterPost) as PermanentPageLinkMap;
                if (pageMap != null)
                {
                    string internalUrl = pageMap.MappedUrl.ToString();
                    internalUrl = UriSupport.AddLanguageSelection(internalUrl, ContentLanguage.PreferredCulture.Name);
                    UrlBuilder urlBuilder = new UrlBuilder(internalUrl);
                    //Rewrite the url to make sure that it gets the friendly url if such a provider has been configured.
                    Global.UrlRewriteProvider.ConvertToExternal(urlBuilder, null, Encoding.UTF8);

                    //Always cast UrlBuilders to get a correctly encoded url since ToString() is for "human" readability.
                    control.Page.Response.Redirect((string)urlBuilder);
                    return;
                }
            }

            //After the form has been posted we remove the form elements and add a "thank you message".
            control.Controls.Clear();
            Label label = new Label();
            label.CssClass = "thankyoumessage";
            label.Text = LanguageManager.Instance.Translate("/form/postedmessage");
            control.Controls.Add(label);
        }

        #endregion

        protected void Application_End(Object sender, EventArgs e)
		{
		}

        /// <summary>
        /// Raises the <see cref="E:ValidateUIAccess"/> event. Override this in inheriting classes to customize behavior,
        /// always calling the base-class implementation as well. Check for e.Cancel == true and do an early exit if so.
        /// </summary>
        /// <remarks>
        /// This is only a code sample on how you can utilize this event.
        /// </remarks>
        /// <param name="e">The <see cref="EPiServer.ValidateUIAccessEventArgs"/> instance containing the event data.</param>
        protected override void OnValidateRequestAccess(ValidateRequestAccessEventArgs e)
        {
            base.OnValidateRequestAccess(e);
            if (e.Cancel)
            {
                return;
            }
        }

        /// <summary>
        /// Gets a list of default documents. Overide if you need to change which documents are actually
        /// tried.
        /// </summary>
        /// <remarks>
        /// This is only a code sample on how you can utilize this method.
        /// </remarks>
        /// <param name="url">The URL of the request that is determined to need a default document</param>
        /// <returns>null or a list of default documents to try</returns>
        protected override string[] GetDefaultDocuments(Uri url)
        {
            return base.GetDefaultDocuments(url);
        }

        protected override void Global_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            base.Global_PreRequestHandlerExecute(sender, e);
        }

        void Application_Error(object sender, EventArgs e)
        {

        }
    }
}


text:
using namespace nd4j::graph;

namespace nd4j {
    namespace ops {
        template <typename T>
        class DeclarableListOp : public nd4j::ops::DeclarableOp<T> {
        protected:
            virtual Nd4jStatus validateAndExecute(Context<T>& block) = 0;

            nd4j::NDArray<T>* getZ(Context<T>& block, int inputId);
        public:
            DeclarableListOp(int numInputs, int numOutputs, const char* opName, int tArgs, int iArgs);
            ~DeclarableListOp();

            Nd4jStatus execute(Context<T>* block) override;

            ResultSet<T>* execute(NDArrayList<T>* list, std::initializer_list<NDArray<T>*> inputs, std::initializer_list<T> tArgs, std::initializer_list<int> iArgs);
            ResultSet<T>* execute(NDArrayList<T>* list, std::vector<NDArray<T>*>& inputs, std::vector<T>& tArgs, std::vector<int>& iArgs);

            ShapeList* calculateOutputShape(ShapeList* inputShape, nd4j::graph::Context<T>& block) override;
        };
    }
}

#endif

redpajama_set_name: RedPajamaGithub


text:
package org.apache.zeppelin.display.ui;

import org.apache.zeppelin.display.Input;

/**
 * Html TextBox control
 */
public class TextBox extends Input<String> {

  public TextBox() {

  }

  public TextBox(String name, String defaultValue) {
    this.name = name;
    this.displayName = name;
    this.defaultValue = defaultValue;
  }

}


text:
package org.lwjgl.nuklear;

import java.nio.*;

import org.lwjgl.system.*;

import static org.lwjgl.system.MemoryUtil.*;

/**
 *
Layout

 *
 *
struct nk_chart {
    int slot;
    float x;
    float y;
    float w;
    float h;
    {@link NkChartSlot struct nk_chart_slot} slots[4];
}

 */
public class NkChart extends Struct {

	/** The struct size in bytes. */
	public static final int SIZEOF;

	public static final int ALIGNOF;

	/** The struct member offsets. */
	public static final int
		SLOT,
		X,
		Y,
		W,
		H,
		SLOTS;

	static {
		Layout layout = __struct(
			__member(4),
			__member(4),
			__member(4),
			__member(4),
			__member(4),
			__array(NkChartSlot.SIZEOF, NkChartSlot.ALIGNOF, 4)
		);

		SIZEOF = layout.getSize();
		ALIGNOF = layout.getAlignment();

		SLOT = layout.offsetof(0);
		X = layout.offsetof(1);
		Y = layout.offsetof(2);
		W = layout.offsetof(3);
		H = layout.offsetof(4);
		SLOTS = layout.offsetof(5);
	}

	NkChart(long address, ByteBuffer container) {
		super(address, container);
	}

	/**
	 * Creates a {@link NkChart} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
	 * visible to the struct instance and vice versa.
	 *
	 *
The created instance holds a strong reference to the container object.

	 */
	public NkChart(ByteBuffer container) {
		this(memAddress(container), checkContainer(container, SIZEOF));
	}

	@Override
	public int sizeof() { return SIZEOF; }

	/** Returns the value of the {@code slot} field. */
	public int slot() { return nslot(address()); }
	/** Returns the value of the {@code x} field. */
	public float x() { return nx(address()); }
	/** Returns the value of the {@code y} field. */
	public float y() { return ny(address()); }
	/** Returns the value of the {@code w} field. */
	public float w() { return nw(address()); }
	/** Returns the value of the {@code h} field. */
	public float h() { return nh(address()); }
	/** Returns a {@link NkChartSlot}.Buffer view of the {@code slots} field. */
	public NkChartSlot.Buffer slots() { return nslots(address()); }
	/** Returns a {@link NkChartSlot} view of the struct at the specified index of the {@code slots} field. */
	public NkChartSlot slots(int index) { return nslots(address(), index); }

	// -----------------------------------

	/** Returns a new {@link NkChart} instance for the specified memory address or {@code null} if the address is {@code NULL}. */
	public static NkChart create(long address) {
		return address == NULL ? null : new NkChart(address, null);
	}

	/**
	 * Create a {@link NkChart.Buffer} instance at the specified memory.
	 *
	 * @param address  the memory address
	 * @param capacity the buffer capacity
	 */
	public static Buffer create(long address, int capacity) {
		return address == NULL ? null : new Buffer(address, null, -1, 0, capacity, capacity);
	}

	// -----------------------------------

	/** Unsafe version of {@link #slot}. */
	public static int nslot(long struct) { return memGetInt(struct + NkChart.SLOT); }
	/** Unsafe version of {@link #x}. */
	public static float nx(long struct) { return memGetFloat(struct + NkChart.X); }
	/** Unsafe version of {@link #y}. */
	public static float ny(long struct) { return memGetFloat(struct + NkChart.Y); }
	/** Unsafe version of {@link #w}. */
	public static float nw(long struct) { return memGetFloat(struct + NkChart.W); }
	/** Unsafe version of {@link #h}. */
	public static float nh(long struct) { return memGetFloat(struct + NkChart.H); }
	/** Unsafe version of {@link #slots}. */
	public static NkChartSlot.Buffer nslots(long struct) {
		return NkChartSlot.create(struct + NkChart.SLOTS, 4);
	}
	/** Unsafe version of {@link #slots(int) slots}. */
	public static NkChartSlot nslots(long struct, int index) {
		return NkChartSlot.create(struct + NkChart.SLOTS + index * NkChartSlot.SIZEOF);
	}

	// -----------------------------------

	/** An array of {@link NkChart} structs. */
	public static class Buffer extends StructBuffer<NkChart, Buffer> {

		/**
		 * Creates a new {@link NkChart.Buffer} instance backed by the specified container.
		 *
		 * Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
		 * will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
		 * by {@link NkChart#SIZEOF}, and its mark will be undefined.
		 *
		 *
The created buffer instance holds a strong reference to the container object.

		 */
		public Buffer(ByteBuffer container) {
			super(container, container.remaining() / SIZEOF);
		}

		Buffer(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
			super(address, container, mark, pos, lim, cap);
		}

		@Override
		protected Buffer self() {
			return this;
		}

		@Override
		protected Buffer newBufferInstance(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
			return new Buffer(address, container, mark, pos, lim, cap);
		}

		@Override
		protected NkChart newInstance(long address) {
			return new NkChart(address, container);
		}

		@Override
		protected int sizeof() {
			return SIZEOF;
		}

		/** Returns the value of the {@code slot} field. */
		public int slot() { return NkChart.nslot(address()); }
		/** Returns the value of the {@code x} field. */
		public float x() { return NkChart.nx(address()); }
		/** Returns the value of the {@code y} field. */
		public float y() { return NkChart.ny(address()); }
		/** Returns the value of the {@code w} field. */
		public float w() { return NkChart.nw(address()); }
		/** Returns the value of the {@code h} field. */
		public float h() { return NkChart.nh(address()); }
		/** Returns a {@link NkChartSlot}.Buffer view of the {@code slots} field. */
		public NkChartSlot.Buffer slots() { return NkChart.nslots(address()); }
		/** Returns a {@link NkChartSlot} view of the struct at the specified index of the {@code slots} field. */
		public NkChartSlot slots(int index) { return NkChart.nslots(address(), index); }

	}

}


text:
package cz.metacentrum.perun.notif.mail;

/**
 * Implementation of html email message
 */
public class PerunNotifHTMLMessage extends MessagePreparator implements EmailMessage {

	public PerunNotifHTMLMessage(String from, String fromText, String subject, String messageContent) {

		super(from, fromText, subject, messageContent, EmailType.HTML);
	}
}


text:
name: clojure.browser.repl/PORT
see also:
---

## Summary

## Details

## Examples


text:
namespace WebServer.Application.Controllers
{
    using Views;
    using Server.Enums;
    using Server.HTTP.Contracts;
    using Server.HTTP.Response;

    public class HomeController
    {

        // GET /
        public IHttpResponse Index()
        {
            return new ViewResponse(HttpStatusCode.Ok, new HomeIndexView());
        }
    }
}


text:
var makeDeque =
(function() { //begin IIFE

	function makeDeque(values) { //begin factory

		// These vars are private, local to scope of makeDeque,
		//  only accessible to functions defined in makeDeque

		var array = values.slice(); //copy values
		var absent = []; //list of missing elements

		// Each function below is specific to one deque, with access to the private vars

		function readmit(val) { //internal function only, do not attach to instances
			var foundAt = absent.indexOf(val);
			if (foundAt<0) return false; //foundAt is -1 if val not found
			// else found; excise from absent array
			absent.splice(foundAt,1);
			return true;
		}

		// ---- Instance methods: -----

		function top() {
			if (array.length)
				return array[array.length-1];
		}

		function bottom() {
			if (array.length)
				return array[0];
		}

		function pop() {
			var val = array.pop();
			if (val !== undefined)
				absent.push(val);
			return val;
		}

		function push(val) {
			return readmit(val) && array.push(val);
		}

		function shift() {
			var val = array.shift();
			if (val !== undefined)
				absent.push(val);
			return val;
		}

		function unshift(val) {
			return readmit(val) && array.unshift(val);
		}

		function sort(sortFn) {
			//don't return:
			array.sort(sortFn);
		}

		function map(convertFn) {
			// This solution works but can be exploited
			// (certain callbacks could change the array):
			// return array.map(convertFn);

			// Safer version: map a copy of array:
			return array.slice().map(convertFn);
		}

		function cut() { //returns # elements moved from upper half to lower (0 if no change)
			var fullLength = array.length;
			var headLength = Math.ceil(fullLength / 2);
			if (headLength == fullLength) // no tail, nothing to swap
				return 0;
			var tail = array.splice(headLength, fullLength); // removes tail from array
			array = tail.concat(array); // swap tail and remaining head
			return tail.length;
		}

		function shuffle() {
		// Knuth-Fisher-Yates, modified from http://bost.ocks.org/mike/shuffle/
			var end = array.length, temp, i;
	  			// While there remain elements to shuffle…
			while (end>1) {
	   			// Pick a remaining element…
	   			i = Math.floor(Math.random() * end--);
	   			// And swap it with the current element.
	   			temp = array[end];
	   			array[end] = array[i];
			    array[i] = temp;
	 		}
	 	}

	 	// Problem 4:
	 	function render(container,renderItemFn) {
	 		if (typeof container === 'string') {
	 			container = document.getElementById(container);
	 		}
	 		if (!(container instanceof HTMLElement)) {
	 			console.log('no such element');
	 			return;
	 		}
	 		for (var i=0; i<array.length; ++i) {
	 			var cell = document.createElement('div');
	 			cell.className = 'dequeItem';
	 			renderItemFn(array[i], cell);
	 			container.appendChild(cell);
	 		}
	 	}

		var deque = {// export each public method by linking an instance property to it:
				sort : sort,
				map : map,
				cut : cut,
				shuffle : shuffle,
				top : top,
				bottom : bottom,
				push : push,
				pop : pop,
				shift : shift,
				unshift : unshift,

				render : render
		};
		return deque;

	} //end factory makeDeque

	return makeDeque;
})(); //end IIFE

if (typeof module !== "undefined") {
    module.exports = makeDeque;
}


text:
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.

package org.jetbrains.kotlin.idea.codeInsight.codevision;

import com.intellij.testFramework.TestDataPath;
import org.jetbrains.kotlin.test.JUnit3RunnerWithInners;
import org.jetbrains.kotlin.test.KotlinTestUtils;
import org.jetbrains.kotlin.test.TestMetadata;
import org.jetbrains.kotlin.test.TestRoot;
import org.junit.runner.RunWith;

/*
 * This class is generated by {@link org.jetbrains.kotlin.generators.tests.TestsPackage}.
 * DO NOT MODIFY MANUALLY.
 */
@SuppressWarnings("all")
@TestRoot("idea/tests")
@TestDataPath("$CONTENT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
@TestMetadata("testData/codeInsight/codeVision")
public class KotlinCodeVisionProviderTestGenerated extends AbstractKotlinCodeVisionProviderTest {
    private void runTest(String testDataFilePath) throws Exception {
        KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
    }

    @TestMetadata("ClassFunctionOverrides.kt")
    public void testClassFunctionOverrides() throws Exception {
        runTest("testData/codeInsight/codeVision/ClassFunctionOverrides.kt");
    }

    @TestMetadata("ClassInheritors.kt")
    public void testClassInheritors() throws Exception {
        runTest("testData/codeInsight/codeVision/ClassInheritors.kt");
    }

    @TestMetadata("ClassMethodUsages.kt")
    public void testClassMethodUsages() throws Exception {
        runTest("testData/codeInsight/codeVision/ClassMethodUsages.kt");
    }

    @TestMetadata("ClassPropertiesOverrides.kt")
    public void testClassPropertiesOverrides() throws Exception {
        runTest("testData/codeInsight/codeVision/ClassPropertiesOverrides.kt");
    }

    @TestMetadata("ClassPropertyUsages.kt")
    public void testClassPropertyUsages() throws Exception {
        runTest("testData/codeInsight/codeVision/ClassPropertyUsages.kt");
    }

    @TestMetadata("ClassUsages.kt")
    public void testClassUsages() throws Exception {
        runTest("testData/codeInsight/codeVision/ClassUsages.kt");
    }

    @TestMetadata("GlobalFunctionUsages.kt")
    public void testGlobalFunctionUsages() throws Exception {
        runTest("testData/codeInsight/codeVision/GlobalFunctionUsages.kt");
    }

    @TestMetadata("InterfaceAbstractMethodImplementation.kt")
    public void testInterfaceAbstractMethodImplementation() throws Exception {
        runTest("testData/codeInsight/codeVision/InterfaceAbstractMethodImplementation.kt");
    }

    @TestMetadata("InterfaceImplementations.kt")
    public void testInterfaceImplementations() throws Exception {
        runTest("testData/codeInsight/codeVision/InterfaceImplementations.kt");
    }

    @TestMetadata("InterfaceMethodUsages.kt")
    public void testInterfaceMethodUsages() throws Exception {
        runTest("testData/codeInsight/codeVision/InterfaceMethodUsages.kt");
    }

    @TestMetadata("InterfaceMethodsOverrides.kt")
    public void testInterfaceMethodsOverrides() throws Exception {
        runTest("testData/codeInsight/codeVision/InterfaceMethodsOverrides.kt");
    }

    @TestMetadata("InterfacePropertiesOverrides.kt")
    public void testInterfacePropertiesOverrides() throws Exception {
        runTest("testData/codeInsight/codeVision/InterfacePropertiesOverrides.kt");
    }

    @TestMetadata("InterfacePropertyUsages.kt")
    public void testInterfacePropertyUsages() throws Exception {
        runTest("testData/codeInsight/codeVision/InterfacePropertyUsages.kt");
    }

    @TestMetadata("InterfaceUsages.kt")
    public void testInterfaceUsages() throws Exception {
        runTest("testData/codeInsight/codeVision/InterfaceUsages.kt");
    }

    @TestMetadata("TooManyUsagesAndInheritors.kt")
    public void testTooManyUsagesAndInheritors() throws Exception {
        runTest("testData/codeInsight/codeVision/TooManyUsagesAndInheritors.kt");
    }

    @TestMetadata("UsagesAndInheritanceTogether.kt")
    public void testUsagesAndInheritanceTogether() throws Exception {
        runTest("testData/codeInsight/codeVision/UsagesAndInheritanceTogether.kt");
    }
}


text:
import mock
import webob

from nova.api.openstack.compute.contrib import flavorextraspecs
import nova.db
from nova import exception
from nova import test
from nova.tests.api.openstack import fakes
from nova.tests.objects import test_flavor

def return_create_flavor_extra_specs(context, flavor_id, extra_specs):
    return stub_flavor_extra_specs()

def return_flavor_extra_specs(context, flavor_id):
    return stub_flavor_extra_specs()

def return_flavor_extra_specs_item(context, flavor_id, key):
    return {key: stub_flavor_extra_specs()[key]}

def return_empty_flavor_extra_specs(context, flavor_id):
    return {}

def delete_flavor_extra_specs(context, flavor_id, key):
    pass

def stub_flavor_extra_specs():
    specs = {
            "key1": "value1",
            "key2": "value2",
            "key3": "value3",
            "key4": "value4",
            "key5": "value5"}
    return specs

class FlavorsExtraSpecsTest(test.TestCase):

    def setUp(self):
        super(FlavorsExtraSpecsTest, self).setUp()
        fakes.stub_out_key_pair_funcs(self.stubs)
        self.controller = flavorextraspecs.FlavorExtraSpecsController()

    def test_index(self):
        flavor = dict(test_flavor.fake_flavor,
                      extra_specs={'key1': 'value1'})

        req = fakes.HTTPRequest.blank('/v2/fake/flavors/1/os-extra_specs')
        with mock.patch('nova.db.flavor_get_by_flavor_id') as mock_get:
            mock_get.return_value = flavor
            res_dict = self.controller.index(req, 1)

        self.assertEqual('value1', res_dict['extra_specs']['key1'])

    def test_index_no_data(self):
        self.stubs.Set(nova.db, 'flavor_extra_specs_get',
                       return_empty_flavor_extra_specs)

        req = fakes.HTTPRequest.blank('/v2/fake/flavors/1/os-extra_specs')
        res_dict = self.controller.index(req, 1)

        self.assertEqual(0, len(res_dict['extra_specs']))

    def test_show(self):
        flavor = dict(test_flavor.fake_flavor,
                      extra_specs={'key5': 'value5'})
        req = fakes.HTTPRequest.blank('/v2/fake/flavors/1/os-extra_specs' +
                                      '/key5')
        with mock.patch('nova.db.flavor_get_by_flavor_id') as mock_get:
            mock_get.return_value = flavor
            res_dict = self.controller.show(req, 1, 'key5')

        self.assertEqual('value5', res_dict['key5'])

    def test_show_spec_not_found(self):
        self.stubs.Set(nova.db, 'flavor_extra_specs_get',
                       return_empty_flavor_extra_specs)

        req = fakes.HTTPRequest.blank('/v2/fake/flavors/1/os-extra_specs' +
                                      '/key6')
        self.assertRaises(webob.exc.HTTPNotFound, self.controller.show,
                          req, 1, 'key6')

    def test_not_found_because_flavor(self):
        req = fakes.HTTPRequestV3.blank('/flavors/1/extra-specs/key5',
                                        use_admin_context=True)
        with mock.patch('nova.db.flavor_get_by_flavor_id') as mock_get:
            mock_get.side_effect = exception.FlavorNotFound(flavor_id='1')
            self.assertRaises(webob.exc.HTTPNotFound, self.controller.show,
                              req, 1, 'key5')
            self.assertRaises(webob.exc.HTTPNotFound, self.controller.update,
                              req, 1, 'key5', {'key5': 'value5'})
            self.assertRaises(webob.exc.HTTPNotFound, self.controller.delete,
                              req, 1, 'key5')

        req = fakes.HTTPRequestV3.blank('/flavors/1/extra-specs',
                                        use_admin_context=True)
        with mock.patch('nova.db.flavor_get_by_flavor_id') as mock_get:
            mock_get.side_effect = exception.FlavorNotFound(flavor_id='1')
            self.assertRaises(webob.exc.HTTPNotFound, self.controller.create,
                              req, 1, {'extra_specs': {'key5': 'value5'}})

    def test_delete(self):
        flavor = dict(test_flavor.fake_flavor,
                      extra_specs={'key5': 'value5'})
        self.stubs.Set(nova.db, 'flavor_extra_specs_delete',
                       delete_flavor_extra_specs)

        req = fakes.HTTPRequest.blank('/v2/fake/flavors/1/os-extra_specs' +
                                      '/key5', use_admin_context=True)
        with mock.patch('nova.db.flavor_get_by_flavor_id') as mock_get:
            mock_get.return_value = flavor
            self.controller.delete(req, 1, 'key5')

    def test_delete_no_admin(self):
        self.stubs.Set(nova.db, 'flavor_extra_specs_delete',
                       delete_flavor_extra_specs)

        req = fakes.HTTPRequest.blank('/v2/fake/flavors/1/os-extra_specs' +
                                      '/key5')
        self.assertRaises(exception.Forbidden, self.controller.delete,
                          req, 1, 'key 5')

    def test_delete_spec_not_found(self):
        req = fakes.HTTPRequest.blank('/v2/fake/flavors/1/os-extra_specs' +
                                      '/key6', use_admin_context=True)
        self.assertRaises(webob.exc.HTTPNotFound, self.controller.delete,
                          req, 1, 'key6')

    def test_create(self):
        self.stubs.Set(nova.db,
                       'flavor_extra_specs_update_or_create',
                       return_create_flavor_extra_specs)
        body = {"extra_specs": {"key1": "value1"}}

        req = fakes.HTTPRequest.blank('/v2/fake/flavors/1/os-extra_specs',
                                       use_admin_context=True)
        res_dict = self.controller.create(req, 1, body)

        self.assertEqual('value1', res_dict['extra_specs']['key1'])

    def test_create_no_admin(self):
        self.stubs.Set(nova.db,
                       'flavor_extra_specs_update_or_create',
                       return_create_flavor_extra_specs)
        body = {"extra_specs": {"key1": "value1"}}

        req = fakes.HTTPRequest.blank('/v2/fake/flavors/1/os-extra_specs')
        self.assertRaises(exception.Forbidden, self.controller.create,
                          req, 1, body)

    def test_create_flavor_not_found(self):
        def fake_instance_type_extra_specs_update_or_create(*args, **kwargs):
            raise exception.FlavorNotFound(flavor_id='')

        self.stubs.Set(nova.db,
                       'flavor_extra_specs_update_or_create',
                       fake_instance_type_extra_specs_update_or_create)
        body = {"extra_specs": {"key1": "value1"}}
        req = fakes.HTTPRequest.blank('/v2/fake/flavors/1/os-extra_specs',
                                      use_admin_context=True)
        self.assertRaises(webob.exc.HTTPNotFound, self.controller.create,
                          req, 1, body)

    def test_create_flavor_db_duplicate(self):
        def fake_instance_type_extra_specs_update_or_create(*args, **kwargs):
            raise exception.FlavorExtraSpecUpdateCreateFailed(id=1, retries=5)

        self.stubs.Set(nova.db,
                       'flavor_extra_specs_update_or_create',
                       fake_instance_type_extra_specs_update_or_create)
        body = {"extra_specs": {"key1": "value1"}}
        req = fakes.HTTPRequest.blank('/v2/fake/flavors/1/os-extra_specs',
                                      use_admin_context=True)
        self.assertRaises(webob.exc.HTTPConflict, self.controller.create,
                          req, 1, body)

    def _test_create_bad_request(self, body):
        self.stubs.Set(nova.db,
                       'flavor_extra_specs_update_or_create',
                       return_create_flavor_extra_specs)

        req = fakes.HTTPRequest.blank('/v2/fake/flavors/1/os-extra_specs',
                                      use_admin_context=True)
        self.assertRaises(webob.exc.HTTPBadRequest, self.controller.create,
                          req, 1, body)

    def test_create_empty_body(self):
        self._test_create_bad_request('')

    def test_create_non_dict_extra_specs(self):
        self._test_create_bad_request({"extra_specs": "non_dict"})

    def test_create_non_string_value(self):
        self._test_create_bad_request({"extra_specs": {"key1": None}})

    def test_create_zero_length_key(self):
        self._test_create_bad_request({"extra_specs": {"": "value1"}})

    def test_create_long_key(self):
        key = "a" * 256
        self._test_create_bad_request({"extra_specs": {key: "value1"}})

    def test_create_long_value(self):
        value = "a" * 256
        self._test_create_bad_request({"extra_specs": {"key1": value}})

    @mock.patch('nova.db.flavor_extra_specs_update_or_create')
    def test_create_invalid_specs_key(self, mock_flavor_extra_specs):
        invalid_keys = ("key1/", "<key>", "$$akey$", "!akey", "")
        mock_flavor_extra_specs.side_effects = return_create_flavor_extra_specs

        for key in invalid_keys:
            body = {"extra_specs": {key: "value1"}}
            req = fakes.HTTPRequest.blank('/v2/fake/flavors/1/os-extra_specs',
                                       use_admin_context=True)
            self.assertRaises(webob.exc.HTTPBadRequest, self.controller.create,
                              req, 1, body)

    @mock.patch('nova.db.flavor_extra_specs_update_or_create')
    def test_create_valid_specs_key(self, mock_flavor_extra_specs):
        valid_keys = ("key1", "month.price", "I_am-a Key", "finance:g2")
        mock_flavor_extra_specs.side_effects = return_create_flavor_extra_specs

        for key in valid_keys:
            body = {"extra_specs": {key: "value1"}}
            req = fakes.HTTPRequest.blank('/v2/fake/flavors/1/os-extra_specs',
                                       use_admin_context=True)
            res_dict = self.controller.create(req, 1, body)
            self.assertEqual('value1', res_dict['extra_specs'][key])

    def test_update_item(self):
        self.stubs.Set(nova.db,
                       'flavor_extra_specs_update_or_create',
                       return_create_flavor_extra_specs)
        body = {"key1": "value1"}

        req = fakes.HTTPRequest.blank('/v2/fake/flavors/1/os-extra_specs' +
                                      '/key1', use_admin_context=True)
        res_dict = self.controller.update(req, 1, 'key1', body)

        self.assertEqual('value1', res_dict['key1'])

    def test_update_item_no_admin(self):
        self.stubs.Set(nova.db,
                       'flavor_extra_specs_update_or_create',
                       return_create_flavor_extra_specs)
        body = {"key1": "value1"}

        req = fakes.HTTPRequest.blank('/v2/fake/flavors/1/os-extra_specs' +
                                      '/key1')
        self.assertRaises(exception.Forbidden, self.controller.update,
                          req, 1, 'key1', body)

    def _test_update_item_bad_request(self, body):
        self.stubs.Set(nova.db,
                       'flavor_extra_specs_update_or_create',
                       return_create_flavor_extra_specs)

        req = fakes.HTTPRequest.blank('/v2/fake/flavors/1/os-extra_specs' +
                                      '/key1', use_admin_context=True)
        self.assertRaises(webob.exc.HTTPBadRequest, self.controller.update,
                          req, 1, 'key1', body)

    def test_update_item_empty_body(self):
        self._test_update_item_bad_request('')

    def test_update_item_too_many_keys(self):
        body = {"key1": "value1", "key2": "value2"}
        self._test_update_item_bad_request(body)

    def test_update_item_non_dict_extra_specs(self):
        self._test_update_item_bad_request("non_dict")

    def test_update_item_non_string_value(self):
        self._test_update_item_bad_request({"key1": None})

    def test_update_item_zero_length_key(self):
        self._test_update_item_bad_request({"": "value1"})

    def test_update_item_long_key(self):
        key = "a" * 256
        self._test_update_item_bad_request({key: "value1"})

    def test_update_item_long_value(self):
        value = "a" * 256
        self._test_update_item_bad_request({"key1": value})

    def test_update_item_body_uri_mismatch(self):
        self.stubs.Set(nova.db,
                       'flavor_extra_specs_update_or_create',
                       return_create_flavor_extra_specs)
        body = {"key1": "value1"}

        req = fakes.HTTPRequest.blank('/v2/fake/flavors/1/os-extra_specs/bad',
                                     use_admin_context=True)
        self.assertRaises(webob.exc.HTTPBadRequest, self.controller.update,
                          req, 1, 'bad', body)

    def test_update_flavor_not_found(self):
        def fake_instance_type_extra_specs_update_or_create(*args, **kwargs):
            raise exception.FlavorNotFound(flavor_id='')

        self.stubs.Set(nova.db,
                       'flavor_extra_specs_update_or_create',
                       fake_instance_type_extra_specs_update_or_create)
        body = {"key1": "value1"}

        req = fakes.HTTPRequest.blank('/v2/fake/flavors/1/extra-specs/key1',
                                      use_admin_context=True)
        self.assertRaises(webob.exc.HTTPNotFound, self.controller.update,
                          req, 1, 'key1', body)

    def test_update_flavor_db_duplicate(self):
        def fake_instance_type_extra_specs_update_or_create(*args, **kwargs):
            raise exception.FlavorExtraSpecUpdateCreateFailed(id=1, retries=5)

        self.stubs.Set(nova.db,
                       'flavor_extra_specs_update_or_create',
                       fake_instance_type_extra_specs_update_or_create)
        body = {"key1": "value1"}

        req = fakes.HTTPRequest.blank('/v2/fake/flavors/1/extra-specs/key1',
                                      use_admin_context=True)
        self.assertRaises(webob.exc.HTTPConflict, self.controller.update,
                          req, 1, 'key1', body)

class FlavorsExtraSpecsXMLSerializerTest(test.TestCase):
    def test_serializer(self):
        serializer = flavorextraspecs.ExtraSpecsTemplate()
        expected = ("<?xml version='1.0' encoding='UTF-8'?>\n"
                    '<extra_specs><key1>value1</key1></extra_specs>')
        text = serializer.serialize(dict(extra_specs={"key1": "value1"}))
        self.assertEqual(text, expected)

    def test_show_update_serializer(self):
        serializer = flavorextraspecs.ExtraSpecTemplate()
        expected = ("<?xml version='1.0' encoding='UTF-8'?>\n"
                    '<extra_spec key="key1">value1</extra_spec>')
        text = serializer.serialize(dict({"key1": "value1"}))
        self.assertEqual(text, expected)

    def test_serializer_with_colon_tagname(self):
        # Our test object to serialize
        obj = {'extra_specs': {'foo:bar': '999'}}
        serializer = flavorextraspecs.ExtraSpecsTemplate()
        expected_xml = (("<?xml version='1.0' encoding='UTF-8'?>\n"
                    '<extra_specs><foo:bar xmlns:foo="foo">999</foo:bar>'
                    '</extra_specs>'))
        result = serializer.serialize(obj)
        self.assertEqual(expected_xml, result)


text:
import os
import subprocess
import sys
import unittest2

from django import VERSION as DJANGO_VERSION
from django.conf import global_settings
from django.test import TestCase
from django.core.exceptions import ImproperlyConfigured

from mock import patch

from configurations.importer import ConfigurationImporter

ROOT_DIR = os.path.dirname(os.path.dirname(__file__))
TEST_PROJECT_DIR = os.path.join(ROOT_DIR, 'test_project')

class MainTests(TestCase):

    def test_simple(self):
        from tests.settings import main
        self.assertEqual(main.ATTRIBUTE_SETTING, True)
        self.assertEqual(main.PROPERTY_SETTING, 1)
        self.assertEqual(main.METHOD_SETTING, 2)
        self.assertEqual(main.LAMBDA_SETTING, 3)
        self.assertNotEqual(main.PRISTINE_LAMBDA_SETTING, 4)
        self.assertTrue(lambda: callable(main.PRISTINE_LAMBDA_SETTING))
        self.assertNotEqual(main.PRISTINE_FUNCTION_SETTING, 5)
        self.assertTrue(lambda: callable(main.PRISTINE_FUNCTION_SETTING))
        self.assertEqual(main.TEMPLATE_CONTEXT_PROCESSORS,
                         tuple(global_settings.TEMPLATE_CONTEXT_PROCESSORS) + (
                                   'tests.settings.base.test_callback',
                               ))
        self.assertEqual(main.PRE_SETUP_TEST_SETTING, 6)
        self.assertRaises(AttributeError, lambda: main.POST_SETUP_TEST_SETTING)
        self.assertEqual(main.Test.POST_SETUP_TEST_SETTING, 7)

    def test_global_arrival(self):
        from django.conf import settings
        self.assertEqual(settings.PROPERTY_SETTING, 1)
        self.assertRaises(AttributeError, lambda: settings._PRIVATE_SETTING)
        self.assertNotEqual(settings.PRISTINE_LAMBDA_SETTING, 4)
        self.assertTrue(lambda: callable(settings.PRISTINE_LAMBDA_SETTING))
        self.assertNotEqual(settings.PRISTINE_FUNCTION_SETTING, 5)
        self.assertTrue(lambda: callable(settings.PRISTINE_FUNCTION_SETTING))
        self.assertEqual(settings.PRE_SETUP_TEST_SETTING, 6)

    @patch.dict(os.environ, clear=True, DJANGO_CONFIGURATION='Test')
    def test_empty_module_var(self):
        self.assertRaises(ImproperlyConfigured, ConfigurationImporter)

    @patch.dict(os.environ, clear=True,
                DJANGO_SETTINGS_MODULE='tests.settings.main')
    def test_empty_class_var(self):
        self.assertRaises(ImproperlyConfigured, ConfigurationImporter)

    def test_global_settings(self):
        from configurations.base import Configuration
        self.assertIn('dictConfig', Configuration.LOGGING_CONFIG)
        self.assertEqual(repr(Configuration),
                         "<Configuration 'configurations.base.Configuration'>")

    def test_repr(self):
        from tests.settings.main import Test
        self.assertEqual(repr(Test),
                         "<Configuration 'tests.settings.main.Test'>")

    @patch.dict(os.environ, clear=True,
                DJANGO_SETTINGS_MODULE='tests.settings.main',
                DJANGO_CONFIGURATION='Test')
    def test_initialization(self):
        importer = ConfigurationImporter()
        self.assertEqual(importer.module, 'tests.settings.main')
        self.assertEqual(importer.name, 'Test')
        self.assertEqual(repr(importer),
                         "<ConfigurationImporter for 'tests.settings.main.Test'>")

    @patch.dict(os.environ, clear=True,
                DJANGO_SETTINGS_MODULE='tests.settings.inheritance',
                DJANGO_CONFIGURATION='Inheritance')
    def test_initialization_inheritance(self):
        importer = ConfigurationImporter()
        self.assertEqual(importer.module,
                         'tests.settings.inheritance')
        self.assertEqual(importer.name, 'Inheritance')

    @patch.dict(os.environ, clear=True,
                DJANGO_SETTINGS_MODULE='tests.settings.main',
                DJANGO_CONFIGURATION='NonExisting')
    @patch.object(sys, 'argv', ['python', 'manage.py', 'test',
                                '--settings=tests.settings.main',
                                '--configuration=Test'])
    def test_configuration_option(self):
        importer = ConfigurationImporter(check_options=False)
        self.assertEqual(importer.module, 'tests.settings.main')
        self.assertEqual(importer.name, 'NonExisting')
        importer = ConfigurationImporter(check_options=True)
        self.assertEqual(importer.module, 'tests.settings.main')
        self.assertEqual(importer.name, 'Test')

    def test_configuration_argument_in_cli(self):
        """
        Verify that's configuration option has been added to managements
        commands
        """
        proc = subprocess.Popen(['django-cadmin', 'test', '--help'],
                                stdout=subprocess.PIPE)
        self.assertIn('--configuration', proc.communicate()[0].decode('utf-8'))
        proc = subprocess.Popen(['django-cadmin', 'runserver', '--help'],
                                stdout=subprocess.PIPE)
        self.assertIn('--configuration', proc.communicate()[0].decode('utf-8'))

    @unittest2.skipIf(DJANGO_VERSION > (1, 10), 'only applies to Django < 1.10')
    def test_deprecated_option_list_command(self):
        """
        Verify that the configuration option is correctly added to any
        management commands which are still relying on option_list to
        add their own custom arguments

        Specific test for a pattern which was deprecated in Django 1.8
        and which will become completely unsupported in Django 1.10.
        https://docs.djangoproject.com/en/1.8/howto/custom-management-commands/#custom-commands-options
        """
        proc = subprocess.Popen(['django-cadmin', 'old_optparse_command', '--help'],
                                stdout=subprocess.PIPE)
        output = proc.communicate()[0].decode('utf-8')
        self.assertIn('--configuration', output)
        self.assertIn('--arg1', output)


text:
package com.pengrad.telegrambot.request;

import com.pengrad.telegrambot.response.BaseResponse;

/**
 * Stas Parshin
 * 01 July 2017
 */
public class SetChatTitle extends BaseRequest<SetChatTitle, BaseResponse> {

    public SetChatTitle(Object chatId, String title) {
        super(BaseResponse.class);
        add("chat_id", chatId).add("title", title);
    }
}


text:
  - Relax constraint on logstash-core-plugin-api to >= 1.60 <= 2.99

## 3.0.1
  - Republish all the gems under jruby.
## 3.0.0
  - Update the plugin to the version 2.0 of the plugin api, this change is required for Logstash 5.0 compatibility. See https://github.com/elastic/logstash/issues/5141
# 2.0.5
  - Depend on logstash-core-plugin-api instead of logstash-core, removing the need to mass update plugins on major releases of logstash
# 2.0.4
  - New dependency requirements for logstash-core for the 5.0 release
## 2.0.3
 - Escape rogue values by default, which can be interpreted by spreadsheet apps. Add option to turn it off

## 2.0.0
 - Plugins were updated to follow the new shutdown semantic, this mainly allows Logstash to instruct input plugins to terminate gracefully,
   instead of using Thread.raise on the plugins' threads. Ref: https://github.com/elastic/logstash/pull/3895
 - Dependency on logstash-core update to 2.0


text:
package com.jcalvopinam.client.conf;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

/**
 * @author Juan Calvopina M. <juan.calvopina@gmail.com>
 *
 */
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConf extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/", "/login", "/resources/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/home").permitAll()
                .and()
            .logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/login");
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("juanca").password("juanca").roles("USER");
    }

}


text:
:mod:`trac.wiki.macros` -- The standard set of Wiki macros
==========================================================

.. module :: trac.wiki.macros

The standard set of components corresponding to Wiki macros are not
meant to be used directly from the API. You may study their
implementation though, for getting inspiration. In particular, you'll
see they all subclass the `WikiMacroBase` class, which provides a
convenient way to implement a new `~trac.wiki.api.IWikiMacroProvider`
interface.

.. autoclass :: WikiMacroBase
   :members:

See also :teo:`wiki/WikiMacros#DevelopingCustomMacros`.