text:
module S3Sync
  module AwsSetting
    def get_setting
      setting = {}
      setting.tap do |h|
        %w(AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_END_POINT AWS_BKUP_DIR).each do |key|
          abort "環境変数#{key}が設定されていません" unless ENV[key]
          h[key] = ENV[key]
        end
      end
    end
  end
  class CLI < Thor
    include S3Sync::AwsSetting
    desc "assert strategy", ''
    def assert strategy
      begin
      setting = get_setting
      strategy = CopyStrategy.new('ogura-test','ogura-test2', setting)
      rescue S3Strategy::DataNotFound, S3Strategy::DataAlreadyExists, S3Strategy::InvalidParameter=>e
        puts e.class.to_s
        puts e.message
        exit
      end
    end
    desc "download BUCKET_NAME", ""
    def download bucket_name
      begin
        setting = get_setting
        strategy = DownloadStrategy.new(bucket_name, setting)
        strategy.execute
      rescue S3Strategy::DataNotFound, S3Strategy::InvalidDataIdentification, AclManager::FileNotFound =>e
        puts e.message
        exit
      end
    end
    desc "list LOCAL_OR_S3 [-b BUCKET_NAME]", ""
    method_options b: :string
    def list(local_or_s3)
      setting = get_setting
      if local_or_s3 == 'local'
        bucket_name = options[:b]
        bucket_list_data = FileAggregator.list(setting['AWS_BKUP_DIR'], bucket_name)
        bucket_list_data.each do |key,value|
          puts "local buckets:#{key}"
          puts "timestamp:"
          value.each_slice(10){|timestamp_list|  timestamp_list.each{|timestamp| print "#{timestamp}\t"}.tap{|t| puts "\n"}}
        end
      elsif local_or_s3 == 's3'
        bucket_name_list = S3Aggregator.bucket_name_list(setting)
        puts "s3 buckets:"
        puts bucket_name_list
      else
        abort 'please choose s3 or local'
      end
    end
    desc "upload BUCKET_NAME TIMESTAMP [--nb NEW_BUCKET_NAME]", ""
    method_options nb: :string
    def upload(bucket_name, timestamp)
      begin
        setting = get_setting
        bucket_name_to = options[:nb] ?  options[:nb] : bucket_name
        strategy = UploadStrategy.new(bucket_name, bucket_name_to, timestamp, setting)
        strategy.execute
      rescue S3Strategy::InvalidParameter, S3Strategy::DataNotFound, S3Strategy::DataAlreadyExists, AclManager::FileNotFound => e
        puts e.message
        exit
      end
    end

    desc "copy FROM_BUCKET_NAME TO_BUCKET_NAME", ""
    def copy(bucket_name_from, bucket_name_to)
      begin
        setting = get_setting
        strategy = CopyStrategy.new(bucket_name_from, bucket_name_to, setting)
        strategy.execute
      rescue S3Strategy::InvalidParameter, S3Strategy::DataNotFound, S3Strategy::DataAlreadyExists => e
        puts e.message
        exit
      end
    end

    desc "remove BUCKET_NAME", ""
    def remove(bucket_name)
      begin
        setting = get_setting
        strategy = RemoveStrategy.new(bucket_name, setting)
        strategy.execute
      rescue S3Strategy::InvalidParameter, S3Strategy::DataNotFound => e
        puts e.message
        exit
      end
    end

    desc "interactive", ""
    def interactive
      setting = get_setting
      #bkupディレクトリ確認
      abort "bkup用ディレクトリの#{setting['AWS_BKUP_DIR']}がありません" if Dir.exists?(setting['AWS_BKUP_DIR']) == false
      puts "以下からアクションを選択してください"
      puts "1:s3バケットをローカルストレージにダウンロード"
      puts "2:ローカルストレージからs3バケットを作成"
      puts "3:s3バケットのコピー"
      puts "4:s3バケット削除"
      print '>>'
      action_id = STDIN.gets.strip.to_i
      abort '入力値が不正です' unless [1,2,3,4].member?(action_id)
      begin
        if action_id == 1
          strategy = DownloadStrategy.initialize_with_cli(setting)
        elsif action_id == 2
          strategy = UploadStrategy.initialize_with_cli(setting)
        elsif action_id == 3
          strategy = CopyStrategy.initialize_with_cli(setting)
        elsif action_id == 4
          strategy = RemoveStrategy.initialize_with_cli(setting)
        else
          abort '入力値が不正です'
        end
        strategy.execute
      rescue S3Strategy::InvalidParameter, S3Strategy::DataNotFound, S3Strategy::DataAlreadyExists => e
        puts e.message
        exit
      end
    end
  end
end


text:
#pragma once
#ifndef OGLPLUS_VERTEX_ATTRIB_1107121519_HPP
#define OGLPLUS_VERTEX_ATTRIB_1107121519_HPP

#include <oglplus/fwd.hpp>
#include <oglplus/config.hpp>
#include <oglplus/glfunc.hpp>
#include <oglplus/error.hpp>
#include <oglplus/friend_of.hpp>
#include <oglplus/program.hpp>
#include <oglplus/data_type.hpp>
#include <oglplus/limited_value.hpp>
#include <oglplus/auxiliary/shader_data.hpp>

#include <oglplus/string.hpp>

#include <type_traits>

