text:
//  (C) Copyright Gennadiy Rozental 2001-2007.
//  Distributed under the Boost Software License, Version 1.0.
//  (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org/libs/test for the library home page.
//
//  File        : $RCSfile$
//
//  Version     : $Revision: 41369 $
//
//  Description : as a central place for global configuration switches
// ***************************************************************************

#ifndef BOOST_TEST_CONFIG_HPP_071894GER
#define BOOST_TEST_CONFIG_HPP_071894GER

// Boost
#include <boost/config.hpp> // compilers workarounds
#include <boost/detail/workaround.hpp>

#if BOOST_WORKAROUND(__GNUC__, < 3) && !defined(__SGI_STL_PORT) && !defined(_STLPORT_VERSION)
#  define BOOST_CLASSIC_IOSTREAMS
#else
#  define BOOST_STANDARD_IOSTREAMS
#endif

//____________________________________________________________________________//

#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x570)) || \
    BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(600))     || \
    (defined __sgi && BOOST_WORKAROUND(_COMPILER_VERSION, BOOST_TESTED_AT(730)))
#  define BOOST_TEST_SHIFTED_LINE
#endif

//____________________________________________________________________________//

#if defined(BOOST_MSVC) || (defined(__BORLANDC__) && !defined(BOOST_DISABLE_WIN32))
#  define BOOST_TEST_CALL_DECL __cdecl
#else
#  define BOOST_TEST_CALL_DECL /**/
#endif

//____________________________________________________________________________//

#if defined(BOOST_HAS_SIGACTION)
#  define BOOST_TEST_SUPPORT_TIMEOUT
#endif

//____________________________________________________________________________//

#if BOOST_WORKAROUND(__BORLANDC__, <= 0x570)           || \
    BOOST_WORKAROUND( __COMO__, <= 0x433 )             || \
    BOOST_WORKAROUND( __INTEL_COMPILER, <= 800 )       || \
    BOOST_WORKAROUND(__GNUC__, < 3)                    || \
    defined(__sgi) && _COMPILER_VERSION <= 730         || \
    BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(600)) || \
    defined(__DECCXX) || \
    defined(__DMC__)
#  define BOOST_TEST_NO_PROTECTED_USING
#endif

//____________________________________________________________________________//

#if defined(__GNUC__) || BOOST_WORKAROUND(BOOST_MSVC, == 1400)
#define BOOST_TEST_PROTECTED_VIRTUAL virtual
#else
#define BOOST_TEST_PROTECTED_VIRTUAL
#endif

//____________________________________________________________________________//

#if defined(BOOST_ALL_DYN_LINK) && !defined(BOOST_TEST_DYN_LINK)
#  define BOOST_TEST_DYN_LINK
#endif

#if defined(BOOST_TEST_INCLUDED)
#  undef BOOST_TEST_DYN_LINK
#endif

#if defined(BOOST_TEST_DYN_LINK)
#  define BOOST_TEST_ALTERNATIVE_INIT_API

#  if defined(BOOST_HAS_DECLSPEC) && defined(BOOST_TEST_DYN_LINK)
#    ifdef BOOST_TEST_SOURCE
#      define BOOST_TEST_DECL __declspec(dllexport)
#    else
#      define BOOST_TEST_DECL __declspec(dllimport)
#    endif  // BOOST_TEST_SOURCE
#  endif  // BOOST_HAS_DECLSPEC
#endif  // BOOST_TEST_DYN_LINK

#ifndef BOOST_TEST_DECL
#  define BOOST_TEST_DECL
#endif

#if !defined(BOOST_TEST_MAIN) && defined(BOOST_AUTO_TEST_MAIN)
#define BOOST_TEST_MAIN BOOST_AUTO_TEST_MAIN
#endif

#if !defined(BOOST_TEST_MAIN) && defined(BOOST_TEST_MODULE)
#define BOOST_TEST_MAIN BOOST_TEST_MODULE
#endif

#endif // BOOST_TEST_CONFIG_HPP_071894GER


text:
I had seen The Boy Friend being performed by Edinburgh Music Theatre a couple of years before, and
thought that it would be fun to do.  But when I got the part of Bobby, and realised that I was playing
opposite Amanda, it gave me pause for thought.  She is so good on stage and such a good dancer, I wondered if
it would ever be possible to dance beside her and not appear to be out of my depth!

I don't know whether I managed it, but I certainly had a great time trying.  The rehearsals and the show itself
all went smoothly.  And it was lovely to be working with Dorothy again, who had directed me in Carousel
way back in... Ulp!... 1991!

As if that wasn't enough to make me feel old, I also got my twenty-five year long service award from NODA,
presented to my by Jim Allardyce!  It was presented to me on stage after the show - lovely!  But then again,
I was being given my twenty-five year award in a show where I was playing a seventeen year old.  Something
wrong there, surely!

redpajama_set_name: RedPajamaGithub


text:
using MySqlConnector.Protocol;
using MySqlConnector.Protocol.Serialization;
using MySqlConnector.Utilities;

namespace MySqlConnector.Core;

internal sealed class StatementPreparer
{
	public StatementPreparerOptions Options { get; }

	public StatementPreparer(string commandText, MySqlParameterCollection? parameters, StatementPreparerOptions options)
	{
		m_commandText = commandText;
		m_parameters = parameters;
		Options = options;
	}

	public ParsedStatements SplitStatements()
	{
		var statements = new List<ParsedStatement>();
		var statementStartEndIndexes = new List<int>();
		var writer = new ByteBufferWriter(m_commandText.Length + 1);
		var parser = new PreparedCommandSqlParser(this, statements, statementStartEndIndexes, writer);
		parser.Parse(m_commandText);
		for (var i = 0; i < statements.Count; i++)
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP3_1_OR_GREATER
			statements[i].StatementBytes = writer.ArraySegment[statementStartEndIndexes[i * 2]..statementStartEndIndexes[i * 2 + 1]];
#else
			statements[i].StatementBytes = writer.ArraySegment.Slice(statementStartEndIndexes[i * 2], statementStartEndIndexes[i * 2 + 1] - statementStartEndIndexes[i * 2]);
#endif
		return new ParsedStatements(statements, writer.ToPayloadData());
	}

	public bool ParseAndBindParameters(ByteBufferWriter writer)
	{
		if (!string.IsNullOrWhiteSpace(m_commandText))
		{
			var parser = new ParameterSqlParser(this, writer);
			parser.Parse(m_commandText);
			return parser.IsComplete;
		}
		return true;
	}

	private int GetParameterIndex(string name)
	{
		var index = m_parameters?.NormalizedIndexOf(name) ?? -1;
		if (index == -1 && (Options & StatementPreparerOptions.AllowUserVariables) == 0)
			throw new MySqlException("Parameter '{0}' must be defined. To use this as a variable, set 'Allow User Variables=true' in the connection string.".FormatInvariant(name));
		return index;
	}

	private MySqlParameter GetInputParameter(int index)
	{
		if (index >= (m_parameters?.Count ?? 0))
			throw new MySqlException("Parameter index {0} is invalid when only {1} parameter{2} defined.".FormatInvariant(index, m_parameters?.Count ?? 0, m_parameters?.Count == 1 ? " is" : "s are"));
		var parameter = m_parameters![index];
		if (parameter.Direction != ParameterDirection.Input && (Options & StatementPreparerOptions.AllowOutputParameters) == 0)
			throw new MySqlException("Only ParameterDirection.Input is supported when CommandType is Text (parameter name: {0})".FormatInvariant(parameter.ParameterName));
		return parameter;
	}

	private sealed class ParameterSqlParser : SqlParser
	{
		public ParameterSqlParser(StatementPreparer preparer, ByteBufferWriter writer)
			: base(preparer)
		{
			m_writer = writer;
		}

		public bool IsComplete { get; private set; }

		protected override void OnNamedParameter(int index, int length)
		{
			var parameterIndex = Preparer.GetParameterIndex(Preparer.m_commandText.Substring(index, length));
			if (parameterIndex != -1)
				DoAppendParameter(parameterIndex, index, length);
		}

		protected override void OnPositionalParameter(int index)
		{
			DoAppendParameter(m_currentParameterIndex, index, 1);
			m_currentParameterIndex++;
		}

		private void DoAppendParameter(int parameterIndex, int textIndex, int textLength)
		{
			m_writer.Write(Preparer.m_commandText, m_lastIndex, textIndex - m_lastIndex);
			var parameter = Preparer.GetInputParameter(parameterIndex);
			parameter.AppendSqlString(m_writer, Preparer.Options);
			m_lastIndex = textIndex + textLength;
		}

		protected override void OnParsed(FinalParseStates states)
		{
			m_writer.Write(Preparer.m_commandText, m_lastIndex, Preparer.m_commandText.Length - m_lastIndex);
			if ((states & FinalParseStates.NeedsNewline) == FinalParseStates.NeedsNewline)
				m_writer.Write((byte) '\n');
			if ((states & FinalParseStates.NeedsSemicolon) == FinalParseStates.NeedsSemicolon && (Preparer.Options & StatementPreparerOptions.AppendSemicolon) == StatementPreparerOptions.AppendSemicolon)
				m_writer.Write((byte) ';');
			IsComplete = (states & FinalParseStates.Complete) == FinalParseStates.Complete;
		}

		private readonly ByteBufferWriter m_writer;
		private int m_currentParameterIndex;
		private int m_lastIndex;
	}

	private sealed class PreparedCommandSqlParser : SqlParser
	{
		public PreparedCommandSqlParser(StatementPreparer preparer, List<ParsedStatement> statements, List<int> statementStartEndIndexes, ByteBufferWriter writer)
			: base(preparer)
		{
			m_statements = statements;
			m_statementStartEndIndexes = statementStartEndIndexes;
			m_writer = writer;
		}

		protected override void OnStatementBegin(int index)
		{
			m_statements.Add(new ParsedStatement());
			m_statementStartEndIndexes.Add(m_writer.Position);
			m_writer.Write((byte) CommandKind.StatementPrepare);
			m_lastIndex = index;
		}

		protected override void OnNamedParameter(int index, int length)
		{
			var parameterName = Preparer.m_commandText.Substring(index, length);
			DoAppendParameter(parameterName, -1, index, length);
		}

		protected override void OnPositionalParameter(int index)
		{
			DoAppendParameter(null, m_currentParameterIndex, index, 1);
			m_currentParameterIndex++;
		}

		private void DoAppendParameter(string? parameterName, int parameterIndex, int textIndex, int textLength)
		{
			// write all SQL up to the parameter
			m_writer.Write(Preparer.m_commandText, m_lastIndex, textIndex - m_lastIndex);
			m_lastIndex = textIndex + textLength;

			// replace the parameter with a ? placeholder
			m_writer.Write((byte) '?');

			// store the parameter index
			m_statements[m_statements.Count - 1].ParameterNames.Add(parameterName);
			m_statements[m_statements.Count - 1].ParameterIndexes.Add(parameterIndex);
		}

		protected override void OnStatementEnd(int index)
		{
			m_writer.Write(Preparer.m_commandText, m_lastIndex, index - m_lastIndex);
			m_lastIndex = index;
			m_statementStartEndIndexes.Add(m_writer.Position);
		}

