text:
#if FEATURE_CORE_DLR
using System.Linq.Expressions;
#if !WIN8
using DynamicExpression = System.Linq.Expressions.Expression;
#endif
#else
using Microsoft.Scripting.Ast;
using dynamic = System.Object;
using DynamicExpression = Microsoft.Scripting.Ast.Expression;
#endif

using System;
using System.Reflection;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;

using Microsoft.Scripting.Utils;

namespace Microsoft.Scripting.Runtime {
    /// <summary>
    /// Provides language specific facilities which are typically called by the runtime.
    /// </summary>
    public abstract class LanguageContext {
        private readonly ScriptDomainManager _domainManager;
        private readonly ContextId _id;
        private DynamicOperations _operations;

        protected LanguageContext(ScriptDomainManager domainManager) {
            ContractUtils.RequiresNotNull(domainManager, "domainManager");

            _domainManager = domainManager;
            _id = domainManager.GenerateContextId();
        }

        /// <summary>
        /// Provides the ContextId which includes members that should only be shown for this LanguageContext.
        ///
        /// ContextId's are used for filtering by Scope's.
        /// </summary>
        public ContextId ContextId {
            get { return _id; }
        }

        /// <summary>
        /// Gets the ScriptDomainManager that this LanguageContext is running within.
        /// </summary>
        public ScriptDomainManager DomainManager {
            get { return _domainManager; }
        }

        /// <summary>
        /// Whether the language can parse code and create source units.
        /// </summary>
        public virtual bool CanCreateSourceCode {
            get { return true; }
        }

        #region Scope

        /// <summary>
        /// Gets the scope associated with a file, or null if none was available
        /// </summary>
        public virtual Scope GetScope(string path) {
            return null;
        }

        /// <summary>
        /// Creates a new ScriptScope using the default storage container
        /// </summary>
        public virtual Scope CreateScope() {
            return new Scope();
        }

        /// <summary>
        /// Creates a new ScriptScope whose storage contains the provided dictionary of objects
        ///
        /// Accesses to the ScriptScope will turn into get,set, and delete members against this dictionary
        /// </summary>
        public virtual Scope CreateScope(IDictionary<string, object> dictionary) {
            return new Scope(dictionary);
        }

        /// <summary>
        /// Creates a new ScriptScope whose storage is an arbitrary object.
        ///
        /// Accesses to the ScriptScope will turn into get, set, and delete members against the object.
        /// </summary>
        public virtual Scope CreateScope(IDynamicMetaObjectProvider storage) {
            return new Scope(storage);
        }

        // TODO: remove
        public ScopeExtension EnsureScopeExtension(Scope scope) {
            ContractUtils.RequiresNotNull(scope, "scope");
            ScopeExtension extension = scope.GetExtension(ContextId);

            if (extension == null) {
                extension = CreateScopeExtension(scope);
                if (extension == null) {
                    throw Error.MustReturnScopeExtension();
                }
                return scope.SetExtension(ContextId, extension);
            }

            return extension;
        }

        // TODO: remove
        public virtual ScopeExtension CreateScopeExtension(Scope scope) {
            return new ScopeExtension(scope);
        }

        /// <summary>
        /// Provides access to setting variables in scopes.
        ///
        /// By default this goes through ObjectOperations which can be rather slow.
        /// Languages can override this to provide fast customized access which avoids
        /// ObjectOperations.  Languages can provide fast access to commonly used scope
        /// types for that language.  Typically this includes ScopeStorage and any other
        /// classes which the language themselves uses for backing of a Scope.
        /// </summary>
        public virtual void ScopeSetVariable(Scope scope, string name, object value) {
            Operations.SetMember(scope, name, value);
        }

        /// <summary>
        /// Provides access to try getting variables in scopes.
        ///
        /// By default this goes through ObjectOperations which can be rather slow.
        /// Languages can override this to provide fast customized access which avoids
        /// ObjectOperations.  Languages can provide fast access to commonly used scope
        /// types for that language.  Typically this includes ScopeStorage and any other
        /// classes which the language themselves uses for backing of a Scope.
        /// </summary>
        public virtual bool ScopeTryGetVariable(Scope scope, string name, out dynamic value) {
            return Operations.TryGetMember(scope, name, out value);
        }

        /// <summary>
        /// Provides access to getting variables in scopes and converting the result.
        ///
        /// By default this goes through ObjectOperations which can be rather slow.
        /// Languages can override this to provide fast customized access which avoids
        /// ObjectOperations.  Languages can provide fast access to commonly used scope
        /// types for that language.  Typically this includes ScopeStorage and any other
        /// classes which the language themselves uses for backing of a Scope.
        /// </summary>
        public virtual T ScopeGetVariable<T>(Scope scope, string name) {
            return Operations.GetMember<T>(scope, name);
        }

        /// <summary>
        /// Provides access to getting variables in scopes.
        ///
        /// By default this goes through ObjectOperations which can be rather slow.
        /// Languages can override this to provide fast customized access which avoids
        /// ObjectOperations.  Languages can provide fast access to commonly used scope
        /// types for that language.  Typically this includes ScopeStorage and any other
        /// classes which the language themselves uses for backing of a Scope.
        /// </summary>
        public virtual dynamic ScopeGetVariable(Scope scope, string name) {
            return Operations.GetMember(scope, name);
        }

        #endregion

        #region Source Code Parsing & Compilation

        /// <summary>
        /// Provides a text reader for source code that is to be read from a given stream.
        /// </summary>
        /// <param name="stream">The stream open for reading. The stream must also allow seeking.</param>
        /// <param name="defaultEncoding">An encoding that should be used if the stream doesn't have Unicode or language specific preamble.</param>
        /// <param name="path">the path of the source unit if available</param>
        /// <returns>The reader.</returns>
        /// <exception cref="IOException">An I/O error occurs.</exception>
        public virtual SourceCodeReader GetSourceReader(Stream stream, Encoding defaultEncoding, string path) {
            ContractUtils.RequiresNotNull(stream, "stream");
            ContractUtils.RequiresNotNull(defaultEncoding, "defaultEncoding");
            ContractUtils.Requires(stream.CanRead && stream.CanSeek, "stream", "The stream must support reading and seeking");

            var result = new StreamReader(stream, defaultEncoding, true);
            result.Peek();
            return new SourceCodeReader(result, result.CurrentEncoding);
        }

        /// <summary>
        /// Creates the language specific CompilerOptions object for compilation of code not bound to any particular scope.
        /// The language should flow any relevant options from LanguageContext to the newly created options instance.
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
        public virtual CompilerOptions GetCompilerOptions() {
            return new CompilerOptions();
        }

        /// <summary>
        /// Creates the language specific CompilerOptions object for compilation of code bound to a given scope.
        /// </summary>
        public virtual CompilerOptions GetCompilerOptions(Scope scope) {
            return GetCompilerOptions();
        }

        /// <summary>
        /// Parses the source code within a specified compiler context.
        /// The source unit to parse is held on by the context.
        /// </summary>
        /// <returns><b>null</b> on failure.</returns>
        /// <remarks>Could also set the code properties and line/file mappings on the source unit.</remarks>
        public abstract ScriptCode CompileSourceCode(SourceUnit sourceUnit, CompilerOptions options, ErrorSink errorSink);

        public virtual ScriptCode LoadCompiledCode(Delegate method, string path, string customData) {
            throw new NotSupportedException();
        }

        public virtual int ExecuteProgram(SourceUnit program) {
            ContractUtils.RequiresNotNull(program, "program");

            object returnValue = program.Execute();

            if (returnValue == null) {
                return 0;
            }

            CallSite<Func<CallSite, object, int>> site =
                CallSite<Func<CallSite, object, int>>.Create(CreateConvertBinder(typeof(int), true));

            return site.Target(site, returnValue);
        }

        #endregion

        #region ScriptEngine API

        public virtual Version LanguageVersion {
            get {
                return new Version(0, 0);
            }
        }

