text:
// bsls_cpp11.t.cpp                                                   -*-C++-*-

#include <bsls_cpp11.h>

#include <cstdlib>
#include <iostream>

// Warning: the following 'using' declarations interfere with the testing of
// the macros defined in this component.  Please do not uncomment them.
// using namespace BloombergLP;
// using namespace std;

//=============================================================================
//                                 TEST PLAN
//-----------------------------------------------------------------------------
//                                  Overview
//                                  --------
//-----------------------------------------------------------------------------
// [ 1] BSLS_CPP11_CONSTEXPR
// [ 2] BSLS_CPP11_EXPLICIT
// [ 3] BSLS_CPP11_FINAL (class)
// [ 4] BSLS_CPP11_FINAL (function)
// [ 5] BSLS_CPP11_NOEXCEPT
// [ 5] BSLS_CPP11_NOEXCEPT_SPECIFICATION
// [ 5] BSLS_CPP11_NOEXCEPT_OPERATOR
// [ 6] BSLS_CPP11_OVERRIDE
//-----------------------------------------------------------------------------
// [ 7] MACRO SAFETY
// [ 8] USAGE EXAMPLE

// ============================================================================
//                     STANDARD BDE ASSERT TEST FUNCTION
// ----------------------------------------------------------------------------

namespace {

int testStatus = 0;

void aSsErT(bool condition, const char *message, int line)
{
    if (condition) {
        std::cout << "Error " __FILE__ "(" << line << "): " << message
                  << "    (failed)" << std::endl;

        if (0 <= testStatus && testStatus <= 100) {
            ++testStatus;
        }
    }
}

}  // close unnamed namespace

#define ASSERT(X) { aSsErT(!(X), #X, __LINE__); }

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

namespace
{
    template <class TYPE>
    class Optional
    {
        TYPE* d_value;
    public:
        Optional(): d_value() {}
            // The default constructor zero initializes the object.
        explicit Optional(const TYPE& value): d_value(new TYPE(value)) {}
            // This constructor sets the object to the specified 'value'.
        ~Optional() { delete d_value; }
            // The destructor destructs the object.

        // ...

        BSLS_CPP11_EXPLICIT
        operator bool() const { return d_value; }
            // The conversion operators returns the object's value.
    };

    template <class, bool Pred>
    struct TestMetafunction {
        enum { value = Pred };
          // Used to construct 'void foo() noexcept(expr-with-commas)'
    };

    void noThrow1() BSLS_CPP11_NOEXCEPT                           {}
    void noThrow2() BSLS_CPP11_NOEXCEPT_SPECIFICATION(true)       {}
    void noThrow3() BSLS_CPP11_NOEXCEPT_SPECIFICATION(
                        BSLS_CPP11_NOEXCEPT_OPERATOR(noThrow1())) {}
    void noThrow4() BSLS_CPP11_NOEXCEPT_SPECIFICATION(
                        TestMetafunction<void, true>::value)      {}
    void throws1()  BSLS_CPP11_NOEXCEPT_SPECIFICATION(false)      {}
    void throws2()  BSLS_CPP11_NOEXCEPT_SPECIFICATION(
                        BSLS_CPP11_NOEXCEPT_OPERATOR(throws1()))  {}
    void throws3()  BSLS_CPP11_NOEXCEPT_SPECIFICATION(
                        TestMetafunction<void, false>::value)     {}
    template <class, class>
    void throws4() BSLS_CPP11_NOEXCEPT_SPECIFICATION(false)       {}
      // 'throws4<T, U>()` is used to test the operator
      // 'noexcept(expr-with-commas)'

}  // close unnamed namespace

//=============================================================================
//                                MAIN PROGRAM
//-----------------------------------------------------------------------------