		private readonly List<ParsedStatement> m_statements;
		private readonly List<int> m_statementStartEndIndexes;
		private readonly ByteBufferWriter m_writer;
		private int m_currentParameterIndex;
		private int m_lastIndex;
	}

	private readonly string m_commandText;
	private readonly MySqlParameterCollection? m_parameters;
}


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Coding with Data</title>
    <link>/</link>
    <description>Recent content on Coding with Data</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <lastBuildDate>Sun, 19 Apr 2020 23:15:14 -0500</lastBuildDate>

	<atom:link href="/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>UFC Stats: Understanding striking performance</title>
      <link>/blog/2020/2020-04-15-striking/</link>
      <pubDate>Sun, 19 Apr 2020 23:15:14 -0500</pubDate>

      <guid>/blog/2020/2020-04-15-striking/</guid>
      <description>A brief history of the Ultimate Fighter The first UFC event was held over a quarter century ago on November 12th 1993 in Denver, CO. The concept was to pit different martial arts and fighting styles against each other to see which one is truly superior. The event was the brainchild of Rorion Gracie, member of the legendary Brazilian jiu-jitsu (BJJ) family. In the late eighties and early nineties Rorion produced and appeared on several VHS tapes demonstrating the power of jiu jitsu over judo, karate, sambo and other martial arts.</description>
    </item>

    <item>
      <title>No frills data warehousing with dbt</title>
      <link>/blog/2019/2019-03-05-dbt/</link>
      <pubDate>Tue, 05 Mar 2019 23:15:14 -0500</pubDate>

      <guid>/blog/2019/2019-03-05-dbt/</guid>
      <description>pre code, pre, code { white-space: pre !important; overflow-x: scroll !important; word-break: keep-all !important; word-wrap: initial !important; }  ETL with ease Analytics databases more often than not contain a multitude of tables and views, depicting facts, dimensions or aggregate statistics. Responsibility for the underlying data pipelines traditionally belonged to Data Architects or Data Engineers. However modern tools like dbt are lowering the barrier to doing ETL.
To use dbt, you only need to be familiar with SQL.</description>
    </item>

    <item>
      <title>Serverless data ingestion into BigQuery</title>
      <link>/blog/2019/2019-02-10-serverless/</link>
      <pubDate>Thu, 07 Feb 2019 23:15:14 -0500</pubDate>

      <guid>/blog/2019/2019-02-10-serverless/</guid>
      <description>pre code, pre, code { white-space: pre !important; overflow-x: scroll !important; word-break: keep-all !important; word-wrap: initial !important; }  Least effort required For a recent project I needed to find an efficient way to extract data from API's and load the response into a database residing in the cloud. It's a fairly common use case, as most online platforms expose data via callable API's. My personal goal was to introduce as little tooling and code as possible.</description>
    </item>

    <item>
      <title>Transfer Learning with Tensornets and Dataset API</title>
      <link>/blog/2019/2019-01-14-tensornets/</link>
      <pubDate>Mon, 14 Jan 2019 23:15:14 -0500</pubDate>

      <guid>/blog/2019/2019-01-14-tensornets/</guid>
      <description>pre code, pre, code { white-space: pre !important; overflow-x: scroll !important; word-break: keep-all !important; word-wrap: initial !important; }  They grow up so fast It's been at least a year since I last dabbled in TensorFlow, and the ecosystem seems to have grown a lot. The general trend is towards higher-level abstractions for building models, defining data pipelines or serving predictions. Then there is also the relentless community-driven development, spawning many useful extensions to the official library.</description>
    </item>

    <item>
      <title>Lightweight streaming analytics with NATS</title>
      <link>/blog/2018/2018-09-17-nats-shiny/</link>
      <pubDate>Tue, 02 Oct 2018 22:13:14 -0500</pubDate>

      <guid>/blog/2018/2018-09-17-nats-shiny/</guid>
      <description>pre code, pre, code { white-space: pre !important; overflow-x: scroll !important; word-break: keep-all !important; word-wrap: initial !important; } library(knitr) eng_go Go in the fast lane Fast data is the new big data. But how difficult is it really to set up a complete streaming analytics solution from the ground up? It turns out not that hard, not if you are using NATS Streaming. Developed in Go
 "…NATS Streaming is an extremely performant, lightweight reliable streaming platform built on NATS.</description>
    </item>

    <item>
      <title>Parallelizing R code on Kubernetes</title>
      <link>/blog/2018/2018-08-06-kubernetes-parallel/</link>
      <pubDate>Tue, 07 Aug 2018 22:13:14 -0500</pubDate>

      <guid>/blog/2018/2018-08-06-kubernetes-parallel/</guid>
      <description>pre code, pre, code { white-space: pre !important; overflow-x: scroll !important; word-break: keep-all !important; word-wrap: initial !important; }  Kubernetes who? The hype around kubernetes is real, but likely also justified. Kubernetes is an open-source tool that facilitates deployment of jobs and services onto computer clusters. It provides different patterns for different type of workloads, be it API servers, databases or running batch jobs. Not only makes kubernetes running workloads and services easy, it also keeps them running.</description>
    </item>

    <item>
      <title>Interpretable GDPR Classifiers</title>
      <link>/blog/2018/2018-07-19_gdpr/</link>
      <pubDate>Tue, 19 Jun 2018 22:13:14 -0500</pubDate>

      <guid>/blog/2018/2018-07-19_gdpr/</guid>
      <description>pre code, pre, code { white-space: pre !important; overflow-x: scroll !important; word-break: keep-all !important; word-wrap: initial !important; }  We have updated our privacy policies… Whether internet companies are now compliant with GDPR is hard to say, but they sure left updating their privacy policies to the last minute. What happened in the last days of May was the greatest corporate email tsunami since Y2K. I hardly read the updated policies, or remember what the old ones looked like.</description>
    </item>

    <item>
      <title>Dockerized Shiny App development</title>
      <link>/blog/2018/2018-01-16-shiny_docker/</link>
      <pubDate>Tue, 16 Jan 2018 22:13:14 -0500</pubDate>

      <guid>/blog/2018/2018-01-16-shiny_docker/</guid>
      <description>pre code, pre, code { white-space: pre !important; overflow-x: scroll !important; word-break: keep-all !important; word-wrap: initial !important; }  Getting on the Docker (container) ship Containers are everywhere, including the realms of data science. You can think of them as small self-contained environments, encapsulating an application and its dependencies. If that sounds a lot like a virtual machine, you are not entirely wrong. But unlike VM's, containers run on the host system's kernel and the processes inside can only see and access their immediate surroundings.</description>
    </item>

    <item>
      <title>An animated neuRal net implementation</title>
      <link>/blog/2017/2017-11-11-animated_net/</link>
      <pubDate>Thu, 09 Nov 2017 21:00:30 -0500</pubDate>

      <guid>/blog/2017/2017-11-11-animated_net/</guid>
      <description>pre code, pre, code { white-space: pre !important; overflow-x: scroll !important; word-break: keep-all !important; word-wrap: initial !important; }  Yet another neural net from scratch tutorial? One would be forgiven to think that artificial neural networks are the newest and shiniest of modern data science. On the contrary, the main concepts have been around for decades. But it is recent progress in computational resources and the availability of massive datasets that these learning architectures revealed their true powers.</description>
    </item>

    <item>
      <title>A tidy text analysis of Rick and Morty</title>
      <link>/blog/2017/2017-10-07-tidyrick/</link>
      <pubDate>Sat, 07 Oct 2017 23:15:14 -0500</pubDate>

      <guid>/blog/2017/2017-10-07-tidyrick/</guid>
      <description>pre code, pre, code { white-space: pre !important; overflow-x: scroll !important; word-break: keep-all !important; word-wrap: initial !important; }  Adventures in the multiverse For those unfamiliar with the show, Rick and Morty is an animated series about the interuniversal exploits of a half-drunk mad scientist Rick, and his daft grandson Morty. Living under one roof with his daughter, Rick constantly drags his grandson Morty along for adventures into unusual worlds inhabited by surreal creatures.</description>
    </item>

    <item>
      <title>Self-learning Hue Lights</title>
      <link>/blog/2017/2017-05-14-hue/</link>
      <pubDate>Wed, 30 Aug 2017 23:15:14 -0500</pubDate>

      <guid>/blog/2017/2017-05-14-hue/</guid>
      <description>pre code, pre, code { white-space: pre !important; overflow-x: scroll !important; word-break: keep-all !important; word-wrap: initial !important; }  The rise of the API Rich API interfaces are one of the main ingredients of today's smart devices. They are by definition built for interconnectivity and there is an active community of developers creating apps as microservices on top of them. Philips Hue is no exception with it's wide variety of apps available to users.</description>
    </item>

    <item>
      <title>Creating a Spotify Playlist using Luigi</title>
      <link>/blog/2017/2017-07-22-spotifyluigi/</link>
      <pubDate>Sat, 22 Jul 2017 21:13:14 -0500</pubDate>

      <guid>/blog/2017/2017-07-22-spotifyluigi/</guid>
      <description>pre code, pre, code { white-space: pre !important; overflow-x: scroll !important; word-break: keep-all !important; word-wrap: initial !important; }  Introduction In the previous post, I shared an analysis of my Spotify listening history using R. In this post, I will discuss what came before having the data: collecting, cleaning and saving it. As the title suggest, we will even go a step further and automate the creation of a weekly top 10 playlist in Spotify using the very same dataset.</description>
    </item>

    <item>
      <title>Analyzing My Spotify Listening History</title>
      <link>/blog/2017/2017-06-02-spotifyr/</link>
      <pubDate>Sun, 02 Jul 2017 21:13:14 -0500</pubDate>

      <guid>/blog/2017/2017-06-02-spotifyr/</guid>
      <description>pre code, pre, code { white-space: pre !important; overflow-x: scroll !important; word-break: keep-all !important; word-wrap: initial !important; }  A new endpoint Following an avalanche of +1 comments on the GitHub issue requesting access to a user's play history, on March 1st Spotify released a new endpoint to their Web API that allows anyone with a Spotify account to pull data on his or her most recently played tracks. To access it, you need go through the Authorization Code Flow, where you get keys and tokens needed for making calls to the API.</description>
    </item>

    <item>
      <title>Starting a blog(down)</title>
      <link>/blog/2017/2017-05-14-blogdown/</link>
      <pubDate>Sun, 14 May 2017 21:13:14 -0500</pubDate>

      <guid>/blog/2017/2017-05-14-blogdown/</guid>
      <description>Starting an analytics blog Having learned lots from the open source community over the past years - from blogs and videos to attending meetups and awesome conferences - I have decided to start a blog myself, and share some of the things I find interesting. I expect most of the posts to be R specific, because that's what I am most comfortable with. However I do enjoy fiddling with other technologies such as Python or Spark, so watch out!</description>
    </item>

    <item>
      <title>About</title>
      <link>/about/about/</link>
      <pubDate>Thu, 05 May 2016 21:48:51 -0700</pubDate>

      <guid>/about/about/</guid>
      <description>My name is Tamas and I am a currently working as a Senior Data Analyst at komoot. I was born in Budapest, studied in Leuven and St. Andrews, and have worked in Montreal and Amsterdam.