        public virtual void SetSearchPaths(ICollection<string> paths) {
            throw new NotSupportedException();
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
        public virtual ICollection<string> GetSearchPaths() {
            return Options.SearchPaths;
        }

#if FEATURE_CODEDOM
        // Convert a CodeDom to source code, and output the generated code and the line number mappings (if any)
        public virtual SourceUnit GenerateSourceCode(System.CodeDom.CodeObject codeDom, string path, SourceCodeKind kind) {
            throw new NotImplementedException();
        }
#endif

        public virtual TService GetService<TService>(params object[] args) where TService : class {
            return null;
        }

        public virtual Guid LanguageGuid {
            get {
                return Guid.Empty;
            }
        }

        public virtual Guid VendorGuid {
            get {
                return Guid.Empty;
            }
        }

        public virtual void Shutdown() {
        }

        public virtual string FormatException(Exception exception) {
            return exception.ToString();
        }

        public virtual IList<DynamicStackFrame> GetStackFrames(Exception exception) {
            return new DynamicStackFrame[0];
        }

        public virtual Microsoft.Scripting.LanguageOptions Options {
            get {
                return new Microsoft.Scripting.LanguageOptions();
            }
        }

        #region Source Units

        public SourceUnit CreateSnippet(string code, SourceCodeKind kind) {
            return CreateSnippet(code, null, kind);
        }

        public SourceUnit CreateSnippet(string code, string id, SourceCodeKind kind) {
            ContractUtils.RequiresNotNull(code, "code");

            return CreateSourceUnit(new SourceStringContentProvider(code), id, kind);
        }

        public SourceUnit CreateFileUnit(string path) {
            return CreateFileUnit(path, StringUtils.DefaultEncoding);
        }

        public SourceUnit CreateFileUnit(string path, Encoding encoding) {
            return CreateFileUnit(path, encoding, SourceCodeKind.File);
        }

        public SourceUnit CreateFileUnit(string path, Encoding encoding, SourceCodeKind kind) {
            ContractUtils.RequiresNotNull(path, "path");
            ContractUtils.RequiresNotNull(encoding, "encoding");

            TextContentProvider provider = new LanguageBoundTextContentProvider(this, new FileStreamContentProvider(DomainManager.Platform, path), encoding, path);
            return CreateSourceUnit(provider, path, kind);
        }

        public SourceUnit CreateFileUnit(string path, string content) {
            ContractUtils.RequiresNotNull(path, "path");
            ContractUtils.RequiresNotNull(content, "content");

            TextContentProvider provider = new SourceStringContentProvider(content);
            return CreateSourceUnit(provider, path, SourceCodeKind.File);
        }

        public SourceUnit CreateSourceUnit(StreamContentProvider contentProvider, string path, Encoding encoding, SourceCodeKind kind) {
            ContractUtils.RequiresNotNull(contentProvider, "contentProvider");
            ContractUtils.RequiresNotNull(encoding, "encoding");
            ContractUtils.Requires(kind.IsValid(), "kind");
            ContractUtils.Requires(CanCreateSourceCode);

            return new SourceUnit(this, new LanguageBoundTextContentProvider(this, contentProvider, encoding, path), path, kind);
        }

        public SourceUnit CreateSourceUnit(TextContentProvider contentProvider, string path, SourceCodeKind kind) {
            ContractUtils.RequiresNotNull(contentProvider, "contentProvider");
            ContractUtils.Requires(kind.IsValid(), "kind");
            ContractUtils.Requires(CanCreateSourceCode);

            return new SourceUnit(this, contentProvider, path, kind);
        }

        #endregion

        #endregion

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
        public virtual ErrorSink GetCompilerErrorSink() {
            return ErrorSink.Null;
        }

        #region Object Operations Support

        internal static DynamicMetaObject ErrorMetaObject(Type resultType, DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) {
            return errorSuggestion ?? new DynamicMetaObject(
                Expression.Throw(Expression.New(typeof(NotImplementedException)), resultType),
                target.Restrictions.Merge(BindingRestrictions.Combine(args))
            );
        }

        public virtual UnaryOperationBinder CreateUnaryOperationBinder(ExpressionType operation) {
            return new DefaultUnaryOperationBinder(operation);
        }

        private sealed class DefaultUnaryOperationBinder : UnaryOperationBinder {
            internal DefaultUnaryOperationBinder(ExpressionType operation)
                : base(operation) {
            }

            public override DynamicMetaObject FallbackUnaryOperation(DynamicMetaObject target, DynamicMetaObject errorSuggestion) {
                return ErrorMetaObject(ReturnType, target, new[] { target }, errorSuggestion);
            }
        }

        public virtual BinaryOperationBinder CreateBinaryOperationBinder(ExpressionType operation) {
            return new DefaultBinaryOperationBinder(operation);
        }

        private sealed class DefaultBinaryOperationBinder : BinaryOperationBinder {
            internal DefaultBinaryOperationBinder(ExpressionType operation)
                : base(operation) {
            }

            public override DynamicMetaObject FallbackBinaryOperation(DynamicMetaObject target, DynamicMetaObject arg, DynamicMetaObject errorSuggestion) {
                return ErrorMetaObject(ReturnType, target, new[] { target, arg }, errorSuggestion);
            }
        }

        private class DefaultConvertAction : ConvertBinder {
            internal DefaultConvertAction(Type type, bool @explicit)
                : base(type, @explicit) {
            }

            public override DynamicMetaObject FallbackConvert(DynamicMetaObject self, DynamicMetaObject errorSuggestion) {
                if (Type.GetTypeInfo().IsAssignableFrom(self.LimitType.GetTypeInfo())) {
                    return new DynamicMetaObject(
                        Expression.Convert(self.Expression, Type),
                        BindingRestrictions.GetTypeRestriction(self.Expression, self.LimitType)
                    );
                }

                if (errorSuggestion != null) {
                    return errorSuggestion;
                }

                return new DynamicMetaObject(
                    Expression.Throw(
                        Expression.Constant(
                            new ArgumentTypeException(string.Format("Expected {0}, got {1}", Type.FullName, self.LimitType.FullName))
                        ),
                        ReturnType
                    ),
                    BindingRestrictions.GetTypeRestriction(self.Expression, self.LimitType)
                );
            }
        }

        /// <summary>
        /// Creates a conversion binder.
        ///
        /// If explicitCast is true then the binder should do explicit conversions.
        /// If explicitCast is false then the binder should do implicit conversions.
        ///
        /// If explicitCast is null it is up to the language to select the conversions
        /// which closest match their normal behavior.
        /// </summary>
        public virtual ConvertBinder CreateConvertBinder(Type toType, bool? explicitCast) {
            return new DefaultConvertAction(toType, explicitCast ?? false);
        }

        private class DefaultGetMemberAction : GetMemberBinder {
            internal DefaultGetMemberAction(string name, bool ignoreCase)
                : base(name, ignoreCase) {
            }

            public override DynamicMetaObject FallbackGetMember(DynamicMetaObject self, DynamicMetaObject errorSuggestion) {
                return errorSuggestion ?? new DynamicMetaObject(
                    Expression.Throw(
                        Expression.New(
                            typeof(MissingMemberException).GetConstructor(new[] { typeof(string) }),
                            Expression.Constant(String.Format("unknown member: {0}", Name))
                        ),
                        typeof(object)
                    ),
                    self.Value == null ?
                        BindingRestrictions.GetExpressionRestriction(Expression.Equal(self.Expression, Expression.Constant(null))) :
                        BindingRestrictions.GetTypeRestriction(self.Expression, self.Value.GetType())
                );
            }
        }

        public virtual GetMemberBinder CreateGetMemberBinder(string name, bool ignoreCase) {
            return new DefaultGetMemberAction(name, ignoreCase);
        }

        private class DefaultSetMemberAction : SetMemberBinder {
            internal DefaultSetMemberAction(string name, bool ignoreCase)
                : base(name, ignoreCase) {
            }

            public override DynamicMetaObject FallbackSetMember(DynamicMetaObject self, DynamicMetaObject value, DynamicMetaObject errorSuggestion) {
                return ErrorMetaObject(ReturnType, self, new DynamicMetaObject[] { value }, errorSuggestion);
            }
        }

        public virtual SetMemberBinder CreateSetMemberBinder(string name, bool ignoreCase) {
            return new DefaultSetMemberAction(name, ignoreCase);
        }

        private class DefaultDeleteMemberAction : DeleteMemberBinder {
            internal DefaultDeleteMemberAction(string name, bool ignoreCase)
                : base(name, ignoreCase) {
            }

            public override DynamicMetaObject FallbackDeleteMember(DynamicMetaObject self, DynamicMetaObject errorSuggestion) {
                return ErrorMetaObject(ReturnType, self, DynamicMetaObject.EmptyMetaObjects, errorSuggestion);
            }
        }

        public virtual DeleteMemberBinder CreateDeleteMemberBinder(string name, bool ignoreCase) {
            return new DefaultDeleteMemberAction(name, ignoreCase);
        }

        private class DefaultCallAction : InvokeMemberBinder {
            private LanguageContext _context;

            internal DefaultCallAction(LanguageContext context, string name, bool ignoreCase, CallInfo callInfo)
                : base(name, ignoreCase, callInfo) {
                _context = context;
            }

            public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) {
                return ErrorMetaObject(ReturnType, target, args.AddFirst(target), errorSuggestion);
            }

            private static Expression[] GetArgs(DynamicMetaObject target, DynamicMetaObject[] args) {
                Expression[] res = new Expression[args.Length + 1];
                res[0] = target.Expression;
                for (int i = 0; i < args.Length; i++) {
                    res[1 + i] = args[i].Expression;
                }

                return res;
            }

            public override DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) {
                return new DynamicMetaObject(
                    DynamicExpression.Dynamic(
                        _context.CreateInvokeBinder(CallInfo),
                        typeof(object),
                        GetArgs(target, args)
                    ),
                    target.Restrictions.Merge(BindingRestrictions.Combine(args))
                );
            }
        }

        public virtual InvokeMemberBinder CreateCallBinder(string name, bool ignoreCase, CallInfo callInfo) {
            return new DefaultCallAction(this, name, ignoreCase, callInfo);
        }

        private class DefaultInvokeAction : InvokeBinder {
            internal DefaultInvokeAction(CallInfo callInfo)
                : base(callInfo) {
            }

            public override DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) {
                return ErrorMetaObject(ReturnType, target, args, errorSuggestion);
            }
        }

        public virtual InvokeBinder CreateInvokeBinder(CallInfo callInfo) {
            return new DefaultInvokeAction(callInfo);
        }

        private class DefaultCreateAction : CreateInstanceBinder {
            internal DefaultCreateAction(CallInfo callInfo)
                : base(callInfo) {
            }

            public override DynamicMetaObject FallbackCreateInstance(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) {
                return ErrorMetaObject(ReturnType, target, args, errorSuggestion);
            }
        }

        public virtual CreateInstanceBinder CreateCreateBinder(CallInfo callInfo) {
            return new DefaultCreateAction(callInfo);
        }

        public DynamicOperations Operations {
            get {
                if (_operations == null) {
                    Interlocked.CompareExchange(ref _operations, new DynamicOperations(this), null);
                }

                return _operations;
            }
        }
        #endregion

        #region Object Introspection Support

        /// <summary>
        /// Gets the member names associated with the object
        /// By default, only returns IDO names
        /// </summary>
        public virtual IList<string> GetMemberNames(object obj) {
            var ido = obj as IDynamicMetaObjectProvider;
            if (ido != null) {
                var mo = ido.GetMetaObject(Expression.Parameter(typeof(object), null));
                return mo.GetDynamicMemberNames().ToReadOnly();
            }
            return EmptyArray<string>.Instance;
        }

        public virtual string GetDocumentation(object obj) {
            return String.Empty;
        }

        public virtual IList<string> GetCallSignatures(object obj) {
            return new string[0];
        }

        public virtual bool IsCallable(object obj) {
            if (obj == null) {
                return false;
            }

            return typeof(Delegate).GetTypeInfo().IsAssignableFrom(obj.GetType().GetTypeInfo());
        }

        #endregion

        #region Object formatting

        /// <summary>
        /// Returns a string representation of the object in a language specific object display format.
        /// </summary>
        /// <param name="operations">Dynamic sites container that could be used for any dynamic dispatches necessary for formatting.</param>
        /// <param name="obj">Object to format.</param>
        /// <returns>A string representation of object.</returns>
        public virtual string FormatObject(DynamicOperations operations, object obj) {
            return obj == null ? "null" : obj.ToString();
        }

        public virtual void GetExceptionMessage(Exception exception, out string message, out string errorTypeName) {
            message = exception.Message;
            errorTypeName = exception.GetType().Name;
        }

        #endregion

    }
}


text:
using namespace std;

// Config variables (defined elsewhere)
extern size_t RAND_POOL_SIZE;
extern size_t total;
extern size_t CURRENT_TEST_MAX;
extern unsigned int times;
extern std::vector<uint_fast64_t> running_sums;

// Check 2D encode function performance (linear)
template <typename morton, typename coord>
static double testEncode_2D_Linear_Perf(morton(*function)(coord, coord), size_t times) {
	Timer timer = Timer();
	morton runningsum = 0;
	for (size_t t = 0; t < times; t++) {
		for (coord i = 0; i < CURRENT_TEST_MAX; i++) {
			for (coord j = 0; j < CURRENT_TEST_MAX; j++) {
				timer.start();
				runningsum += function(i, j);
				timer.stop();
			}
		}
	}
	running_sums.push_back(runningsum);
	return timer.elapsed_time_milliseconds / (float)times;
}

// Check 2D encode function performance (random)
template <typename morton, typename coord>
static double testEncode_2D_Random_Perf(morton(*function)(coord, coord), size_t times) {
	Timer timer = Timer();
	coord maximum = ~0;
	morton runningsum = 0;
	coord x, y, z;

	for (size_t t = 0; t < times; t++) {
		// Create a pool of random numbers
		std::vector<coord> randnumbers;
		for (size_t i = 0; i < RAND_POOL_SIZE; i++) {
			randnumbers.push_back(rand() % maximum);
		}
		// Do the performance test
		for (size_t i = 0; i < total; i++) {
			x = randnumbers[i % RAND_POOL_SIZE];
			y = randnumbers[(i + 1) % RAND_POOL_SIZE];
			timer.start();
			runningsum += function(x, y);
			timer.stop();
		}
	}
	running_sums.push_back(runningsum);
	return timer.elapsed_time_milliseconds / (float)times;
}

// TODO: Check 2D decode function performance (linear)
template <typename morton, typename coord>
static double testDecode_2D_Linear_Perf(void(*function)(const morton, coord&, coord&), size_t times) {
	size_t max_morton = CURRENT_TEST_MAX * CURRENT_TEST_MAX;
	Timer timer = Timer();
	coord x, y;
	coord runningsum = 0;
	for (size_t t = 0; t < times; t++) {
		for (morton i = 0; i < max_morton; i += 8) {
			timer.start();
			function(i, x, y);
			runningsum += x + y;
			function(i + 1, x, y);
			runningsum += x + y;
			function(i + 2, x, y);
			runningsum += x + y;
			function(i + 3, x, y);
			runningsum += x + y;
			function(i + 4, x, y);
			runningsum += x + y;
			function(i + 5, x, y);
			runningsum += x + y;
			function(i + 6, x, y);
			runningsum += x + y;
			function(i + 7, x, y);
			runningsum += x + y;
			timer.stop();
		}
	}
	running_sums.push_back(runningsum);
	return timer.elapsed_time_milliseconds / (float)times;
}