int main(int argc, char *argv[])
{
    int test = argc > 1 ? atoi(argv[1]) : 0;
    int verbose = argc > 2;

    std::cout << "TEST " << __FILE__ << " CASE " << test << std::endl;

    switch (test) { case 0:
      case 8: {
        // --------------------------------------------------------------------
        // TESTING USAGE EXAMPLE
        // Concerns:
        //   The usage example provided in the component header file must
        //   compile, link, and run on all platforms as shown.
        //
        // Plan:
        //   Run the usage example.
        //
        // Testing:
        //   USAGE EXAMPLE
        // --------------------------------------------------------------------

        if (verbose)
            std::cout << std::endl
                      << "TESTING USAGE EXAMPLE" << std::endl
                      << "=====================" << std::endl;

        Optional<int> value;
        ASSERT(bool(value) == false);
        if (value) { /*... */ }
#if !defined(BSLS_COMPILERFEATURES_SUPPORT_OPERATOR_EXPLICIT) \
 || defined(FAIL_USAGE_EXPLICIT)
        bool flag = value;
        ASSERT(flag == false);
#endif

        class FinalClass BSLS_CPP11_FINAL
        {
            int d_value;
        public:
            explicit FinalClass(int value = 0)
                // Initialize the object with the optionally specified 'value'.
                : d_value(value) {}
            int value() const { return d_value; }
                // Returns the object's value.
        };
        class FinalClassDerived
#if !defined(BSLS_COMPILERFEATURES_SUPPORT_FINAL) \
 || defined(FAIL_USAGE_FINAL_CLASS)
            : public FinalClass
#endif
        {
            int d_anotherValue;
        public:
            explicit FinalClassDerived(int value)
                // Initialize the object with the specified 'value'.
                : d_anotherValue(2 * value) {
            }
            int anotherValue() const { return d_anotherValue; }
                // Returns another value for the object.
        };

        FinalClass finalValue(1);
        ASSERT(finalValue.value() == 1);
        FinalClassDerived derivedValue(2);
        ASSERT(derivedValue.anotherValue() == 4);

        struct FinalFunctionBase
        {
            virtual int f() { return 0; }
                // Returns a value associated with the the class's type.
        };
        struct FinalFunctionDerived: FinalFunctionBase
        {
            int f() BSLS_CPP11_FINAL
                // Returns a value associated with the the class's type.
            { return 1; }
        };
        struct FinalFunctionFailure: FinalFunctionDerived
        {
#if !defined(BSLS_COMPILERFEATURES_SUPPORT_FINAL) \
 || defined(FAIL_USAGE_FINAL_FUNCTION)
            int f()
                // Returns a value associated with the the class's type.
            { return 2; }
#endif
        };

        FinalFunctionBase finalFunctionBase;
        ASSERT(finalFunctionBase.f()    == 0);

        FinalFunctionDerived finalFunctionDerived;
        ASSERT(finalFunctionDerived.f() == 1);

        FinalFunctionFailure finalFunctionFailure;
#if defined(BSLS_COMPILERFEATURES_SUPPORT_FINAL)
        ASSERT(finalFunctionFailure.f() == 1);
#else
        ASSERT(finalFunctionFailure.f() == 2);
#endif

        struct OverrideBase
        {
            virtual int f() const
                // Returns a value associated with the type.
            { return 0; }
        };
        struct OverrideSuccess: OverrideBase
        {
            int f() const BSLS_CPP11_OVERRIDE
                // Returns a value associated with the type.
            { return 1; }
        };
        struct OverrideFailure: OverrideBase
        {
            int f()
                // Returns a value associated with the type.
#if !defined(BSLS_COMPILERFEATURES_SUPPORT_OVERRIDE) \
 || defined(FAIL_USAGE_OVERRIDE)
                BSLS_CPP11_OVERRIDE
#endif
            { return 2; }
        };

        OverrideBase overrideBase;
        ASSERT(overrideBase.f() == 0);
        OverrideSuccess overrideSuccess;
        ASSERT(overrideSuccess.f() == 1);
        ASSERT(static_cast<const OverrideBase&>(overrideSuccess).f() == 1);
        OverrideFailure overrideFailure;
        ASSERT(overrideFailure.f() == 2);
        ASSERT(static_cast<const OverrideBase&>(overrideFailure).f() == 0);
      } break;
      case 7: {
        // --------------------------------------------------------------------
        // TESTING MACRO SAFETY
        //
        // Concerns:
        //   The macros should be usable outside 'namespace' 'BloombergLP' and
        //   'namespace' 'std'.
        //
        // Plan:
        //   The 'using' declarations at the top of the file are specifically
        //   commented out to test the concern.  If the concerns is violated,
        //   the test driver should fail to compile.
        //
        // Testing:
        //   MACRO SAFETY
        // --------------------------------------------------------------------

        if (verbose) std::cout << std::endl
                               << "TESTING MACRO SAFETY" << std::endl
                               << "====================" << std::endl;

        struct TestBase {
            virtual void f() = 0;
                // Used to verify the derived type overrides the function.
            virtual void g() = 0;
                // Used to verify the derived type overrides the function.
        };
        struct TestIntermediate
            : TestBase {
            void f() BSLS_CPP11_OVERRIDE BSLS_CPP11_FINAL
                // Override the abstraction function.
            {}
            void g() BSLS_CPP11_FINAL BSLS_CPP11_OVERRIDE
                // Override the abstraction function.
            {}
        };
        struct TestDerived BSLS_CPP11_FINAL
            : TestIntermediate {
            bool test()
                // Returns 'true'.
            { return true; }
            BSLS_CPP11_EXPLICIT
            operator bool() const
                // The conversion operator always returns 'true'.
            { return true; }
        };

        TestDerived object;
        ASSERT(object.test());
        ASSERT(bool(object));
      } break;
      case 6: {
        // --------------------------------------------------------------------
        // TESTING: BSLS_CPP11_OVERRIDE
        //
        // Concerns:
        //   1) Marking an overriding function as 'override' using
        //      'BSLS_CPP11_OVERRIDE' shall compile OK both with C++03 and
        //      C++11 mode.
        //
        //   2) Marking a function which isn't overriding a 'virtual' function
        //      as 'override' using 'BSLS_CPP11_OVERRIDE' shall fail to
        //      compile when compiling using C++11 mode.  It may fail when
        //      using C++03 mode due to a warning about an overload hiding
        //      base class functions.
        //
        // Plan:
        //   Define a base class with a 'virtual' function and two derived
        //   classes which override the function correctly and incorrectly.  In
        //   both cases use the 'BSLS_CPP11_OVERRIDE' macro and determine if
        //   the compilation is successful.  The incorrect use is guarded by a
        //   the macro 'FAIL_OVERRIDE' to restrict compilation failure to
        //   compilations with this macro defined.
        // --------------------------------------------------------------------

        if (verbose)
            std::cout << std::endl
                      << "TESTING: BSLS_CPP11_OVERRIDE" << std::endl
                      << "============================" << std::endl;

        struct Base
        {
            virtual int f() const
                // Returns a value for each type.
            {
                return 0;
            }
        };
        struct OverrideOK
            : Base
        {
            int f() const BSLS_CPP11_OVERRIDE
                // Returns a value specific to this type.
            {
                return 1;
            }
        };
        struct OverrideFail
            : Base
        {
            int f()
                // Returns a value specific to this type.
#if !defined(BSLS_COMPILERFEATURES_SUPPORT_OVERRIDE) || defined(FAIL_OVERRIDE)
                BSLS_CPP11_OVERRIDE
#endif
            {
                return 2;
            }
        };

        OverrideOK ok;
        ASSERT(ok.f() == 1);
        ASSERT(static_cast<const Base&>(ok).f() == 1);
        OverrideFail fail;
        ASSERT(fail.f() == 2);
        ASSERT(static_cast<const Base&>(fail).f() == 0);

      } break;
      case 5: {
        // --------------------------------------------------------------------
        // TESTING BSLS_CPP11_NOEXCEPT, BSLS_CPP11_NOEXCEPT_SPECIFICATION(pred)
        // BSLS_CPP11_NOEXCEPT_OPERATOR(expr)
        //
        // Concerns:
        //   1) Marking a function 'noexcept' using 'BSLS_CPP11_NOEXCEPT' or
        //      'BSLS_CPP11_NOEXCEPT_SPECIFICATION(pred)' or
        //      'BSLS_CPP11_NOEXCEPT_SPECIFICATION(
        //          BSLS_CPP11_NOEXCEPT_OPERATOR(expr))' should result in a
        //      successful compilation in C++03 mode.
        //
        //   2) Marking a function 'noexcept' or 'noexcept(bool)' using
        //      'BSLS_CPP11_NOEXCEPT' or
        //      'BSLS_CPP11_NOEXCEPT_SPECIFICATION(pred)' or
        //      'BSLS_CPP11_NOEXCEPT_SPECIFICATION(
        //          BSLS_CPP11_NOEXCEPT_OPERATOR(expr))' should be detectable
        //      using 'BSLS_CPP11_NOEXCEPT_OPERATOR(function(...))`.
        //
        //   3) The `BSLS_CPP11_NOEXCEPT_SPECIFICATION(pred)` and
        //       'BSLS_CPP11_NOEXCEPT_OPERATOR(expr)' macros both allow commas
        //       in template parameter lists.
        //
        // Plan:
        //   Define a function marking it 'noexcept' using the various forms of
        //   the macro. Then use `BSLS_CPP11_NOEXCEPT_OPERATOR(function(...))`
        //   to check that the function's 'noexcept' specification matches
        //   the expected specification.
        //
        // NOTE: The test functions are called only to prevent
        //  '-Wunused-function' warning.
        // --------------------------------------------------------------------
        if (verbose){
            std::cout << '\n'
                      << "TESTING: BSLS_CPP11_NOEXCEPT\n"
                      << "============================\n";
        }
#if defined(BSLS_COMPILERFEATURES_SUPPORT_NOEXCEPT)
        const bool hasNoexceptSupport = true;
#else
        const bool hasNoexceptSupport = false;
#endif

        noThrow1();
        const bool isNoThrow1 = BSLS_CPP11_NOEXCEPT_OPERATOR(noThrow1());
        ASSERT(isNoThrow1 == hasNoexceptSupport);

        noThrow2();
        const bool isNoThrow2 = BSLS_CPP11_NOEXCEPT_OPERATOR(noThrow2());
        ASSERT(isNoThrow2 == hasNoexceptSupport);

        noThrow3();
        const bool isNoThrow3 = BSLS_CPP11_NOEXCEPT_OPERATOR(noThrow3());
        ASSERT(isNoThrow3 == hasNoexceptSupport);

        noThrow4();
        const bool isNoThrow4 = BSLS_CPP11_NOEXCEPT_OPERATOR(noThrow4());
        ASSERT(isNoThrow4 == hasNoexceptSupport);

        throws1();
        const bool isNoThrow5 = BSLS_CPP11_NOEXCEPT_OPERATOR(throws1());
        ASSERT(isNoThrow5 == false);

        throws2();
        const bool isNoThrow6 = BSLS_CPP11_NOEXCEPT_OPERATOR(throws2());
        ASSERT(isNoThrow6 == false);

        throws3();
        const bool isNoThrow7 = BSLS_CPP11_NOEXCEPT_OPERATOR(throws3());
        ASSERT(isNoThrow7 == false);

        throws4<void, void>();
        const bool isNoThrow8 = BSLS_CPP11_NOEXCEPT_OPERATOR(
                                                        throws4<void, void>());
        ASSERT(isNoThrow8 == false);

      } break;
      case 4: {
        // --------------------------------------------------------------------
        // TESTING BSLS_CPP11_FINAL (function)
        //
        // Concerns:
        //   1) Marking a 'virtual' function as 'final' should compile.
        //
        //   2) Trying to override a function marked as 'final' shall fail to
        //      to compile when compiling with C++11 mode.  Since
        //      'BSLS_CPP11_FINAL' is replaced by nothing when compiling with
        //      C++03 mode the could should compile in this case.
        //
        // Plan:
        //   Define a base class with a 'virtual' function and mark it 'final'
        //   using 'BSLS_CPP11_FINAL' in a derived class.  Creating a further
        //   derived class which also overrides the function marked as 'final'
        //   should fail compilation when compiling with C++11 mode.
        // --------------------------------------------------------------------

        if (verbose)
            std::cout << std::endl
                      << "TESTING: BSLS_CPP11_FINAL (function)" << std::endl
                      << "====================================" << std::endl;

        struct FinalFunctionBase
        {
            virtual int f()
                // Returns a value for each type.
            { return 0; }
        };
        struct FinalFunctionDerived: FinalFunctionBase
        {
            int f()
                // Returns a value for the specific type.
                BSLS_CPP11_FINAL
            { return 1; }
        };
        struct FinalFunctionFailure: FinalFunctionDerived
        {
#if !defined(BSLS_COMPILERFEATURES_SUPPORT_FINAL) \
 || defined(FAIL_FINAL_FUNCTION)
            int f()
                // Returns a value for the specific type.
            { return 2; }
#endif
        };

        FinalFunctionBase finalFunctionBase;
        ASSERT(finalFunctionBase.f() == 0);

        FinalFunctionDerived finalFunctionDerived;
        ASSERT(finalFunctionDerived.f() == 1);

        FinalFunctionFailure finalFunctionFailure;
#if defined(BSLS_COMPILERFEATURES_SUPPORT_FINAL)
        ASSERT(finalFunctionFailure.f() == 1);
#else
        ASSERT(finalFunctionFailure.f() == 2);
#endif
      } break;
      case 3: {
        // --------------------------------------------------------------------
        // TESTING: BSLS_CPP11_FINAL (class)
        //
        // Concerns:
        //   1) Marking a class 'final' using 'BSLS_CPP11_FINAL' should result
        //      in a successful compilation.
        //
        //   2) Trying to further derive from a function marked as 'final'
        //      shall fail to compile when compiling with C++11 mode.  Since
        //      'BSLS_CPP11_FINAL' is replaced by nothing when compiling with
        //      C++03 mode the could should compile in this case.
        //
        // Plan:
        //   Define a class marking it 'final' using 'BSLS_CPP11_FINAL'.
        //   Creating a derived class from the 'final' class should fail
        //   compilation when compiling with C++11 mode.
        // --------------------------------------------------------------------

        if (verbose)
            std::cout << std::endl
                      << "TESTING: BSLS_CPP11_FINAL (class)" << std::endl
                      << "=================================" << std::endl;

        class FinalClass BSLS_CPP11_FINAL
        {
            int d_value;
        public:
            explicit FinalClass(int value = 0)
                // Initialize with the optionally specified 'value'.
                : d_value(value) {}
            int value() const
                // Returns the object's value.
            { return d_value; }
        };
        class FinalClassDerived
#if !defined(BSLS_COMPILERFEATURES_SUPPORT_FINAL) || defined(FAIL_FINAL_CLASS)
            : public FinalClass
#endif
        {
            int d_anotherValue;
        public:
            explicit FinalClassDerived(int value)
                // Initialize with the specified 'value'.
                : d_anotherValue(2 * value) {
            }
            int anotherValue() const
                // Returns another value for the object.
            { return d_anotherValue; }
        };

        FinalClass finalValue(1);
        ASSERT(finalValue.value() == 1);
        FinalClassDerived derivedValue(2);
        ASSERT(derivedValue.anotherValue() == 4);

      } break;
      case 2: {
        // --------------------------------------------------------------------
        // TESTING: BSLS_CPP11_EXPLICIT
        //
        // Concerns:
        //   1) Marking a conversion operator 'explicit' using
        //      'BSLS_CPP11_EXPLICIT' needs to allow explicit conversions.
        //
        //   2) Marking a conversion operator 'explicit' using
        //      'BSLS_CPP11_EXPLICIT' should prevent attempts of implicit
        //      conversion when compiling with C++11 mode. When compiling with
        //      C++03 mode compilation will succeed.
        //
        // Plan:
        //   Define a class with an explicit conversion operator and
        //   verify that explicit and implicit conversions succeed when using
        //   C++03 mode. When compiling with C++11 mode the implicit conversion
        //   should fail.
        // --------------------------------------------------------------------

        if (verbose)
            std::cout << std::endl
                      << "TESTING: BSLS_CPP11_EXPLICIT" << std::endl
                      << "============================" << std::endl;

        struct Explicit
        {
            BSLS_CPP11_EXPLICIT
            operator int() const
                // Returns a value for the object.
            { return 3; }
        };

        Explicit explicitObject;

        int explicitResult(explicitObject);
        ASSERT(explicitResult == 3);
#if !defined(BSLS_COMPILERFEATURES_SUPPORT_OPERATOR_EXPLICIT) \
 || defined(FAIL_EXPLICIT)
        int implicitResult = explicitObject;
        ASSERT(implicitResult == 3);
#endif
      } break;
      case 1:{
        // --------------------------------------------------------------------
        // TESTING BSLS_CPP11_CONSTEXPR
        //
        // Concerns:
        //   1) Marking a function 'constexpr' using 'BSLS_CPP11_CONSTEXPR'
        //      should result in a successful compilation.
        //
        //   2) Marking a function 'constexpr' using 'BSLS_CPP11_CONSTEXPR'
        //      should make the test driver not compile if the use of the
        //      resulting constexpr function is used illegally.
        //
        // Plan:
        //   Define a struct marking its various member functions as constexprs
        //   functions. Verify that if the constexpr member functions are not
        //   used appropriately the program will fail to compile in cpp11 mode.
        //
        //   Since the correct behaviour will case the program to not compile,
        //   it is rather difficult to create test cases that actaully tests
        //   the feature and still have the test driver pass. As such, this
        //   tests must be manually checked to ensure that the program does not
        //   compile if testStruct is not used correctly.
        // --------------------------------------------------------------------
          struct testStruct {
              BSLS_CPP11_CONSTEXPR testStruct (int i) : value(i){}
              BSLS_CPP11_CONSTEXPR operator int() const {return value; }
              BSLS_CPP11_CONSTEXPR operator long() const {return 1.0; }
              private:
                  int value;
          };

          BSLS_CPP11_CONSTEXPR testStruct B (15);
#if defined(BSLS_COMPILERFEATURES_SUPPORT_CONSTEXPR)
          BSLS_CPP11_CONSTEXPR int X (B);
#else
          int X (B);
#endif
      } break;
      default: {
        std::cerr << "WARNING: CASE `" << test << "' NOT FOUND." << std::endl;
        testStatus = -1;
      }
    }

    if (testStatus > 0) {
        std::cerr << "Error, non-zero test status = " << testStatus << "."
                  << std::endl;
    }
    return testStatus;
}

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


text:
module OpenXml
  class ContentTypesPresets
    attr_reader :defaults, :overrides

    def initialize
      @defaults, @overrides = {}, {}
    end

    def default(extension, content_type)
      defaults[extension] = content_type
    end

    def override(part_name, content_type)
      overrides[part_name] = content_type
    end

  end
end

redpajama_set_name: RedPajamaGithub


text:
"use strict";
// This program is free software: you can redistribute it and/or modify
// it under the condition that it is for private or home useage and
// this whole comment is reproduced in the source code file.
// Commercial utilisation is not authorized without the appropriate
// written agreement from amg0 / alexis . mermet @ gmail . com
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