My main area of expertise is digital analytics, however I have worked on projects in a variety of industries such as online media, e-commerce, travel and banking. I love solving business problems with data, discovering new insights and building scalable solutions.</description>
    </item>

    <item>
      <title>Consulting</title>
      <link>/consulting/consulting/</link>
      <pubDate>Mon, 01 Jan 0001 00:00:00 +0000</pubDate>

      <guid>/consulting/consulting/</guid>
      <description>I consult both small and large business on all aspects of data analytics, including:
 Creating robust data pipelines for data of all sizes. Building interactive dashboards for all audiences. Implementing principled A/B testing workflows. Developing and analyzing models to solve business problems. Integrating predictive analytics into production systems. Communicating insights and results to stakeholders.  Feel free to contact me for any questions!</description>
    </item>

    <item>
      <title>Speaking</title>
      <link>/speaking/speaking/</link>
      <pubDate>Mon, 01 Jan 0001 00:00:00 +0000</pubDate>

      <guid>/speaking/speaking/</guid>
      <description> I regularly speak at conferences and meetups about analytics workflows, new technologies in the data space and more. If you're interested in having me speak at your event, feel free to send me an email!
Selected Talks  Using Docker containers in R amsteRdam meetup 2018. Robust Data Pipelines with drake and Docker eRum 2018. Building Data Products at Home: Self-learning Hue Lights Budapest BI Conf 2017.  </description>
    </item>

  </channel>
</rss>


text:
package org.elasticsearch.search;

import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.CharsRefBuilder;
import org.elasticsearch.common.CheckedBiConsumer;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.LoggingDeprecationHandler;
import org.elasticsearch.core.RestApiVersion;
import org.elasticsearch.index.query.AbstractQueryBuilder;
import org.elasticsearch.index.query.CommonTermsQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryRewriteContext;
import org.elasticsearch.index.query.SearchExecutionContext;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.TypeQueryV7Builder;
import org.elasticsearch.index.query.functionscore.GaussDecayFunctionBuilder;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationReduceContext;
import org.elasticsearch.search.aggregations.AggregatorFactories.Builder;
import org.elasticsearch.search.aggregations.AggregatorFactory;
import org.elasticsearch.search.aggregations.BaseAggregationBuilder;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.terms.heuristic.ChiSquare;
import org.elasticsearch.search.aggregations.pipeline.AbstractPipelineAggregationBuilder;
import org.elasticsearch.search.aggregations.pipeline.DerivativePipelineAggregationBuilder;
import org.elasticsearch.search.aggregations.pipeline.InternalDerivative;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator;
import org.elasticsearch.search.aggregations.support.AggregationContext;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.search.aggregations.support.ValuesSourceAggregationBuilder;
import org.elasticsearch.search.aggregations.support.ValuesSourceAggregatorFactory;
import org.elasticsearch.search.aggregations.support.ValuesSourceConfig;
import org.elasticsearch.search.aggregations.support.ValuesSourceRegistry;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.search.fetch.FetchSubPhase;
import org.elasticsearch.search.fetch.subphase.ExplainPhase;
import org.elasticsearch.search.fetch.subphase.highlight.CustomHighlighter;
import org.elasticsearch.search.fetch.subphase.highlight.FastVectorHighlighter;
import org.elasticsearch.search.fetch.subphase.highlight.Highlighter;
import org.elasticsearch.search.fetch.subphase.highlight.PlainHighlighter;
import org.elasticsearch.search.fetch.subphase.highlight.UnifiedHighlighter;
import org.elasticsearch.search.internal.ShardSearchRequest;
import org.elasticsearch.search.rescore.QueryRescorerBuilder;
import org.elasticsearch.search.rescore.RescoreContext;
import org.elasticsearch.search.rescore.RescorerBuilder;
import org.elasticsearch.search.suggest.Suggest.Suggestion;
import org.elasticsearch.search.suggest.Suggest.Suggestion.Entry;
import org.elasticsearch.search.suggest.Suggest.Suggestion.Entry.Option;
import org.elasticsearch.search.suggest.Suggester;
import org.elasticsearch.search.suggest.SuggestionBuilder;
import org.elasticsearch.search.suggest.SuggestionSearchContext;
import org.elasticsearch.search.suggest.SuggestionSearchContext.SuggestionContext;
import org.elasticsearch.search.suggest.term.TermSuggestion;
import org.elasticsearch.search.suggest.term.TermSuggestionBuilder;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xcontent.NamedXContentRegistry;
import org.elasticsearch.xcontent.ParseField;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentParser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.nullValue;

public class SearchModuleTests extends ESTestCase {

    public void testDoubleRegister() {
        SearchPlugin registersDupeHighlighter = new SearchPlugin() {
            @Override
            public Map<String, Highlighter> getHighlighters() {
                return singletonMap("plain", new PlainHighlighter());
            }
        };
        expectThrows(IllegalArgumentException.class, registryForPlugin(registersDupeHighlighter));

        SearchPlugin registersDupeSuggester = new SearchPlugin() {
            @Override
            public List<SearchPlugin.SuggesterSpec<?>> getSuggesters() {
                return singletonList(
                    new SuggesterSpec<>(
                        TermSuggestionBuilder.SUGGESTION_NAME,
                        TermSuggestionBuilder::new,
                        TermSuggestionBuilder::fromXContent,
                        TermSuggestion::new
                    )
                );
            }
        };
        expectThrows(IllegalArgumentException.class, registryForPlugin(registersDupeSuggester));

        SearchPlugin registersDupeScoreFunction = new SearchPlugin() {
            @Override
            public List<ScoreFunctionSpec<?>> getScoreFunctions() {
                return singletonList(
                    new ScoreFunctionSpec<>(
                        GaussDecayFunctionBuilder.NAME,
                        GaussDecayFunctionBuilder::new,
                        GaussDecayFunctionBuilder.PARSER
                    )
                );
            }
        };
        expectThrows(IllegalArgumentException.class, registryForPlugin(registersDupeScoreFunction));

        SearchPlugin registersDupeSignificanceHeuristic = new SearchPlugin() {
            @Override
            public List<SignificanceHeuristicSpec<?>> getSignificanceHeuristics() {
                return singletonList(new SignificanceHeuristicSpec<>(ChiSquare.NAME, ChiSquare::new, ChiSquare.PARSER));
            }
        };
        expectThrows(IllegalArgumentException.class, registryForPlugin(registersDupeSignificanceHeuristic));

        SearchPlugin registersDupeFetchSubPhase = new SearchPlugin() {
            @Override
            public List<FetchSubPhase> getFetchSubPhases(FetchPhaseConstructionContext context) {
                return singletonList(new ExplainPhase());
            }
        };
        expectThrows(IllegalArgumentException.class, registryForPlugin(registersDupeFetchSubPhase));

        SearchPlugin registersDupeQuery = new SearchPlugin() {
            @Override
            public List<SearchPlugin.QuerySpec<?>> getQueries() {
                return singletonList(new QuerySpec<>(TermQueryBuilder.NAME, TermQueryBuilder::new, TermQueryBuilder::fromXContent));
            }
        };
        expectThrows(IllegalArgumentException.class, registryForPlugin(registersDupeQuery));

        SearchPlugin registersDupeAggregation = new SearchPlugin() {
            @Override
            public List<AggregationSpec> getAggregations() {
                return singletonList(
                    new AggregationSpec(TermsAggregationBuilder.NAME, TermsAggregationBuilder::new, TermsAggregationBuilder.PARSER)
                );
            }
        };
        expectThrows(IllegalArgumentException.class, registryForPlugin(registersDupeAggregation));

        SearchPlugin registersDupePipelineAggregation = new SearchPlugin() {
            @Override
            public List<PipelineAggregationSpec> getPipelineAggregations() {
                return singletonList(
                    new PipelineAggregationSpec(
                        DerivativePipelineAggregationBuilder.NAME,
                        DerivativePipelineAggregationBuilder::new,
                        DerivativePipelineAggregationBuilder::parse
                    ).addResultReader(InternalDerivative::new)
                );
            }
        };
        expectThrows(IllegalArgumentException.class, registryForPlugin(registersDupePipelineAggregation));

        SearchPlugin registersDupeRescorer = new SearchPlugin() {
            @Override
            public List<RescorerSpec<?>> getRescorers() {
                return singletonList(
                    new RescorerSpec<>(QueryRescorerBuilder.NAME, QueryRescorerBuilder::new, QueryRescorerBuilder::fromXContent)
                );
            }
        };
        expectThrows(IllegalArgumentException.class, registryForPlugin(registersDupeRescorer));
    }

    private ThrowingRunnable registryForPlugin(SearchPlugin plugin) {
        return () -> new NamedXContentRegistry(new SearchModule(Settings.EMPTY, singletonList(plugin)).getNamedXContents());
    }

    public void testRegisterSuggester() {
        SearchModule module = new SearchModule(Settings.EMPTY, singletonList(new SearchPlugin() {
            @Override
            public List<SuggesterSpec<?>> getSuggesters() {
                return singletonList(
                    new SuggesterSpec<>(
                        TestSuggestionBuilder.SUGGESTION_NAME,
                        TestSuggestionBuilder::new,
                        TestSuggestionBuilder::fromXContent,
                        TestSuggestion::new
                    )
                );
            }
        }));

        assertEquals(
            1,
            module.getNamedXContents()
                .stream()
                .filter(e -> e.categoryClass.equals(SuggestionBuilder.class) && e.name.match("term", LoggingDeprecationHandler.INSTANCE))
                .count()
        );
        assertEquals(
            1,
            module.getNamedXContents()
                .stream()
                .filter(e -> e.categoryClass.equals(SuggestionBuilder.class) && e.name.match("phrase", LoggingDeprecationHandler.INSTANCE))
                .count()
        );
        assertEquals(
            1,
            module.getNamedXContents()
                .stream()
                .filter(
                    e -> e.categoryClass.equals(SuggestionBuilder.class) && e.name.match("completion", LoggingDeprecationHandler.INSTANCE)
                )
                .count()
        );
        assertEquals(
            1,
            module.getNamedXContents()
                .stream()
                .filter(e -> e.categoryClass.equals(SuggestionBuilder.class) && e.name.match("test", LoggingDeprecationHandler.INSTANCE))
                .count()
        );

        assertEquals(
            1,
            module.getNamedWriteables()
                .stream()
                .filter(e -> e.categoryClass.equals(SuggestionBuilder.class) && e.name.equals("term"))
                .count()
        );
        assertEquals(
            1,
            module.getNamedWriteables()
                .stream()
                .filter(e -> e.categoryClass.equals(SuggestionBuilder.class) && e.name.equals("phrase"))
                .count()
        );
        assertEquals(
            1,
            module.getNamedWriteables()
                .stream()
                .filter(e -> e.categoryClass.equals(SuggestionBuilder.class) && e.name.equals("completion"))
                .count()
        );
        assertEquals(
            1,
            module.getNamedWriteables()
                .stream()
                .filter(e -> e.categoryClass.equals(SuggestionBuilder.class) && e.name.equals("test"))
                .count()
        );

        assertEquals(
            1,
            module.getNamedWriteables().stream().filter(e -> e.categoryClass.equals(Suggestion.class) && e.name.equals("term")).count()
        );
        assertEquals(
            1,
            module.getNamedWriteables().stream().filter(e -> e.categoryClass.equals(Suggestion.class) && e.name.equals("phrase")).count()
        );
        assertEquals(
            1,
            module.getNamedWriteables()
                .stream()
                .filter(e -> e.categoryClass.equals(Suggestion.class) && e.name.equals("completion"))
                .count()
        );
        assertEquals(
            1,
            module.getNamedWriteables().stream().filter(e -> e.categoryClass.equals(Suggestion.class) && e.name.equals("test")).count()
        );
    }

