text:
#pragma once
#include <aws/comprehendmedical/ComprehendMedical_EXPORTS.h>
#include <aws/core/client/ClientConfiguration.h>
#include <aws/core/client/AWSClient.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/comprehendmedical/ComprehendMedicalServiceClientModel.h>

namespace Aws
{
namespace ComprehendMedical
{
  /**
   *
 Comprehend Medical; extracts structured information from unstructured
   * clinical text. Use these actions to gain insight in your documents.

   */
  class AWS_COMPREHENDMEDICAL_API ComprehendMedicalClient : public Aws::Client::AWSJsonClient
  {
    public:
      typedef Aws::Client::AWSJsonClient BASECLASS;
      static const char* SERVICE_NAME;
      static const char* ALLOCATION_TAG;

       /**
        * Initializes client to use DefaultCredentialProviderChain, with default http client factory, and optional client config. If client config
        * is not specified, it will be initialized to default values.
        */
        ComprehendMedicalClient(const Aws::ComprehendMedical::ComprehendMedicalClientConfiguration& clientConfiguration = Aws::ComprehendMedical::ComprehendMedicalClientConfiguration(),
                                std::shared_ptr<ComprehendMedicalEndpointProviderBase> endpointProvider = Aws::MakeShared<ComprehendMedicalEndpointProvider>(ALLOCATION_TAG));

       /**
        * Initializes client to use SimpleAWSCredentialsProvider, with default http client factory, and optional client config. If client config
        * is not specified, it will be initialized to default values.
        */
        ComprehendMedicalClient(const Aws::Auth::AWSCredentials& credentials,
                                std::shared_ptr<ComprehendMedicalEndpointProviderBase> endpointProvider = Aws::MakeShared<ComprehendMedicalEndpointProvider>(ALLOCATION_TAG),
                                const Aws::ComprehendMedical::ComprehendMedicalClientConfiguration& clientConfiguration = Aws::ComprehendMedical::ComprehendMedicalClientConfiguration());

       /**
        * Initializes client to use specified credentials provider with specified client config. If http client factory is not supplied,
        * the default http client factory will be used
        */
        ComprehendMedicalClient(const std::shared_ptr<Aws::Auth::AWSCredentialsProvider>& credentialsProvider,
                                std::shared_ptr<ComprehendMedicalEndpointProviderBase> endpointProvider = Aws::MakeShared<ComprehendMedicalEndpointProvider>(ALLOCATION_TAG),
                                const Aws::ComprehendMedical::ComprehendMedicalClientConfiguration& clientConfiguration = Aws::ComprehendMedical::ComprehendMedicalClientConfiguration());

        /* Legacy constructors due deprecation */
       /**
        * Initializes client to use DefaultCredentialProviderChain, with default http client factory, and optional client config. If client config
        * is not specified, it will be initialized to default values.
        */
        ComprehendMedicalClient(const Aws::Client::ClientConfiguration& clientConfiguration);

       /**
        * Initializes client to use SimpleAWSCredentialsProvider, with default http client factory, and optional client config. If client config
        * is not specified, it will be initialized to default values.
        */
        ComprehendMedicalClient(const Aws::Auth::AWSCredentials& credentials,
                                const Aws::Client::ClientConfiguration& clientConfiguration);

       /**
        * Initializes client to use specified credentials provider with specified client config. If http client factory is not supplied,
        * the default http client factory will be used
        */
        ComprehendMedicalClient(const std::shared_ptr<Aws::Auth::AWSCredentialsProvider>& credentialsProvider,
                                const Aws::Client::ClientConfiguration& clientConfiguration);

        /* End of legacy constructors due deprecation */
        virtual ~ComprehendMedicalClient();

        /**
         *
Gets the properties associated with a medical entities detection job. Use
         * this operation to get the status of a detection job.

See Also:

         * AWS
         * API Reference

         */
        virtual Model::DescribeEntitiesDetectionV2JobOutcome DescribeEntitiesDetectionV2Job(const Model::DescribeEntitiesDetectionV2JobRequest& request) const;

        /**
         * A Callable wrapper for DescribeEntitiesDetectionV2Job that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::DescribeEntitiesDetectionV2JobOutcomeCallable DescribeEntitiesDetectionV2JobCallable(const Model::DescribeEntitiesDetectionV2JobRequest& request) const;

        /**
         * An Async wrapper for DescribeEntitiesDetectionV2Job that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void DescribeEntitiesDetectionV2JobAsync(const Model::DescribeEntitiesDetectionV2JobRequest& request, const DescribeEntitiesDetectionV2JobResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Gets the properties associated with an InferICD10CM job. Use this operation
         * to get the status of an inference job.

See Also:
   AWS
         * API Reference

         */
        virtual Model::DescribeICD10CMInferenceJobOutcome DescribeICD10CMInferenceJob(const Model::DescribeICD10CMInferenceJobRequest& request) const;

        /**
         * A Callable wrapper for DescribeICD10CMInferenceJob that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::DescribeICD10CMInferenceJobOutcomeCallable DescribeICD10CMInferenceJobCallable(const Model::DescribeICD10CMInferenceJobRequest& request) const;

        /**
         * An Async wrapper for DescribeICD10CMInferenceJob that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void DescribeICD10CMInferenceJobAsync(const Model::DescribeICD10CMInferenceJobRequest& request, const DescribeICD10CMInferenceJobResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Gets the properties associated with a protected health information (PHI)
         * detection job. Use this operation to get the status of a detection
         * job.

See Also:
   AWS
         * API Reference

         */
        virtual Model::DescribePHIDetectionJobOutcome DescribePHIDetectionJob(const Model::DescribePHIDetectionJobRequest& request) const;

        /**
         * A Callable wrapper for DescribePHIDetectionJob that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::DescribePHIDetectionJobOutcomeCallable DescribePHIDetectionJobCallable(const Model::DescribePHIDetectionJobRequest& request) const;

        /**
         * An Async wrapper for DescribePHIDetectionJob that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void DescribePHIDetectionJobAsync(const Model::DescribePHIDetectionJobRequest& request, const DescribePHIDetectionJobResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Gets the properties associated with an InferRxNorm job. Use this operation to
         * get the status of an inference job.

See Also:
   AWS
         * API Reference

         */
        virtual Model::DescribeRxNormInferenceJobOutcome DescribeRxNormInferenceJob(const Model::DescribeRxNormInferenceJobRequest& request) const;

        /**
         * A Callable wrapper for DescribeRxNormInferenceJob that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::DescribeRxNormInferenceJobOutcomeCallable DescribeRxNormInferenceJobCallable(const Model::DescribeRxNormInferenceJobRequest& request) const;

        /**
         * An Async wrapper for DescribeRxNormInferenceJob that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void DescribeRxNormInferenceJobAsync(const Model::DescribeRxNormInferenceJobRequest& request, const DescribeRxNormInferenceJobResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
 Gets the properties associated with an InferSNOMEDCT job. Use this operation
         * to get the status of an inference job.

See Also:
   AWS
         * API Reference

         */
        virtual Model::DescribeSNOMEDCTInferenceJobOutcome DescribeSNOMEDCTInferenceJob(const Model::DescribeSNOMEDCTInferenceJobRequest& request) const;

        /**
         * A Callable wrapper for DescribeSNOMEDCTInferenceJob that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::DescribeSNOMEDCTInferenceJobOutcomeCallable DescribeSNOMEDCTInferenceJobCallable(const Model::DescribeSNOMEDCTInferenceJobRequest& request) const;

        /**
         * An Async wrapper for DescribeSNOMEDCTInferenceJob that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void DescribeSNOMEDCTInferenceJobAsync(const Model::DescribeSNOMEDCTInferenceJobRequest& request, const DescribeSNOMEDCTInferenceJobResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Inspects the clinical text for a variety of medical entities and returns
         * specific information about them such as entity category, location, and
         * confidence score on that information. Amazon Comprehend Medical only detects
         * medical entities in English language texts.

The
         * DetectEntitiesV2 operation replaces the DetectEntities
         * operation. This new action uses a different model for determining the entities
         * in your medical text and changes the way that some entities are returned in the
         * output. You should use the DetectEntitiesV2 operation in all new
         * applications.

The DetectEntitiesV2 operation returns the
         * Acuity and Direction entities as attributes instead of
         * types.

See Also:
   AWS
         * API Reference

         */
        virtual Model::DetectEntitiesV2Outcome DetectEntitiesV2(const Model::DetectEntitiesV2Request& request) const;

        /**
         * A Callable wrapper for DetectEntitiesV2 that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::DetectEntitiesV2OutcomeCallable DetectEntitiesV2Callable(const Model::DetectEntitiesV2Request& request) const;

        /**
         * An Async wrapper for DetectEntitiesV2 that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void DetectEntitiesV2Async(const Model::DetectEntitiesV2Request& request, const DetectEntitiesV2ResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
 Inspects the clinical text for protected health information (PHI) entities
         * and returns the entity category, location, and confidence score for each entity.
         * Amazon Comprehend Medical only detects entities in English language
         * texts.

See Also:
   AWS
         * API Reference

         */
        virtual Model::DetectPHIOutcome DetectPHI(const Model::DetectPHIRequest& request) const;