var ALTUI_VirtualAlarmPanel = ( function( window, undefined ) {

	function _onDeviceStatusChanged( event, device ) {
		if (device.device_type === "urn:schemas-upnp-org:device:VirtualAlarmPanel:1") {
			for (var i = 0; i < device.states.length; i++) {
				if (device.states[i].variable === "AlarmPanel") {
					$(".altui-device[data-altuiid='" + device.altuiid + "']").each( function(index, element) {
						$(element).find(".panel-content").each( function(index, element) {
							$(element).html(device.states[i].value);
						});
					});
					break;
				}
			}
		}
	};

	function _drawDevice( device ) {
		var htmlAlarmPanel = MultiBox.getStatus(device, 'urn:upnp-org:serviceId:VirtualAlarmPanel1', 'AlarmPanel');
		return '
' + htmlAlarmPanel + '
';
	};

  // explicitly return public methods when this object is instantiated
	return {
		//---------------------------------------------------------
		// PUBLIC  functions
		//---------------------------------------------------------
		//getStyle 	: _getStyle,
		drawDevice: _drawDevice,
		onDeviceStatusChanged: _onDeviceStatusChanged
	};
})( window );

EventBus.registerEventHandler("on_ui_deviceStatusChanged", ALTUI_VirtualAlarmPanel, "onDeviceStatusChanged");


text:
package out_test

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"testing"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"github.com/onsi/gomega/gexec"
)

var outPath string

var _ = BeforeSuite(func() {
	var err error

	if _, err = os.Stat("/opt/resource/out"); err == nil {
		outPath = "/opt/resource/out"
	} else {
		outPath, err = gexec.Build("github.com/concourse/s3-resource/cmd/out")
		Ω(err).ShouldNot(HaveOccurred())
	}

})

var _ = AfterSuite(func() {
	gexec.CleanupBuildArtifacts()
})

func TestOut(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Out Suite")
}

func Fixture(filename string) string {
	path := filepath.Join("fixtures", filename)
	contents, err := ioutil.ReadFile(path)
	if err != nil {
		panic(err)
	}

	return string(contents)
}


text:
var Pending = require('./exceptions').Pending,
  AssertionError = require('assert').AssertionError;

exports.Context = Context;

// We use defineProperty `get` so that we can
// raise an exception on `set` rather than just failing silently
// this is to avoid mysteriously failing tests

function Context(nodespec, deps) {
  var assertion_count = 0, expected_assertions;
  // non-enumerable instance variable
  Object.defineProperty(this, 'expected_assertions', {
    get: function() { return expected_assertions; },
    set: function(assertions) {
      if (typeof assertions !== 'number') {
        throw new TypeError('assertions must be a number');
      }
      expected_assertions = assertions;
    }
  });
  Object.defineProperty(this, 'assert', {
    get: function() {
      assertion_count += 1;
      return nodespec.assert;
    },
    set: function() { throw new Error('Cannot redefine `assert`'); }
  });
  Object.defineProperty(this, 'assertions', {
    get: function() {
      return assertion_count;
    },
    set: function(assertions) {
      assertion_count = assertions;
    }
  });
  Object.defineProperty(this, 'pending', {
    get: function() {
      return function(reason) {
        throw new deps.Pending(reason);
      }
    },
    set: function() { throw new Error('Cannot redefine `pending`'); }
  });
  var on_error = false;
  Object.defineProperty(this, 'onError', {
    get: function() {
      return function(func) {
        if (typeof func === 'function' || func === false) {
          on_error = func;
        }
        return on_error;
      }
    },
    set: function() { throw new Error('Cannot redefine `onError`'); }
  });
}

Object.defineProperty(Context.prototype, '_setup_done', {
  get: function() {
    return function(done_function) {
      if (!done_function) {
        delete this.done;
      } else {
        Object.defineProperty(this, 'done', {
          get: function() { return done_function; },
          set: function() {
            throw new Error('Cannot redefine `done`');
          },
          configurable: true
        });
      }
    };
  },
  set: function() { throw new Error('Cannot redefine `_setup_done`'); }
});

Object.defineProperty(Context.prototype, 'expect', {
  get: function() {
    return function(assertions) {
      this.expected_assertions = assertions;
    }
  },
  set: function() { throw new Error('Cannot redefine `expect`'); }
});


text:
<?php

namespace OC\User;

use OC\DB\QueryBuilder\Literal;
use OCP\AppFramework\Db\Entity;
use OCP\AppFramework\Db\Mapper;
use OCP\IConfig;
use OCP\IDBConnection;

class AccountMapper extends Mapper {

	/* @var IConfig */
	protected $config;

	/* @var AccountTermMapper */
	protected $termMapper;

	public function __construct(IConfig $config, IDBConnection $db, AccountTermMapper $termMapper) {
		parent::__construct($db, 'accounts', Account::class);
		$this->config = $config;
		$this->termMapper = $termMapper;
	}

	/**
	 * Delegate to term mapper to avoid needing to inject term mapper
	 * @param $account_id
	 * @param array $terms
	 */
	public function setTermsForAccount($account_id, array $terms) {
		$this->termMapper->setTermsForAccount($account_id, $terms);
	}

	/**
	 * Delegate to term mapper to avoid needing to inject term mapper
	 * @param $account_id
	 * @return AccountTerm[] $terms
	 */
	public function findByAccountId($account_id) {
		return $this->termMapper->findByAccountId($account_id);
	}

	/**
	 * @param Account $entity
	 * @return Entity the saved entity with the set id
	 */
	public function insert(Entity $entity) {
		// run the normal entity insert operation to get an id
		$entity = parent::insert($entity);

		/** @var Account $entity */
		if ($entity->haveTermsChanged()) {
			$this->termMapper->setTermsForAccount($entity->getId(), $entity->getSearchTerms());
		}
		return $entity;
	}

	/**
	 * @param Account $entity
	 * @return Entity the deleted entity
	 */
	public function delete(Entity $entity) {
		// First delete the search terms for this account
		$this->termMapper->deleteTermsForAccount($entity->getId());
		return parent::delete($entity);
	}

	/**
	 * @param Account $entity
	 * @return Entity the updated entity
	 */
	public function update(Entity $entity) {
		if ($entity->haveTermsChanged()) {
			$this->termMapper->setTermsForAccount($entity->getId(), $entity->getSearchTerms());
		}
		// Then run the normal entity insert operation
		return parent::update($entity);
	}

	/**
	 * @param string $email
	 * @return Account[]
	 */
	public function getByEmail($email) {
		if ($email === null || \trim($email) === '') {
			throw new \InvalidArgumentException('$email must be defined');
		}
		$qb = $this->db->getQueryBuilder();
		// RFC 5321 says that only domain name is case insensitive, but in practice
		// it's the whole email
		$qb->select('*')
			->from($this->getTableName())
			->where($qb->expr()->eq($qb->createFunction('LOWER(`email`)'), $qb->createFunction('LOWER(' . $qb->createNamedParameter($email) . ')')));

		return $this->findEntities($qb->getSQL(), $qb->getParameters());
	}

	/**
	 * @param string $uid
	 * @return Account
	 */
	public function getByUid($uid) {
		$qb = $this->db->getQueryBuilder();
		$qb->select('*')
			->from($this->getTableName())
			->where($qb->expr()->eq('lower_user_id', $qb->createNamedParameter(\strtolower($uid))));

		return $this->findEntity($qb->getSQL(), $qb->getParameters());
	}