    public void testRegisterHighlighter() {
        CustomHighlighter customHighlighter = new CustomHighlighter();
        SearchModule module = new SearchModule(Settings.EMPTY, singletonList(new SearchPlugin() {
            @Override
            public Map<String, Highlighter> getHighlighters() {
                return singletonMap("custom", customHighlighter);
            }
        }));

        Map<String, Highlighter> highlighters = module.getHighlighters();
        assertEquals(FastVectorHighlighter.class, highlighters.get("fvh").getClass());
        assertEquals(PlainHighlighter.class, highlighters.get("plain").getClass());
        assertEquals(UnifiedHighlighter.class, highlighters.get("unified").getClass());
        assertSame(highlighters.get("custom"), customHighlighter);
    }

    public void testRegisteredQueries() {
        List<String> allSupportedQueries = new ArrayList<>();
        Collections.addAll(allSupportedQueries, NON_DEPRECATED_QUERIES);
        Collections.addAll(allSupportedQueries, DEPRECATED_QUERIES);
        Collections.addAll(allSupportedQueries, REST_COMPATIBLE_QUERIES);

        SearchModule module = new SearchModule(Settings.EMPTY, emptyList());

        Set<String> registeredNonDeprecated = module.getNamedXContents()
            .stream()
            .filter(e -> e.categoryClass.equals(QueryBuilder.class))
            .filter(e -> e.name.getAllReplacedWith() == null)
            .filter(e -> RestApiVersion.current().matches(e.restApiCompatibility))
            .map(e -> e.name.getPreferredName())
            .collect(toSet());
        Set<String> registeredAll = module.getNamedXContents()
            .stream()
            .filter(e -> e.categoryClass.equals(QueryBuilder.class))
            .flatMap(e -> Arrays.stream(e.name.getAllNamesIncludedDeprecated()))
            .collect(toSet());

        assertThat(registeredNonDeprecated, containsInAnyOrder(NON_DEPRECATED_QUERIES));
        assertThat(registeredAll, containsInAnyOrder(allSupportedQueries.toArray(new String[0])));
    }

    public void testRegisterAggregation() {
        SearchModule module = new SearchModule(Settings.EMPTY, singletonList(new SearchPlugin() {
            @Override
            public List<AggregationSpec> getAggregations() {
                return singletonList(new AggregationSpec("test", TestAggregationBuilder::new, TestAggregationBuilder::fromXContent));
            }
        }));

        assertThat(
            module.getNamedXContents()
                .stream()
                .filter(
                    entry -> entry.categoryClass.equals(BaseAggregationBuilder.class)
                        && entry.name.match("test", LoggingDeprecationHandler.INSTANCE)
                )
                .collect(toList()),
            hasSize(1)
        );
    }

    public void testRegisterPipelineAggregation() {
        SearchModule module = new SearchModule(Settings.EMPTY, singletonList(new SearchPlugin() {
            @Override
            public List<PipelineAggregationSpec> getPipelineAggregations() {
                return singletonList(
                    new PipelineAggregationSpec("test", TestPipelineAggregationBuilder::new, TestPipelineAggregationBuilder::fromXContent)
                );
            }
        }));

        assertThat(
            module.getNamedXContents()
                .stream()
                .filter(
                    entry -> entry.categoryClass.equals(BaseAggregationBuilder.class)
                        && entry.name.match("test", LoggingDeprecationHandler.INSTANCE)
                )
                .collect(toList()),
            hasSize(1)
        );
    }

    public void testRegisterRescorer() {
        SearchModule module = new SearchModule(Settings.EMPTY, singletonList(new SearchPlugin() {
            @Override
            public List<RescorerSpec<?>> getRescorers() {
                return singletonList(new RescorerSpec<>("test", TestRescorerBuilder::new, TestRescorerBuilder::fromXContent));
            }
        }));
        assertThat(
            module.getNamedXContents()
                .stream()
                .filter(
                    entry -> entry.categoryClass.equals(RescorerBuilder.class)
                        && entry.name.match("test", LoggingDeprecationHandler.INSTANCE)
                )
                .collect(toList()),
            hasSize(1)
        );
    }

    public void testRegisterNullRequestCacheKeyDifferentiator() {
        final SearchModule module = new SearchModule(Settings.EMPTY, List.of());
        assertThat(module.getRequestCacheKeyDifferentiator(), nullValue());
    }

    public void testRegisterRequestCacheKeyDifferentiator() {
        final CheckedBiConsumer<ShardSearchRequest, StreamOutput, IOException> requestCacheKeyDifferentiator = (r, o) -> {};
        final SearchModule module = new SearchModule(Settings.EMPTY, List.of(new SearchPlugin() {
            @Override
            public CheckedBiConsumer<ShardSearchRequest, StreamOutput, IOException> getRequestCacheKeyDifferentiator() {
                return requestCacheKeyDifferentiator;
            }
        }));
        assertThat(module.getRequestCacheKeyDifferentiator(), equalTo(requestCacheKeyDifferentiator));
    }

    public void testCannotRegisterMultipleRequestCacheKeyDifferentiators() {
        final CheckedBiConsumer<ShardSearchRequest, StreamOutput, IOException> differentiator1 = (r, o) -> {};
        final CheckedBiConsumer<ShardSearchRequest, StreamOutput, IOException> differentiator2 = (r, o) -> {};
        final IllegalArgumentException e = expectThrows(
            IllegalArgumentException.class,
            () -> new SearchModule(Settings.EMPTY, List.of(new SearchPlugin() {
                @Override
                public CheckedBiConsumer<ShardSearchRequest, StreamOutput, IOException> getRequestCacheKeyDifferentiator() {
                    return differentiator1;
                }
            }, new SearchPlugin() {
                @Override
                public CheckedBiConsumer<ShardSearchRequest, StreamOutput, IOException> getRequestCacheKeyDifferentiator() {
                    return differentiator2;
                }
            }))
        );
        assertThat(e.getMessage(), containsString("Cannot have more than one plugin providing a request cache key differentiator"));
    }

    private static final String[] NON_DEPRECATED_QUERIES = new String[] {
        "bool",
        "boosting",
        "constant_score",
        "combined_fields",
        "dis_max",
        "exists",
        "function_score",
        "fuzzy",
        "geo_bounding_box",
        "geo_distance",
        "geo_shape",
        "ids",
        "intervals",
        "match",
        "match_all",
        "match_bool_prefix",
        "match_none",
        "match_phrase",
        "match_phrase_prefix",
        "more_like_this",
        "multi_match",
        "nested",
        "prefix",
        "query_string",
        "range",
        "regexp",
        "script",
        "script_score",
        "simple_query_string",
        "span_containing",
        "span_field_masking",
        "span_first",
        "span_gap",
        "span_multi",
        "span_near",
        "span_not",
        "span_or",
        "span_term",
        "span_within",
        "term",
        "terms",
        "terms_set",
        "wildcard",
        "wrapper",
        "distance_feature" };

    // add here deprecated queries to make sure we log a deprecation warnings when they are used
    private static final String[] DEPRECATED_QUERIES = new String[] { "field_masking_span", "geo_polygon" };
    private static final String[] REST_COMPATIBLE_QUERIES = new String[] {
        TypeQueryV7Builder.NAME_V7.getPreferredName(),
        CommonTermsQueryBuilder.NAME_V7.getPreferredName() };

    /**
     * Dummy test {@link AggregationBuilder} used to test registering aggregation builders.
     */
    private static class TestAggregationBuilder extends ValuesSourceAggregationBuilder<TestAggregationBuilder> {
        protected TestAggregationBuilder(TestAggregationBuilder clone, Builder factoriesBuilder, Map<String, Object> metadata) {
            super(clone, factoriesBuilder, metadata);
        }

        @Override
        protected ValuesSourceType defaultValueSourceType() {
            return CoreValuesSourceType.KEYWORD;
        }

        @Override
        protected AggregationBuilder shallowCopy(Builder factoriesBuilder, Map<String, Object> metadata) {
            return new TestAggregationBuilder(this, factoriesBuilder, metadata);
        }

        /**
         * Read from a stream.
         */
        protected TestAggregationBuilder(StreamInput in) throws IOException {
            super(in);
        }

        @Override
        public String getType() {
            return "test";
        }

        @Override
        protected ValuesSourceRegistry.RegistryKey<?> getRegistryKey() {
            return ValuesSourceRegistry.UNREGISTERED_KEY;
        }

        @Override
        protected void innerWriteTo(StreamOutput out) throws IOException {}

        @Override
        public BucketCardinality bucketCardinality() {
            return BucketCardinality.NONE;
        }

        @Override
        protected ValuesSourceAggregatorFactory innerBuild(
            AggregationContext context,
            ValuesSourceConfig config,
            AggregatorFactory parent,
            Builder subFactoriesBuilder
        ) throws IOException {
            return null;
        }

        @Override
        protected XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
            return null;
        }