        /**
         * A Callable wrapper for DetectPHI that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::DetectPHIOutcomeCallable DetectPHICallable(const Model::DetectPHIRequest& request) const;

        /**
         * An Async wrapper for DetectPHI that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void DetectPHIAsync(const Model::DetectPHIRequest& request, const DetectPHIResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
InferICD10CM detects medical conditions as entities listed in a patient
         * record and links those entities to normalized concept identifiers in the
         * ICD-10-CM knowledge base from the Centers for Disease Control. Amazon Comprehend
         * Medical only detects medical entities in English language texts.

See
         * Also:
   AWS
         * API Reference

         */
        virtual Model::InferICD10CMOutcome InferICD10CM(const Model::InferICD10CMRequest& request) const;

        /**
         * A Callable wrapper for InferICD10CM that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::InferICD10CMOutcomeCallable InferICD10CMCallable(const Model::InferICD10CMRequest& request) const;

        /**
         * An Async wrapper for InferICD10CM that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void InferICD10CMAsync(const Model::InferICD10CMRequest& request, const InferICD10CMResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
InferRxNorm detects medications as entities listed in a patient record and
         * links to the normalized concept identifiers in the RxNorm database from the
         * National Library of Medicine. Amazon Comprehend Medical only detects medical
         * entities in English language texts.

See Also:
   AWS
         * API Reference

         */
        virtual Model::InferRxNormOutcome InferRxNorm(const Model::InferRxNormRequest& request) const;

        /**
         * A Callable wrapper for InferRxNorm that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::InferRxNormOutcomeCallable InferRxNormCallable(const Model::InferRxNormRequest& request) const;

        /**
         * An Async wrapper for InferRxNorm that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void InferRxNormAsync(const Model::InferRxNormRequest& request, const InferRxNormResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
 InferSNOMEDCT detects possible medical concepts as entities and links them
         * to codes from the Systematized Nomenclature of Medicine, Clinical Terms
         * (SNOMED-CT) ontology

See Also:
   AWS
         * API Reference

         */
        virtual Model::InferSNOMEDCTOutcome InferSNOMEDCT(const Model::InferSNOMEDCTRequest& request) const;

        /**
         * A Callable wrapper for InferSNOMEDCT that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::InferSNOMEDCTOutcomeCallable InferSNOMEDCTCallable(const Model::InferSNOMEDCTRequest& request) const;

        /**
         * An Async wrapper for InferSNOMEDCT that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void InferSNOMEDCTAsync(const Model::InferSNOMEDCTRequest& request, const InferSNOMEDCTResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Gets a list of medical entity detection jobs that you have
         * submitted.

See Also:
   AWS
         * API Reference

         */
        virtual Model::ListEntitiesDetectionV2JobsOutcome ListEntitiesDetectionV2Jobs(const Model::ListEntitiesDetectionV2JobsRequest& request) const;

        /**
         * A Callable wrapper for ListEntitiesDetectionV2Jobs that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::ListEntitiesDetectionV2JobsOutcomeCallable ListEntitiesDetectionV2JobsCallable(const Model::ListEntitiesDetectionV2JobsRequest& request) const;

        /**
         * An Async wrapper for ListEntitiesDetectionV2Jobs that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void ListEntitiesDetectionV2JobsAsync(const Model::ListEntitiesDetectionV2JobsRequest& request, const ListEntitiesDetectionV2JobsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Gets a list of InferICD10CM jobs that you have submitted.

See
         * Also:
   AWS
         * API Reference

         */
        virtual Model::ListICD10CMInferenceJobsOutcome ListICD10CMInferenceJobs(const Model::ListICD10CMInferenceJobsRequest& request) const;

        /**
         * A Callable wrapper for ListICD10CMInferenceJobs that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::ListICD10CMInferenceJobsOutcomeCallable ListICD10CMInferenceJobsCallable(const Model::ListICD10CMInferenceJobsRequest& request) const;

        /**
         * An Async wrapper for ListICD10CMInferenceJobs that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void ListICD10CMInferenceJobsAsync(const Model::ListICD10CMInferenceJobsRequest& request, const ListICD10CMInferenceJobsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Gets a list of protected health information (PHI) detection jobs that you
         * have submitted.

See Also:
   AWS
         * API Reference

         */
        virtual Model::ListPHIDetectionJobsOutcome ListPHIDetectionJobs(const Model::ListPHIDetectionJobsRequest& request) const;

        /**
         * A Callable wrapper for ListPHIDetectionJobs that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::ListPHIDetectionJobsOutcomeCallable ListPHIDetectionJobsCallable(const Model::ListPHIDetectionJobsRequest& request) const;

        /**
         * An Async wrapper for ListPHIDetectionJobs that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void ListPHIDetectionJobsAsync(const Model::ListPHIDetectionJobsRequest& request, const ListPHIDetectionJobsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Gets a list of InferRxNorm jobs that you have submitted.

See
         * Also:
   AWS
         * API Reference

         */
        virtual Model::ListRxNormInferenceJobsOutcome ListRxNormInferenceJobs(const Model::ListRxNormInferenceJobsRequest& request) const;

        /**
         * A Callable wrapper for ListRxNormInferenceJobs that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::ListRxNormInferenceJobsOutcomeCallable ListRxNormInferenceJobsCallable(const Model::ListRxNormInferenceJobsRequest& request) const;

        /**
         * An Async wrapper for ListRxNormInferenceJobs that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void ListRxNormInferenceJobsAsync(const Model::ListRxNormInferenceJobsRequest& request, const ListRxNormInferenceJobsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
 Gets a list of InferSNOMEDCT jobs a user has submitted.

See
         * Also:
   AWS
         * API Reference

         */
        virtual Model::ListSNOMEDCTInferenceJobsOutcome ListSNOMEDCTInferenceJobs(const Model::ListSNOMEDCTInferenceJobsRequest& request) const;

        /**
         * A Callable wrapper for ListSNOMEDCTInferenceJobs that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::ListSNOMEDCTInferenceJobsOutcomeCallable ListSNOMEDCTInferenceJobsCallable(const Model::ListSNOMEDCTInferenceJobsRequest& request) const;

        /**
         * An Async wrapper for ListSNOMEDCTInferenceJobs that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void ListSNOMEDCTInferenceJobsAsync(const Model::ListSNOMEDCTInferenceJobsRequest& request, const ListSNOMEDCTInferenceJobsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Starts an asynchronous medical entity detection job for a collection of
         * documents. Use the DescribeEntitiesDetectionV2Job operation to
         * track the status of a job.

See Also:
   AWS
         * API Reference

         */
        virtual Model::StartEntitiesDetectionV2JobOutcome StartEntitiesDetectionV2Job(const Model::StartEntitiesDetectionV2JobRequest& request) const;

        /**
         * A Callable wrapper for StartEntitiesDetectionV2Job that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::StartEntitiesDetectionV2JobOutcomeCallable StartEntitiesDetectionV2JobCallable(const Model::StartEntitiesDetectionV2JobRequest& request) const;

        /**
         * An Async wrapper for StartEntitiesDetectionV2Job that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void StartEntitiesDetectionV2JobAsync(const Model::StartEntitiesDetectionV2JobRequest& request, const StartEntitiesDetectionV2JobResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Starts an asynchronous job to detect medical conditions and link them to the
         * ICD-10-CM ontology. Use the DescribeICD10CMInferenceJob operation
         * to track the status of a job.

See Also:
   AWS
         * API Reference

         */
        virtual Model::StartICD10CMInferenceJobOutcome StartICD10CMInferenceJob(const Model::StartICD10CMInferenceJobRequest& request) const;

        /**
         * A Callable wrapper for StartICD10CMInferenceJob that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::StartICD10CMInferenceJobOutcomeCallable StartICD10CMInferenceJobCallable(const Model::StartICD10CMInferenceJobRequest& request) const;

        /**
         * An Async wrapper for StartICD10CMInferenceJob that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void StartICD10CMInferenceJobAsync(const Model::StartICD10CMInferenceJobRequest& request, const StartICD10CMInferenceJobResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Starts an asynchronous job to detect protected health information (PHI). Use
         * the DescribePHIDetectionJob operation to track the status of a
         * job.

See Also:
   AWS
         * API Reference

         */
        virtual Model::StartPHIDetectionJobOutcome StartPHIDetectionJob(const Model::StartPHIDetectionJobRequest& request) const;

        /**
         * A Callable wrapper for StartPHIDetectionJob that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::StartPHIDetectionJobOutcomeCallable StartPHIDetectionJobCallable(const Model::StartPHIDetectionJobRequest& request) const;

        /**
         * An Async wrapper for StartPHIDetectionJob that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void StartPHIDetectionJobAsync(const Model::StartPHIDetectionJobRequest& request, const StartPHIDetectionJobResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Starts an asynchronous job to detect medication entities and link them to the
         * RxNorm ontology. Use the DescribeRxNormInferenceJob operation to
         * track the status of a job.

See Also:
   AWS
         * API Reference

         */
        virtual Model::StartRxNormInferenceJobOutcome StartRxNormInferenceJob(const Model::StartRxNormInferenceJobRequest& request) const;

