text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using System.Management.Automation;

namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery
{
    /// <summary>
    ///     Resumes Azure Site Recovery Job.
    /// </summary>
    [Cmdlet("Stop", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "RecoveryServicesAsrJob",DefaultParameterSetName = ASRParameterSets.ByObject,SupportsShouldProcess = true)]
    [Alias("Stop-ASRJob")]
    [OutputType(typeof(ASRJob))]
    public class StopAzureRmRecoveryServicesAsrJob : SiteRecoveryCmdletBase
    {
        /// <summary>
        ///     Gets or sets Job ID.
        /// </summary>
        [Parameter(
            ParameterSetName = ASRParameterSets.ByName,
            Mandatory = true)]
        [ValidateNotNullOrEmpty]
        public string Name { get; set; }

        /// <summary>
        ///     Gets or sets Job Object.
        /// </summary>
        [Parameter(
            ParameterSetName = ASRParameterSets.ByObject,
            Mandatory = true,
            ValueFromPipeline = true)]
        [ValidateNotNullOrEmpty]
        [Alias("Job")]
        public ASRJob InputObject { get; set; }

        /// <summary>
        ///     ProcessRecord of the command.
        /// </summary>
        public override void ExecuteSiteRecoveryCmdlet()
        {
            base.ExecuteSiteRecoveryCmdlet();

            if (this.InputObject != null)
            {
                this.Name = this.InputObject.Name;
            }

            if (this.ShouldProcess(
                this.Name,
                VerbsLifecycle.Stop))
            {
                switch (this.ParameterSetName)
                {
                    case ASRParameterSets.ByObject:
                        this.Name = this.InputObject.Name;
                        this.StopByName();
                        break;

                    case ASRParameterSets.ByName:
                        this.StopByName();
                        break;
                }
            }
        }

        /// <summary>
        ///     Restart by Name.
        /// </summary>
        private void StopByName()
        {
            var response = this.RecoveryServicesClient.CancelAzureSiteRecoveryJob(this.Name);

            var jobResponse = this.RecoveryServicesClient.GetAzureSiteRecoveryJobDetails(
                PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location));

            this.WriteObject(new ASRJob(jobResponse));
        }
    }
}


text:
@interface XHMessageVoiceFactory : NSObject

+ (UIImageView *)messageVoiceAnimationImageViewWithBubbleMessageType:(XHMessageType)type;

@end

redpajama_set_name: RedPajamaGithub


text:
/**
 *
 */
/**
 * @author Mario Posta
 *
 */
package homeworkProject.data;


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using Bloom.Collection;
using L10NSharp;
using SIL.Extensions;
using SIL.IO;
using SIL.Progress;
using SIL.Reporting;
using SIL.Xml;

namespace Bloom.Book
{
	///
	/// Handles chores related to Front and Back Matter packs.
	/// These allow users to have a set which fits there country/organizational situation, and have it applied
	/// to all books they create, whether original or from shells created in other country/organization contexts.
	///
	public class XMatterHelper
	{
		private readonly HtmlDom _bookDom;
		private readonly string _nameOfXMatterPack;

		///
		/// Constructs by finding the file and folder of the xmatter pack, given the its key name e.g. "Factory", "SILIndonesia".
		/// The default key name is provided as a method parameter, but that can be overridden by a value from inside the book.
		/// The name of the file should be (key)-XMatter.htm. The name and the location of the folder is not our problem...
		/// we leave it to the supplied fileLocator to find it.
		///
		/// <param name="xmatterNameFromCollectionSettings">e.g. "Factory", "SILIndonesia".  This can be overridden inside the bookDom.</param>
		/// <param name="fileLocator">The locator needs to be able tell us the path to an xmatter html file, given its name</param>
		public XMatterHelper(HtmlDom bookDom, string xmatterNameFromCollectionSettings, IFileLocator fileLocator)
		{
			string directoryPath = null;
			_bookDom = bookDom;
			var bookSpecificXMatterPack = bookDom.GetMetaValue("xmatter", null);
			if (!String.IsNullOrWhiteSpace(bookSpecificXMatterPack))
			{
				bookSpecificXMatterPack = MigrateXMatterName(bookSpecificXMatterPack);
				_nameOfXMatterPack = bookSpecificXMatterPack;
				var errorTemplate = LocalizationManager.GetString("Errors.XMatterSpecifiedByBookNotFound",
					"This book called for a Front/Back Matter pack named '{0}', but this version of Bloom does not have it, and Bloom could not find it on this computer. The book has been changed to use the Front/Back Matter pages from the Collection Settings.");
				directoryPath = GetXMatterDirectory(_nameOfXMatterPack, fileLocator, String.Format(errorTemplate, bookSpecificXMatterPack), false);
				if (directoryPath == null)
				{
					// Remove the xmatter specification from the DOM since it couldn't be found.
					_bookDom.RemoveMetaElement("xmatter");
				}
			}
			if (directoryPath == null)
			{
				_nameOfXMatterPack = xmatterNameFromCollectionSettings;
				directoryPath = GetXMatterDirectory(_nameOfXMatterPack, fileLocator, "It should not be possible to get an error here, because the collection verifies its xmatter name in CheckAndFixDependencies()", true);
			}
			var htmName = _nameOfXMatterPack + "-XMatter.html";
			PathToXMatterHtml = directoryPath.CombineForPath(htmName);
			if(!RobustFile.Exists(PathToXMatterHtml))
			{
				htmName = _nameOfXMatterPack + "-XMatter.htm"; // pre- Bloom 3.7
				PathToXMatterHtml = directoryPath.CombineForPath(htmName);
			}
			if (!RobustFile.Exists(PathToXMatterHtml))
			{
				ErrorReport.NotifyUserOfProblem(new ShowOncePerSessionBasedOnExactMessagePolicy(), "Could not locate the file {0} in {1} (also checked .html)", htmName, directoryPath);
				throw new ApplicationException();
			}
			PathToXMatterStylesheet = directoryPath.CombineForPath(GetStyleSheetFileName());
			if (!RobustFile.Exists(PathToXMatterHtml))
			{
				ErrorReport.NotifyUserOfProblem(new ShowOncePerSessionBasedOnExactMessagePolicy(), "Could not locate the file {0} in {1}", GetStyleSheetFileName(), directoryPath);
				throw new ApplicationException();
			}
			XMatterDom = XmlHtmlConverter.GetXmlDomFromHtmlFile(PathToXMatterHtml, false);
		}

		public static string GetXMatterDirectory(string nameOfXMatterPack, IFileLocator fileLocator, string errorMsg, bool throwIfError)
		{
			try
			{
				var directoryName = nameOfXMatterPack + "-XMatter";
				return fileLocator.LocateDirectoryWithThrow(directoryName);
			}
			catch (ApplicationException error)
			{
				var frontBackMatterProblem = LocalizationManager.GetString("Errors.XMatterProblemLabel", "Front/Back Matter Problem", "This shows in the 'toast' that pops up to notify the user of a non-fatal problem.");
				NonFatalProblem.Report(ModalIf.None, PassiveIf.All, frontBackMatterProblem, errorMsg, error);
				if (throwIfError)
					throw new ApplicationException(errorMsg);
			}
			return null;
		}

		public string GetStyleSheetFileName()
		{
//			var layout = SizeAndOrientation.FromDom(_dom);
//			return layout.PageSizeName + "-" + layout.OrientationName + "-" + _nameOfXMatterPack + "-XMatter.css";
			return _nameOfXMatterPack + "-XMatter.css";
		}

		///
		/// Set this if you want the xmatter stuff copied into a document folder. This makes sense when setting up or
		/// modifying one of the users books, but not when just displaying a book from a shell collection.
		///
		public string FolderPathForCopyingXMatterFiles { get; set; }

		///
		/// The location of the stylesheet for the selected xmatter pack.
		///
		public string PathToXMatterStylesheet { get; set; }

		///
		/// This exists in an XMatter-pack folder, which we infer from this file location.
		///
		public string PathToXMatterHtml { get; set; }

		///
		/// this is separated out to ease unit testing
		///
		public XmlDocument XMatterDom { get; set; }