        private static TestAggregationBuilder fromXContent(String name, XContentParser p) {
            return null;
        }
    }

    /**
     * Dummy test {@link PipelineAggregator} used to test registering aggregation builders.
     */
    private static class TestPipelineAggregationBuilder extends AbstractPipelineAggregationBuilder<TestPipelineAggregationBuilder> {
        /**
         * Read from a stream.
         */
        TestPipelineAggregationBuilder(StreamInput in) throws IOException {
            super(in, "test");
        }

        @Override
        public String getWriteableName() {
            return "test";
        }

        @Override
        protected void doWriteTo(StreamOutput out) throws IOException {}

        @Override
        protected PipelineAggregator createInternal(Map<String, Object> metadata) {
            return null;
        }

        @Override
        protected XContentBuilder internalXContent(XContentBuilder builder, Params params) throws IOException {
            return null;
        }

        private static TestPipelineAggregationBuilder fromXContent(String name, XContentParser p) {
            return null;
        }

        @Override
        protected void validate(ValidationContext context) {}
    }

    /**
     * Dummy test {@link PipelineAggregator} used to test registering aggregation builders.
     */
    private static class TestPipelineAggregator extends PipelineAggregator {
        TestPipelineAggregator() {
            super("test", new String[] {}, null);
        }

        @Override
        public InternalAggregation reduce(InternalAggregation aggregation, AggregationReduceContext reduceContext) {
            return null;
        }
    }

    private static class TestRescorerBuilder extends RescorerBuilder<TestRescorerBuilder> {
        public static TestRescorerBuilder fromXContent(XContentParser parser) {
            return null;
        }

        TestRescorerBuilder(StreamInput in) throws IOException {
            super(in);
        }

        @Override
        public String getWriteableName() {
            return "test";
        }

        @Override
        public RescorerBuilder<TestRescorerBuilder> rewrite(QueryRewriteContext ctx) throws IOException {
            return this;
        }

        @Override
        protected void doWriteTo(StreamOutput out) throws IOException {}

        @Override
        protected void doXContent(XContentBuilder builder, Params params) throws IOException {}

        @Override
        public RescoreContext innerBuildContext(int windowSize, SearchExecutionContext context) throws IOException {
            return null;
        }
    }

    private static class TestSuggester extends Suggester<SuggestionSearchContext.SuggestionContext> {

        @Override
        protected Suggestion<? extends Suggestion.Entry<? extends Suggestion.Entry.Option>> innerExecute(
            String name,
            SuggestionSearchContext.SuggestionContext suggestion,
            IndexSearcher searcher,
            CharsRefBuilder spare
        ) throws IOException {
            return null;
        }

        @Override
        protected Suggestion<? extends Entry<? extends Option>> emptySuggestion(
            String name,
            SuggestionContext suggestion,
            CharsRefBuilder spare
        ) throws IOException {
            return null;
        }
    }

    private static class TestSuggestionBuilder extends SuggestionBuilder<TestSuggestionBuilder> {

        public static final String SUGGESTION_NAME = "test";

        TestSuggestionBuilder(StreamInput in) throws IOException {
            super(in);
        }

        @Override
        protected void doWriteTo(StreamOutput out) throws IOException {}

        public static TestSuggestionBuilder fromXContent(XContentParser parser) {
            return null;
        }

        @Override
        protected XContentBuilder innerToXContent(XContentBuilder builder, Params params) throws IOException {
            return null;
        }

        @Override
        protected SuggestionSearchContext.SuggestionContext build(SearchExecutionContext context) throws IOException {
            return null;
        }

        @Override
        protected boolean doEquals(TestSuggestionBuilder other) {
            return false;
        }

        @Override
        protected int doHashCode() {
            return 0;
        }

        @Override
        public String getWriteableName() {
            return "test";
        }
    }

    @SuppressWarnings("rawtypes")
    private static class TestSuggestion<T extends Suggestion.Entry> extends Suggestion<T> {
        TestSuggestion(StreamInput in) throws IOException {
            super(in);
        }

        @Override
        protected T newEntry(StreamInput in) throws IOException {
            return null;
        }

        @Override
        public String getWriteableName() {
            return "test";
        }
    }

    static class CompatQueryBuilder extends AbstractQueryBuilder<CompatQueryBuilder> {
        public static final String NAME = "compat_name";
        public static final ParseField NAME_OLD = new ParseField(NAME).forRestApiVersion(
            RestApiVersion.equalTo(RestApiVersion.minimumSupported())
        );

        public static CompatQueryBuilder fromXContent(XContentParser parser) throws IOException {
            return null;
        }

        @Override
        public String getWriteableName() {
            return NAME;
        }

        @Override
        protected void doWriteTo(StreamOutput out) throws IOException {}

        @Override
        protected void doXContent(XContentBuilder builder, Params params) throws IOException {}

        @Override
        protected Query doToQuery(SearchExecutionContext context) throws IOException {
            return null;
        }

        @Override
        protected boolean doEquals(CompatQueryBuilder other) {
            return false;
        }

        @Override
        protected int doHashCode() {
            return 0;
        }
    }

    public void testRegisterRestApiCompatibleQuery() {
        SearchPlugin registerCompatQuery = new SearchPlugin() {
            @Override
            public List<SearchPlugin.QuerySpec<?>> getQueries() {
                return singletonList(
                    new QuerySpec<>(
                        CompatQueryBuilder.NAME_OLD,
                        (streamInput) -> new CompatQueryBuilder(),
                        CompatQueryBuilder::fromXContent
                    )
                );
            }
        };

        final SearchModule searchModule = new SearchModule(Settings.EMPTY, singletonList(registerCompatQuery));

        // all entries can be used for current and previous versions except for compatible entry
        assertThat(searchModule.getNamedXContents().stream().filter(e ->
        // filter out compatible entry
        e.name.match(CompatQueryBuilder.NAME_OLD.getPreferredName(), LoggingDeprecationHandler.INSTANCE) == false)
            .filter(e -> RestApiVersion.minimumSupported().matches(e.restApiCompatibility))
            .filter(e -> RestApiVersion.current().matches(e.restApiCompatibility))
            .collect(toSet()),
            // -1 because of the registered in the test
            hasSize(searchModule.getNamedXContents().size() - REST_COMPATIBLE_QUERIES.length - 1)
        );

        final List<NamedXContentRegistry.Entry> compatEntry = searchModule.getNamedXContents()
            .stream()
            .filter(
                e -> e.categoryClass.equals(QueryBuilder.class)
                    && RestApiVersion.minimumSupported().matches(e.name.getForRestApiVersion()) // v7 compatbile
                    && RestApiVersion.current().matches(e.name.getForRestApiVersion()) == false
            ) // but not v8 compatible
            .collect(toList());
        assertThat(compatEntry, hasSize(REST_COMPATIBLE_QUERIES.length + 1));// +1 because of registered in the test
        assertTrue(RestApiVersion.minimumSupported().matches(compatEntry.get(0).restApiCompatibility));
        assertFalse(RestApiVersion.current().matches(compatEntry.get(0).restApiCompatibility));
    }
}


text:
package it.uliana;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Uniroma3IotApplication {

	public static void main(String[] args) {
		SpringApplication.run(Uniroma3IotApplication.class, args);
	}
}


text:
  National Insurance number
  It'll be on your last payslip. For example, VO 12 34 56 D.

<input class="form-control" id="ni-number" type="text">


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Marasmius umbraculum Berk. & Broome

### Remarks
null


text:
package org.wso2.carbon.identity.notification.mgt;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
import org.wso2.carbon.identity.notification.mgt.bean.ModuleConfiguration;
import org.wso2.carbon.identity.notification.mgt.bean.Subscription;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.securevault.SecretResolver;
import org.wso2.securevault.SecretResolverFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * Configuration builder class for Message Management component. Responsible for reading msg-mgt
 * .properties file and extract properties and distribute them to relevant message sending
 * components.
 */
@SuppressWarnings("unused")
public class NotificationMgtConfigBuilder {

    private static final Log log = LogFactory.getLog(NotificationMgtConfigBuilder.class);
    /**
     * All properties configured in msg-mgt.properties file
     */
    private Properties notificationMgtConfigProperties;
    /**
     * Map of configurations which are specific to notification sending modules
     */
    private Map<String, ModuleConfiguration> moduleConfiguration;
    /**
     * Thread pool size for message sending task
     */
    private String threadPoolSize;

    /**
     * Load properties file and set Module properties
     *
     * @param bundleContext Bundle context
     * @throws NotificationManagementException
     */
    public NotificationMgtConfigBuilder(BundleContext bundleContext) throws NotificationManagementException {
        notificationMgtConfigProperties = loadProperties(bundleContext);
        setThreadPoolSize();
        resolveSecrets();
        moduleConfiguration = new HashMap<String, ModuleConfiguration>();
        build();
    }

    /**
     * Sets the thread pool size read from configurations
     */
    private void setThreadPoolSize() {
        threadPoolSize = (String) notificationMgtConfigProperties.remove(NotificationMgtConstants.Configs.
                THREAD_POOL_SIZE);
    }

    /**
     * Load properties which are defined in msg-mgt.properties file
     *
     * @param bundleContext Bundle context
     * @return Set of properties which are defined in msg-mgt.properties file
     * @throws NotificationManagementException
     */
    private Properties loadProperties(BundleContext bundleContext) throws NotificationManagementException {
        Properties properties = new Properties();
        InputStream inStream = null;

        // Open the default configuration file in carbon conf directory path .
        File MessageMgtPropertyFile = new File(CarbonUtils.getCarbonConfigDirPath() + File.separator + "identity" +
                File.separator, NotificationMgtConstants.MODULE_CONFIG_FILE);

        try {
            // If the configuration exists in the carbon conf directory, read properties from there
            if (MessageMgtPropertyFile.exists()) {
                inStream = new FileInputStream(MessageMgtPropertyFile);
                // Else read properties form either bundle context path or class path
            } else {
                URL url;
                if (bundleContext != null) {
                    if ((url = bundleContext.getBundle().getResource(NotificationMgtConstants.MODULE_CONFIG_FILE))
                            != null) {
                        inStream = url.openStream();
                    } else {
                        log.warn("Bundle context could not find resource " + NotificationMgtConstants
                                .MODULE_CONFIG_FILE);
                    }
                    // If bundle context is not found, read properties file from class path
                } else {

                    if ((url = this.getClass().getClassLoader().getResource(NotificationMgtConstants.
                            MODULE_CONFIG_FILE)) != null) {
                        inStream = url.openStream();
                    } else {
                        log.warn("Class resource loader could not find resource " + NotificationMgtConstants.
                                MODULE_CONFIG_FILE);
                    }
                }
            }

            if (inStream != null) {
                properties.load(inStream);
            }
            //Even if the configurations are not found, individual modules can behave themselves without configuration
        } catch (FileNotFoundException e) {
            log.warn("Could not find configuration file for Message Sending module", e);
        } catch (IOException e) {
            log.warn("Error while opening input stream for property file", e);
            // Finally close input stream
        } finally {
            try {
                if (inStream != null) {
                    inStream.close();
                }
            } catch (IOException e) {
                log.error("Error while closing input stream ", e);
            }
        }

        return properties;
    }

    /**
     * Build and store per module configuration objects
     */
    private void build() {
        Properties moduleNames = NotificationManagementUtils.getSubProperties(NotificationMgtConstants.Configs.
                MODULE_NAME, notificationMgtConfigProperties);
        Enumeration propertyNames = moduleNames.propertyNames();
        // Iterate through events and build event objects
        while (propertyNames.hasMoreElements()) {
            String key = (String) propertyNames.nextElement();
            String moduleName = (String) moduleNames.remove(key);
            moduleConfiguration.put(moduleName, buildModuleConfigurations(moduleName));
        }
    }

    /**
     * Building per module configuration objects
     *
     * @param moduleName Name of the module
     * @return ModuleConfiguration object which has configurations for the given module name
     */
    private ModuleConfiguration buildModuleConfigurations(String moduleName) {
        Properties moduleProperties = getModuleProperties(moduleName);
        List<Subscription> subscriptionList = buildSubscriptionList(moduleName, moduleProperties);

        return new ModuleConfiguration(getModuleProperties(moduleName), subscriptionList);
    }