namespace oglplus {

#if OGLPLUS_DOCUMENTATION_ONLY
/// Type for the vertex attribute slot (implementation-dependent limited) number
/**
 *  @see VertexAttrib
 *
 *  @ingroup shader_variables
 */
class VertexAttribSlot
 : public LimitedCount
{
public:
	VertexAttribSlot(GLuint count);
};
#else
OGLPLUS_DECLARE_LIMITED_COUNT_TYPE(
	VertexAttribSlot,
	MAX_VERTEX_ATTRIBS
)
#endif

/// Helper class that encapsulates vertex attribute functionality
/**
 *  @note Do not use this class directly, use VertexAttrib instead.
 *
 *  @see VertexAttrib
 *
 *  @ingroup shader_variables
 */
class VertexAttribOps
 : public FriendOf<ProgramOps>
{
protected:
	GLint _location;

	friend class FriendOf<VertexAttribOps>;

	VertexAttribOps(VertexAttribSlot i)
	 : _location(GLint(i))
	{ }

	static GLint _get_location(
		const ProgramOps& program,
		const GLchar* identifier
	)
	{
		return OGLPLUS_GLFUNC(GetAttribLocation)(
			FriendOf<ProgramOps>::GetName(program),
			identifier
		);
	}

	static void _handle_inactive(
		const ProgramOps& program,
		const GLchar* identifier,
		GLint result
	);

	static GLint _find_location(
		const ProgramOps& program,
		const GLchar* identifier
	)
	{
		GLint result = _get_location(program, identifier);
		OGLPLUS_CHECK(OGLPLUS_ERROR_INFO(GetAttribLocation));
		if(OGLPLUS_IS_ERROR(result == GLint(-1)))
		{
			_handle_inactive(program, identifier, result);
		}
		return result;
	}

	static bool _query_location(
		const ProgramOps& program,
		const String& identifier,
		VertexAttribSlot& location
	)
	{
		GLint result = _get_location(program, identifier.c_str());
		if(OGLPLUS_GLFUNC(GetError)() != GL_NO_ERROR)
			return false;
		if(result < 0) return false;
		location = result;
		return true;
	}

	template <typename Iterator>
	static bool _query_common_location(
		Iterator pprogram_begin,
		Iterator pprogram_end,
		const GLchar* identifier,
		VertexAttribSlot& location
	)
	{
		Iterator i=pprogram_begin, e=pprogram_end;
		if(i != e)
		{
			const ProgramOps* pprog = *i;
			assert(pprog);
			const ProgramOps& prog = *pprog;
			if(!_query_location(prog, identifier, location))
				return false;
			const VertexAttribSlot prev_loc(location);
			while(++i != e)
			{
				if(!_query_location(prog, identifier, location))
					return false;
				if(prev_loc != location)
					return false;
			}
			return true;
		}
		return false;
	}

	static void _handle_inconsistent_location(
		const GLchar* identifier,
		VertexAttribSlot location
	);

	template <typename Iterator>
	static VertexAttribSlot _get_common_location(
		Iterator pprogram_begin,
		Iterator pprogram_end,
		const GLchar* identifier
	)
	{
		VertexAttribSlot location;
		if(OGLPLUS_IS_ERROR(!_query_common_location(
			pprogram_begin,
			pprogram_end,
			identifier,
			location
		)))
		{
			_handle_inconsistent_location(identifier, location);
		}
		return location;
	}

	class _common_location_query
	{
	private:
		const GLchar* _identifier;
		VertexAttribSlot& _location;
		bool _first, _ok;

		_common_location_query(
			const GLchar* identifier,
			VertexAttribSlot& location,
			bool ok
		): _identifier(identifier)
		 , _location(location)
		 , _first(false)
		 , _ok(ok)
		{ }

	public:
		_common_location_query(
			const GLchar* identifier,
			VertexAttribSlot& location
		): _identifier(identifier)
		 , _location(location)
		 , _first(true)
		 , _ok(true)
		{ }

		_common_location_query In(const ProgramOps& prog) const
		{
			return _common_location_query(
				_identifier,
				_location,
				_ok && VertexAttribOps::_query_location(
					prog,
					_identifier,
					_location
				)
			);
		}

		_common_location_query And(const ProgramOps& prog) const
		{
			return In(prog);
		}

		operator bool (void) const
		{
			return !_first && _ok;
		}
	};

	// Functions for autodetection of values-per-vertex
	template <typename T>
	static GLint _get_values_per_vertex(T*)
	{
		return 1;
	}

	template <typename T, std::size_t N>
	static GLint _get_values_per_vertex(Vector<T, N>*)
	{
		return N;
	}

	template <typename T, std::size_t Rows, std::size_t Cols>
	static GLint _get_values_per_vertex(Matrix<T, Rows, Cols>*)
	{
		return Rows*Cols;
	}

	// Functions for autodetection of element type
	template <typename T>
	static T _get_element_type(T* p);

	template <typename T, std::size_t N>
	static T _get_element_type(Vector<T, N>*);

	template <typename T, std::size_t Rows, std::size_t Cols>
	static T _get_element_type(Matrix<T, Rows, Cols>*);

	VertexAttribOps(const ProgramOps& program, const GLchar* identifier)
	 : _location(_find_location(program, identifier))
	{ }
public:
	/// Returns the location of this vertex attribute in a program
	/**
	 *
	 *  @see GetLocation
	 *  @see GetCommonLocation
	 *  @see QueryLocation
	 *  @see BindLocation
	 *
	 *  @glsymbols
	 *  @glfunref{GetAttribLocation}
	 */
	VertexAttribSlot Location(void) const
	{
		return VertexAttribSlot(_location);
	}

	static VertexAttribSlot GetLocation(
		const ProgramOps& program,
		const GLchar* identifier
	)
	{
		return VertexAttribSlot(_find_location(
			program,
			identifier
		));
	}

	/// Finds the vertex attribute location, throws on failure
	/** Finds the location of the input vertex attribute specified
	 *  by @p identifier in a @p program. Throws if no such attribute
	 *  exists or if it is not active. For a non-throwing version
	 *  see QueryLocation().
	 *
	 *  @see GetCommonLocation
	 *  @see QueryLocation
	 *  @see BindLocation
	 *
	 *  @glsymbols
	 *  @glfunref{GetAttribLocation}
	 */
	static VertexAttribSlot GetLocation(
		const ProgramOps& program,
		const String& identifier
	)
	{
		return VertexAttribSlot(_find_location(
			program,
			identifier.c_str()
		));
	}

#if OGLPLUS_DOCUMENTATION_ONLY || !OGLPLUS_NO_VARIADIC_TEMPLATES
	/// Returns vertex attr. location in multiple programs if it's consistent
	/** Finds the location of the input vertex attribute specified
	 *  by @p identifier in every program in @p programs.
	 *  Throws Error if no such attribute exists or if it is not active
	 *  in some of the programs or if the attribute has different locations
	 *  in different programs. Otherwise returns the vertex attribute
	 *  position.
	 *
	 *  @code
	 *  VertexArray vao;
	 *  Buffer buf;
	 *  Program prog1, prog2, prog3;
	 *  // build the programs, load data into the buffer, ...
	 *  vao.Bind();
	 *  buffer.Bind(Buffer::Target::Array);
	 *  try
	 *  {
	 *      VertexAttribArray attr(
	 *          VertexAttribOps::GetCommonLocation(
	 *              "Position",
	 *              prog1,
	 *              prog2,
	 *              prog3
	 &          )
	 *      );
	 *      attr.Setup(n_per_vertex, DataType::Float);
	 *      attr.Enable();
	 *  }
	 *  catch(Error& error)
	 *  {
	 *      // handle the error or bind the locations manually
	 *  }
	 *
	 *  @endcode
	 *
	 *  @see GetLocation
	 *  @see GetCommonLocation
	 *  @see QueryLocation
	 *  @see BindLocation
	 *
	 *  @glsymbols
	 *  @glfunref{GetAttribLocation}
	 */
	template <typename ... ProgramOps_>
	static VertexAttribSlot GetCommonLocation(
		const GLchar* identifier,
		const ProgramOps & program,
		const ProgramOps_& ... programs
	)
	{
		const ProgramOps* pprogs[] = {
			&program,
			&programs...
		};
		return _get_common_location(
			pprogs,
			pprogs+1+sizeof...(programs),
			identifier
		);
	}
#else
	static VertexAttribSlot GetCommonLocation(
		const GLchar* identifier,
		const ProgramOps& program1,
		const ProgramOps& program2
	)
	{
		const ProgramOps* pprogs[] = {
			&program1,
			&program2
		};
		return _get_common_location(
			pprogs,
			pprogs+2,
			identifier
		);
	}

	static VertexAttribSlot GetCommonLocation(
		const GLchar* identifier,
		const ProgramOps& program1,
		const ProgramOps& program2,
		const ProgramOps& program3
	)
	{
		const ProgramOps* pprogs[] = {
			&program1,
			&program2,
			&program3
		};
		return _get_common_location(
			pprogs,
			pprogs+3,
			identifier
		);
	}
#endif

	static bool QueryLocation(
		const ProgramOps& program,
		const GLchar* identifier,
		VertexAttribSlot& location
	)
	{
		return _query_location(program, identifier, location);
	}

	/// Queries the vertex attribute @p location in a program
	/** Finds the @p location of the input vertex attribute specified
	 *  by @p identifier in a @p program. Returns false if no such attribute
	 *  exists or if it is not active, otherwise stores the vertex attribute
	 *  position in @p location and returns true.
	 *  For a throwing version see GetLocation().
	 *
	 *  @see GetLocation
	 *  @see GetCommonLocation
	 *  @see QueryCommonLocation
	 *  @see BindLocation
	 *
	 *  @glsymbols
	 *  @glfunref{GetAttribLocation}
	 */
	static bool QueryLocation(
		const ProgramOps& program,
		const String& identifier,
		VertexAttribSlot& location
	)
	{
		return _query_location(program, identifier.c_str(), location);
	}

	static _common_location_query QueryCommonLocation(
		const GLchar* identifier,
		VertexAttribSlot& location
	)
	{
		return _common_location_query(identifier, location);
	}

	/// Allows to query the vertex attribute @p location in multiple programs
	/** This function returns a temporary object that allows to query
	 *  the @p location of the specified @p identifier in several programs.
	 *  The returned object has two functions called @c In and @c And
	 *  which are equivalent and take a Program as the argument. Both
	 *  these functions return in turn a new instance of the temporary
	 *  which allows to check in another program, and so on.
	 *  The temporary is also convertible to @c bool indicating whether
	 *  a common location was found in all programs in the chain.
	 *
	 *  @code
	 *  VertexArray vao;
	 *  Buffer buf;
	 *  Program prog1, prog2, prog3, prog4;
	 *  // build the programs, load data into the buffer, ...
	 *  vao.Bind();
	 *  buffer.Bind(Buffer::Target::Array);
	 *  VertexAttribSlot loc;
	 *  if(VertexAttribOps::QueryCommonLocation("Pos", loc)
	 *	.In(prog1).In(prog2).In(prog3).And(prog4)
	 *  )
	 *  {
	 *      VertexAttribArray attr(location);
	 *      attr.Setup(n_per_vertex, DataType::Float);
	 *      attr.Enable();
	 *  }
	 *  else
	 *  {
	 *      // handle the error or bind the locations manually
	 *  }
	 *  @endcode
	 *
	 *  @note Never store the resulting object in a named variable
	 *  nor use it after the call to this overload of QueryCommonLocation
	 *  has finished. Doing this causes undefined behavior.
	 *
	 *  @see GetLocation
	 *  @see GetCommonLocation
	 *  @see QueryLocation
	 *  @see BindLocation
	 *
	 *  @glsymbols
	 *  @glfunref{GetAttribLocation}
	 */
	static _common_location_query QueryCommonLocation(
		const String& identifier,
		VertexAttribSlot& location
	)
	{
		return _common_location_query(identifier.c_str(), location);
	}

#if OGLPLUS_DOCUMENTATION_ONLY || !OGLPLUS_NO_VARIADIC_TEMPLATES
	/// Queries the vertex attribute @p location in multiple programs
	/** Finds the @p location of the input vertex attribute specified
	 *  by @p identifier in every program in @p programs.
	 *  Returns false if no such attribute exists or if it is not active
	 *  in some of the programs or if the attribute has different locations
	 *  in different programs. Otherwise stores the vertex attribute
	 *  position in @p location and returns true.
	 *
	 *  @see GetLocation
	 *  @see GetCommonLocation
	 *  @see QueryLocation
	 *  @see BindLocation
	 *
	 *  @glsymbols
	 *  @glfunref{GetAttribLocation}
	 */
	template <typename ... ProgramOps_>
	static bool QueryCommonLocation(
		const GLchar* identifier,
		VertexAttribSlot& location,
		const ProgramOps & program,
		const ProgramOps_& ... programs
	)
	{
		const ProgramOps* pprogs[] = {
			&program,
			&programs...
		};
		return _query_common_location(
			pprogs,
			pprogs+1+sizeof...(programs),
			identifier,
			location
		);
	}
#else
	static bool QueryCommonLocation(
		const GLchar* identifier,
		VertexAttribSlot& location,
		const ProgramOps& program1,
		const ProgramOps& program2
	)
	{
		const ProgramOps* pprogs[] = {
			&program1,
			&program2
		};
		return _query_common_location(
			pprogs,
			pprogs+2,
			identifier,
			location
		);
	}

	static bool QueryCommonLocation(
		const GLchar* identifier,
		VertexAttribSlot& location,
		const ProgramOps& program1,
		const ProgramOps& program2,
		const ProgramOps& program3
	)
	{
		const ProgramOps* pprogs[] = {
			&program1,
			&program2,
			&program3
		};
		return _query_common_location(
			pprogs,
			pprogs+3,
			identifier,
			location
		);
	}
#endif

	void BindLocation(
		const ProgramOps& program,
		const GLchar* identifier
	) const
	{
		OGLPLUS_GLFUNC(BindAttribLocation)(
			FriendOf<ProgramOps>::GetName(program),
			_location,
			identifier
		);
		OGLPLUS_CHECK(OGLPLUS_ERROR_INFO(BindAttribLocation));
	}

	/// Bind the vertex attribute location
	/**
	 *  @see GetLocation
	 *  @see QueryLocation
	 *
	 *  @glsymbols
	 *  @glfunref{BindAttribLocation}
	 */
	void BindLocation(
		const ProgramOps& program,
		const String& identifier
	) const
	{
		OGLPLUS_GLFUNC(BindAttribLocation)(
			FriendOf<ProgramOps>::GetName(program),
			_location,
			identifier.c_str()
		);
		OGLPLUS_CHECK(OGLPLUS_ERROR_INFO(BindAttribLocation));
	}

#if OGLPLUS_DOCUMENTATION_ONLY || GL_VERSION_3_3
	/// Set the vertex attrib divisor
	/**
	 *  @glverreq{3,3}
	 *  @glsymbols
	 *  @glfunref{VertexAttribDivisor}
	 */
	void Divisor(GLuint divisor) const
	{
		OGLPLUS_GLFUNC(VertexAttribDivisor)(
			_location,
			divisor
		);
		OGLPLUS_CHECK(OGLPLUS_ERROR_INFO(VertexAttribDivisor));
	}
#endif
};

// Things from to Program related to vertex attributes
void ProgramOps::BindLocation(
	const VertexAttribOps& vertex_attrib,
	const GLchar* identifier
) const
{
	OGLPLUS_GLFUNC(BindAttribLocation)(
		_name,
		FriendOf<VertexAttribOps>::GetLocation(vertex_attrib),
		identifier
	);
	OGLPLUS_CHECK(OGLPLUS_ERROR_INFO(BindAttribLocation));
}

namespace aux {

class VertexAttribSetters
{
protected:
	OGLPLUS_ERROR_INFO_CONTEXT(VertexAttrib, VertexAttrib)