		public void InjectXMatter(Dictionary<string, string> writingSystemCodes, Layout layout)
		{
			//don't want to pollute shells with this content
			if (!string.IsNullOrEmpty(FolderPathForCopyingXMatterFiles))
			{
				//copy over any image files used by this front matter
				string path = Path.GetDirectoryName(PathToXMatterHtml);
				foreach (var file in Directory.GetFiles(path, "*.png").Concat(Directory.GetFiles(path, "*.jpg").Concat(Directory.GetFiles(path, "*.gif").Concat(Directory.GetFiles(path, "*.bmp")))))
				{
					RobustFile.Copy(file, FolderPathForCopyingXMatterFiles.CombineForPath(Path.GetFileName(file)), true);
				}
			}

			//note: for debugging the template/css purposes, it makes our life easier if, at runtime, the html is pointing the original.
			//makes it easy to drop into a css editor and fix it up with the content we're looking at.
			//TODO:But then later, we want to save it so that these are found in the same dir as the book.
			_bookDom.AddStyleSheet(PathToXMatterStylesheet.ToLocalhost());

			//it's important that we append *after* this, so that these values take precendance (the template will just have empty values for this stuff)
			//REVIEW: I think all stylesheets now get sorted once they are all added: see HtmlDoc.SortStyleSheetLinks()
			XmlNode divBeforeNextFrontMattterPage = _bookDom.RawDom.SelectSingleNode("//body/div[@id='bloomDataDiv']");

			foreach (XmlElement xmatterPage in XMatterDom.SafeSelectNodes("/html/body/div[contains(@data-page,'required')]"))
			{
				var newPageDiv = _bookDom.RawDom.ImportNode(xmatterPage, true) as XmlElement;
				//give a new id, else thumbnail caches get messed up becuase every book has, for example, the same id for the cover.
				newPageDiv.SetAttribute("id", Guid.NewGuid().ToString());

				if (IsBackMatterPage(xmatterPage))
				{
					//note: this is redundant unless this is the 1st backmatterpage in the list
					divBeforeNextFrontMattterPage = _bookDom.RawDom.SelectSingleNode("//body/div[last()]");
				}

				//we want the xmatter pages to match what we found in the source book
				SizeAndOrientation.UpdatePageSizeAndOrientationClasses(newPageDiv, layout);

				//any @lang attributes that have a metalanguage code (N1, N2, V) get filled with the actual code.
				//note that this older method is crude, as you're in trouble if the user changes one of those to
				//a different language. Instead, use data-metalanguage.
				foreach ( XmlElement node in newPageDiv.SafeSelectNodes("//*[@lang]"))
				{
					var lang = node.GetAttribute("lang");
					if (writingSystemCodes.ContainsKey(lang))
					{
						node.SetAttribute("lang", writingSystemCodes[lang]);
					}
				}

				_bookDom.RawDom.SelectSingleNode("//body").InsertAfter(newPageDiv, divBeforeNextFrontMattterPage);
				divBeforeNextFrontMattterPage = newPageDiv;

				//enhance... this is really ugly. I'm just trying to clear out any remaining "{blah}" left over from the template
				foreach (XmlElement e in newPageDiv.SafeSelectNodes("//*[starts-with(text(),'{')]"))
				{
					foreach ( var node in e.ChildNodes)
					{
						XmlText t = node as XmlText;
						if(t!=null && t.Value.StartsWith("{"))
							t.Value =""; //otherwise html tidy will through away span's (at least) that are empty, so we never get a chance to fill in the values.
					}
				}
			}
			InjectFlyleafIfNeeded(layout);
		}

		///
		/// Some book layouts rely on the first page facing the second page. A Wall Calendar is one example.
		/// Here we check if the first content page has this requirement and, if so, we insert a blank "flyleaf"
		/// page.
		///
		private void InjectFlyleafIfNeeded(Layout layout)
		{
			// the "inside" here means "not counting the cover"
			var numberOfFrontMatterPagesInside = XMatterDom.SafeSelectNodes("//div[contains(@class,'bloom-frontMatter')]").Count - 1;
			var firstPageWouldNotBePartOfASpread = numberOfFrontMatterPagesInside%2 != 0;

			if(firstPageWouldNotBePartOfASpread)
			{
				var lastFrontMatterPage = _bookDom.SelectSingleNode("//div[contains(@class,'bloom-frontMatter')][last()]");

				var firstContentPageAndAlsoStartsSpread = _bookDom.SelectSingleNode(
					"//div[contains(@class,'bloom-frontMatter')][last()]" // last frontmatter page
					+ "/following-sibling::div[contains(@data-page, 'spread-start')]");
					// page after that says it needs to be facing the next page
				if(firstContentPageAndAlsoStartsSpread != null)
				{
					var flyDom = new XmlDocument();
					flyDom.LoadXml(@"

Flyleaf

");
					var flyleaf = _bookDom.RawDom.ImportNode(flyDom.FirstChild, true) as XmlElement;
					flyleaf.SetAttribute("id", Guid.NewGuid().ToString());
					lastFrontMatterPage.ParentNode.InsertAfter(flyleaf, lastFrontMatterPage);
					SizeAndOrientation.UpdatePageSizeAndOrientationClasses(flyleaf, layout);
				}
			}
		}

		//		//in the beta, 0.8, the ID of the page in the front-matter template was used for the 1st
		//		//page of every book. This screws up thumbnail caching.
		//		private void FixPageId(XmlDocument bookDom)
		//		{
		//			XmlElement page = bookDom.SelectSingleNode("//div[@id='74731b2d-18b0-420f-ac96-6de20f659810']") as XmlElement;
		//			if (page != null)
		//			{
		//				page.SetAttribute("id", Guid.NewGuid().ToString());
		//			}
		//		}

		public static bool IsFrontMatterPage(XmlElement pageDiv)
		{
			return pageDiv.SelectSingleNode("self::div[contains(@class, 'bloom-frontMatter')]") != null;
		}

		public static bool IsBackMatterPage(XmlElement pageDiv)
		{
			return pageDiv.SelectSingleNode("self::div[contains(@class, 'bloom-backMatter')]") != null;
		}

		///
		///remove any x-matter in the book
		///
		public static void RemoveExistingXMatter(HtmlDom dom)
		{
			foreach (XmlElement div in dom.SafeSelectNodes("//div[contains(@class,'bloom-frontMatter') or contains(@class,'bloom-backMatter')]"))
			{
				div.ParentNode.RemoveChild(div);
			}
		}

		///
		/// This will return a different name if we recognize the submitted name and we know that we have changed it or retired it.
		///
		public static string MigrateXMatterName(string nameOfXMatterPack)
		{
			// Bloom 3.7 retired the BigBook xmatter pack.
			// If we ever create another xmatter pack called BigBook (or rename the Factory pack) we'll need to redo this.
			string[] retiredPacks = { "BigBook" };
			if (retiredPacks.Contains(nameOfXMatterPack))
				return CollectionSettings.kDefaultXmatterName;
			return nameOfXMatterPack;;
		}
	}
}


text:
fn main() {
    let type = "foo"; //~ error: expected identifier, found keyword `type`
}


text:
from odk_logger.models import XForm, Instance
import os
from datetime import datetime, timedelta

from pyxform import *
from pyxform.builder import create_survey_element_from_dict

XFORM_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S.000"
ONE_HOUR = timedelta(0, 3600)

def _load_registration_survey_object():
    """
    Loads a registration survey with all the values necessary
    to register a surveyor.
    """
    survey = Survey(name=u"registration", id_string=u"registration")
    survey.add_child(create_survey_element_from_dict({
        u'type':u'text',u'name':u'name', u'label':u'Name'
    }))
    survey.add_child(create_survey_element_from_dict({
        u'type': u'start time',
        u'name': u'start'
    }))
    survey.add_child(create_survey_element_from_dict({
        u'type': u'end time',
        u'name': u'end'
    }))
    survey.add_child(create_survey_element_from_dict({
        u'type': u'imei',
        u'name': u'device_id'
    }))
    return survey

def _load_simple_survey_object():
    """
    Returns a "watersimple" survey object,
    complete with questions.
    """
    survey = Survey(name=u"WaterSimple", id_string=u"WaterSimple")
    survey.add_child(create_survey_element_from_dict({
        u'hint': {u'English':u'What is this point named?'},
        u'label': {u'English':u'Water Point Name'},
        u'type': u'text',
        u'name': u'name'
    }))
    survey.add_child(create_survey_element_from_dict({
        u'hint': {u'English':u'How many people use this every month?'},
        u'label': {u'English':u'Monthly Usage'},
        u'name': u'users_per_month',
        u'type': u'integer'
    }))
    survey.add_child(create_survey_element_from_dict({
        u'type': u'gps',
        u'name': u'geopoint',
        u'label': {u'English':u'Location'}
    }))
    survey.add_child(create_survey_element_from_dict({
        u'type': u'imei',
        u'name': u'device_id'
    }))
    survey.add_child(create_survey_element_from_dict({
        u'type': u'start time',
        u'name': u'start'
    }))
    survey.add_child(create_survey_element_from_dict({
        u'type': u'end time',
        u'name': u'end'
    }))
    return survey

class XFormManagerFactory(object):

    def create_registration_xform(self):
        """
        Calls 'get_registration_xform', saves the result, and returns.
        """
        xf = self.get_registration_xform()
        xf.save()
        return xf

    def get_registration_xform(self):
        """
        Gets a registration xform. (currently loaded in from fixture)
        Returns it without saving.
        """
        reg_xform = _load_registration_survey_object()
        return XForm(xml=reg_xform.to_xml())

    def create_registration_instance(self, custom_values={}):
        i = self.get_registration_instance(custom_values)
        i.save()
        return i

    def get_registration_instance(self, custom_values={}):
        """
        1. Checks to see if the registration form has been created alread. If not, it loads it in.

        2. Loads a registration instance.
        """
        registration_xforms = XForm.objects.filter(title=u"registration")
        if registration_xforms.count() == 0:
            xf = self.create_registration_xform()
        else:
            xf = registration_xforms[0]

        values = {
            u'device_id': u'12345',
            u'start': u'2011-01-01T09:50:06.966',
            u'end': u'2011-01-01T09:53:22.965'
        }

        if u'start' in custom_values:
            st = custom_values[u'start']
            custom_values[u'start'] = st.strftime(XFORM_TIME_FORMAT)

            #if no end_time is specified, defaults to 1 hour
            values[u'end'] = (st+ONE_HOUR).strftime(XFORM_TIME_FORMAT)

        if u'end' in custom_values:
            custom_values[u'end'] = custom_values[u'end'].strftime(XFORM_TIME_FORMAT)

        values.update(custom_values)

        reg_xform = _load_registration_survey_object()
        reg_instance = reg_xform.instantiate()
        reg_instance._id = xf.id_string

        for k, v in values.items():
            reg_instance.answer(name=k, value=v)

        instance_xml = reg_instance.to_xml()

        return Instance(xml=instance_xml)

    def create_simple_xform(self):
        xf = self.get_simple_xform()
        xf.save()
        return xf

    def get_simple_xform(self):
        survey_object = _load_simple_survey_object()
        return XForm(xml=survey_object.to_xml())