    /**
     * Build a list of subscription by a particular module
     *
     * @param moduleName       Name of the module
     * @param moduleProperties Set of properties which
     * @return A list of subscriptions by the module
     */
    private List<Subscription> buildSubscriptionList(String moduleName, Properties moduleProperties) {
        // Get subscribed events
        Properties subscriptions = NotificationManagementUtils.getSubProperties(moduleName + "." +
                NotificationMgtConstants.Configs.SUBSCRIPTION, moduleProperties);

        List<Subscription> subscriptionList = new ArrayList<Subscription>();
        Enumeration propertyNames = subscriptions.propertyNames();
        // Iterate through events and build event objects
        while (propertyNames.hasMoreElements()) {
            String key = (String) propertyNames.nextElement();
            String subscriptionName = (String) subscriptions.remove(key);
            // Read all the event properties starting from the event prefix
            Properties subscriptionProperties = NotificationManagementUtils.getPropertiesWithPrefix
                    (moduleName + "." + NotificationMgtConstants.Configs.SUBSCRIPTION + "." + subscriptionName,
                            moduleProperties);
            Subscription subscription = new Subscription(subscriptionName, subscriptionProperties);
            subscriptionList.add(subscription);
        }
        return subscriptionList;
    }

    /**
     * Retrieve all properties defined for a particular module
     *
     * @param moduleName Name of the module
     * @return A set of properties which are defined for a particular module
     */
    private Properties getModuleProperties(String moduleName) {
        return NotificationManagementUtils.getPropertiesWithPrefix(moduleName, notificationMgtConfigProperties);
    }

    /**
     * Returns a module configuration object for the passed mdoule name
     *
     * @param moduleName Name of the module
     * @return Module configuration object which is relevant to the given name.
     */
    public ModuleConfiguration getModuleConfigurations(String moduleName) {
        return this.moduleConfiguration.get(moduleName);
    }

    public String getThreadPoolSize() {
        return threadPoolSize;
    }

    /**
     * There can be sensitive information like passwords in configuration file. If they are encrypted using secure
     * vault, this method will resolve them and replace with original values.
     */
    private void resolveSecrets() {

        SecretResolver secretResolver = SecretResolverFactory.create(notificationMgtConfigProperties);
        Enumeration propertyNames = notificationMgtConfigProperties.propertyNames();
        if (secretResolver != null && secretResolver.isInitialized()) {
            // Iterate through whole config file and find encrypted properties and resolve them
            while (propertyNames.hasMoreElements()) {
                String key = (String) propertyNames.nextElement();
                if (secretResolver.isTokenProtected(key)) {
                    if (log.isDebugEnabled()) {
                        log.debug("Resolving and replacing secret for " + key);
                    }
                    // Resolving the secret password.
                    String value = secretResolver.resolve(key);
                    // Replaces the original encrypted property with resolved property
                    notificationMgtConfigProperties.put(key, value);
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("No encryption done for value with key :" + key);
                    }
                }
            }
        } else {
            if(log.isDebugEnabled()){
                log.debug("Secret Resolver is not present. Will not resolve encryptions in config file");
            }
        }
    }
}


text:
#include "NetworkStack.h"
#include "nsapi_dns.h"
#include "mbed.h"
#include "stddef.h"
#include <new>

// Default NetworkStack operations
const char *NetworkStack::get_ip_address()
{
    return 0;

}
nsapi_error_t NetworkStack::gethostbyname(const char *name, SocketAddress *address, nsapi_version_t version)
{
    if (name[0] == '\0') {
        return NSAPI_ERROR_PARAMETER;
    }

    // check for simple ip addresses
    if (address->set_ip_address(name)) {
        if (version != NSAPI_UNSPEC && address->get_ip_version() != version) {
            return NSAPI_ERROR_DNS_FAILURE;
        }

        return NSAPI_ERROR_OK;
    }

    // if the version is unspecified, try to guess the version from the
    // ip address of the underlying stack
    if (version == NSAPI_UNSPEC) {
        SocketAddress testaddress;
        if (testaddress.set_ip_address(this->get_ip_address())) {
            version = testaddress.get_ip_version();
        }
    }

    return nsapi_dns_query(this, name, address, version);
}

nsapi_value_or_error_t NetworkStack::gethostbyname_async(const char *name, hostbyname_cb_t callback, nsapi_version_t version)
{
    SocketAddress address;

    if (name[0] == '\0') {
        return NSAPI_ERROR_PARAMETER;
    }

    // check for simple ip addresses
    if (address.set_ip_address(name)) {
        if (version != NSAPI_UNSPEC && address.get_ip_version() != version) {
            return NSAPI_ERROR_DNS_FAILURE;
        }

        callback(NSAPI_ERROR_OK, &address);
        return NSAPI_ERROR_OK;
    }

    // if the version is unspecified, try to guess the version from the
    // ip address of the underlying stack
    if (version == NSAPI_UNSPEC) {
        SocketAddress testaddress;
        if (testaddress.set_ip_address(this->get_ip_address())) {
            version = testaddress.get_ip_version();
        }
    }

    call_in_callback_cb_t call_in_cb = get_call_in_callback();

    return nsapi_dns_query_async(this, name, callback, call_in_cb, version);
}

nsapi_error_t NetworkStack::gethostbyname_async_cancel(int id)
{
    return nsapi_dns_query_async_cancel(id);
}

nsapi_error_t NetworkStack::add_dns_server(const SocketAddress &address)
{
    return nsapi_dns_add_server(address);
}

nsapi_error_t NetworkStack::get_dns_server(int index, SocketAddress *address)
{
    return NSAPI_ERROR_UNSUPPORTED;
}

nsapi_error_t NetworkStack::setstackopt(int level, int optname, const void *optval, unsigned optlen)
{
    return NSAPI_ERROR_UNSUPPORTED;
}

nsapi_error_t NetworkStack::getstackopt(int level, int optname, void *optval, unsigned *optlen)
{
    return NSAPI_ERROR_UNSUPPORTED;
}

nsapi_error_t NetworkStack::setsockopt(void *handle, int level, int optname, const void *optval, unsigned optlen)
{
    return NSAPI_ERROR_UNSUPPORTED;
}

nsapi_error_t NetworkStack::getsockopt(void *handle, int level, int optname, void *optval, unsigned *optlen)
{
    return NSAPI_ERROR_UNSUPPORTED;
}

nsapi_error_t NetworkStack::call_in(int delay, mbed::Callback<void()> func)
{
    static events::EventQueue *event_queue = mbed::mbed_event_queue();

    if (!event_queue) {
        return NSAPI_ERROR_NO_MEMORY;
    }

    if (delay > 0) {
        if (event_queue->call_in(delay, func) == 0) {
            return NSAPI_ERROR_NO_MEMORY;
        }
    } else {
        if (event_queue->call(func) == 0) {
            return NSAPI_ERROR_NO_MEMORY;
        }
    }

    return NSAPI_ERROR_OK;
}

call_in_callback_cb_t NetworkStack::get_call_in_callback()
{
    call_in_callback_cb_t cb(this, &NetworkStack::call_in);
    return cb;
}

// NetworkStackWrapper class for encapsulating the raw nsapi_stack structure
class NetworkStackWrapper : public NetworkStack {
private:
    inline nsapi_stack_t *_stack()
    {
        return reinterpret_cast<nsapi_stack_t *>(
                   reinterpret_cast<uint8_t *>(this)
                   - offsetof(nsapi_stack_t, _stack_buffer));
    }

    inline const nsapi_stack_api_t *_stack_api()
    {
        return _stack()->stack_api;
    }

public:
    virtual const char *get_ip_address()
    {
        if (!_stack_api()->get_ip_address) {
            return 0;
        }

        static uint8_t buffer[sizeof(SocketAddress)];
        SocketAddress *address = new (buffer) SocketAddress(_stack_api()->get_ip_address(_stack()));
        return address->get_ip_address();
    }

    virtual nsapi_error_t gethostbyname(const char *name, SocketAddress *address, nsapi_version_t version)
    {
        if (!_stack_api()->gethostbyname) {
            return NetworkStack::gethostbyname(name, address, version);
        }

        nsapi_addr_t addr = {NSAPI_UNSPEC, 0};
        nsapi_error_t err = _stack_api()->gethostbyname(_stack(), name, &addr, version);
        address->set_addr(addr);
        return err;
    }

    virtual nsapi_error_t add_dns_server(const SocketAddress &address)
    {
        if (!_stack_api()->add_dns_server) {
            return NetworkStack::add_dns_server(address);
        }

        return _stack_api()->add_dns_server(_stack(), address.get_addr());
    }

    virtual nsapi_error_t setstackopt(int level, int optname, const void *optval, unsigned optlen)
    {
        if (!_stack_api()->setstackopt) {
            return NSAPI_ERROR_UNSUPPORTED;
        }

        return _stack_api()->setstackopt(_stack(), level, optname, optval, optlen);
    }

    virtual nsapi_error_t getstackopt(int level, int optname, void *optval, unsigned *optlen)
    {
        if (!_stack_api()->getstackopt) {
            return NSAPI_ERROR_UNSUPPORTED;
        }

        return _stack_api()->getstackopt(_stack(), level, optname, optval, optlen);
    }

protected:
    virtual nsapi_error_t socket_open(nsapi_socket_t *socket, nsapi_protocol_t proto)
    {
        if (!_stack_api()->socket_open) {
            return NSAPI_ERROR_UNSUPPORTED;
        }

        return _stack_api()->socket_open(_stack(), socket, proto);
    }

    virtual nsapi_error_t socket_close(nsapi_socket_t socket)
    {
        if (!_stack_api()->socket_close) {
            return NSAPI_ERROR_UNSUPPORTED;
        }

        return _stack_api()->socket_close(_stack(), socket);
    }

    virtual nsapi_error_t socket_bind(nsapi_socket_t socket, const SocketAddress &address)
    {
        if (!_stack_api()->socket_bind) {
            return NSAPI_ERROR_UNSUPPORTED;
        }

        return _stack_api()->socket_bind(_stack(), socket, address.get_addr(), address.get_port());
    }

    virtual nsapi_error_t socket_listen(nsapi_socket_t socket, int backlog)
    {
        if (!_stack_api()->socket_listen) {
            return NSAPI_ERROR_UNSUPPORTED;
        }

        return _stack_api()->socket_listen(_stack(), socket, backlog);
    }

    virtual nsapi_error_t socket_connect(nsapi_socket_t socket, const SocketAddress &address)
    {
        if (!_stack_api()->socket_connect) {
            return NSAPI_ERROR_UNSUPPORTED;
        }

        return _stack_api()->socket_connect(_stack(), socket, address.get_addr(), address.get_port());
    }

    virtual nsapi_error_t socket_accept(nsapi_socket_t server, nsapi_socket_t *socket, SocketAddress *address)
    {
        if (!_stack_api()->socket_accept) {
            return NSAPI_ERROR_UNSUPPORTED;
        }

        nsapi_addr_t addr = {NSAPI_IPv4, 0};
        uint16_t port = 0;

        nsapi_error_t err = _stack_api()->socket_accept(_stack(), server, socket, &addr, &port);

        if (address) {
            address->set_addr(addr);
            address->set_port(port);
        }

        return err;
    }

    virtual nsapi_size_or_error_t socket_send(nsapi_socket_t socket, const void *data, nsapi_size_t size)
    {
        if (!_stack_api()->socket_send) {
            return NSAPI_ERROR_UNSUPPORTED;
        }

        return _stack_api()->socket_send(_stack(), socket, data, size);
    }