	OGLPLUS_AUX_VARPARA_FNS(VertexAttrib, f, t, GLfloat)
#if OGLPLUS_DOCUMENTATION_ONLY || GL_VERSION_3_0
	OGLPLUS_AUX_VARPARA_FNS(VertexAttrib, d, t, GLdouble)
	OGLPLUS_AUX_VARPARA_FNS(VertexAttrib, s, t, GLshort)

	OGLPLUS_AUX_VARPARA_FNS(VertexAttribI, i, t, GLint)
	OGLPLUS_AUX_VARPARA_FNS(VertexAttribI, ui, t, GLuint)
#endif

	OGLPLUS_AUX_VARPARA_FNS(VertexAttrib, fv, v, GLfloat)
#if OGLPLUS_DOCUMENTATION_ONLY || GL_VERSION_3_0
	OGLPLUS_AUX_VARPARA_FNS(VertexAttrib, dv, v, GLdouble)
	OGLPLUS_AUX_VARPARA_FNS(VertexAttrib, sv, v, GLshort)

	OGLPLUS_AUX_VARPARA_FNS(VertexAttribI, i, v, GLint)
	OGLPLUS_AUX_VARPARA_FNS(VertexAttribI, ui, v, GLuint)
#endif
};

} // namespace aux

/// Encapsulates vertex attribute functionality
/**
 *  @ingroup shader_variables
 */
template <typename T>
class VertexAttrib
 : public VertexAttribOps
#if OGLPLUS_DOCUMENTATION_ONLY
 , public Unspecified
#else
 , public aux::ShaderDataSetOps<
	aux::VertexAttribSetters,
	aux::ActiveProgramCallOps<T>,
	16
>
#endif
{
public:
	/// References the vertex attribute array at @p location
	/**
	 *  @glsymbols
	 *  @glfunref{GetAttribLocation}
	 */
	VertexAttrib(VertexAttribSlot location)
	 : VertexAttribOps(location)
	{ }

	/// References the vertex attribute @p identifier of the @p program
	/**
	 *  @glsymbols
	 *  @glfunref{GetAttribLocation}
	 */
	VertexAttrib(const ProgramOps& program, const GLchar* identifier)
	 : VertexAttribOps(program, identifier)
	{ }

	/// References the vertex attribute @p identifier of the @p program
	VertexAttrib(const ProgramOps& program, const String& identifier)
	 : VertexAttribOps(program, identifier.c_str())
	{ }

	/// Set the value of the vertex attribute
	/**
	 *  @glsymbols
	 *  @glfunref{VertexAttrib}
	 */
	void Set(T value) const
	{
		this->_do_set(0, _location, value);
	}

	/// Set the value of the vertex attribute
	/**
	 *  @glsymbols
	 *  @glfunref{VertexAttrib}
	 */
	inline void operator = (T value) const
	{
		Set(value);
	}
};

template <typename T, std::size_t N>
class VertexAttrib<Vector<T, N> >
 : public VertexAttribOps
 , public aux::ShaderDataSetOps<
	aux::VertexAttribSetters,
	aux::ActiveProgramCallOps<T>,
	4
>
{
public:
	/// References the vertex attribute array at @p location
	/**
	 *  @glsymbols
	 *  @glfunref{GetAttribLocation}
	 */
	VertexAttrib(VertexAttribSlot location)
	 : VertexAttribOps(location)
	{ }

	/// References the vertex attribute @p identifier of the @p program
	/**
	 *  @glsymbols
	 *  @glfunref{GetAttribLocation}
	 */
	VertexAttrib(const ProgramOps& program, const GLchar* identifier)
	 : VertexAttribOps(program, identifier)
	{ }

	/// References the vertex attribute @p identifier of the @p program
	VertexAttrib(const ProgramOps& program, const String& identifier)
	 : VertexAttribOps(program, identifier.c_str())
	{ }

	/// Set the vector value of the vertex attribute
	/**
	 *  @glsymbols
	 *  @glfunref{VertexAttrib}
	 */
	void Set(const Vector<T, N>& value) const
	{
		this->template _do_set<N>(0, _location, Data(value));
	}

	/// Set the vector value of the vertex attribute
	/**
	 *  @glsymbols
	 *  @glfunref{VertexAttrib}
	 */
	inline void operator = (const Vector<T, N>& value) const
	{
		Set(value);
	}
};

template <typename T, std::size_t Rows, std::size_t Cols>
class VertexAttrib<Matrix<T, Rows, Cols> >
 : public VertexAttribOps
 , public aux::ShaderDataSetOps<
	aux::VertexAttribSetters,
	aux::ActiveProgramCallOps<T>,
	16
>
{
public:
	/// References the vertex attribute array at @p location
	/**
	 *  @glsymbols
	 *  @glfunref{GetAttribLocation}
	 */
	VertexAttrib(VertexAttribSlot location)
	 : VertexAttribOps(location)
	{ }

	/// References the vertex attribute @p identifier of the @p program
	/**
	 *  @glsymbols
	 *  @glfunref{GetAttribLocation}
	 */
	VertexAttrib(const ProgramOps& program, const GLchar* identifier)
	 : VertexAttribOps(program, identifier)
	{ }

	/// References the vertex attribute @p identifier of the @p program
	VertexAttrib(const ProgramOps& program, const String& identifier)
	 : VertexAttribOps(program, identifier.c_str())
	{ }

	/// Set the matrix value of the vertex attribute
	/**
	 *  @glsymbols
	 *  @glfunref{VertexAttrib}
	 */
	void Set(const Matrix<T, Rows, Cols>& value) const
	{
		this->template _do_set<Rows*Cols>(0, _location, Data(value));
	}

	/// Set the matrix value of the vertex attribute
	/**
	 *  @glsymbols
	 *  @glfunref{VertexAttrib}
	 */
	inline void operator = (const Matrix<T, Rows, Cols>& value) const
	{
		Set(value);
	}
};

/// Encapsulates vertex attribute array functionality
/**
 *  @ingroup shader_variables
 */
class VertexAttribArray
 : public VertexAttribOps
{
private:
public:
	/// References the vertex attribute array at @p location
	/**
	 *  @glsymbols
	 *  @glfunref{GetAttribLocation}
	 */
	VertexAttribArray(VertexAttribSlot location)
	 : VertexAttribOps(location)
	{ }

	/// References the vertex attrib array @p identifier of the @p program
	/**
	 *  @glsymbols
	 *  @glfunref{GetAttribLocation}
	 */
	VertexAttribArray(const ProgramOps& program, const GLchar* identifier)
	 : VertexAttribOps(program, identifier)
	{ }

	/// References the vertex attrib array @p identifier of the @p program
	/**
	 *  @glsymbols
	 *  @glfunref{GetAttribLocation}
	 */
	VertexAttribArray(const ProgramOps& program, const String& identifier)
	 : VertexAttribOps(program, identifier.c_str())
	{ }

	/// Setup the properties of this vertex attribute array
	/** Equivalent to
	 *  @code
	 *  Pointer(valuer_per_vertex, data_type, false, 0, NULL)
	 *  @endcode
	 *  if @p data_type is DataType::Float or to
	 *  @code
	 *  LPointer(valuer_per_vertex, data_type, 0, NULL)
	 *  @endcode
	 *  if @p data_type is DataType::Double or to
	 *  @code
	 *  IPointer(valuer_per_vertex, data_type, 0, NULL)
	 *  @endcode
	 *  otherwise.
	 *
	 *  @note Consider using the templated version of Setup(), because
	 *  it is more portable. For example instead of:
	 *  @code
	 *  attr.Setup(3, DataType::Float);
	 *  @endcode
	 *  use
	 *  @code
	 *  attr.Setup<Vec3f>();
	 *  @endcode
	 *  or
	 *  @code
	 *  attr.Setup<GLfloat>(3);
	 *  @endcode
	 *
	 *  @see Pointer
	 *  @see IPointer
	 *  @see LPointer
	 *
	 *  @glsymbols
	 *  @glfunref{VertexAttribPointer}
	 */
	const VertexAttribArray& Setup(
		GLint values_per_vertex,
		DataType data_type
	) const
	{
		if(data_type == DataType::Float)
		{
			Pointer(
				values_per_vertex,
				data_type,
				false,
				0,
				nullptr
			);
		}
#ifdef GL_DOUBLE
		else if(data_type == DataType::Double)
		{
			LPointer(
				values_per_vertex,
				data_type,
				0,
				nullptr
			);
		}
#endif
		else
		{
			IPointer(
				values_per_vertex,
				data_type,
				0,
				nullptr
			);
		}
		return *this;
	}

	const VertexAttribArray& Setup(
		GLint values_per_vertex,
		std::integral_constant<
			typename enums::EnumValueType<DataType>::Type,
			OGLPLUS_CONST_ENUM_VALUE(DataType::Float)
		>
	) const
	{
		return Pointer(
			values_per_vertex,
			DataType::Float,
			false,
			0,
			nullptr
		);
	}

#ifdef GL_DOUBLE
	const VertexAttribArray& Setup(
		GLint values_per_vertex,
		std::integral_constant<
			typename enums::EnumValueType<DataType>::Type,
			OGLPLUS_CONST_ENUM_VALUE(DataType::Double)
		>
	) const
	{
		return LPointer(
			values_per_vertex,
			DataType::Double,
			0,
			nullptr
		);
	}
#endif

	template <
		typename enums::EnumValueType<DataType>::Type DataTypeValue
	>
	const VertexAttribArray& Setup(
		GLint values_per_vertex,
		std::integral_constant<
			typename enums::EnumValueType<DataType>::Type,
			DataTypeValue
		>
	) const
	{
		return IPointer(
			values_per_vertex,
			DataTypeValue,
			0,
			nullptr
		);
	}

	/// Setup the properties of this vertex attribute array
	/**
	 *  @see Pointer
	 *  @see IPointer
	 *  @see LPointer
	 *
	 *  @glsymbols
	 *  @glfunref{VertexAttribPointer}
	 */
	template <typename T>
	const VertexAttribArray& Setup(GLuint n = 1) const
	{
		typedef decltype(_get_element_type((T*)nullptr)) elem_type;

		return Setup(
			_get_values_per_vertex((T*)nullptr)*n,
			typename DataTypeCT<elem_type>::type()
		);
	}

	/// Setup the properties of this vertex attribute array
	/**
	 *  @glsymbols
	 *  @glfunref{VertexAttribPointer}
	 */
	const VertexAttribArray& Pointer(
		GLint values_per_vertex,
		DataType data_type,
		bool normalized,
		GLsizei stride,
		const void* pointer
	) const
	{
		OGLPLUS_GLFUNC(VertexAttribPointer)(
			_location,
			values_per_vertex,
			GLenum(data_type),
			normalized ? GL_TRUE : GL_FALSE,
			stride,
			pointer
		);
		OGLPLUS_CHECK(OGLPLUS_ERROR_INFO(VertexAttribPointer));
		return *this;
	}

	/// Setup the properties of this vertex attribute array
	/**
	 *  @glsymbols
	 *  @glfunref{VertexAttribPointer}
	 */
	const VertexAttribArray& IPointer(
		GLuint values_per_vertex,
		DataType data_type,
		GLsizei stride,
		const void* pointer
	) const
	{
		OGLPLUS_GLFUNC(VertexAttribIPointer)(
			_location,
			values_per_vertex,
			GLenum(data_type),
			stride,
			pointer
		);
		OGLPLUS_CHECK(OGLPLUS_ERROR_INFO(VertexAttribIPointer));
		return *this;
	}

	/// Setup the properties of this vertex attribute array
	/**
	 *  @glsymbols
	 *  @glfunref{VertexAttribPointer}
	 */
	const VertexAttribArray& LPointer(
		GLuint values_per_vertex,
		DataType data_type,
		GLsizei stride,
		const void* pointer
	) const
	{
#if GL_VERSION_4_2 || GL_ARB_vertex_attrib_64bit
		OGLPLUS_GLFUNC(VertexAttribLPointer)(
			_location,
			values_per_vertex,
			GLenum(data_type),
			stride,
			pointer
		);
		OGLPLUS_CHECK(OGLPLUS_ERROR_INFO(VertexAttribLPointer));
#else
		OGLPLUS_FAKE_USE(values_per_vertex);
		OGLPLUS_FAKE_USE(data_type);
		OGLPLUS_FAKE_USE(stride);
		OGLPLUS_FAKE_USE(pointer);
		assert(!
			"The glVertexAttribLPointer function is "
			"required but not available! Double-precision "
			"vertex attribute values are not supported."
		);
#endif
		return *this;
	}

#if OGLPLUS_DOCUMENTATION_ONLY || GL_VERSION_4_3 || GL_ARB_vertex_attrib_binding
	/// Setup the format of this vertex attribute array
	/**
	 *  @glsymbols
	 *  @glfunref{VertexAttribFormat}
	 */
	const VertexAttribArray& Format(
		GLint values_per_vertex,
		DataType data_type,
		bool normalized,
		GLuint relative_offset
	) const
	{
		OGLPLUS_GLFUNC(VertexAttribFormat)(
			_location,
			values_per_vertex,
			GLenum(data_type),
			normalized ? GL_TRUE : GL_FALSE,
			relative_offset
		);
		OGLPLUS_CHECK(OGLPLUS_ERROR_INFO(VertexAttribFormat));
		return *this;
	}

	/// Setup the format of this vertex attribute array
	/**
	 *  @glsymbols
	 *  @glfunref{VertexAttribIFormat}
	 */
	const VertexAttribArray& IFormat(
		GLint values_per_vertex,
		DataType data_type,
		GLuint relative_offset
	) const
	{
		OGLPLUS_GLFUNC(VertexAttribIFormat)(
			_location,
			values_per_vertex,
			GLenum(data_type),
			relative_offset
		);
		OGLPLUS_CHECK(OGLPLUS_ERROR_INFO(VertexAttribIFormat));
		return *this;
	}

	/// Setup the format of this vertex attribute array
	/**
	 *  @glsymbols
	 *  @glfunref{VertexAttribLFormat}
	 */
	const VertexAttribArray& LFormat(
		GLint values_per_vertex,
		DataType data_type,
		GLuint relative_offset
	) const
	{
		OGLPLUS_GLFUNC(VertexAttribLFormat)(
			_location,
			values_per_vertex,
			GLenum(data_type),
			relative_offset
		);
		OGLPLUS_CHECK(OGLPLUS_ERROR_INFO(VertexAttribLFormat));
		return *this;
	}
#endif

	/// Enables this vertex attribute array
	/**
	 *  @glsymbols
	 *  @glfunref{EnableVertexAttribArray}
	 */
	const VertexAttribArray& Enable(void) const
	{
		OGLPLUS_GLFUNC(EnableVertexAttribArray)(_location);
		OGLPLUS_VERIFY(OGLPLUS_ERROR_INFO(EnableVertexAttribArray));
		return *this;
	}

	/// Disables this vertex attribute array
	/**
	 *  @glsymbols
	 *  @glfunref{DisableVertexAttribArray}
	 */
	const VertexAttribArray& Disable(void) const
	{
		OGLPLUS_GLFUNC(DisableVertexAttribArray)(_location);
		OGLPLUS_VERIFY(OGLPLUS_ERROR_INFO(DisableVertexAttribArray));
		return *this;
	}
};

/// Syntax sugar for construction of a VertexAttribArray object
/** Constructs an instance of VertexAttribArray for a vertex attribute
 *  identified by @p identifier in a @p program.
 *
 *  @see VertexAttribArray
 */
template <std::size_t N>
inline VertexAttribArray operator | (
	const ProgramOps& program,
	const GLchar (&identifier)[N]
)
{
	return VertexAttribArray(program, identifier);
}

/// Syntax sugar for construction of a VertexAttribArray object
/** Constructs an instance of VertexAttribArray for a vertex attribute
 *  at the specified @p location in a @p program.
 *
 *  @see VertexAttribArray
 */
inline VertexAttribArray operator | (
	const ProgramOps& program,
	GLuint location
)
{
	OGLPLUS_FAKE_USE(program);
	return VertexAttribArray(VertexAttribSlot(location));
}

} // namespace oglplus