// TODO: Check 2D decode function performance (random)
template <typename morton, typename coord>
static double testDecode_2D_Random_Perf(void(*function)(const morton, coord&, coord&), size_t times) {
	Timer timer = Timer();
	coord x, y, z;
	morton maximum = ~0; // maximum for the random morton codes
	morton runningsum = 0;
	morton m;

	size_t max_morton = CURRENT_TEST_MAX * CURRENT_TEST_MAX;

	// Create a pool of randum numbers
	std::vector<morton> randnumbers;
	for (size_t i = 0; i < RAND_POOL_SIZE; i++) {
		randnumbers.push_back((morton(rand()) + morton(rand())) % maximum);
	}

	// Start performance test
	for (size_t t = 0; t < times; t++) {
		for (size_t i = 0; i < max_morton; i++) {
			m = randnumbers[i % RAND_POOL_SIZE];
			timer.start();
			function(m, x, y);
			timer.stop();
			runningsum += x + y;
		}
	}
	running_sums.push_back(runningsum);
	return timer.elapsed_time_milliseconds / (float)times;
}

static void test_2D_performance(vector<encode_2D_64_wrapper>* funcs64_encode, vector<encode_2D_32_wrapper>* funcs32_encode,
	vector<decode_2D_64_wrapper>* funcs64_decode, vector<decode_2D_32_wrapper>* funcs32_decode) {
	cout << "++ (2D) Encoding " << CURRENT_TEST_MAX << "^2 morton codes (" << total << " in total)" << endl;
	cout << "+++ (2D) Encoding 64-bit sized morton codes" << endl;
	stringstream os;
	//os << setfill('0') << std::setw(6) << std::fixed << std::setprecision(3);
	for (auto it = (*funcs64_encode).begin(); it != (*funcs64_encode).end(); it++) {
		os.str("");
		os << testEncode_2D_Linear_Perf((*it).encode, times) << " ms\t";
		os << testEncode_2D_Random_Perf((*it).encode, times) << " ms\t";
		cout << os.str() << "64-bit " << (*it).description << endl;
	}
	cout << "+++ (2D) Encoding 32-bit sized morton codes" << endl;
	for (auto it = (*funcs32_encode).begin(); it != (*funcs32_encode).end(); it++) {
		os.str("");
		os << testEncode_2D_Linear_Perf((*it).encode, times) << " ms\t";
		os << testEncode_2D_Random_Perf((*it).encode, times) << " ms\t";
		cout << os.str() << "32-bit " << (*it).description << endl;
	}
	 cout << "++ (2D) Decoding " << CURRENT_TEST_MAX << "^2 morton codes (" << total << " in total)" << endl;
	 cout << "+++ (2D) Decoding 64-bit sized morton codes" << endl;
	 for (auto it = (*funcs64_decode).begin(); it != (*funcs64_decode).end(); it++) {
	 	os.str("");
	 	os << testDecode_2D_Linear_Perf((*it).decode, times) << " ms\t";
	 	os << testDecode_2D_Random_Perf((*it).decode, times) << " ms\t";
	 	cout << os.str() << "64-bit " << (*it).description << endl;
	 }
	 cout << "+++ (2D) Decoding 32-bit sized morton codes" << endl;
	 for (auto it = (*funcs32_decode).begin(); it != (*funcs32_decode).end(); it++) {
	 	os.str("");
	 	os << setfill('0') << std::setw(6) << std::fixed << std::setprecision(3);
	 	os << testDecode_2D_Linear_Perf((*it).decode, times) << " ms\t";
	 	os << testDecode_2D_Random_Perf((*it).decode, times) << " ms\t";
	 	cout << os.str() << "32-bit " << (*it).description << endl;
	 }
}

redpajama_set_name: RedPajamaGithub


text:
package org.michenux.drodrolib.ui.listener;

import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.view.View;

/**
 * @author Michenux
 *
 */
public class StartActivityOnClickListener implements View.OnClickListener {

	/**
	 *
	 */
	private Context context ;

	/**
	 *
	 */
	private Intent intent ;

	/**
	 *
	 */
	private Fragment fragment ;

	/**
	 * @param context
	 * @param objectClass
	 */
	public StartActivityOnClickListener(Context context, Class<?> objectClass) {
		super();
		this.context = context ;
		this.intent = new Intent(this.context, objectClass);
	}

	/**
	 * @param fragment
	 * @param objectClass
	 */
	public StartActivityOnClickListener(Fragment fragment, Class<?> objectClass) {
		super();
		this.fragment = fragment ;
		this.intent = new Intent(fragment.getActivity(), objectClass);
	}

	/**
	 * @param context
	 * @param intent
	 */
	public StartActivityOnClickListener(Context context, Intent intent) {
		super();
		this.context = context ;
		this.intent = intent;
	}

	/**
	 * {@inheritDoc}
	 */
	public void onClick(View view) {
		if ( this.context != null ) {
			this.context.startActivity(this.intent);
		}
		else {
			this.fragment.startActivity(this.intent);
		}
	}
}


text:
#include "MockHTTP2Connection.h"

namespace alexaClientSDK {
namespace avsCommon {
namespace utils {
namespace http2 {
namespace test {

using namespace ::testing;
using namespace avsCommon::utils::http;

MockHTTP2Connection::MockHTTP2Connection(std::string dURL, std::string pingURL, bool delegateToReal) :
        m_downchannelURL{dURL},
        m_pingURL{pingURL},
        m_postResponseCode{HTTPResponseCode::HTTP_RESPONSE_CODE_UNDEFINED},
        m_maxPostRequestsEnqueued{0} {
    if (delegateToReal) {
        ON_CALL(*this, createAndSendRequest(_))
            .WillByDefault(Invoke(this, &MockHTTP2Connection::createAndSendRequestConcrete));
    }
}

std::shared_ptr<HTTP2RequestInterface> MockHTTP2Connection::createAndSendRequestConcrete(
    const HTTP2RequestConfig& config) {
    std::lock_guard<std::mutex> lock(m_requestMutex);
    // Create HTTP2 request from config.
    auto request = std::make_shared<MockHTTP2Request>(config);

    // Add request to queue.
    m_requestQueue.push_back(request);

    // Notify any listeners that are waiting for a header match.
    if (m_headerMatch.length() > 0) {
        for (auto header : request->getSource()->getRequestHeaderLines()) {
            if (header.find(m_headerMatch) != std::string::npos) {
                m_requestHeaderCv.notify_one();
            }
        }
    }

    if (request->getRequestType() == HTTP2RequestType::POST) {
        // Parse POST HTTP2 Requests.
        std::lock_guard<std::mutex> innerLock(m_postRequestMutex);
        m_postRequestQueue.push_back(request);
        if (m_postResponseCode != HTTPResponseCode::HTTP_RESPONSE_CODE_UNDEFINED) {
            request->getSink()->onReceiveResponseCode(responseCodeToInt(m_postResponseCode));
        }
        if (m_postRequestQueue.size() > m_maxPostRequestsEnqueued) {
            m_maxPostRequestsEnqueued = m_postRequestQueue.size();
        }
        m_requestPostCv.notify_one();
    } else if (m_downchannelURL == request->getUrl()) {
        // Push downchannel requests to its queue.
        std::lock_guard<std::mutex> innerLock(m_downchannelRequestMutex);
        m_downchannelRequestQueue.push_back(request);
        m_downchannelRequestCv.notify_all();
    } else if (m_pingURL == request->getUrl()) {
        // Push ping requests to its queue.
        std::lock_guard<std::mutex> innerLock(m_pingRequestMutex);
        m_pingRequestQueue.push_back(request);
        m_pingRequestCv.notify_one();
    }

    m_requestCv.notify_one();
    return request;
}

bool MockHTTP2Connection::isRequestQueueEmpty() {
    std::lock_guard<std::mutex> lock(m_requestMutex);
    return m_requestQueue.empty();
}

std::shared_ptr<MockHTTP2Request> MockHTTP2Connection::waitForRequest(
    std::chrono::milliseconds timeout,
    unsigned requestNum) {
    std::unique_lock<std::mutex> lock(m_requestMutex);
    if (!m_requestCv.wait_for(lock, timeout, [this, requestNum] {
            return !m_requestQueue.empty() && m_requestQueue.size() >= requestNum;
        })) {
        return nullptr;
    }
    return m_requestQueue.front();
}

std::shared_ptr<MockHTTP2Request> MockHTTP2Connection::dequeRequest() {
    std::lock_guard<std::mutex> lock(m_requestMutex);
    auto req = m_requestQueue.front();
    m_requestQueue.pop_front();
    return req;
}

void MockHTTP2Connection::setWaitRequestHeader(const std::string& matchString) {
    std::lock_guard<std::mutex> lock(m_requestMutex);
    m_headerMatch = matchString;
}

bool MockHTTP2Connection::waitForRequestWithHeader(std::chrono::milliseconds timeout) {
    if (waitForRequest(timeout)) {
        std::unique_lock<std::mutex> lock(m_requestMutex);
        return m_requestHeaderCv.wait_for(lock, timeout, [this] { return !m_requestQueue.empty(); });
    }

    return false;
}

std::shared_ptr<MockHTTP2Request> MockHTTP2Connection::waitForPostRequest(const std::chrono::milliseconds timeout) {
    std::unique_lock<std::mutex> lock(m_postRequestMutex);

    if (!m_requestPostCv.wait_for(lock, timeout, [this] { return !m_postRequestQueue.empty(); })) {
        return nullptr;
    }

    auto request = m_postRequestQueue.back();

    // Need to send 200 to MIME decoder in order for it parse the message.
    request->getMimeDecoder()->onReceiveResponseCode(
        static_cast<std::underlying_type<HTTPResponseCode>::type>(HTTPResponseCode::SUCCESS_OK));

    // Feed the header lines to the MIME decoder.
    for (auto headerLine : request->getSource()->getRequestHeaderLines()) {
        request->getMimeDecoder()->onReceiveHeaderLine(headerLine);
    }

    // Feed the data to the MIME decoder.
    char buf[READ_DATA_BUF_SIZE] = {'\0'};
    bool stop = false;
    do {
        auto res = request->getSource()->onSendData(buf, READ_DATA_BUF_SIZE);
        switch (res.status) {
            case HTTP2SendStatus::COMPLETE:
            case HTTP2SendStatus::ABORT:
                stop = true;
                break;
            case HTTP2SendStatus::PAUSE:
                if (!isPauseOnSendReceived()) {
                    m_receivedPauseOnSend.setValue();
                }
            // fall-through
            case HTTP2SendStatus::CONTINUE:
                break;
        }
        if (stop) {
            break;
        }

        request->getMimeDecoder()->onReceiveData(buf, res.size);

    } while (true);

    return request;
}

std::shared_ptr<MockHTTP2Request> MockHTTP2Connection::waitForPingRequest(const std::chrono::milliseconds timeout) {
    std::unique_lock<std::mutex> lock(m_pingRequestMutex);
    if (!m_pingRequestCv.wait_for(lock, timeout, [this] { return !m_pingRequestQueue.empty(); })) {
        return nullptr;
    }

    return m_pingRequestQueue.back();
}

bool MockHTTP2Connection::respondToDownchannelRequests(
    long responseCode,
    bool sendResponseFinished,
    const std::chrono::milliseconds timeout) {
    std::unique_lock<std::mutex> lock(m_downchannelRequestMutex);
    auto ret = m_downchannelRequestCv.wait_for(lock, timeout, [this] { return !m_downchannelRequestQueue.empty(); });

    for (auto request : m_downchannelRequestQueue) {
        request->getSink()->onReceiveResponseCode(responseCode);
        if (sendResponseFinished) {
            request->getSink()->onResponseFinished(HTTP2ResponseFinishedStatus::COMPLETE);
        }
    }
    return ret;
}

void MockHTTP2Connection::setResponseToPOSTRequests(HTTPResponseCode responseCode) {
    std::lock_guard<std::mutex> lock(m_postRequestMutex);
    m_postResponseCode = responseCode;
}

std::shared_ptr<MockHTTP2Request> MockHTTP2Connection::getDownchannelRequest(std::chrono::milliseconds timeout) {
    std::unique_lock<std::mutex> lock(m_downchannelRequestMutex);
    m_downchannelRequestCv.wait_for(lock, timeout);
    if (m_downchannelRequestQueue.empty()) {
        return nullptr;
    }
    return m_downchannelRequestQueue.back();
}

bool MockHTTP2Connection::isPauseOnSendReceived(std::chrono::milliseconds timeout) {
    return m_receivedPauseOnSend.waitFor(timeout);
}

std::size_t MockHTTP2Connection::getPostRequestsNum() {
    return m_postRequestQueue.size();
}

std::size_t MockHTTP2Connection::getRequestsNum() {
    return m_requestQueue.size();
}

std::size_t MockHTTP2Connection::getDownchannelRequestsNum() {
    return m_downchannelRequestQueue.size();
}

std::shared_ptr<MockHTTP2Request> MockHTTP2Connection::dequePostRequest() {
    std::lock_guard<std::mutex> lock(m_postRequestMutex);
    if (m_postRequestQueue.empty()) {
        return nullptr;
    }
    auto req = m_postRequestQueue.front();
    m_postRequestQueue.pop_front();
    return req;
}

std::shared_ptr<MockHTTP2Request> MockHTTP2Connection::dequePostRequest(const std::chrono::milliseconds timeout) {
    auto req = dequePostRequest();

    if (!req) {
        if (waitForPostRequest(timeout) == nullptr) {
            return nullptr;
        }
        req = dequePostRequest();
    }

    return req;
}

std::shared_ptr<MockHTTP2Request> MockHTTP2Connection::dequePingRequest() {
    std::lock_guard<std::mutex> lock(m_pingRequestMutex);
    if (m_pingRequestQueue.empty()) {
        return nullptr;
    }
    auto req = m_pingRequestQueue.front();
    m_pingRequestQueue.pop_front();
    return req;
}

std::size_t MockHTTP2Connection::getMaxPostRequestsEnqueud() {
    return m_maxPostRequestsEnqueued;
}

void MockHTTP2Connection::addObserver(std::shared_ptr<HTTP2ConnectionObserverInterface> observer) {
    std::lock_guard<std::mutex> lock{m_observersMutex};
    m_observers.insert(observer);
}
void MockHTTP2Connection::removeObserver(std::shared_ptr<HTTP2ConnectionObserverInterface> observer) {
    std::lock_guard<std::mutex> lock{m_observersMutex};
    m_observers.erase(observer);
}

}  // namespace test
}  // namespace http2
}  // namespace utils
}  // namespace avsCommon
}  // namespace alexaClientSDK


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