    virtual nsapi_size_or_error_t socket_recv(nsapi_socket_t socket, void *data, nsapi_size_t size)
    {
        if (!_stack_api()->socket_recv) {
            return NSAPI_ERROR_UNSUPPORTED;
        }

        return _stack_api()->socket_recv(_stack(), socket, data, size);
    }

    virtual nsapi_size_or_error_t socket_sendto(nsapi_socket_t socket, const SocketAddress &address, const void *data, nsapi_size_t size)
    {
        if (!_stack_api()->socket_sendto) {
            return NSAPI_ERROR_UNSUPPORTED;
        }

        return _stack_api()->socket_sendto(_stack(), socket, address.get_addr(), address.get_port(), data, size);
    }

    virtual nsapi_size_or_error_t socket_recvfrom(nsapi_socket_t socket, SocketAddress *address, void *data, nsapi_size_t size)
    {
        if (!_stack_api()->socket_recvfrom) {
            return NSAPI_ERROR_UNSUPPORTED;
        }

        nsapi_addr_t addr = {NSAPI_IPv4, 0};
        uint16_t port = 0;

        nsapi_size_or_error_t err = _stack_api()->socket_recvfrom(_stack(), socket, &addr, &port, data, size);

        if (address) {
            address->set_addr(addr);
            address->set_port(port);
        }

        return err;
    }

    virtual void socket_attach(nsapi_socket_t socket, void (*callback)(void *), void *data)
    {
        if (!_stack_api()->socket_attach) {
            return;
        }

        return _stack_api()->socket_attach(_stack(), socket, callback, data);
    }

    virtual nsapi_error_t setsockopt(nsapi_socket_t socket, int level, int optname, const void *optval, unsigned optlen)
    {
        if (!_stack_api()->setsockopt) {
            return NSAPI_ERROR_UNSUPPORTED;
        }

        return _stack_api()->setsockopt(_stack(), socket, level, optname, optval, optlen);
    }

    virtual nsapi_error_t getsockopt(nsapi_socket_t socket, int level, int optname, void *optval, unsigned *optlen)
    {
        if (!_stack_api()->getsockopt) {
            return NSAPI_ERROR_UNSUPPORTED;
        }

        return _stack_api()->getsockopt(_stack(), socket, level, optname, optval, optlen);
    }
};

// Conversion function for network stacks
NetworkStack *nsapi_create_stack(nsapi_stack_t *stack)
{
    MBED_STATIC_ASSERT(sizeof stack->_stack_buffer >= sizeof(NetworkStackWrapper),
                       "The nsapi_stack_t stack buffer must fit a NetworkStackWrapper");
    return new (stack->_stack_buffer) NetworkStackWrapper;
}

NetworkStack *nsapi_create_stack(NetworkStack *stack)
{
    return stack;
}


text:
var db = require('../config.js');
var Quest = require('./quest.js');

var Waypoint = db.Model.extend({
	tableName: 'waypoints',
	quest: function() {
		return this.belongsTo(Quest);
	},
	hasTimestamps: true
});

module.exports = Waypoint;


text:
<title>M68K-Chars - Using as</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Using as">
<meta name="generator" content="makeinfo 4.11">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="M68K_002dopcodes.html#M68K_002dopcodes" title="M68K-opcodes">
<link rel="prev" href="M68K_002dBranch.html#M68K_002dBranch" title="M68K-Branch">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Previous: M68K-Branch,
Up: M68K-opcodes

9.21.6.2 Special Characters

The immediate character is ‘<samp>#</samp>’ for Sun compatibility.  The
line-comment character is ‘<samp>|</samp>’ (unless the ‘<samp>--bitwise-or</samp>’
option is used).  If a ‘<samp>#</samp>’ appears at the beginning of a line, it
is treated as a comment unless it looks like ‘<samp># line file</samp>’, in
which case it is treated normally.


text:
<?php
/*
 * Api2PostnordComFindNearbyServicePointsLib
 *
 * This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ) on 06/29/2016
 */

namespace Api2PostnordComFindNearbyServicePointsLib\Http;

/**
* HTTP Methods Enumeration
*/
class HttpMethod
{
    const GET = "Get";
    const POST = "Post";
    const PUT = "Put";
    const PATCH = "Patch";
    const DELETE = "Delete";
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
PMSubjectFragment.SubjectCursorAdapter
</TITLE>

<META NAME="date" CONTENT="2014-05-30">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.panacea.sdk.fragment

Class PMSubjectFragment.SubjectCursorAdapter

java.lang.Object
  android.widget.BaseAdapter
      android.support.v4.widget.CursorAdapter
          com.panacea.sdk.fragment.PMSubjectFragment.SubjectCursorAdapter

All Implemented Interfaces:
android.widget.Adapter, android.widget.Filterable, android.widget.ListAdapter, android.widget.SpinnerAdapter

Enclosing class:
PMSubjectFragment

public class PMSubjectFragment.SubjectCursorAdapter
extends android.support.v4.widget.CursorAdapter

Field Summary

private  android.content.Context
mContext

Fields inherited from class android.support.v4.widget.CursorAdapter

FLAG_AUTO_REQUERY, FLAG_REGISTER_CONTENT_OBSERVER, mAutoRequery, mChangeObserver, mCursor, mCursorFilter, mDataSetObserver, mDataValid, mFilterQueryProvider, mRowIDColumn

Fields inherited from interface android.widget.Adapter

IGNORE_ITEM_VIEW_TYPE, NO_SELECTION

Constructor Summary

PMSubjectFragment.SubjectCursorAdapter(android.content.Context context,
                                       android.database.Cursor c)

Method Summary

 void
bindView(android.view.View view,
         android.content.Context context,
         android.database.Cursor cursor)

 android.view.View
newView(android.content.Context context,
        android.database.Cursor cursor,
        android.view.ViewGroup parent)

Methods inherited from class android.support.v4.widget.CursorAdapter

changeCursor, convertToString, getCount, getCursor, getDropDownView, getFilter, getFilterQueryProvider, getItem, getItemId, getView, hasStableIds, init, newDropDownView, onContentChanged, runQueryOnBackgroundThread, setFilterQueryProvider, swapCursor

Methods inherited from class android.widget.BaseAdapter

areAllItemsEnabled, getItemViewType, getViewTypeCount, isEmpty, isEnabled, notifyDataSetChanged, notifyDataSetInvalidated, registerDataSetObserver, unregisterDataSetObserver

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

mContext

private android.content.Context mContext

Constructor Detail

PMSubjectFragment.SubjectCursorAdapter

public PMSubjectFragment.SubjectCursorAdapter(android.content.Context context,
                                              android.database.Cursor c)

Method Detail

bindView

public void bindView(android.view.View view,
                     android.content.Context context,
                     android.database.Cursor cursor)

Specified by:
bindView in class android.support.v4.widget.CursorAdapter

newView

public android.view.View newView(android.content.Context context,
                                 android.database.Cursor cursor,
                                 android.view.ViewGroup parent)

Specified by:
newView in class android.support.v4.widget.CursorAdapter

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
xplayer
=======

a web player for PC and mobile device


text:
<?php

class Category extends MY_Model {

    public static $definition = array(
        'primary' => 'id_category',
        'properties' => array (
            'id_category' => array (
                'defaultValue' => null
            ),
            'id_parent' => array (
                'defaultValue' => null
            ),
            'id_image_group' => array (
                'defaultValue' => null
            ),
            'active' => array (
                'defaultValue' => false
            )
        )
    );
    public static $joinable = array(
        array('join_with' => 'Category',
               'own_join_attribute' => 'id_category',
               'foreign_join_attribute' => 'id_category',
               'join_operation' => '='),
        array('join_with' => 'ImageGroup',
            'own_join_attribute' => 'id_image_group',
            'foreign_join_attribute' => 'id_image_group',
            'join_operation' => '='
        /*
        ,
            'AND' => array(
                'own_join_attribute' => '"category"',
                'foreign_join_attribute' => 'type',
                'join_operation' => '=',
            )
        */
        )
    );
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.datamigration.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Input for the task that validates connection to Azure SQL Database Managed Instance online scenario. */
@Fluent
public final class ConnectToTargetSqlMISyncTaskInput {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(ConnectToTargetSqlMISyncTaskInput.class);

    /*
     * Connection information for Azure SQL Database Managed Instance
     */
    @JsonProperty(value = "targetConnectionInfo", required = true)
    private MiSqlConnectionInfo targetConnectionInfo;

    /*
     * Azure Active Directory Application the DMS instance will use to connect
     * to the target instance of Azure SQL Database Managed Instance and the
     * Azure Storage Account
     */
    @JsonProperty(value = "azureApp", required = true)
    private AzureActiveDirectoryApp azureApp;

    /**
     * Get the targetConnectionInfo property: Connection information for Azure SQL Database Managed Instance.
     *
     * @return the targetConnectionInfo value.
     */
    public MiSqlConnectionInfo targetConnectionInfo() {
        return this.targetConnectionInfo;
    }

    /**
     * Set the targetConnectionInfo property: Connection information for Azure SQL Database Managed Instance.
     *
     * @param targetConnectionInfo the targetConnectionInfo value to set.
     * @return the ConnectToTargetSqlMISyncTaskInput object itself.
     */
    public ConnectToTargetSqlMISyncTaskInput withTargetConnectionInfo(MiSqlConnectionInfo targetConnectionInfo) {
        this.targetConnectionInfo = targetConnectionInfo;
        return this;
    }

    /**
     * Get the azureApp property: Azure Active Directory Application the DMS instance will use to connect to the target
     * instance of Azure SQL Database Managed Instance and the Azure Storage Account.
     *
     * @return the azureApp value.
     */
    public AzureActiveDirectoryApp azureApp() {
        return this.azureApp;
    }

    /**
     * Set the azureApp property: Azure Active Directory Application the DMS instance will use to connect to the target
     * instance of Azure SQL Database Managed Instance and the Azure Storage Account.
     *
     * @param azureApp the azureApp value to set.
     * @return the ConnectToTargetSqlMISyncTaskInput object itself.
     */
    public ConnectToTargetSqlMISyncTaskInput withAzureApp(AzureActiveDirectoryApp azureApp) {
        this.azureApp = azureApp;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (targetConnectionInfo() == null) {
            throw logger
                .logExceptionAsError(
                    new IllegalArgumentException(
                        "Missing required property targetConnectionInfo in model ConnectToTargetSqlMISyncTaskInput"));
        } else {
            targetConnectionInfo().validate();
        }
        if (azureApp() == null) {
            throw logger
                .logExceptionAsError(
                    new IllegalArgumentException(
                        "Missing required property azureApp in model ConnectToTargetSqlMISyncTaskInput"));
        } else {
            azureApp().validate();
        }
    }
}


text:
package edu.uw.easysrl.util;

import java.lang.reflect.Field;

public class LibraryUtil {
	private LibraryUtil() {
	}