#if !OGLPLUS_LINK_LIBRARY || defined(OGLPLUS_IMPLEMENTING_LIBRARY)
#include <oglplus/vertex_attrib.ipp>
#endif

#endif // include guard

redpajama_set_name: RedPajamaGithub


text:
This project is created to play with Arduino and IoT solutions.
It should help in watering plants at home to keep them full of life.
Current implmentation checks soil moisture once every 4 hours and show it's level using 3 LED diods.

## CHANGE LOG

### Added Temperature and Moisture sensor DHT21 12.01.2018 (2nd note)

Testing new sensor.

### Fixed SLEEP_TIME 12.01.2018

I used int which maximum value is 32767 and it's not enough for 4 hours.
delay() function takes long parameter (not int) so I changed SLEEP_TIME to long.

### Resolving sensor problem 05.01.2018

Moisture sensor is repleaced with different one.
The sensor VCC is now powered by digital pin 9.
After 4 hours of sleep the sensor is turned on, then it waits 3 seconds to stabilize power and read analog value of moisture.
I'll see if it resolves the problem.

### Sensor problem 10.07.2017

Current implementation was working for 5 days.
After that time one leg of the moisture sensor had destroyed because of continued work.
Probalby because of the electrolysis?

Possible solution:
Power should be turned on only for measurment purposes, and measurment should be prepared once a while (eg. 1 hour).

