text:
'use strict';

angular
	.module('invitations', [])
	.controller('EditInvitationController', ['$scope', '$state', '$modal', 'AlertService', 'Authentication', 'NgTableParams',  '_', 'CommunicationModel', 'project', 'communication', 'mode', function EditInvitationController($scope, $state, $modal, AlertService, Authentication, NgTableParams,  _, CommunicationModel, project, communication, mode) {
		$scope.project = project;
		$scope.authentication = Authentication;
		$scope.mode = mode;
		// disable the delete button if user doesn't have permission to delete
		$scope.canDelete = $scope.mode === 'edit' && communication.userCan.delete;

		var self = this;
		self.communication = communication;
		self.communication.type = 'Invitation';
		self.communication.project = $scope.project._id;
		self.communication.personalized = true;
		self.communication.artifacts = [];

		$scope.emailTemplate = null;
		$scope.recipients = angular.copy(self.communication.recipients);

		var transformTemplate = function() {

			var invitationUrl = "" + $scope.project.name + "";
			var projectUrl = window.location.origin + '/p/' + $scope.project.code + '/detail';
			var projectUrlHtml = "" + $scope.project.name + "";

			var subject = !_.isEmpty(self.communication.templateSubject) ? self.communication.templateSubject : '';
			subject = subject.replace('%PROJECT_NAME%', $scope.project.name);
			subject = subject.replace('%CURRENT_USER_NAME%', $scope.authentication.user.displayName);
			subject = subject.replace('%CURRENT_USER_EMAIL%', $scope.authentication.user.email);

			var content = !_.isEmpty(self.communication.templateContent) ? self.communication.templateContent : '';
			content = content.replace('%PROJECT_URL%', projectUrlHtml);
			content = content.replace('%PROJECT_NAME%', $scope.project.name);
			content = content.replace('%CURRENT_USER_NAME%', $scope.authentication.user.displayName);
			content = content.replace('%CURRENT_USER_EMAIL%', $scope.authentication.user.email);
			content = content.replace('%INVITATION_URL%', invitationUrl);

			return {
				subject : subject,
				content: content,
				personalized: true
			};
		};

		var populateCommunication = function() {
			// call this before save...
			//
			// set the project...
			self.communication.type = 'Invitation';
			self.communication.project = $scope.project._id;
			self.communication.personalized = true;
			self.communication.artifacts = [];

			// set the email template
			if ($scope.emailTemplate && $scope.emailTemplate._id) {
				self.communication.emailTemplate = $scope.emailTemplate._id;
			}

			//(use angular copy to remove $$hashKey)...
			// create a recipient list...
			self.communication.recipients = [];
			_.each($scope.recipients, function(r) {
				// recipients mgr may have added some extra fields we don't store...
				var arrr = _.omit(angular.copy(r), ['firstName', 'lastName']);
				self.communication.recipients.push(arrr);
			});

		};

		var transformEmail = function() {
			var xformEmail = transformTemplate();
			self.communication.subject = xformEmail.subject;
			self.communication.content = xformEmail.content;
		};

		$scope.originalData = JSON.stringify(self.communication); // used to capture unsaved changes when we leave this route/screen
		$scope.allowTransition = false;

		var $locationChangeStartUnbind = $scope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
			// no check
			if (mode !== 'detail' && !$scope.allowTransition) {
				// rebuild the communication object and compare...
				populateCommunication();
				// do the check...
				if ($scope.originalData !== JSON.stringify(self.communication)) {
					// something changed...
					// do NOT allow the state change yet.
					event.preventDefault();

					$modal.open({
						animation: true,
						templateUrl: 'modules/vcs/client/views/vc-modal-confirm-cancel.html',
						controller: function($scope, $state, $modalInstance) {
							var self = this;
							self.ok = function() {
								$modalInstance.close();
							};
							self.cancel = function() {
								$modalInstance.dismiss('cancel');
							};
						},
						controllerAs: 'self',
						scope: $scope
					}).result.then(function (res) {
						$scope.allowTransition = true;
						$state.go(toState);
					}, function (err) {
						// cancelled...
					});

				} else {
					//DO NOTHING THERE IS NO CHANGES IN THE FORM
					//console.log('data NOT changed, let my data go!');
				}
			}
		});

		$scope.$on('$destroy', function () {
			window.onbeforeunload = null;
			$locationChangeStartUnbind();
		});

		var goToList = function() {
			$state.transitionTo('p.invitation.list', {projectid: $scope.project.code}, {
				reload: true, inherit: false, notify: true
			});
		};

		var reloadEdit = function() {
			// want to reload this screen, do not catch unsaved changes (we are probably in the middle of saving).
			$scope.allowTransition = true;
			$state.reload();
		};

		var goToEdit = function(model) {
			// want to reload this screen, do not catch unsaved changes (we are probably in the middle of saving).
			$scope.allowTransition = true;
			$state.transitionTo('p.invitation.edit', {projectid: $scope.project.code, communicationId: model._id }, {
				reload: true, inherit: false, notify: true
			});
		};

		var goNowhere = function() {
			// do nothing...
		};

		$scope.$watch(function(scope) { return scope.emailTemplate; },
			function(data) {
				if (data && data._id !== undefined) {
					self.communication.templateSubject = data.subject;
					self.communication.templateContent = data.content;
				}
			}
		);

		$scope.showError = function(msg, errorList, transitionCallback, title) {
			var modalDocView = $modal.open({
				animation: true,
				templateUrl: 'modules/vcs/client/views/vc-modal-error.html',
				controller: function($scope, $state, $modalInstance, _) {
					var self = this;
					self.title = title || 'An error has occurred';
					self.msg = msg;
					self.errors = errorList;
					self.ok = function() {
						$modalInstance.close();
					};
					self.cancel = function() {
						$modalInstance.dismiss('cancel');
					};
				},
				controllerAs: 'self',
				scope: $scope,
				size: 'md',
				windowClass: 'modal-alert',
				backdropClass: 'modal-alert-backdrop'
			});
			// do not care how this modal is closed, just go to the desired location...
			modalDocView.result.then(function (res) {transitionCallback(); }, function (err) { transitionCallback(); });
		};

		$scope.showSuccess = function(msg, transitionCallback, title) {
			var modalDocView = $modal.open({
				animation: true,
				templateUrl: 'modules/vcs/client/views/vc-modal-success.html',
				controller: function($scope, $state, $modalInstance, _) {
					var self = this;
					self.title = title || 'Success';
					self.msg = msg;
					self.ok = function() {
						$modalInstance.close();
					};
					self.cancel = function() {
						$modalInstance.dismiss('cancel');
					};
				},
				controllerAs: 'self',
				scope: $scope,
				size: 'md',
				windowClass: 'modal-alert',
				backdropClass: 'modal-alert-backdrop'
			});
			// do not care how this modal is closed, just go to the desired location...
			modalDocView.result.then(function (res) {transitionCallback(); }, function (err) { transitionCallback(); });
		};

		var doSend = function(communication) {
			if (communication.recipients.length === 0) {
				AlertService.error('Must have at least one recipient to send.');
				return;
			}
			var modalDocView = $modal.open({
				animation: true,
				templateUrl: 'modules/invitations/client/views/confirm-send.html',
				controller: function($scope, $state, $modalInstance, CommunicationModel, _) {
					var self = this;
					self.message = "Are you sure you want send '" + communication.name + "' to " + communication.recipients.length + " recipients?";
					self.ok = function() {
						$modalInstance.close();
					};
					self.cancel = function() {
						$modalInstance.dismiss('cancel');
					};
				},
				controllerAs: 'self',
				scope: $scope,
				size: 'md'
			});
			modalDocView.result.then(function () {
				CommunicationModel.save(communication)
					.then(function(saveRes) {
						return CommunicationModel.sendInvitation(saveRes);
					})
					.then(function(sendRes) {
						$scope.allowTransition = true;
						$scope.showSuccess('"'+ communication.name +'"' + ' was sent successfully.', goToList, 'Send Success');
					})
					.catch(function(errRes) {
						$scope.showError('"'+ communication.name +'"' + ' was not sent.', [], reloadEdit, 'Send Error');
					});
			}, function () {
				//console.log('delete modalDocView error');
			});
		};

		$scope.save = function(isValid) {
			if (!isValid) {
				$scope.$broadcast('show-errors-check-validity', 'mainForm');
				$scope.$broadcast('show-errors-check-validity', 'detailsForm');
				$scope.$broadcast('show-errors-check-validity', 'recipientsForm');
				return false;
			}

			populateCommunication();
			transformEmail();
			if (mode === 'create') {
				CommunicationModel.add(self.communication)
					.then (function (res) {
						function editWithResult() {
							goToEdit(res);
						}
						$scope.showSuccess('"'+ self.communication.name +'"' + ' was saved successfully', editWithResult, 'Save Successful');
					})
					.catch (function (err) {
						$scope.showError('"'+ self.communication.name +'"' + ' was not saved.', [], goNowhere, 'Save Error');
					});

			} else {
				CommunicationModel.save(self.communication)
					.then (function (res) {
						$scope.showSuccess('"'+ self.communication.name +'"' + ' was saved successfully', reloadEdit, 'Save Successful');
					})
					.catch (function (err) {
						$scope.showError('"'+ self.communication.name +'"' + ' was not saved.', [], reloadEdit, 'Save Error');
					});
			}

		};

		$scope.send = function(isValid) {
			// pop up preview and confirmation?
			if (!isValid) {
				$scope.$broadcast('show-errors-check-validity', 'mainForm');
				$scope.$broadcast('show-errors-check-validity', 'detailsForm');
				$scope.$broadcast('show-errors-check-validity', 'recipientsForm');
				return false;
			}
			populateCommunication();
			transformEmail();
			doSend(self.communication);
		};

		$scope.delete = function(communication) {
			var modalDocView = $modal.open({
				animation: true,
				templateUrl: 'modules/invitations/client/views/confirm-delete.html',
				controller: function($scope, $state, $modalInstance, CommunicationModel, _) {
					var self = this;
					self.communication = communication;
					self.message = "Are you sure you want to delete '" + communication.name + "' from this project?";
					self.ok = function() {
						$modalInstance.close(communication);
					};
					self.cancel = function() {
						$modalInstance.dismiss('cancel');
					};
				},
				controllerAs: 'self',
				scope: $scope,
				size: 'md'
			});
			modalDocView.result.then(function (res) {
				CommunicationModel.deleteId(communication._id)
					.then(function(res) {
						// deleted show the message, and go to list...
						$scope.allowTransition = true;
						$scope.showSuccess('"'+ communication.name +'"' + ' was deleted successfully from this project.', goToList, 'Delete Success');
					})
					.catch(function(res) {
						// could have errors from a delete check...
						$scope.showError('"'+ communication.name +'"' + ' was not deleted.', [], reloadEdit, 'Delete Error');
					});
			}, function () {
				//console.log('delete modalDocView error');
			});
		};

		$scope.cancel = function() {
			goToList();
		};

		$scope.hasMailRecipients = function() {
			return _.some($scope.recipients, 'viaMail', true);
		};

	}]);