	public static void setLibraryPath(String libraryPath) {
		System.setProperty("java.library.path", libraryPath);
		try {
			final Field fieldSysPath = ClassLoader.class.getDeclaredField("sys_paths");
			fieldSysPath.setAccessible(true);
			fieldSysPath.set(null, null);
		} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}
}


text:
/* -*- Mode: js2; tab-width: 4; indent-tabs-mode: nil; -*-
 * vim: set ts=4 sw=4 et tw=99 ft=js:
 */
import * as escodegen from '../escodegen/escodegen-es6';

import * as debug from './debug';

import { EqIdioms }         from './passes/eq-idioms'
import { ReplaceUnaryVoid } from './passes/replace-unary-void'

const passes = [
    EqIdioms,
    ReplaceUnaryVoid,
];

export function run (tree) {

    passes.forEach ((passType) => {
        let pass = new passType();
        tree = pass.visit(tree);
        debug.log (2, `after: ${passType.name}`);
        debug.log (2, () => escodegen.generate(tree));
    });
    return tree;
}


text:
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_IMAGE_DECODERS_PNG_PNG_IMAGE_DECODER_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_IMAGE_DECODERS_PNG_PNG_IMAGE_DECODER_H_

#include <memory>

#include "third_party/blink/renderer/platform/image-decoders/image_decoder.h"
#include "third_party/blink/renderer/platform/image-decoders/png/png_image_reader.h"

namespace blink {

class PLATFORM_EXPORT PNGImageDecoder final : public ImageDecoder {
 public:
  PNGImageDecoder(AlphaOption,
                  HighBitDepthDecodingOption,
                  const ColorBehavior&,
                  wtf_size_t max_decoded_bytes,
                  wtf_size_t offset = 0);
  PNGImageDecoder(const PNGImageDecoder&) = delete;
  PNGImageDecoder& operator=(const PNGImageDecoder&) = delete;
  ~PNGImageDecoder() override;

  // ImageDecoder:
  String FilenameExtension() const override { return "png"; }
  bool SetSize(unsigned, unsigned) override;
  int RepetitionCount() const override;
  bool ImageIsHighBitDepth() override;
  bool FrameIsReceivedAtIndex(wtf_size_t) const override;
  base::TimeDelta FrameDurationAtIndex(wtf_size_t) const override;
  bool SetFailed() override;

  // Callbacks from libpng
  void HeaderAvailable();
  void RowAvailable(unsigned char* row, unsigned row_index, int);
  void FrameComplete();

  void SetColorSpace();
  void SetRepetitionCount(int);
  void SetBitDepth();

 private:
  using ParseQuery = PNGImageReader::ParseQuery;

  // ImageDecoder:
  void DecodeSize() override { Parse(ParseQuery::kSize); }
  void Decode(wtf_size_t) override;
  void Parse(ParseQuery);
  wtf_size_t DecodeFrameCount() override;
  void InitializeNewFrame(wtf_size_t) override;
  void ClearFrameBuffer(wtf_size_t) override;
  bool CanReusePreviousFrameBuffer(wtf_size_t) const override;

  std::unique_ptr<PNGImageReader> reader_;
  const unsigned offset_;
  wtf_size_t current_frame_;
  int repetition_count_;
  bool has_alpha_channel_;
  bool current_buffer_saw_alpha_;
  bool decode_to_half_float_;
  wtf_size_t bit_depth_;
  std::unique_ptr<ImageFrame::PixelData[]> color_transform_scanline_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_IMAGE_DECODERS_PNG_PNG_IMAGE_DECODER_H_


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycologia 40: 315 (1948)

#### Original name
Leptothyrium avenae Tehon

### Remarks
null


text:
@interface ViewController : UIViewController

@property (nonatomic, weak) IBOutlet TKAutoCompleteTextField *textFieldSample1;
@property (nonatomic, weak) IBOutlet TKAutoCompleteTextField *textFieldSample2;
@property (nonatomic, weak) IBOutlet TKAutoCompleteTextField *textFieldSample3;

@end


text:
package io.scigraph.lucene;

import java.io.IOException;

import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;

/***
 * Adds a beginning of line token and an ending of line token.
 *
 * <p>Useful for supporting "exactish" matching with Lucene.
 */
public final class BolEolFilter extends TokenFilter {

  private final String bol;
  private final String eol;

  boolean addedBol = false;
  boolean addedEol = false;
  private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);

  public BolEolFilter(TokenStream input) {
    this(input, "^", "$");
  }

  public BolEolFilter(TokenStream input, String bol, String eol) {
    super(input);
    this.bol = bol;
    this.eol = eol;
  }

  @Override
  public boolean incrementToken() throws IOException {
    if (!addedBol) {
      termAtt.setEmpty().append(bol);
      addedBol = true;
      return true;
    }
    if (input.incrementToken()) {
      return true;
    }
    if (!addedEol) {
      termAtt.setEmpty().append(eol);
      addedEol = true;
      return true;
    }
    return false;
  }

}


text:
# ifndef KAA_NOTIFICATION_DEFINITIONS_H_
# define KAA_NOTIFICATION_DEFINITIONS_H_

# include "kaa_notification_gen.h"

# ifdef __cplusplus
extern "C" {
# endif

typedef kaa_notification_endnode_notifications_t kaa_notification_t;
# define KAA_NOTIFICATION_DESERIALIZE(reader)  kaa_notification_endnode_notifications_deserialize(reader)

# ifdef __cplusplus
}      /* extern "C" */
# endif

# endif /* KAA_NOTIFICATION_DEFINITIONS_H_ */


text:
<?php

namespace Sensorario\Resources;

class Container
{
    private $resources;

    private $rewrites;

    private $allowed = [
        'allowed',
        'allowedRanges',
        'allowedValues',
        'defaults',
        'mandatory',
        'rules',
    ];

    private $globals;

    private $resourceConstraints;

    public function __construct(array $resources)
    {
        $this->ensureResourcesItemIsDefined($resources);

        $this->rewrites = [];
        $this->globals  = [];

        $this->ensureValidConstraints($resources);

        $this->fillInRewrites($resources['resources']);

        if (isset($resources['globals'])) {
            $this->globals = $resources['globals'];
        }

        $this->resources = $resources;
    }

    private function ensureValidConstraints($resources)
    {
        foreach ($resources['resources'] as $item) {
            if (isset($item['constraints'])) {
                foreach ($item['constraints'] as $name => $value) {
                    $this->ensureNameIsAllowed($name, $value);
                }
            }
        }
    }

    public function ensureNameIsAllowed($name, $value)
    {
        if (!in_array($name, $this->allowed)) {
            throw new \Sensorario\Resources\Exceptions\InvalidConstraintException(
                'Invalid constraint: '
                . 'name ' . $name
                . '; value ' . $value
            );
        }
    }

    public function countResources()
    {
        return count(
            $this->resources['resources']
        );
    }

    private function getResourceConstraints($resource)
    {
        if (!$this->resourceConstraints) {
            $this->resourceConstraints = $this->resources['resources'][$resource]['constraints'];
        }

        return $this->resourceConstraints;
    }

    public function create($resource, array $constraints)
    {
        foreach ($constraints as $name => $value) {
            if (
                !isset($this->getResourceConstraints($resource)['allowed'])
                || !in_array($name, $this->getResourceConstraints($resource)['allowed'])
            ) {
                throw new \Sensorario\Resources\Exceptions\NotAllowedConstraintException(
                    'Not allowed `' . $name . '` constraint with value `' . $value . '`'
                );
            }
        }

        return true;
    }

    public function allowed($resource)
    {
        $allowed = [];

        foreach ($this->allowed as $item) {
            if (isset($this->getResourceConstraints($resource)[$item])) {
                $allowed = array_merge(
                    $allowed,
                    $this->getResourceConstraints($resource)[$item]
                );
            }
        }

        return $allowed;
    }

    public function getConstraints($constraint, $resource) : array
    {
        if (isset($this->getResourceConstraints($resource)[$constraint])) {
            return $this->getResourceConstraints($resource)[$constraint];
        }

        return [];
    }

    public function rewrites()
    {
        return $this->rewrites;
    }

    public function globals()
    {
        return $this->globals;
    }

    public function mandatory($resource)
    {
        return $this->getConstraints(
            'mandatory',
            $resource
        );
    }

    public function defaults($resource)
    {
        return $this->getConstraints(
            'defaults',
            $resource
        );
    }

    public function rules($resource)
    {
        return $this->getConstraints(
            'rules',
            $resource
        );
    }

    public function allowedValues($resource)
    {
        return $this->getConstraints(
            'allowedValues',
            $resource
        );
    }

    public function ranges($resource)
    {
        return $this->getConstraints(
            'allowedRanges',
            $resource
        );
    }

    public function ensureResourcesItemIsDefined($resources)
    {
        if (!isset($resources['resources'])) {
            throw new \Sensorario\Resources\Exceptions\EmptyConfigurationException(
                'resources element is not defined'
            );
        }
    }

    public function fillInRewrites(array $resources)
    {
        foreach ($resources as $item) {
            if (isset($item['rewrite'])) {
                foreach ($item['rewrite'] as $field => $rewriteRule) {
                    $this->rewrites[$field] = $rewriteRule;
                }
            }
        }
    }
}


text:
#include "ResourceManager.h"

#include <boost/filesystem.hpp>

namespace fs = boost::filesystem;

namespace game {

  template<typename T>
  T *ResourceManager::ResourceCache<T>::findResource(const boost::filesystem::path& key) {
    auto it = m_cache.find(key);

    if (it != m_cache.end()) {
      return it->second.get();
    }

    return nullptr;
  }

  template<typename T>
  T *ResourceManager::ResourceCache<T>::loadResource(const boost::filesystem::path& key, const boost::filesystem::path& path) {
    std::unique_ptr<T> obj(new T);

    bool loaded = obj->loadFromFile(path.string());
    assert(loaded);

    auto inserted = m_cache.emplace(key, std::move(obj));
    assert(inserted.second);

    return inserted.first->second.get();
  }

  sf::Font *ResourceManager::getFont(const boost::filesystem::path& path) {
    return getResource(path, m_fonts);
  }

  sf::SoundBuffer *ResourceManager::getSoundBuffer(const boost::filesystem::path& path) {
    return getResource(path, m_sounds);
  }

  sf::Texture *ResourceManager::getTexture(const boost::filesystem::path& path) {
    return getResource(path, m_textures);
  }

  template<typename T>
  T *ResourceManager::getResource(const boost::filesystem::path& path, ResourceCache<T>& cache) {
    auto res = cache.findResource(path);

    if (res != nullptr) {
      return res;
    }

    auto absolute_path = getAbsolutePath(path);

    if (absolute_path.empty()) {
      return nullptr;
    }

    return cache.loadResource(path, absolute_path);
  }

}


text:
require 'spec_helper'

describe USPS::Request::TrackingFieldLookup do

  it 'should be using the proper USPS api settings' do
    USPS::Request::TrackingFieldLookup.tap do |klass|
      expect(klass.secure).to be_falsey
      expect(klass.api).to eq('TrackV2')
      expect(klass.tag).to eq('TrackFieldRequest')
    end
  end

  it "should build a proper request" do
    request = USPS::Request::TrackingFieldLookup.new("EJ958083578US").build
    xml = Nokogiri::XML.parse(request)
    expect(xml.search('TrackID').text).to eq('')
    expect(xml.search('TrackID').attr("ID").text).to eq("EJ958083578US")
  end

end