### Project Started 05.07.2017


text:
function addHTMLSpaces(text) {
  let nbsp = '\u00A0';
  return text.replace(/  /g, ' ' + nbsp);
}

export function createTextNode(dom, text) {
  return dom.createTextNode(addHTMLSpaces(text));
}

export function normalizeTagName(tagName) {
  return tagName.toLowerCase();
}


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W29166_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans12.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">CONFIDENTIAL: FILED AS A PART OF AN APD
STATE OF NORTH DAKOTA§
§ COUNTY OF WARD §

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">AFFIDAVIT TO THE PUBLIC

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Before me. the undersigned authority, on this day personally appeared Eric Rolli, as Facilities Engineering Team Lead for Hess Bakken Investments 11, LLC, with an address of 3015 16lll Street SW, #20, Minot, North Dakota 58701 ("Hess"), who, afier being by me duly sworn,
upon oath states:
In conjunction with Hess' submission of the SC-Norma/Gene Gas Capture Plan ("GCP") to the Oil and Gas Division of the North Dakota Industrial Commission, Hess representatives communicated with Cathey Benefield of Hiland Partners, LP (the "Gas Gatherer") and provided Gas Gatherer with the anticipated completion dates and anticipated production rates of the following wells: SC-Norma-l54-98-0706H-6, SC-Norma-l54-98-07061'1-7. SC-Nonna-lS4-980706H-8, SC-Nonna-LE-l54-98-0706H-1, SC-Norma-LE-l54-98-0705H-2, SC-Gcnc-154-980805H-2.

    <p class="styleSans21.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Executed this /7*" day of July , 2011

    <p class="styleSans33.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">4' fl
Eric Rolli

    <p class="styleSans14.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">SUBSCRIBED AND SWORN TO before me, the undersigned authority, b'y_Eric Rolli, as

    <p class="styleSans30.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Facilities Engineering Team Lead for Hess Bakken Investments 11, LLC on this I 2 day
ELF 20/_'/.

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">of

    <p class="styleSans47.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">
ADAM LANDSTROM Notary Public State of North Dakota My Commission Expires Septembel 20. 2018

    <p class="styleSans21.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">: Notary Public, State of in; g


text:
using System;
using System.Windows;
using System.Windows.Interop;

namespace MO.Editor.Scene.Console.Face
{
   //============================================================
   // <T>控制台窗口。</T>
   //
   // @history MAOCY 140424
   //============================================================
   public partial class WConsoleWindow : Window
   {
      // 消息定义
      private const int WM_NCHITTEST = 0x0084;

      //============================================================
      // <T>构造控制台窗口。</T>
      //============================================================
      public WConsoleWindow() {
         InitializeComponent();
      }

      //============================================================
      // <T>启动窗口。</T>
      //============================================================
      private void Window_Loaded(object sender, RoutedEventArgs e) {
         // 添加一个消息过滤器
         IntPtr hwnd = new WindowInteropHelper(this).Handle;
         HwndSource.FromHwnd(hwnd).AddHook(new HwndSourceHook(WindowHandleProcess));
      }

      //============================================================
      // <T>卸载窗口。</T>
      //============================================================
      private void Window_Unloaded(object sender, RoutedEventArgs e) {
      }

      //============================================================
      // <T>关闭处理。</T>
      //============================================================
      private void CloseButton_Click(object sender, RoutedEventArgs e) {
         Window_Unloaded(sender, e) ;
         Close();
         Application.Current.Shutdown();
      }

      //============================================================
      // <T>测试是否窗口栏。</T>
      //
      // @return 是否窗口栏
      //============================================================
      private bool isOnTitleBar(Point position) {
         // 检查位置
         Point titleStart = pnlTitle.TranslatePoint(new Point(0, 0), this);
         Point titleStop = pnlTitle.TranslatePoint(new Point(pnlTitle.ActualWidth, pnlTitle.ActualHeight), this);
         if((position.X < titleStart.X) || (position.X > titleStop.X) || (position.Y < titleStart.Y) || (position.Y > titleStop.Y)) {
            return false;
         }
         // 在图标区
         Point imageStart = imgTitle.TranslatePoint(new Point(), this);
         Point imageStop = imgTitle.TranslatePoint(new Point(imgTitle.ActualWidth, imgTitle.ActualHeight), this);
         if((position.X >= imageStart.X) && (position.X <= imageStop.X) && (position.Y >= imageStart.Y) && (position.Y <= imageStop.Y)) {
            return true;
         }
         //// 在标题区
         //Point canvasStart = cvsTitle.TranslatePoint(new Point(), this);
         //Point canvasStop = cvsTitle.TranslatePoint(new Point(cvsTitle.ActualWidth, cvsTitle.ActualHeight), this);
         //if((position.X >= canvasStart.X) && (position.X <= canvasStop.X) && (position.Y >= canvasStart.Y) && (position.Y <= canvasStop.Y)) {
         //   return true;
         //}
         // 返回结果
         return false;
      }

      //============================================================
      // <T>窗口事件处理。</T>
      //============================================================
      private IntPtr WindowHandleProcess(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) {
         if (msg == WM_NCHITTEST) {
            // 获取屏幕坐标
            Point p = new Point();
            int pInt = lParam.ToInt32();
            p.X = (pInt << 16) >> 16;
            p.Y = pInt >> 16;
            if (isOnTitleBar(PointFromScreen(p))) {
               // 欺骗系统鼠标在标题栏上
               handled = true;
               return new IntPtr(2);
            }
         }
         return IntPtr.Zero;
      }
   }
}


text:
class RefIdMapping
{
public:
    String<unsigned> map;

    RefIdMapping() {}
};

// ============================================================================
// Metafunctions
// ============================================================================

// ============================================================================
// Functions
// ============================================================================

// ----------------------------------------------------------------------------
// Function length()
// ----------------------------------------------------------------------------

inline unsigned length(RefIdMapping const & mapping)
{
    return length(mapping.map);
}

// ----------------------------------------------------------------------------
// Function rebuildMapping()
// ----------------------------------------------------------------------------

template <typename TTargetNameStore, typename TTargetNameStoreCache, typename TSourceNameStore>
void rebuildMapping(RefIdMapping & mapping,
                    TTargetNameStore const & targetNameStore,
                    TTargetNameStoreCache const & targetNameStoreCache,
                    TSourceNameStore const & sourceNameStore)
{
    clear(mapping.map);
    resize(mapping.map, length(sourceNameStore), maxValue<unsigned>());

    for (unsigned i = 0; i < length(sourceNameStore); ++i)
    {
        unsigned idx = 0;
        if (getIdByName(targetNameStore, sourceNameStore[i], idx, targetNameStoreCache))
            mapping.map[i] = idx;
    }
}