	/**
	 * @param string $fieldName
	 * @param string $pattern
	 * @param integer $limit
	 * @param integer $offset
	 * @return Account[]
	 */
	public function search($fieldName, $pattern, $limit, $offset) {
		$qb = $this->db->getQueryBuilder();
		$qb->select('*')
			->from($this->getTableName())
			->where($qb->expr()->iLike($fieldName, $qb->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')))
			->orderBy($fieldName);

		return $this->findEntities($qb->getSQL(), $qb->getParameters(), $limit, $offset);
	}

	/**
	 * @param string $pattern
	 * @param integer $limit
	 * @param integer $offset
	 * @return Account[]
	 */
	public function find($pattern, $limit = null, $offset = null) {
		$allowMedialSearches = $this->config->getSystemValue('accounts.enable_medial_search', true);
		if ($allowMedialSearches) {
			$parameter = '%' . $this->db->escapeLikeParameter($pattern) . '%';
			$loweredParameter = '%' . $this->db->escapeLikeParameter(\strtolower($pattern)) . '%';
		} else {
			$parameter = $this->db->escapeLikeParameter($pattern) . '%';
			$loweredParameter = $this->db->escapeLikeParameter(\strtolower($pattern)) . '%';
		}

		$qb = $this->db->getQueryBuilder();
		$qb->selectAlias('DISTINCT a.id', 'id')
			->addSelect(['user_id', 'lower_user_id', 'display_name', 'email', 'last_login', 'backend', 'state', 'quota', 'home'])
			->from($this->getTableName(), 'a')
			->leftJoin('a', 'account_terms', 't', $qb->expr()->eq('a.id', 't.account_id'))
			->orderBy('display_name')
			->where($qb->expr()->like('lower_user_id', $qb->createPositionalParameter($loweredParameter)))
			->orWhere($qb->expr()->iLike('display_name', $qb->createPositionalParameter($parameter)))
			->orWhere($qb->expr()->iLike('email', $qb->createPositionalParameter($parameter)))
			->orWhere($qb->expr()->like('t.term', $qb->createPositionalParameter($loweredParameter)));

		return $this->findEntities($qb->getSQL(), $qb->getParameters(), $limit, $offset);
	}

	public function getUserCountPerBackend($hasLoggedIn) {
		$qb = $this->db->getQueryBuilder();
		$qb->select(['backend', $qb->createFunction('count(*) as `count`')])
			->from($this->getTableName())
			->groupBy('backend');

		if ($hasLoggedIn) {
			$qb->where($qb->expr()->gt('last_login', new Literal(0)));
		}

		$result = $qb->execute();
		$data = $result->fetchAll();
		$result->closeCursor();

		$return = [];
		foreach ($data as $d) {
			$return[$d['backend']] = $d['count'];
		}

		return $return;
	}

	public function getUserCount($hasLoggedIn) {
		$qb = $this->db->getQueryBuilder();
		$qb->select([$qb->createFunction('count(*) as `count`')])
			->from($this->getTableName());

		if ($hasLoggedIn) {
			$qb->where($qb->expr()->gt('last_login', new Literal(0)));
		}

		$result = $qb->execute();
		$data = $result->fetch();
		$result->closeCursor();

		return (int) $data['count'];
	}

	public function callForAllUsers($callback, $search, $onlySeen) {
		return $this->callForUsers($callback, $search, $onlySeen);
	}

	public function callForUsers($callback, $search, $onlySeen, $limit = null, $offset = null) {
		$qb = $this->db->getQueryBuilder();
		$qb->select(['*'])
			->from($this->getTableName());

		if ($search) {
			$qb->where($qb->expr()->iLike('user_id',
				$qb->createNamedParameter('%' . $this->db->escapeLikeParameter($search) . '%')));
		}
		if ($onlySeen) {
			$qb->where($qb->expr()->gt('last_login', new Literal(0)));
		}

		if ($limit !== null || $offset !== null) {
			$qb->orderBy('user_id'); // needed for predictable limit & offset
		}

		if ($limit !== null) {
			$qb->setMaxResults($limit);
		}
		if ($offset !== null) {
			$qb->setFirstResult($offset);
		}

		$stmt = $qb->execute();
		while ($row = $stmt->fetch()) {
			$return = $callback($this->mapRowToEntity($row));
			if ($return === false) {
				break;
			}
		}

		$stmt->closeCursor();
	}

	/**
	 * @param string $backend
	 * @param bool $hasLoggedIn
	 * @param integer $limit
	 * @param integer $offset
	 * @return string[]
	 */
	public function findUserIds($backend = null, $hasLoggedIn = null, $limit = null, $offset = null) {
		$qb = $this->db->getQueryBuilder();
		$qb->select('user_id')
			->from($this->getTableName())
			->orderBy('user_id'); // needed for predictable limit & offset

		if ($backend !== null) {
			$qb->andWhere($qb->expr()->eq('backend', $qb->createNamedParameter($backend)));
		}
		if ($hasLoggedIn === true) {
			$qb->andWhere($qb->expr()->gt('last_login', new Literal(0)));
		} elseif ($hasLoggedIn === false) {
			$qb->andWhere($qb->expr()->eq('last_login', new Literal(0)));
		}
		if ($limit !== null) {
			$qb->setMaxResults($limit);
		}
		if ($offset !== null) {
			$qb->setFirstResult($offset);
		}

		$stmt = $qb->execute();
		$rows = $stmt->fetchAll(\PDO::FETCH_COLUMN);
		$stmt->closeCursor();
		return $rows;
	}
}


text:
class ElectrumErrorResponse(RuntimeError):
    pass


text:
{\color{indiagreen}\subsection{GIT}}
Git je brezplačni in odprtokodni version control sistem, ki ima veliko uporabnih funkcij. Navedel bom samo nekatere, ki so najbolj pogoste za uporabo.
Vse funkcije imajo pred ukazom besedo git.
Funkcije:
\begin{itemize}
	\item \textbf{init} : Naredi prazen git mapo ali pa na novo reinicializira že obstoječo mapo.\\
	Komanda bi zgledala nekako takole:\\
	\bashsource{Izvorna_koda/GitInit.sh}
	\item \textbf{clone} : Klonira že obstoječo mapo v trenutno mapo\\
	Najbolj pogosto se ta komanda uporablja, da kloniramo mapo ali projekt iz kakšne strani, na naš računalnik. Lahko pa tudi lokalno pri sebi kloniramo iz ene mapo v drugo.\\
	Za kloniranje map iz url naslova git podpira ssh, git, http in https. Url naslov mora biti v eni izmed takih oblik:
	\begin{itemize}
		\item ssh://[user@]host.xz[:port]/path/to/repo.git/
		\item git://host.xz[:port]/path/to/repo.git/
		\item http[s]://host.xz[:port]/path/to/repo.git/
	\end{itemize}
	In ko vse skupaj sestavimo bi bil primer komande takšen:\\
	\bashsource{Izvorna_koda/GitClone.sh}
	\item \textbf{config} : Nastavi globalne ali lokalne spremeljivke mape.\\
	Ne bom se poglabljav v vse možnosti uporabe te komande, ampak bom naštel samo nekaj osnovnih. V bistvu bosta nas zanimali samo dve in to sta:\\
	\bashsource{Izvorna_koda/GitConfig.sh}
	\item \textbf{add} : Doda datoteko ali skupino datotek k delovnemu drevesu.\\
	Ta komanda doda datoteko, tako da se upoštevajo in beležijo vse spremembe narejene na njej. Na začetku, ko inicializiramo mapo, hočemo da se upoštevajo vse, nato pa dodajamo posamezne datoteke.\\
	Par primerov uporabe te komande:\\
	\bashsource{Izvorna_koda/GitAdd.sh}
	\item \textbf{commit} : Zapiše spremembe v mapi\\
	To komando pokličemo, po komandi add ali ko združujemo skupaj dve veji. Poleg tega imamo možnost, da poleg commita dodamo tudi sporočilo oz. poročilo kaj smo naredili. Primer:\\
	\bashsource{Izvorna_koda/GitCommit.sh}
	\item \textbf{push} : Naloži datoteke na oddaljen strežnik\\
	To komando pokličemo čisto nakoncu, ko smo dodali vse datoteke, jih zapisali (commitali). Imamo pa tudi možnost, da pushamo na različne veje(branche).\\
	Primer:\\
	\bashsource{Izvorna_koda/GitPush.sh}
	\item \textbf{pull} : Potegne datoteke iz oddaljenega strežnika in jih združi z lokalno mapo.\\
	Ta komanda požene git fetch komando, ki dobi podatke iz strežnika in potem za tem požene git merge, ki združi lokalno verzijo z verzijo iz oddaljenega strežnika.
	Primer:\\
	\bashsource{Izvorna_koda/GitPull.sh}
	\item itd.
\end{itemize}


text:
namespace smalls
{

///------------------------------------------------------------------------------------------------
/// @brief Creates a Vector alias as a column Matrix.
///------------------------------------------------------------------------------------------------
template<size_t SizeT, typename ScalarT, template <typename, size_t> class StorageT = StorageOwned>
    using Vector = Matrix<SizeT, 1, ScalarT, StorageT>;

///------------------------------------------------------------------------------------------------
/// @brief Helper function to create a Vector. The size is deduced at compile time, user needs
/// to specify the type.
///------------------------------------------------------------------------------------------------
template<typename ScalarT, typename ...Args>
SPECIFIER Vector<sizeof...(Args), ScalarT> make_vector(Args&&... args)
{
    return Vector<sizeof...(Args), ScalarT>(std::forward<Args>(args)...);
}

///------------------------------------------------------------------------------------------------
/// @brief Helper function to create a Vector that maps the input Vector.
/// This is useful to create "sub-views" of a Vector and avoid unnecessary copies.
///------------------------------------------------------------------------------------------------
template<size_t startIndex, size_t endIndex, size_t RowsT, size_t ColsT, typename ScalarT,
    template<size_t, size_t, typename, template <typename, size_t > class> class VectorT,
    template <typename, size_t> class StorageT,
    size_t mappedSize = endIndex - startIndex + 1,
    typename MappedVector = VectorT<mappedSize, ColsT, ScalarT, StorageMapped >>
SPECIFIER MappedVector make_map_vector(VectorT<RowsT, ColsT, ScalarT, StorageT>& vector)
{
    static_assert(
        endIndex <= VectorT<RowsT, ColsT, ScalarT, StorageT>::Size &&
        startIndex <= VectorT<RowsT, ColsT, ScalarT, StorageT>::Size &&
        startIndex <= endIndex,
        "The indices cannot be greater than the size of the underlying vector and "
        "the start index cannot be greater than the end index.");
    static_assert(1 == ColsT, "You are trying to map a non-vector type - mapping is only available "
        "for vector for now");
    StorageMapped<ScalarT, mappedSize> storageMapped(vector.data() + startIndex);
    return MappedVector(storageMapped);
}
}

#endif //SMALLS_VECTOR_H


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    checksum-maven-plugin - http://checksum-maven-plugin.nicoulaj.net
    Copyright © 2010-2021 checksum-maven-plugin contributors

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>net.nicoulaj.maven.plugins.checksum.test.projects</groupId>
  <artifactId>single-pom.artifacts.default</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>pom</packaging>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <build>
    <plugins>
      <plugin>
        <groupId>net.nicoulaj.maven.plugins</groupId>
        <artifactId>checksum-maven-plugin</artifactId>
        <version>@project.version@</version>
        <executions>
          <execution>
            <goals>
              <goal>artifacts</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

</project>


text:
extern "Java"
{
  namespace gnu
  {
    namespace javax
    {
      namespace net
      {
        namespace ssl
        {
          namespace provider
          {
              class X509KeyManagerFactory;
              class X509KeyManagerFactory$Manager;
          }
        }
      }
    }
  }
  namespace java
  {
    namespace net
    {
        class Socket;
    }
    namespace security
    {
        class Principal;
        class PrivateKey;
      namespace cert
      {
          class X509Certificate;
      }
    }
  }
  namespace javax
  {
    namespace net
    {
      namespace ssl
      {
          class SSLEngine;
      }
    }
  }
}

class gnu::javax::net::ssl::provider::X509KeyManagerFactory$Manager : public ::javax::net::ssl::X509ExtendedKeyManager
{

public: // actually package-private
  X509KeyManagerFactory$Manager(::gnu::javax::net::ssl::provider::X509KeyManagerFactory *, ::java::util::Map *, ::java::util::Map *);
public:
  virtual ::java::lang::String * chooseClientAlias(JArray< ::java::lang::String * > *, JArray< ::java::security::Principal * > *, ::java::net::Socket *);
  virtual ::java::lang::String * chooseEngineClientAlias(JArray< ::java::lang::String * > *, JArray< ::java::security::Principal * > *, ::javax::net::ssl::SSLEngine *);
  virtual JArray< ::java::lang::String * > * getClientAliases(::java::lang::String *, JArray< ::java::security::Principal * > *);
  virtual ::java::lang::String * chooseServerAlias(::java::lang::String *, JArray< ::java::security::Principal * > *, ::java::net::Socket *);
  virtual ::java::lang::String * chooseEngineServerAlias(::java::lang::String *, JArray< ::java::security::Principal * > *, ::javax::net::ssl::SSLEngine *);
  virtual JArray< ::java::lang::String * > * getServerAliases(::java::lang::String *, JArray< ::java::security::Principal * > *);
private:
  JArray< ::java::lang::String * > * getAliases(::java::lang::String *, JArray< ::java::security::Principal * > *);
public:
  virtual JArray< ::java::security::cert::X509Certificate * > * getCertificateChain(::java::lang::String *);
  virtual ::java::security::PrivateKey * getPrivateKey(::java::lang::String *);
private:
  ::java::util::Map * __attribute__((aligned(__alignof__( ::javax::net::ssl::X509ExtendedKeyManager)))) privateKeys;
  ::java::util::Map * certChains;
public: // actually package-private
  ::gnu::javax::net::ssl::provider::X509KeyManagerFactory * this$0;
public:
  static ::java::lang::Class class$;
};

#endif // __gnu_javax_net_ssl_provider_X509KeyManagerFactory$Manager__


text:
#include "config.h"

#include "UnitTestUtils/EWK2UnitTestBase.h"
#include "UnitTestUtils/EWK2UnitTestServer.h"

using namespace EWK2UnitTest;

extern EWK2UnitTestEnvironment* environment;

static void onIntentServiceRegistration(void* userData, Evas_Object*, void* eventInfo)
{
    bool* intentRegistered = static_cast<bool*>(userData);
    ASSERT_FALSE(*intentRegistered);
    *intentRegistered = true;

    Ewk_Intent_Service* service = static_cast<Ewk_Intent_Service*>(eventInfo);
    ASSERT_TRUE(service);
    EXPECT_STREQ("action", ewk_intent_service_action_get(service));
    EXPECT_STREQ("type", ewk_intent_service_type_get(service));
    EXPECT_STREQ("Title", ewk_intent_service_title_get(service));
    EXPECT_STREQ("http://example.com/service", ewk_intent_service_href_get(service));
    EXPECT_STREQ("inline", ewk_intent_service_disposition_get(service));
}

TEST_F(EWK2UnitTestBase, ewk_intent_service_registration)
{
    bool intentRegistered = false;
    evas_object_smart_callback_add(webView(), "intent,service,register", onIntentServiceRegistration, &intentRegistered);
    ASSERT_TRUE(loadUrlSync(environment->urlForResource("intent-service.html").data()));
    evas_object_smart_callback_del(webView(), "intent,service,register", onIntentServiceRegistration);
    ASSERT_TRUE(intentRegistered);
}

int stringSortCb(const void* d1, const void* d2)
{
    return strcmp(static_cast<const char*>(d1), static_cast<const char*>(d2));
}

static void onIntentReceived(void* userData, Evas_Object*, void* eventInfo)
{
    unsigned* intentReceivedCount = static_cast<unsigned*>(userData);
    ASSERT_GE(*intentReceivedCount, 0);
    ASSERT_LE(*intentReceivedCount, 1);
    ++(*intentReceivedCount);

    Ewk_Intent* intent = static_cast<Ewk_Intent*>(eventInfo);
    ASSERT_TRUE(intent);

    if (*intentReceivedCount == 1) {
        // First intent.
        EXPECT_STREQ("action1", ewk_intent_action_get(intent));
        EXPECT_STREQ("mime/type1", ewk_intent_type_get(intent));
        EXPECT_STREQ("http://service1.com/", ewk_intent_service_get(intent));
        EXPECT_STREQ("value1", ewk_intent_extra_get(intent, "key1"));
        EXPECT_STREQ("value2", ewk_intent_extra_get(intent, "key2"));
    } else {
        // Second intent.
        EXPECT_STREQ("action2", ewk_intent_action_get(intent));
        EXPECT_STREQ("mime/type2", ewk_intent_type_get(intent));
        Eina_List* suggestions = ewk_intent_suggestions_get(intent);
        ASSERT_TRUE(suggestions);
        ASSERT_EQ(2, eina_list_count(suggestions));
        // We need to sort the suggestions since Intent is using a HashSet internally.
        suggestions = eina_list_sort(suggestions, 2, stringSortCb);
        EXPECT_STREQ("http://service1.com/", static_cast<const char*>(eina_list_nth(suggestions, 0)));
        EXPECT_STREQ("http://service2.com/", static_cast<const char*>(eina_list_nth(suggestions, 1)));

        void* listData = 0;
        EINA_LIST_FREE(suggestions, listData)
             eina_stringshare_del(static_cast<const char*>(listData));
    }
}

TEST_F(EWK2UnitTestBase, ewk_intent_request)
{
    unsigned intentReceivedCount = 0;
    evas_object_smart_callback_add(webView(), "intent,request,new", onIntentReceived, &intentReceivedCount);
    ASSERT_TRUE(loadUrlSync(environment->urlForResource("intent-request.html").data()));

    // A user gesture is required for the intent to start.
    mouseClick(5, 5);
    while (intentReceivedCount != 1)
        ecore_main_loop_iterate();
    ASSERT_EQ(1, intentReceivedCount);

    // Generate a second intent request.
    mouseClick(5, 5);
    while (intentReceivedCount != 2)
        ecore_main_loop_iterate();
    ASSERT_EQ(2, intentReceivedCount);
    evas_object_smart_callback_del(webView(), "intent,request,new", onIntentReceived);
}


text:
package com.vmware.vim25;

/**
@author Steve Jin (sjin@vmware.com)
*/

public class ArrayOfHostScsiDisk
{
  public HostScsiDisk[] HostScsiDisk;

  public HostScsiDisk[] getHostScsiDisk()
  {
    return this.HostScsiDisk;
  }

  public HostScsiDisk getHostScsiDisk(int i)
  {
    return this.HostScsiDisk[i];
  }

  public void setHostScsiDisk(HostScsiDisk[] HostScsiDisk)
  {
    this.HostScsiDisk=HostScsiDisk;
  }
}


text:
package core

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"

	"github.com/jzaikovs/core/loggy"
	"github.com/jzaikovs/core/session"
	"github.com/jzaikovs/t"
)

// Input is interface for routes input handler
type Input interface {
	App() *App

	RequestURI() string
	// Get used for getting GET passed parameters
	Get(key string) (val string)
	// Returns method of request (GET, POST, PUT, ...)
	Method() string
	// Returns header value
	HeaderValue(string) string

	ContentType() string
	// wrapper for http.Request.FormValue
	FormValue(string) string

	CookieValue(string) (string, bool)
	// Return user agent
	UserAgent() string
	// Returns remote IP address
	RemoteAddr() string

	// Returns true if request is marked as AJAX based
	Ajax() bool
	// Access to URL parameters
	Args(int) t.T
	// Access to posted data
	Data() t.Map
	// Provides access to session data
	Session() *session.Session

	// returns body content, JSON post with JSON as content-body
	Body() (result string)

	Request() *http.Request

	linkArgs([]t.T)
	linkSession(*session.Session)
	addData(string, interface{})
}

type defaultInput struct {
	app     *App
	request *http.Request
	args    []t.T
	session *session.Session
	data    t.Map
	parsed  bool
	body    []byte
	reqURI  string
}

func newInput(app *App, request *http.Request) (in *defaultInput) {
	in = &defaultInput{
		request: request,
		data:    make(t.Map),
		args:    make([]t.T, 0),
		app:     app,
	}

	in.parseSegments()

	in.body, _ = ioutil.ReadAll(in.request.Body)
	in.request.Body.Close()

	buf := new(bytes.Buffer)
	buf.Write(in.body)
	in.request.Body = ioutil.NopCloser(buf)

	in.data["base_url"] = app.Config.BaseURL
	return in
}

func (in *defaultInput) parseSegments() {
	u, err := url.ParseQuery(in.RequestURI())
	if err != nil {
		loggy.Error.Println(err)
		return
	}

	for k, v := range u {
		if len(v) == 1 {
			in.data[k] = v[0]
		} else {
			in.data[k] = v
		}
	}
}

func (in *defaultInput) App() *App {
	return in.app
}

func (in *defaultInput) linkArgs(args []t.T) {
	in.args = args
}

func (in *defaultInput) linkSession(session *session.Session) {
	in.session = session
}

func (in *defaultInput) Args(idx int) t.T {
	return in.args[idx]
}

func (in *defaultInput) Session() *session.Session {
	return in.session
}
func (in *defaultInput) ContentType() string {
	return in.HeaderValue("Content-Type")
}

func (in *defaultInput) Data() t.Map {
	// repeat request will return result of previous calls
	if in.parsed {
		return in.data
	}

	if strings.Contains(in.ContentType(), ContentType_JSON) {
		temp := make(t.Map)

		// parse body for JSON data into temporal map
		if err := json.Unmarshal(in.body, &temp); err != nil {
			loggy.Error.Println("core.input.data err", in.RemoteAddr(), err.Error(), string(in.body))
		}

		// clean all incoming values, to protect as from some bad injections
		// TODO: do we really need?
		for k, v := range temp {
			switch val := v.(type) {
			case string:
				in.data[k] = Clean(val)
			default:
				in.data[k] = v
			}
		}

		// mark that data is parsed and can be returned on next call without parsing
		in.parsed = true

		return in.data
	}

	if in.request.Form == nil {
		in.request.ParseMultipartForm(32 << 20) // 32MB
	}

	// read all form values if we have post-data
	for k, v := range in.request.Form {
		switch len(v) {
		case 1:
			in.data[k] = v[0] // remove from slice if single value
		case 0:
		default:
			in.data[k] = v
		}
	}

	in.parsed = true

	return in.data
}

func (in *defaultInput) RequestURI() (uri string) {
	if in.reqURI != "" {
		return in.reqURI
	}

	uri = in.request.URL.Path

	if in.app.Config.FCGI && len(in.request.URL.Opaque) > 0 {
		// using Nginx hack
		// fastcgi_param REQUEST_URI "$scheme: $request_uri";
		// fastcgi_param HTTP_HOST "";
		uri = in.request.URL.Opaque[1:]
	} else {
		if len(in.request.RequestURI) > 0 {
			uri = in.request.RequestURI
		} else if in.app.Config.FCGI {
			// using Nginx hack
			// fastcgi_param HTTP_REQUEST_URI $request_uri;
			uri = strings.TrimRight(in.request.Header.Get("Request-Uri"), "?")[len(in.app.Config.Subdir):]
		}
	}

	in.reqURI = uri
	return
}

func (in *defaultInput) HeaderValue(key string) string {
	return in.request.Header.Get(key)
}

func (in *defaultInput) Get(key string) (val string) {
	val = in.data.Str(key)
	return
}

func (in *defaultInput) Method() string {
	return in.request.Method
}

func (in *defaultInput) FormValue(name string) string {
	return in.request.FormValue(name)
}

func (in *defaultInput) CookieValue(name string) (string, bool) {
	cookie, err := in.request.Cookie(name)
	if err != nil {
		return "", false
	}
	return cookie.Value, true
}

func (in *defaultInput) UserAgent() string {
	return in.request.UserAgent()
}

func (in *defaultInput) RemoteAddr() string {
	return strings.Split(in.request.RemoteAddr, ":")[0]
}

func (in *defaultInput) Body() string {
	return string(in.body)
}

func (in *defaultInput) Ajax() bool {
	if in.ContentType() == "application/json" {
		return true
	}
	return strings.ToLower(in.request.Header.Get("X-Requested-With")) == "xmlhttprequest"
}

func (in *defaultInput) Request() *http.Request {
	return in.request
}

func (in *defaultInput) addData(k string, v interface{}) {
	in.data[k] = v
}


text:
require "spec_helper"
require "package_processor"

describe PackageProcessor do