    def create_simple_instance(self, custom_values={}):
        i = self.get_simple_instance(custom_values)
        i.save()
        return i

    def get_simple_instance(self, custom_values={}):
        simple_xforms = XForm.objects.filter(title=u"WaterSimple")
        if simple_xforms.count() == 0:
            xf = self.create_simple_xform()
        else:
            xf = simple_xforms[0]

        #these values can be overridden with custom values
        values = {
            u'device_id': u'12345',
            u'start': u'2011-01-01T09:50:06.966',
            u'end': u'2011-01-01T09:53:22.965',
            u'geopoint': u'40.783594633609184 -73.96436698913574 300.0 4.0'
        }

        if u'start' in custom_values:
            st = custom_values[u'start']
            custom_values[u'start'] = st.strftime(XFORM_TIME_FORMAT)

            #if no end_time is specified, defaults to 1 hour
            values[u'end'] = (st+ONE_HOUR).strftime(XFORM_TIME_FORMAT)

        if u'end' in custom_values:
            custom_values[u'end'] = custom_values[u'end'].strftime(XFORM_TIME_FORMAT)

        values.update(custom_values)

        water_simple_survey = _load_simple_survey_object()
        simple_survey = water_simple_survey.instantiate()

        for k, v in values.items():
            simple_survey.answer(name=k, value=v)

        #setting the id_string so that it doesn't end up
        #with the timestamp of the new survey object
        simple_survey._id = xf.id_string

        instance_xml = simple_survey.to_xml()

        return Instance(xml=instance_xml)


text:
package helpers;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * Created by Adam on 2015-11-26.
 */
public class FileHelper {

    public String readFile(String fileLocation) {
        ClassLoader classLoader = getClass().getClassLoader();
        String file;
        try {
            file = classLoader.getResource(fileLocation).getFile();
        } catch (Exception e) {

            file = fileLocation;
        }

        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(file));

            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append("\n");
                line = br.readLine();
            }
            br.close();
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}


text:
/*

 sizeof.js

 A function to calculate the approximate memory usage of objects

 Created by Stephen Morley - http://code.stephenmorley.org/ - and released under
 the terms of the CC0 1.0 Universal legal code:

 http://creativecommons.org/publicdomain/zero/1.0/legalcode

 */

/* Returns the approximate memory usage, in bytes, of the specified object. The
 * parameter is:
 *
 * object - the object whose size should be determined
 */
module.exports = function sizeof(object) {

	// initialise the list of objects and size
	const objects = [object]
	let size = 0
	let key

	// loop over the objects
	for (let index = 0; index < objects.length; index++) {

		// determine the type of the object
		switch (typeof objects[index]) {

			// the object is a boolean
			case 'boolean':
				size += 4
				break

			// the object is a number
			case 'number':
				size += 8
				break

			// the object is a string
			case 'string':
				size += 2 * objects[index].length
				break

			// the object is a generic object
			case 'object':
				// if the object is not an array, add the sizes of the keys
				if (Object.prototype.toString.call(objects[index]) != '[object Array]') {
					for (key in objects[index]) size += 2 * key.length
				}

				// loop over the keys
				for (key in objects[index]) {

					// determine whether the value has already been processed
					let processed = false
					for (let search = 0; search < objects.length; search++) {
						if (objects[search] === objects[index][key]) {
							processed = true
							break
						}
					}

					// queue the value to be processed if appropriate
					if (! processed) objects.push(objects[index][key])

				}
		}

	}

	// return the calculated size
	return size

}


text:
//=================================================================================================

//=================================================================================================

#ifndef _BLAZETEST_MATHTEST_RANDOMLIMITS_H_
#define _BLAZETEST_MATHTEST_RANDOMLIMITS_H_

//*************************************************************************************************
// Includes
//*************************************************************************************************

#include <blaze/util/constraints/Numeric.h>
#include <blaze/util/typetraits/IsFloatingPoint.h>
#include <blaze/util/typetraits/IsSigned.h>

namespace blazetest {

//=================================================================================================
//
//  CLASS DEFINITION
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Initialization limits for all built-in data types
//
// The RandomLimits class provides minimum and maximum limits for the random initialization of
// all numerical built-in data types. Via the \a min and \a max functions all numerical data
// types are restricted to a fixed range of values. Unsigned integral data types are restricted
// to the range \f$ [0..10] \f$, signed integral data types to the range \f$ [-10..10] \f$, and
// floating point data types to the range \f$ [-1..1) \f$.
//
// Code examples:

   \code
   // Smallest allowed signed integer value
   int i = RandomLimits<int>::min();

   // Largest allowed double precision floating point value
   double d = RandomLimits<double>::max();
   \endcode
*/
template< typename Type >
struct RandomLimits
{
   //**Limit functions*****************************************************************************
   /*!\name Limit functions */
   //@{
   static inline Type min();
   static inline Type max();
   //@}
   //**********************************************************************************************

   //**Compile time checks*************************************************************************
   /*! \cond BLAZE_INTERNAL */
   BLAZE_CONSTRAINT_MUST_BE_NUMERIC_TYPE( Type );
   /*! \endcond */
   //**********************************************************************************************
};
//*************************************************************************************************

//=================================================================================================
//
//  LIMIT FUNCTIONS
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Initialization minimum.
//
// \return The smallest allowed initialization value.
*/
template< typename Type >
inline Type RandomLimits<Type>::min()
{
   if( blaze::IsSigned<Type>::value )
      return Type(-10);
   else if( blaze::IsFloatingPoint<Type>::value )
      return Type(-1);
   else
      return Type(0);
}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Initialization maximum.
//
// \return The largest allowed initialization value.
*/
template< typename Type >
inline Type RandomLimits<Type>::max()
{
   if( blaze::IsFloatingPoint<Type>::value )
      return Type(1);
   else
      return Type(10);
}
//*************************************************************************************************

} // namespace blazetest

#endif