#endif  // #ifndef SEQAN_APPS_RABEMA_REF_ID_MAPPING_H_


text:
from pants.build_graph.address import Address

class InjectablesMixin:
    """A mixin for classes (typically optionables) that require certain targets in order to
    function.

    :API: public
    """

    class NoMappingForKey(Exception):
        """Thrown when a mapping doesn't exist for a given injectables key."""

    class TooManySpecsForKey(Exception):
        """Thrown when a mapping contains multiple specs when a singular spec is expected."""

    def injectables(self, build_graph):
        """Given a `BuildGraph`, inject any targets required for this object to function.

        This function will be called just before `Target` injection time. Any objects injected here
        should have a static spec path that will need to be emitted, pre-injection, by the
        `injectables_specs` classmethod for the purpose of dependency association for e.g. `changed`.

        :API: public
        """

    @property
    def injectables_address_spec_mapping(self):
        """A mapping of {key: address_spec} that is used for locating injectable address specs.

        This should be overridden by subclasses who wish to define an injectables mapping.

        :API: public
        """
        return {}

    def injectables_address_specs_for_key(self, key):
        """Given a key, yield all relevant injectable address specs.

        :API: public
        """
        mapping = self.injectables_address_spec_mapping
        if key not in mapping:
            raise self.NoMappingForKey(key)
        address_specs = mapping[key]
        assert isinstance(address_specs, list), (
            'invalid `injectables_address_spec_mapping` on {!r} for key "{}". '
            "expected a `list` but instead found a `{}`: {}"
        ).format(self, key, type(address_specs), address_specs)
        return [Address.parse(s).spec for s in address_specs]

    def injectables_address_spec_for_key(self, key):
        """Given a key, yield a singular address spec representing that key.

        :API: public
        """
        address_specs = self.injectables_address_specs_for_key(key)
        specs_len = len(address_specs)
        if specs_len == 0:
            return None
        if specs_len != 1:
            raise self.TooManySpecsForKey(
                f"injectables address spec mapping for key included {specs_len} elements, expected 1"
            )
        return address_specs[0]


text:
require "thincloud/authentication/engine"

module Thincloud
  module Authentication
  end
end


text:
package registry

import (
	"context"
	"encoding/json"
	"errors"
	"net/url"

	"github.com/manifoldco/torus-cli/envelope"
	"github.com/manifoldco/torus-cli/identity"
	"github.com/manifoldco/torus-cli/primitive"
)

// ErrMemberNotFound is returned when a keyring member find call fails.
var ErrMemberNotFound = errors.New("keyring membership not found")

// KeyringClient represents the `/keyrings` registry end point for accessing
// keyrings the user or machine belong too.
type KeyringClient struct {
	client  RoundTripper
	Members *KeyringMembersClient
}

// KeyringSection is the shared interface between different KeyringSection
// versions.
type KeyringSection interface {
	GetKeyring() envelope.KeyringInf
	KeyringVersion() int
	FindMember(*identity.ID) (*primitive.KeyringMember, *primitive.MEKShare, error)
	FindMEKByKeyID(*identity.ID) (*primitive.MEKShare, error)
	HasRevocations() bool
	GetClaims() []envelope.KeyringMemberClaim
}

// KeyringSectionV1 represents a section of the CredentialGraph only pertaining to
// a keyring and it's membership.
type KeyringSectionV1 struct {
	Keyring *envelope.KeyringV1        `json:"keyring"`
	Members []envelope.KeyringMemberV1 `json:"members"`
}

// GetKeyring returns the Keyring object in this KeyringSection
func (k *KeyringSectionV1) GetKeyring() envelope.KeyringInf {
	return k.Keyring
}

// KeyringVersion returns the version of the keyring itself (not its schema).
func (k *KeyringSectionV1) KeyringVersion() int {
	return k.Keyring.Body.KeyringVersion
}

// FindMember returns the membership and mekshare for the given user id.
// The data is returned in V2 format.
func (k *KeyringSectionV1) FindMember(id *identity.ID) (*primitive.KeyringMember, *primitive.MEKShare, error) {
	var krm *primitive.KeyringMember
	var mekshare *primitive.MEKShare
	for _, m := range k.Members {
		if *m.Body.OwnerID == *id {
			krm, mekshare = convertV1KRM(&m)
			break
		}
	}

	if krm == nil {
		return nil, nil, ErrMemberNotFound
	}

	return krm, mekshare, nil
}

// FindMEKByKeyID returns the MEKShare for the given encrypting key id.
//
// The data is returned in the V2 format.
func (k *KeyringSectionV1) FindMEKByKeyID(id *identity.ID) (*primitive.MEKShare, error) {
	var mekshare *primitive.MEKShare
	for _, m := range k.Members {
		if *m.Body.EncryptingKeyID == *id {
			mekshare = &primitive.MEKShare{
				Key: m.Body.Key,
			}
			break
		}
	}

	if mekshare == nil {
		return nil, ErrMemberNotFound
	}

	return mekshare, nil
}

func convertV1KRM(krm *envelope.KeyringMemberV1) (*primitive.KeyringMember, *primitive.MEKShare) {
	return &primitive.KeyringMember{
			OrgID:           krm.Body.OrgID,
			KeyringID:       krm.Body.KeyringID,
			OwnerID:         krm.Body.OwnerID,
			PublicKeyID:     krm.Body.PublicKeyID,
			EncryptingKeyID: krm.Body.EncryptingKeyID,
		}, &primitive.MEKShare{
			Key: krm.Body.Key,
		}
}

// HasRevocations indicates that a Keyring holds revoked user keys. We don't
// track in V1 so it is always false.
func (KeyringSectionV1) HasRevocations() bool {
	return false
}

// GetClaims returns the Member claims for this keyring. These don't exist in V1
// so it is always an empty list.
func (KeyringSectionV1) GetClaims() []envelope.KeyringMemberClaim {
	return nil
}

// KeyringSectionV2 represents a Keyring and its members.
type KeyringSectionV2 struct {
	Keyring *envelope.Keyring             `json:"keyring"`
	Members []KeyringMember               `json:"members"`
	Claims  []envelope.KeyringMemberClaim `json:"claims"`
}

// GetKeyring returns the Keyring object in this KeyringSection
func (k *KeyringSectionV2) GetKeyring() envelope.KeyringInf {
	return k.Keyring
}

// KeyringVersion returns the version of the keyring itself (not its schema).
func (k *KeyringSectionV2) KeyringVersion() int {
	return k.Keyring.Body.KeyringVersion
}

// FindMember returns the membership and mekshare for the given user id.
//
// An owner (user/machine token) may have multiple memberships, one per
// encryption key. There will only be one unrevoked membership.
// Either this unrevoked membership will be returned, or the result will error
// with ErrMemberNotFound.
func (k *KeyringSectionV2) FindMember(id *identity.ID) (*primitive.KeyringMember, *primitive.MEKShare, error) {
	var krm *primitive.KeyringMember
	var mekshare *primitive.MEKShare

outerLoop:
	for _, m := range k.Members {
		if *m.Member.Body.OwnerID == *id {
			// We've found the right owner. Now see if this membership is
			// unrevoked.
			// A revocation is always terminal for a claim chain, so if there's
			// any revocations for this membership, we know it is invalid.
			if krmIsRevoked(m, k.Claims) {
				continue outerLoop
			}

			krm = m.Member.Body
			// We never get the MEKShare for another user returned.
			if m.MEKShare != nil {
				mekshare = m.MEKShare.Body
			}
			break
		}
	}

	if krm == nil {
		return nil, nil, ErrMemberNotFound
	}

	return krm, mekshare, nil
}

// FindMEKByKeyID returns the mekshare for the given encrypting key id.
//
// An owner (user/machine token) may have multiple memberships, one per
// encryption key. There will only be one unrevoked membership. Eitgher this
// unrevoked membership will ber returned, or the result will error with
// ErrMemberNotFound.
func (k *KeyringSectionV2) FindMEKByKeyID(id *identity.ID) (*primitive.MEKShare, error) {
	var mekshare *primitive.MEKShare

outerLoop:
	for _, m := range k.Members {
		if *m.Member.Body.EncryptingKeyID == *id {
			// We've found the right key. Now see if this membership is
			// unrevoked.
			// A revocation is always terminal for a claim chain, so if there's
			// any revocations for this membership, we know it is invalid.
			if krmIsRevoked(m, k.Claims) {
				continue outerLoop
			}

			if m.MEKShare == nil {
				return nil, ErrMemberNotFound
			}

			mekshare = m.MEKShare.Body
			break
		}
	}

	return mekshare, nil
}

func krmIsRevoked(m KeyringMember, claims []envelope.KeyringMemberClaim) bool {
	for _, c := range claims {
		if *c.Body.KeyringMemberID == *m.Member.ID && c.Body.ClaimType == primitive.RevocationClaimType {
			return true
		}
	}

	return false
}

// HasRevocations indicates that a Keyring holds revoked user keys.
func (k *KeyringSectionV2) HasRevocations() bool {
	for _, claim := range k.Claims {
		if claim.Body.ClaimType == primitive.RevocationClaimType {
			return true
		}
	}
	return false
}