  before(:each) do
    @package = Package.create
    mock_client = double(Pusher::Channel)
    allow(Pusher).to receive(:[]) { mock_client }
    allow(mock_client).to receive(:trigger)
  end

  it "creates a package from a url" do
    mock_file("http://example.com/test.csv", 'csvs/valid.csv')
    processor = described_class.new({
      urls: ['http://example.com/test.csv']
    }, @package.id)
    processor.process

    expect(@package.validations.count).to eq(1)
  end

  it "creates a package from a data url" do
    processor = described_class.new({
      files_data: create_data_uri('csvs/valid.csv')
    }, @package.id)
    processor.process

    expect(@package.validations.count).to eq(1)
  end

  it "creates a package from an uploaded file" do
    processor = described_class.new({
      file_ids: [
        mock_upload('valid.csv')
      ]
    }, @package.id)
    processor.process

    expect(@package.validations.count).to eq(1)
  end

  it "creates a package from a vanilla file upload" do
    processor = described_class.new({
      files: [
        mock_uploaded_file('csvs/valid.csv')
      ]
    }, @package.id)
    processor.process

    expect(@package.validations.count).to eq(1)
  end

  it "creates a package from a zipped url" do
    mock_file("http://example.com/valid.zip", 'csvs/valid.zip')
    processor = described_class.new({
      urls: ['http://example.com/valid.zip']
    }, @package.id)
    processor.process

    expect(@package.validations.count).to eq(1)
  end

  it "joins chunks in the correct order" do
    (1..10).to_a.shuffle.each do |i|
      StoredChunk.save('chunked_file', i.to_s, i)
    end

    processor = described_class.new({
      file_ids: [
        'chunked_file,10'
      ]
    }, @package.id)
    processor.fetch_uploaded_files

    file = FogStorage.new.find_file('chunked_file')

    expect(file.body).to eq("12345678910")
  end

end


text:
using Signum.Entities.Authorization;
using System.ComponentModel;

namespace Signum.Entities.Map;

public enum MapMessage
{
    Map,
    Namespace,
    TableSize,
    Columns,
    Rows,
    [Description("Press {0} to explore each table")]
    Press0ToExploreEachTable,
    [Description("Press {0} to explore states and operations")]
    Press0ToExploreStatesAndOperations,
    Filter,
    Color,
    State,
    StateColor,
    RowsHistory,
    TableSizeHistory,
}

[DescriptionOptions(DescriptionOptions.Members)]
public enum DefaultState
{
    Start,
    All,
    End,
}

[AutoInit]
public static class MapPermission
{
    public static PermissionSymbol ViewMap;
}


text:
package org.dswarm.persistence.service.test.utils;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.json.JSONException;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.dswarm.persistence.DMPPersistenceException;
import org.dswarm.persistence.GuicedTest;
import org.dswarm.persistence.model.DMPObject;
import org.dswarm.persistence.model.proxy.ProxyDMPObject;
import org.dswarm.persistence.service.BasicJPAService;
import org.dswarm.persistence.service.UUIDService;
import org.dswarm.persistence.service.test.BasicJPAServiceTest;

public abstract class BasicJPAServiceTestUtils<POJOCLASSPERSISTENCESERVICE extends BasicJPAService<PROXYPOJOCLASS, POJOCLASS>, PROXYPOJOCLASS extends ProxyDMPObject<POJOCLASS>, POJOCLASS extends DMPObject> {

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