        /**
         * A Callable wrapper for StartRxNormInferenceJob that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::StartRxNormInferenceJobOutcomeCallable StartRxNormInferenceJobCallable(const Model::StartRxNormInferenceJobRequest& request) const;

        /**
         * An Async wrapper for StartRxNormInferenceJob that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void StartRxNormInferenceJobAsync(const Model::StartRxNormInferenceJobRequest& request, const StartRxNormInferenceJobResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
 Starts an asynchronous job to detect medical concepts and link them to the
         * SNOMED-CT ontology. Use the DescribeSNOMEDCTInferenceJob operation to track the
         * status of a job.

See Also:
   AWS
         * API Reference

         */
        virtual Model::StartSNOMEDCTInferenceJobOutcome StartSNOMEDCTInferenceJob(const Model::StartSNOMEDCTInferenceJobRequest& request) const;

        /**
         * A Callable wrapper for StartSNOMEDCTInferenceJob that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::StartSNOMEDCTInferenceJobOutcomeCallable StartSNOMEDCTInferenceJobCallable(const Model::StartSNOMEDCTInferenceJobRequest& request) const;

        /**
         * An Async wrapper for StartSNOMEDCTInferenceJob that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void StartSNOMEDCTInferenceJobAsync(const Model::StartSNOMEDCTInferenceJobRequest& request, const StartSNOMEDCTInferenceJobResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Stops a medical entities detection job in progress.

See Also:

         * AWS
         * API Reference

         */
        virtual Model::StopEntitiesDetectionV2JobOutcome StopEntitiesDetectionV2Job(const Model::StopEntitiesDetectionV2JobRequest& request) const;

        /**
         * A Callable wrapper for StopEntitiesDetectionV2Job that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::StopEntitiesDetectionV2JobOutcomeCallable StopEntitiesDetectionV2JobCallable(const Model::StopEntitiesDetectionV2JobRequest& request) const;

        /**
         * An Async wrapper for StopEntitiesDetectionV2Job that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void StopEntitiesDetectionV2JobAsync(const Model::StopEntitiesDetectionV2JobRequest& request, const StopEntitiesDetectionV2JobResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Stops an InferICD10CM inference job in progress.

See Also:

         * AWS
         * API Reference

         */
        virtual Model::StopICD10CMInferenceJobOutcome StopICD10CMInferenceJob(const Model::StopICD10CMInferenceJobRequest& request) const;

        /**
         * A Callable wrapper for StopICD10CMInferenceJob that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::StopICD10CMInferenceJobOutcomeCallable StopICD10CMInferenceJobCallable(const Model::StopICD10CMInferenceJobRequest& request) const;

        /**
         * An Async wrapper for StopICD10CMInferenceJob that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void StopICD10CMInferenceJobAsync(const Model::StopICD10CMInferenceJobRequest& request, const StopICD10CMInferenceJobResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Stops a protected health information (PHI) detection job in
         * progress.

See Also:
   AWS
         * API Reference

         */
        virtual Model::StopPHIDetectionJobOutcome StopPHIDetectionJob(const Model::StopPHIDetectionJobRequest& request) const;

        /**
         * A Callable wrapper for StopPHIDetectionJob that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::StopPHIDetectionJobOutcomeCallable StopPHIDetectionJobCallable(const Model::StopPHIDetectionJobRequest& request) const;

        /**
         * An Async wrapper for StopPHIDetectionJob that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void StopPHIDetectionJobAsync(const Model::StopPHIDetectionJobRequest& request, const StopPHIDetectionJobResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
Stops an InferRxNorm inference job in progress.

See Also:
   AWS
         * API Reference

         */
        virtual Model::StopRxNormInferenceJobOutcome StopRxNormInferenceJob(const Model::StopRxNormInferenceJobRequest& request) const;

        /**
         * A Callable wrapper for StopRxNormInferenceJob that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::StopRxNormInferenceJobOutcomeCallable StopRxNormInferenceJobCallable(const Model::StopRxNormInferenceJobRequest& request) const;

        /**
         * An Async wrapper for StopRxNormInferenceJob that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void StopRxNormInferenceJobAsync(const Model::StopRxNormInferenceJobRequest& request, const StopRxNormInferenceJobResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

        /**
         *
 Stops an InferSNOMEDCT inference job in progress.

See Also:

         * AWS
         * API Reference

         */
        virtual Model::StopSNOMEDCTInferenceJobOutcome StopSNOMEDCTInferenceJob(const Model::StopSNOMEDCTInferenceJobRequest& request) const;

        /**
         * A Callable wrapper for StopSNOMEDCTInferenceJob that returns a future to the operation so that it can be executed in parallel to other requests.
         */
        virtual Model::StopSNOMEDCTInferenceJobOutcomeCallable StopSNOMEDCTInferenceJobCallable(const Model::StopSNOMEDCTInferenceJobRequest& request) const;

        /**
         * An Async wrapper for StopSNOMEDCTInferenceJob that queues the request into a thread executor and triggers associated callback when operation has finished.
         */
        virtual void StopSNOMEDCTInferenceJobAsync(const Model::StopSNOMEDCTInferenceJobRequest& request, const StopSNOMEDCTInferenceJobResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;

      void OverrideEndpoint(const Aws::String& endpoint);
      std::shared_ptr<ComprehendMedicalEndpointProviderBase>& accessEndpointProvider();
    private:
      void init(const ComprehendMedicalClientConfiguration& clientConfiguration);

      ComprehendMedicalClientConfiguration m_clientConfiguration;
      std::shared_ptr<Aws::Utils::Threading::Executor> m_executor;
      std::shared_ptr<ComprehendMedicalEndpointProviderBase> m_endpointProvider;
  };

} // namespace ComprehendMedical
} // namespace Aws


text:
package com.vise.baseble.exception;

import android.bluetooth.BluetoothGatt;

import com.vise.baseble.common.BleExceptionCode;

/**
 * @Description: 连接异常
 * @author: DAWI
 * @date: 16/8/14 10:29.
 */
public class ConnectException extends BleException {
    private BluetoothGatt bluetoothGatt;
    private int gattStatus;

    public ConnectException(BluetoothGatt bluetoothGatt, int gattStatus) {
        super(BleExceptionCode.CONNECT_ERR, "Connect Exception Occurred! ");
        this.bluetoothGatt = bluetoothGatt;
        this.gattStatus = gattStatus;
    }

    public int getGattStatus() {
        return gattStatus;
    }

    public ConnectException setGattStatus(int gattStatus) {
        this.gattStatus = gattStatus;
        return this;
    }

    public BluetoothGatt getBluetoothGatt() {
        return bluetoothGatt;
    }

    public ConnectException setBluetoothGatt(BluetoothGatt bluetoothGatt) {
        this.bluetoothGatt = bluetoothGatt;
        return this;
    }