<title>org.bouncycastle.cert.crmf.jcajce (Bouncy Castle Library 1.52 API Specification)</title>
<meta name="date" content="2015-03-01">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

org.bouncycastle.cert.crmf.jcajce

Classes

JcaCertificateRequestMessage

JcaCertificateRequestMessageBuilder

JcaEncryptedValueBuilder

JcaPKIArchiveControlBuilder

JceAsymmetricValueDecryptorGenerator

JceCRMFEncryptorBuilder

JcePKMACValuesCalculator


text:
package uniform

//go:generate gostub Factory

type Factory interface {
	CreateFloat3Uniform() (Float3Uniform, error)
	CreateFloat4Uniform() (Float4Uniform, error)
	CreateFloat4x4Uniform() (Float4x4Uniform, error)
}

type factory struct{}

func NewFactory() Factory {
	return &factory{}
}

func (f *factory) CreateFloat3Uniform() (Float3Uniform, error) {
	return newFloat3Uniform(), nil
}

func (f *factory) CreateFloat4Uniform() (Float4Uniform, error) {
	return newFloat4Uniform(), nil
}

func (f *factory) CreateFloat4x4Uniform() (Float4x4Uniform, error) {
	return newFloat4x4Uniform(), nil
}


text:
An example of output written to the file `./testMatrix.json` when coverage
is run with the `--matrix` cli flag. (Source project: [sc-forks/hardhat-e2e][1])

[1]: https://github.com/sc-forks/hardhat-e2e

```js
// Paths are relative to the project root directory
{
 // Solidity file name
 "contracts/EtherRouter/EtherRouter.sol": {

  // Line number
  "23": [
   {
    // Grep-able mocha test title
    "title": "Resolves methods routed through an EtherRouter proxy",

    // Selectable mocha test file
    "file": "test/etherrouter.js"
   }
  ],
  "42": [
   {
    "title": "Resolves methods routed through an EtherRouter proxy",
    "file": "test/etherrouter.js"
   }
  ],
  "45": [
   {
    "title": "Resolves methods routed through an EtherRouter proxy",
    "file": "test/etherrouter.js"
   }
  ],
  "61": [
   {
    "title": "Resolves methods routed through an EtherRouter proxy",
    "file": "test/etherrouter.js"
   }
  ]
 },
 "contracts/EtherRouter/Factory.sol": {
  "19": [
   {
    "title": "Resolves methods routed through an EtherRouter proxy",
    "file": "test/etherrouter.js"
   }
  ]
 },
 "contracts/EtherRouter/Resolver.sol": {
  "22": [
   {
    "title": "Resolves methods routed through an EtherRouter proxy",
    "file": "test/etherrouter.js"
   }
  ],
  "26": [
   {
    "title": "Resolves methods routed through an EtherRouter proxy",
    "file": "test/etherrouter.js"
   }
  ],
  "30": [
   {
    "title": "Resolves methods routed through an EtherRouter proxy",
    "file": "test/etherrouter.js"
   }
  ]
 },
 "contracts/MetaCoin.sol": {
  "16": [
   {
    "title": "should put 10000 MetaCoin in the first account",
    "file": "test/metacoin.js"
   },
   {
    "title": "should call a function that depends on a linked library",
    "file": "test/metacoin.js"
   },
   {
    "title": "should send coin correctly",
    "file": "test/metacoin.js"
   },
   {
    "title": "a and b",
    "file": "test/multicontract.js"
   }
  ],
  "20": [
   {
    "title": "should send coin correctly",
    "file": "test/metacoin.js"
   }
  ],
  "21": [
   {
    "title": "should send coin correctly",
    "file": "test/metacoin.js"
   }
  ],
  "22": [
   {
    "title": "should send coin correctly",
    "file": "test/metacoin.js"
   }
  ],
  "23": [
   {
    "title": "should send coin correctly",
    "file": "test/metacoin.js"
   }
  ],
  "24": [
   {
    "title": "should send coin correctly",
    "file": "test/metacoin.js"
   }
  ],
  "28": [
   {
    "title": "should call a function that depends on a linked library",
    "file": "test/metacoin.js"
   }
  ],
  "32": [
   {
    "title": "should put 10000 MetaCoin in the first account",
    "file": "test/metacoin.js"
   },
   {
    "title": "should call a function that depends on a linked library",
    "file": "test/metacoin.js"
   },
   {
    "title": "should send coin correctly",
    "file": "test/metacoin.js"
   }
  ]
 },
 "contracts/ConvertLib.sol": {
  "6": [
   {
    "title": "should call a function that depends on a linked library",
    "file": "test/metacoin.js"
   }
  ]
 },
 "contracts/MultiContractFile.sol": {
  "7": [
   {
    "title": "a and b",
    "file": "test/multicontract.js"
   },
   {
    "title": "methods that call methods in other contracts",
    "file": "test/variablecosts.js"
   }
  ],
  "15": [
   {
    "title": "a and b",
    "file": "test/multicontract.js"
   }
  ]
 },
 "contracts/VariableConstructor.sol": {
  "8": [
   {
    "title": "should should initialize with a short string",
    "file": "test/variableconstructor.js"
   },
   {
    "title": "should should initialize with a medium length string",
    "file": "test/variableconstructor.js"
   },
   {
    "title": "should should initialize with a long string",
    "file": "test/variableconstructor.js"
   },
   {
    "title": "should should initialize with a random length string",
    "file": "test/variableconstructor.js"
   }
  ]
 },
 "contracts/VariableCosts.sol": {
  "13": [
   {
    "title": "should should initialize with a short string",
    "file": "test/variableconstructor.js"
   },
   {
    "title": "should should initialize with a medium length string",
    "file": "test/variableconstructor.js"
   },
   {
    "title": "should should initialize with a long string",
    "file": "test/variableconstructor.js"
   },
   {
    "title": "should should initialize with a random length string",
    "file": "test/variableconstructor.js"
   },
   {
    "title": "should add one",
    "file": "test/variablecosts.js"
   },
   {
    "title": "should add three",
    "file": "test/variablecosts.js"
   },
   {
    "title": "should add even 5!",
    "file": "test/variablecosts.js"
   },
   {
    "title": "should delete one",
    "file": "test/variablecosts.js"
   },
   {
    "title": "should delete three",
    "file": "test/variablecosts.js"
   },
   {
    "title": "should delete five",
    "file": "test/variablecosts.js"
   },
   {
    "title": "should add five and delete one",
    "file": "test/variablecosts.js"
   },
   {
    "title": "should set a random length string",
    "file": "test/variablecosts.js"
   },
   {
    "title": "methods that do not throw",
    "file": "test/variablecosts.js"
   },
   {
    "title": "methods that throw",
    "file": "test/variablecosts.js"
   },
   {
    "title": "methods that call methods in other contracts",
    "file": "test/variablecosts.js"
   },
   {
    "title": "should allow contracts to have identically named methods",
    "file": "test/variablecosts.js"
   }
  ],
  "29": [
   {
    "title": "should add one",
    "file": "test/variablecosts.js"
   },
   {
    "title": "should add three",
    "file": "test/variablecosts.js"
   },
   {
    "title": "should add even 5!",
    "file": "test/variablecosts.js"
   },
   {
    "title": "should add five and delete one",
    "file": "test/variablecosts.js"
   }
  ],
  "30": [
   {
    "title": "should add one",
    "file": "test/variablecosts.js"
   },
   {
    "title": "should add three",
    "file": "test/variablecosts.js"
   },
   {
    "title": "should add even 5!",
    "file": "test/variablecosts.js"
   },
   {
    "title": "should add five and delete one",
    "file": "test/variablecosts.js"
   }
  ],
  "34": [
   {
    "title": "should delete one",
    "file": "test/variablecosts.js"
   },
   {
    "title": "should delete three",
    "file": "test/variablecosts.js"
   },
   {
    "title": "should delete five",
    "file": "test/variablecosts.js"
   },
   {
    "title": "should add five and delete one",
    "file": "test/variablecosts.js"
   }
  ],
  "35": [
   {
    "title": "should delete one",
    "file": "test/variablecosts.js"
   },
   {
    "title": "should delete three",
    "file": "test/variablecosts.js"
   },
   {
    "title": "should delete five",
    "file": "test/variablecosts.js"
   },
   {
    "title": "should add five and delete one",
    "file": "test/variablecosts.js"
   }
  ],
  "43": [
   {
    "title": "should set a random length string",
    "file": "test/variablecosts.js"
   }
  ],
  "47": [
   {
    "title": "methods that do not throw",
    "file": "test/variablecosts.js"
   },
   {
    "title": "methods that throw",
    "file": "test/variablecosts.js"
   }
  ],
  "48": [
   {
    "title": "methods that do not throw",
    "file": "test/variablecosts.js"
   }
  ],
  "52": [
   {
    "title": "methods that call methods in other contracts",
    "file": "test/variablecosts.js"
   }
  ],
  "53": [
   {
    "title": "methods that call methods in other contracts",
    "file": "test/variablecosts.js"
   }
  ],
  "54": [
   {
    "title": "methods that call methods in other contracts",
    "file": "test/variablecosts.js"
   }
  ]
 },
 "contracts/Wallets/Wallet.sol": {
  "8": [
   {
    "title": "should allow contracts to have identically named methods",
    "file": "test/variablecosts.js"
   },
   {
    "title": "should should allow transfers and sends",
    "file": "test/wallet.js"
   }
  ],
  "12": [
   {
    "title": "should allow contracts to have identically named methods",
    "file": "test/variablecosts.js"
   },
   {
    "title": "should should allow transfers and sends",
    "file": "test/wallet.js"
   }
  ],
  "17": [
   {
    "title": "should allow contracts to have identically named methods",
    "file": "test/variablecosts.js"
   },
   {
    "title": "should should allow transfers and sends",
    "file": "test/wallet.js"
   }
  ],
  "22": [
   {
    "title": "should allow contracts to have identically named methods",
    "file": "test/variablecosts.js"
   },
   {
    "title": "should should allow transfers and sends",
    "file": "test/wallet.js"
   }
  ],
  "23": [
   {
    "title": "should allow contracts to have identically named methods",
    "file": "test/variablecosts.js"
   },
   {
    "title": "should should allow transfers and sends",
    "file": "test/wallet.js"
   }
  ]
 }
}
```