	protected final Class<POJOCLASS> pojoClass;

	protected final String pojoClassName;

	protected final Class<POJOCLASSPERSISTENCESERVICE> persistenceServiceClass;

	protected final ObjectMapper objectMapper;
	protected final String type;

	public POJOCLASSPERSISTENCESERVICE getJpaService() {
		return jpaService;
	}

	protected final POJOCLASSPERSISTENCESERVICE jpaService;

	protected Map<String, POJOCLASS> cache = new HashMap<>();

	public abstract POJOCLASS createObject(final JsonNode objectDescription) throws Exception;

	public abstract POJOCLASS createObject(final String identifier) throws Exception;

	public abstract POJOCLASS createAndPersistDefaultObject() throws Exception;

	public abstract POJOCLASS createDefaultObject() throws Exception;

	protected PROXYPOJOCLASS createObject() {

		PROXYPOJOCLASS proxyObject = null;

		try {

			proxyObject = jpaService.createObjectTransactional();
		} catch (final DMPPersistenceException e) {

			Assert.assertTrue("something went wrong during object creation.\n" + e.getMessage(), false);
		}

		Assert.assertNotNull(type + " shouldn't be null", proxyObject);
		Assert.assertNotNull(type + " id shouldn't be null", proxyObject.getId());

		BasicJPAServiceTestUtils.LOG.debug("created new {} with id = '{}'", type, proxyObject.getId());

		return proxyObject;
	}

	public BasicJPAServiceTestUtils(final Class<POJOCLASS> pojoClassArg, final Class<POJOCLASSPERSISTENCESERVICE> persistenceServiceClassArg) {

		pojoClass = pojoClassArg;
		pojoClassName = pojoClass.getSimpleName();
		type = pojoClassName;

		persistenceServiceClass = persistenceServiceClassArg;

		jpaService = GuicedTest.getInstance(persistenceServiceClassArg).get();
		objectMapper = GuicedTest.getInstance(ObjectMapper.class).get();
	}

	/**
	 * Assert that neither {@code expectedObject} nor {@code actualObject} is null.
	 *
	 * @param expectedObject
	 * @param actualObject
	 */
	public void compareObjects(final POJOCLASS expectedObject, final POJOCLASS actualObject) throws JsonProcessingException, JSONException {

		Assert.assertNotNull("excepted " + pojoClassName + " shouldn't be null", expectedObject);
		Assert.assertNotNull("actual " + pojoClassName + " shouldn't be null", actualObject);
	}

	public void evaluateObjects(final String objectsJSON, final Set<POJOCLASS> expectedObjects) throws Exception {

		Assert.assertNotNull("the " + pojoClassName + "s JSON string shouldn't be null", objectsJSON);

		final Map<String, POJOCLASS> responseObjects = Maps.newLinkedHashMap();
		final ArrayNode responseObjectsJSONArray = objectMapper.readValue(objectsJSON, ArrayNode.class);

		Assert.assertNotNull("response " + pojoClassName + "s JSON array shouldn't be null", responseObjectsJSONArray);

		for (final JsonNode responseObjectJSON : responseObjectsJSONArray) {

			final POJOCLASS responseObject = objectMapper.readValue(responseObjectJSON.toString(), pojoClass);

			responseObjects.put(responseObject.getUuid(), responseObject);
		}

		final Set<POJOCLASS> newExpectedObjects;

		if (expectedObjects != null) {

			newExpectedObjects = Sets.newLinkedHashSet();

			for (final POJOCLASS expectedObject : expectedObjects) {

				final String expectedObjectJSONString = objectMapper.writeValueAsString(expectedObject);
				final POJOCLASS newExpectedObject = objectMapper.readValue(expectedObjectJSONString, pojoClass);

				newExpectedObjects.add(newExpectedObject);
			}
		} else {

			newExpectedObjects = expectedObjects;
		}

		compareObjects(newExpectedObjects, responseObjects);
	}

	/**
	 * Assert that expectedObjects and actualObjects have the same size.<br />
	 * Assert that both collections contain equal objects regarding id and name.
	 *
	 * @param expectedObjects
	 * @param actualObjects
	 */
	public void compareObjects(final Set<POJOCLASS> expectedObjects, final Map<String, POJOCLASS> actualObjects)
			throws JsonProcessingException, JSONException {

		Assert.assertNotNull("expected objects shouldn't be null", expectedObjects);
		Assert.assertNotNull("actual objects shouldn't be null", actualObjects);

		Assert.assertEquals("different number of " + pojoClassName + " objects.", expectedObjects.size(), actualObjects.size());

		for (final POJOCLASS expectedObject : expectedObjects) {

			final POJOCLASS actualObject = actualObjects.get(expectedObject.getUuid());

			Assert.assertNotNull(pojoClassName + " for id '" + expectedObject.getUuid() + "' shouldn't be null", actualObject);
			Assert.assertEquals(pojoClassName + "s are not equal", expectedObject, actualObject);

			compareObjects(expectedObject, actualObject);
		}
	}

	public List<POJOCLASS> getObjects() {

		return jpaService.getObjects();
	}

	public POJOCLASS getObject(final POJOCLASS expectedObject) throws JsonProcessingException, JSONException {

		final POJOCLASS responseObject = jpaService.getObject(expectedObject.getUuid());

		Assert.assertNotNull("the updated " + type + " shouldn't be null", responseObject);
		Assert.assertEquals("the " + type + "s are not equal", expectedObject, responseObject);

		reset();
		compareObjects(expectedObject, responseObject);

		return responseObject;
	}

	/**
	 * creates an object and compares the result via #compareObjects
	 *
	 * @param object
	 * @param expectedObject
	 * @return
	 * @throws Exception
	 */
	public POJOCLASS createAndCompareObject(final POJOCLASS object, final POJOCLASS expectedObject) throws Exception {

		PROXYPOJOCLASS proxyObject = null;

		try {

			proxyObject = createObject(object);
		} catch (final DMPPersistenceException e) {

			Assert.assertTrue("something went wrong during object creation.\n" + e.getMessage(), false);
		}

		Assert.assertNotNull(type + " shouldn't be null", proxyObject);
		Assert.assertNotNull(type + " id shouldn't be null", proxyObject.getId());

		BasicJPAServiceTestUtils.LOG.debug("created new " + type + " with id = '" + proxyObject.getId() + "'");

		final POJOCLASS createdObject = proxyObject.getObject();
		final POJOCLASS objectWithUpdates = prepareObjectForUpdate(object, createdObject);

		try {

			proxyObject = jpaService.updateObjectTransactional(objectWithUpdates);
		} catch (final DMPPersistenceException e) {

			Assert.assertTrue("something went wrong during object update.\n" + e.getMessage(), false);
		}

		Assert.assertNotNull(type + " shouldn't be null", proxyObject);

		compareObjects(expectedObject, proxyObject.getObject());

		return proxyObject.getObject();
	}

	public POJOCLASS updateObject(final POJOCLASS updateObject) {

		try {

			final PROXYPOJOCLASS proxyUpdatedObject = jpaService.updateObjectTransactional(updateObject);

			Assert.assertNotNull("the proxy object of " + type + " shouldn't be null", proxyUpdatedObject);

			return proxyUpdatedObject.getObject();
		} catch (final DMPPersistenceException e) {

			Assert.assertTrue("something went wrong while updating the " + type, false);
		}

		return null;
	}

	public POJOCLASS updateAndCompareObject(final POJOCLASS updateObject, final POJOCLASS expectedObject) throws Exception {

		POJOCLASS freshUpdatedObject = updateObject(updateObject);

		Assert.assertNotNull("the object of " + type + " shouldn't be null", freshUpdatedObject);

		compareObjects(expectedObject, freshUpdatedObject);

		return freshUpdatedObject;
	}

	public void deleteObject(final POJOCLASS object) {

		final String objectId = object.getUuid();

		deleteObject(objectId);
	}

	protected void deleteObject(final String uuid) {

		jpaService.deleteObject(uuid);

		final POJOCLASS deletedObject = jpaService.getObject(uuid);

		Assert.assertNull("deleted " + type + " shouldn't exist any more", deletedObject);
	}

	/**
	 * default impl return getDefaultObject
	 *
	 * @return
	 * @throws Exception
	 */
	public POJOCLASS createAndPersistDefaultCompleteObject() throws Exception {

		return createAndPersistDefaultObject();
	}

	/**
	 * default impl return getDefaultObject
	 *
	 * @return
	 * @throws Exception
	 */
	public POJOCLASS createDefaultCompleteObject() throws Exception {

		return createDefaultObject();
	}

	/**
	 * Prepares a given object with information from an object with updates.
	 *
	 * @param objectWithUpdates an object with updates
	 * @param object            the given object
	 * @return the updated object
	 */
	protected abstract POJOCLASS prepareObjectForUpdate(final POJOCLASS objectWithUpdates, final POJOCLASS object);

	protected PROXYPOJOCLASS createObject(final POJOCLASS object) throws DMPPersistenceException {

		return jpaService.createObjectTransactional(object.getUuid());
	}

	/**
	 * Creates a new object of the concrete POJO class.
	 *
	 * @return a new instance of the concrete POJO class
	 * @throws DMPPersistenceException if something went wrong.
	 */
	protected POJOCLASS createNewObject(final String uuid) throws DMPPersistenceException {

		final POJOCLASS object;

		Constructor<POJOCLASS> constructor = null;

		try {
			constructor = pojoClass.getConstructor(String.class);
		} catch (final SecurityException | NoSuchMethodException e1) {

			throw new DMPPersistenceException(e1.getMessage());
		}

		if (null == constructor) {

			throw new DMPPersistenceException("couldn't find constructor to instantiate new '" + pojoClassName + "' with a uuid");
		}

		final String finalUUID;

		if (uuid != null) {

			finalUUID = uuid;
		} else {
			finalUUID = UUIDService.getUUID(pojoClassName);
		}

		try {

			object = constructor.newInstance(finalUUID);
		} catch (final InstantiationException | InvocationTargetException | IllegalArgumentException | IllegalAccessException e) {

			BasicJPAServiceTestUtils.LOG.error("something went wrong while " + pojoClassName + "object creation", e);

			throw new DMPPersistenceException(e.getMessage());
		}

		return object;
	}

	public abstract void reset();
}


text:
Introduction
====

Cabin (CAbal BINary sandbox) is a tool to manage cabal binary sandboxes. It
lets you install a binary program from cabal into an individual sandbox, and
then load that sandbox's bin directory into your home environment. For example:

```
cabin install alex
cabin load alex
```

Would install `alex` into its own sandbox and link the relevant binaries into
your $PATH.

Installation
====

There are two easy ways to install:

From Hackage
-----

    cabal --no-require-sandbox install cabin

will install cabin in your default cabal profile, whence you can run it:

    $HOME/.cabal/bin/cabin

You also need to add the cabin binary path to your PATH:

    export PATH=$PATH:$HOME/.cabin/bin

And add this line to the relevant `.profile` file.

From github
------

    wget -O - https://raw.githubusercontent.com/nc6/cabin/master/bootstrap.sh | bash

Should bootstrap the operation and install `cabin` into its own cabin, which
will be loaded for you. Note that if you then call `cabin unload cabin`, it will
no longer be available and you will have to invoke the `cabin` binary directly
from within `$HOME/.cabin/cabins/cabin/.cabal-sandbox/bin/cabin`.


text:
import IAction from './action.i';
import IEntity from '../entity/entity.i';
import EventEmitter from 'eventemitter3';

export default interface ITurn extends EventEmitter {
  readonly turnNumber: number;
  readonly owner: IEntity;
  action?: IAction;

  isResolved(): boolean;
  begin(): void;
  end(): void;
  resolve(action: IAction): void;
}


text:
package org.jboss.resteasy.plugins.providers;

import org.jboss.resteasy.util.NoContent;

import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

/**
 * @author Bill Burke
 * @version $Revision: 1 $
 */
@Provider
@Produces("*/*")
@Consumes("*/*")
public class StringTextStar implements MessageBodyReader<String>, MessageBodyWriter<String>
{
   public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
   {
      return String.class.equals(type);
   }

   public String readFrom(Class<String> type,
                          Type genericType,
                          Annotation[] annotations,
                          MediaType mediaType,
                          MultivaluedMap<String, String> httpHeaders,
                          InputStream entityStream) throws IOException
   {
      if (NoContent.isContentLengthZero(httpHeaders)) return "";
      return ProviderHelper.readString(entityStream, mediaType);
   }

   public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
   {
      return String.class.equals(type);
   }

   public long getSize(String o, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
   {
      return -1;
   }

   public void writeTo(String o,
                       Class<?> type,
                       Type genericType,
                       Annotation[] annotations,
                       MediaType mediaType,
                       MultivaluedMap<String, Object> httpHeaders,
                       OutputStream entityStream) throws IOException
   {
      String charset = mediaType.getParameters().get("charset");
      if (charset == null) entityStream.write(o.getBytes("UTF-8"));
      else entityStream.write(o.getBytes(charset));

   }
}


text:
var parser = require('./parser');
var File = require('./file');

var fs = require('fs');
var path = require('path');
var _ = require('lodash');
var resolve = require('enhanced-resolve');

var RJSS = module.exports = function (options) {
  this._cache = {};
  this.options = options;
};

RJSS.prototype = {
  parseFileSync: function (filepath) {
    var absolutePath = resolve.sync(process.cwd(), filepath);
    var stat = fs.statSync(absolutePath);

    if (!stat.isFile()) {
      throw new Error(filepath + " is not a file");
    }

    var mtime = stat.mtime;

    var cached;

    if ((cached = this._cache[absolutePath]) && cached.mtime === mtime) {
      return cached.file;
    }

    var content = fs.readFileSync(absolutePath);

    var file = this.parseContentSync(content, {
      path: filepath,
      absolute_path: absolutePath
    });

    this._cache[absolutePath] = {
      mtime: mtime,
      file: file
    };

    return file;
  },
  parseContentSync: function (content, options) {
    var options = _.extend({}, this.options, options || {});

    if (!options.absolute_path && options.path) {
      options.absolute_path = resolve.sync(process.cwd(), options.path);
    }

    var result = parser.parse(content.toString());
    var file = new File(result, this, options);
    file.processScopeSync();
    return file;
  }
};


text:
pub enum ExpectedType {
    Boolean,
    Integer,
    Long,
    Short,
    Double,
    Str,
    Binary,
}

impl ExpectedType {
    /// Returns an option of the `ExpectedType` for the given code, or `None`.
    pub fn get_expected_type(code: i32) -> ::std::option::Option<Self> {
        match code {
            0..=9 => Some(ExpectedType::Str),
            10..=39 => Some(ExpectedType::Double),
            40..=59 => Some(ExpectedType::Double),
            60..=79 => Some(ExpectedType::Short),
            90..=99 => Some(ExpectedType::Integer),
            100..=102 => Some(ExpectedType::Str),
            105 => Some(ExpectedType::Str),
            110..=119 => Some(ExpectedType::Double),
            120..=129 => Some(ExpectedType::Double),
            130..=139 => Some(ExpectedType::Double),
            140..=149 => Some(ExpectedType::Double),
            160..=169 => Some(ExpectedType::Long),
            170..=179 => Some(ExpectedType::Short),
            210..=239 => Some(ExpectedType::Double),
            270..=279 => Some(ExpectedType::Short),
            280..=289 => Some(ExpectedType::Short),
            290..=299 => Some(ExpectedType::Boolean),
            300..=309 => Some(ExpectedType::Str),
            310..=319 => Some(ExpectedType::Binary),
            320..=329 => Some(ExpectedType::Str),
            330..=369 => Some(ExpectedType::Str),
            370..=379 => Some(ExpectedType::Short),
            380..=389 => Some(ExpectedType::Short),
            390..=399 => Some(ExpectedType::Str),
            400..=409 => Some(ExpectedType::Short),
            410..=419 => Some(ExpectedType::Str),
            420..=429 => Some(ExpectedType::Integer),
            430..=439 => Some(ExpectedType::Str),
            440..=449 => Some(ExpectedType::Integer),
            450..=459 => Some(ExpectedType::Integer),
            460..=469 => Some(ExpectedType::Double),
            470..=479 => Some(ExpectedType::Str),
            480..=481 => Some(ExpectedType::Str),
            999 => Some(ExpectedType::Str),
            1000..=1009 => Some(ExpectedType::Str),
            1010..=1059 => Some(ExpectedType::Double),
            1060..=1070 => Some(ExpectedType::Short),
            1071 => Some(ExpectedType::Integer),
            _ => None,
        }
    }
}


text:
#include "pch.h"
#include "AudioSourceReader.h"
#include <windows.media.mediaproperties.h>
#include <windows.media.core.interop.h>
#include <windows.media.h>

static bool g_MFInitialized = false;

void InitializeMediaFoundation() {
	if (!g_MFInitialized) {
		MFStartup(MF_VERSION);
		g_MFInitialized = true;
	}
}

namespace winrt::AudioVisualizer::implementation
{

	int32_t AudioSourceReader::FirstAudioStreamIndex()
	{
		return MF_SOURCE_READER_FIRST_AUDIO_STREAM;
	}

	void AudioSourceReader::Close()
	{
		reader = nullptr;
	}

	int32_t AudioSourceReader::StreamIndex()
	{
		if (!reader) {
			throw hresult_error(RO_E_CLOSED);
		}
		return streamIndex;
	}

	void AudioSourceReader::StreamIndex(int32_t index)
	{
		if (index != streamIndex) {
			com_ptr<IMFMediaType> nativeType;
			check_hresult(reader->GetNativeMediaType(index, 0, nativeType.put()));
			GUID majorType;
			nativeType->GetMajorType(&majorType);
			if (majorType != MFMediaType_Audio) {
				throw hresult_invalid_argument(L"Not an audio stream");
			}
			// Unselect old stream, select new stream
			reader->SetStreamSelection(streamIndex, FALSE);
			reader->SetStreamSelection(index, TRUE);
			streamIndex = index;
			SetFormatProperties();
			com_ptr<IMFMediaType> mediaType;
			check_hresult(reader->GetNativeMediaType(streamIndex, 0, mediaType.put()));
			GUID subType;
			memset(&subType, 0, sizeof(GUID));
			check_hresult(mediaType->GetGUID(MF_MT_SUBTYPE, &subType));
			b_IsMp3 = subType == MFAudioFormat_MP3;
		}
	}

	void AudioSourceReader::Seek(Windows::Foundation::TimeSpan position)
	{
		if (!reader) {
			throw hresult_error(RO_E_CLOSED);
		}
		PROPVARIANT pvPosition;
		PropVariantInit(&pvPosition);
		pvPosition.vt = VT_I8;
		pvPosition.hVal.QuadPart = position.count();
		check_hresult(reader->SetCurrentPosition(GUID_NULL, pvPosition));
		currentSampleIndex = -1;
	}

	Windows::Media::AudioFrame AudioSourceReader::Read()
	{
		if (!reader) {
			throw hresult_error(RO_E_CLOSED);
		}
		com_ptr<IMFSample> sample;
		DWORD dwStreamFlags = 0;
		check_hresult(reader->ReadSample(streamIndex, 0, nullptr, &dwStreamFlags, nullptr, sample.put()));

		flags = (AudioSourceReaderFlags)dwStreamFlags;
		if (dwStreamFlags & MF_SOURCE_READERF_ERROR) {
			throw hresult_error(E_FAIL);
		}

		Windows::Media::AudioFrame result{ nullptr };

		if (sample)
		{
			// Fix up position if non-compressed format
			if (samplesPerSecond != 0) {
				DWORD sampleBufferLength = 0;
				check_hresult(sample->GetTotalLength(&sampleBufferLength));
				int64_t sampleCount = sampleBufferLength / bytesPerSample;

				// Read the sample time position from the reader
				if (currentSampleIndex == -1) {
					REFERENCE_TIME sampleTime = 0;
					check_hresult(sample->GetSampleTime(&sampleTime));
					currentSampleIndex = time_to_samples(sampleTime);
				}
				else {
					// Fix up sample time based on tracked sample index
					check_hresult(sample->SetSampleTime(samples_to_time(currentSampleIndex)));
					check_hresult(sample->SetSampleDuration(samples_to_time(sampleCount)));
				}
				currentSampleIndex += sampleCount;
			}
			// Convert sample to audio frame IAudioFrameNativeFactory allows that without copy
			MULTI_QI qiFactory[1] = { { &__uuidof(IAudioFrameNativeFactory),nullptr,S_OK } };
			check_hresult(CoCreateInstanceFromApp(CLSID_AudioFrameNativeFactory, nullptr, CLSCTX_INPROC_SERVER, nullptr, 1, qiFactory));
			check_hresult(qiFactory[0].hr);

			com_ptr<IAudioFrameNativeFactory> nativeFactory;
			copy_from_abi(nativeFactory, qiFactory[0].pItf);

			// Now use the factory to create frame out of IMFSample
			com_ptr<ABI::Windows::Media::IAudioFrame> frame;
			check_hresult(nativeFactory->CreateFromMFSample(sample.get(), false, IID_PPV_ARGS(frame.put())));

			copy_from_abi(result, frame.get());
		}

		return result;
	}

	AudioSourceReader::AudioSourceReader(Windows::Storage::Streams::IRandomAccessStream const& stream)
	{
		InitializeMediaFoundation();

		com_ptr<IMFByteStream> byteStream;
		HRESULT hr = MFCreateMFByteStreamOnStreamEx(reinterpret_cast<IUnknown*>(winrt::get_abi(stream)), byteStream.put());
		check_hresult(hr);

		hr = MFCreateSourceReaderFromByteStream(byteStream.get(), nullptr, reader.put());
		check_hresult(hr);

		StreamIndex(AudioSourceReader::FirstAudioStreamIndex());
	}
	Windows::Foundation::TimeSpan AudioSourceReader::Duration()
	{
		if (!reader) {
			throw hresult_error(RO_E_CLOSED);
		}
		PROPVARIANT pvDuration;
		PropVariantInit(&pvDuration);
		check_hresult(reader->GetPresentationAttribute((DWORD)MF_SOURCE_READER_MEDIASOURCE, MF_PD_DURATION, &pvDuration));
		return Windows::Foundation::TimeSpan(pvDuration.hVal.QuadPart);
	}
	Windows::Media::MediaProperties::IMediaEncodingProperties AudioSourceReader::GetNativeFormat(int32_t forStreamIndex)
	{
		if (!reader) {
			throw hresult_error(RO_E_CLOSED);
		}
		com_ptr<IMFMediaType> mediaType;
		HRESULT hr = reader->GetNativeMediaType(forStreamIndex, 0, mediaType.put());
		if (hr == MF_E_INVALIDSTREAMNUMBER)
			return nullptr;

		check_hresult(hr);
		com_ptr<ABI::Windows::Media::MediaProperties::IMediaEncodingProperties> abiMediaProps;
		check_hresult(MFCreatePropertiesFromMediaType(mediaType.get(), IID_PPV_ARGS(abiMediaProps.put())));

		Windows::Media::MediaProperties::IMediaEncodingProperties mediaProperties;
		winrt::copy_from_abi(mediaProperties, abiMediaProps.get());
		return mediaProperties;
	}