// GetClaims returns the list of Member claims for this keyring.
func (k *KeyringSectionV2) GetClaims() []envelope.KeyringMemberClaim {
	return k.Claims
}

// KeyringMember holds membership information for v2 keyrings. In v2, a user
// can have their master encryption key share removed.
type KeyringMember struct {
	Member   *envelope.KeyringMember `json:"member"`
	MEKShare *envelope.MEKShare      `json:"mekshare"`
}

// List retrieves an array of KeyringSections from the registry.
func (k *KeyringClient) List(ctx context.Context, orgID *identity.ID,
	ownerID *identity.ID) ([]KeyringSection, error) {

	query := &url.Values{}

	if orgID != nil {
		query.Set("org_id", orgID.String())
	}
	if ownerID != nil {
		query.Set("owner_id", ownerID.String())
	}

	resp := []struct {
		Keyring *envelope.Signed              `json:"keyring"`
		Members json.RawMessage               `json:"members"`
		Claims  []envelope.KeyringMemberClaim `json:"claims"`
	}{}

	err := k.client.RoundTrip(ctx, "GET", "/keyrings", query, nil, &resp)
	if err != nil {
		return nil, err
	}

	converted := make([]KeyringSection, len(resp))
	for i, k := range resp {
		if k.Keyring.Version == 1 {
			kre := &envelope.KeyringV1{
				ID:        k.Keyring.ID,
				Version:   k.Keyring.Version,
				Signature: k.Keyring.Signature,
				Body:      k.Keyring.Body.(*primitive.KeyringV1),
			}

			s := KeyringSectionV1{
				Keyring: kre,
			}
			err := json.Unmarshal(k.Members, &s.Members)
			if err != nil {
				return nil, err
			}
			converted[i] = &s
		} else {
			kre := &envelope.Keyring{
				ID:        k.Keyring.ID,
				Version:   k.Keyring.Version,
				Signature: k.Keyring.Signature,
				Body:      k.Keyring.Body.(*primitive.Keyring),
			}
			s := KeyringSectionV2{
				Keyring: kre,
				Claims:  k.Claims,
			}
			err := json.Unmarshal(k.Members, &s.Members)
			if err != nil {
				return nil, err
			}
			converted[i] = &s
		}
	}

	return converted, nil
}


text:
package remoteexec

import (
	"bytes"
	"context"
	"errors"
	"io"
	"net"
	"testing"
	"time"

	"github.com/hashicorp/terraform/config"
	"github.com/hashicorp/terraform/helper/schema"
	"github.com/hashicorp/terraform/terraform"
)

func TestResourceProvider_Validate_good(t *testing.T) {
	c := testConfig(t, map[string]interface{}{
		"inline": "echo foo",
	})
	p := Provisioner()
	warn, errs := p.Validate(c)
	if len(warn) > 0 {
		t.Fatalf("Warnings: %v", warn)
	}
	if len(errs) > 0 {
		t.Fatalf("Errors: %v", errs)
	}
}

func TestResourceProvider_Validate_bad(t *testing.T) {
	c := testConfig(t, map[string]interface{}{
		"invalid": "nope",
	})
	p := Provisioner()
	warn, errs := p.Validate(c)
	if len(warn) > 0 {
		t.Fatalf("Warnings: %v", warn)
	}
	if len(errs) == 0 {
		t.Fatalf("Should have errors")
	}
}

var expectedScriptOut = `cd /tmp
wget http://foobar
exit 0
`

func TestResourceProvider_generateScript(t *testing.T) {
	p := Provisioner().(*schema.Provisioner)
	conf := map[string]interface{}{
		"inline": []interface{}{
			"cd /tmp",
			"wget http://foobar",
			"exit 0",
		},
	}
	out, err := generateScripts(schema.TestResourceDataRaw(
		t, p.Schema, conf))
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	if len(out) != 1 {
		t.Fatal("expected 1 out")
	}

	if out[0] != expectedScriptOut {
		t.Fatalf("bad: %v", out)
	}
}

func TestResourceProvider_CollectScripts_inline(t *testing.T) {
	p := Provisioner().(*schema.Provisioner)
	conf := map[string]interface{}{
		"inline": []interface{}{
			"cd /tmp",
			"wget http://foobar",
			"exit 0",
		},
	}

	scripts, err := collectScripts(schema.TestResourceDataRaw(
		t, p.Schema, conf))
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	if len(scripts) != 1 {
		t.Fatalf("bad: %v", scripts)
	}

	var out bytes.Buffer
	_, err = io.Copy(&out, scripts[0])
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	if out.String() != expectedScriptOut {
		t.Fatalf("bad: %v", out.String())
	}
}

func TestResourceProvider_CollectScripts_script(t *testing.T) {
	p := Provisioner().(*schema.Provisioner)
	conf := map[string]interface{}{
		"script": "test-fixtures/script1.sh",
	}

	scripts, err := collectScripts(schema.TestResourceDataRaw(
		t, p.Schema, conf))
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	if len(scripts) != 1 {
		t.Fatalf("bad: %v", scripts)
	}

	var out bytes.Buffer
	_, err = io.Copy(&out, scripts[0])
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	if out.String() != expectedScriptOut {
		t.Fatalf("bad: %v", out.String())
	}
}

func TestResourceProvider_CollectScripts_scripts(t *testing.T) {
	p := Provisioner().(*schema.Provisioner)
	conf := map[string]interface{}{
		"scripts": []interface{}{
			"test-fixtures/script1.sh",
			"test-fixtures/script1.sh",
			"test-fixtures/script1.sh",
		},
	}

	scripts, err := collectScripts(schema.TestResourceDataRaw(
		t, p.Schema, conf))
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	if len(scripts) != 3 {
		t.Fatalf("bad: %v", scripts)
	}

	for idx := range scripts {
		var out bytes.Buffer
		_, err = io.Copy(&out, scripts[idx])
		if err != nil {
			t.Fatalf("err: %v", err)
		}

		if out.String() != expectedScriptOut {
			t.Fatalf("bad: %v", out.String())
		}
	}
}

func TestRetryFunc(t *testing.T) {
	// succeed on the third try
	errs := []error{io.EOF, &net.OpError{Err: errors.New("ERROR")}, nil}
	count := 0

	err := retryFunc(context.Background(), time.Second, func() error {
		if count >= len(errs) {
			return errors.New("failed to stop after nil error")
		}

		err := errs[count]
		count++

		return err
	})

	if count != 3 {
		t.Fatal("retry func should have been called 3 times")
	}

	if err != nil {
		t.Fatal(err)
	}
}

func testConfig(
	t *testing.T,
	c map[string]interface{}) *terraform.ResourceConfig {
	r, err := config.NewRawConfig(c)
	if err != nil {
		t.Fatalf("bad: %s", err)
	}

	return terraform.NewResourceConfig(r)
}


text:
class PasswordGorilla < Cask
  version '1.5.3.7.2'
  sha256 '4d026a5fa088fe9622cbe00c5811da2f360949c7cfb46ce6e4899a09645cb83a'

  url 'http://zdia.de/downloads/gorilla/gorilla15372.zip'
  homepage 'https://github.com/zdia/gorilla'

  app 'Password Gorilla.app'
  caveats <<-EOS.undent
    Password Gorilla must be run in 32-bit mode.
    Gatekeeper may need to be temporarily disabled for the first launch.
  EOS
end


text:
package com.google.template.soy.soytree;

import com.google.template.soy.base.SourceLocation;
import com.google.template.soy.basetree.CopyState;
import com.google.template.soy.basetree.MixinParentNode;
import com.google.template.soy.basetree.Node;
import com.google.template.soy.soytree.SoyNode.ParentSoyNode;
import java.util.List;

/**
 * Abstract implementation of a ParentNode and CommandNode.
 *
 * <p>Important: Do not use outside of Soy code (treat as superpackage-private).
 *
 */