    @Override
    public String toString() {
        return "ConnectException{" +
                "gattStatus=" + gattStatus +
                ", bluetoothGatt=" + bluetoothGatt +
                "} " + super.toString();
    }
}

redpajama_set_name: RedPajamaGithub


text:
var Survey = React.createClass({ displayName: 'Survey',

    getInitialState: function() {
        return {page: null, selectValue1: "", selectValue2: "", yes1: 0, no1: 0, yes2: 0, no2: 0, store: 'data/survey_responses.json.data', iter: this.props.iter}
    },

    handleNextPage: function(e) {
        e.preventDefault()
        console.log("Submit state: ",this.state)
        var y1 = this.state.yes1
        var n1 = this.state.no1
        var y2 = this.state.yes2
        var n2 = this.state.no2
        var it = this.state.iter
        var store = this.state.store
        var da

        $.ajax({
            type: "GET",
            url: store,
            dataType : 'json',
            error: function(xhr, status, err) {
                console.error(store, status, err.toString())
            }.bind(this)
        }).done(function(data){
                da = data
                console.log("(GET) data[", it, "]: ", da)
                da[it].q1yes = da[it].q1yes + y1
                da[it].q1no = da[it].q1no + n1
                da[it].q2yes = da[it].q2yes + y2
                da[it].q2no = da[it].q2no + n2
                $.ajax({
                    type: "POST",
                    url: store,
                    dataType: 'json',
                    data: da[it],
                    error: function(xhr, status, err) {
                        console.error(store, status, err.toString())
                    }.bind(this)
                }).done(
                    function(){
                        console.log("(POST) data to post is:", da[it])
                        console.log("Iteration: ", this.state.iter)
                        it++
                        this.setState({iter: it})
                        console.log("State after submit: ", this.state)
                        console.log("\nHandling Next Page\n")
                        this.props.handleNextPage()
                    }.bind(this)
                )
            }.bind(this)
        );

    },

    handleChange1: function(e){
        console.log("Question1 targetValue: ", e.target.value)
        this.setState({selectValue1:e.target.value})
        if (e.target.value == "Yes"){
            this.setState({yes1: 1})
            this.setState({no1: 0})
        }
        else if (e.target.value == "No"){
            this.setState({yes1: 0})
            this.setState({no1: 1})
        }
        else{
            this.setState({yes1: 0})
            this.setState({no1: 0})
        }
    },

    handleChange2: function(e){
        console.log("Question2 targetValue: ", e.target.value)
        this.setState({selectValue2:e.target.value})
        if (e.target.value == "Yes"){
            this.setState({yes2: 1})
            this.setState({no2: 0})
        }
        else if (e.target.value == "No"){
            this.setState({yes2: 0})
            this.setState({no2: 1})
        }
        else{
            this.setState({yes2: 0})
            this.setState({no2: 0})
        }
    },

    handleSubmit: function(e){
    },

    render: function(){
        return (

Is there any cyberaggressive behavior in the online posts? Mark yes if there is at least one negative word/comment and or content with intent to harm someone or others.

                        <select value={this.state.selectValue1}  onChange={this.handleChange1}>
                            <option value="Yes">Yes</option>
                            <option value="No">No</option>
                            <option value=""></option>
                        </select>

Is there any cyerbullying in the online post? Mark yes if there are negative words and or comment with intent to harm someone or other, and the posts include two or more repeated negativity against a victim that cannot easily defend him or herself

                        <select value={this.state.selectValue2} onChange={this.handleChange2}>
                            <option value="Yes">Yes</option>
                            <option value="No">No</option>
                            <option value=""></option>
                        </select>

                    <form className='nextButton' onSubmit={this.handleSubmit} onSubmit={this.handleNextPage}>
                    <input type='submit' value='Next'/>
                    </form>

        )
    }

})


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataExplorer.Application.Core.Queries;
using DataExplorer.Application.Layouts.Base.Queries;
using DataExplorer.Application.Views;
using DataExplorer.Domain.Layouts;

namespace DataExplorer.Application.Layouts.Color.Queries
{
    public class GetColorSortOrderQueryHandler
        : BaseGetLayoutSortOrderQueryHandler,
        IQueryHandler<GetColorSortOrderQuery, SortOrder>
    {
        public GetColorSortOrderQueryHandler(IViewRepository repository)
            : base(repository)
        {
        }

        public SortOrder Execute(GetColorSortOrderQuery query)
        {
            return base.Execute(p => p.ColorSortOrder);
        }
    }
}


text:
using System;
using System.Collections.Generic;

namespace Spect.Net.Assembler.SyntaxTree
{
    /// <summary>
    /// This class represents a single line of Z80 assembly in the syntax tree
    /// </summary>
    public abstract class SourceLineBase
    {
        private const string TASK_INDICATOR = "todo";

        /// <summary>
        /// The index of the source file this line belongs to
        /// </summary>
        public int FileIndex;

        /// <summary>
        /// The source line number
        /// </summary>
        public int SourceLine;

        /// <summary>
        /// The first column within a source code line
        /// </summary>
        public int FirstColumn;

        /// <summary>
        /// The first position within a source code
        /// </summary>
        public int FirstPosition;

        /// <summary>
        /// The last position within a source code
        /// </summary>
        public int LastPosition;

        /// <summary>
        /// Exception detected by the parser
        /// </summary>
        public Exception ParserException;

        /// <summary>
        /// The optional label
        /// </summary>
        public string Label;

        /// <summary>
        /// Indicates if the label had a colon
        /// </summary>
        public bool LabelColon;

        /// <summary>
        /// Label span information
        /// </summary>
        public TextSpan LabelSpan;

        /// <summary>
        /// Assembly keyword/pragma/directive span information
        /// </summary>
        public TextSpan KeywordSpan;

        /// <summary>
        /// Number spans
        /// </summary>
        public List<TextSpan> NumberSpans;

        /// <summary>
        /// String spans
        /// </summary>
        public List<TextSpan> StringSpans;

        /// <summary>
        /// Identifier spans
        /// </summary>
        public List<TextSpan> IdentifierSpans;

        /// <summary>
        /// Function spans
        /// </summary>
        public List<TextSpan> FunctionSpans;

        /// <summary>
        /// Macro parameters in the source line
        /// </summary>
        public List<TextSpan> MacroParamSpans;

        /// <summary>
        /// Macro parameter names in the source line
        /// </summary>
        public List<string> MacroParamNames;

        /// <summary>
        /// Semi-variables spans
        /// </summary>
        public List<TextSpan> SemiVarSpans;

        /// <summary>
        /// Statement spans
        /// </summary>
        public List<TextSpan> StatementSpans;

        /// <summary>
        /// Operand spans
        /// </summary>
        public List<TextSpan> OperandSpans;

        /// <summary>
        /// Mnemonic spans
        /// </summary>
        public List<TextSpan> MnemonicSpans;

        /// <summary>
        /// Comment information
        /// </summary>
        public string Comment;

        /// <summary>
        /// Comment span information
        /// </summary>
        public TextSpan CommentSpan;

        /// <summary>
        /// The Z80 assembly instruction span
        /// </summary>
        public TextSpan InstructionSpan;

        /// <summary>
        /// Source text of the entire line
        /// </summary>
        public string SourceText;

        /// <summary>
        /// The source text of the macro line
        /// </summary>
        /// <remarks>
        /// Contains value only when the line has a macro parameter
        /// </remarks>
        public string MacroSourceText;

        /// <summary>
        /// Set this value to an error code to emit that issue
        /// </summary>
        public string IssueToEmit;

        /// <summary>
        /// Gets a value indicating whether this line creates a task.
        /// </summary>
        public bool DefinesTask => Comment != null
            && Comment.IndexOf(TASK_INDICATOR, StringComparison.InvariantCultureIgnoreCase) >= 0;

        /// <summary>
        /// Gets the Description for a line that defines a task, or null if no tas is defined
        /// </summary>
        public string TaskDescription => !DefinesTask
            ? null
            : Comment.Substring(Comment.IndexOf(TASK_INDICATOR, StringComparison.InvariantCultureIgnoreCase));
    }
}


text:
google_maps_iframe.dart
============

A wrapper for Google Maps JS API inside a iframe. Outside of an iframe the Google Maps component is not stable when working with CSS 3D transformations and animations.

##Example

```dart

import 'dart:html';
import 'dart:async';

import 'package:google_maps_iframe/google_maps_iframe.dart';

main() {

  Element elem = new Element.div() ;
  elem.text = 'Google Map:';

  Element cont = querySelector('#cont') ;

  GMapIframe gmap = new GMapIframe(cont) ;

  new Future.delayed(new Duration(seconds: 3) , () {
    gmap.setCenter( new GMapLatLong(-27.5928287 , -48.5195031)) ;
    gmap.setZoom(12) ;

    gmap.addMarker( new GMapLatLong(-27.5928287 , -48.5195031) , 'Florianopolis' ) ;
  }) ;

  new Future.delayed(new Duration(seconds: 5) , () {
      gmap.setMapType(GMapIframe.MAP_TYPE_TERRAIN) ;
  }) ;

}

```

TODO
----

* More examples of usage.

CHANGELOG
---------

  * version: 0.1.1:
  Fix load of iframe code.

  * version: 0.1.0:
  First version


text:
package com.intellij.ui;

import com.intellij.openapi.extensions.ExtensionPointName;
import org.intellij.lang.annotations.JdkConstants;
import org.jetbrains.annotations.NotNull;

import java.awt.*;

interface SuitableFontProvider {
  ExtensionPointName<SuitableFontProvider> EP_NAME = ExtensionPointName.create("com.intellij.ui.suitableFontProvider");

  Font getFontAbleToDisplay(char c, int size, @JdkConstants.FontStyle int style, @NotNull String defaultFontFamily);
}


text:
package org.elasticsearch.xpack.eql.execution.search;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.xpack.eql.execution.payload.ReversePayload;
import org.elasticsearch.xpack.eql.session.Payload;

public class ReverseListener extends ActionListener.Delegating<Payload, Payload> {

    public ReverseListener(ActionListener<Payload> delegate) {
        super(delegate);
    }