	Windows::Media::MediaProperties::IMediaEncodingProperties AudioSourceReader::Format()
	{
		if (!reader) {
			throw hresult_error(RO_E_CLOSED);
		}
		com_ptr<IMFMediaType> mediaType;
		check_hresult(reader->GetCurrentMediaType(streamIndex, mediaType.put()));
		com_ptr<ABI::Windows::Media::MediaProperties::IMediaEncodingProperties> abiMediaProps;
		check_hresult(MFCreatePropertiesFromMediaType(mediaType.get(), IID_PPV_ARGS(abiMediaProps.put())));

		Windows::Media::MediaProperties::IMediaEncodingProperties mediaProperties;
		winrt::copy_from_abi(mediaProperties, abiMediaProps.get());
		return mediaProperties;
	}

	void AudioSourceReader::Format(Windows::Media::MediaProperties::IMediaEncodingProperties const & format)
	{
		if (!reader) {
			throw hresult_error(RO_E_CLOSED);
		}
		com_ptr<IMFMediaType> mediaType;
		check_hresult(MFCreateMediaTypeFromProperties(reinterpret_cast<IUnknown*>(winrt::get_abi(format)), mediaType.put()));
		check_hresult(reader->SetCurrentMediaType(streamIndex, nullptr, mediaType.get()));
		SetFormatProperties();
	}

	void AudioSourceReader::SetFormatProperties()
	{
		com_ptr<IMFMediaType> mediaType;
		check_hresult(reader->GetCurrentMediaType(streamIndex, mediaType.put()));
		GUID subType;
		memset(&subType, 0, sizeof(subType));
		check_hresult(mediaType->GetGUID(MF_MT_SUBTYPE, &subType));
		if (subType == MFAudioFormat_PCM || subType == MFAudioFormat_Float) {
			// The next property is really frames per second
			UINT32 framesPerSecond = 0;
			check_hresult(mediaType->GetUINT32(MF_MT_AUDIO_SAMPLES_PER_SECOND, &framesPerSecond));
			UINT32 channelCount = 0;
			check_hresult(mediaType->GetUINT32(MF_MT_AUDIO_NUM_CHANNELS, &channelCount));
			samplesPerSecond = framesPerSecond * channelCount;
			UINT32 bitsPerSample = 0;
			check_hresult(mediaType->GetUINT32(MF_MT_AUDIO_BITS_PER_SAMPLE, &bitsPerSample));
			bytesPerSample = bitsPerSample >> 3;
		}
		else {
			samplesPerSecond = 0;
			bytesPerSample = 0;
		}
	}
}


text:
package org.hisp.dhis.common;

import java.util.Map;
import java.util.Set;

import org.hisp.dhis.common.view.DetailedView;
import org.hisp.dhis.common.view.ExportView;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.dataelement.DataElementDomain;
import org.hisp.dhis.dataelement.DataElementOperand;
import org.hisp.dhis.dataset.DataSet;
import org.hisp.dhis.indicator.Indicator;
import org.hisp.dhis.program.ProgramIndicator;
import org.hisp.dhis.trackedentity.TrackedEntityAttribute;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;

/**
* @author Lars Helge Overland
*/
@JacksonXmlRootElement( localName = "dataDimensionItem", namespace = DxfNamespaces.DXF_2_0 )
public class DataDimensionItem
{
    public static final Set<Class<? extends IdentifiableObject>> DATA_DIMENSION_CLASSES = ImmutableSet.<Class<? extends IdentifiableObject>>builder().
        add( Indicator.class ).add( DataElement.class ).add( DataElementOperand.class ).
        add( DataSet.class ).add( ProgramIndicator.class ).add( TrackedEntityAttribute.class ).build();

    public static final Map<DataDimensionItemType, Class<? extends NameableObject>> DATA_DIMENSION_TYPE_CLASS_MAP = ImmutableMap.<DataDimensionItemType, Class<? extends NameableObject>>builder().
        put( DataDimensionItemType.INDICATOR, Indicator.class ).put( DataDimensionItemType.AGGREGATE_DATA_ELEMENT, DataElement.class ).
        put( DataDimensionItemType.DATA_ELEMENT_OPERAND, DataElementOperand.class ).put( DataDimensionItemType.DATA_SET, DataSet.class ).
        put( DataDimensionItemType.PROGRAM_INDICATOR, ProgramIndicator.class ).put( DataDimensionItemType.PROGRAM_ATTRIBUTE, TrackedEntityAttribute.class ).
        put( DataDimensionItemType.PROGRAM_DATA_ELEMENT, DataElement.class ).build();

    public static final Map<DataDimensionItemType, DataElementDomain> DATA_DIMENSION_TYPE_DOMAIN_MAP = ImmutableMap.<DataDimensionItemType, DataElementDomain>builder().
        put( DataDimensionItemType.AGGREGATE_DATA_ELEMENT, DataElementDomain.AGGREGATE ).put( DataDimensionItemType.PROGRAM_DATA_ELEMENT, DataElementDomain.TRACKER ).build();

    private int id;

    // -------------------------------------------------------------------------
    // Data dimension objects
    // -------------------------------------------------------------------------

    private Indicator indicator;

    private DataElement dataElement;

    private DataElementOperand dataElementOperand;

    private DataSet dataSet;

    private ProgramIndicator programIndicator;

    private TrackedEntityAttribute trackedEntityAttribute;

    // -------------------------------------------------------------------------
    // Constructor
    // -------------------------------------------------------------------------

    public DataDimensionItem()
    {
    }

    public static DataDimensionItem create( NameableObject object )
    {
        DataDimensionItem dimension = new DataDimensionItem();

        if ( Indicator.class.isAssignableFrom( object.getClass() ) )
        {
            dimension.setIndicator( (Indicator) object );
        }
        else if ( DataElement.class.isAssignableFrom( object.getClass() ) )
        {
            dimension.setDataElement( (DataElement) object );
        }
        else if ( DataElementOperand.class.isAssignableFrom( object.getClass() ) )
        {
            dimension.setDataElementOperand( (DataElementOperand) object );
        }
        else if ( DataSet.class.isAssignableFrom( object.getClass() ) )
        {
            dimension.setDataSet( (DataSet) object );
        }
        else if ( ProgramIndicator.class.isAssignableFrom( object.getClass() ) )
        {
            dimension.setProgramIndicator( (ProgramIndicator) object );
        }
        else if ( TrackedEntityAttribute.class.isAssignableFrom( object.getClass() ) )
        {
            dimension.setTrackedEntityAttribute( (TrackedEntityAttribute) object );
        }
        else
        {
            throw new IllegalArgumentException( "Not a valid data dimension: " + object.getClass().getSimpleName() + ", " + object );
        }

        return dimension;
    }

    // -------------------------------------------------------------------------
    // Logic
    // -------------------------------------------------------------------------

    public NameableObject getNameableObject()
    {
        if ( indicator != null )
        {
            return indicator;
        }
        else if ( dataElement != null )
        {
            return dataElement;
        }
        else if ( dataElementOperand != null )
        {
            return dataElementOperand;
        }
        else if ( dataSet != null )
        {
            return dataSet;
        }
        else if ( programIndicator != null )
        {
            return programIndicator;
        }
        else if ( trackedEntityAttribute != null )
        {
            return trackedEntityAttribute;
        }

        return null;
    }

    @JsonProperty
    @JsonView( { DetailedView.class, ExportView.class } )
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public DataDimensionItemType getDataDimensionItemType()
    {
        if ( indicator != null )
        {
            return DataDimensionItemType.INDICATOR;
        }
        else if ( dataElement != null )
        {
            if ( DataElementDomain.TRACKER.equals( dataElement.getDomainType() ) )
            {
                return DataDimensionItemType.PROGRAM_DATA_ELEMENT;
            }
            else
            {
                return DataDimensionItemType.AGGREGATE_DATA_ELEMENT;
            }
        }
        else if ( dataElementOperand != null )
        {
            return DataDimensionItemType.DATA_ELEMENT_OPERAND;
        }
        else if ( dataSet != null )
        {
            return DataDimensionItemType.DATA_SET;
        }
        else if ( programIndicator != null )
        {
            return DataDimensionItemType.PROGRAM_INDICATOR;
        }
        else if ( trackedEntityAttribute != null )
        {
            return DataDimensionItemType.PROGRAM_ATTRIBUTE;
        }

        return null;
    }

    // -------------------------------------------------------------------------
    // Get and set methods
    // -------------------------------------------------------------------------

    @JsonIgnore
    public int getId()
    {
        return id;
    }

    public void setId( int id )
    {
        this.id = id;
    }

    @JsonProperty
    @JsonSerialize( as = BaseNameableObject.class )
    @JsonView( { DetailedView.class, ExportView.class } )
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public Indicator getIndicator()
    {
        return indicator;
    }

    public void setIndicator( Indicator indicator )
    {
        this.indicator = indicator;
    }

    @JsonProperty
    @JsonSerialize( as = BaseNameableObject.class )
    @JsonView( { DetailedView.class, ExportView.class } )
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public DataElement getDataElement()
    {
        return dataElement;
    }

    public void setDataElement( DataElement dataElement )
    {
        this.dataElement = dataElement;
    }

    @JsonProperty
    @JsonSerialize( as = BaseNameableObject.class )
    @JsonView( { DetailedView.class, ExportView.class } )
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public DataElementOperand getDataElementOperand()
    {
        return dataElementOperand;
    }

    public void setDataElementOperand( DataElementOperand dataElementOperand )
    {
        this.dataElementOperand = dataElementOperand;
    }

    @JsonProperty
    @JsonSerialize( as = BaseNameableObject.class )
    @JsonView( { DetailedView.class, ExportView.class } )
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public DataSet getDataSet()
    {
        return dataSet;
    }

    public void setDataSet( DataSet dataSet )
    {
        this.dataSet = dataSet;
    }

    @JsonProperty
    @JsonSerialize( as = BaseNameableObject.class )
    @JsonView( { DetailedView.class, ExportView.class } )
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public ProgramIndicator getProgramIndicator()
    {
        return programIndicator;
    }

    public void setProgramIndicator( ProgramIndicator programIndicator )
    {
        this.programIndicator = programIndicator;
    }

    @JsonProperty
    @JsonSerialize( as = BaseNameableObject.class )
    @JsonView( { DetailedView.class, ExportView.class } )
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public TrackedEntityAttribute getTrackedEntityAttribute()
    {
        return trackedEntityAttribute;
    }

    public void setTrackedEntityAttribute( TrackedEntityAttribute trackedEntityAttribute )
    {
        this.trackedEntityAttribute = trackedEntityAttribute;
    }
}