text:
layout: page
title: about the Bruise
permalink: /about/
---

The Bruise is a home for short stories and essays. Words and thoughts about falling down, and getting up again.

All content by Jonathan Souder ([@blindeinstein](http://twitter.com/blindeinstein)) unless otherwise specified.
Think you have something you would like to contribute? Just want to say hi? [Contact](http://thebruise.net/contact) us.

And hey,
Thanks.

redpajama_set_name: RedPajamaGithub


text: Set user flairs


text:
from gusto import *
from firedrake import PeriodicIntervalMesh, ExtrudedMesh, Constant
from os import path
from netCDF4 import Dataset

# this tests the dry compressible hydrostatic balance, by setting up a vertical slice
# with this initial procedure, before taking a few time steps and ensuring that
# the resulting velocities are very small

def setup_balance(dirname):

    # set up grid and time stepping parameters
    dt = 1.
    tmax = 5.
    deltax = 400
    L = 2000.
    H = 10000.

    nlayers = int(H/deltax)
    ncolumns = int(L/deltax)

    m = PeriodicIntervalMesh(ncolumns, L)
    mesh = ExtrudedMesh(m, layers=nlayers, layer_height=H/nlayers)

    fieldlist = ['u', 'rho', 'theta']
    timestepping = TimesteppingParameters(dt=dt, maxk=4, maxi=1)
    output = OutputParameters(dirname=dirname+'/dry_balance', dumpfreq=10, dumplist=['u'])
    parameters = CompressibleParameters()
    diagnostics = Diagnostics(*fieldlist)
    diagnostic_fields = []

    state = State(mesh, vertical_degree=1, horizontal_degree=1,
                  family="CG",
                  timestepping=timestepping,
                  output=output,
                  parameters=parameters,
                  diagnostics=diagnostics,
                  fieldlist=fieldlist,
                  diagnostic_fields=diagnostic_fields)

    # Initial conditions
    u0 = state.fields("u")
    rho0 = state.fields("rho")
    theta0 = state.fields("theta")

    # spaces
    Vu = u0.function_space()
    Vt = theta0.function_space()
    Vr = rho0.function_space()

    # Isentropic background state
    Tsurf = Constant(300.)
    theta0.interpolate(Tsurf)

    # Calculate hydrostatic Pi
    compressible_hydrostatic_balance(state, theta0, rho0, solve_for_rho=True)

    state.initialise([('u', u0),
                      ('rho', rho0),
                      ('theta', theta0)])
    state.set_reference_profiles([('rho', rho0),
                                  ('theta', theta0)])

    # Set up advection schemes
    ueqn = EulerPoincare(state, Vu)
    rhoeqn = AdvectionEquation(state, Vr, equation_form="continuity")
    thetaeqn = EmbeddedDGAdvection(state, Vt, equation_form="advective", options=EmbeddedDGOptions())

    advected_fields = [("u", ThetaMethod(state, u0, ueqn)),
                       ("rho", SSPRK3(state, rho0, rhoeqn)),
                       ("theta", SSPRK3(state, theta0, thetaeqn))]

    # Set up linear solver
    linear_solver = CompressibleSolver(state)

    # Set up forcing
    compressible_forcing = CompressibleForcing(state)

    # build time stepper
    stepper = CrankNicolson(state, advected_fields, linear_solver,
                            compressible_forcing)

    return stepper, tmax

def run_balance(dirname):

    stepper, tmax = setup_balance(dirname)
    stepper.run(t=0, tmax=tmax)

def test_balance_setup(tmpdir):

    dirname = str(tmpdir)
    run_balance(dirname)
    filename = path.join(dirname, "dry_balance/diagnostics.nc")
    data = Dataset(filename, "r")

    u = data.groups['u']
    umax = u.variables['max']

    assert umax[-1] < 1e-8


text:
extern "C"
{
	//--------------------------------------------------------------------------------------
	/// Called by Java when the product descriptions have been fetched
	///
	/// @author S Downie
	///
	/// @param JNI environment
	/// @param Pointer to the calling function
	/// @param Array of product IDs
	/// @param Array of product Names
	/// @param Array of product Descriptions
	/// @param Array of product Prices
	//--------------------------------------------------------------------------------------
	void Java_com_chilliworks_chillisource_googleplay_networking_GooglePlayIAPNativeInterface_NativeOnProductsDescriptionsRequestComplete(JNIEnv* in_env, jobject in_this, jobjectArray in_productIds, jobjectArray in_names, jobjectArray in_descs, jobjectArray in_prices);
	//--------------------------------------------------------------------------------------
	/// Called by Java when the transaction status updates
	///
	/// @author S Downie
	///
	/// @param JNI environment
	/// @param Pointer to the calling function
	/// @param Result (SUCCESS - 0, FAILED - 1)
	/// @param Product ID
	/// @param Transaction ID
	/// @param Receipt
	//--------------------------------------------------------------------------------------
	void Java_com_chilliworks_chillisource_googleplay_networking_GooglePlayIAPNativeInterface_NativeOnTransactionStatusUpdated(JNIEnv* in_env, jobject in_this, jint in_result, jstring in_productId, jstring in_transactionId, jstring instrReceipt);
	//--------------------------------------------------------------------------------------
	/// Called by Java when the transaction close result returns
	///
	/// @param JNI environment
	/// @param Pointer to the calling function
	/// @param Product ID
	/// @param Transaction ID
	/// @param Success or failure
	//--------------------------------------------------------------------------------------
	void Java_com_chilliworks_chillisource_googleplay_networking_GooglePlayIAPNativeInterface_NativeOnTransactionClosed(JNIEnv* in_env, jobject in_this, jstring in_productId, jstring in_transactionId, jboolean in_success);
}

//--------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------
void Java_com_chilliworks_chillisource_googleplay_networking_GooglePlayIAPNativeInterface_NativeOnProductsDescriptionsRequestComplete(JNIEnv* in_env, jobject in_this, jobjectArray in_productIds, jobjectArray in_names, jobjectArray in_descs, jobjectArray in_prices)
{
	CSBackend::Android::GooglePlayIAPJavaInterfaceSPtr javaInterface = CSBackend::Android::JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CSBackend::Android::GooglePlayIAPJavaInterface>();
	if (javaInterface != nullptr)
	{
		u32 numProducts = in_env->GetArrayLength(in_productIds);
		std::vector<CSNetworking::IAPSystem::ProductDesc> products;
		products.reserve(numProducts);

		for(u32 i=0; i<numProducts; ++i)
		{
			CSNetworking::IAPSystem::ProductDesc desc;
			jstring id = (jstring)in_env->GetObjectArrayElement(in_productIds, i);
			desc.m_id = CSBackend::Android::JavaInterfaceUtils::CreateSTDStringFromJString(id);

			jstring name = (jstring)in_env->GetObjectArrayElement(in_names, i);
			desc.m_name = CSBackend::Android::JavaInterfaceUtils::CreateSTDStringFromJString(name);

			jstring description = (jstring)in_env->GetObjectArrayElement(in_descs, i);
			desc.m_description = CSBackend::Android::JavaInterfaceUtils::CreateSTDStringFromJString(description);

			jstring price = (jstring)in_env->GetObjectArrayElement(in_prices, i);
			desc.m_formattedPrice = CSBackend::Android::JavaInterfaceUtils::CreateSTDStringFromJString(price);

			products.push_back(desc);
		}

		CSCore::Application::Get()->GetTaskScheduler()->ScheduleMainThreadTask(std::bind(&CSBackend::Android::GooglePlayIAPJavaInterface::OnProductDescriptionsRequestComplete, javaInterface.get(), products));
	}
}
//--------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------
void Java_com_chilliworks_chillisource_googleplay_networking_GooglePlayIAPNativeInterface_NativeOnTransactionStatusUpdated(JNIEnv* in_env, jobject in_this, jint in_result, jstring in_productId, jstring in_transactionId, jstring in_receipt)
{
	CSBackend::Android::GooglePlayIAPJavaInterfaceSPtr javaInterface = CSBackend::Android::JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CSBackend::Android::GooglePlayIAPJavaInterface>();
	if (javaInterface != nullptr)
	{
		CSNetworking::IAPSystem::Transaction transaction;
		transaction.m_productId = CSBackend::Android::JavaInterfaceUtils::CreateSTDStringFromJString(in_productId);
		transaction.m_transactionId = CSBackend::Android::JavaInterfaceUtils::CreateSTDStringFromJString(in_transactionId);
		transaction.m_receipt = CSBackend::Android::JavaInterfaceUtils::CreateSTDStringFromJString(in_receipt);

		CSCore::Application::Get()->GetTaskScheduler()->ScheduleMainThreadTask(std::bind(&CSBackend::Android::GooglePlayIAPJavaInterface::OnTransactionStatusUpdated, javaInterface.get(), in_result, transaction));
	}
}
//--------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------
void Java_com_chilliworks_chillisource_googleplay_networking_GooglePlayIAPNativeInterface_NativeOnTransactionClosed(JNIEnv* in_env, jobject in_this, jstring in_productId, jstring in_transactionId, jboolean in_success)
{
	CSBackend::Android::GooglePlayIAPJavaInterfaceSPtr javaInterface = CSBackend::Android::JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<CSBackend::Android::GooglePlayIAPJavaInterface>();
	if (javaInterface != nullptr)
	{
		std::string productId = CSBackend::Android::JavaInterfaceUtils::CreateSTDStringFromJString(in_productId);
		std::string transactionId = CSBackend::Android::JavaInterfaceUtils::CreateSTDStringFromJString(in_transactionId);
		CSCore::Application::Get()->GetTaskScheduler()->ScheduleMainThreadTask(std::bind(&CSBackend::Android::GooglePlayIAPJavaInterface::OnTransactionClosed, javaInterface.get(), productId, transactionId, in_success));
	}
}

namespace CSBackend
{
	namespace Android
	{
		namespace
		{
			const std::string k_pendingCacheFile("GoogleIAPPendingTransactions.json");

			//---------------------------------------------------------------
			/// Adds the given transaction ID to the "pending transaction"
			/// cache.
			///
			/// @author S Downie
			///
			/// @param The transaction ID.
			//---------------------------------------------------------------
			void AddToPendingCache(const std::string& in_transactionId)
			{
				Json::Value jData;
				CSCore::JsonUtils::ReadJson(CSCore::StorageLocation::k_cache, k_pendingCacheFile, jData);
				jData[in_transactionId] = 0;
				CSCore::Utils::StringToFile(CSCore::StorageLocation::k_cache, k_pendingCacheFile, jData.toStyledString());
			}
			//---------------------------------------------------------------
			/// Removes the given transaction ID from the "pending transaction"
			/// cache.
			///
			/// @author S Downie
			///
			/// @param The transaction ID.
			//---------------------------------------------------------------
			void RemoveFromPendingCache(const std::string& in_transactionId)
			{
				//Remove the transaction from the pending cache
				Json::Value jData;
				if(CSCore::JsonUtils::ReadJson(CSCore::StorageLocation::k_cache, k_pendingCacheFile, jData))
				{
					jData.removeMember(in_transactionId);
					CSCore::Utils::StringToFile(CSCore::StorageLocation::k_cache, k_pendingCacheFile, jData.toStyledString());
				}
			}
		}

		CS_DEFINE_NAMEDTYPE(GooglePlayIAPJavaInterface);

		//--------------------------------------------------------------
		//--------------------------------------------------------------
		GooglePlayIAPJavaInterface::GooglePlayIAPJavaInterface(const std::string& in_publicKey)
		{
			CreateNativeInterface("com/chilliworks/chillisource/googleplay/networking/GooglePlayIAPNativeInterface");
			CreateMethodReference("Init", "(Ljava/lang/String;)V");
			CreateMethodReference("IsPurchasingEnabled", "()Z");
			CreateMethodReference("RequestProductDescriptions", "([Ljava/lang/String;)V");
			CreateMethodReference("CancelProductDescriptionsRequest", "()V");
			CreateMethodReference("RequestProductPurchase", "(Ljava/lang/String;I)V");
			CreateMethodReference("CloseTransaction", "(Ljava/lang/String;Ljava/lang/String;)V");
			CreateMethodReference("RestoreManagedPurchases", "()V");
			CreateMethodReference("RestorePendingUnmanagedTransactions", "()V");
			CreateMethodReference("RestorePendingManagedTransactions", "([Ljava/lang/String;)V");

			//initialise the system
			JNIEnv* env = JavaInterfaceManager::GetSingletonPtr()->GetJNIEnvironmentPtr();
			jstring publicKey = JavaInterfaceUtils::CreateJStringFromSTDString(in_publicKey);
			env->CallVoidMethod(GetJavaObject(), GetMethodID("Init"), publicKey);
			env->DeleteLocalRef(publicKey);
		}
		//--------------------------------------------------------------
		//--------------------------------------------------------------
		bool GooglePlayIAPJavaInterface::IsA(CSCore::InterfaceIDType in_interfaceId) const
		{
			return (in_interfaceId == GooglePlayIAPJavaInterface::InterfaceID);
		}
        //---------------------------------------------------------------
        //---------------------------------------------------------------
        bool GooglePlayIAPJavaInterface::IsPurchasingEnabled()
        {
			JNIEnv* env = JavaInterfaceManager::GetSingletonPtr()->GetJNIEnvironmentPtr();
			return env->CallBooleanMethod(GetJavaObject(), GetMethodID("IsPurchasingEnabled"));
        }
        //---------------------------------------------------------------
        //---------------------------------------------------------------
        void GooglePlayIAPJavaInterface::StartListeningForTransactionUpdates(const CSNetworking::IAPSystem::TransactionStatusDelegate& in_delegate)
        {
        	CS_ASSERT(in_delegate != nullptr, "Cannot have null transaction delegate");

        	m_transactionStatusDelegate = in_delegate;

        	JNIEnv* env = JavaInterfaceManager::GetSingletonPtr()->GetJNIEnvironmentPtr();
        	env->CallVoidMethod(GetJavaObject(), GetMethodID("RestorePendingUnmanagedTransactions"));

        	Json::Value jData;
        	if(CSCore::JsonUtils::ReadJson(CSCore::StorageLocation::k_cache, k_pendingCacheFile, jData))
        	{
        		const Json::Value::Members& members = jData.getMemberNames();
        		jobjectArray transactionIDs = env->NewObjectArray(members.size(), env->FindClass("java/lang/String"), env->NewStringUTF(""));

        		u32 index = 0;
        		for(Json::Value::Members::const_iterator it = members.begin(); it != members.end(); ++it, ++index)
        		{
    				jstring jtransactionId = JavaInterfaceUtils::CreateJStringFromSTDString(*it);
    				env->SetObjectArrayElement(transactionIDs, index, jtransactionId);
    				env->DeleteLocalRef(jtransactionId);
        		}

            	env->CallVoidMethod(GetJavaObject(), GetMethodID("RestorePendingManagedTransactions"), transactionIDs);
            	env->DeleteLocalRef(transactionIDs);
        	}
        }
        //---------------------------------------------------------------
        //---------------------------------------------------------------
        void GooglePlayIAPJavaInterface::StopListeningForTransactionUpdates()
        {
        	m_transactionStatusDelegate = nullptr;
        }
        //---------------------------------------------------------------
        //---------------------------------------------------------------
        void GooglePlayIAPJavaInterface::RequestProductDescriptions(const std::vector<std::string>& in_productIds, const CSNetworking::IAPSystem::ProductDescDelegate& in_delegate)
        {
            CS_ASSERT(in_productIds.empty() == false, "Cannot request no product descriptions");
            CS_ASSERT(in_delegate != nullptr, "Cannot have null product description delegate");
            CS_ASSERT(m_productsRequestDelegate == nullptr, "Only 1 product description request can be active at a time");

        	m_productsRequestDelegate = in_delegate;

        	JNIEnv* env = JavaInterfaceManager::GetSingletonPtr()->GetJNIEnvironmentPtr();

			jstring jstrEmptyString = env->NewStringUTF("");
			jclass jStringClass = env->FindClass("java/lang/String");

			jobjectArray productIDs = env->NewObjectArray(in_productIds.size(), jStringClass, jstrEmptyString);

			u32 productIDIndex = 0;
			for(std::vector<std::string>::const_iterator it = in_productIds.begin(); it != in_productIds.end(); ++it)
			{
				jstring jproductId = JavaInterfaceUtils::CreateJStringFromSTDString(*it);
				env->SetObjectArrayElement(productIDs, productIDIndex, jproductId);
				env->DeleteLocalRef(jproductId);
				productIDIndex++;
			}

			env->CallVoidMethod(GetJavaObject(), GetMethodID("RequestProductDescriptions"), productIDs);

			env->DeleteLocalRef(productIDs);
			env->DeleteLocalRef(jstrEmptyString);
			env->DeleteLocalRef(jStringClass);
        }
        //---------------------------------------------------------------
        //---------------------------------------------------------------
        void GooglePlayIAPJavaInterface::OnProductDescriptionsRequestComplete(const std::vector<CSNetworking::IAPSystem::ProductDesc>& in_products)
        {
        	if(m_productsRequestDelegate == nullptr)
        		return;

        	m_productsRequestDelegate(in_products);
        	m_productsRequestDelegate = nullptr;
        }
        //---------------------------------------------------------------
        //---------------------------------------------------------------
        void GooglePlayIAPJavaInterface::CancelProductDescriptionsRequest()
        {
			JNIEnv* env = JavaInterfaceManager::GetSingletonPtr()->GetJNIEnvironmentPtr();
			env->CallVoidMethod(GetJavaObject(), GetMethodID("CancelProductDescriptionsRequest"));
        }
        //---------------------------------------------------------------
        //---------------------------------------------------------------
        void GooglePlayIAPJavaInterface::RequestProductPurchase(const std::string& in_productId, CSNetworking::IAPSystem::ProductRegInfo::Type in_type)
        {
        	const u32 k_managedType = 0;
        	const u32 k_unManagedType = 1;
        	u32 type = k_unManagedType;

        	switch(in_type)
        	{
        		case CSNetworking::IAPSystem::ProductRegInfo::Type::k_managed:
        			type = k_managedType;
        			break;
        		case CSNetworking::IAPSystem::ProductRegInfo::Type::k_unmanaged:
        			type = k_unManagedType;
        			break;
        	}

			JNIEnv* env = JavaInterfaceManager::GetSingletonPtr()->GetJNIEnvironmentPtr();
			jstring jproductId = JavaInterfaceUtils::CreateJStringFromSTDString(in_productId);
			env->CallVoidMethod(GetJavaObject(), GetMethodID("RequestProductPurchase"), jproductId, type);
			env->DeleteLocalRef(jproductId);
        }
        //---------------------------------------------------------------
        //---------------------------------------------------------------
        void GooglePlayIAPJavaInterface::OnTransactionStatusUpdated(u32 in_statusId, const CSNetworking::IAPSystem::Transaction& in_transaction)
        {
        	if(m_transactionStatusDelegate == nullptr)
        		return;

        	CSNetworking::IAPSystem::Transaction::Status status = CSNetworking::IAPSystem::Transaction::Status::k_failed;

        	//This requires a little bit of faith. These numbers correspond to the constants defined
        	//in the java transaction description
        	//    	public final static int SUCCEEDED = 0;
        	//    	public final static int FAILED = 1;
        	//    	public final static int CANCELLED = 2;
    		//		public final static int RESTORED = 3;
    		//		public final static int RESUMED = 4;
        	//		public final static int REFUNDED = 5;
        	switch(in_statusId)
        	{
        		case 0:
        			status = CSNetworking::IAPSystem::Transaction::Status::k_succeeded;
        			AddToPendingCache(in_transaction.m_transactionId);
        			break;
        		case 1:
        			status = CSNetworking::IAPSystem::Transaction::Status::k_failed;
        			break;
        		case 2:
        			status = CSNetworking::IAPSystem::Transaction::Status::k_cancelled;
        			break;
        		case 3:
        			status = CSNetworking::IAPSystem::Transaction::Status::k_restored;
        			break;
        		case 4:
        			status = CSNetworking::IAPSystem::Transaction::Status::k_resumed;
        			break;
           		case 5:
           			status = CSNetworking::IAPSystem::Transaction::Status::k_refunded;
            		break;
        	}

        	CSNetworking::IAPSystem::TransactionSPtr transaction(new CSNetworking::IAPSystem::Transaction());
        	transaction->m_productId = in_transaction.m_productId;
        	transaction->m_transactionId = in_transaction.m_transactionId;
        	transaction->m_receipt = in_transaction.m_receipt;

        	m_transactionStatusDelegate(status, transaction);
        }
        //---------------------------------------------------------------
        //---------------------------------------------------------------
        void GooglePlayIAPJavaInterface::CloseTransaction(const std::string& in_productId, const std::string& in_transactionId, const CSNetworking::IAPSystem::TransactionCloseDelegate& in_delegate)
        {
        	CS_ASSERT(in_delegate != nullptr, "Cannot have null transaction close delegate");
        	CS_ASSERT(m_transactionCloseDelegate == nullptr, "Only 1 transaction can be closed at a time");

        	m_transactionCloseDelegate = in_delegate;

			JNIEnv* env = JavaInterfaceManager::GetSingletonPtr()->GetJNIEnvironmentPtr();
			jstring jproductId = JavaInterfaceUtils::CreateJStringFromSTDString(in_productId);
			jstring jtransactionId = JavaInterfaceUtils::CreateJStringFromSTDString(in_transactionId);
			env->CallVoidMethod(GetJavaObject(), GetMethodID("CloseTransaction"), jproductId, jtransactionId);
			env->DeleteLocalRef(jproductId);
			env->DeleteLocalRef(jtransactionId);

			RemoveFromPendingCache(in_transactionId);
        }
        //---------------------------------------------------------------
        //---------------------------------------------------------------
        void GooglePlayIAPJavaInterface::OnTransactionClosed(const std::string& in_productId, const std::string& in_transactionId, bool in_success)
        {
        	if(m_transactionCloseDelegate)
        	{
        		m_transactionCloseDelegate(in_productId, in_transactionId, in_success);
        		m_transactionCloseDelegate = nullptr;
        	}
        }
        //---------------------------------------------------------------
        //---------------------------------------------------------------
        void GooglePlayIAPJavaInterface::RestoreManagedPurchases()
        {
        	JNIEnv* env = JavaInterfaceManager::GetSingletonPtr()->GetJNIEnvironmentPtr();
        	env->CallVoidMethod(GetJavaObject(), GetMethodID("RestoreManagedPurchases"));
        }
	}
}

#endif

#endif


text:
namespace Crabwise.CommandWrap
{
    using System;
    using System.Collections.Generic;
    using System.Text;

    public class CommandStartingEventArgs : EventArgs
    {
        private readonly CommandStartInfo startInfo;

        public CommandStartingEventArgs(CommandStartInfo startInfo)
        {
            this.startInfo = startInfo;
        }

        public bool Cancel { get; set; }

        public CommandStartInfo StartInfo
        {
            get
            {
                return this.startInfo;
            }
        }
    }
}


text:
API wrapper for Envisia Contacts

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'envisia_contacts', '~> 0.1.0.beta', git: "https://github.com/envisialearning/envisia_contacts.git"
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install envisia_contacts --pre

## Usage

Create a file in your `config/initializers` folder named `envisia_contacts.rb` (or whichever name you prefer)

    EnvisiaContacts.configure do |c|
      c.api_key = 'api_key_here'
      c.url = "api_url_here"
    end

ActiveRecord methods available

    # Create
    contact = EnvisiaContact.create( email: 'someemail@example.com', first_name: 'Some', last_name: 'Example' )

    # Get
    contact = EnvisiaContact.find(contact_id)

    # Fetch via email
    contact = EnvisiaContact.find_by_email('someone@example.com')

    # Update
    contact.email = 'newemail@somewhere.com'
    contact.save

    # Delete
    contact.destroy

    # contact_added_to_cms_project
    contact = EnvisiaContact.contact_added_to_cms_project(guid, params)

    # update_contact_lifetime_value
    contact = EnvisiaContact.update_contact_lifetime_value(guid, params)


text:
#include "Vk.h"

static void Abort (char const *programName, char const *complaint) {
    fprintf (
	stderr,
	"Usage:\n\t%s upperBound\n\t%s\n",
	programName,
	complaint
    );
    exit (ErrorExitValue);
}

int main (int argc, char *argv[]) {
    int
	upperBound, inputValue;
    char
	inputString[128];

    if (argc < 2)
    {
	Abort (argv[0], "Too Few Arguments Specified");
    }

    if (1 != sscanf (argv[1], "%d", &upperBound))
    {
	Abort (argv[0], "Upper Bound Not Numeric");
    }

    while (fgets (inputString, sizeof inputString, stdin))
    {
	if (1 == sscanf (inputString, " %d", &inputValue) &&
	    inputValue < upperBound)
	{
	    printf ("mv %d .dsegs\n", inputValue);
	}
    }

    return NormalExitValue;
}

/************************** SOURCE FILE HISTORY: ************************/
/************************************************************************
  mkmvscript.c 1 replace /vision/tools/source
  871017 22:11:09 insyte Install tool source in source control

 ************************************************************************/


text:
package boa.types.proto;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import boa.types.BoaBool;
import boa.types.BoaProtoList;
import boa.types.BoaProtoTuple;
import boa.types.BoaString;
import boa.types.BoaType;
import boa.types.proto.enums.ExpressionKindProtoMap;

/**
 * A {@link ExpressionProtoTuple}.
 *
 * @author rdyer
 */
public class ExpressionProtoTuple extends BoaProtoTuple {
	private final static List<BoaType> members = new ArrayList<BoaType>();
	private final static Map<String, Integer> names = new HashMap<String, Integer>();

	static {
		int counter = 0;

		names.put("kind", counter++);
		members.add(new ExpressionKindProtoMap());

		names.put("expressions", counter++);
		members.add(new BoaProtoList(new ExpressionProtoTuple()));

		names.put("variable_decls", counter++);
		members.add(new BoaProtoList(new VariableProtoTuple()));

		names.put("new_type", counter++);
		members.add(new TypeProtoTuple());

		names.put("generic_parameters", counter++);
		members.add(new BoaProtoList(new TypeProtoTuple()));

		names.put("is_postfix", counter++);
		members.add(new BoaBool());

		names.put("literal", counter++);
		members.add(new BoaString());

		names.put("variable", counter++);
		members.add(new BoaString());

		names.put("method", counter++);
		members.add(new BoaString());

		names.put("method_args", counter++);
		members.add(new BoaProtoList(new ExpressionProtoTuple()));

		names.put("anon_declaration", counter++);
		members.add(new DeclarationProtoTuple());

		names.put("annotation", counter++);
		members.add(new ModifierProtoTuple());
	}

	/**
	 * Construct a {@link ExpressionProtoTuple}.
	 */
	public ExpressionProtoTuple() {
		super(members, names);
	}

	/** @{inheritDoc} */
	@Override
	public String toJavaType() {
		return "boa.types.Ast.Expression";
	}
}


text:
using factor10.VisionThing.CameraStuff;
using factor10.VisionThing.Effects;
using SharpDX;

namespace factor10.VisionThing
{
    public class VDrawableInstance : VDrawable
    {
        public readonly IVDrawable Thing;
        public Matrix World;

        public VDrawableInstance(IVEffect effect, IVDrawable thing, Matrix world )
            : base(effect)
        {
            Thing = thing;
            World = world;
        }

        protected override bool draw(Camera camera, DrawingReason drawingReason, ShadowMap shadowMap)
        {
            camera.UpdateEffect(Effect);
            Effect.World = World;
            Thing.Draw(Effect);
            return true;
        }
    }

}


text:
/* 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.
 */
package org.camunda.bpm.engine.test.bpmn.event.timer;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.camunda.bpm.engine.impl.cmd.DeleteJobsCmd;
import org.camunda.bpm.engine.impl.interceptor.CommandExecutor;
import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase;
import org.camunda.bpm.engine.impl.util.ClockUtil;
import org.camunda.bpm.engine.impl.util.IoUtil;
import org.camunda.bpm.engine.runtime.Job;
import org.camunda.bpm.engine.runtime.JobQuery;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.runtime.ProcessInstanceQuery;
import org.camunda.bpm.engine.test.Deployment;

/**
 * @author Joram Barrez
 */
public class StartTimerEventTest extends PluggableProcessEngineTestCase {

  @Deployment
  public void testDurationStartTimerEvent() throws Exception {

    // Set the clock fixed
    Date startTime = new Date();

    // After process start, there should be timer created
    JobQuery jobQuery = managementService.createJobQuery();
    assertEquals(1, jobQuery.count());

    // After setting the clock to time '50minutes and 5 seconds', the second timer should fire
    ClockUtil.setCurrentTime(new Date(startTime.getTime() + ((50 * 60 * 1000) + 5000)));

    executeAllJobs();

    executeAllJobs();

    List<ProcessInstance> pi = runtimeService.createProcessInstanceQuery().processDefinitionKey("startTimerEventExample")
        .list();
    assertEquals(1, pi.size());

    assertEquals(0, jobQuery.count());

  }

  @Deployment
  public void testFixedDateStartTimerEvent() throws Exception {

    // After process start, there should be timer created
    JobQuery jobQuery = managementService.createJobQuery();
    assertEquals(1, jobQuery.count());

    ClockUtil.setCurrentTime(new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").parse("15/11/2036 11:12:30"));
    executeAllJobs();

    List<ProcessInstance> pi = runtimeService.createProcessInstanceQuery().processDefinitionKey("startTimerEventExample")
        .list();
    assertEquals(1, pi.size());

    assertEquals(0, jobQuery.count());

  }

  // FIXME: This test likes to run in an endless loop when invoking the waitForJobExecutorOnCondition method
  @Deployment
  public void FAILING_testCycleDateStartTimerEvent() throws Exception {
    ClockUtil.setCurrentTime(new Date());

    // After process start, there should be timer created
    JobQuery jobQuery = managementService.createJobQuery();
    assertEquals(1, jobQuery.count());

    final ProcessInstanceQuery piq = runtimeService.createProcessInstanceQuery().processDefinitionKey("startTimerEventExample");

    assertEquals(0, piq.count());

    moveByMinutes(5);
    executeAllJobs();
    assertEquals(1, piq.count());
    assertEquals(1, jobQuery.count());

    moveByMinutes(5);
    executeAllJobs();
    assertEquals(1, piq.count());

    assertEquals(1, jobQuery.count());
    //have to manually delete pending timer
    cleanDB();

  }

  private void moveByMinutes(int minutes) throws Exception {
    ClockUtil.setCurrentTime(new Date(ClockUtil.getCurrentTime().getTime() + ((minutes * 60 * 1000) + 5000)));
  }

  @Deployment
  public void testCycleWithLimitStartTimerEvent() throws Exception {
    ClockUtil.setCurrentTime(new Date());

    // After process start, there should be timer created
    JobQuery jobQuery = managementService.createJobQuery();
    assertEquals(1, jobQuery.count());

    final ProcessInstanceQuery piq = runtimeService.createProcessInstanceQuery().processDefinitionKey("startTimerEventExampleCycle");

    assertEquals(0, piq.count());

    moveByMinutes(5);
    executeAllJobs();
    assertEquals(1, piq.count());
    assertEquals(1, jobQuery.count());

    moveByMinutes(5);
    executeAllJobs();
    assertEquals(2, piq.count());
    assertEquals(0, jobQuery.count());

  }

  @Deployment
  public void testExpressionStartTimerEvent() throws Exception {
    // ACT-1415: fixed start-date is an expression
    JobQuery jobQuery = managementService.createJobQuery();
    assertEquals(1, jobQuery.count());

    ClockUtil.setCurrentTime(new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").parse("15/11/2036 11:12:30"));
    executeAllJobs();

    List<ProcessInstance> pi = runtimeService.createProcessInstanceQuery().processDefinitionKey("startTimerEventExample")
        .list();
    assertEquals(1, pi.size());

    assertEquals(0, jobQuery.count());
  }

  @Deployment
  public void testVersionUpgradeShouldCancelJobs() throws Exception {
    ClockUtil.setCurrentTime(new Date());

    // After process start, there should be timer created
    JobQuery jobQuery = managementService.createJobQuery();
    assertEquals(1, jobQuery.count());

    //we deploy new process version, with some small change
    InputStream in = getClass().getResourceAsStream("StartTimerEventTest.testVersionUpgradeShouldCancelJobs.bpmn20.xml");
    String process = new String(IoUtil.readInputStream(in, "")).replaceAll("beforeChange","changed");
    IoUtil.closeSilently(in);
    in = new ByteArrayInputStream(process.getBytes());
    String id = repositoryService.createDeployment().addInputStream("StartTimerEventTest.testVersionUpgradeShouldCancelJobs.bpmn20.xml",
        in).deploy().getId();
    IoUtil.closeSilently(in);

    assertEquals(1, jobQuery.count());

    moveByMinutes(5);
    executeAllJobs();
    ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processDefinitionKey("startTimerEventExample").singleResult();
    String pi = processInstance.getProcessInstanceId();
    assertEquals("changed", runtimeService.getActiveActivityIds(pi).get(0));

    assertEquals(1, jobQuery.count());

    cleanDB();
    repositoryService.deleteDeployment(id, true);
  }

  @Deployment
  public void testTimerShouldNotBeRecreatedOnDeploymentCacheReboot() {

    // Just to be sure, I added this test. Sounds like something that could easily happen
    // when the order of deploy/parsing is altered.

    // After process start, there should be timer created
    JobQuery jobQuery = managementService.createJobQuery();
    assertEquals(1, jobQuery.count());

    // Reset deployment cache
    ((ProcessEngineConfigurationImpl) processEngineConfiguration).getDeploymentCache().discardProcessDefinitionCache();

    // Start one instance of the process definition, this will trigger a cache reload
    runtimeService.startProcessInstanceByKey("startTimer");

    // No new jobs should have been created
    assertEquals(1, jobQuery.count());
  }

  // Test for ACT-1533
  public void testTimerShouldNotBeRemovedWhenUndeployingOldVersion() throws Exception {
    // Deploy test process
    InputStream in = getClass().getResourceAsStream("StartTimerEventTest.testTimerShouldNotBeRemovedWhenUndeployingOldVersion.bpmn20.xml");
    String process = new String(IoUtil.readInputStream(in, ""));
    IoUtil.closeSilently(in);

    in = new ByteArrayInputStream(process.getBytes());
    String firstDeploymentId = repositoryService.createDeployment().addInputStream("StartTimerEventTest.testVersionUpgradeShouldCancelJobs.bpmn20.xml",
            in).deploy().getId();
    IoUtil.closeSilently(in);

    // After process start, there should be timer created
    JobQuery jobQuery = managementService.createJobQuery();
    assertEquals(1, jobQuery.count());

    //we deploy new process version, with some small change
    String processChanged = process.replaceAll("beforeChange","changed");
    in = new ByteArrayInputStream(processChanged.getBytes());
    String secondDeploymentId = repositoryService.createDeployment().addInputStream("StartTimerEventTest.testVersionUpgradeShouldCancelJobs.bpmn20.xml",
        in).deploy().getId();
    IoUtil.closeSilently(in);
    assertEquals(1, jobQuery.count());

    // Remove the first deployment
    repositoryService.deleteDeployment(firstDeploymentId, true);

    // The removal of an old version should not affect timer deletion
    // ACT-1533: this was a bug, and the timer was deleted!
    assertEquals(1, jobQuery.count());

    // Cleanup
    cleanDB();
    repositoryService.deleteDeployment(secondDeploymentId, true);
  }

  // util methods ////////////////////////////////////////

  /** executes all jobs in this threads until they are either done or retries are exhausted. */
  protected void executeAllJobs() {
    String nextJobId = getNextExecutableJobId();

    while(nextJobId != null) {
      try {
        managementService.executeJob(nextJobId);
      } catch(Throwable t) { /* ignore */ }
      nextJobId = getNextExecutableJobId();
    }

  }

  protected String getNextExecutableJobId() {
    List<Job> jobs = managementService.createJobQuery().executable().listPage(0, 1);
    if(jobs.size() == 1) {
      return jobs.get(0).getId();
    } else {
      return null;
    }
  }

  private void cleanDB() {
    String jobId = managementService.createJobQuery().singleResult().getId();
    CommandExecutor commandExecutor = processEngineConfiguration.getCommandExecutorTxRequired();
    commandExecutor.execute(new DeleteJobsCmd(jobId));
  }

}


text:
<?xml version="1.0"?>
<tool id="pne_search_by_pmids" name="Related PNE articles" is_multi_byte="true">
  <description></description>

  <command interpreter="ruby">related_pne_articles.rb --query-file '$pmids' -o '$output'</command>

  <inputs>
    <param name="pmids" format="txt" type="data" label="PMID list(s) or MEDLINE search result(s)"/>
  </inputs>

  <outputs>
    <data format="tabular" name="output" />
  </outputs>

  <help>
**What it does**

This tool provides related protein, nucleic acid and enzyme (PNE) article(s) for MEDLINE abstract(s).

PNE is a journal of Japan publishing review articles in all aspects of biology, and all articles in PNE are written in Japanese.

To recognize representative keyword(s) in MEDLINE abstracts, a biomedical term recognizer is developted by Dr. Chun of DBCLS using FACTA dictionaries of the National Centre for Text Mining (NaCTeM).

To translate representative English keywords in MEDLINE abstracts into Japanese terms, an English-Japanese dictionary developed by the dictionary team in DBCLS was used.

To search PNE articles, a PNE search API developed by the dictionary team in DBCLS was used.

-----

**How to use**

To use this tool a user first needs PubMed ID list as an input.

A user also can get PubMed ID list by performing a MEDLINE search.

Please select the PubMed ID list, and click the execute button.

The results can be shown on the middle pane by clicking the eye symbol on the history pane.

-----

**Output**

PMID{tab}TITLE{tab}PNE title{tab}PNE URL
  </help>

</tool>


text:
<!DOCTYPE html>
<!--
Copyright (c) 2013 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="/base/base.html">

<script>
'use strict';

tr.exportTo('tr.b', function() {
  function guessBinary(url) {
    return /[.]gz$/.test(url) || /[.]zip$/.test(url);
  }
  function get(url, async) {
    var req = new XMLHttpRequest();
    req.overrideMimeType('text/plain; charset=x-user-defined');
    req.open('GET', url, async);
    var isBinary = guessBinary(url);
    if (isBinary && async)
      req.responseType = 'arraybuffer';

    if (!async) {
      req.send(null);
      if (req.status == 200) {
        return req.responseText;
      } else {
        throw new Error('XHR failed with status ' + req.status);
      }
    }

    var p = new Promise(function(resolve, reject) {
      req.onreadystatechange = function(aEvt) {
        if (req.readyState == 4) {
          window.setTimeout(function() {
            if (req.status == 200) {
              if (req.responseType === 'arraybuffer')
                return resolve(req.response);
              return resolve(req.responseText);
            } else {
              reject(new Error('XHR failed with status ' + req.status));
            }
          }, 0);
        }
      };
    });
    req.send();
    return p;
  }

  function getAsync(url) {
    if (!tr.isHeadless)
      return get(url, true);
    var filename;
    if (url.startsWith('file:///'))
      filename = url.substring(7);
    else
      filename = global.hrefToAbsolutePath(url);
    var isBinary = guessBinary(url);
    return Promise.resolve().then(function() {
      if (isBinary)
        return readbuffer(filename);
      return read(filename);
    });
  }

  function getSync(url) {
    if (!tr.isHeadless)
      return get(url, false);
    var filename;
    if (url.startsWith('file:///'))
      filename = url.substring(7);
    else
      filename = global.hrefToAbsolutePath(url);
    var isBinary = guessBinary(url);
    if (isBinary)
      return readbuffer(filename);
    return read(filename);
  }

  return {
    getAsync: getAsync,
    getSync: getSync
  };
});
</script>


text:
using System;
using System.Linq;
using System.Reflection;
using DbUp;

namespace CatalogApi.Database.Mysql
{
    class Program
    {
        static int Main(string[] args)
        {
            var connectionString =
                args.FirstOrDefault()
                ?? "Server=(local)\\SqlExpress; Database=MyApp; Trusted_connection=true";

            var upgrader =
                DeployChanges.To
                    .SqlDatabase(connectionString)
                    .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly())
                    .LogToConsole()
                    .Build();

            var result = upgrader.PerformUpgrade();

            if (!result.Successful)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(result.Error);
                Console.ResetColor();
#if DEBUG
                Console.ReadLine();
#endif
                return -1;
            }

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Success!");
            Console.ResetColor();
            return 0;
        }
    }
}


text:
id: 880
title: 'LeetCode Jump Game II: Greedy vs DP vs BFS'
author: sigmainfy
excerpt: Greedy algorithm could solve the LeetCode problem Jump Game II in linear time, another two alternatives are DP and BFS with more time complexit
layout: post
guid: http://tech-wonderland.net/?p=880
views:
  - 800
dsq_thread_id:
  - 4379632018
categories:
  - Algorithm
  - LeetCode
tags:
  - bfs
  - dp
  - greedy
  - LeetCode
---
## Overview

Greedy algorithm could solve the LeetCode problem Jump Game II in linear time, another two alternatives are DP and BFS with more time complexit

## LeetCode Jump Game II Problem

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = `[2,3,1,1,4]`

The minimum number of jumps to reach the last index is `2`. (Jump `1` step from index 0 to 1, then `3` steps to the last index.)

## Greedy, DP, BFS Solution Analysis

(1) DP: let F(i) denote the minimum number of jumps, then we have F(i) = min(F(j) ) + 1 where j = 0, … i – 1, this is O(N^2) approach and will get TLE by the OJ

(2) BFS: For each i in A, set the number of steps to all the reachable potions (not visited ones) as the number of steps to reach i plus 1, this is O(N * max(A[i])), and still will get TLE by the OJ

(3) Greedy: still, keep the current maximum reach distance, and the number of steps to reach this current maximum distances, and keep another variable to record the next maximum reachable distance, which cost the current steps plus 1. The key idea behind is that, all the positions before the maximum reachable distance would be able to be reached! Then we linear scan the array to keep updating the current maximum and the next maximum as well as the number of steps. We can achieve the linear time algorithm.

The following code is accepted by the LeetCode OJ to pass the Jump Game II Problem:

{% highlight cpp linenos %}int jump(int A[], int n) {
    if (n <= 1) return 0;
    int maxReachableDistance = 0;
    int maxNextAvailableDist = 0;
    int minSteps = 0;

    for (int i = 0; i < n; ++i) {
        if (i > maxReachableDistance) {
            if (maxNextAvailableDist > maxReachableDistance) {
                maxReachableDistance = maxNextAvailableDist;
                ++minSteps;
            }
            else
                return -1;
        }
        maxNextAvailableDist = max(maxNextAvailableDist, A[i] + i);
        if (maxNextAvailableDist >= n - 1) return minSteps + 1;
    }
}
{% endhighlight %}

**Remarks:** The key idea behind the linear algorithm is that instead of keeping to know every position is reachable by how many steps, we only need to keep a single maximum reachable distances and the steps needed. So every time we only need to update this single value in constant time rather than update a linear portion of positions.

## **Summary**

Greedy algorithm could solve the LeetCode problem Jump Game II in linear time, another two alternatives are DP and BFS with more time complexit.


text:
package ddl

import (
	"github.com/juju/errors"
	"github.com/pingcap/tidb/infoschema"
	"github.com/pingcap/tidb/meta"
	"github.com/pingcap/tidb/model"
)

func (d *ddl) onCreateForeignKey(t *meta.Meta, job *model.Job) (ver int64, _ error) {
	schemaID := job.SchemaID
	tblInfo, err := getTableInfo(t, job, schemaID)
	if err != nil {
		return ver, errors.Trace(err)
	}

	var fkInfo model.FKInfo
	err = job.DecodeArgs(&fkInfo)
	if err != nil {
		job.State = model.JobStateCancelled
		return ver, errors.Trace(err)
	}
	fkInfo.ID = allocateIndexID(tblInfo)
	tblInfo.ForeignKeys = append(tblInfo.ForeignKeys, &fkInfo)

	originalState := fkInfo.State
	switch fkInfo.State {
	case model.StateNone:
		// We just support record the foreign key, so we just make it public.
		// none -> public
		fkInfo.State = model.StatePublic
		ver, err = updateVersionAndTableInfo(t, job, tblInfo, originalState != fkInfo.State)
		if err != nil {
			return ver, errors.Trace(err)
		}
		// Finish this job.
		job.FinishTableJob(model.JobStateDone, model.StatePublic, ver, tblInfo)
		return ver, nil
	default:
		return ver, ErrInvalidForeignKeyState.Gen("invalid fk state %v", fkInfo.State)
	}
}

func (d *ddl) onDropForeignKey(t *meta.Meta, job *model.Job) (ver int64, _ error) {
	schemaID := job.SchemaID
	tblInfo, err := getTableInfo(t, job, schemaID)
	if err != nil {
		return ver, errors.Trace(err)
	}

	var (
		fkName model.CIStr
		found  bool
		fkInfo model.FKInfo
	)
	err = job.DecodeArgs(&fkName)
	if err != nil {
		job.State = model.JobStateCancelled
		return ver, errors.Trace(err)
	}

	for _, fk := range tblInfo.ForeignKeys {
		if fk.Name.L == fkName.L {
			found = true
			fkInfo = *fk
		}
	}

	if !found {
		job.State = model.JobStateCancelled
		return ver, infoschema.ErrForeignKeyNotExists.GenByArgs(fkName)
	}

	nfks := tblInfo.ForeignKeys[:0]
	for _, fk := range tblInfo.ForeignKeys {
		if fk.Name.L != fkName.L {
			nfks = append(nfks, fk)
		}
	}
	tblInfo.ForeignKeys = nfks

	originalState := fkInfo.State
	switch fkInfo.State {
	case model.StatePublic:
		// We just support record the foreign key, so we just make it none.
		// public -> none
		fkInfo.State = model.StateNone
		ver, err = updateVersionAndTableInfo(t, job, tblInfo, originalState != fkInfo.State)
		if err != nil {
			return ver, errors.Trace(err)
		}
		// Finish this job.
		job.FinishTableJob(model.JobStateDone, model.StateNone, ver, tblInfo)
		return ver, nil
	default:
		return ver, ErrInvalidForeignKeyState.Gen("invalid fk state %v", fkInfo.State)
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
  <parent>
    <groupId>org.guvnor</groupId>
    <artifactId>guvnor-services</artifactId>
    <version>7.0.0-SNAPSHOT</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>

  <artifactId>guvnor-services-backend</artifactId>

  <name>Guvnor - Services Backend</name>
  <description>Guvnor - Services Backend</description>

  <dependencies>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
    </dependency>

    <dependency>
      <groupId>com.thoughtworks.xstream</groupId>
      <artifactId>xstream</artifactId>
    </dependency>
    <dependency>
      <groupId>org.guvnor</groupId>
      <artifactId>guvnor-project-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-bus</artifactId>
    </dependency>
    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-security-server</artifactId>
    </dependency>

    <dependency>
      <groupId>org.guvnor</groupId>
      <artifactId>guvnor-services-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.guvnor</groupId>
      <artifactId>guvnor-structure-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-server</artifactId>
    </dependency>
    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-backend-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-backend-server</artifactId>
    </dependency>
    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-security-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-commons</artifactId>
    </dependency>
    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-io</artifactId>
    </dependency>
    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-nio2-model</artifactId>
    </dependency>
    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-nio2-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-commons-editor-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-preferences-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-nio2-fs</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>javax.enterprise</groupId>
      <artifactId>cdi-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.jboss.spec.javax.servlet</groupId>
      <artifactId>jboss-servlet-api_3.1_spec</artifactId>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>

    <!-- The version of commons-io in droolsjbpm-build-bootstrap pom is way too old-->
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
    </dependency>

  </dependencies>

</project>


text:
(function (window, angular, undefined) {
  'use strict';
  angular
    .module('module.gallery')
    .directive('galleryPhotoList', function () {
      return {
        restrict: 'E',
        scope: {
          data: '=gallery',
          loading: '='
        },
        templateUrl: 'module/gallery/view/gallery.photos.list.html',
        link: function (scope, elem, attr) {

        }
      }
    });
})(window, window.angular);


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="false"
    android:drawable="@drawable/btn_share_unpressed" />

<item android:state_pressed="true"
    android:drawable="@drawable/btn_share_pressed" />

</selector>


text:
package bei.jmeter.persistent.properties.gui;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.table.TableCellEditor;

import org.apache.jmeter.gui.AbstractJMeterGuiComponent;
import org.apache.jmeter.gui.util.HeaderAsPropertyRenderer;
import org.apache.jmeter.gui.util.PowerTableModel;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.property.CollectionProperty;
import org.apache.jorphan.gui.GuiUtils;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;

import bei.jmeter.persistent.properties.AbstractPersistentProperties;

abstract class AbstractPersistentPropertiesGui extends
		AbstractJMeterGuiComponent {

	private static final long serialVersionUID = 0L;

	protected static final Logger log = LoggingManager.getLoggerForClass();

	protected static final String PARAMETER_COL_RESOURCE = "name"; // $NON-NLS-1$

	protected static final String DEFAULT_PARAM_FILTER = ".*"; // $NON-NLS-1$

	protected JPanel optionsPanel;

	protected JTable paramTable;

	protected PowerTableModel paramTableModel;

	private JButton addButton, deleteButton;

	private JPanel paramPanel;

	protected JTextField paramFilepath;

	protected JCheckBox useDefaultParamFile;

	public AbstractPersistentPropertiesGui() {
		super();
		init();
		clearGui();
	}

	protected void init() {
		setBorder(makeBorder());
		setLayout(new BorderLayout());

		add(makeTitlePanel(), BorderLayout.NORTH);

		JPanel mainPanel = new JPanel(new BorderLayout());

		Box mainBox = Box.createVerticalBox();
		mainBox.add(makeOptionsPanel());
		mainPanel.add(mainBox, BorderLayout.NORTH);

		mainPanel.add(makeParameterPanel(), BorderLayout.CENTER);
		add(mainPanel, BorderLayout.CENTER);
	}

	private JPanel makeOptionsPanel() {

		JPanel panelParamFilepath = new JPanel(new BorderLayout(5, 0));
		paramFilepath = new JTextField("", 20);
		JLabel paramFilepathLabel = new JLabel("Property file path: "); // $NON-NLS-1$
		paramFilepathLabel.setLabelFor(paramFilepath);
		panelParamFilepath.add(paramFilepathLabel, BorderLayout.WEST);
		panelParamFilepath.add(paramFilepath, BorderLayout.CENTER);

		JPanel panelUseDefaultParamFile = new JPanel(new BorderLayout(5, 0));
		useDefaultParamFile = new JCheckBox();
		JLabel useDefaultParamFileLabel = new JLabel(
				"Use default parameter file: "); // $NON-NLS-1$
		useDefaultParamFileLabel.setLabelFor(useDefaultParamFile);
		panelUseDefaultParamFile.add(useDefaultParamFileLabel,
				BorderLayout.WEST);
		panelUseDefaultParamFile.add(useDefaultParamFile, BorderLayout.CENTER);

		optionsPanel = new JPanel();
		optionsPanel.setLayout(new BoxLayout(optionsPanel, BoxLayout.Y_AXIS));
		optionsPanel.setBorder(BorderFactory.createEtchedBorder());

		optionsPanel.add(panelParamFilepath);
		optionsPanel.add(panelUseDefaultParamFile);

		return optionsPanel;
	}

	private JPanel makeParameterPanel() {
		JLabel tableLabel = new JLabel("user_parameters_table"); // $NON-NLS-1$
		initTableModel();
		paramTable = new JTable(paramTableModel);
		paramTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		paramTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

		paramTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

		paramPanel = new JPanel(new BorderLayout());
		paramPanel.add(tableLabel, BorderLayout.NORTH);
		JScrollPane scroll = new JScrollPane(paramTable);
		scroll.setPreferredSize(scroll.getMinimumSize());
		paramPanel.add(scroll, BorderLayout.CENTER);
		paramPanel.add(makeButtonPanel(), BorderLayout.SOUTH);
		return paramPanel;
	}

	abstract String getTitle();

	@Override
	public String getLabelResource() {
		return getTitle(); // $NON-NLS-1$
	}

	@Override
	public String getStaticLabel() {
		return getLabelResource();
	}

	/**
	 * Modifies a given GUI to mirror the data in the TestElement.
	 *
	 * @see org.apache.jmeter.gui.JMeterGUIComponent#configure(TestElement)
	 */
	@Override
	public void configure(TestElement element) {
		super.configure(element);

		initTableModel();
		paramTable.setModel(paramTableModel);

		AbstractPersistentProperties persistentProp = (AbstractPersistentProperties) element;
		CollectionProperty paramFiletrs = persistentProp.getFilters();
		paramTableModel.setColumnData(0,
				(List<?>) paramFiletrs.getObjectValue());
		useDefaultParamFile.setSelected(persistentProp.useDefaultFilepath());
		paramFilepath.setText(persistentProp.getFilepath());

	}

	abstract AbstractPersistentProperties getPersistentUserParametersInstance();

	/**
	 * @see org.apache.jmeter.gui.JMeterGUIComponent#createTestElement()
	 */
	@Override
	public TestElement createTestElement() {
		AbstractPersistentProperties persistentProp = getPersistentUserParametersInstance();
		modifyTestElement(persistentProp);
		return persistentProp;
	}

	/**
	 * Modifies a given TestElement to mirror the data in the GUI components.
	 *
	 * @see org.apache.jmeter.gui.JMeterGUIComponent#modifyTestElement(TestElement)
	 */
	@Override
	public void modifyTestElement(TestElement element) {
		super.configureTestElement(element);

		GuiUtils.stopTableEditing(paramTable);

		AbstractPersistentProperties persistentProp = ((AbstractPersistentProperties) element);

		persistentProp.setFilters(paramTableModel.getColumnData(PARAMETER_COL_RESOURCE));
		persistentProp.setUseDefaultFilepath(useDefaultParamFile.isSelected());
		persistentProp.setFilepath(paramFilepath.getText().trim());
	}

	/**
	 * Implements JMeterGUIComponent.clearGui
	 */
	@Override
	public void clearGui() {
		super.clearGui();

		clearParamTable();

		addDefaultParamFilter();

		paramFilepath.setText("");
		useDefaultParamFile.setSelected(true);
	}

	private void addDefaultParamFilter() {

		paramTableModel.addRow(new Object[] { DEFAULT_PARAM_FILTER }); // $NON-NLS-1$
		paramTableModel.fireTableDataChanged();
	}

	private void clearParamTable() {
		initTableModel();
		paramTable.setModel(paramTableModel);
		HeaderAsPropertyRenderer defaultRenderer = new HeaderAsPropertyRenderer() {
			private static final long serialVersionUID = 240L;

			@Override
			protected String getText(Object value, int row, int column) {
				return super.getText(value, row, column);
			}
		};
		paramTable.getTableHeader().setDefaultRenderer(defaultRenderer);
	}

	protected void initTableModel() {
		paramTableModel = new PowerTableModel(
				new String[] { PARAMETER_COL_RESOURCE } // $NON-NLS-1$
				, new Class[] { String.class });
	}

	private JPanel makeButtonPanel() {
		JPanel buttonPanel = new JPanel();
		buttonPanel.setLayout(new GridLayout(2, 2));
		addButton = new JButton("Add parameter filter"); // $NON-NLS-1$
		deleteButton = new JButton("Delete parameter filter"); // $NON-NLS-1$
		buttonPanel.add(addButton);
		buttonPanel.add(deleteButton);
		addButton.addActionListener(new AddAction());
		deleteButton.addActionListener(new DeleteAction());
		return buttonPanel;
	}

	private class AddAction implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			GuiUtils.stopTableEditing(paramTable);

			paramTableModel.addNewRow();
			paramTableModel.fireTableDataChanged();

			// Enable DELETE (which may already be enabled, but it won't hurt)
			deleteButton.setEnabled(true);

			// Highlight (select) the appropriate row.
			int rowToSelect = paramTableModel.getRowCount() - 1;
			paramTable.setRowSelectionInterval(rowToSelect, rowToSelect);
		}
	}

	private class DeleteAction implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			if (paramTable.isEditing()) {
				TableCellEditor cellEditor = paramTable.getCellEditor(
						paramTable.getEditingRow(),
						paramTable.getEditingColumn());
				cellEditor.cancelCellEditing();
			}

			int rowSelected = paramTable.getSelectedRow();
			if (rowSelected >= 0) {
				paramTableModel.removeRow(rowSelected);
				paramTableModel.fireTableDataChanged();

				// Disable DELETE if there are no rows in the table to delete.
				if (paramTableModel.getRowCount() == 0) {
					deleteButton.setEnabled(false);
				}

				// Table still contains one or more rows, so highlight (select)
				// the appropriate one.
				else {
					int rowToSelect = rowSelected;

					if (rowSelected >= paramTableModel.getRowCount()) {
						rowToSelect = rowSelected - 1;
					}

					paramTable
							.setRowSelectionInterval(rowToSelect, rowToSelect);
				}
			}
		}
	}

}


text:
// Copyright 2014 Traceur Authors.
//
// 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.

import {assert} from '../util/assert.js';
import {LoaderCompiler} from '../runtime/LoaderCompiler.js';
import {ExportsList} from '../codegeneration/module/ModuleSymbol.js';
import {Map} from './polyfills/Map.js';
import {isAbsolute, resolveUrl} from '../util/url.js';
import {Options} from '../Options.js';

var NOT_STARTED = 0;
var LOADING = 1;
var LOADED = 2;
var PARSED = 3;
var TRANSFORMING = 4
var TRANSFORMED = 5;
var COMPLETE = 6;
var ERROR = 7;

function mapToValues(map) {
  // We are having issues with cross frame/context symbols so we cannot use
  // iterators here.
  // https://github.com/google/traceur-compiler/issues/1152
  var array = [];
  map.forEach((v) => {
    array.push(v);
  });
  return array;
}

class LoaderError extends Error {
  constructor(msg, tree) {
    this.message = msg;
    this.tree = tree;
    this.name = 'LoaderError';
  }
}

/**
 * Base class representing a piece of code that is to be loaded or evaluated.
 * Similar to js-loader Load object
 */
class CodeUnit {
  /**
   * @param {LoaderCompiler} loaderCompiler Callbacks for parsing/transforming.
   * @param {string} normalizedName The normalized name of this dependency.
   * @param {string} type Either 'script' or 'module'. This determinse how to
   *     parse the code.
   * @param {number} state
   */
  constructor(loaderCompiler, normalizedName, type, state,
      name, referrerName, address) {
    this.promise = new Promise((res, rej) => {
      this.loaderCompiler = loaderCompiler;
      this.normalizedName = normalizedName;
      this.type = type;
      this.name_ = name;
      this.referrerName_ = referrerName;
      this.address = address;
      this.state_ = state || NOT_STARTED;
      this.error = null;
      this.result = null;
      this.metadata_ = {};
      this.dependencies = [];
      this.resolve = res;
      this.reject = rej;
    });
  }

  get state() {
    return this.state_;
  }

  set state(value) {
    if (value < this.state_) {
      throw new Error('Invalid state change');
    }
    this.state_ = value;
  }

  /**
   * @return opaque value set and used by loaderCompiler
   */
  get metadata() {
    return this.metadata_;
  }

  set metadata(value) {
    assert(value);
    this.metadata_ = value;
  }

  nameTrace() {
    var trace = this.specifiedAs();
    if (isAbsolute(this.name_)) {
      return trace + 'An absolute name.\n';
    }
    if (this.referrerName_) {
      return trace + this.importedBy() + this.normalizesTo();
    }
    return trace + this.normalizesTo();
  }

  specifiedAs() {
    return `Specified as ${this.name_}.\n`;
  }

  importedBy() {
    return `Imported by ${this.referrerName_}.\n`;
  }

  normalizesTo() {
    return 'Normalizes to ' + this.normalizedName + '\n';
  }

}

/**
 * CodeUnit coming from {@code Loader.set}.
 */
class PreCompiledCodeUnit extends CodeUnit {
  constructor(loaderCompiler, normalizedName, name, referrerName, address,
      module) {
    super(loaderCompiler, normalizedName, 'module', COMPLETE,
        name, referrerName, address);
    this.result = module;
    this.resolve(this.result);
  }
}

/**
 * CodeUnit coming from {@code Loader.register}.
 */
class BundledCodeUnit extends CodeUnit {
  constructor(loaderCompiler, normalizedName, name, referrerName, address,
      deps, execute) {
    super(loaderCompiler, normalizedName, 'module', TRANSFORMED,
        name, referrerName, address);
    this.deps = deps;
    this.execute = execute;
  }
  getModuleSpecifiers() {
    return this.deps;
  }
  evaluate() {
    var normalizedNames =
        this.deps.map((name) => this.loader_.normalize(name));
    var module = this.execute.apply(Reflect.global, normalizedNames);
    System.set(this.normalizedName, module);
    return module;
  }
}

/**
 * CodeUnit for sharing methods that just call back to loaderCompiler
 */
class HookedCodeUnit extends CodeUnit {
  getModuleSpecifiers() {
    return this.loaderCompiler.getModuleSpecifiers(this);
  }
  evaluate() {
    return this.loaderCompiler.evaluateCodeUnit(this);
  }
}

/**
 * CodeUnit used for {@code Loader.load}.
 */
class LoadCodeUnit extends HookedCodeUnit {
  /**
   * @param {InternalLoader} loader
   * @param {string} normalizedName
   */
  constructor(loaderCompiler, normalizedName, name, referrerName, address) {
    super(loaderCompiler, normalizedName, 'module', NOT_STARTED,
        name, referrerName, address);
  }
}

/**
 * CodeUnit used for {@code Loader.eval} and {@code Loader.module}.
 */
class EvalCodeUnit extends HookedCodeUnit {
  /**
   * @param {LoaderCompiler} loaderCompiler
   * @param {string} code
   * @param {string} caller script or module name
   */
  constructor(loaderCompiler, code, type = 'script',
      normalizedName, referrerName, address) {
    super(loaderCompiler, normalizedName, type,
        LOADED, null, referrerName, address);
    this.source = code;
  }
}

var uniqueNameCount = 0;

/**
 * The internal implementation of the code loader.
 */
export class InternalLoader {
  /**
   * @param {loaderCompiler} loaderCompiler
   */
  constructor(loader, loaderCompiler) {
    assert(loaderCompiler);

    this.loader_ = loader;
    this.loaderCompiler = loaderCompiler;
    this.cache = new Map();
    this.urlToKey = Object.create(null);
    this.sync_ = false;
    this.sourceMapsByURL_ = Object.create(null);
    this.sourceMapsByOutputName_ = Object.create(null);
  }

  defaultMetadata_(metadata = {}) {
    metadata.traceurOptions = metadata.traceurOptions || new Options();
    return metadata;
  }

  defaultModuleMetadata_(metadata = {}) {
    var metadata = this.defaultMetadata_(metadata);
    metadata.traceurOptions.script = false;
    return metadata;
  }

  getSourceMap(url) {
    // The caller may want the sourcemap from input to output or vice versa.
    return this.sourceMapsByURL_[url] || this.sourceMapsByOutputName_[url];
  }

  load(name, referrerName = this.loader_.baseURL,
      address, metadata = {}) {
    metadata = this.defaultMetadata_(metadata);
    var codeUnit = this.getOrCreateCodeUnit_(name, referrerName, address, metadata);
    this.load_(codeUnit);
    return codeUnit.promise.then(() => codeUnit);
  }

  load_(codeUnit) {
    if (codeUnit.state === ERROR) {
      return codeUnit;
    }

    if (codeUnit.state === TRANSFORMED) {
      this.handleCodeUnitLoaded(codeUnit)
    } else {
      if (codeUnit.state !== NOT_STARTED)
        return codeUnit;

      codeUnit.state = LOADING;
      codeUnit.address = this.loader_.locate(codeUnit);

      this.loader_.fetch(codeUnit).then((text) => {
        codeUnit.source = text;
        return codeUnit;
      }).
      then((load) => {
        return this.loader_.translate(load)
      }).
      then((source) => {
        codeUnit.source = source;
        codeUnit.state = LOADED;
        this.handleCodeUnitLoaded(codeUnit);
        return codeUnit;
      }).
      catch((err) => {
        try {
          codeUnit.state = ERROR;
          codeUnit.error = err;
          this.handleCodeUnitLoadError(codeUnit);
        } catch (ex) {
          console.error('Internal Error ' + (ex.stack || ex));
        }
      });
    }

    return codeUnit;
  }

  module(code, referrerName, address, metadata) {
    var codeUnit = new EvalCodeUnit(this.loaderCompiler, code, 'module',
                                      null, referrerName, address);
    codeUnit.metadata = this.defaultMetadata_(metadata);
    this.cache.set({}, codeUnit);
    this.handleCodeUnitLoaded(codeUnit);
    return codeUnit.promise;
  }

  define(normalizedName, code, address, metadata) {
    var codeUnit = new EvalCodeUnit(this.loaderCompiler, code, 'module',
                                    normalizedName, null, address);
    var key = this.getKey(normalizedName, 'module');
    codeUnit.metadata = this.defaultMetadata_(metadata);
    this.cache.set(key, codeUnit);
    this.handleCodeUnitLoaded(codeUnit);
    return codeUnit.promise;
  }

  /**
   * @param {string} code, source to be compiled as 'Script'
   * @param {string=} name,  ModuleSpecifier-like name, not normalized.
   * @param {string=} referrerName,  normalized name of container
   * @param {string=} address, URL
   */
  script(code, name, referrerName, address, metadata) {
    var normalizedName = System.normalize(name || '', referrerName, address);
    var codeUnit = new EvalCodeUnit(this.loaderCompiler, code, 'script',
                                    normalizedName, referrerName, address);
    var key = {};
    if (name)
      key = this.getKey(normalizedName, 'script');
    codeUnit.metadata = this.defaultMetadata_(metadata);
    this.cache.set(key, codeUnit);
    this.handleCodeUnitLoaded(codeUnit);
    return codeUnit.promise;
  }

  getKey(url, type) {
    var combined = type + ':' + url;
    if (combined in this.urlToKey) {
      return this.urlToKey[combined];
    }

    return this.urlToKey[combined] = {};
  }

  getCodeUnit_(normalizedName, type) {
    var key = this.getKey(normalizedName, type);
    var codeUnit = this.cache.get(key);
    return {key, codeUnit};
  }

  getOrCreateCodeUnit_(name, referrerName, address, metadata) {
    var normalizedName = System.normalize(name, referrerName, address);
    // TODO(jjb): embed type in name per es-discuss Yehuda Katz,
    // eg import 'name,script';
    var type = 'module';
    if (metadata && metadata.traceurOptions && metadata.traceurOptions.script)
      type = 'script';
    var {key, codeUnit} = this.getCodeUnit_(normalizedName, type);

    if (!codeUnit) {
      // All new code units need metadata set.
      assert(metadata && metadata.traceurOptions);
      var module = this.loader_.get(normalizedName);
      if (module) {
        codeUnit = new PreCompiledCodeUnit(this.loaderCompiler, normalizedName,
            name, referrerName, address, module);
        codeUnit.type = 'module';
      } else {
        var bundledModule = this.loader_.bundledModule(name);
        if (bundledModule) {
          codeUnit = new BundledCodeUnit(this.loaderCompiler, normalizedName,
              name, referrerName, address,
              bundledModule.deps, bundledModule.execute);
        } else {
          codeUnit = new LoadCodeUnit(this.loaderCompiler, normalizedName,
              name, referrerName, address);
          codeUnit.type = type;
        }
      }
      // We copy the incoming metadata to pass values from the API and to
      // inherit value from the API call into modules imported by the root.
      // But we don't want to inherit tree etc.
      // TODO(jjb): move this into the CodeUnit constructors.
      codeUnit.metadata = {
        traceurOptions: metadata.traceurOptions,
        outputName: metadata.outputName,
      };
      this.cache.set(key, codeUnit);
    }
    return codeUnit;
  }

  areAll(state) {
    return mapToValues(this.cache).every((codeUnit) => codeUnit.state >= state);
  }

  getCodeUnitForModuleSpecifier(name, referrerName) {
    var normalizedName = this.loader_.normalize(name, referrerName);
    return this.getCodeUnit_(normalizedName, 'module').codeUnit;
  }

  getExportsListForModuleSpecifier(name, referrer) {
    var codeUnit = this.getCodeUnitForModuleSpecifier(name, referrer);
    var exportsList = codeUnit.metadata.moduleSymbol;
    if (!exportsList) {
      if (codeUnit.result) {
        exportsList =
            new ExportsList(codeUnit.normalizedName);
        exportsList.addExportsFromModule(codeUnit.result);
      } else {
        throw new Error(
            `InternalError: ${name} is not a module, required by ${referrer}`);
      }
    }
    return exportsList;
  }

  /**
   * This is called when a codeUnit is loaded.
   * @param {CodeUnit} codeUnit
   */
  handleCodeUnitLoaded(codeUnit) {
    var referrerName = codeUnit.normalizedName;
    try {
      var moduleSpecifiers = codeUnit.getModuleSpecifiers();
      if (!moduleSpecifiers) {
        this.abortAll(`No module specifiers in ${referrerName}`);
        return;
      }
      codeUnit.dependencies = moduleSpecifiers.sort().map((name) => {
        return this.getOrCreateCodeUnit_(name, referrerName, null,
            this.defaultModuleMetadata_(codeUnit.metadata));
      });
    } catch (error) {
      this.rejectOneAndAll(codeUnit, error);
      return;
    }

    codeUnit.dependencies.forEach((dependency) => {
      this.load_(dependency);
    });

    if (this.areAll(PARSED)) {
      try {
        this.analyze();
        this.transform();
        this.evaluate();
      } catch (error) {
        this.rejectOneAndAll(codeUnit, error);
      }
    }
  }

  rejectOneAndAll(codeUnit, error) {
    codeUnit.state.ERROR;
    codeUnit.error = error;
    codeUnit.reject(error);
    // TODO(jjb): reject the other codeUnits with a distinct error.
    this.abortAll(error);
  }

  /**
   * This is called when a code unit failed to load.
   * @param {CodeUnit} codeUnit
   */
  handleCodeUnitLoadError(codeUnit) {
    var message = codeUnit.error ? String(codeUnit.error) + '\n' :
        `Failed to load '${codeUnit.address}'.\n`;
    message += codeUnit.nameTrace() + this.loader_.nameTrace(codeUnit);

    this.rejectOneAndAll(codeUnit, new Error(message));
  }

  /**
   * Aborts all loading code units.
   */
  abortAll(errorMessage) {
    // Notify all codeUnit listeners (else tests hang til timeout).
    this.cache.forEach((codeUnit) => {
      if (codeUnit.state !== ERROR)
        codeUnit.reject(errorMessage);
    });
  }

  analyze() {
    this.loaderCompiler.analyzeDependencies(mapToValues(this.cache), this);
  }

  transform() {
    this.transformDependencies_(mapToValues(this.cache));
  }

  transformDependencies_(dependencies, dependentName) {
    for (var i = 0; i < dependencies.length; i++) {
      var codeUnit = dependencies[i];
      if (codeUnit.state >= TRANSFORMED) {
        continue;
      }
      if (codeUnit.state === TRANSFORMING) {
        var cir = codeUnit.normalizedName;
        var cle = dependentName;
        this.rejectOneAndAll(codeUnit, new Error(
            `Unsupported circular dependency between ${cir} and ${cle}`));
        return;
      }
      codeUnit.state = TRANSFORMING;
      try {
        this.transformCodeUnit_(codeUnit);
      } catch(error) {
        this.rejectOneAndAll(codeUnit, error);
        return;
      }
    }
  }

  transformCodeUnit_(codeUnit) {
    this.transformDependencies_(codeUnit.dependencies, codeUnit.normalizedName);
    if (codeUnit.state === ERROR)
      return;

    this.loaderCompiler.transform(codeUnit);
    codeUnit.state = TRANSFORMED;
    this.loaderCompiler.write(codeUnit);
    var info = codeUnit.metadata.compiler.sourceMapInfo;
    if (info) {
      this.sourceMapsByURL_[info.url] = info.map;
      this.sourceMapsByOutputName_[info.outputName] = info.map;
    }
    this.loader_.instantiate(codeUnit);
  }

  orderDependencies() {
    // Order the dependencies.
    var visited = new Map();
    var ordered = [];
    function orderCodeUnits(codeUnit) {
      // Cyclic dependency.
      if (visited.has(codeUnit)) {
        return;
      }

      visited.set(codeUnit, true);
      codeUnit.dependencies.forEach(orderCodeUnits);
      ordered.push(codeUnit);
    }
    this.cache.forEach(orderCodeUnits);
    return ordered;
  }

  evaluate() {
    var dependencies = this.orderDependencies();

    for (var i = 0; i < dependencies.length; i++) {
      var codeUnit = dependencies[i];
      if (codeUnit.state >= COMPLETE) {
        continue;
      }

      var result;
      try {
        result = codeUnit.evaluate();
      } catch (ex) {
        this.rejectOneAndAll(codeUnit, ex);
        return;
      }

      codeUnit.result = result;
      codeUnit.source = null;
    }

    for (var i = 0; i < dependencies.length; i++) {
      var codeUnit = dependencies[i];
      if (codeUnit.state >= COMPLETE) {
        continue;
      }
      codeUnit.state = COMPLETE;
      codeUnit.resolve(codeUnit.result);
    }
  }

}

export var internals = {
  CodeUnit,
  EvalCodeUnit,
  LoadCodeUnit,
  LoaderCompiler
};