abstract class AbstractParentCommandNode<N extends SoyNode> extends AbstractCommandNode
    implements ParentSoyNode<N> {

  /** The mixin object that implements the ParentNode functionality. */
  private final MixinParentNode<N> parentMixin;

  /**
   * @param id The id for this node.
   * @param sourceLocation The node's source location.
   * @param commandName The name of the Soy command.
   */
  public AbstractParentCommandNode(int id, SourceLocation sourceLocation, String commandName) {
    super(id, sourceLocation, commandName);
    parentMixin = new MixinParentNode<>(this);
  }

  /**
   * Copy constructor.
   *
   * @param orig The node to copy.
   */
  protected AbstractParentCommandNode(AbstractParentCommandNode<N> orig, CopyState copyState) {
    super(orig, copyState);
    this.parentMixin = new MixinParentNode<>(orig.parentMixin, this, copyState);
  }

  @Override
  public String toSourceString() {
    StringBuilder sb = new StringBuilder();
    sb.append(getTagString());
    appendSourceStringForChildren(sb);
    sb.append("{/").append(getCommandName()).append('}');
    return sb.toString();
  }

  @Override
  public int numChildren() {
    return parentMixin.numChildren();
  }

  @Override
  public N getChild(int index) {
    return parentMixin.getChild(index);
  }

  @Override
  public int getChildIndex(Node child) {
    return parentMixin.getChildIndex(child);
  }

  @Override
  public List<N> getChildren() {
    return parentMixin.getChildren();
  }

  @Override
  public void addChild(N child) {
    parentMixin.addChild(child);
  }

  @Override
  public void addChild(int index, N child) {
    parentMixin.addChild(index, child);
  }

  @Override
  public void removeChild(int index) {
    parentMixin.removeChild(index);
  }

  @Override
  public void removeChild(N child) {
    parentMixin.removeChild(child);
  }

  @Override
  public void replaceChild(int index, N newChild) {
    parentMixin.replaceChild(index, newChild);
  }

  @Override
  public void replaceChild(N currChild, N newChild) {
    parentMixin.replaceChild(currChild, newChild);
  }

  @Override
  public void clearChildren() {
    parentMixin.clearChildren();
  }

  @Override
  public void addChildren(List<? extends N> children) {
    parentMixin.addChildren(children);
  }

  @Override
  public void addChildren(int index, List<? extends N> children) {
    parentMixin.addChildren(index, children);
  }

  @Override
  public void appendSourceStringForChildren(StringBuilder sb) {
    parentMixin.appendSourceStringForChildren(sb);
  }
}


text:
<?php

namespace Ginsberg\TransportationBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * TicketRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class TicketRepository extends EntityRepository
{
  /**
   * Returns all Tickets associated with a given Person's Reservations.
   *
   * @param Person $person The Person whose tickets we want to find
   *
   * @return array
   */
  public function findTicketsForPerson($person)
  {
    $em = $this->getEntityManager();
    $query = $em->createQuery('SELECT t FROM GinsbergTransportationBundle:Ticket t
      WHERE t.isPaid = 0 AND t.reservation IN
        (SELECT r FROM GinsbergTransportationBundle:Reservation r WHERE r.person = :person)')
            ->setParameters(array('person' => $person));

    try {
      $tickets = $query->getResult();
      return $tickets;
    } catch (\Doctrine\ORM\NoResultException $ex) {
      return NULL;
    }
  }
}


text:
package org.wisdom.cache.ehcache;

import org.joda.time.Duration;
import org.junit.Ignore;
import org.junit.Test;
import org.osgi.framework.BundleContext;
import org.wisdom.api.cache.Cache;
import org.wisdom.api.configuration.ApplicationConfiguration;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * Check the creation of the EhCache-based cache service implementation.
 */
public class EhCacheServiceTest {

    @Test
    public void test() throws InterruptedException {
        ApplicationConfiguration configuration = mock(ApplicationConfiguration.class);
        when(configuration.getBooleanWithDefault("ehcache.enabled", true)).thenReturn(true);
        EhCacheService svc = new EhCacheService();
        svc.configuration = configuration;
        svc.context = mock(BundleContext.class);
        svc.start();

        assertThat(svc.get("key")).isNull();
        svc.set("key", "value", Duration.standardSeconds(1));
        assertThat(svc.get("key")).isEqualTo("value");

        waitForCleanup(svc);
        assertThat(svc.get("key")).isNull();

        svc.set("key", "value", 0);
        assertThat(svc.get("key")).isEqualTo("value");
        assertThat(svc.remove("key")).isTrue();
        assertThat(svc.get("key")).isNull();
        assertThat(svc.remove("missing")).isFalse();

        svc.stop();
    }

    @Test
    public void testDisabled() {
        ApplicationConfiguration configuration = mock(ApplicationConfiguration.class);
        when(configuration.getBooleanWithDefault("ehcache.enabled", true)).thenReturn(false);
        EhCacheService svc = new EhCacheService();
        svc.configuration = configuration;
        svc.context = mock(BundleContext.class);
        svc.start();

        svc.stop();
    }

    @Test
    public void testUsingGenerics() throws InterruptedException {
        ApplicationConfiguration configuration = mock(ApplicationConfiguration.class);
        when(configuration.getBooleanWithDefault("ehcache.enabled", true)).thenReturn(true);
        EhCacheService impl = new EhCacheService();
        impl.configuration = configuration;
        impl.context = mock(BundleContext.class);
        impl.start();

        Cache svc = impl;

        assertThat((String) svc.get("key")).isNull();
        svc.set("key", "value", Duration.standardSeconds(1));
        assertThat(svc.<String>get("key")).contains("value").isEqualTo("value");

        waitForCleanup(impl);
        assertThat(svc.<String>get("key")).isNull();

        svc.set("key", "value", 0);
        final String v = svc.get("key");
        assertThat(v).isEqualTo("value");
        assertThat(svc.remove("key")).isTrue();
        assertThat(svc.<String>get("key")).isNull();
        assertThat(svc.remove("missing")).isFalse();

        impl.stop();
    }

    @Test
    public void testUsingGenericsAndObjects() throws InterruptedException {
        ApplicationConfiguration configuration = mock(ApplicationConfiguration.class);
        when(configuration.getBooleanWithDefault("ehcache.enabled", true)).thenReturn(true);
        EhCacheService impl = new EhCacheService();
        impl.configuration = configuration;
        impl.context = mock(BundleContext.class);
        impl.start();

        Cache svc = impl;

        assertThat((String) svc.get("key")).isNull();
        svc.set("key", new User("foo"), Duration.standardSeconds(1));
        assertThat(svc.<User>get("key").name).isEqualTo("foo");

        waitForCleanup(impl);
        assertThat(svc.<String>get("key")).isNull();

        impl.set("key", new User("wisdom"), 0);
        assertThat(svc.<User>get("key")).isEqualTo(new User("wisdom"));
        assertThat(svc.remove("key")).isTrue();
        assertThat(svc.<User>get("key")).isNull();
        assertThat(svc.remove("missing")).isFalse();

        impl.stop();
    }

    private static class User {
        String name;

        public User(String n) {
            this.name = n;
        }

        public boolean equals(Object u) {
            return u instanceof User  && ((User) u).name.equals(name);
        }
    }

    /**
     * Test #297.
     */
    @Test
    public void testRestart() throws InterruptedException {
        ApplicationConfiguration configuration = mock(ApplicationConfiguration.class);
        when(configuration.getBooleanWithDefault("ehcache.enabled", true)).thenReturn(true);
        EhCacheService svc = new EhCacheService();
        svc.configuration = configuration;
        svc.context = mock(BundleContext.class);
        svc.start();

        assertThat(svc.get("key")).isNull();
        svc.set("key", "value", Duration.standardSeconds(1));
        assertThat(svc.get("key")).isEqualTo("value");

        waitForCleanup(svc);
        assertThat(svc.get("key")).isNull();

        svc.set("key", "value", 0);
        assertThat(svc.get("key")).isEqualTo("value");
        assertThat(svc.remove("key")).isTrue();
        assertThat(svc.get("key")).isNull();
        assertThat(svc.remove("missing")).isFalse();

        svc.stop();

        svc.start();

        assertThat(svc.get("key")).isNull();
        svc.set("key", "value", Duration.standardSeconds(1));
        assertThat(svc.get("key")).isEqualTo("value");

        waitForCleanup(svc);
        assertThat(svc.get("key")).isNull();

        svc.set("key", "value", 0);
        assertThat(svc.get("key")).isEqualTo("value");
        assertThat(svc.remove("key")).isTrue();
        assertThat(svc.get("key")).isNull();
        assertThat(svc.remove("missing")).isFalse();

    }

    @Test
    @Ignore("Does not reproduce the race condition")
    public void testPeak() throws InterruptedException {
        ApplicationConfiguration configuration = mock(ApplicationConfiguration.class);
        when(configuration.getBooleanWithDefault("ehcache.enabled", true)).thenReturn(true);
        final EhCacheService svc = new EhCacheService();
        svc.configuration = configuration;
        svc.context = mock(BundleContext.class);
        svc.start();

        assertThat(svc.get("key")).isNull();
        svc.set("key", "value", Duration.standardSeconds(60));
        assertThat(svc.get("key")).isEqualTo("value");

        CountDownLatch startSignal = new CountDownLatch(1);
        final int client = 100;
        final CountDownLatch doneSignal = new CountDownLatch(client);
        ExecutorService executor = Executors.newFixedThreadPool(client);
        final AtomicInteger counter = new AtomicInteger();

        for (int i = 1; i < client + 1; ++i) {
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    Object val = svc.get("key");
                    if (val == null || !(val instanceof String) || ((String) val).length() == 0) {
                        counter.incrementAndGet();
                    }
                    doneSignal.countDown();
                }
            });
        }

        startSignal.countDown();
        doneSignal.await(60, TimeUnit.SECONDS);

        assertThat(counter.get()).isEqualTo(0);

        svc.remove("key");

        svc.stop();
    }

    private void waitForCleanup(EhCacheService svc) throws InterruptedException {
        for (int count = 0; count < 5; count++) {
            Object obj = svc.get("key");
            if (obj == null) {
                return;
            } else {
                Thread.sleep(1000);
            }
        }
    }
}