    @Override
    public void onResponse(Payload response) {
        delegate.onResponse(new ReversePayload(response));
    }
}


text:
This application provides a simple mechanism for supervising `gen_event` event
handlers, packaged as an OTP library for convenient reuse.

## Rationale

OTP's `gen_event` mechanism is different from the other OTP behaviours, because
the (user) callback module does not represent (i.e, is not run in) its own,
separate process. Using the standard OTP `gen_event` mechanism, an event hander
callback module that crashes will be silently removed from its event manager.
Because the event handler is not a process, it is not therefore possible to have
the handler participate in a supervision tree. To compensate for this apparent
lack, the `gen_event` module exports an `add_sup_handler/3` method which offers
the calling process a contract which promises notification of exit/error signals
in the callback module, delivered to its message queue.

This library takes advantage of this *supervision* mechanism, wrapping up all the
details and providing a pre-packaged supervision tree for event managers and
handlers, with a simple API and configuration system for managing all the above.

## License

The `gen_event_registrar` package is licensed under a permissive, BSD-like
license, which allows for combined with other works under different (sub) license
conditions.

## Releases

This project will use [semantic versioning](http://www.semver.org), and all major
releases will be made available as binary packages via github downloads and via
the [nebularis-maven-repository](https://github.com/nebularis/maven-repo).


text:
<?php

namespace Game;

class Game {
    // Game class bootstrap
}


text:
set -ex

# change to grpc repo root
cd $(dirname $0)/../../..

source tools/internal_ci/helper_scripts/prepare_build_linux_rc

export DOCKERFILE_DIR=tools/dockerfile/test/bazel
export DOCKER_RUN_SCRIPT=$BAZEL_SCRIPT
export OUTPUT_DIR=reports
exec tools/run_tests/dockerize/build_and_run_docker.sh


text:
layout: post
title: 为什么某些BlueprintNode的Target可以连接多个对象?
date: 2019-07-14
category: notes
tags: [unreal4,c++]
---

### Description
允许多个Link

不允许多个Link

### Cause
查看两个UFUNCTION的specifier
``` c++
// Allow multple links to Target
UFUNCTION(BlueprintCallable, Category=Character)
       virtual void Jump();

// Unallow
UFUNCTION(BlueprintCallable, meta=(ScriptNoExport, BlueprintInternalUseOnly = "true", DefaultToSelf="ComponentTemplateContext", InternalUseParam="ComponentTemplateContext"))
       class UActorComponent* AddComponent(FName TemplateName, bool bManualAttachment, const FTransform& RelativeTransform, const UObject* ComponentTemplateContext);
```
看上去没有什么和Pin直接有关系的,只不过蓝图中是`AddCameraComponent`,而源代码则指向了一个通用的`AddComponent`,也就是说,蓝图中的这个函数结点是根据通用函数生成出来的,并没有实际的函数对应。

于是顺着结点生成的相关代码找去,通过Debugger捕捉Link和Unlink的行为,终于发现和下面这个函数有关,大家重点关注bMultipleSelfException的赋值:
``` c++
const FPinConnectionResponse UEdGraphSchema_K2::DetermineConnectionResponseOfCompatibleTypedPins(const UEdGraphPin* PinA, const UEdGraphPin* PinB, const UEdGraphPin* InputPin, const UEdGraphPin* OutputPin) const
{
	// Now check to see if there are already connections and this is an 'exclusive' connection
	const bool bBreakExistingDueToExecOutput = IsExecPin(*OutputPin) && (OutputPin->LinkedTo.Num() > 0);
	const bool bBreakExistingDueToDataInput = !IsExecPin(*InputPin) && (InputPin->LinkedTo.Num() > 0);

	bool bMultipleSelfException = false;
	const UK2Node* OwningNode = Cast<UK2Node>(InputPin->GetOwningNode());
	if (bBreakExistingDueToDataInput &&
		IsSelfPin(*InputPin) &&
		OwningNode &&
		OwningNode->AllowMultipleSelfs(false) &&
		!InputPin->PinType.IsContainer() &&
		!OutputPin->PinType.IsContainer() )
	{
		//check if the node wont be expanded as foreach call, if there is a link to an array
		bool bAnyContainerInput = false;
		for(int InputLinkIndex = 0; InputLinkIndex < InputPin->LinkedTo.Num(); InputLinkIndex++)
		{
			if(const UEdGraphPin* Pin = InputPin->LinkedTo[InputLinkIndex])
			{
				if(Pin->PinType.IsContainer())
				{
					bAnyContainerInput = true;
					break;
				}
			}
		}
		bMultipleSelfException = !bAnyContainerInput;
	}

	if (bBreakExistingDueToExecOutput)
	{
		const ECanCreateConnectionResponse ReplyBreakOutputs = (PinA == OutputPin) ? CONNECT_RESPONSE_BREAK_OTHERS_A : CONNECT_RESPONSE_BREAK_OTHERS_B;
		return FPinConnectionResponse(ReplyBreakOutputs, TEXT("Replace existing output connections"));
	}
	else if (bBreakExistingDueToDataInput && !bMultipleSelfException)
	{
		const ECanCreateConnectionResponse ReplyBreakInputs = (PinA == InputPin) ? CONNECT_RESPONSE_BREAK_OTHERS_A : CONNECT_RESPONSE_BREAK_OTHERS_B;
		return FPinConnectionResponse(ReplyBreakInputs, TEXT("Replace existing input connections"));
	}
	else
	{
		return FPinConnectionResponse(CONNECT_RESPONSE_MAKE, TEXT(""));
	}
}
```
看来只有Target(也就是CPP函数的this)的Pin可以连接,并且使用的函数结点其`AllowMultipleSelfs()`也要返回True,至于其他条件代码写的很明白就不说了。

不同的结点类型,允许连接多个对象的条件不同,譬如`UK2Node_CallFunction`这个类型就会以函数是否有返回值作为标准,如下:
``` C++
bool UK2Node_CallFunction::AllowMultipleSelfs(bool bInputAsArray) const
{
	if (UFunction* Function = GetTargetFunction())
	{
		return CanFunctionSupportMultipleTargets(Function);
	}

	return Super::AllowMultipleSelfs(bInputAsArray);
}

bool UK2Node_CallFunction::CanFunctionSupportMultipleTargets(UFunction const* Function)
{
	bool const bIsImpure = !Function->HasAnyFunctionFlags(FUNC_BlueprintPure);
	bool const bIsLatent = Function->HasMetaData(FBlueprintMetadata::MD_Latent);
	bool const bHasReturnParam = (Function->GetReturnProperty() != nullptr);

	return !bHasReturnParam && bIsImpure && !bIsLatent;
}
```


text:
namespace Osmosis {
namespace Client
{

DelayedLabels::DelayedLabels( const std::string & label )
{
	if ( label == "+" )
		return;
	fromLabel( label );
}

const std::vector< std::string > & DelayedLabels::labels()
{
	ASSERT( _labels.size() > 0 );
	return _labels;
}

void DelayedLabels::fetch()
{
	BACKTRACE_BEGIN
	if ( _labels.size() > 0 )
		return;
	TRACE_INFO( "Enter label name on next line:" );
	std::string line;
	std::getline( std::cin, line );
	if ( line.size() <= 0 )
		THROW( Error, "Invalid label from stdin: '" << line << "'" );
	TRACE_INFO( "Got label name: '" << line << "'" );
	fromLabel( line );
	BACKTRACE_END
}

void DelayedLabels::fromLabel( const std::string & label )
{
	boost::split( _labels, label, boost::is_any_of( "+" ) );
}

} // namespace Client
} // namespace Osmosis


text:
using System.Windows;
using Microsoft.Extensions.DependencyInjection;
using VkNet.Enums.Filters;
using VkNet.Model;
using VkNet.Model.RequestParams;
using VkNet.Shared;
using VkNet.Utils;

namespace VkNet.Wpf
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow
	{
		private VkApi _api;

		public MainWindow()
		{
			InitializeComponent();
		}

		private void Window_Initialized(object sender, System.EventArgs e)
		{
			_api = Api.GetInstance(InitDi());

			if (_api.IsAuthorized)
			{
				return;
			}

			_api.Authorize(new ApiAuthParams
			{
				ApplicationId = 4268118,
				Settings = Settings.All
			});
		}

		private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
		{
			var tmp = _api.Groups.Get(new GroupsGetParams());
			MessageBox.Show(tmp.TotalCount.ToString());
		}

		private static ServiceCollection InitDi()
		{
			var di = new ServiceCollection();

			di.AddSingleton<IBrowser, WpfAuthorize>();

			return di;
		}
	}
}


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

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!--扫描@Controller-->
    <context:component-scan base-package="com.wind">
        <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--定义spring 视图解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
        <property name="mediaTypes">
            <value>
                json=application/json
                xml=application/xml
            </value>
        </property>
    </bean>

    <!--自动扫描spring mvc注解-->
    <mvc:annotation-driven/>

    <!-- 容器默认的DefaultServletHandler处理 所有静态内容与无RequestMapping处理的URL-->
    <mvc:default-servlet-handler/>

    <mvc:view-controller path="/" view-name="index"/>
    <mvc:view-controller path="/WEB-INF/jsp" view-name="index"/>

</beans>


text:
export WRAPPER="`readlink -f "$0"`"
HERE="`dirname "$WRAPPER"`"
. $HERE/../config.sh
. $HERE/../colors.sh

which apt-get > /dev/null && {
	echo apt-get install -y wget >> $LOG_FILE
	apt-get install -y wget &> $LOG_FILE || {
		echo_error "Failed installing wget: apt-get install -y wget. Please check log ..."
		exit 1
	}
}

which update-java-alternatives > dev/null || update-java-alternatives -l | grep 7-oracle > /dev/null || {
	echo_warn "Idea requires Oracle Java 7 or higher. Installing Oracle Java 7.".
	echo_warn "To install version 8 or higher, please alter the script's content... "
	echo_warn "(please press any key to continue, Ctrl+C to quit)"
	read x
	. $HERE/../java.sh oracle java7
}

echo_info "Installing Idea ...";
if [ "x1" == "x`ls -la /opt | grep idea | wc -l`" ]; then
	echo_warn "Idea already exists. Upgrading... (please press any key to continue, Ctrl+C to quit)";
	read x;
fi

url=`wget https://www.jetbrains.com/idea/download/download_thanks.jsp?os=linux -q -O - | grep HTTP | grep href | grep tar.gz | sed "s/<a/\n/g" | tail -n 2 | head -n 1 | awk -F '"' '{print $2}'`;
[ "$1" == "com" ] && {
	url=`echo $url | sed "s/IU/IC/g"`;
}
echo_info "Downloading $url to /opt ...";
wget "$url" -O /opt/idea.tar.gz;
cd /opt && rm -rf Idea* && tar -xzf idea.tar.gz;

echo_info "Creating symlinks ...";
rm -rf /usr/bin/idea && ln -s /opt/idea*/bin/idea.sh /usr/bin/idea || {
	echo_error "Could not create symlinks!";
}

echo_info "Done.";


text:
<component name="libraryTable">
  <library name="CityPickerWebView-0.1.0">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.github.open-android/CityPickerWebView/0.1.0/jars/classes.jar!/" />
      <root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.github.open-android/CityPickerWebView/0.1.0/res" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
<?php

namespace deduar\S3SandBoxBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class DefaultController extends Controller
{
    /**
     * @Route("/")
     */
    public function indexAction()
    {
        return $this->render('S3SandBoxBundle:Default:index.html.twig');
    }
}


text:
"use strict";

const { expect } = require("chai");
const SwaggerParser = require("../../..");
const helper = require("../../utils/helper");
const path = require("../../utils/path");
const parsedAPI = require("./parsed");
const dereferencedAPI = require("./dereferenced");
const bundledAPI = require("./bundled");

describe("Object sources (instead of file paths)", () => {
  it("should dereference an object that references external files", async () => {
    let parser = new SwaggerParser();
    const api = await parser.dereference(helper.cloneDeep(parsedAPI.api));
    expect(api).to.equal(parser.api);
    expect(api).to.deep.equal(dereferencedAPI);
    // The API path should be the current directory, and all other paths should be absolute
    let expectedPaths = [
      path.cwd(),
      path.abs("specs/object-source/definitions/definitions.json"),
      path.abs("specs/object-source/definitions/name.yaml"),
      path.abs("specs/object-source/definitions/required-string.yaml")
    ];
    expect(parser.$refs.paths()).to.have.same.members(expectedPaths);
    expect(parser.$refs.values()).to.have.keys(expectedPaths);
    // Reference equality
    expect(api.paths["/people/{name}"].get.responses["200"].schema)
      .to.equal(api.definitions.name);
    expect(api.definitions.requiredString)
      .to.equal(api.definitions.name.properties.first)
      .to.equal(api.definitions.name.properties.last)
      .to.equal(api.paths["/people/{name}"].get.responses["200"].schema.properties.first)
      .to.equal(api.paths["/people/{name}"].get.responses["200"].schema.properties.last);
  });

  it("should bundle an object that references external files", async () => {
    let parser = new SwaggerParser();
    const api = await parser.bundle(helper.cloneDeep(parsedAPI.api));
    expect(api).to.equal(parser.api);
    expect(api).to.deep.equal(bundledAPI);
    // The API path should be the current directory, and all other paths should be absolute
    let expectedPaths = [
      path.cwd(),
      path.abs("specs/object-source/definitions/definitions.json"),
      path.abs("specs/object-source/definitions/name.yaml"),
      path.abs("specs/object-source/definitions/required-string.yaml")
    ];
    expect(parser.$refs.paths()).to.have.same.members(expectedPaths);
    expect(parser.$refs.values()).to.have.keys(expectedPaths);
  });

  it("should validate an object that references external files", async () => {
    let parser = new SwaggerParser();
    const api = await parser.dereference(helper.cloneDeep(parsedAPI.api));
    expect(api).to.equal(parser.api);
    expect(api).to.deep.equal(dereferencedAPI);
    // The API path should be the current directory, and all other paths should be absolute
    let expectedPaths = [
      path.cwd(),
      path.abs("specs/object-source/definitions/definitions.json"),
      path.abs("specs/object-source/definitions/name.yaml"),
      path.abs("specs/object-source/definitions/required-string.yaml")
    ];
    expect(parser.$refs.paths()).to.have.same.members(expectedPaths);
    expect(parser.$refs.values()).to.have.keys(expectedPaths);
    // Reference equality
    expect(api.paths["/people/{name}"].get.responses["200"].schema)
      .to.equal(api.definitions.name);
    expect(api.definitions.requiredString)
      .to.equal(api.definitions.name.properties.first)
      .to.equal(api.definitions.name.properties.last)
      .to.equal(api.paths["/people/{name}"].get.responses["200"].schema.properties.first)
      .to.equal(api.paths["/people/{name}"].get.responses["200"].schema.properties.last);
  });
});


text:
function addTaskFromOverlay () {
  tasks.setSelected(tasks.add())
  taskOverlay.hide()

  rerenderTabstrip()
  addTab()
}

function removeTabFromOverlay (tabId, task) {
  task.tabs.destroy(tabId)
  destroyWebview(tabId)

  rerenderTabstrip()

  // if there are no tabs left, remove the task
  if (task.tabs.count() === 0) {
    destroyTask(task.id)
    if (tasks.get().length === 0) {
      addTaskFromOverlay()
    } else {
      // re-render the overlay to remove the task element
      getTaskContainer(task.id).remove()
    }
  }
}

var TaskOverlayBuilder = {
  create: {
    task: {
      nameInputField: function (task, taskIndex) {
        var input = document.createElement('input')
        input.classList.add('task-name')

        input.placeholder = 'Task ' + (taskIndex + 1)
        input.value = task.name || 'Task ' + (taskIndex + 1)

        input.addEventListener('keyup', function (e) {
          if (e.keyCode === 13) {
            this.blur()
          }
          tasks.update(task.id, {name: this.value})
        })

        input.addEventListener('focus', function () {
          this.select()
        })
        return input
      },

      deleteButton: function (container, task) {
        var deleteButton = document.createElement('i')
        deleteButton.className = 'fa fa-trash-o'

        deleteButton.addEventListener('click', function (e) {
          destroyTask(task.id)
          container.remove()

          if (tasks.get().length === 0) { // create a new task
            addTaskFromOverlay()
          }
        })
        return deleteButton
      },

      actionContainer: function (taskContainer, task, taskIndex) {
        var taskActionContainer = document.createElement('div')
        taskActionContainer.className = 'task-action-container'

        // add the input for the task name
        var input = this.nameInputField(task, taskIndex)
        taskActionContainer.appendChild(input)

        // add the delete button
        var deleteButton = this.deleteButton(taskContainer, task)
        taskActionContainer.appendChild(deleteButton)

        return taskActionContainer
      },
      container: function (task, taskIndex) {
        var container = document.createElement('div')
        container.className = 'task-container'
        container.setAttribute('data-task', task.id)

        var taskActionContainer = this.actionContainer(container, task, taskIndex)
        container.appendChild(taskActionContainer)

        var tabContainer = TaskOverlayBuilder.create.tab.container(task)
        container.appendChild(tabContainer)

        return container
      }
    },

    tab: {
      element: function (tabContainer, task, tab) {
        var el = createSearchbarItem({
          title: tab.title || 'New Tab',
          secondaryText: urlParser.removeProtocol(tab.url),
          classList: ['task-tab-item'],
          delete: function () {
            removeTabFromOverlay(tab.id, task)
          }
        })

        el.setAttribute('data-tab', tab.id)
        el.setAttribute('data-task', task.id)

        el.addEventListener('click', function (e) {
          switchToTask(this.getAttribute('data-task'))
          switchToTab(this.getAttribute('data-tab'))

          taskOverlay.hide()
        })

        var closeTabButton = this.closeButton(el)
        el.querySelector('.title').appendChild(closeTabButton)
        return el
      },

      container: function (task) {
        var tabContainer = document.createElement('div')
        tabContainer.className = 'task-tabs-container'

        if (task.tabs) {
          for (var i = 0; i < task.tabs.length; i++) {
            var el = this.element(tabContainer, task, task.tabs[i])
            tabContainer.appendChild(el)
          }
        }

        return tabContainer
      },

      closeButton: function (taskTabElement) {
        var closeTabButton = document.createElement('button')
        closeTabButton.innerHTML = '<i class="fa fa-close"/>'
        closeTabButton.className = 'closeTab'

        closeTabButton.addEventListener('click', function (e) {
          var tabId = taskTabElement.getAttribute('data-tab')
          var taskId = taskTabElement.getAttribute('data-task')

          removeTabFromOverlay(tabId, tasks.get(taskId))
          taskTabElement.parentNode.removeChild(taskTabElement)

          // do not close taskOverlay
          // (the close button is part of the tab-element, so a click on it
          // would otherwise trigger opening this tab, and it was just closed)
          e.stopImmediatePropagation()
        })

        return closeTabButton
      }
    }

  }
  // extend with other helper functions?
}

window.task_container_build_func = TaskOverlayBuilder.create.task.container.bind(TaskOverlayBuilder.create.task)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NLua;

namespace Watertight.Simulation
{
    class EntityComponentDictionary
    {

        static Dictionary<string, LuaTable> ComponentDictionary = new Dictionary<string, LuaTable>();

        static Dictionary<string, Type> EngineComponents = new Dictionary<string, Type>()
        {
            {"Transform", typeof(TransformComponent)},
            {"Renderer", typeof(RenderComponent)},
            {"Camera", typeof(CameraComponent)},
        };

        [BindFunction("_G", "RegisterComponent")]
        public static void RegisterComponent(string Name, LuaTable tab)
        {

            Util.Msg("Registring Component " + Name);

            if(ComponentDictionary.ContainsKey(Name))
            {
                Util.Msg("Warning: Lua Component " + Name + " Already registered! Skipping");
                return;
            }

            ComponentDictionary[Name] = tab;
        }

        public static EntityComponent NewComponent(string Name)
        {
            if(EngineComponents.ContainsKey(Name))
            {
                return NewEngineComponent(Name);
            }
            if (!ComponentDictionary.ContainsKey(Name))
            {
                Util.Msg("Warning: Component named " + Name + " was not registered");
                return null;
            }

            var tab = ComponentDictionary[Name];

            var newobj = LuaHelper.LuaVM.GetFunction("Instantiate").Call(tab)[0] as LuaTable;

            return new LuaComponent(newobj);

        }

        private static EntityComponent NewEngineComponent(string name)
        {
            var type = EngineComponents[name];

            return type.GetConstructor(Type.EmptyTypes).Invoke(new object[] { }) as EntityComponent;

        }

    }
}


text:
var HOBBY_STUDY = (function () {
            var my = {};

            my.letters_to_remove = 2; // number of missituationrs to complete in the term.
            my.total_scenarios = 24;  // How many scenarios should be randomly selected out of the full set?
            my.question_type = "yes_no";  // Can be yes_no, mc1, or mc2.
            my.base_url = "/js/training";
            my.post_url = "/jspsych";
            my.status_url = "/jspsych/status";
            my.redirect_url = "/jspsych/continue";
            my.lemon = false;
            my.session = "eightSession";
            my.data = {};
            my.lastSaveIndex = 0;
            my.start = 0;

            // This score is incremented for every correct answer and displayed
            // to the user.
            var score_letters = 0;
            var score_questions = 0;
            var progress = -1;
            var vivid_response;
            var followup_count = 0;
            var completed_previously = 0;

            my.execute = function () {
                if (my.base_url.slice(-1) !== '/') my.base_url = my.base_url + "/";
                parse_data(my.base_url + "scenarios/" + my.session + ".csv", parse_complete);
            };

            function parse_data(url, callBack) {
                Papa.parse(url, {
                    download: true,
                    dynamicTyping: true,
                    header: true,
                    skipEmptyLines: true,
                    complete: function (results) {
                        callBack(results.data);
                    }
                });
            }

            function parse_complete(data) {
                my.data = data;
                load_past_progress(progress_loaded)
            }

            function load_past_progress(callback) {
                $.ajax({
                    type: 'get',
                    contentType: 'application/json',
                    cache: false,
                    url: my.status_url, // this is the path to the above PHP script
                    complete: function (results) {
                        callback(results);
                    }
                });
            }

            function progress_loaded(results) {
                data = results.responseJSON;
                // Figure out how many tasks were completed previously.  If any.
                // And reduce the number of scenerios to complete by this amount.
                for (var t in data) {
                    if (data[t].trial_type == "missing-letters") {
                        completed_previously++;
                    }
                }
                my.total_scenarios = my.total_scenarios - completed_previously;
                my.start = completed_previously;

                // Build the timeline.
                build_timeline(my.data);

                console.log("Progress fully loaded");
                updateProgress();
                updateScore();
            }

            /**
             * Randomize array element order in-place.
             * Using Durstenfeld shuffle algorithm. (taken from Stackoverflow - Laurens Holst)
             */
            function shuffleArray(array) {
                for (var i = array.length - 1; i > 0; i--) {
                    var j = Math.floor(Math.random() * (i + 1));
                    var temp = array[i];
                    array[i] = array[j];
                    array[j] = temp;
                }
            }

            // DISPLAY SCORE AND PROGRESS
            // ***************

            function updateBanner(content) {
                document.getElementById('banner').textContent = content;
            }

            function updateScore() {
                document.getElementById('score').textContent = "Score: " + (score_letters + score_questions);
            }

            function updateProgress() {
                progress++;
                document.getElementById('progress').textContent =
                    "Completed : " + progress + " of " + my.total_scenarios;
            }

            // This is called when we complete parsing the CSV file (see parseData above),
            // and will in tern build all the trials.
            function build_timeline(scenarios) {

                /***********************************************
                 * STATIC TRIALS
                 ***********************************************/
                    // An introduction / instructions
                var introduction = {
                        type: 'html-button-response',
                        choices: ['Continue'],
                        stimulus: function () {
                            return (
                                "
 " +
                                " " +
                                "
 In this study, you will see a set of short stories. All stories will start with the story's title, " +
                                "so you know what the story is about. " +
                                "The stories will be presented in different formats, some will include pictures, some will not.
 " +
                                "
 " +
                                "For each story: " +
                                "
 " +
                                "
Please imagine yourself in the situation described in each story. " +
                                "
Remember, even if the story describes you reacting in a way that you would not usually react, please " +
                                "try to picture yourself responding in the way the story describes.
 " +
                                "
There will be an incomplete word at the end of each story.
 " +
                                "
Click the letter that completes each word.
 " +
                                "
When you correctly complete the word you will move on to the next screen and be asked a " +
                                "question about the story.
 " +
                                "
 " +
                                "
"
                            )
                        },

                        on_finish: function (data) {
                            data.stimulus = "introduction"
                        }
                    };

                var lemon_exercise = {
                    type: 'instructions',
                    show_clickable_nav: true,
                    pages: ["
" +
                    '
In this task you will read or listen to a series of short stories. We will ask you to imagine yourself in the situation described in each story.
' +
                    "
Before we begin, we\'d like to walk you through a brief imagination exercise.
",
                        '
Welcome to the "Lemon" exercise.

The purpose of this quick exercise is to demonstrate what imagination-based thinking is.

You will go through what imagining seeing, touching, and smelling a lemon is like.

Please imagine it as if you are really experiencing it.
',
                        '
First-person perspective

In this exercise, and throughout the training program, please remember to imagine what is happening through your own eyes (picture on the left), not as an outside observer (picture on the right) ...
' +
                        '

',
                        '
Ok, let\'s begin:

Imagine you are holding the lemon in your right hand, and you can feel its shape and its weight.
' +
                        '
(Please take a few seconds to imagine this)
',
                        '
Now imagine you are shining a light on the lemon, and you can see the waxy and lumpy texture of the yellow skin.
' +
                        '
(Please take a few seconds to imagine this)
',
                        '
Now imagine that you scratch the skin with your fingernail, then you bring the lemon up to your nose, and you can smell the fresh zesty juice from the skin.
' +
                        '
(Please take a few seconds to imagine this)
',
                        '
Now imagine that you cut the lemon in half, and you bring one half of it up for a closer look. You can see the juicy flesh in the shape of segments that look like a wagon wheel.
' +
                        '
(Please take a few seconds to imagine this)
',
                        '
Now imagine that you squeeze the lemon and some of the juice squirts right into your eyes, and it is really stinging, making your eyes water.
' +
                        '
(Please take a few seconds to imagine this)
',
                        '
That was the lemon exercise!

Don\'t worry if you didn\'t experience all of the sensations strongly, this is completely normal.
' +
                        '
'
                    ]
                };

                var vividness = {
                    type: 'html-button-response',
                    is_html: true,
                    stimulus: 'How vividly did you imagine yourself in the scenario?',
                    choices: ['Not at all', 'Somewhat', 'Moderately', 'Very', 'Totally'],
                    on_finish: function (trial_data) {
                        vivid_response = trial_data.button_pressed > 2;
                        trial_data.stimulus = "vividness"
                    }
                };

                // The Final Score, shown at the end of the experiment.
                var final_trial_score = {
                    type: 'html-button-response',
                    is_html: true,
                    choices: ['Continue'],
                    stimulus: function () {
                        var max_score = my.total_scenarios + followup_count;
                        var pct_ct_s = Math.round((score_letters / my.total_scenarios) * 100);
                        var pct_ct_c = Math.round((score_questions / followup_count) * 100);
                        var score = score_letters + score_questions;
                        var feed_back_score = "You scored " + score + " out of a maximum possible score of " + max_score;
                        var feed_back_s = 'You filled in the missing letters correctly on the first try ' + pct_ct_s + '% of the time this round. ';
                        var feed_back_c = 'You answered the yes/no question following each story correctly on the first try ' + pct_ct_c + '% of the time this round. ';

                        if (pct_ct_s >= 90) feed_back_s +=
                            'Great job, we're really impressed with your ability to complete the stories! ';
                        if (pct_ct_s < 90 && pct_ct_s >= 70) feed_back_s +=
                            'You're doing well, and we encourage you to pay really close attention to the ' +
                            'stories to work out what letters are needed to complete the final words. ' +
                            'This will allow you to get the most out of the training.';
                        else feed_back_s += 'We want to encourage you to pay really close attention to the ' +
                            'stories to work out what letters are needed to complete the final words. ' +
                            'This will allow you to get the most out of the training. If any aspect of' +
                            ' the task is unclear, please email us with any questions at studyteam@mindtrails.org.';
                        if (pct_ct_c >= 90)
                            feed_back_c += 'That's terrific, and shows you're paying really careful attention to the stories!';
                        else if (pct_ct_c < 90 && pct_ct_s >= 70)
                            feed_back_c += 'You're doing a good job, and we want to remind you to pay really close attention ' +
                                'to the whole story each time, including how it ends, and just use the information in the ' +
                                'story to answer the question. This will allow you to get the most out of the training.';
                        else
                            feed_back_c += 'We want to remind you to pay really close attention to the whole story ' +
                                'each time, including how it ends, and just use the information in the story to ' +
                                'answer the question. This will allow you to get the most out of the training. If' +
                                'any aspect of the task is unclear, please email us with any questions at ' +
                                'studyteam@mindtrails.org.';

                        return (
                        '
' +
                        '' +
                        '
' + feed_back_score + "
" +
                        '
' + feed_back_s + '
' +
                        '
' + feed_back_c + '
')
                    },
                    on_finish: function(data){ data.stimulus = "final score screen" }
                };

                var save_data = {
                    type: 'call-function',
                    func: function () {
                        saveData(function () {
                            jsPsych.data.aaData = []; // Clear data just sent.
                            console.log("DATA IS " + jsPsych.data.get());
                        })
                    }
                };

                /* create experiment timeline array */
                var timeline = [];
                if (my.lemon) {
                    timeline.push(lemon_exercise);
                }
                timeline.push(introduction);

                // Loop through the time-line creating scenarios
                var positive = true;
                for (var k = my.start; k < scenarios.length; k++) {
                    var scenario;
                    var paragraph;
                    var phrase;
                    var immersion;
                    var title;
                    var yes_no_correct;
                    var mcq_positive;
                    var mcq_negative;
                    var mcq_answer;
                    var format;

                    paragraph = scenarios[k]['Paragraph'];
                    scenario = scenarios[k]['Scenario'];
                    format = scenarios[k]['Format'];
                    immersion = scenarios[k]['Immersion'];
                    title = scenarios[k]['Title'];
                    positive = true;

                    if (positive) {
                        phrase = scenarios[k]['FinalWord'];
                        yes_no_correct = scenarios[k]['Correct'];
                        mcq_positive = scenarios[k]['MCQ_Positive'];
                        mcq_negative = scenarios[k]['MCQ_Negative'];
                        mcq_answer = scenarios[k]['MCQ_Answer'];
                    }

                    /***********************************************
                     * SCENARIO BASED TRIALS
                     ***********************************************/

                    var immersion_trial = null;

                    if (immersion === "picture") {
                        immersion_trial = {
                            type: 'html-button-response',
                            stimulus: "
Story: " + title + "
",
                            trial_duration: 5000, // Show trial for 5 seconds
                            data: {immersion: immersion, format: format, scenario: scenario}
                        }
                    } else if (immersion === "picture_sound") {
                        immersion_trial = {
                            type: 'audio-button-response',
                            stimulus: 'sounds/background/' + scenario + '.mp3',
                            trial_duration: 5000, // Show trial for 5 seconds
                            prompt: "
Story: " + title + "
",
                            data: {immersion: immersion, format: format, scenario: scenario}
                        }
                    } else {
                        immersion_trial = {
                            type: 'html-button-response',
                            stimulus: "
Story: " + title + "
",
                            trial_duration: 5000,
                            data: {immersion: immersion, format: format, scenario: scenario}
                        }
                    }

                    var main_trial = null;

                    if (format === "Auditory") {
                        main_trial = {
                            type: 'audio-button-response',
                            stimulus: my.base_url + 'sounds/' + scenario + '.mp3',
                            trial_ends_after_audio: true,
                            prompt: '
Please listen ...
',
                            data: {immersion: immersion, format: format, scenario: scenario}
                        };
                    } else {
                        main_trial = {
                            type: 'sentence-reveal',
                            paragraph: paragraph,
                            data: {immersion: immersion, format: format, scenario: scenario}
                        };
                    }

                    var phrase_trial = {
                        type: 'missing-letters',
                        phrase: phrase,
                        letters_to_remove: my.letters_to_remove,
                        data: {immersion: immersion, format: format, scenario: scenario},
                        on_finish: function (trial_data) {
                            if (trial_data.correct) score_letters++;
                            updateScore();
                            updateProgress();
                        }
                    };

                    var mcq = {
                        type: 'button-response-correct',
                        is_html: true,
                        stimulus: scenarios[k]['Questions'],
                        choices: [scenarios[k]['MCQ_Positive'], scenarios[k]['MCQ_Negative']],
                        correct_choice: mcq_answer == "Positive" ? scenarios[k]['MCQ_Positive'] : scenarios[k]['MCQ_Negative'],
                        on_finish: function (trial_data) {
                            if (trial_data.correct) score_questions++;
                            updateScore();
                        }
                    };

                    var yes_no = {
                        type: 'button-response-correct',
                        is_html: true,
                        stimulus: scenarios[k]['Questions'],
                        choices: ["Yes", "No"],
                        correct_choice: yes_no_correct,
                        on_finish: function (trial_data) {
                            if (trial_data.correct) score_questions++;
                            updateScore();
                        }
                    };

                    // Vivid Follow up - changes based on response.
                    var stimulus;
                    switch (k) {
                        case 5:
                            stimulus = "
Well done.
" +
                                "
Remember, imagine the scenario as if you are experiencing it through your own eyes.
";
                            break;
                        case 10:
                            stimulus = "
Nice Work.
" +
                                "
Take time to visualize each situation.
";
                            break;
                        case 15:
                            stimulus = "
Good job.
" +
                                "
Remember, try to imagine the stories as vividly as you can.
";
                            break;
                        case 20:
                            stimulus = "
You're doing great.
" +
                                "
Keep focusing on the stories and imagine them from your own eyes.
"
                            break;
                        default:
                            stimulus = "
Almost there.
" +
                                "
Keep imagining as vividly as you can.
"
                            break;
                    }
                    var vividness_followup = {
                        type: 'html-button-response',
                        choices: ['Continue'],
                        stimulus: "
" +
                        stimulus +
                        "" +
                        "
"
                    };

                    // BUILD THE TIMELINE FROM THE COMPONENTS ABOVE.
                    // *********************************************

                    if (k % 5 === 0 && k !== 0) {
                        timeline.push(vividness_followup)
                    }

                    timeline.push(immersion_trial);
                    timeline.push(main_trial);
                    timeline.push(phrase_trial);

                    // Only ask a followup question 2/3rd of the time.
                    if (Math.random() >= 0.333) {
                        followup_count++;
                        if  (scenarios[k]["Correct"]) {
                            timeline.push(yes_no);
                        }   else {
                            timeline.push(mcq);
                        }
                    }

                    // Save data to the server after each scenerio is completed.
                    timeline.push(save_data);

                }

                timeline.push(final_trial_score);

                function saveData(callback) {
                    var all_data = jsPsych.data.get().values();
                    var data_to_save = [];
                    var saved_from = my.lastSaveIndex;

                    for (var i = my.lastSaveIndex; i < all_data.length; i++) {
                        data_to_save.push(all_data[i]);
                    }
                    my.lastSaveIndex = all_data.length;

                    $.ajax({
                        type: 'post',
                        contentType: 'application/json',
                        cache: false,
                        url: my.post_url, // this is the path to the above PHP script
                        data: JSON.stringify(data_to_save),
                        success: callback,
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            my.lastSaveIndex = saved_from;
                            alert("Status: " + textStatus);
                            alert("Error: " + errorThrown);
                        }
                    });
                }

                function redirect() {
                    window.location.assign(my.redirect_url);
                }

                // Preload images
                // an array of paths to images that need to be loaded
                /*
                 var images = [];
                 images.push(my.base_url + "images/finished.png");
                 images.push(my.base_url + "images/good-job.png");
                 images.push(my.base_url + "images/halfway.png");
                 images.push(my.base_url + "images/imagination.png");
                 for(var s = 1; s < 5; s++) {
                 for(var i = 8; i < 33; i += 8) {
                 images.push(my.base_url + "images/s" + s + "/" + i + ".png");
                 }
                 }

                 setTimeout(
                 jsPsych.pluginAPI.preloadImages(images, function(){ startExperiment(); }),
                 10000);
                 */
                startExperiment();

                // Start the experiment.
                function startExperiment() {
                    $("#spinner").hide();
                    jsPsych.init({
                        timeline: timeline,
                        display_element: my.target,
                        on_finish: function (data) {
                            window.onbeforeunload = null; // Remove any warnings about leaving the page.
                            jsPsych.data.addProperties({
                                condition: my.condition
                            });
                            saveData(redirect);

                        }
                    });
                }

            }

            return my;
        }
        ()
    )
;