text:
<?php

  /**
  *
  */

 	require_once(__CA_LIB_DIR__.'/ca/Browse/BaseBrowse.php');
 	require_once(__CA_LIB_DIR__.'/ca/Browse/TourBrowseResult.php');

	class TourBrowse extends BaseBrowse {
		# ------------------------------------------------------
		/**
		 * Which table does this class represent?
		 */
		protected $ops_tablename = "ca_tours";
		protected $ops_primary_key = "tour_id";
		# ----------------------------------------------------------------------
		public function __construct($pn_browse_id=null, $ps_context='') {
			parent::__construct($this->ops_tablename, $pn_browse_id, $ps_context);
		}
		# ------------------------------------------------------
		public function getResults($pa_options=null) {
			return parent::doGetResults(new TourBrowseResult(), $pa_options);
		}
		# ----------------------------------------------------------------------
	}
?>


text:
.thz-typography-group {
	display:block;
	float:left;
	margin:10px;
	position:relative;
}
.thz-typography-group span {
	display:block;
	clear:both;
}
.thz-fontbox {
	display:block;
	position:relative;
	clear:both;
}
.thz-fontbox:before,
.thz-fontbox:after{
	display:table;
	content:'';
	clear:both;
}
#thz-font-selector {
	display:none;
	clear:both;
	float:left;
}
.thz-font-input {
	cursor:pointer;
}
.thz-typography-preview {
	display: block;
	border: 1px solid #ccc;
	border-radius: 5px;
	clear: both;
	margin:10px;
	overflow: hidden;
	float: left;
	padding: 30px;
	font-size: 28px;
	line-height: 1.4;
	text-align: center;
	max-width: 500px;
}
.thz-typography-subsets {
	display:none;
}
.thz-typography-group .iris-picker{
	position:absolute;
	z-index: 99999;
}


text:
#if !defined(BOOST_SPIRIT_GRAMMAR_FEBRUARY_19_2007_0236PM)
#define BOOST_SPIRIT_GRAMMAR_FEBRUARY_19_2007_0236PM

#if defined(_MSC_VER)
#pragma once
#endif

#include <lslboost/spirit/home/support/unused.hpp>
#include <lslboost/spirit/home/support/info.hpp>
#include <lslboost/spirit/home/support/assert_msg.hpp>
#include <lslboost/spirit/home/qi/domain.hpp>
#include <lslboost/spirit/home/qi/nonterminal/rule.hpp>
#include <lslboost/spirit/home/qi/nonterminal/nonterminal_fwd.hpp>
#include <lslboost/spirit/home/qi/reference.hpp>
#include <lslboost/noncopyable.hpp>
#include <lslboost/type_traits/is_same.hpp>

namespace lslboost { namespace spirit { namespace qi
{
    template <
        typename Iterator, typename T1, typename T2, typename T3
      , typename T4>
    struct grammar
      : proto::extends<
            typename proto::terminal<
                reference<rule<Iterator, T1, T2, T3, T4> const>
            >::type
          , grammar<Iterator, T1, T2, T3, T4>
        >
      , parser<grammar<Iterator, T1, T2, T3, T4> >
      , noncopyable
    {
        typedef Iterator iterator_type;
        typedef rule<Iterator, T1, T2, T3, T4> start_type;
        typedef typename start_type::sig_type sig_type;
        typedef typename start_type::locals_type locals_type;
        typedef typename start_type::skipper_type skipper_type;
        typedef typename start_type::encoding_type encoding_type;
        typedef grammar<Iterator, T1, T2, T3, T4> base_type;
        typedef reference<start_type const> reference_;
        typedef typename proto::terminal<reference_>::type terminal;

        static size_t const params_size = start_type::params_size;

        template <typename Context, typename Iterator_>
        struct attribute
        {
            typedef typename start_type::attr_type type;
        };

        grammar(
            start_type const& start
          , std::string const& name_ = "unnamed-grammar")
        : proto::extends<terminal, base_type>(terminal::make(reference_(start)))
        , name_(name_)
        {}

        // This constructor is used to catch if the start rule is not
        // compatible with the grammar.
        template <typename Iterator_,
            typename T1_, typename T2_, typename T3_, typename T4_>
        grammar(
            rule<Iterator_, T1_, T2_, T3_, T4_> const&
          , std::string const& = "unnamed-grammar")
        {
            // If you see the assertion below failing then the start rule
            // passed to the constructor of the grammar is not compatible with
            // the grammar (i.e. it uses different template parameters).
            BOOST_SPIRIT_ASSERT_MSG(
                (is_same<start_type, rule<Iterator_, T1_, T2_, T3_, T4_> >::value)
              , incompatible_start_rule, (rule<Iterator_, T1_, T2_, T3_, T4_>));
        }

        std::string name() const
        {
            return name_;
        }

        void name(std::string const& str)
        {
            name_ = str;
        }

        template <typename Context, typename Skipper, typename Attribute>
        bool parse(Iterator& first, Iterator const& last
          , Context& context, Skipper const& skipper
          , Attribute& attr) const
        {
            return this->proto_base().child0.parse(
                first, last, context, skipper, attr);
        }

        template <typename Context>
        info what(Context&) const
        {
            return info(name_);
        }

        // bring in the operator() overloads
        start_type const& get_parameterized_subject() const
        { return this->proto_base().child0.ref.get(); }
        typedef start_type parameterized_subject_type;
        #include <lslboost/spirit/home/qi/nonterminal/detail/fcall.hpp>

        std::string name_;

    };
}}}

namespace lslboost { namespace spirit { namespace traits
{
    ///////////////////////////////////////////////////////////////////////////
    template <
        typename IteratorA, typename IteratorB, typename Attribute
      , typename Context, typename T1, typename T2, typename T3, typename T4>
    struct handles_container<
        qi::grammar<IteratorA, T1, T2, T3, T4>, Attribute, Context, IteratorB>
      : traits::is_container<
          typename attribute_of<
              qi::grammar<IteratorA, T1, T2, T3, T4>, Context, IteratorB
          >::type
        >
    {};
}}}

#endif


text:
var elixir = require('laravel-elixir');

/*
 |--------------------------------------------------------------------------
 | Elixir Asset Management
 |--------------------------------------------------------------------------
 |
 | Elixir provides a clean, fluent API for defining some basic Gulp tasks
 | for your Laravel application. By default, we are compiling the Sass
 | file for our application, as well as publishing vendor resources.
 |
 */

elixir(function(mix) {
    /*
    | ---------------------------------------------------------------------
    | Stylesheets
    | ---------------------------------------------------------------------
    */
    mix.sass('app.scss', 'public/css/app.css');

    /*
    | ---------------------------------------------------------------------
    | Javascripts
    | ---------------------------------------------------------------------
    */
    mix.scripts([
        'toggler.js',
        'sticky.js',
        'vendorInits.js',
        'toolbar.js',
        'search.js',
    ], 'public/js/app.js');
});


text:
## LabeledInput

TODOC


text:
@implementation GIRI

+ (void)recognizeSpeech:(NSString*)wavFile durationPerFile:(NSInteger)durationPerFile onComplete:(void (^)(NSString* text, NSError *error))onComplete {
    const char *wave_file = [wavFile UTF8String];

    //convert to FLAC
    NSString *flacFileWithoutExtension = [NSTemporaryDirectory() stringByAppendingPathComponent:@"tmp"];
    char** flac_files = (char**) malloc(sizeof(char*) * 1024);
    for(int i = 0; i < 1024; i++) {
        *(flac_files+i) = NULL;
    }
    int conversionResult = convertWavToFlac(wave_file, [flacFileWithoutExtension UTF8String], 20, flac_files);

    if(conversionResult == 0) {
        //convert the output files to an array of strings
        NSMutableArray *flacFilesOut = [NSMutableArray array];
        for(int i = 0; i < 1024; i++) {
            char *out_file = *(flac_files+i);
            if(out_file == NULL) {
                break;
            }
            [flacFilesOut addObject:[NSString stringWithUTF8String:out_file]];
            free(out_file);
        }

        GISpeechRecognitionController *speechRecognitionController = [GISpeechRecognitionController sharedInstance];
        [speechRecognitionController googleSpeechRecognizeFiles:flacFilesOut currentText:[[NSMutableString alloc] init] onComplete:^(NSString *text, NSError *error) {
            onComplete(text, error);
        }];
    }
    else {
        NSDictionary *errorDict = [NSDictionary dictionaryWithObjectsAndKeys:@"Error converting wave file to flac file", NSLocalizedDescriptionKey, nil];
        onComplete(nil, [NSError errorWithDomain:@"GIRI" code:0 userInfo:errorDict]);
    }
}

+ (void)recognizeSpeech:(NSString*)wavFile onComplete:(void (^)(NSString* text, NSError *error))onComplete {
    [GIRI recognizeSpeech:wavFile durationPerFile:20 onComplete:onComplete];
}

@end


text:
package org.unbrokendome.gradle.plugins.gitversion.model;

import java.io.File;
import java.util.Collections;
import java.util.function.Supplier;

public class MockGitRepositoryFactory implements GitRepositoryFactory {