text:
{-# LANGUAGE OverloadedStrings, ExtendedDefaultRules #-}
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
{-|
    Azurify is an incomplete yet sort-of-functional library and command line client to access the Azure Blob Storage API

    The following features are implemented:

    * Creating and deleting containers

    * Listing the contents of a container

    * Downloading blobs

    * Uploading a new block blob if it's no larger than 64MB

    * Deleting a blob

    * Breaking a blob lease
-}
module Azure ( createContainer
             , deleteContainer
             , listContainerRaw
#ifndef NO_XML
             , listContainer
#endif
             , changeContainerACL
             , createBlob
             , deleteBlob
             , getBlob
             , breakLease
             , module Azure.BlobDataTypes) where

import Azure.BlobDataTypes
#ifndef NO_XML
import Azure.BlobListParser
#endif

import Network.HTTP.Conduit
import Network.HTTP.Types (urlDecode, renderQuery, simpleQueryToQuery)
import Network.HTTP.Types.Header
import Network.HTTP.Types.Status
import System.Locale
import System.IO (openBinaryFile, IOMode(..))
import Data.List
import Data.Time
import Data.Char (isSpace)
import Data.CaseInsensitive (foldedCase)
import Data.Maybe (fromJust, isJust, listToMaybe, fromMaybe)
import Data.Ord (comparing)
import Network (withSocketsDo)

import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Char8 as L8
import qualified Data.ByteString.Lazy.UTF8 as LUTF8

import Data.Monoid
import Control.Arrow (second)
import Control.Monad.IO.Class (liftIO)

import Data.Digest.Pure.SHA (hmacSha256, bytestringDigest)
import qualified Data.ByteString.Base64 as B64

default (Int)

maybeResponseError :: Response t -> Maybe (Int, t)
maybeResponseError rsp = let status = (responseStatus rsp) in
    if statusCode status >= 300 || statusCode status < 200
               then Just (statusCode status, responseBody rsp)
               else Nothing

-- |Create a new container
createContainer :: B.ByteString -- ^ The account name
                -> B.ByteString -- ^ Authorisation key
                -> B.ByteString -- ^ Container name
                -> AccessControl -- ^ Access control of the container
                -> IO (Maybe (Int, L.ByteString)) -- ^ Nothing when creating was successful, otherwise HTTP status and content
createContainer account authKey containerName accessControl = do
    let resource = "/" <> containerName
    rsp <- doRequest account authKey resource [("restype", "container")] "PUT" "" hdrs
    return $ maybeResponseError rsp
    where hdrs = case accessControl of
                    ContainerPublic -> [("x-ms-blob-public-access", "container")]
                    BlobPublic -> [("x-ms-blob-public-access", "blob")]
                    Private -> []

-- |Delete a container
deleteContainer :: B.ByteString -- ^ The account name
                -> B.ByteString -- ^ Authorisation key
                -> B.ByteString -- ^ Container name
                -> IO (Maybe (Int, L.ByteString)) -- ^ Nothing when creating was successful, otherwise HTTP status and content
deleteContainer account authKey containerName = do
    let resource = "/" <> containerName
    rsp <- doRequest account authKey resource [("restype", "container")] "DELETE" "" []
    return $ maybeResponseError rsp

-- |List all blobs in a given container
listContainerRaw :: B.ByteString -- ^ The account name
              -> B.ByteString -- ^ Authorisation key
              -> B.ByteString -- ^ Container name
              -> IO (Either (Int, L.ByteString) L.ByteString) -- ^ Either the HTTP error code and content OR a list of Blobs
listContainerRaw account authKey containerName = do
    let resource = "/" <> containerName
    rsp <- doRequest account authKey resource [("restype", "container"), ("comp", "list")] "GET" "" []
    case maybeResponseError rsp of
      Just err -> return $ Left err
      Nothing -> return $ Right $ responseBody rsp

#ifndef NO_XML
-- |List all blobs in a given container
listContainer :: B.ByteString -- ^ The account name
              -> B.ByteString -- ^ Authorisation key
              -> B.ByteString -- ^ Container name
              -> IO (Either (Int, L.ByteString) [Blob]) -- ^ Either the HTTP error code and content OR a list of Blobs
listContainer account authKey containerName = do
  res <- listContainerRaw account authKey containerName
  case res of
    Right raw -> fmap Right $ parse $ L8.unpack $ raw
    Left err -> return $ Left err
#endif

-- |Set the access control on a container
changeContainerACL :: B.ByteString -- ^ The account name
                   -> B.ByteString -- ^ The authorisation key
                   -> B.ByteString -- ^ Container name
                   -> AccessControl -- ^ Access control specifier
                   -> IO (Maybe (Int, L.ByteString)) -- ^ Nothing when successful, HTTP error code and content otherwise
changeContainerACL account authKey containerName accessControl = do
    let resource = "/" <> containerName
    rsp <- doRequest account authKey resource [("restype", "container"), ("comp", "acl")] "PUT" "" hdrs
    return $ maybeResponseError rsp
    where hdrs = case accessControl of
                    ContainerPublic -> [("x-ms-blob-public-access", "container")]
                    BlobPublic -> [("x-ms-blob-public-access", "blob")]
                    Private -> []

-- |Upload a new blob to a container
createBlob :: B.ByteString -- ^ The account name
           -> B.ByteString -- ^ The authorisation key
           -> B.ByteString -- ^ Container name
           -> BlobSettings -- ^ The blob itself, note that Page blobs are *not supported*
           -> IO (Maybe (Int, L.ByteString)) -- ^ Nothing when successful, HTTP error code and content otherwise
createBlob account authKey containerName blobSettings =
    case blobSettings of
      BlockBlobSettings name contents settings ->
        blockBlobApi name contents settings []
      PageBlobSettings name contentLength settings ->
        createPageBlob name contentLength settings

      FileBlobSettings name fp settings -> do
        h <- openBinaryFile fp ReadMode
        let doBlock i = do
              contents <- B.hGetSome h (4 * 1048576) -- 4 MB is max size
              if B.null contents then return $ Right (i - 1)
                else do
                  mrsp <- createBlockBlob name settings contents (toB64 i)
                  case mrsp of
                    Nothing -> doBlock (i + 1)
                    Just rsp -> return $ Left rsp
        result <- doBlock 1
        case result of
          Left err -> return $ Just err
          Right lastBlockId -> do
            putStrLn $ show lastBlockId ++ " blocks uploaded. Committing..."
            createBlobApi [] name (blockListBody lastBlockId) settings [("comp", "blocklist")]

  where
    toB64 = B64.encode . B8.pack . padZeroes . show
    -- http://gauravmantri.com/2013/05/18/windows-azure-blob-storage-dealing-with-the-specified-blob-or-block-content-is-invalid-error/
    padZeroes s | length s > maxSize = error "azurify: too big for this hack!"
                | otherwise = concatMap (const "0") [1 .. maxSize - length s] ++ s
      where maxSize = 5

    blockListBody :: Int -> B.ByteString
    blockListBody lastId = "<?xml version=\"1.0\" encoding=\"utf-8\"?><BlockList>"
                           <> commits lastId
                           <> "</BlockList>"
    commits :: Int -> B.ByteString
    commits 0 = ""
    commits i = commits (i - 1) <> "<Uncommitted>" <> toB64 i <> "</Uncommitted>"

    createBlockBlob name settings contents blockId =
      blockBlobApi name contents settings [
          ("comp", "block"), ("blockid", blockId)
        ]

    blockBlobApi = createBlobApi [("x-ms-blob-type", "BlockBlob")]

    createBlobApi :: [Header]
            -> B.ByteString -> B.ByteString -> CommonBlobSettings
            -> [(B.ByteString, B.ByteString)] -- ^ params
            -> IO (Maybe (Int, L.ByteString))
    createBlobApi headers name content conf params = do
        let resource = "/" <> containerName <> "/" <> name
        rsp <- doRequest account authKey resource params "PUT" content hdrs
        return $ maybeResponseError rsp
      where
        hdrs = blobHeaders conf headers

    blobHeaders conf extra = (
          map (second fromJust) $ filter (\(_,a) -> isJust a)
                    [ ("Content-Type", blobSettingsContentType conf)
                    , ("Content-Encoding", blobSettingsContentEncoding conf)
                    , ("Content-Language", blobSettingsContentLanguage conf)
                    , ("Content-MD5", blobSettingsContentMD5 conf)
                    , ("Cache-Control", blobSettingsCacheControl conf)
                    ]
            ) ++ extra

    createPageBlob :: B.ByteString -> Integer -> CommonBlobSettings -> IO (Maybe (Int, L.ByteString))
    createPageBlob name contentLength conf = createBlobApi
            [ ("x-ms-blob-type", "PageBlob")
            , ("x-ms-blob-content-length", B8.pack $ show $ contentLength)
            ] name "" conf []

-- |Delete a blob from a container
deleteBlob :: B.ByteString -- ^ The account name
           -> B.ByteString -- ^ The authorsation key
           -> B.ByteString -- ^ The container name
           -> B.ByteString -- ^ The blob name
           -> IO (Maybe (Int, L.ByteString)) -- ^ Nothing when successful, HTTP error code and content otherwise
deleteBlob account authKey containerName blobName = do
    let resource = "/" <> containerName <> "/" <> blobName
    rsp <- doRequest account authKey resource [] "DELETE" "" [] -- TODO: Add support for snapshots
    return $ maybeResponseError rsp

-- |Download a blob
getBlob :: B.ByteString -- ^ The account name
        -> B.ByteString -- ^ The authorisation key
        -> B.ByteString -- ^ The container name
        -> B.ByteString -- ^ The blob name
        -> IO (Either (Int, L.ByteString) L.ByteString) -- ^ Nothing when successful, HTTP error code and content otherwise
getBlob account authKey containerName blobName = do
    let resource = "/" <> containerName <> "/" <> blobName
    rsp <- doRequest account authKey resource [] "GET" "" []
    return $ case maybeResponseError rsp of
      Just err -> Left err
      Nothing -> Right $ responseBody rsp

-- |Break a lease of a blob
breakLease :: B.ByteString -- ^ The account name
           -> B.ByteString -- ^ The authorisation key
           -> B.ByteString -- ^ The container name
           -> B.ByteString -- ^ The blob name
           -> IO (Maybe (Int, L.ByteString)) -- ^ Nothing when successful, HTTP error code and content otherwise
breakLease account authKey containerName blobName = do
    let resource = "/" <> containerName <> "/" <> blobName
    rsp <- doRequest account authKey resource [("comp", "lease")] "PUT" "" [("x-ms-lease-action", "break")]
    return $ maybeResponseError rsp

doRequest :: B.ByteString -> B.ByteString -> B.ByteString -> [(B.ByteString, B.ByteString)] -> B.ByteString -> B.ByteString -> [Header] -> IO (Response L.ByteString)
doRequest account authKey resource params reqType reqBody extraHeaders = do
    now <- liftIO httpTime
    let url = B8.unpack ("http://" <> account <> ".blob.core.windows.net" <> resource <> encodeParams params)
    initReq <- parseUrl url

    let headers = ("x-ms-version", "2011-08-18")
                : ("x-ms-date", now)
                : extraHeaders ++ requestHeaders initReq
    let getHeader hdr = listToMaybe $ map snd $ filter (\(a,_) -> a == hdr) headers
    let signData = defaultSignData { verb = reqType
                                   , contentLength = if reqType `elem` ["PUT", "DELETE"] || not (B.null reqBody) then B8.pack $ show $ B.length reqBody else ""
                                   , canonicalizedHeaders = canonicalizeHeaders headers
                                   , canonicalizedResource = canonicalizeResource account resource params
                                   , contentType = fromMaybe "" $ getHeader "Content-Type"
                                   , contentEncoding = fromMaybe "" $ getHeader "Content-Encoding"
                                   , contentLanguage = fromMaybe "" $ getHeader "Content-Language"
                                   , contentMD5 = fromMaybe "" $ getHeader "Content-MD5"
                                   , date = ""
                                   , ifModifiedSince = fromMaybe "" $ getHeader "If-Modified-Since"
                                   , ifMatch = fromMaybe "" $ getHeader "If-Match"
                                   , ifNoneMatch = fromMaybe "" $ getHeader "If-None-Match"
                                   , ifUnmodifiedSince = fromMaybe "" $ getHeader "If-Unmodified-Since"
                                   , range = fromMaybe "" $ getHeader "Range"
                                   }
    let signature = sign authKey signData
    let authHeader = ("Authorization", "SharedKey " <> account <> ":" <> signature)
    let request = initReq { method = reqType
                          , requestHeaders = authHeader : headers
                          , checkStatus = \_ _ _ -> Nothing -- don't throw an exception when a non-2xx error code is received
                          , requestBody = RequestBodyBS reqBody }

    withSocketsDo $ withManager $ \manager -> httpLbs request manager

encodeParams :: [(B.ByteString, B.ByteString)] -> B.ByteString
encodeParams = renderQuery True . simpleQueryToQuery

canonicalizeHeaders :: [Header] -> B.ByteString
canonicalizeHeaders headers = B.intercalate "\n" unfoldHeaders
    where headerStrs = map (\(a, b) -> strip $ foldedCase a <> ":" <> strip b) headers
          xmsHeaders = filter (\hdr ->  "x-ms" `B.isPrefixOf` hdr) headerStrs
          sortedHeaders = sort xmsHeaders
          unfoldHeaders = map (B8.pack . unwords . words . B8.unpack) sortedHeaders

canonicalizeResource :: B.ByteString -> B.ByteString -> [(B.ByteString, B.ByteString)] -> B.ByteString
canonicalizeResource accountName uriPath params = "/" <> accountName <> uriPath <> "\n" <> canonParams
    where canonParams = strip $ B.intercalate "\n" $ map (\(k,v) -> (urlDecode True) k <> ":" <> (urlDecode True v)) $ sortBy (comparing fst) params

strip :: B.ByteString -> B.ByteString
strip = f . f
   where f = B8.pack . reverse . dropWhile isSpace . B8.unpack

data SignData = SignData { verb :: B.ByteString
                         , contentEncoding :: B.ByteString
                         , contentLanguage :: B.ByteString
                         , contentLength :: B.ByteString
                         , contentMD5 :: B.ByteString
                         , contentType :: B.ByteString
                         , date :: B.ByteString
                         , ifModifiedSince :: B.ByteString
                         , ifMatch :: B.ByteString
                         , ifNoneMatch :: B.ByteString
                         , ifUnmodifiedSince :: B.ByteString
                         , range :: B.ByteString
                         , canonicalizedHeaders :: B.ByteString
                         , canonicalizedResource :: B.ByteString
                         }

defaultSignData :: SignData
defaultSignData = SignData undefined "" "" "" "" "" "" "" "" "" "" "" undefined undefined

stringToSign :: SignData -> B.ByteString
stringToSign SignData {..} =
    strip $ B.intercalate "\n" [verb, contentEncoding, contentLanguage, contentLength, contentMD5, contentType, date, ifModifiedSince, ifMatch, ifNoneMatch, ifUnmodifiedSince, range, canonicalizedHeaders, canonicalizedResource]

httpTime :: IO B.ByteString
httpTime = fmap (B8.pack . formatTime defaultTimeLocale "%a, %d %b %Y %X GMT") getCurrentTime

sign :: B.ByteString -> SignData -> B.ByteString
sign key = B64.encode . toStrict . bytestringDigest . hmacSha256 (toLazy $ B64.decodeLenient key) . LUTF8.fromString . B8.unpack . stringToSign

toLazy :: B8.ByteString -> LUTF8.ByteString
toLazy a = L.fromChunks [a]

toStrict :: LUTF8.ByteString -> B8.ByteString
toStrict = B.concat . L.toChunks


text:
<?php
$OUTPUT->header();
?>

This request is missing critical lauch data.  This URL is intended to be
launched using
IMS Learning
Tools Interoperability with POST data that is signed using an
OAuth Key and secret that needs to be obtained from the system administrator
of
<?php echo($CFG->servicename); ?>.  At a minumum this application needs
a user_id parameter as part of the LTI launch data (i.e. no anonymous launches).

<?php
if ( count($_POST) > 0 ) {
    print "
\n";
    print "Raw POST Parameters:\n\n";
    ksort($_POST);
    foreach($_POST as $key => $value ) {
        print htmlent_utf8($key) . "=" . htmlent_utf8($value) . " (".mb_detect_encoding($value).")\n";
    }
    print "
\n";
}

$OUTPUT->footer();


text:
ms_fvstrip.ado - Stata utility for factor variables.  Takes an expanded varlist with possible FVs and strips out b/n/o notation, and returns results in r(varlist).  Optionally also omits omittable FVs.  If varlist needs expansion, use the expand option.

Options:
   expand calls fvexpand on full varlist
   onebyone + expand calls fvexpand on elements of varlist
   dropomit omits omitted variables from stripped r(varlist)
   noisily displays the stripped r(varlist)

Examples:

fvexpand i.foreign =>
r(varlist) : "0b.foreign 1.foreign"

ms_fvstrip i.foreign, expand =>
r(varlist) : "0.foreign 1.foreign"

ms_fvstrip i.foreign, expand dropomit =>
r(varlist) : "1.foreign"


text:
My Projects

        {% for project in site.data.projects %}
            {% assign loopindex = forloop.index | modulo: 2 %}
            {% if forloop.last %}
                {% if forloop.last == forloop.first %}

                {% else %}

                {% endif %}
            {% else %}

            {% endif %}

{{ project.name }}

{{ project.desc }}

      {% endfor %}


text:
module RUser
  # This module defines the RandomUser.me API constants used by classes.
  # @author Joshua Kendall
  module Api
    # The URL for the API.
    URL = 'https://api.randomuser.me'.freeze

    # The version of the API that is used.
    VERSION = '0.7'.freeze
  end
end


text:
package org.elasticsearch.index.engine;

import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.SearcherManager;
import org.apache.lucene.store.AlreadyClosedException;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ElasticsearchIllegalStateException;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.store.Store;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Searcher for an Engine
 */
public class EngineSearcher extends Engine.Searcher {
    private final SearcherManager manager;
    private final AtomicBoolean released = new AtomicBoolean(false);
    private final Store store;
    private final ESLogger logger;

    public EngineSearcher(String source, IndexSearcher searcher, SearcherManager manager, Store store, ESLogger logger) {
        super(source, searcher);
        this.manager = manager;
        this.store = store;
        this.logger = logger;
    }

    @Override
    public void close() throws ElasticsearchException {
        if (!released.compareAndSet(false, true)) {
                /* In general, searchers should never be released twice or this would break reference counting. There is one rare case
                 * when it might happen though: when the request and the Reaper thread would both try to release it in a very short amount
                 * of time, this is why we only log a warning instead of throwing an exception.
                 */
            logger.warn("Searcher was released twice", new ElasticsearchIllegalStateException("Double release"));
            return;
        }
        try {
            manager.release(this.searcher());
        } catch (IOException e) {
            throw new ElasticsearchIllegalStateException("Cannot close", e);
        } catch (AlreadyClosedException e) {
                /* this one can happen if we already closed the
                 * underlying store / directory and we call into the
                 * IndexWriter to free up pending files. */
        } finally {
            store.decRef();
        }
    }
}


text:
"""
This module provides a simple rank/select interface to a sorted list/array
of integers.

See https://en.wikipedia.org/wiki/Succinct_data_structure for more
general information about the API.
"""

__docformat__ = 'restructuredtext'

import array

class sparse:
    """
    The sparse class is for presenting a sparse set of integers through
    a rank/select interface.
    """

    def __init__(self, B, xs):
        """
        Create a new sparse set object.

        The parameter `B` is the width of the elements in bits. It is
        an error to attempt to include elements >= 2**B.

        The parameter `xs` gives the elements of the set. These must be
        in sorted order, and the type of `xs` must be a list/array or some
        other object which supports ordinal access in the same manner.
        """
        self.B = B
        self.S = B - 10
        self.xs = xs
        self.toc = array.array('I', [0 for i in xrange(1024+1)])
        for x in xs:
            v = x >> self.S
            self.toc[v+1] += 1
        t = 0
        for i in xrange(1024+1):
            t += self.toc[i]
            self.toc[i] = t

    def size(self):
        """
        Return the number of possible elements in the set.  That is,
        the size of the domain.
        """
        return 1 << self.B

    def count(self):
        """
        Return the number of elements in the set.
        """
        return len(self.xs)

    def rank(self, x):
        """
        The `rank` method returns, given `x`, the rank of `x` in the set,
        which is the number of elements in the set which are strictly
        less than `x`.

        It is an error for `x` to be outside the interval [0, 2**B).
        """
        v = x >> self.S
        l = self.toc[v]
        h = self.toc[v+1] - 1
        while h >= l:
            m = (h + l) // 2
            y = self.xs[m]
            if y == x:
                return m
            if y < x:
                l = m + 1
            else:
                h = m - 1
        return l

    def rank2(self, x0, x1):
        """
        Perform `rank` operations on x0 and x1. Equivalent to
            return(rank(x0), rank(x1)),
        but assumes that x1 has a nearby rank.

        It is an error if x1 <= x0.
        """
        assert x0 <= x1
        r0 = self.rank(x0)
        z = len(self.xs)
        r1 = r0
        while r1 < z and self.xs[r1] < x1:
            r1 += 1
        return (r0, r1)

    def access(self, x):
        """
        Return the rank of `x` if it is in the set, and None
        otherwise.
        """
        (r0, r1) = self.rank2(x, x+1)
        if r1 == r0:
            return None
        else:
            return r0

    def select(self, i):
        """
        The `select` method returns, given `i`, the ith smallest item
        in the set.

        Given the set s, is an error for `i` to be outside the interval
        [0, s.count()).
        """
        assert 0 <= i
        assert i < self.count()
        return self.xs[i]


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**meta** | [**Meta**](Meta.md) | Meta-data | [optional]
**coverages** | [**[DrugCoverage]**](DrugCoverage.md) | Coverages associated with the plan. | [optional]
**plans** | [**[ACAPlan2018]**](ACAPlan2018.md) | Plan search results | [optional]


text:
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var core_1 = require('@angular/core');
var async_1 = require('../facade/async');
var model_1 = require('../model');
var validators_1 = require('../validators');
var abstract_form_group_directive_1 = require('./abstract_form_group_directive');
var control_container_1 = require('./control_container');
var control_value_accessor_1 = require('./control_value_accessor');
var ng_control_1 = require('./ng_control');
var ng_form_1 = require('./ng_form');
var ng_model_group_1 = require('./ng_model_group');
var shared_1 = require('./shared');
var template_driven_errors_1 = require('./template_driven_errors');
exports.formControlBinding = {
    provide: ng_control_1.NgControl,
    useExisting: core_1.forwardRef(function () { return NgModel; })
};
var resolvedPromise = Promise.resolve(null);
var NgModel = (function (_super) {
    __extends(NgModel, _super);
    function NgModel(_parent, _validators, _asyncValidators, valueAccessors) {
        _super.call(this);
        this._parent = _parent;
        this._validators = _validators;
        this._asyncValidators = _asyncValidators;
        /** @internal */
        this._control = new model_1.FormControl();
        /** @internal */
        this._registered = false;
        this.update = new async_1.EventEmitter();
        this.valueAccessor = shared_1.selectValueAccessor(this, valueAccessors);
    }
    NgModel.prototype.ngOnChanges = function (changes) {
        this._checkForErrors();
        if (!this._registered)
            this._setUpControl();
        if (shared_1.isPropertyUpdated(changes, this.viewModel)) {
            this._updateValue(this.model);
            this.viewModel = this.model;
        }
    };
    NgModel.prototype.ngOnDestroy = function () { this.formDirective && this.formDirective.removeControl(this); };
    Object.defineProperty(NgModel.prototype, "control", {
        get: function () { return this._control; },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(NgModel.prototype, "path", {
        get: function () {
            return this._parent ? shared_1.controlPath(this.name, this._parent) : [this.name];
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(NgModel.prototype, "formDirective", {
        get: function () { return this._parent ? this._parent.formDirective : null; },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(NgModel.prototype, "validator", {
        get: function () { return shared_1.composeValidators(this._validators); },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(NgModel.prototype, "asyncValidator", {
        get: function () {
            return shared_1.composeAsyncValidators(this._asyncValidators);
        },
        enumerable: true,
        configurable: true
    });
    NgModel.prototype.viewToModelUpdate = function (newValue) {
        this.viewModel = newValue;
        this.update.emit(newValue);
    };
    NgModel.prototype._setUpControl = function () {
        this._isStandalone() ? this._setUpStandalone() :
            this.formDirective.addControl(this);
        this._registered = true;
    };
    NgModel.prototype._isStandalone = function () {
        return !this._parent || (this.options && this.options.standalone);
    };
    NgModel.prototype._setUpStandalone = function () {
        shared_1.setUpControl(this._control, this);
        this._control.updateValueAndValidity({ emitEvent: false });
    };
    NgModel.prototype._checkForErrors = function () {
        if (!this._isStandalone()) {
            this._checkParentType();
        }
        this._checkName();
    };
    NgModel.prototype._checkParentType = function () {
        if (!(this._parent instanceof ng_model_group_1.NgModelGroup) &&
            this._parent instanceof abstract_form_group_directive_1.AbstractFormGroupDirective) {
            template_driven_errors_1.TemplateDrivenErrors.formGroupNameException();
        }
        else if (!(this._parent instanceof ng_model_group_1.NgModelGroup) && !(this._parent instanceof ng_form_1.NgForm)) {
            template_driven_errors_1.TemplateDrivenErrors.modelParentException();
        }
    };
    NgModel.prototype._checkName = function () {
        if (this.options && this.options.name)
            this.name = this.options.name;
        if (!this._isStandalone() && !this.name) {
            template_driven_errors_1.TemplateDrivenErrors.missingNameException();
        }
    };
    NgModel.prototype._updateValue = function (value) {
        var _this = this;
        resolvedPromise.then(function () { _this.control.setValue(value, { emitViewToModelChange: false }); });
    };
    /** @nocollapse */
    NgModel.decorators = [
        { type: core_1.Directive, args: [{
                    selector: '[ngModel]:not([formControlName]):not([formControl])',
                    providers: [exports.formControlBinding],
                    exportAs: 'ngModel'
                },] },
    ];
    /** @nocollapse */
    NgModel.ctorParameters = [
        { type: control_container_1.ControlContainer, decorators: [{ type: core_1.Optional }, { type: core_1.Host },] },
        { type: Array, decorators: [{ type: core_1.Optional }, { type: core_1.Self }, { type: core_1.Inject, args: [validators_1.NG_VALIDATORS,] },] },
        { type: Array, decorators: [{ type: core_1.Optional }, { type: core_1.Self }, { type: core_1.Inject, args: [validators_1.NG_ASYNC_VALIDATORS,] },] },
        { type: Array, decorators: [{ type: core_1.Optional }, { type: core_1.Self }, { type: core_1.Inject, args: [control_value_accessor_1.NG_VALUE_ACCESSOR,] },] },
    ];
    /** @nocollapse */
    NgModel.propDecorators = {
        'model': [{ type: core_1.Input, args: ['ngModel',] },],
        'name': [{ type: core_1.Input },],
        'options': [{ type: core_1.Input, args: ['ngModelOptions',] },],
        'update': [{ type: core_1.Output, args: ['ngModelChange',] },],
    };
    return NgModel;
}(ng_control_1.NgControl));
exports.NgModel = NgModel;
//# sourceMappingURL=ng_model.js.map


text:
using System.Configuration;
using System.Security.Claims;
using Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;

namespace WebApp
{
    public partial class Startup
    {
        private static readonly string GoogleClientId = ConfigurationManager.AppSettings["google:ClientId"];
        private static readonly string GoogleClientSecret = ConfigurationManager.AppSettings["google:Secret"];

        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseGoogleAuthentication(
                new GoogleOAuth2AuthenticationOptions()
                {
                    ClientId = GoogleClientId,
                    ClientSecret = GoogleClientSecret,
                    AuthenticationMode = AuthenticationMode.Active,
                    Provider = new GoogleOAuth2AuthenticationProvider()
                    {
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
                        OnAuthenticated = async context =>
                        {
                            var user = context.User.Root;
                            context.Identity.AddClaim(new Claim(Utilities.IdentityHelpers.IMAGE_URI_K, user["image"]?["url"]?.ToString()));
                            context.Identity.AddClaim(new Claim(Utilities.IdentityHelpers.PERSON_ID_K, $"{user["id"]?.ToString()}:{user["emails"]?.First?["value"]?.ToString()}"));
                            context.Identity.AddClaim(new Claim(Utilities.IdentityHelpers.PERSON_FIRSTNAME_K, user["name"]?["givenName"]?.ToString()));
                            context.Identity.AddClaim(new Claim(Utilities.IdentityHelpers.PERSON_LASTNAME_K, user["name"]?["familyName"]?.ToString()));
                            context.Identity.AddClaim(new Claim(Utilities.IdentityHelpers.PERSON_PRIMARY_EMAIL_K, user["emails"]?.First?["value"]?.ToString()));
                        }
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
                    }
                });
        }
    }
}


text:
/*
Example of wrapper for getyx() and similar macros, in case this is needed for
portability. Compile this into a dynamic library, and then use something like
this to access:

class CursesPoint is repr('CStruct') {
    has int $.y;
    has int $.x;
}

sub term_curses_getyx(OpaquePointer, CursesPoint) is native('your-library-name');
sub term_curses_getmaxyx(OpaquePointer, CursesPoint) is native('your-library-name');

my $p = CursesPoint.new;
term_curses_getyx($!stdscr, $p);
say "I'm at {$p.y}, {$p.x}";

*/

#include <curses.h>

struct Point {
    long y;
    long x;
};

void term_curses_getyx(WINDOW *win, struct Point *p) {
    getyx(win, p->y, p->x);
}

void term_curses_getmaxyx(WINDOW *win, struct Point *p) {
    getmaxyx(win, p->y, p->x);
}


text:
const assert = require('assert')
const { find } = require('lodash')

module.exports = (field, name, args) => {
  assert('directives' in field.astNode, 'No directives found')
  assert(field.astNode.directives.length, 'No directives found')

  const directive = find(field.astNode.directives, { name: { value: name } })

  assert(directive, `Directive ${name} not found`)

  if (!args) return

  Object.keys(args).forEach(name => {
    const arg = find(directive.arguments, { name: { value: name } })

    assert(arg, `Missing ${name} directive argument`)
    assert.strictEqual(arg.value.value, args[name], `Incorrect ${name} directive argument value`)
  })
}


text:
package io.jsonwebtoken.impl.compression;

import io.jsonwebtoken.CompressionAlgorithm;
import io.jsonwebtoken.lang.Assert;

/**
 * DefaultCompressorFactory
 *
 * @since 0.5.2
 */
public class DefaultCompressorFactory implements CompressorFactory {

    public static final CompressorFactory INSTANCE = new DefaultCompressorFactory();

    @Override
    public Compressor createCompressor(CompressionAlgorithm alg) {
        Assert.notNull(alg, "CompressionAlgorithm cannot be null.");

        switch (alg) {
            case DEFLATE:
                return new DeflateCompressor();
            default:
                return new GzipCompressor();
        }
    }
}


text:
$.do.newDroplet = function(){
  // show newdroplet template in modal
  var datas = {};
  $.do.common.simpleGET('https://api.digitalocean.com/v2/images?per_page=100', {}, function(data, status, xhr){
    var images  = [];

    // make our private images the first ones listed
    $.each(data.images, function(index, image){
      if (!image.public){
        images.push(image);
      }
    });

    $.each(data.images, function(index, image){
      if (image.public){
        images.push(image);
      }
    });

    datas.images = images;

    $.do.common.simpleGET('https://api.digitalocean.com/v2/regions', {}, function(data, status, xhr){
      datas.regions = data.regions;

      $.do.common.simpleGET('https://api.digitalocean.com/v2/sizes',   {}, function(data, status, xhr){
        datas.sizes = data.sizes;

        $.do.common.simpleGET('https://api.digitalocean.com/v2/account/keys', {}, function(data, status, xhr){
          $.do.common.regionsSizes = datas;
          datas.keys = data.ssh_keys;

          $.do.common.loadColumn('newdroplet', datas, 'central-new-droplet');
          $('#central-new-droplet-col').on('do:newdroplet:column:loaded', function(){
            $('#createDroplet').remove();
            $('.popover-trigger').popover({});

            $('#new-droplet-form').on('ajax:success', function(ajax, response, status) {
              $('#central-col').mustache("droplettemplate", [response.droplet], { method: 'prepend' });

              $.do.common.messageDisplay('success', 'Droplet created!');

              $('.dlt-droplet').on('ajax:success', function() {
                $.do.common.messageDisplay('success', 'Droplet deleted!');
                $(this).closest('.well').remove();
              });

              $(this).parent().remove();
            });

            $('input[name=region]').on('change', function(e){
              $('input[name=size]').attr('disabled', false);

              // selecting a region will invalidate some sizes
              $.each($.do.common.regionsSizes.regions, function(index, region){
                if (region.slug == $('input[name=region]:checked').val()) {
                  $('input[name=size]').not('input[name=size][value=' + region.sizes.join('],[value=') + ']').attr('disabled', true);
                }
              });
            });

            $('input[name=size]').on('change', function(e){
              $('input[name=region]').attr('disabled', false);

              // selecting a size will invalidate some regions
              $.each($.do.common.regionsSizes.sizes, function(index, size){
                if (size.slug == $('input[name=size]:checked').val()) {
                  $('input[name=region]').not('input[name=region][value=' + size.regions.join('],[value=') + ']').attr('disabled', true);
                }
              });
            });
          });
        });
      });
    });
  });
}


text:
package org.culturegraph.mf.test;

import java.io.InputStream;
import java.util.List;

import org.culturegraph.mf.exceptions.FormatException;
import org.junit.runner.Description;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.ParentRunner;
import org.junit.runners.model.InitializationError;

/**
 * @author Christoph Böhme <c.boehme@dnb.de>, Markus Michael Geipel
 *
 */
final class TestCaseRunner extends ParentRunner<TestCase> {

	private final Class<?> clazz;
	private final List<TestCase> testCases;
	private final String testDefinition;

	public TestCaseRunner(final Class<?> clazz,  final String testDefinition)
			throws InitializationError {
		super(clazz);
		this.clazz = clazz;
		final InputStream inputStream = clazz.getResourceAsStream(testDefinition);
		if(null==inputStream){
			throw new IllegalArgumentException("'" + testDefinition + "' does not exist!");
		}
		this.testCases = TestCaseLoader.load(inputStream);
		this.testDefinition = testDefinition;
	}

	@Override
	protected String getName() {
		return testDefinition;
	}

	@Override
	protected List<TestCase> getChildren() {
		return testCases;
	}

	@Override
	protected Description describeChild(final TestCase child) {
		return Description.createTestDescription(clazz, child.getName());
	}

	@Override
	protected void runChild(final TestCase child, final RunNotifier notifier) {
		if (child.isIgnore()) {
			notifier.fireTestIgnored(describeChild(child));
		} else {
			notifier.fireTestStarted(describeChild(child));
			try {
				child.run();
			} catch (final FormatException e) {
				notifier.fireTestFailure(new Failure(describeChild(child),
						new AssertionError(e)));
			} catch (final Throwable e) {
				notifier.fireTestFailure(new Failure(describeChild(child), e));
			} finally {
				notifier.fireTestFinished(describeChild(child));
			}
		}
	}
}


text:
<?php

namespace Drupal\diff\Controller;

use Drupal\node\NodeInterface;

/**
 * Returns responses for Node Revision routes.
 */
class NodeRevisionController extends PluginRevisionController {

  /**
   * Returns a form for revision overview page.
   *
   * @todo This might be changed to a view when the issue at this link is
   *   resolved: https://drupal.org/node/1863906
   *
   * @param \Drupal\node\NodeInterface $node
   *   The node whose revisions are inspected.
   *
   * @return array
   *   Render array containing the revisions table for $node.
   */
  public function revisionOverview(NodeInterface $node) {
    return $this->formBuilder()->getForm('Drupal\diff\Form\RevisionOverviewForm', $node);
  }

  /**
   * Returns a table which shows the differences between two node revisions.
   *
   * @param \Drupal\node\NodeInterface $node
   *   The node whose revisions are compared.
   * @param int $left_revision
   *   Vid of the node revision from the left.
   * @param int $right_revision
   *   Vid of the node revision from the right.
   * @param string $filter
   *   If $filter == 'raw' raw text is compared (including html tags)
   *   If $filter == 'raw-plain' markdown function is applied to the text before comparison.
   *
   * @return array
   *   Table showing the diff between the two node revisions.
   */
  public function compareNodeRevisions(NodeInterface $node, $left_revision, $right_revision, $filter) {
    $storage = $this->entityTypeManager()->getStorage('node');
    $route_match = \Drupal::routeMatch();
    $left_revision = $storage->loadRevision($left_revision);
    $right_revision = $storage->loadRevision($right_revision);
    $build = $this->compareEntityRevisions($route_match, $left_revision, $right_revision, $filter);
    return $build;
  }

}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.34014
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace SuperScript.Templates.jQueryTmpl.Properties {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    public class Resources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SuperScript.Templates.jQueryTmpl.Properties.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to (function (a) { var r = a.fn.domManip, d = "_tmplitem", q = /^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /, b = {}, f = {}, e, p = { key: 0, data: {} }, i = 0, c = 0, l = []; function g(g, d, h, e) { var c = { data: e || (e === 0 || e === false) ? e : d ? d.data : {}, _wrap: d ? d._wrap : null, tmpl: null, parent: d || null, nodes: [], calls: u, nest: w, wrap: x, html: v, update: t }; g && a.extend(c, g, { nodes: [], parent: d }); if (h) { c.tmpl = h; c._ctnt = c._ctnt || c.tmpl(a, c); c.key = ++i; (l.length ? f : b)[i] [rest of string was truncated]";.
        /// </summary>
        public static string jquery_tmpl {
            get {
                return ResourceManager.GetString("jquery_tmpl", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to // Obtained from https://github.com/andrewdavey/cassette/blob/master/src/Cassette.JQueryTmpl/Resources/jqueryTmplCompiler.js
        ///
        ///// This code was butchered out of https://github.com/jquery/jquery-tmpl
        ///// It provides just enough to build HTML templates into a JavaScript function.
        ///
        ////*!
        ///* jQuery Templates Plugin 1.0.0pre
        ///* http://github.com/jquery/jquery-tmpl
        ///* Requires jQuery 1.4.2
        ///*
        ///* Copyright Software Freedom Conservancy, Inc.
        ///* Dual licensed under the MIT or GPL Version 2 licenses.
        ///* http://jquer [rest of string was truncated]";.
        /// </summary>
        public static string jqueryTmplCompiler {
            get {
                return ResourceManager.GetString("jqueryTmplCompiler", resourceCulture);
            }
        }
    }
}


text:
class MeetingInvitationMailer < ActionMailer::Base
  include EmailHeaderHelper
  include ApplicationHelper

  helper ApplicationHelper

  def invite(meeting, member)
    @member = member
    @meeting = meeting
    @host_address = AddressPresenter.new(@meeting.venue.address)
    @rsvp_url = meeting_url(@meeting)

    subject = "You are invited to codebar's #{@meeting.name} on #{humanize_date(@meeting.date_and_time)}"
    mail(mail_args(@member, subject)) do |format|
      format.html
    end
  end

  def attending(meeting, member)
    @member = member
    @meeting = meeting
    @host_address = AddressPresenter.new(@meeting.venue.address)
    @cancellation_url = meeting_url(@meeting)

    subject = "See you at #{@meeting.name} on #{humanize_date(@meeting.date_and_time)}"
    mail(mail_args(@member, subject)) do |format|
      format.html
    end
  end

  def approve_from_waitlist(meeting, member)
    @member = member
    @meeting = meeting
    @host_address = AddressPresenter.new(@meeting.venue.address)
    @cancellation_url = meeting_url(@meeting)

    subject = "A spot opened up for #{@meeting.name} on #{humanize_date(@meeting.date_and_time)}"
    mail(mail_args(@member, subject)) do |format|
      format.html
    end
  end

  def attendance_reminder(meeting, member)
    @member = member
    @meeting = meeting
    @host_address = AddressPresenter.new(@meeting.venue.address)
    @cancellation_url = meeting_url(@meeting)

    subject = "Reminder: You have a spot for #{@meeting.name} on #{humanize_date(@meeting.date_and_time)}"
    mail(mail_args(@member, subject)) do |format|
      format.html
    end
  end

  private

  helper do
    def full_url_for(path)
      "#{@host}#{path}"
    end
  end
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>fastText: Class Members</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

fastText
    d00d36476b15

Fast text processing tool/library

Here is a list of all class members with links to the classes they belong to:

- e -

EOS
: fasttext::Dictionary

EOW
: fasttext::Dictionary

epoch
: fasttext::Args

eps_
: fasttext::ProductQuantizer

Estep()
: fasttext::ProductQuantizer

Generated by

     1.8.13


text:
package org.elasticsearch.action.admin.cluster.node.info;

import org.elasticsearch.action.support.nodes.NodesOperationRequestBuilder;
import org.elasticsearch.client.ElasticsearchClient;

/**
 *
 */
public class NodesInfoRequestBuilder extends NodesOperationRequestBuilder<NodesInfoRequest, NodesInfoResponse, NodesInfoRequestBuilder> {

    public NodesInfoRequestBuilder(ElasticsearchClient client, NodesInfoAction action) {
        super(client, action, new NodesInfoRequest());
    }

    /**
     * Clears all info flags.
     */
    public NodesInfoRequestBuilder clear() {
        request.clear();
        return this;
    }

    /**
     * Sets to return all the data.
     */
    public NodesInfoRequestBuilder all() {
        request.all();
        return this;
    }

    /**
     * Should the node settings be returned.
     */
    public NodesInfoRequestBuilder setSettings(boolean settings) {
        request.settings(settings);
        return this;
    }

    /**
     * Should the node OS info be returned.
     */
    public NodesInfoRequestBuilder setOs(boolean os) {
        request.os(os);
        return this;
    }

    /**
     * Should the node OS process be returned.
     */
    public NodesInfoRequestBuilder setProcess(boolean process) {
        request.process(process);
        return this;
    }

    /**
     * Should the node JVM info be returned.
     */
    public NodesInfoRequestBuilder setJvm(boolean jvm) {
        request.jvm(jvm);
        return this;
    }

    /**
     * Should the node thread pool info be returned.
     */
    public NodesInfoRequestBuilder setThreadPool(boolean threadPool) {
        request.threadPool(threadPool);
        return this;
    }

    /**
     * Should the node Transport info be returned.
     */
    public NodesInfoRequestBuilder setTransport(boolean transport) {
        request.transport(transport);
        return this;
    }

    /**
     * Should the node HTTP info be returned.
     */
    public NodesInfoRequestBuilder setHttp(boolean http) {
        request.http(http);
        return this;
    }

    /**
     * Should the node plugins info be returned.
     */
    public NodesInfoRequestBuilder setPlugins(boolean plugins) {
        request().plugins(plugins);
        return this;
    }

    /**
     * Should the node ingest info be returned.
     */
    public NodesInfoRequestBuilder setIngest(boolean ingest) {
        request().ingest(ingest);
        return this;
    }
}


text:
#ifndef _SIRIKATA_INPUT_BINDING_EVENT_HPP_
#define _SIRIKATA_INPUT_BINDING_EVENT_HPP_

#include <sirikata/core/util/Platform.hpp>
#include <sirikata/proxyobject/Invokable.hpp>

namespace Sirikata {
namespace SimpleCamera {

class InputBindingEvent {
public:
    enum Modifier {
        NONE = 0,
        SHIFT = 1,
        CTRL = 2,
        ALT = 4,
        SUPER = 8
    };

    static InputBindingEvent Key(String button, Modifier mod);
    static InputBindingEvent MouseClick(int32 button);
    static InputBindingEvent MouseDrag(int32 button);
    static InputBindingEvent Axis(uint32 index);
    static InputBindingEvent Web(const String& wvname, const String& name);

    InputBindingEvent();
    InputBindingEvent(const InputBindingEvent& rhs);
    InputBindingEvent(const boost::any& evt);
    ~InputBindingEvent();

    bool valid() const;

    bool isKey() const;
    String keyButton() const;
    Modifier keyModifiers() const;
    bool keyPressed() const;
    bool keyReleased() const;

    bool isMouseClick() const;
    int32 mouseClickButton() const;

    bool isMouseDrag() const;
    int32 mouseDragButton() const;

    float mouseX() const;
    float mouseY() const;

    bool isAxis() const;
    uint32 axisIndex() const;
    float axisValue() const;

    bool isWeb() const;
    String webViewName() const;
    String webName() const;

    InputBindingEvent& operator=(const InputBindingEvent& rhs);

    String toString() const;
    static InputBindingEvent fromString(const String& asString);

    // Checks if the events "match", which is looser than being equal, allowing
    // a binding to pair an actual event with an event template for a handler.
    bool matches(const InputBindingEvent& rhs) const;

    bool operator<(const InputBindingEvent& rhs) const;
private:
    static String keyModifiersAsString(Modifier m);
    static Modifier keyModifiersFromString(const String& s);

    // Get a type tag to help with comparisons
    int32 typeTag() const;

    Invokable::Dict mEvent;
};

std::istream& operator>>(std::istream& is, Sirikata::SimpleCamera::InputBindingEvent& ibe);
std::ostream& operator<<(std::ostream& os, const Sirikata::SimpleCamera::InputBindingEvent& ibe);

} // namespace SimpleCamera
} // namespace Sirikata

#endif //_SIRIKATA_INPUT_BINDING_EVENT_HPP_


text:
package com.intellij.ide.impl;

import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.Nullable;

public class PsiElementDataValidator extends DataValidator<PsiElement> {
  @Override
  @Nullable
  public PsiElement findInvalid(final String dataId, PsiElement psiElement, final Object dataSource) {
    return psiElement.isValid() ? null : psiElement;
  }
}


text:
package vals

import (
	"testing"

	"src.elv.sh/pkg/tt"
)

func TestErrors(t *testing.T) {
	tt.Test(t, tt.Fn("error.Error", error.Error), tt.Table{
		Args(cannotIterate{"num"}).Rets("cannot iterate num"),
		Args(cannotIterateKeysOf{"num"}).Rets("cannot iterate keys of num"),
	})
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.iontorrent.utils;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JDialog;
import javax.swing.JPanel;
import org.apache.log4j.Logger;

/**
 *
 * @author Chantal Roth
 */
public class SimpleDialog extends JDialog {

    private static Logger log = Logger.getLogger(SimpleDialog.class);

    public SimpleDialog(String title, JPanel mainpanel, int width, int height) {
        setLocationRelativeTo(null);
        this.setUndecorated(false);

        JPanel main = new JPanel(new BorderLayout());
        super.setTitle(title);
        this.add(main);
        main.add(mainpanel, BorderLayout.CENTER);
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();

        int x = (int) Math.max(100, screen.getWidth() / 2 - 400);
        int y = (int) Math.max(100, screen.getHeight() / 2 - 200);
        this.setLocation(x, y);
        this.setVisible(true);
        this.setSize(width, height);
        this.toFront();
    }
     private void p(String msg) {
        log.info(msg);
    }
}


text:
require 'tempfile'
require_relative '../../spec_helper'
require_lib 'reek/examiner'
require_lib 'reek/report/report'

RSpec.describe Reek::Report::HTMLReport do
  let(:instance) { Reek::Report::HTMLReport.new }

  context 'with an empty source' do
    let(:examiner) { Reek::Examiner.new('') }

    before do
      instance.add_examiner examiner
    end

    it 'has the text 0 total warnings' do
      tempfile = Tempfile.new(['Reek::Report::HTMLReport.', '.html'])
      response = "HTML file saved\n"
      expect { instance.show(target_path: tempfile.path) }.
        to output(response).to_stdout
      expect(tempfile.read).to include('0 total warnings')
    end
  end
end


text:
import sys

if sys.version_info < (3, 7):
    from ._yaxes import YaxesValidator
    from ._xaxes import XaxesValidator
    from ._visible import VisibleValidator
    from ._unselected import UnselectedValidator
    from ._uirevision import UirevisionValidator
    from ._uid import UidValidator
    from ._textsrc import TextsrcValidator
    from ._text import TextValidator
    from ._stream import StreamValidator
    from ._showupperhalf import ShowupperhalfValidator
    from ._showlowerhalf import ShowlowerhalfValidator
    from ._showlegend import ShowlegendValidator
    from ._selectedpoints import SelectedpointsValidator
    from ._selected import SelectedValidator
    from ._opacity import OpacityValidator
    from ._name import NameValidator
    from ._metasrc import MetasrcValidator
    from ._meta import MetaValidator
    from ._marker import MarkerValidator
    from ._legendgroup import LegendgroupValidator
    from ._idssrc import IdssrcValidator
    from ._ids import IdsValidator
    from ._hovertextsrc import HovertextsrcValidator
    from ._hovertext import HovertextValidator
    from ._hovertemplatesrc import HovertemplatesrcValidator
    from ._hovertemplate import HovertemplateValidator
    from ._hoverlabel import HoverlabelValidator
    from ._hoverinfosrc import HoverinfosrcValidator
    from ._hoverinfo import HoverinfoValidator
    from ._dimensiondefaults import DimensiondefaultsValidator
    from ._dimensions import DimensionsValidator
    from ._diagonal import DiagonalValidator
    from ._customdatasrc import CustomdatasrcValidator
    from ._customdata import CustomdataValidator
else:
    from _plotly_utils.importers import relative_import

    __all__, __getattr__, __dir__ = relative_import(
        __name__,
        [],
        [
            "._yaxes.YaxesValidator",
            "._xaxes.XaxesValidator",
            "._visible.VisibleValidator",
            "._unselected.UnselectedValidator",
            "._uirevision.UirevisionValidator",
            "._uid.UidValidator",
            "._textsrc.TextsrcValidator",
            "._text.TextValidator",
            "._stream.StreamValidator",
            "._showupperhalf.ShowupperhalfValidator",
            "._showlowerhalf.ShowlowerhalfValidator",
            "._showlegend.ShowlegendValidator",
            "._selectedpoints.SelectedpointsValidator",
            "._selected.SelectedValidator",
            "._opacity.OpacityValidator",
            "._name.NameValidator",
            "._metasrc.MetasrcValidator",
            "._meta.MetaValidator",
            "._marker.MarkerValidator",
            "._legendgroup.LegendgroupValidator",
            "._idssrc.IdssrcValidator",
            "._ids.IdsValidator",
            "._hovertextsrc.HovertextsrcValidator",
            "._hovertext.HovertextValidator",
            "._hovertemplatesrc.HovertemplatesrcValidator",
            "._hovertemplate.HovertemplateValidator",
            "._hoverlabel.HoverlabelValidator",
            "._hoverinfosrc.HoverinfosrcValidator",
            "._hoverinfo.HoverinfoValidator",
            "._dimensiondefaults.DimensiondefaultsValidator",
            "._dimensions.DimensionsValidator",
            "._diagonal.DiagonalValidator",
            "._customdatasrc.CustomdatasrcValidator",
            "._customdata.CustomdataValidator",
        ],
    )