    private final Supplier<String> branchNameSupplier;

    public MockGitRepositoryFactory(String branchName) {
        this(() -> branchName);
    }

    public MockGitRepositoryFactory(Supplier<String> branchNameSupplier) {
        this.branchNameSupplier = branchNameSupplier;
    }

    @Override
    public CloseableGitRepository getRepository(File dir) {
        MockGitRepositoryBuilder builder = MockGitRepository.builder()
                .setWorkingDir(dir)
                .checkoutNew("master")
                .commit("initial commit");

        String branchName = branchNameSupplier.get();
        if (branchName != null) {
            builder.checkout(branchName);
        } else {
            builder.detach();
        }

        return builder.build();
    }
}


text:
@interface PodsDummy_Pods_ZCMobilePayment_Tests : NSObject
@end
@implementation PodsDummy_Pods_ZCMobilePayment_Tests
@end


text:
import {ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, ViewEncapsulation} from "@angular/core";
import {CommandFactory, ICommand, Library, Oas20Document, OasDocument, OasInfo} from "apicurio-data-models";
import {CommandService} from "../../../_services/command.service";
import {AbstractBaseComponent} from "../../common/base-component";
import {DocumentService} from "../../../_services/document.service";
import {SelectionService} from "../../../_services/selection.service";

@Component({
    selector: "info-section",
    templateUrl: "info-section.component.html",
    encapsulation: ViewEncapsulation.None,
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class InfoSectionComponent extends AbstractBaseComponent {

    @Input() document: OasDocument;

    constructor(private changeDetectorRef: ChangeDetectorRef, private documentService: DocumentService,
                private commandService: CommandService, private selectionService: SelectionService) {
        super(changeDetectorRef, documentService, selectionService);
    }

    public info(): OasInfo {
        return this.document.info;
    }

    /**
     * returns the version.
     */
    public version(): string {
        if (this.info()) {
            return this.info().version;
        } else {
            return null;
        }
    }

    /**
     * returns the description.
     */
    public description(): string {
        if (this.info()) {
            return this.info().description;
        } else {
            return null;
        }
    }

    /**
     * Called when the user changes the version.
     * @param newVersion
     */
    public onVersionChange(newVersion: string): void {
        console.info("[InfoSectionComponent] User changed the version to: ", newVersion);
        let command: ICommand = CommandFactory.createChangeVersionCommand(newVersion);
        this.commandService.emit(command);
    }

    /**
     * Called when the user changes the description.
     * @param newDescription
     */
    public onDescriptionChange(newDescription: string): void {
        console.info("[InfoSectionComponent] User changed the description.");
        let command: ICommand = CommandFactory.createChangeDescriptionCommand(newDescription);
        this.commandService.emit(command);
    }

    /**
     * Called when the user changes the "consumes".
     * @param newValue
     */
    public onConsumesChange(newValue: string[]): void {
        console.info("[InfoSectionComponent] User changed the consumes to: ", newValue);
        let command: ICommand = CommandFactory.createChangePropertyCommand<string[]>(this.document, "consumes", newValue);
        this.commandService.emit(command);
    }

    /**
     * Called when the user changes the "produces".
     * @param newValue
     */
    public onProducesChange(newValue: string[]): void {
        console.info("[InfoSectionComponent] User changed the produces to: ", newValue);
        let command: ICommand = CommandFactory.createChangePropertyCommand<string[]>(this.document, "produces", newValue);
        this.commandService.emit(command);
        let path = Library.createNodePath(this.document);
        path.appendSegment("produces", false);
        this.selectionService.select(path.toString());
    }

    public consumes(): string[] {
        return (this.document as Oas20Document).consumes;
    }

    public produces(): string[] {
        return (this.document as Oas20Document).produces;
    }

}


text:
<!DOCTYPE html>

  <title>Get and set cursor position with contenteditable div</title>
  <meta charset="UTF-8">

contenteditable means this div can be edit.

  <button onclick="set_mouse_position()">Set Mouse Position</button>
  <button onclick="get_mouse_position()">Get Mouse Position</button>


text:
package org.myrobotlab.net.http;

public final class ResponseException extends Exception {

	private static final long serialVersionUID = 1L;
	private final Response.Status status;

    public ResponseException(Response.Status status, String message) {
        super(message);
        this.status = status;
    }

    public ResponseException(Response.Status status, String message, Exception e) {
        super(message, e);
        this.status = status;
    }

    public Response.Status getStatus() {
        return status;
    }
}


text:
import React from 'react'
import { Grid, Segment } from 'shengnian-ui-react'

const GridExampleEqualWidthRow = () => (
  <Grid columns='equal'>
    <Grid.Row>
      <Grid.Column>
        <Segment>1</Segment>
      </Grid.Column>
      <Grid.Column>
        <Segment>2</Segment>
      </Grid.Column>
      <Grid.Column>
        <Segment>3</Segment>
      </Grid.Column>
      <Grid.Column>
        <Segment>4</Segment>
      </Grid.Column>
    </Grid.Row>
    <Grid.Row>
      <Grid.Column>
        <Segment>1</Segment>
      </Grid.Column>
      <Grid.Column>
        <Segment>2</Segment>
      </Grid.Column>
      <Grid.Column>
        <Segment>3</Segment>
      </Grid.Column>
    </Grid.Row>
    <Grid.Row>
      <Grid.Column>
        <Segment>1</Segment>
      </Grid.Column>
      <Grid.Column>
        <Segment>2</Segment>
      </Grid.Column>
    </Grid.Row>
  </Grid>
)

export default GridExampleEqualWidthRow


text:
var express = require('express');
var request = require('request');
var cheerio = require('cheerio');
var cache = require('memory-cache');
var config = require('../config');

var routes = function (s) {

    var productRouter = express.Router();
    var prds = [] ;
    var item = {} ;
    var scrape = function(html){

        var $ = cheerio.load(html);
        prds = [] ;

        $('.proList li').each(function (i, el) {
            try {
                item = {};
                item['site'] = s.site;
                item['href'] = s.burl + '/' + $(this).find('a').attr('href').split(/[?#]/)[0];
                item['image_tn'] = s.burl + $(this).find('img').attr('src');
                item['product'] = $(this).find('img').attr('alt');
                item['price'] = Number($(this).find('.cost').html().trim().split(/ /)[0].trim());
                item['stock'] = 1 ;
                prds.push(item);
            } catch (e) {
                console.log(i + item['product'] + e);
            }
        });

    };

    productRouter.route('/Products')

        .get(function(req, res) {

            var options = {
                url: s.burl + '/search.aspx?text='+req.query.q,
                headers: {
                    'User-Agent': 'Request'
                }
            };

            var html = cache.get( s.site + '-' + req.query.q );

            if(html){
                scrape(html) ;
                //console.log(html);
                res.set(config.res_headers).status(200).json(prds);

            } else {
                request(options, function (error, response, html) {
                    console.log('request callback ' + s.site);
                    if (error) {
                        res.set(config.res_headers).send(500);
                    } else {
                        cache.put(s.site + '-' + req.query.q, html, config.cache_expiry) ;
                        scrape(html) ;
                        res.set(config.res_headers).status(200).json(prds);
                    }
                });

            }

        });

    return productRouter;

};

module.exports = routes;


text:
namespace Wulf {
	namespace OpenGL {
		enum class Font {
			Normal = 0,
			Bold
		};
		class FontRenderer {
		public:
			FontRenderer(ResourceManager& mgr);
			~FontRenderer();
			void Initialize(const GLuint textureOffset = 10);
			void DrawString(const GLfloat x, const GLfloat y, const char *words, const Font font = Font::Normal);
			void DrawStringXY(const GLuint  x, const GLuint  y, const char *words, const Font font = Font::Normal);

		private:
			ResourceManager& mgr;

			std::vector<GLuint> programs;
			std::vector<char>   charNums;
			std::vector<GLuint> charPosses;
			std::vector<GLuint>  posPosses;
			std::vector<GLuint> scalePosses;

			// Aaaaaaaaaaaaaaaaaaaaa
			std::vector<std::vector<GLfloat>> charWidths;

			// Avoid recreating shit
			std::vector<GLubyte> chars;
			std::vector<GLfloat> poses;
			GLfloat width;
			char mchars;
			byte cchar;

			// OGL
			GLuint vao;
			GLuint charvbo, posvbo;

			// Viewport tinks
			GLfloat vWidth;
			GLfloat vHeight;
			GLfloat hvWidth;
			GLfloat hvHeight;
		};
	}
}


text:
#pragma once

#include <stdint.h>

namespace px4
{

class WorkQueue; // forward declaration

struct wq_config_t {
	const char *name;
	uint16_t stacksize;
	int8_t relative_priority; // relative to max
};

namespace wq_configurations
{
static constexpr wq_config_t rate_ctrl{"wq:rate_ctrl", 1952, 0}; // PX4 inner loop highest priority
static constexpr wq_config_t ctrl_alloc{"wq:ctrl_alloc", 9500, 0}; // PX4 control allocation, same priority as rate_ctrl

static constexpr wq_config_t SPI0{"wq:SPI0", 2336, -1};
static constexpr wq_config_t SPI1{"wq:SPI1", 2336, -2};
static constexpr wq_config_t SPI2{"wq:SPI2", 2336, -3};
static constexpr wq_config_t SPI3{"wq:SPI3", 2336, -4};
static constexpr wq_config_t SPI4{"wq:SPI4", 2336, -5};
static constexpr wq_config_t SPI5{"wq:SPI5", 2336, -6};
static constexpr wq_config_t SPI6{"wq:SPI6", 2336, -7};

static constexpr wq_config_t I2C0{"wq:I2C0", 2336, -8};
static constexpr wq_config_t I2C1{"wq:I2C1", 2336, -9};
static constexpr wq_config_t I2C2{"wq:I2C2", 2336, -10};
static constexpr wq_config_t I2C3{"wq:I2C3", 2336, -11};
static constexpr wq_config_t I2C4{"wq:I2C4", 2336, -12};

// PX4 att/pos controllers, highest priority after sensors.
static constexpr wq_config_t nav_and_controllers{"wq:nav_and_controllers", 2240, -13};

static constexpr wq_config_t INS0{"wq:INS0", 6000, -14};
static constexpr wq_config_t INS1{"wq:INS1", 6000, -15};
static constexpr wq_config_t INS2{"wq:INS2", 6000, -16};
static constexpr wq_config_t INS3{"wq:INS3", 6000, -17};

static constexpr wq_config_t hp_default{"wq:hp_default", 1900, -18};

static constexpr wq_config_t uavcan{"wq:uavcan", 3624, -19};

static constexpr wq_config_t UART0{"wq:UART0", 1536, -21};
static constexpr wq_config_t UART1{"wq:UART1", 1536, -22};
static constexpr wq_config_t UART2{"wq:UART2", 1536, -23};
static constexpr wq_config_t UART3{"wq:UART3", 1536, -24};
static constexpr wq_config_t UART4{"wq:UART4", 1536, -25};
static constexpr wq_config_t UART5{"wq:UART5", 1536, -26};
static constexpr wq_config_t UART6{"wq:UART6", 1536, -27};
static constexpr wq_config_t UART7{"wq:UART7", 1536, -28};
static constexpr wq_config_t UART8{"wq:UART8", 1536, -29};
static constexpr wq_config_t UART_UNKNOWN{"wq:UART_UNKNOWN", 1536, -30};

static constexpr wq_config_t lp_default{"wq:lp_default", 1920, -50};

static constexpr wq_config_t test1{"wq:test1", 2000, 0};
static constexpr wq_config_t test2{"wq:test2", 2000, 0};

} // namespace wq_configurations

/**
 * Start the work queue manager task.
 */
int WorkQueueManagerStart();

/**
 * Stop the work queue manager task.
 */
int WorkQueueManagerStop();

/**
 * Work queue manager status.
 */
int WorkQueueManagerStatus();

/**
 * Create (or find) a work queue with a particular configuration.
 *
 * @param new_wq		The work queue configuration (see WorkQueueManager.hpp).
 * @return		A pointer to the WorkQueue, or nullptr on failure.
 */
WorkQueue *WorkQueueFindOrCreate(const wq_config_t &new_wq);

/**
 * Map a PX4 driver device id to a work queue (by sensor bus).
 *
 * @param device_id		The PX4 driver's device id.
 * @return		A work queue configuration.
 */
const wq_config_t &device_bus_to_wq(uint32_t device_id);

/**
 * Map a serial device path (eg /dev/ttyS1) to a work queue.
 *
 * @param device_id		The device path.
 * @return		A work queue configuration.
 */
const wq_config_t &serial_port_to_wq(const char *serial);

const wq_config_t &ins_instance_to_wq(uint8_t instance);

} // namespace px4


text:
<?php
/**
 * Displays a select box with the available themes.
 *
 * @package    ##PROJECT_NAME##
 * @subpackage widget
 * @author     ##AUTHOR_NAME##
 */
class sfWidgetFormPlopChoiceTheme extends sfWidgetFormChoice
{
  public function configure($options = array(), $attributes = array())
  {
    $this->addOption('add_empty', false);

    parent::configure($options, $attributes);

    $this->setOption('choices', array());
  }

  public function getChoices()
  {
    $choices = sfPlop::getAllThemes();

    if ($this->options['add_empty'] === true)
      $choices = array('' => '') + $choices;

    return $choices;
  }
}


text:
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#pragma once

namespace Js {
    class ByteCodeBufferBuilder;
    class ByteCodeBufferReader;

    //
    // ScopeInfo is used to persist Scope info of outer functions. When reparsing deferred nested
    // functions, use persisted ScopeInfo to restore outer closures.
    //
    class ScopeInfo
    {
        friend class ByteCodeBufferBuilder;
        friend class ByteCodeBufferReader;

        DECLARE_RECYCLER_VERIFY_MARK_FRIEND()

        struct MapSymbolData
        {
            ByteCodeGenerator *byteCodeGenerator;
            FuncInfo* func;
            int nonScopeSymbolCount;
        };

        struct SymbolInfo
        {
            union
            {
                Field(PropertyId) propertyId;
                Field(PropertyRecord const*) name;
            };
            Field(SymbolType) symbolType;
            Field(bool) hasFuncAssignment : 1;
            Field(bool) isBlockVariable : 1;
            Field(bool) isConst : 1;
            Field(bool) isFuncExpr : 1;
            Field(bool) isModuleExportStorage : 1;
            Field(bool) isModuleImport : 1;
            Field(bool) needDeclaration : 1;
        };

    private:
        Field(ScopeInfo *) parent;               // link to parent scope info (if any)
        Field(FunctionInfo * const) functionInfo;// link to function owning this scope

        Field(BYTE) isDynamic : 1;             // isDynamic bit affects how deferredChild access global ref
        Field(BYTE) isObject : 1;              // isObject bit affects how deferredChild access closure symbols
        Field(BYTE) mustInstantiate : 1;       // the scope must be instantiated as an object/array
        Field(BYTE) isCached : 1;              // indicates that local vars and functions are cached across invocations
        Field(BYTE) areNamesCached : 1;
        Field(BYTE) hasLocalInClosure : 1;
        Field(BYTE) isGeneratorFunctionBody : 1;
        Field(BYTE) isAsyncFunctionBody : 1;
        Field(BYTE) isClassConstructor : 1;

        FieldNoBarrier(Scope *) scope;
        Field(::ScopeType) scopeType;
        Field(int) scopeId;
        Field(int) symbolCount;                // symbol count in this scope
        Field(SymbolInfo) symbols[];           // symbol PropertyIDs, index == sym.scopeSlot

    private:
        ScopeInfo(FunctionInfo * function, int symbolCount)
            : functionInfo(function), /*funcExprScopeInfo(nullptr), paramScopeInfo(nullptr),*/ symbolCount(symbolCount), parent(nullptr), scope(nullptr), areNamesCached(false), hasLocalInClosure(false), isGeneratorFunctionBody(false), isAsyncFunctionBody(false), isClassConstructor(false)/*, parentOnly(false)*/
        {
        }

        void SetSymbolId(int i, PropertyId propertyId)
        {
            Assert(!areNamesCached);
            Assert(i >= 0 && i < symbolCount);
            symbols[i].propertyId = propertyId;
        }

        void SetSymbolType(int i, SymbolType symbolType)
        {
            Assert(!areNamesCached);
            Assert(i >= 0 && i < symbolCount);
            symbols[i].symbolType = symbolType;
        }

        void SetHasFuncAssignment(int i, bool has)
        {
            Assert(!areNamesCached);
            Assert(i >= 0 && i < symbolCount);
            symbols[i].hasFuncAssignment = has;
        }

        void SetIsBlockVariable(int i, bool is)
        {
            Assert(!areNamesCached);
            Assert(i >= 0 && i < symbolCount);
            symbols[i].isBlockVariable = is;
        }

        void SetIsConst(int i, bool is)
        {
            Assert(!areNamesCached);
            Assert(i >= 0 && i < symbolCount);
            symbols[i].isConst = is;
        }

        void SetIsFuncExpr(int i, bool is)
        {
            Assert(!areNamesCached);
            Assert(i >= 0 && i < symbolCount);
            symbols[i].isFuncExpr = is;
        }

        void SetIsModuleExportStorage(int i, bool is)
        {
            Assert(!areNamesCached);
            Assert(i >= 0 && i < symbolCount);
            symbols[i].isModuleExportStorage = is;
        }

        void SetIsModuleImport(int i, bool is)
        {
            Assert(!areNamesCached);
            Assert(i >= 0 && i < symbolCount);
            symbols[i].isModuleImport = is;
        }

        void SetNeedDeclaration(int i, bool is)
        {
            Assert(!areNamesCached);
            Assert(i >= 0 && i < symbolCount);
            symbols[i].needDeclaration = is;
        }

        void SetPropertyName(int i, PropertyRecord const* name)
        {
            Assert(!areNamesCached);
            Assert(i >= 0 && i < symbolCount);
            symbols[i].name = name;
        }

        PropertyId GetSymbolId(int i) const
        {
            Assert(!areNamesCached);
            Assert(i >= 0 && i < symbolCount);
            return symbols[i].propertyId;
        }

        SymbolType GetSymbolType(int i) const
        {
            Assert(i >= 0 && i < symbolCount);
            return symbols[i].symbolType;
        }

        bool GetHasFuncAssignment(int i)
        {
            Assert(i >= 0 && i < symbolCount);
            return symbols[i].hasFuncAssignment;
        }

        bool GetIsModuleExportStorage(int i)
        {
            Assert(i >= 0 && i < symbolCount);
            return symbols[i].isModuleExportStorage;
        }

        bool GetIsModuleImport(int i)
        {
            Assert(i >= 0 && i < symbolCount);
            return symbols[i].isModuleImport;
        }

        bool GetNeedDeclaration(int i)
        {
            Assert(i >= 0 && i < symbolCount);
            return symbols[i].needDeclaration;
        }

        bool GetIsBlockVariable(int i)
        {
            Assert(i >= 0 && i < symbolCount);
            return symbols[i].isBlockVariable;
        }

        bool GetIsConst(int i)
        {
            Assert(i >= 0 && i < symbolCount);
            return symbols[i].isConst;
        }

        bool GetIsFuncExpr(int i)
        {
            Assert(i >= 0 && i < symbolCount);
            return symbols[i].isFuncExpr;
        }

        PropertyRecord const* GetPropertyName(int i)
        {
            Assert(areNamesCached);
            Assert(i >= 0 && i < symbolCount);
            return symbols[i].name;
        }

        void SaveSymbolInfo(Symbol* sym, MapSymbolData* mapSymbolData);

        static ScopeInfo* SaveScopeInfo(ByteCodeGenerator * byteCodeGenerator, Scope * scope, ScriptContext * scriptContext);
        static ScopeInfo* SaveOneScopeInfo(ByteCodeGenerator * byteCodeGenerator, Scope * scope, ScriptContext * scriptContext);

    public:
        FunctionInfo * GetFunctionInfo() const
        {
            return functionInfo;
        }

        ParseableFunctionInfo * GetParseableFunctionInfo() const
        {
            return functionInfo ? functionInfo->GetParseableFunctionInfo() : nullptr;
        }

        ScopeInfo* GetParentScopeInfo() const
        {
            return parent;//? parent->GetParseableFunctionInfo()->GetScopeInfo() : nullptr;
        }

        void SetParentScopeInfo(ScopeInfo * parent)
        {
            Assert(this->parent == nullptr);
            this->parent = parent;
        }

        Scope * GetScope() const
        {
            return scope;
        }

        void SetScope(Scope * scope)
        {
            this->scope = scope;
        }

        ::ScopeType GetScopeType() const
        {
            return scopeType;
        }

        void SetScopeType(::ScopeType type)
        {
            this->scopeType = type;
        }

        void SetScopeId(int id)
        {
            this->scopeId = id;
        }

        int GetScopeId() const
        {
            return scopeId;
        }

        int GetSymbolCount() const
        {
            return symbolCount;
        }

        bool IsObject() const
        {
            return isObject;
        }

        bool IsCached() const
        {
            return isCached;
        }

        void SetHasLocalInClosure(bool has)
        {
            hasLocalInClosure = has;
        }

        bool GetHasOwnLocalInClosure() const
        {
            return hasLocalInClosure;
        }

        bool IsGeneratorFunctionBody() const
        {
            return this->isGeneratorFunctionBody;
        }

        bool IsAsyncFunctionBody() const
        {
            return this->isAsyncFunctionBody;
        }

        bool IsClassConstructor() const
        {
            return this->isClassConstructor;
        }

        static void SaveEnclosingScopeInfo(ByteCodeGenerator* byteCodeGenerator, /*FuncInfo* parentFunc,*/ FuncInfo* func);

        void EnsurePidTracking(ScriptContext* scriptContext);

        void ExtractScopeInfo(Parser *parser, /*ByteCodeGenerator* byteCodeGenerator, FuncInfo* funcInfo,*/ Scope* scope);

        //
        // Turn on capturesAll for a Scope temporarily. Restore old capturesAll when this object
        // goes out of scope.
        //
        class AutoCapturesAllScope
        {
        private:
            Scope* scope;
            bool oldCapturesAll;

        public:
            AutoCapturesAllScope(Scope* scope, bool turnOn);
            ~AutoCapturesAllScope();
            bool OldCapturesAll() const
            {
                return oldCapturesAll;
            }
        };
    };
}


text:
%% Identifying Round Objects
% This example shows how to classify objects based on their roundness using
% |bwboundaries|, a boundary tracing routine.

% Copyright 1993-2013 The MathWorks, Inc.

%% Step 1: Read Image
% Read in |pills_etc.png|.

RGB = imread('./0.bmp');
imshow(RGB);

%% Step 2: Threshold the Image
% Convert the image to black and white in order to prepare for
% boundary tracing using |bwboundaries|.

I = rgb2gray(RGB);
threshold = graythresh(I);
bw = im2bw(I,threshold);
imshow(bw)

%% Step 3: Remove the Noise
% Using morphology functions, remove pixels which do not belong to the
% objects of interest.

% remove all object containing fewer than 30 pixels
bw = bwareaopen(bw,30);

% fill a gap in the pen's cap
se = strel('disk',2);
bw = imclose(bw,se);

% fill any holes, so that regionprops can be used to estimate
% the area enclosed by each of the boundaries
bw = imfill(bw,'holes');

imshow(bw)

%% Step 4: Find the Boundaries
% Concentrate only on the exterior boundaries.  Option 'noholes' will
% accelerate the processing by preventing |bwboundaries| from searching
% for inner contours.

[B,L] = bwboundaries(bw,'noholes');

% Display the label matrix and draw each boundary
imshow(label2rgb(L, @jet, [.5 .5 .5]))
hold on
for k = 1:length(B)
  boundary = B{k};
  plot(boundary(:,2), boundary(:,1), 'w', 'LineWidth', 2)
end

%% Step 5: Determine which Objects are Round
% Estimate each object's area and perimeter. Use these results
% to form a simple metric indicating the roundness of an object:
%
%  metric = 4*pi*area/perimeter^2.
%
% This metric is equal to one only for a circle and it is less than one for
% any other shape. The discrimination process can be controlled by setting
% an appropriate threshold. In this example use a threshold of 0.94 so
% that only the pills will be classified as round.
%
% Use |regionprops| to obtain estimates of the area for all of the objects.
% Notice that the label matrix returned by |bwboundaries| can be
% reused by |regionprops|.

stats = regionprops(L,'Area','Centroid');

threshold = 0.94;

% loop over the boundaries
for k = 1:length(B)

  % obtain (X,Y) boundary coordinates corresponding to label 'k'
  boundary = B{k};

  % compute a simple estimate of the object's perimeter
  delta_sq = diff(boundary).^2;
  perimeter = sum(sqrt(sum(delta_sq,2)));

  % obtain the area calculation corresponding to label 'k'
  area = stats(k).Area;

  % compute the roundness metric
  metric = 4*pi*area/perimeter^2;

  % display the results
  metric_string = sprintf('%2.2f',metric);

  % mark objects above the threshold with a black circle
  if metric > threshold
    centroid = stats(k).Centroid;
    plot(centroid(1),centroid(2),'ko');
  end

  text(boundary(1,2)-35,boundary(1,1)+13,metric_string,'Color','y',...
       'FontSize',14,'FontWeight','bold');

end

title(['Metrics closer to 1 indicate that ',...
       'the object is approximately round']);

displayEndOfDemoMessage(mfilename)


text:
using CsvHelper;
using DotNet.Highcharts.Options;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SpentBook.Domain;
using SpentBook.Web.Filters;
using SpentBook.Web.Models;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;

namespace SpentBook.Web.Controllers
{
    [JsonOutputWhenModelInvalid]
    [JsonOutputWhenGenericException]
    [Authorize]
    public class DashboardController : Controller
    {
        private IUnitOfWork uow;

        public DashboardController(IUnitOfWork uow)
        {
            this.uow = uow;
        }

        public ActionResult Index()
        {
            return View();
        }

        public PartialViewResult Dashboards()
        {
            var model = new DashboardsModel();
            model.Dashboards = uow.Dashboards.GetAll().ToList();

            return PartialView(model);
        }

        [ActionName("View")]
        public ActionResult Dashboard(string id)
        {
            var model = new DashboardModel();
            model.Dashboard = uow.Dashboards.Get(f => f.FriendlyUrl == id).FirstOrDefault();
            return View("Dashboard", model);
        }

        [HttpPost]
        public JsonResult Create(DashboardModel model)
        {
            var name = model.Name.Trim();
            var dashboard = new Dashboard()
            {
                Name = name,
                FriendlyUrl = Helper.CreateFriendlyURL(name)
            };

            var dashboardExists = uow.Dashboards.Get(f => f.FriendlyUrl == dashboard.FriendlyUrl).FirstOrDefault();
            if (dashboardExists != null)
                throw new Exception("Já existe um dashboard cadastrado com esse mesmo nome, tente outro.");

            uow.Dashboards.Insert(dashboard);
            uow.Save();

            return Json(new { Success = true });
        }

        [HttpGet]
        public JsonResult Delete(Guid id)
        {
            uow.Dashboards.Delete(id);
            uow.Save();

            //return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
            return Json(new { Success = true });
        }
    }
}


text:
class Protobuf240a < Formula
  homepage "https://github.com/google/protobuf"
  url "https://launchpad.net/ubuntu/+archive/primary/+files/protobuf_2.4.0a.orig.tar.gz"
  sha256 "bb20941d4958bcf2fa76fde251bb4f71463d4fe28884a015c7335894344cffcb"

  bottle do
    cellar :any
    sha256 "19d29ffebfeb9beab833b7e8254ad19de11afea643bab6381dd51858e6a680db" => :yosemite
    sha256 "8e6160ffa4e7d1eeb4dd293b07fe4dd5fd78b134ee5a0af6e77053a57a0ccea2" => :mavericks
    sha256 "5de5e189c764f8f1922754a31f5d4151b9d65cf60b9fccd54ec727dbbf54ed0e" => :mountain_lion
  end

  keg_only "Conflicts with protobuf in main repository."

  option :universal

  fails_with :llvm do
    build 2334
  end

  # Fix build with clang and libc++
  patch :DATA

  def install
    # Don't build in debug mode. See:
    # https://github.com/homebrew/homebrew/issues/9279
    ENV.prepend "CXXFLAGS", "-DNDEBUG"
    ENV.universal_binary if build.universal?

    system "./configure", "--disable-debug",
                          "--disable-dependency-tracking",
                          "--prefix=#{prefix}",
                          "--with-zlib"
    system "make"
    system "make", "install"

    # Install editor support and examples
    doc.install "editors", "examples"
  end

  def caveats; <<-EOS.undent
    Editor support and examples have been installed to:
      #{doc}
    EOS
  end

  test do
    (testpath/"test.proto").write <<-EOS.undent
      package test;
      message TestCase {
        required string name = 4;
      }
      message Test {
        repeated TestCase case = 1;
      }
    EOS

    system bin/"protoc", "test.proto", "--cpp_out=."
  end
end

__END__
diff --git a/src/google/protobuf/message.cc b/src/google/protobuf/message.cc
index 91e6878..0409a94 100644
--- a/src/google/protobuf/message.cc
+++ b/src/google/protobuf/message.cc
@@ -32,6 +32,7 @@
 //  Based on original Protocol Buffers design by
 //  Sanjay Ghemawat, Jeff Dean, and others.

+#include <istream>
 #include <stack>
 #include <google/protobuf/stubs/hash.h>


text:
package org.apache.camel.component.ganglia;

import info.ganglia.gmetric4j.Publisher;
import info.ganglia.gmetric4j.gmetric.GMetricSlope;
import info.ganglia.gmetric4j.gmetric.GMetricType;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.support.DefaultProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GangliaProducer extends DefaultProducer {

    private static final Logger LOG = LoggerFactory.getLogger(GangliaProducer.class);

    private final Publisher publisher;
    private final GangliaEndpoint gangliaEndpoint;

    public GangliaProducer(GangliaEndpoint endpoint, Publisher publisher) {
        super(endpoint);
        this.gangliaEndpoint = endpoint;
        this.publisher = publisher;
    }

    @Override
    public void process(Exchange exchange) throws Exception {
        Message message = exchange.getIn();

        GangliaConfiguration conf = gangliaEndpoint.getConfiguration();

        String groupName = conf.getGroupName();
        if (message.getHeaders().containsKey(GangliaConstants.GROUP_NAME)) {
            groupName = message.getHeader(GangliaConstants.GROUP_NAME, String.class);
        }

        String prefix = conf.getPrefix();
        String metricName = conf.getMetricName();
        if (message.getHeaders().containsKey(GangliaConstants.METRIC_NAME)) {
            metricName = message.getHeader(GangliaConstants.METRIC_NAME, String.class);
        }
        if (prefix != null && prefix.length() > 0) {
            metricName = prefix + "_" + metricName;
        }

        GMetricType type = conf.getType();
        if (message.getHeaders().containsKey(GangliaConstants.METRIC_TYPE)) {
            type = message.getHeader(GangliaConstants.METRIC_TYPE, GMetricType.class);
        }

        GMetricSlope slope = conf.getSlope();
        if (message.getHeaders().containsKey(GangliaConstants.METRIC_SLOPE)) {
            slope = message.getHeader(GangliaConstants.METRIC_SLOPE, GMetricSlope.class);
        }

        String units = conf.getUnits();
        if (message.getHeaders().containsKey(GangliaConstants.METRIC_UNITS)) {
            units = message.getHeader(GangliaConstants.METRIC_UNITS, String.class);
        }

        int tmax = conf.getTmax();
        if (message.getHeaders().containsKey(GangliaConstants.METRIC_TMAX)) {
            tmax = message.getHeader(GangliaConstants.METRIC_TMAX, Integer.class);
        }

        int dmax = conf.getDmax();
        if (message.getHeaders().containsKey(GangliaConstants.METRIC_DMAX)) {
            dmax = message.getHeader(GangliaConstants.METRIC_DMAX, Integer.class);
        }

        String value = message.getBody(String.class);
        if ((value == null || value.length() == 0)
                && (type == GMetricType.FLOAT || type == GMetricType.DOUBLE)) {
            LOG.debug("Metric {} string value was null, using NaN", metricName);
            value = "NaN";
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Sending metric {} to Ganglia: {}", metricName, value);
        }
        publisher.publish(groupName,
                metricName, value, type, slope, tmax, dmax, units);
        LOG.trace("Sending metric done");
    }
}


text:
'use strict';

const _ = require('lodash/fp');
const cp = require('child_process');
const gutil = require('gulp-util');
const typescript = require('typescript');
const {watchMode, noop} = require('../utils');

const watch = watchMode();
const typescriptSuccessRegex = /Compilation complete/;
const typescriptErrorRegex = /\(\d+,\d+\): error TS\d+:/;

function run({done = noop}) {
  gutil.log(`Compiling TypeScript @ ${typescript.version}`);

  const bin = require.resolve('typescript/bin/tsc');

  const args = toCliArgs({
    project: 'tsconfig.json',
    rootDir: '.',
    outDir: './dist/'
  });

  const child = cp.spawn(bin, [...args, ...watch ? ['--watch'] : []]);

  return new Promise((resolve, reject) => {
    child.stdout.on('data', onStdout(_.compose(resolve, done), reject));
  });
}

function onStdout(resolve, reject) {
  return buffer => {
    const str = buffer.toString();

    if (typescriptErrorRegex.test(str)) {
      printLines(str, 'red');
      reject();

      if (!watch) {
        throw new gutil.PluginError('WixTypeScriptTask', {
          message: 'TypeScript transpilation failed! Please see the red error above.'
        });
      }
    } else if (typescriptSuccessRegex.test(str)) {
      printLines(str, 'green');
      resolve();
    }
  };
}

function print(color) {
  return line => gutil.log(gutil.colors[color](line));
}

function printLines(lines, color) {
  return lines.split('\n').filter(a => a.length > 0).forEach(print(color));
}

function toCliArgs(obj) {
  return _.toPairs(obj).reduce((list, [key, value]) => [...list, `--${key}`, value], []);
}

module.exports = {run};