text:
import itertools

_call_timestamps = itertools.count()

def test_regular_ordering(hook):

    handler1, handler2, handler3 = handlers = [create_handler() for _ in range(3)] # pylint: disable=redefined-builtin

    for h in handlers:
        hook.register(h)

    hook.trigger(kwargs={})

    assert handler1.call_timestamp < handler2.call_timestamp < handler3.call_timestamp

def test_higher_lower_weight(hook):

    lower_priority = create_handler()
    hook.register(lower_priority, priority=-1)

    handler1, handler2, handler3 = handlers = [create_handler() for _ in range(3)] # pylint: disable=redefined-builtin

    higher_priority = create_handler()
    hook.register(higher_priority, priority=1)

    for h in handlers:
        hook.register(h)

    hook.trigger(kwargs={})

    assert handler1.call_timestamp < handler2.call_timestamp < handler3.call_timestamp
    assert lower_priority.call_timestamp > handler3.call_timestamp
    assert higher_priority.call_timestamp < handler1.call_timestamp

def create_handler():
    def returned():
        assert returned.call_timestamp is None
        returned.call_timestamp = next(_call_timestamps)

    returned.call_timestamp = None
    return returned

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var tv4 = require('tv4');
var formats = require('tv4-formats');
var json = tv4.freshApi();

// generic formats
json.addFormat(formats);

// custom formats
json.addFormat('throwUniqueError', function (data, schema) {
    return data.table + ': ' + data.property + ', ' + data.value + ' already exists';
});

json.addFormat('throwForeignKeyError', function (data, schema) {
    return data.property + ', ' + data.key + ' does not exist within: ' + data.table + '\'s collection';
});

module.exports = json;


text:
package com.google.gerrit.client.ui;

import com.google.gerrit.client.Gerrit;
import com.google.gerrit.client.changes.ChangeDetailCache;
import com.google.gerrit.common.PageLinks;
import com.google.gerrit.common.data.ChangeDetail;
import com.google.gwt.user.client.ui.FocusWidget;

public abstract class ActionDialog extends CommentedActionDialog<ChangeDetail> {
  public ActionDialog(final FocusWidget enableOnFailure, final boolean redirect,
      String dialogTitle, String dialogHeading) {
    super(dialogTitle, dialogHeading, new ChangeDetailCache.IgnoreErrorCallback() {
        @Override
        public void onSuccess(ChangeDetail result) {
          if (redirect) {
            Gerrit.display(PageLinks.toChange(result.getChange().getId()));
          } else {
            super.onSuccess(result);
          }
        }

        @Override
        public void onFailure(Throwable caught) {
          enableOnFailure.setEnabled(true);
        }
      });
  }
}


text:
	#include <xtl.h>
#elif defined(_WIN32)
	#include <windows.h>
#elif defined(__CELLOS_LV2__)
	#include <sys/synchronization.h>
	#include <pthread.h>
	//#define SPEEDTREE_USE_LIGHTWEIGHT_MUTEX
#elif defined(__psp2__)
	#include <kernel/threadmgr.h>
#elif defined(__APPLE__) || defined(__GNUC__)
	#include <pthread.h>
#elif defined(_OPENMP)
	#include <omp.h>
#elif defined(NDEV)
	#include <cafe/os.h>
#else
	#error SpeedTree CMutex not yet defined for this platform
#endif

///////////////////////////////////////////////////////////////////////
//  Packing

#ifdef ST_SETS_PACKING_INTERNALLY
	#pragma pack(push, 4)
#endif

///////////////////////////////////////////////////////////////////////
//  All SpeedTree SDK classes and variables are under the namespace "SpeedTree"

namespace SpeedTree
{

	///////////////////////////////////////////////////////////////////////
	//  Class CMutex

	class ST_DLL_LINK CMutex
	{
	public:
									CMutex( );
									~CMutex( );

			void					Lock(void);
			void					Unlock(void);
	private:
		#ifdef _WIN32 // Windows or Xbox 360
			CRITICAL_SECTION		m_sLock;
		#elif defined(__CELLOS_LV2__)
			#ifdef SPEEDTREE_USE_LIGHTWEIGHT_MUTEX
				sys_lwmutex_t		m_sLock;
			#else
				pthread_mutex_t		m_sLock;
			#endif
		#elif defined (__psp2__)
			SceUID					m_sLock;
		#elif defined(__APPLE__) || defined(__GNUC__)
			pthread_mutex_t			m_sLock;
		#elif defined(_OPENMP)
			omp_lock_t				m_sLock;
		#elif defined(NDEV)
			OSMutex					m_sLock;
		#endif
	};

	///////////////////////////////////////////////////////////////////////
	//  CMutex::CMutex

	inline CMutex::CMutex( )
	{
		#ifdef _WIN32 // Windows or Xbox 360
			InitializeCriticalSection(&m_sLock);
		#elif defined(__CELLOS_LV2__)
			#ifdef SPEEDTREE_USE_LIGHTWEIGHT_MUTEX
				sys_lwmutex_attribute_t sAttribute;
				sys_lwmutex_attribute_initialize(sAttribute);
				assert(sys_lwmutex_create(&m_sLock, &sAttribute) == CELL_OK);
			#else
				pthread_mutexattr_t sAttribute;
				pthread_mutexattr_init(&sAttribute);
				assert(pthread_mutex_init(&m_sLock, &sAttribute) == CELL_OK);
			#endif
		#elif defined(__psp2__)
			m_sLock = sceKernelCreateMutex("SpeedTree", SCE_KERNEL_MUTEX_ATTR_TH_PRIO, 0, NULL);
		#elif defined(__APPLE__) || defined(__GNUC__)
			pthread_mutex_init(&m_sLock, NULL);
		#elif defined(_OPENMP)
			omp_init_lock(&m_sLock);
		#elif defined(NDEV)
			OSInitMutex(&m_sLock);
		#endif
	}

	///////////////////////////////////////////////////////////////////////
	//  CMutex::~CMutex

	inline CMutex::~CMutex( )
	{
		#ifdef _WIN32 // Windows or Xbox 360
			DeleteCriticalSection(&m_sLock);
		#elif defined(__CELLOS_LV2__)
			#ifdef SPEEDTREE_USE_LIGHTWEIGHT_MUTEX
				assert(sys_lwmutex_destroy(&m_sLock) == CELL_OK);
			#else
				assert(pthread_mutex_destroy(&m_sLock) == CELL_OK);
			#endif
		#elif defined(__psp2__)
			sceKernelDeleteMutex(m_sLock);
		#elif defined(__APPLE__) || defined(__GNUC__)
			pthread_mutex_destroy(&m_sLock);
		#elif defined(_OPENMP)
			omp_destroy_lock(&m_sLock);
		#elif defined(NDEV)
			// do nothing
		#endif
	}

	///////////////////////////////////////////////////////////////////////
	//  CMutex::Lock

	inline void CMutex::Lock(void)
	{
		#ifdef _WIN32 // Windows or Xbox 360
			EnterCriticalSection(&m_sLock);
		#elif defined(__CELLOS_LV2__)
			#ifdef SPEEDTREE_USE_LIGHTWEIGHT_MUTEX
				assert(sys_lwmutex_lock(&m_sLock, SYS_NO_TIMEOUT) == CELL_OK);
			#else
				assert(pthread_mutex_lock(&m_sLock) == CELL_OK);
			#endif
		#elif defined(__psp2__)
			sceKernelLockMutex(m_sLock, 1, NULL);
		#elif defined(__APPLE__) || defined(__GNUC__)
			pthread_mutex_lock(&m_sLock);
		#elif defined(_OPENMP)
			omp_set_lock(&m_sLock);
		#elif defined(NDEV)
			OSLockMutex(&m_sLock);
		#endif
	}

	///////////////////////////////////////////////////////////////////////
	//  CMutex::Unlock

	inline void CMutex::Unlock(void)
	{
		#ifdef _WIN32 // Windows or Xbox 360
			LeaveCriticalSection(&m_sLock);
		#elif defined(__CELLOS_LV2__)
			#ifdef SPEEDTREE_USE_LIGHTWEIGHT_MUTEX
				assert(sys_lwmutex_unlock(&m_sLock) == CELL_OK);
			#else
				assert(pthread_mutex_unlock(&m_sLock) == CELL_OK);
			#endif
		#elif defined(__psp2__)
			sceKernelUnlockMutex(m_sLock, 1);
		#elif defined(__APPLE__) || defined(__GNUC__)
			pthread_mutex_unlock(&m_sLock);
		#elif defined(_OPENMP)
			omp_unset_lock(&m_sLock);
		#elif defined(NDEV)
			OSUnlockMutex(&m_sLock);
		#endif
	}

} // end namespace SpeedTree

#ifdef ST_SETS_PACKING_INTERNALLY
	#pragma pack(pop)
#endif


text:
package org.finra.herd.service.helper;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import org.finra.herd.core.helper.ConfigurationHelper;
import org.finra.herd.dao.SqsDao;
import org.finra.herd.dao.StorageFileDao;
import org.finra.herd.dao.StorageUnitDao;
import org.finra.herd.dao.helper.AwsHelper;
import org.finra.herd.dao.helper.JsonHelper;
import org.finra.herd.model.api.xml.BusinessObjectData;
import org.finra.herd.model.api.xml.BusinessObjectDataKey;
import org.finra.herd.model.api.xml.BusinessObjectDataRetryStoragePolicyTransitionRequest;
import org.finra.herd.model.dto.AwsParamsDto;
import org.finra.herd.model.dto.ConfigurationValue;
import org.finra.herd.model.dto.StoragePolicySelection;
import org.finra.herd.model.jpa.BusinessObjectDataEntity;
import org.finra.herd.model.jpa.StorageEntity;
import org.finra.herd.model.jpa.StoragePolicyEntity;
import org.finra.herd.model.jpa.StorageUnitEntity;
import org.finra.herd.model.jpa.StorageUnitStatusEntity;

@Component
public class BusinessObjectDataRetryStoragePolicyTransitionHelper
{
    private static final Logger LOGGER = LoggerFactory.getLogger(BusinessObjectDataRetryStoragePolicyTransitionHelper.class);

    @Autowired
    private AwsHelper awsHelper;

    @Autowired
    private BusinessObjectDataDaoHelper businessObjectDataDaoHelper;

    @Autowired
    private BusinessObjectDataHelper businessObjectDataHelper;

    @Autowired
    private ConfigurationHelper configurationHelper;

    @Autowired
    private JsonHelper jsonHelper;

    @Autowired
    private S3KeyPrefixHelper s3KeyPrefixHelper;

    @Autowired
    private SqsDao sqsDao;

    @Autowired
    private StorageFileDao storageFileDao;

    @Autowired
    private StoragePolicyDaoHelper storagePolicyDaoHelper;

    @Autowired
    private StoragePolicyHelper storagePolicyHelper;

    @Autowired
    private StorageUnitDao storageUnitDao;

    /**
     * Executes a retry of the storage policy transition and return the business object data information.
     *
     * @param businessObjectDataKey the business object data key
     * @param request the information needed to retry a storage policy transition
     *
     * @return the business object data information
     */
    public BusinessObjectData retryStoragePolicyTransition(BusinessObjectDataKey businessObjectDataKey,
        BusinessObjectDataRetryStoragePolicyTransitionRequest request)
    {
        // Validate and trim the business object data key.
        businessObjectDataHelper.validateBusinessObjectDataKey(businessObjectDataKey, true, true);

        // Validate and trim the request.
        validateBusinessObjectDataRetryStoragePolicyTransitionRequest(request);

        // Retrieve the business object data and ensure it exists.
        BusinessObjectDataEntity businessObjectDataEntity = businessObjectDataDaoHelper.getBusinessObjectDataEntity(businessObjectDataKey);

        // Retrieve and ensure that a storage policy exists with the specified key.
        StoragePolicyEntity storagePolicyEntity = storagePolicyDaoHelper.getStoragePolicyEntityByKey(request.getStoragePolicyKey());

        // Validate that storage policy filter matches this business object data, except for the storage.
        Assert.isTrue((storagePolicyEntity.getBusinessObjectDefinition() == null ||
            storagePolicyEntity.getBusinessObjectDefinition().equals(businessObjectDataEntity.getBusinessObjectFormat().getBusinessObjectDefinition())) &&
            (StringUtils.isBlank(storagePolicyEntity.getUsage()) ||
                storagePolicyEntity.getUsage().equalsIgnoreCase(businessObjectDataEntity.getBusinessObjectFormat().getUsage())) &&
            (storagePolicyEntity.getFileType() == null ||
                storagePolicyEntity.getFileType().equals(businessObjectDataEntity.getBusinessObjectFormat().getFileType())), String
            .format("Business object data does not match storage policy filter. " + "Storage policy: {%s}, business object data: {%s}",
                storagePolicyHelper.storagePolicyKeyAndVersionToString(request.getStoragePolicyKey(), storagePolicyEntity.getVersion()),
                businessObjectDataHelper.businessObjectDataEntityAltKeyToString(businessObjectDataEntity)));

        // Validate the storage policy filter storage.
        storagePolicyDaoHelper.validateStoragePolicyFilterStorage(storagePolicyEntity.getStorage());

        // Retrieve and validate a storage unit for this business object data.
        StorageUnitEntity storageUnitEntity = getStorageUnit(businessObjectDataEntity, storagePolicyEntity.getStorage());

        // Get S3 key prefix for this business object data.
        String s3KeyPrefix = s3KeyPrefixHelper
            .buildS3KeyPrefix(storagePolicyEntity.getStorage(), storageUnitEntity.getBusinessObjectData().getBusinessObjectFormat(), businessObjectDataKey);

        // Retrieve storage files registered with this business object data in the  storage.
        int storageFilesCount = storageUnitEntity.getStorageFiles().size();

        // Validate that we have storage files registered in the storage.
        Assert.isTrue(storageFilesCount > 0, String.format("Business object data has no storage files registered in \"%s\" storage. Business object data: {%s}",
            storageUnitEntity.getStorage().getName(), businessObjectDataHelper.businessObjectDataKeyToString(businessObjectDataKey)));

        // Retrieve all registered storage files from the storage that start with the S3 key prefix.
        // Since the S3 key prefix represents a directory, we add a trailing '/' character to it.
        String s3KeyPrefixWithTrailingSlash = StringUtils.appendIfMissing(s3KeyPrefix, "/");
        Long registeredStorageFilesMatchingS3KeyPrefixCount =
            storageFileDao.getStorageFileCount(storageUnitEntity.getStorage().getName(), s3KeyPrefixWithTrailingSlash);

        // Sanity check for the S3 key prefix.
        if (registeredStorageFilesMatchingS3KeyPrefixCount.intValue() != storageFilesCount)
        {
            throw new IllegalArgumentException(String.format(
                "Number of storage files (%d) registered for the business object data in \"%s\" storage is not equal to " +
                    "the number of registered storage files (%d) matching \"%s\" S3 key prefix in the same storage. Business object data: {%s}",
                storageFilesCount, storageUnitEntity.getStorage().getName(), registeredStorageFilesMatchingS3KeyPrefixCount, s3KeyPrefixWithTrailingSlash,
                businessObjectDataHelper.businessObjectDataKeyToString(businessObjectDataKey)));
        }

        // Get the SQS queue name from the system configuration.
        String sqsQueueName = configurationHelper.getProperty(ConfigurationValue.STORAGE_POLICY_SELECTOR_JOB_SQS_QUEUE_NAME);

        // Throw IllegalStateException if SQS queue name is not defined.
        if (StringUtils.isBlank(sqsQueueName))
        {
            throw new IllegalStateException(String.format("SQS queue name not found. Ensure the \"%s\" configuration entry is configured.",
                ConfigurationValue.STORAGE_POLICY_SELECTOR_JOB_SQS_QUEUE_NAME.getKey()));
        }

        // Create a storage policy selection.
        StoragePolicySelection storagePolicySelection =
            new StoragePolicySelection(businessObjectDataKey, storagePolicyHelper.getStoragePolicyKey(storagePolicyEntity), storagePolicyEntity.getVersion());

        // Executes SQS specific steps needed to retry a storage policy transition.
        sendStoragePolicySelectionSqsMessage(sqsQueueName, storagePolicySelection);

        // Create and return the business object data object from the entity.
        return businessObjectDataHelper.createBusinessObjectDataFromEntity(businessObjectDataEntity);
    }

    /**
     * Sends out an SQS message that contains the specified storage policy selection to the SQS queue name.
     *
     * @param sqsQueueName the SQS queue name
     * @param storagePolicySelection the storage policy selection
     */
    protected void sendStoragePolicySelectionSqsMessage(String sqsQueueName, StoragePolicySelection storagePolicySelection)
    {
        // Send the storage policy selection to the relative AWS SQS queue.
        AwsParamsDto awsParamsDto = awsHelper.getAwsParamsDto();
        String messageText = null;
        try
        {
            messageText = jsonHelper.objectToJson(storagePolicySelection);
            sqsDao.sendMessage(awsParamsDto, sqsQueueName, messageText, null);
        }
        catch (RuntimeException e)
        {
            LOGGER.error("Failed to publish message to the JMS queue. jmsQueueName=\"{}\" jmsMessagePayload={}", sqsQueueName, messageText);

            // Rethrow the original exception.
            throw e;
        }
    }

    /**
     * Retrieves and validates the storage unit for the specified business object data.
     *
     * @param businessObjectDataEntity the business object data entity
     * @param storageEntity the storage entity
     *
     * @return the storage unit entity
     */
    private StorageUnitEntity getStorageUnit(BusinessObjectDataEntity businessObjectDataEntity, StorageEntity storageEntity)
    {
        // Retrieve and validate storage unit for the business object data.
        StorageUnitEntity storageUnitEntity = storageUnitDao.getStorageUnitByBusinessObjectDataAndStorage(businessObjectDataEntity, storageEntity);

        // Validate the storage unit.
        if (storageUnitEntity == null)
        {
            throw new IllegalArgumentException(String
                .format("Business object data has no storage unit in \"%s\" storage. Business object data: {%s}", storageEntity.getName(),
                    businessObjectDataHelper.businessObjectDataEntityAltKeyToString(businessObjectDataEntity)));
        }
        else
        {
            // Validate that storage unit is in "ARCHIVING" state.
            Assert.isTrue(StorageUnitStatusEntity.ARCHIVING.equals(storageUnitEntity.getStatus().getCode()), String.format(
                "Business object data is not currently being archived. " +
                    "Storage unit in \"%s\" storage must have \"%s\" status, but it actually has \"%s\" status. Business object data: {%s}",
                storageEntity.getName(), StorageUnitStatusEntity.ARCHIVING, storageUnitEntity.getStatus().getCode(),
                businessObjectDataHelper.businessObjectDataEntityAltKeyToString(businessObjectDataEntity)));
        }

        return storageUnitEntity;
    }

    /**
     * Validates a business object data retry storage policy transition request. This method also trims the request parameters.
     *
     * @param request the business object data retry storage policy transition request
     */
    private void validateBusinessObjectDataRetryStoragePolicyTransitionRequest(BusinessObjectDataRetryStoragePolicyTransitionRequest request)
    {
        Assert.notNull(request, "A business object data retry storage policy transition request must be specified.");
        storagePolicyHelper.validateStoragePolicyKey(request.getStoragePolicyKey());
    }
}


text:
class OwnersController < ApplicationController
	def index
		render json
	end

end


text:
'use strict';

const Defaults = require('../entities/Defaults.js'),
  Client = require('../dao/client.js'),
  Server = require('../dao/socketServer.js'),
  util = require('util');

class IPC {
  constructor() {
    this.config = new Defaults();
    this.of = {};

    Object.defineProperties(
      this,
      {
        connectTo   : {
          enumerable:true,
          writable:false,
          value:connect
        },
        connectToNet: {
          enumerable:true,
          writable:false,
          value:connectNet
        },
        disconnect  : {
          enumerable:true,
          writable:false,
          value:disconnect
        },
        serve       : {
          enumerable:true,
          writable:false,
          value:serve
        },
        serveNet    : {
          enumerable:true,
          writable:false,
          value:serveNet
        },
        server      : {
          enumerable:true,
          writable:true,
          configurable:true,
          value:false
        },
        log         : {
          enumerable:true,
          writable:false,
          value:log
        }
      }
    );
  }
}

function log() {
  if (this.config.silent) {
    return;
  }

  let args = Array.prototype.slice.call(arguments);

  for (let i=0, count=args.length; i<count; i++) {
    if (typeof args[i] != 'object') {
      continue;
    }

    args[i] = util.inspect(args[i],{colors:true});
  }

  console.log(args.join(' '));
}

function disconnect(id) {
  if (!this.of[id]) {
    return;
  }

  this.of[id].config.stopRetrying = true;

  this.of[id].off('*');
  if (this.of[id].socket) {
    if (this.of[id].socket.destroy) {
      this.of[id].socket.destroy();
    }
  }

  delete this.of[id];
}

function serve(path, callback) {
  if (typeof path == 'function') {
    callback = path;
    path = false;
  }

  if (!path) {
    this.log(
      'Server path not specified, so defaulting to'.notice,
      'ipc.config.socketRoot + ipc.config.appspace + ipc.config.id'.variable,
      (this.config.socketRoot+this.config.appspace+this.config.id).data
    );
    path = this.config.socketRoot+this.config.appspace+this.config.id;
  }

  if (!callback) {
    callback = emptyCallback;
  }

  this.server = new Server(
    path,
    this.config,
    log
  );

  this.server.on('start', callback);
}

function emptyCallback() {
  //Do Nothing
}

function serveNet(host, port, UDPType, callback) {
  if (typeof host == 'number') {
    callback = UDPType;
    UDPType = port;
    port = host;
    host = false;
  }

  if (typeof host == 'function') {
    callback = host;
    UDPType = false;
    host = false;
    port = false;
  }

  if (!host) {
    this.log(
      'Server host not specified, so defaulting to'.notice,
      'ipc.config.networkHost'.variable,
      this.config.networkHost.data
    );
    host=this.config.networkHost;
  }

  if (host.toLowerCase() == 'udp4' || host.toLowerCase() == 'udp6') {
    callback = port;
    UDPType = host.toLowerCase();
    port = false;
    host = this.config.networkHost;
  }

  if (typeof port == 'string') {
    callback = UDPType;
    UDPType = port;
    port = false;
  }
  if (typeof port == 'function') {
    callback = port;
    UDPType = false;
    port = false;
  }
  if (!port) {
    this.log(
      'Server port not specified, so defaulting to'.notice,
      'ipc.config.networkPort'.variable,
      this.config.networkPort
    );
    port = this.config.networkPort;
  }

  if (typeof UDPType == 'function') {
    callback = UDPType;
    UDPType = false;
  }

  if (!callback) {
    callback = emptyCallback;
  }

  this.server = new Server(host, this.config, log, port);

  if (UDPType) {
    this.server[UDPType] = true;
  }

  this.server.on('start', callback);
}

function connect(id, path, callback) {
  if (typeof path == 'function') {
    callback = path;
    path = false;
  }

  if (!callback) {
    callback = emptyCallback;
  }

  if (!id) {
    this.log(
      'Service id required'.warn,
      'Requested service connection without specifying service id. Aborting connection attempt'.notice
    );
    return;
  }

  if (!path) {
    this.log(
      'Service path not specified, so defaulting to'.notice,
      'ipc.config.socketRoot + ipc.config.appspace + id'.variable,
      (this.config.socketRoot + this.config.appspace + id).data
    );
    path = this.config.socketRoot + this.config.appspace + id;
  }

  if (this.of[id]) {
    if (!this.of[id].socket.destroyed) {
      this.log(
        'Already Connected to'.notice,
        id.variable,
        '- So executing success without connection'.notice
      );
      callback();
      return;
    }
    this.of[id].socket.destroy();
  }

  this.of[id] = new Client(this.config, this.log);
  this.of[id].id = id;
  this.of[id].path = path;

  this.of[id].connect();

  // sync execute
  callback(this);
}

function connectNet(id, host, port, callback) {
  if (!id) {
    this.log(
      'Service id required'.warn,
      'Requested service connection without specifying service id. Aborting connection attempt'.notice
    );
    return;
  }

  if (typeof host=='number') {
    callback = port;
    port = host;
    host = false;
  }

  if(typeof host=='function'){
    callback=host;
    host=false;
    port=false;
  }

  if (!host) {
    this.log(
      'Server host not specified, so defaulting to'.notice,
      'ipc.config.networkHost'.variable,
      this.config.networkHost.data
    );
    host=this.config.networkHost;
  }

  if (typeof port=='function') {
    callback=port;
    port=false;
  }

  if (!port) {
    this.log(
      'Server port not specified, so defaulting to'.notice,
      'ipc.config.networkPort'.variable,
      this.config.networkPort
    );
    port=this.config.networkPort;
  }

  if (typeof callback == 'string') {
    id = callback;
    callback = false;
  }
  if (!callback) {
    callback = emptyCallback;
  }

  if (this.of[id]) {
    if(!this.of[id].socket.destroyed){
      this.log(
        'Already Connected to'.notice,
        id.variable,
        '- So executing success without connection'.notice
      );
      callback();
      return;
    }
    this.of[id].socket.destroy();
  }

  this.of[id] = new Client(this.config, this.log);
  this.of[id].id = id;
  this.of[id].path = host;
  this.of[id].port = port;

  this.of[id].connect();

  callback(this);
}

module.exports=IPC;


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Corytholoma curtiflorum Malme

### Remarks
null


text:
<?php

namespace spec\LdapTools\Query\Builder;

use LdapTools\Connection\LdapConnectionInterface;
use LdapTools\DomainConfiguration;
use LdapTools\Query\Operator\Comparison;
use PhpSpec\ObjectBehavior;

class FilterBuilderSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('LdapTools\Query\Builder\FilterBuilder');
    }

    function it_should_get_an_instance_through_the_factory_method(LdapConnectionInterface $connection)
    {
        $connection->getConfig()->willReturn((new DomainConfiguration('foo.bar'))->setLdapType('openldap'));
        $this::getInstance()->shouldReturnAnInstanceOf('LdapTools\Query\Builder\FilterBuilder');
        $this::getInstance($connection)->shouldReturnAnInstanceOf('LdapTools\Query\Builder\FilterBuilder');
    }

    function it_should_return_bAnd_when_calling_bAnd()
    {
        $this->bAnd()->shouldReturnAnInstanceOf('LdapTools\Query\Operator\bAnd');
    }

    function it_should_return_bOr_when_calling_bOr()
    {
        $this->bOr()->shouldReturnAnInstanceOf('LdapTools\Query\Operator\bOr');
    }

    function it_should_return_bOr_when_calling_bNot()
    {
        $this->bNot(new Comparison('foo', Comparison::EQ, 'bar'))->shouldReturnAnInstanceOf('LdapTools\Query\Operator\bNot');
    }

    function it_should_return_bNot_when_calling_neq()
    {
        $this->neq('foo', 'bar')->shouldReturnAnInstanceOf('LdapTools\Query\Operator\bNot');
    }

    function it_should_return_a_comparison_when_calling_eq()
    {
        $this->eq('foo', 'bar')->shouldReturnAnInstanceOf('LdapTools\Query\Operator\Comparison');
    }

    function it_should_return_a_comparison_when_calling_gte()
    {
        $this->gte('foo', 'bar')->shouldReturnAnInstanceOf('LdapTools\Query\Operator\Comparison');
    }

    function it_should_return_a_comparison_when_calling_lte()
    {
        $this->lte('foo', 'bar')->shouldReturnAnInstanceOf('LdapTools\Query\Operator\Comparison');
    }

    function it_should_return_a_comparison_when_calling_aeq()
    {
        $this->aeq('foo', 'bar')->shouldReturnAnInstanceOf('LdapTools\Query\Operator\Comparison');
    }

    function it_should_return_a_wildcard_when_calling_startsWith()
    {
        $this->startsWith('foo', 'bar')->shouldReturnAnInstanceOf('LdapTools\Query\Operator\Wildcard');
    }

    function it_should_return_a_wildcard_when_calling_endsWith()
    {
        $this->endsWith('foo', 'bar')->shouldReturnAnInstanceOf('LdapTools\Query\Operator\Wildcard');
    }

    function it_should_return_a_wildcard_when_calling_contains()
    {
        $this->contains('foo', 'bar')->shouldReturnAnInstanceOf('LdapTools\Query\Operator\Wildcard');
    }

    function it_should_return_a_wildcard_when_calling_like()
    {
        $this->like('foo', 'b*a*r')->shouldReturnAnInstanceOf('LdapTools\Query\Operator\Wildcard');
    }

    function it_should_return_a_wildcard_when_calling_present()
    {
        $this->present('foo')->shouldReturnAnInstanceOf('LdapTools\Query\Operator\Wildcard');
    }

    function it_should_return_bNot_when_calling_notPresent()
    {
        $this->notPresent('bar')->shouldReturnAnInstanceOf('LdapTools\Query\Operator\bNot');
    }

    function it_should_return_MatchingRule_when_calling_bitwiseAnd()
    {
        $this->bitwiseAnd('bar', 2)->shouldReturnAnInstanceOf('LdapTools\Query\Operator\MatchingRule');
    }

    function it_should_return_MatchingRule_when_calling_bitwiseOr()
    {
        $this->bitwiseOr('bar', 2)->shouldReturnAnInstanceOf('LdapTools\Query\Operator\MatchingRule');
    }

    function it_should_return_bAnd_when_calling_lt()
    {
        $this->lt('foo', '5')->shouldReturnAnInstanceOf('LdapTools\Query\Operator\bAnd');
    }

    function it_should_return_bAnd_when_calling_gt()
    {
        $this->gt('foo', '5')->shouldReturnAnInstanceOf('LdapTools\Query\Operator\bAnd');
    }

    function it_should_correctly_format_a_less_than_filter()
    {
        $this->lt('foo', '5')->toLdapFilter()->shouldBeEqualTo('(&(!(foo>=5))(foo=*))');
    }

    function it_should_correctly_format_a_greater_than_filter()
    {
        $this->gt('foo', '5')->toLdapFilter()->shouldBeEqualTo('(&(!(foo<=5))(foo=*))');
    }

    function it_should_correctly_format_a_generic_matching_rule()
    {
        $this->match('foo', 'caseExact', 'bar')->toLdapFilter()->shouldBeEqualTo('(foo:caseExact:=bar)');
        $this->match(null, '2.4.8.10', 'America', true)->toLdapFilter()->shouldBeEqualTo('(:dn:2.4.8.10:=America)');
    }

    function it_should_correctly_format_a_match_dn_filter()
    {
        $this->matchDn('ou', 'Sales')->toLdapFilter()->shouldBeEqualTo('(ou:dn:=Sales)');
    }

    function it_should_correctly_format_an_in_filter()
    {
        $this->in('id', [1, 2, 3, 4, 5])->toLdapFilter()->shouldBeEqualTo('(|(id=1)(id=2)(id=3)(id=4)(id=5))');
    }
}


text:
import os
from collections import Counter
from flask import Flask, render_template, request, redirect
from flask.ext.wtf import Form
from flask_wtf.html5 import NumberInput
from wtforms import StringField, SubmitField
from wtforms.validators import Required
from flask.ext.bootstrap import Bootstrap

from which_plates.main import which_plates

app = Flask(__name__)
Bootstrap(app)
app.secret_key = os.environ.get("SECRET_KEY")

class PlatesForm(Form):
    plates = StringField("plates", default="55,45,44,35,33,25,22,10,5,2.5", validators=[Required()])
    goal = StringField("goal", default="225", validators=[Required()])
    bar = StringField("bar", default="45", validators=[Required()])
    submit = SubmitField('Submit')

@app.route("/", methods=["GET", "POST"])
def index():
    warm_up = None
    if request.method == "POST":

        warm_up = which_plates(
            (float(request.form['goal'])- float(request.form['bar']))/2 ,
            Counter([float(p) for p in request.form['plates'].split(',')]),
            [.20, .40, .60, .80, 1]
        )
        warm_up = [(plates, sum(plates)) for action, plates in warm_up if action=="l"]
    return render_template("index.html", form=PlatesForm(), warm_up=warm_up)

if __name__ == '__main__':
    PORT = int(os.environ.get("PORT", 5000))
    DEBUG = bool(os.environ.get("DEBUG", False))
    app.run(host="0.0.0.0", port=PORT, debug=DEBUG)


text:
package main

import (
	"bufio"
	"fmt"
	"os"
	"path/filepath"

	"github.com/urfave/cli"
)

const CALL_GIM_GIT_HOOK_CODE = "$GOPATH/bin/gim sync"

func installCmd(c *cli.Context) error {
	fmt.Println("Install Git hooks...")

	hp, err := filepath.Abs("./.git/hooks")
	if err != nil {
		fmt.Println("Unable to check Git hooks directory: " + err.Error())
	}

	err = installGitHook(hp + string(os.PathSeparator) + "post-merge")
	if err != nil {
		return cli.NewExitError("Unable to insatll Git post-merge hook: "+err.Error(), 1)
	}
	fmt.Println("Post-merge Git hook installed")

	installGitHook(hp + string(os.PathSeparator) + "post-checkout")
	if err != nil {
		return cli.NewExitError("Unable to insatll Git post-checkout hook: "+err.Error(), 1)
	}
	fmt.Println("Post-checkout Git hook installed")

	return nil
}

func installGitHook(filepath string) error {
	f, err := os.OpenFile(filepath, os.O_CREATE|os.O_RDWR, 0755)
	if err != nil {
		return err
	}
	defer f.Close()

	i, sc := false, bufio.NewScanner(f)
	for sc.Scan() {
		if sc.Text() == CALL_GIM_GIT_HOOK_CODE {
			i = true
			break
		}
	}

	if i {
		return nil
	}

	_, err = f.WriteString(CALL_GIM_GIT_HOOK_CODE + "\n")
	return err
}


text:
/*** Included Header Files ***/
#include <UdmBase.h>
#include "Visitor.h"
#include "ConfigKeeper.h"

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

int main( int argc, char **argv ) {
	ConfigKeeper &config = ConfigKeeper::Inst();
	if ( !config.ProcessCmdLine( argc, argv )  ) return 1;
	// Process the model
	try {

		if ( config.GetParadigm() == string( "BIP" ) )
		{
			Udm::SmartDataNetwork sdn( BIP::diagram );
			sdn.OpenExisting( config.GetInfileName() );

			BIP::RootFolder brf = BIP::RootFolder::Cast(sdn.GetRootObject());
			TimeStamp ts;
			BIPVisitor bv( brf, ts );

			// Read-only access to input model
			sdn.CloseNoUpdate();
		}
		else if ( config.GetParadigm() == string( "ESMoL" ) )
		{
			Udm::SmartDataNetwork sdn( ESMoL::diagram );
			sdn.OpenExisting( config.GetInfileName() );

			//Get the root folder
			ESMoL::RootFolder erf = ESMoL::RootFolder::Cast(sdn.GetRootObject());

			// Read-only access to input model
			sdn.CloseNoUpdate();
		}

	} catch( udm_exception &ex )	{
		std::cout << "Exception occured in udm " << std::endl;
		std::cout << ex.what() << std::endl;
	}
	return 0;
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using ALinq.SqlClient;
using NpgsqlTypes;

namespace ALinq.PostgreSQL
{
    class PgsqlFormatter : DbFormatter
    {
        public PgsqlFormatter(SqlProvider sqlProvider)
            : base(sqlProvider)
        {
        }

        internal override SqlFormatter.Visitor CreateVisitor()
        {
            return new Visitor();
        }

        private class Visitor : SqlFormatter.Visitor
        {
            protected override void WriteName(string name)
            {
                if (SqlIdentifier.NeedToQuote(name))
                    sb.Append(SqlIdentifier.QuoteCompoundIdentifier(name));
                else
                    sb.Append(name);
            }

            internal override string GetBoolValue(bool value)
            {
                return value ? "true" : "false";
            }

            protected override SqlExpression TranslateConverter(SqlUnary uo)
            {
                //兼容类型,无需转换
                switch (((SqlDataType<NpgsqlDbType>)uo.SqlType).Category)
                {
                    case DBTypeCategory.Text:
                        if (uo.Operand.ClrType == typeof(char) || uo.Operand.ClrType == typeof(string))
                        {
                            Visit(uo.Operand);
                            return uo;
                        }
                        break;
                    case DBTypeCategory.Numeric:
                        //if (uo.Operand.ClrType == typeof(int) || uo.Operand.ClrType == typeof(Int16) ||
                        //   uo.Operand.ClrType == typeof(long) || uo.Operand.ClrType == typeof(byte))
                        if (uo.Operand.ClrType.IsValueType)
                        {
                            Visit(uo.Operand);
                            return uo;
                        }
                        break;
                }

                sb.Append("CAST(");
                QueryFormatOptions none = QueryFormatOptions.None;
                if (uo.Operand.SqlType.CanSuppressSizeForConversionToString)
                {
                    none = QueryFormatOptions.SuppressSize;
                }
                Visit(uo.Operand);
                sb.Append(" AS ");
                sb.Append(uo.SqlType.ToQueryString(none));
                sb.Append(")");
                return uo;
            }

            public override string GetOperator(SqlNodeType nt)
            {
                if (nt == SqlNodeType.LongCount)
                    return "COUNT";
                return base.GetOperator(nt);
            }

            internal override SqlExpression VisitUnaryOperator(SqlUnary uo)
            {

                if (uo.NodeType == SqlNodeType.Min || uo.NodeType == SqlNodeType.Max ||
                    uo.NodeType == SqlNodeType.Avg || uo.NodeType == SqlNodeType.Sum)
                {
                    Debug.Assert(uo.Operand != null);

                    sb.Append("COALESCE(");
                    sb.Append(GetOperator(uo.NodeType));
                    sb.Append("(");
                    Visit(uo.Operand);

                    //============================================================
                    // 说明:增加对类型的判断
                    var defaultValue = TypeSystem.GetDefaultValue(uo.ClrType);
                    if (defaultValue is DateTime)
                        sb.Append(string.Format("), CAST('{0}' AS DATE))", ((DateTime)defaultValue).ToShortDateString()));
                    else if (defaultValue is string)
                        sb.Append(string.Format("),'{0}')", defaultValue));
                    else
                        sb.Append(string.Format("),{0})", defaultValue));
                    //============================================================
                    //sb.Append("),0)"); 旧代码
                    //============================================================

                    return uo;
                }

                return base.VisitUnaryOperator(uo);
            }

            //将Select.Top等价于limit,将其后置。
            internal override SqlSelect VisitSelect(SqlSelect ss)
            {
                if (!ss.DoNotOutput)
                {
                    string str = null;
                    if (ss.From != null)
                    {
                        StringBuilder oldsb = this.sb;
                        this.sb = new StringBuilder();
                        if (this.IsSimpleCrossJoinList(ss.From))
                        {
                            this.VisitCrossJoinList(ss.From);
                        }
                        else
                        {
                            this.Visit(ss.From);
                        }
                        str = this.sb.ToString();
                        this.sb = oldsb;
                    }
                    this.sb.Append("SELECT ");
                    if (ss.IsDistinct)
                    {
                        this.sb.Append("DISTINCT ");
                    }

                    if (ss.Row.Columns.Count > 0)
                    {
                        this.VisitRow(ss.Row);
                    }
                    else if (this.isDebugMode)
                    {
                        this.Visit(ss.Selection);
                    }
                    else
                    {
                        sb.Append("NULL AS ");
                        sb.Append(SqlIdentifier.QuoteCompoundIdentifier("EMPTY"));
                    }
                    if (str != null)
                    {
                        this.NewLine();
                        this.sb.Append("FROM ");
                        this.sb.Append(str);
                    }
                    if (ss.Where != null)
                    {
                        this.NewLine();
                        this.sb.Append("WHERE ");
                        this.Visit(ss.Where);
                    }
                    if (ss.GroupBy.Count > 0)
                    {
                        this.NewLine();
                        this.sb.Append("GROUP BY ");
                        int num = 0;
                        int count = ss.GroupBy.Count;
                        while (num < count)
                        {
                            SqlExpression node = ss.GroupBy[num];
                            if (num > 0)
                            {
                                this.sb.Append(", ");
                            }
                            this.Visit(node);
                            num++;
                        }
                        if (ss.Having != null)
                        {
                            this.NewLine();
                            this.sb.Append("HAVING ");
                            this.Visit(ss.Having);
                        }
                    }
                    if ((ss.OrderBy.Count > 0) && (ss.OrderingType != SqlOrderingType.Never))
                    {
                        this.NewLine();
                        this.sb.Append("ORDER BY ");
                        int num3 = 0;
                        int num4 = ss.OrderBy.Count;
                        while (num3 < num4)
                        {
                            SqlOrderExpression expression2 = ss.OrderBy[num3];
                            if (num3 > 0)
                            {
                                this.sb.Append(", ");
                            }
                            this.Visit(expression2.Expression);
                            if (expression2.OrderType == SqlOrderType.Descending)
                            {
                                this.sb.Append(" DESC");
                            }
                            num3++;
                        }
                    }
                    //Select.Top后置!
                    if (ss.Top != null)
                    {
                        this.NewLine();
                        //this.sb.Append("LIMIT ");
                        this.Visit(ss.Top);
                        this.sb.Append(" ");
                    }
                }
                return ss;
            }

            internal override SqlExpression VisitBinaryOperator(SqlBinary bo)
            {
                if (bo.NodeType == SqlNodeType.Coalesce)
                {
                    this.sb.Append("COALESCE(");
                    this.Visit(bo.Left);
                    this.sb.Append(",");
                    this.Visit(bo.Right);
                    this.sb.Append(")");
                    return bo;
                }

                this.VisitWithParens(bo.Left, bo);
                this.sb.Append(" ");

                //将string + string的运算符转换为"||"
                if ((bo.NodeType == SqlNodeType.Concat || bo.NodeType == SqlNodeType.Add) &&
                    (bo.Left.ClrType == typeof(string) || bo.Left.ClrType == typeof(string)))
                    sb.Append("||");
                else
                    this.sb.Append(this.GetOperator(bo.NodeType));

                this.sb.Append(" ");
                this.VisitWithParens(bo.Right, bo);
                return bo;
            }
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Melanconiopsis africana Luc

### Remarks
null


text:
module CRubyExtension
  def CRubyExtension.ruby_method
    puts "A Ruby Extension"
  end
end


text:
package io.openliberty.tools.maven.server;

import static org.twdata.maven.mojoexecutor.MojoExecutor.artifactId;
import static org.twdata.maven.mojoexecutor.MojoExecutor.configuration;
import static org.twdata.maven.mojoexecutor.MojoExecutor.element;
import static org.twdata.maven.mojoexecutor.MojoExecutor.executeMojo;
import static org.twdata.maven.mojoexecutor.MojoExecutor.executionEnvironment;
import static org.twdata.maven.mojoexecutor.MojoExecutor.goal;
import static org.twdata.maven.mojoexecutor.MojoExecutor.groupId;
import static org.twdata.maven.mojoexecutor.MojoExecutor.name;
import static org.twdata.maven.mojoexecutor.MojoExecutor.plugin;
import static org.twdata.maven.mojoexecutor.MojoExecutor.version;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.PluginManagement;
import org.apache.maven.plugin.BuildPluginManager;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.tools.ant.taskdefs.Copy;
import org.apache.tools.ant.types.FileSet;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.twdata.maven.mojoexecutor.MojoExecutor.Element;

import io.openliberty.tools.ant.ServerTask;
import io.openliberty.tools.common.plugins.config.ServerConfigDropinXmlDocument;
import io.openliberty.tools.maven.BasicSupport;
import io.openliberty.tools.maven.utils.ExecuteMojoUtil;

/**
 * Start/Debug server support.
 */
public class StartDebugMojoSupport extends BasicSupport {

    private static final String LIBERTY_MAVEN_PLUGIN_GROUP_ID = "io.openliberty.tools";
    private static final String LIBERTY_MAVEN_PLUGIN_ARTIFACT_ID = "liberty-maven-plugin";
    protected static final String HEADER = "# Generated by liberty-maven-plugin";
    private static final String LIBERTY_CONFIG_MAVEN_PROPS = "(^liberty\\.(env|jvm|bootstrap|var|defaultVar)\\.).+";
    private static final Pattern pattern = Pattern.compile(LIBERTY_CONFIG_MAVEN_PROPS);

    private static boolean configFilesCopied = false;

    protected final String PLUGIN_VARIABLE_CONFIG_OVERRIDES_XML = "configDropins/overrides/liberty-plugin-variable-config.xml";
    protected final String PLUGIN_VARIABLE_CONFIG_DEFAULTS_XML = "configDropins/defaults/liberty-plugin-variable-config.xml";

    protected Map<String,String> bootstrapMavenProps = new HashMap<String,String>();
    protected Map<String,String> envMavenProps = new HashMap<String,String>();
    protected List<String> jvmMavenProps = new ArrayList<String>();
    protected Map<String,String> varMavenProps = new HashMap<String,String>();
    protected Map<String,String> defaultVarMavenProps = new HashMap<String,String>();

    protected Map<String,String> combinedBootstrapProperties = null;
    protected List<String> combinedJvmOptions = null;

    @Component
    protected BuildPluginManager pluginManager;

    /*
     * Define a set of dependencies to copy to the target Liberty server.
     */
    @Parameter
    protected CopyDependencies copyDependencies;

    /**
     * Location of customized configuration file server.xml
     */
    @Parameter(alias="configFile", property = "serverXmlFile")
    protected File serverXmlFile;

    /**
     * Location of bootstrap.properties file.
     */
    @Parameter(property = "bootstrapPropertiesFile")
    protected File bootstrapPropertiesFile;

    @Parameter
    protected Map<String, String> bootstrapProperties;

    /**
     * Location of jvm.options file.
     */
    @Parameter(property = "jvmOptionsFile")
    protected File jvmOptionsFile;

    @Parameter
    protected List<String> jvmOptions;

    /**
     * The current plugin's descriptor. This is auto-filled by Maven 3.
     */
    @Parameter( defaultValue = "${plugin}", readonly = true )
    private PluginDescriptor plugin;

    private enum PropertyType {
        BOOTSTRAP("liberty.bootstrap."),
        ENV("liberty.env."),
        JVM("liberty.jvm."),
        VAR("liberty.var."),
        DEFAULTVAR("liberty.defaultVar.");

        private final String prefix;

        private PropertyType(final String prefix) {
            this.prefix = prefix;
        }

        private static final Map<String, PropertyType> lookup = new HashMap<String, PropertyType>();

        static {
            for (PropertyType s : EnumSet.allOf(PropertyType.class)) {
               lookup.put(s.prefix, s);
            }
        }

        public static PropertyType getPropertyType(String propertyName) {
            // get a matcher object from pattern
            Matcher matcher = pattern.matcher(propertyName);

            // check whether Regex string is found in propertyName or not
            if (matcher.find()) {
                // strip off the end of the property name to get the prefix
                String prefix = matcher.group(1);
                return lookup.get(prefix);
            }
            return null;
        }

        public String getPrefix() {
            return prefix;
        }

    }

    protected ServerTask initializeJava() {
        ServerTask serverTask = (ServerTask) ant.createTask("antlib:io/openliberty/tools/ant:server");
        if (serverTask == null) {
            throw new IllegalStateException(MessageFormat.format(messages.getString("error.dependencies.not.found"), "server"));
        }
        serverTask.setInstallDir(installDirectory);
        serverTask.setServerName(serverName);
        serverTask.setUserDir(userDirectory);
        serverTask.setOutputDir(outputDirectory);
        return serverTask;
    }

    protected void runMojo(String groupId, String artifactId, String goal) throws MojoExecutionException {
        Plugin plugin = getPlugin(groupId, artifactId);
        Xpp3Dom config = ExecuteMojoUtil.getPluginGoalConfig(plugin, goal, log);
        log.info("Running " + artifactId + ":" + goal);
        log.debug("configuration:\n" + config);
        executeMojo(plugin, goal(goal), config,
                executionEnvironment(project, session, pluginManager));
    }

    /**
     * Given the groupId and artifactId get the corresponding plugin
     *
     * @param groupId
     * @param artifactId
     * @return Plugin
     */
    protected Plugin getPlugin(String groupId, String artifactId) {
        Plugin plugin = project.getPlugin(groupId + ":" + artifactId);
        if (plugin == null) {
            plugin = getPluginFromPluginManagement(groupId, artifactId);
        }
        if (plugin == null) {
            plugin = plugin(groupId(groupId), artifactId(artifactId), version("RELEASE"));
        }
        return plugin;
    }

    protected Plugin getLibertyPlugin() {
        // Try getting the version from Maven 3's plugin descriptor
        String version = null;
        if (plugin != null && plugin.getPlugin() != null) {
            version = plugin.getVersion();
            log.debug("Setting plugin version to " + version);
        }
        Plugin projectPlugin = project.getPlugin(LIBERTY_MAVEN_PLUGIN_GROUP_ID + ":" + LIBERTY_MAVEN_PLUGIN_ARTIFACT_ID);
        if (projectPlugin == null) {
            projectPlugin = getPluginFromPluginManagement(LIBERTY_MAVEN_PLUGIN_GROUP_ID, LIBERTY_MAVEN_PLUGIN_ARTIFACT_ID);
        }
        if (projectPlugin == null) {
            projectPlugin = plugin(LIBERTY_MAVEN_PLUGIN_GROUP_ID, LIBERTY_MAVEN_PLUGIN_ARTIFACT_ID, "LATEST");
        }
        if (version != null) {
            projectPlugin.setVersion(version);
        }
        return projectPlugin;
    }

    protected Plugin getPluginFromPluginManagement(String groupId, String artifactId) {
        Plugin retVal = null;
        PluginManagement pm = project.getPluginManagement();
        if (pm != null) {
            for (Plugin p : pm.getPlugins()) {
                if (groupId.equals(p.getGroupId()) && artifactId.equals(p.getArtifactId())) {
                    retVal = p;
                    break;
                }
            }
        }
        return retVal;
    }

    protected void runLibertyMojoCreate() throws MojoExecutionException {
        Xpp3Dom config = ExecuteMojoUtil.getPluginGoalConfig(getLibertyPlugin(), "create", log);
        runLibertyMojo("create", config);
    }

    protected void runLibertyMojoDeploy() throws MojoExecutionException {
        runLibertyMojoDeploy(true);
    }

    protected void runLibertyMojoDeploy(boolean forceLooseApp) throws MojoExecutionException {
        Xpp3Dom config = ExecuteMojoUtil.getPluginGoalConfig(getLibertyPlugin(), "deploy", log);
        if(forceLooseApp) {
            Xpp3Dom looseApp = config.getChild("looseApplication");
            if (looseApp != null && "false".equals(looseApp.getValue())) {
                log.warn("Overriding liberty plugin pararmeter, \"looseApplication\" to \"true\" and deploying application in looseApplication format");
                looseApp.setValue("true");
            }
        }
        runLibertyMojo("deploy", config);
    }

    protected void runLibertyMojoInstallFeature(Element features, String containerName) throws MojoExecutionException {
        Xpp3Dom config = ExecuteMojoUtil.getPluginGoalConfig(getLibertyPlugin(), "install-feature", log);;
        if (features != null) {
            config = Xpp3Dom.mergeXpp3Dom(configuration(features), config);
        }
        if (containerName != null) {
            config.addChild(element(name("containerName"), containerName).toDom());
        }
        runLibertyMojo("install-feature", config);
    }

    private void runLibertyMojo(String goal, Xpp3Dom config) throws MojoExecutionException {
        log.info("Running liberty:" + goal);
        log.debug("configuration:\n" + config);
        executeMojo(getLibertyPlugin(), goal(goal), config,
                executionEnvironment(project, session, pluginManager));
    }

    private void copyDependencies() throws Exception {
        if (copyDependencies != null) {
            List<Dependency> deps = copyDependencies.getDependencies();
            boolean defaultStripVersion = copyDependencies.isStripVersion();
            String defaultLocation = copyDependencies.getLocation();
            File dftLocationFile = new File(defaultLocation);

            if (!dftLocationFile.isAbsolute()) {
                // relative path
                dftLocationFile = new File(serverDirectory,defaultLocation);
            }

            if (!dftLocationFile.exists()) {
                dftLocationFile.mkdirs();
            } else if (!dftLocationFile.isDirectory()) {
                // send config error
                throw new MojoExecutionException("The copyDependencies location "+ dftLocationFile.getCanonicalPath() +" is not a directory.");
            }

            String dftLocationPath = dftLocationFile.getCanonicalPath();

            if (!deps.isEmpty()) {
                log.debug("copyDependencies to location: "+dftLocationPath);
            }

            for (Dependency dep : deps) {
                copyDependencies(dep, null, dftLocationPath, defaultStripVersion);
            }

            List<DependencyGroup> depGroups = copyDependencies.getDependencyGroups();

            for (DependencyGroup depGroup : depGroups) {
                String overrideLocation = depGroup.getLocation();
                if (overrideLocation != null) {
                    log.debug("copyDependencies to location: "+ overrideLocation);
                } else {
                    log.debug("copyDependencies to location: "+dftLocationPath);
                }
                boolean stripVersion = defaultStripVersion;
                Boolean overrideStripVersion = depGroup.getStripVersion();
                if (overrideStripVersion != null) {
                    stripVersion = overrideStripVersion.booleanValue();
                }
                List<Dependency> groupDeps = depGroup.getDependencies();
                for (Dependency dep : groupDeps) {
                    copyDependencies(dep, overrideLocation, dftLocationPath, stripVersion);
                }
            }

        }
    }

    private void copyDependencies(Dependency dep, String overrideLocation, String defaultLocation, boolean stripVersion) throws Exception {

        String location = defaultLocation;

        if (overrideLocation != null) {
            File overrideLocationFile = new File(overrideLocation);
            if (!overrideLocationFile.isAbsolute()) {
                // relative path
                overrideLocationFile = new File(serverDirectory, overrideLocation);
            }

            location = overrideLocationFile.getCanonicalPath();

            if (!overrideLocationFile.exists()) {
                overrideLocationFile.mkdirs();
            } else if (!overrideLocationFile.isDirectory()) {
                // send config error
                log.warn("The specified dependency location "+ overrideLocationFile.getCanonicalPath() +" is not a directory. Using default copyDependencies location "+ defaultLocation +" instead.");
                location = defaultLocation;
            }
        }

        Set<Artifact> artifactsToCopy = getResolvedDependencyWithTransitiveDependencies(dep.getGroupId(), dep.getArtifactId(), dep.getVersion(), dep.getType());

        if (artifactsToCopy.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            sb.append("copyDependencies failed for dependency with groupId "+ dep.getGroupId());
            String artifactId = dep.getArtifactId();
            if (artifactId != null) {
                sb.append(", artifactId "+artifactId);
            }
            String version = dep.getVersion();
            if (version != null) {
                sb.append(", version "+ version);
            }
            sb.append(" and type "+dep.getType());
            sb.append(". No matching resolved dependencies were found.");

            log.warn(sb.toString());
        } else {
            for (Artifact nextArtifact : artifactsToCopy) {
                File nextFile = nextArtifact.getFile();
                String targetFileName = nextFile.getName();
                if (stripVersion) {
                    targetFileName = stripVersionFromName(targetFileName, nextArtifact.getVersion());
                }

                File fileToCopyTo = new File(location, targetFileName);

                Copy copy = (Copy) ant.createTask("copy");
                copy.setFile(nextFile);
                copy.setTofile(fileToCopyTo);
                copy.setOverwrite(true);
                copy.execute();

                log.info("copyDependencies copied file "+nextFile.getName()+" to location "+location+"/"+targetFileName+".");
            }
        }
    }

    /**
     * @throws Exception
     */
    protected void copyConfigFiles() throws Exception {

        String jvmOptionsPath = null;
        String bootStrapPropertiesPath = null;
        String serverEnvPath = null;
        String serverXMLPath = null;

        // First check for Liberty configuration specified by Maven properties.
        loadLibertyConfigFromProperties();

        if (configDirectory != null && configDirectory.exists()) {
            // copy configuration files from configuration directory to server directory if end-user set it
            Copy copydir = (Copy) ant.createTask("copy");
            FileSet fileset = new FileSet();
            fileset.setDir(configDirectory);

            // If mergeServerEnv is true, don't overwrite generated server.env
            File configDirServerEnv = new File(configDirectory, "server.env");
            if(mergeServerEnv && configDirServerEnv.exists()){
                // set excludes pattern
                fileset.setExcludes("server.env");
            }

            copydir.addFileset(fileset);
            copydir.setTodir(serverDirectory);
            copydir.setOverwrite(true);
            copydir.execute();

            File configDirServerXML = new File(configDirectory, "server.xml");
            if (configDirServerXML.exists()) {
                serverXMLPath = configDirServerXML.getCanonicalPath();
            }

            File configDirJvmOptionsFile = new File(configDirectory, "jvm.options");
            if (configDirJvmOptionsFile.exists()) {
                jvmOptionsPath = configDirJvmOptionsFile.getCanonicalPath();
            }

            File configDirBootstrapFile = new File(configDirectory, "bootstrap.properties");
            if (configDirBootstrapFile.exists()) {
                bootStrapPropertiesPath = configDirBootstrapFile.getCanonicalPath();
            }

            if (configDirServerEnv.exists()) {
                serverEnvPath = configDirServerEnv.getCanonicalPath();
            }
        }

        // copy server.xml file to server directory if end-user explicitly set it.
        if (serverXmlFile != null && serverXmlFile.exists()) {
            if (serverXMLPath != null && ! serverXmlFile.getCanonicalPath().equals(serverXMLPath)) {
                log.warn("The " + serverXMLPath + " file is overwritten by the "+serverXmlFile.getCanonicalPath()+" file.");
            }
            Copy copy = (Copy) ant.createTask("copy");
            copy.setFile(serverXmlFile);
            copy.setTofile(new File(serverDirectory, "server.xml"));
            copy.setOverwrite(true);
            copy.execute();
            serverXMLPath = serverXmlFile.getCanonicalPath();
        }

        // copy jvm.options to server directory if end-user explicitly set it
        File optionsFile = new File(serverDirectory, "jvm.options");
        if (optionsFile.exists() && jvmOptionsPath == null) {
            optionsFile.delete();
        }
        if (jvmOptions != null || !jvmMavenProps.isEmpty()) {
            if (jvmOptionsPath != null) {
                log.warn("The " + jvmOptionsPath + " file is overwritten by inlined configuration.");
            }
            writeJvmOptions(optionsFile, jvmOptions, jvmMavenProps);
            jvmOptionsPath = "inlined configuration";
        } else if (jvmOptionsFile != null && jvmOptionsFile.exists()) {
            if (jvmOptionsPath != null) {
                log.warn("The " + jvmOptionsPath + " file is overwritten by the "+jvmOptionsFile.getCanonicalPath()+" file.");
            }
            Copy copy = (Copy) ant.createTask("copy");
            copy.setFile(jvmOptionsFile);
            copy.setTofile(optionsFile);
            copy.setOverwrite(true);
            copy.execute();
            jvmOptionsPath = jvmOptionsFile.getCanonicalPath();
        }

        // copy bootstrap.properties to server directory if end-user explicitly set it
        File bootstrapFile = new File(serverDirectory, "bootstrap.properties");
        if (bootstrapFile.exists() && bootStrapPropertiesPath == null) {
            bootstrapFile.delete();
        }
        if (bootstrapProperties != null || !bootstrapMavenProps.isEmpty()) {
            if (bootStrapPropertiesPath != null) {
                log.warn("The " + bootStrapPropertiesPath + " file is overwritten by inlined configuration.");
            }
            writeBootstrapProperties(bootstrapFile, bootstrapProperties, bootstrapMavenProps);
            bootStrapPropertiesPath = "inlined configuration";
        } else if (bootstrapPropertiesFile != null && bootstrapPropertiesFile.exists()) {
            if (bootStrapPropertiesPath != null) {
                log.warn("The " + bootStrapPropertiesPath + " file is overwritten by the "+ bootstrapPropertiesFile.getCanonicalPath()+" file.");
            }
            Copy copy = (Copy) ant.createTask("copy");
            copy.setFile(bootstrapPropertiesFile);
            copy.setTofile(bootstrapFile);
            copy.setOverwrite(true);
            copy.execute();
            bootStrapPropertiesPath = bootstrapPropertiesFile.getCanonicalPath();
        }

        // copy server.env to server directory if end-user explicitly set it
        File envFile = new File(serverDirectory, "server.env");
        if(mergeServerEnv) {
            serverEnvPath = mergeServerEnvFileAndEnvMavenProps(serverEnvPath);
        }
        else {
            if (!envMavenProps.isEmpty()) {
                Map<String,String> envPropsToWrite = envMavenProps;
                if (serverEnvFile == null && serverEnvPath == null) {
                    // Do a special case merge but ONLY if there are no other config options present
                    envPropsToWrite = mergeSpecialPropsFromInstallServerEnvIfAbsent(envMavenProps);
                } else if (serverEnvPath != null) {
                    log.warn("The " + serverEnvPath + " file is overwritten by inlined configuration.");
                }
                writeServerEnvProperties(envFile, envPropsToWrite);
                serverEnvPath = "inlined configuration";
            } else if (serverEnvFile != null && serverEnvFile.exists()) {
                Copy copy = (Copy) ant.createTask("copy");
                copy.setFile(serverEnvFile);
                copy.setTofile(envFile);
                copy.setOverwrite(true);
                copy.execute();
                serverEnvPath = serverEnvFile.getCanonicalPath();
            }
        }

        File pluginVariableConfig = new File(serverDirectory, PLUGIN_VARIABLE_CONFIG_OVERRIDES_XML);
        if (pluginVariableConfig.exists()) {
            pluginVariableConfig.delete();
        }
        if (!varMavenProps.isEmpty()) {
            writeConfigDropinsServerVariables(pluginVariableConfig, varMavenProps, false);
        }

        pluginVariableConfig = new File(serverDirectory, PLUGIN_VARIABLE_CONFIG_DEFAULTS_XML);
        if (pluginVariableConfig.exists()) {
            pluginVariableConfig.delete();
        }
        if (!defaultVarMavenProps.isEmpty()) {
            writeConfigDropinsServerVariables(pluginVariableConfig, defaultVarMavenProps, true);
        }

        // log info on the configuration files that get used
        if (serverXMLPath != null && !serverXMLPath.isEmpty()) {
            log.info(MessageFormat.format(messages.getString("info.server.start.update.config"),
                "server.xml", serverXMLPath));
        }
        if (jvmOptionsPath != null && !jvmOptionsPath.isEmpty()) {
            log.info(MessageFormat.format(messages.getString("info.server.start.update.config"),
                "jvm.options", jvmOptionsPath));
        }
        if (bootStrapPropertiesPath != null && !bootStrapPropertiesPath.isEmpty()) {
            log.info(MessageFormat.format(messages.getString("info.server.start.update.config"),
                "bootstrap.properties", bootStrapPropertiesPath));
        }
        if (serverEnvPath != null && !serverEnvPath.isEmpty()) {
            log.info(MessageFormat.format(messages.getString("info.server.start.update.config"),
                "server.env", serverEnvPath));
        }

        configFilesCopied = true;

        // Now process the copyDependencies configuration
        copyDependencies();
    }

    /**
     * Merges envProps with special properties found in the install (target) server.env.  We return a clone/copy of
     * envProps, to which any of a list of special properties found in server.env have been added.  We give precedence
     * to properties already in envProps.
     */
    private Map<String, String> mergeSpecialPropsFromInstallServerEnvIfAbsent(Map<String, String> envProps) throws IOException {

        String[] specialProps = { "keystore_password" };

        // Clone to avoid side effects
        Map<String, String> mergedProps = new HashMap<String,String>(envProps);

        // From install (target) dir
        File serverEnv = new File(serverDirectory, "server.env");
        Map<String, String> serverEnvProps = convertServerEnvToProperties(serverEnv);

        for (String propertyName : specialProps) {
            if (serverEnvProps.containsKey(propertyName)) {
                mergedProps.putIfAbsent(propertyName,serverEnvProps.get(propertyName));
            }
        }

        return mergedProps;
    }

    // Merges configured serverEnvFile with envMavenProps if specified, and returns the updated serverEnvPath
    private String mergeServerEnvFileAndEnvMavenProps(String serverEnvPath) throws IOException {
        String modifiedServerEnvPath = serverEnvPath;
        boolean mergeRequired = serverEnvPath != null ||
                                (serverEnvFile != null && serverEnvFile.exists()) ||
                                !envMavenProps.isEmpty();

        if (mergeRequired) {
            File serverEnv = new File(serverDirectory, "server.env");
            Map<String, String> serverEnvProps = convertServerEnvToProperties(serverEnv);

            // merge configDir serverEnv if present
            if (serverEnvPath!= null) {
                File configDirServerEnv = new File(configDirectory, "server.env");
                Map<String, String> configDirServerEnvProps = convertServerEnvToProperties(configDirServerEnv);
                serverEnvProps.putAll(configDirServerEnvProps);
            }

            //merge specified server.env if present
            if (serverEnvFile != null && serverEnvFile.exists()) {
                Map<String, String> serverEnvFileProps = convertServerEnvToProperties(serverEnvFile);
                serverEnvProps.putAll(serverEnvFileProps);
            }

            //merge server env props
            if (!envMavenProps.isEmpty()) {
                serverEnvProps.putAll(envMavenProps);
            }

            writeServerEnvProperties(serverEnv, serverEnvProps);
            modifiedServerEnvPath = getMergedServerEnvPath(serverEnvPath);
        }

        return modifiedServerEnvPath;
    }

    private String getMergedServerEnvPath(String serverEnvPath) throws IOException {
        boolean configDirEnvMerged = serverEnvPath != null;
        boolean serverEnvFileMerged = serverEnvFile != null && serverEnvFile.exists();
        boolean inlineEnvPropsMerged = !envMavenProps.isEmpty();

        StringBuilder updatedServerEnvPath = new StringBuilder("merging");

        if(configDirEnvMerged) {
            updatedServerEnvPath.append(" configDir server.env " +  serverEnvPath + ", ");
        }
        if (serverEnvFileMerged) {
            updatedServerEnvPath.append(" serverEnvFile " +  serverEnvFile.getCanonicalPath() + ", ");
        }
        if (inlineEnvPropsMerged) {
            updatedServerEnvPath.append(" env properties, ");
        }
        // remove excess comma and space
        int lastCommaIndex = updatedServerEnvPath.lastIndexOf(", ");
        updatedServerEnvPath = updatedServerEnvPath.replace(lastCommaIndex, lastCommaIndex + 2, ".");

        //replace last comma and space with and
        lastCommaIndex = updatedServerEnvPath.lastIndexOf(", ");
        if(lastCommaIndex > 0) {
            updatedServerEnvPath = updatedServerEnvPath.replace(lastCommaIndex, lastCommaIndex + 2, "");
            updatedServerEnvPath = updatedServerEnvPath.insert(lastCommaIndex, " and");
        }

        return updatedServerEnvPath.toString();
    }

    private Map<String, String> convertServerEnvToProperties(File serverEnv) throws IOException {
        Map<String, String> mavenProperties = new HashMap<String, String>();

        if ((serverEnv == null) || !serverEnv.exists()) {
            return mavenProperties;
        }

        BufferedReader bf = new BufferedReader(new FileReader(serverEnv));
        String line;
        while((line = bf.readLine()) != null) {

            //Skip comments
            if(!line.startsWith("#")) {
                String[] keyValue = line.split("=", 2);
                String key = keyValue[0];
                String value = keyValue[1];

                mavenProperties.put(key,value);
            }
        }

        return mavenProperties;
    }

    private void loadLibertyConfigFromProperties() {

        loadLibertyConfigFromProperties(project.getProperties());
        loadLibertyConfigFromProperties(System.getProperties());

    }

    private void loadLibertyConfigFromProperties(Properties props) {
        Set<Entry<Object, Object>> entries = props.entrySet();
        for (Entry<Object, Object> entry : entries) {
            String key = (String) entry.getKey();
            PropertyType propType = PropertyType.getPropertyType(key);

            if (propType != null) {
                String suffix = key.substring(propType.getPrefix().length());
                String value = (String) entry.getValue();
                log.debug("Processing Liberty configuration from property with key "+key+" and value "+value);
                switch (propType) {
                    case ENV:        envMavenProps.put(suffix, value);
                                     break;
                    case BOOTSTRAP:  bootstrapMavenProps.put(suffix, value);
                                     break;
                    case JVM:        jvmMavenProps.add(value);
                                     break;
                    case VAR:        varMavenProps.put(suffix, value);
                                     break;
                    case DEFAULTVAR: defaultVarMavenProps.put(suffix, value);
                                     break;
                }
            }
        }
    }

    // The properties parameter comes from the <bootstrapProperties> configuration in pom.xml and takes precedence over
    // the mavenProperties parameter, which comes from generic maven <properties> configuration.
    // One of the passed in Maps must be not null and not empty
    private void writeBootstrapProperties(File file, Map<String, String> properties, Map<String, String> mavenProperties) throws IOException {
        if (!mavenProperties.isEmpty()) {
            if (properties == null) {
                combinedBootstrapProperties = mavenProperties;
            } else {
                combinedBootstrapProperties = new HashMap<String,String> ();
                // add the maven properties first so that they do not take precedence over the properties specified with <bootstrapProperties>
                combinedBootstrapProperties.putAll(mavenProperties);
                combinedBootstrapProperties.putAll(properties);
            }
        } else {
            combinedBootstrapProperties = properties;
        }

        makeParentDirectory(file);
        PrintWriter writer = null;
        try {
            writer = new PrintWriter(file, "UTF-8");
            writer.println(HEADER);
            for (Map.Entry<String, String> entry : combinedBootstrapProperties.entrySet()) {
                String key = entry.getKey();
                writer.print(key);
                writer.print("=");
                String value = entry.getValue();

                writer.println((value != null) ? value.replace("\\", "/") : "");
                if (value == null) {
                    log.warn("The value of the bootstrap property " + key + " is null. Verify if the needed POM properties are set correctly.");
                }
            }
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    private void writeServerEnvProperties(File file, Map<String, String> mavenProperties) throws IOException {
        makeParentDirectory(file);
        PrintWriter writer = null;
        try {
            writer = new PrintWriter(file, "UTF-8");
            writer.println(HEADER);
            for (Map.Entry<String, String> entry : mavenProperties.entrySet()) {
                String key = entry.getKey();
                writer.print(key);
                writer.print("=");
                String value = entry.getValue();
                writer.println((value != null) ? value.replace("\\", "/") : "");
                if (value == null) {
                    log.warn("The value of the server.env property " + entry.getKey() + " is null. Verify if the needed POM properties are set correctly.");
                }
            }
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    // One of the passed in Lists must be not null and not empty
    private void writeJvmOptions(File file, List<String> options, List<String> mavenProperties) throws IOException {
        if (!mavenProperties.isEmpty()) {
            if (options == null) {
                combinedJvmOptions = mavenProperties;
            } else {
                combinedJvmOptions = new ArrayList<String> ();
                // add the maven properties first so that they do not take precedence over the options specified with jvmOptions
                combinedJvmOptions.addAll(mavenProperties);
                combinedJvmOptions.addAll(options);
            }
        } else {
            combinedJvmOptions = options;
        }

        makeParentDirectory(file);
        PrintWriter writer = null;
        try {
            writer = new PrintWriter(file, "UTF-8");
            writer.println(HEADER);
            for (String option : combinedJvmOptions) {
                writer.println(option);
            }
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    private void writeConfigDropinsServerVariables(File file, Map<String,String> props, boolean isDefaultVar) throws IOException, TransformerException, ParserConfigurationException {

        ServerConfigDropinXmlDocument configDocument = ServerConfigDropinXmlDocument.newInstance();

        configDocument.createComment(HEADER);

        for (Map.Entry<String, String> entry : props.entrySet()) {
            configDocument.createVariableWithValue(entry.getKey(), entry.getValue(), isDefaultVar);
        }

        // write XML document to file
        makeParentDirectory(file);
        configDocument.writeXMLDocument(file);

    }

    private void makeParentDirectory(File file) {
        File parentDir = file.getParentFile();
        if (parentDir != null) {
            parentDir.mkdirs();
        }
    }

    public static boolean isConfigCopied() {
        return configFilesCopied;
    }
}


text:
import datetime
import pytz

try:
    from django.contrib.sites.requests import RequestSite
except ImportError:  # Django < 1.9
    from django.contrib.sites.models import RequestSite

from django.core.exceptions import ObjectDoesNotExist
from django.forms.models import model_to_dict
from django.shortcuts import render_to_response, get_object_or_404
from django.utils.timezone import now, make_aware

from graphite.compat import HttpResponse, JsonResponse
from graphite.util import json, epoch
from graphite.events.models import Event
from graphite.render.attime import parseATTime

class EventEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return epoch(obj)
        return json.JSONEncoder.default(self, obj)

def view_events(request):
    if request.method == 'GET':
        context = {'events': fetch(request),
                   'site': RequestSite(request),
                   'protocol': 'https' if request.is_secure() else 'http'}
        return render_to_response('events.html', context)
    else:
        return post_event(request)

def detail(request, event_id):
    if request.META['HTTP_ACCEPT'] == 'application/json':
        try:
           e = Event.objects.get(id=event_id)
           e.tags = e.tags.split()
           response = JsonResponse(model_to_dict(e))
           return response
        except ObjectDoesNotExist:
           error = {'error': 'Event matching query does not exist'}
           response = JsonResponse(error, status=404)
           return response
    else:
        e = get_object_or_404(Event, pk=event_id)
        context = {'event': e}
        return render_to_response('event.html', context)

def post_event(request):
    if request.method == 'POST':
        event = json.loads(request.body)
        assert isinstance(event, dict)

        tags = event.get('tags')
        if tags:
            if not isinstance(tags, list):
                return HttpResponse(
                    json.dumps({'error': '"tags" must be an array'}),
                    status=400)
            tags = ' '.join(tags)
        if 'when' in event:
            when = make_aware(
                datetime.datetime.utcfromtimestamp(
                    event.get('when')), pytz.utc)
        else:
            when = now()

        Event.objects.create(
            what=event.get('what'),
            tags=tags,
            when=when,
            data=event.get('data', ''),
        )

        return HttpResponse(status=200)
    else:
        return HttpResponse(status=405)

def get_data(request):
    query_params = request.GET.copy()
    query_params.update(request.POST)

    if 'jsonp' in query_params:
        response = HttpResponse(
          "%s(%s)" % (query_params.get('jsonp'),
              json.dumps(fetch(request), cls=EventEncoder)),
          content_type='text/javascript')
    else:
        response = HttpResponse(
            json.dumps(fetch(request), cls=EventEncoder),
            content_type='application/json')
    return response

def fetch(request):
    if request.GET.get('from') is not None:
        time_from = parseATTime(request.GET['from'])
    else:
        time_from = datetime.datetime.fromtimestamp(0)

    if request.GET.get('until') is not None:
        time_until = parseATTime(request.GET['until'])
    else:
        time_until = now()

    set_operation = request.GET.get('set')

    tags = request.GET.get('tags')
    if tags is not None:
        tags = request.GET.get('tags').split(' ')

    result = []
    for x in Event.find_events(time_from, time_until, tags=tags, set_operation=set_operation):

        # django-tagging's with_intersection() returns matches with unknown tags
        # this is a workaround to ensure we only return positive matches
        if set_operation == 'intersection':
            if len(set(tags) & set(x.as_dict()['tags'])) == len(tags):
                result.append(x.as_dict())
        else:
            result.append(x.as_dict())
    return result


text:
.class public interface abstract Landroid/webkit/HtmlComposerView$RichTextFormatChangedListener;
.super Ljava/lang/Object;
.source "HtmlComposerView.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/webkit/HtmlComposerView;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x609
    name = "RichTextFormatChangedListener"
.end annotation

# static fields
.field public static final RICH_TOOL_BAR_DISABLE_CLEAR:I = 0x0

.field public static final RICH_TOOL_BAR_ENABLE:I = 0x2

.field public static final RICH_TOOL_BAR_ONLY_DISABLE:I = 0x1

# virtual methods
.method public abstract onChanged(I)V
.end method


text:
package org.apache.commons.httpclient.contrib.auth;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.auth.AuthChallengeException;
import org.apache.commons.httpclient.auth.AuthScheme;
import org.apache.commons.httpclient.auth.AuthenticationException;
import org.apache.commons.httpclient.auth.CredentialsNotAvailableException;
import org.apache.commons.httpclient.auth.InvalidCredentialsException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ietf.jgss.GSSContext;
import org.ietf.jgss.GSSException;
import org.ietf.jgss.GSSManager;
import org.ietf.jgss.GSSName;
import org.ietf.jgss.Oid;

/**
 *
 * @author Mikael Wilstrom
 * @author Mikael Wikstrom
 */
public class NegotiateScheme implements AuthScheme {

    /** Log object for this class. */
    private static final Log LOG = LogFactory.getLog(NegotiateScheme.class);

    /** challenge string. */
    private String challenge = null;

    private static final int UNINITIATED         = 0;
    private static final int INITIATED           = 1;
    private static final int NEGOTIATING         = 3;
    private static final int ESTABLISHED         = 4;
    private static final int FAILED              = Integer.MAX_VALUE;

    private GSSContext context = null;

    /** Authentication process state */
    private int state;

    /** base64 decoded challenge **/
    byte[] token = new byte[0];

    /**
     * Init GSSContext for negotiation.
     *
     * @param server servername only (e.g: radar.it.su.se)
     */
    protected void init(String server) throws GSSException {
         LOG.debug("init " + server);
         /* Kerberos v5 GSS-API mechanism defined in RFC 1964. */
         Oid krb5Oid = new Oid("1.2.840.113554.1.2.2");
         GSSManager manager = GSSManager.getInstance();
         GSSName serverName = manager.createName("HTTP/"+server, null);
         context = manager.createContext(serverName, krb5Oid, null,
                                    GSSContext.DEFAULT_LIFETIME);
         context.requestMutualAuth(true);
         context.requestCredDeleg(true);
         state = INITIATED;
    }

    /**
     * Default constructor for the Negotiate authentication scheme.
     *
     * @since 3.0
     */
    public NegotiateScheme() {
        super();
        state = UNINITIATED;
    }

    /**
     * Constructor for the Negotiate authentication scheme.
     *
     * @param challenge The authentication challenge
     */
    public NegotiateScheme(final String challenge) {
        super();
        LOG.debug("enter NegotiateScheme("+challenge+")");
        processChallenge(challenge);
    }

    /**
     * Processes the Negotiate challenge.
     *
     * @param challenge the challenge string
     *
     * @since 3.0
     */
    public void processChallenge(final String challenge){
        LOG.debug("enter processChallenge(challenge=\""+challenge+"\")");
        if (challenge.startsWith("Negotiate")) {
            if(isComplete() == false)
                state = NEGOTIATING;

            if (challenge.startsWith("Negotiate "))
                token = new Base64().decode(challenge.substring(10).getBytes());
            else
                token = new byte[0];
        }
    }

    /**
     * Tests if the Negotiate authentication process has been completed.
     *
     * @return <tt>true</tt> if authorization has been processed,
     *   <tt>false</tt> otherwise.
     *
     * @since 3.0
     */
    public boolean isComplete() {
        LOG.debug("enter isComplete()");
        return this.state == ESTABLISHED || this.state == FAILED;
    }

    /**
     * Returns textual designation of the Negotiate authentication scheme.
     *
     * @return Negotiate
     */
    public String getSchemeName() {
        return "Negotiate";
    }

    /**
     * The concept of an authentication realm is not supported by the Negotiate
     * authentication scheme. Always returns null.
     *
     * @return null
     */
    public String getRealm() {
        return null;
    }

    /**
     * Returns a String identifying the authentication challenge.  This is
     * used, in combination with the host and port to determine if
     * authorization has already been attempted or not.  Schemes which
     * require multiple requests to complete the authentication should
     * return a different value for each stage in the request.
     *
     *
Additionally, the ID should take into account any changes to the
     * authentication challenge and return a different value when appropriate.
     * For example when the realm changes in basic authentication it should be
     * considered a different authentication attempt and a different value should
     * be returned.

     *
     * @return String a String identifying the authentication challenge.  The
     * returned value may be null.
     *
     * @deprecated no longer used
     */
    public String getID() {
        LOG.debug("enter getID(): " + challenge);
        return challenge;
    }

    /**
     * Returns the authentication parameter with the given name, if available.
     *
     *
There are no valid parameters for Negotiate authentication so this
     * method always returns <tt>null</tt>.

     *
     * @param name The name of the parameter to be returned
     *
     * @return the parameter with the given name
     */
    public String getParameter(String name) {
        LOG.debug("enter getParameter("+name+")");
        if (name == null) {
            throw new IllegalArgumentException("Parameter name may not be null");
        }
        return null;
    }

    /**
     * Returns <tt>true</tt>.
     * Negotiate authentication scheme is connection based.
     *
     * @return <tt>true</tt>.
     *
     * @since 3.0
     */
    public boolean isConnectionBased() {
        LOG.info("enter isConnectionBased()");
        return true;
    }

    /**
     * Method not supported by Negotiate scheme.
     *
     * @throws AuthenticationException if called.
     *
     * @deprecated Use {@link #authenticate(Credentials, HttpMethod)}
     */
    public String authenticate(Credentials credentials, String method, String uri)
      throws AuthenticationException {
        throw new AuthenticationException("method not supported by Negotiate scheme");
    }

    /**
     * Produces Negotiate authorization string based on token created by
     * processChallenge.
     *
     * @param credentials Never used be the Negotiate scheme but must be provided to
     * satisfy common-httpclient API. Credentials from JAAS will be used insted.
     * @param method The method being authenticated
     *
     * @throws AuthenticationException if authorization string cannot
     *   be generated due to an authentication failure
     *
     * @return an Negotiate authorization string
     *
     * @since 3.0
     */
    public String authenticate(
        Credentials credentials,
        HttpMethod method
    ) throws AuthenticationException {
        LOG.debug("enter NegotiateScheme.authenticate(Credentials, HttpMethod)");

        if (state == UNINITIATED) {
            throw new IllegalStateException(
               "Negotiation authentication process has not been initiated");
        }

        try {
            try {
                if(context==null) {
                    LOG.info("host: " + method.getURI().getHost());
                    init( method.getURI().getHost() );
                }
            } catch (org.apache.commons.httpclient.URIException urie) {
                LOG.error(urie.getMessage());
                state = FAILED;
                throw new AuthenticationException(urie.getMessage());
            }

            // HTTP 1.1 issue:
            // Mutual auth will never complete do to 200 insted of 401 in
            // return from server. "state" will never reach ESTABLISHED
            // but it works anyway
            token = context.initSecContext(token, 0, token.length);
            LOG.info("got token, sending " + token.length + " to server");
        } catch (GSSException gsse) {
            LOG.fatal(gsse.getMessage());
            state = FAILED;
            if( gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL
                    || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED )
                throw new InvalidCredentialsException(gsse.getMessage(),gsse);
            if( gsse.getMajor() == GSSException.NO_CRED )
                throw new CredentialsNotAvailableException(gsse.getMessage(),gsse);
            if( gsse.getMajor() == GSSException.DEFECTIVE_TOKEN
                    || gsse.getMajor() == GSSException.DUPLICATE_TOKEN
                    || gsse.getMajor() == GSSException.OLD_TOKEN )
                throw new AuthChallengeException(gsse.getMessage(),gsse);
            // other error
            throw new AuthenticationException(gsse.getMessage());
        }
        return "Negotiate " + new String(new Base64().encode(token));
    }
}


text:
//=============================================================================
//  THIS SOURCE CODE IS PROPRIETARY INFORMATION BELONGING TO INTERVIDEO, INC.
//  ANY USE INCLUDING BUT NOT LIMITED TO COPYING OF CODE, CONCEPTS, AND/OR
//  ALGORITHMS IS PROHIBITED EXCEPT WITH EXPRESS WRITTEN PERMISSION BY THE
//  COMPANY.
//
//  THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
//  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
//  PURPOSE.
//
//  Copyright (c) 1998 - 2006  InterVideo Corporation.  All Rights Reserved.
//
//-----------------------------------------------------------------------------
#ifndef _IVI_BREAKPOINT_DETECT_H
#define _IVI_BREAKPOINT_DETECT_H

#include "IVITrWinDef.h"
#include "IVITRComm.h"

NS_TRLIB_BEGIN

///*!
// [Internal function. Do not call it.]
//
// Check has break point at specified memory address.
//
// Return value - [bool] true is exist, false is not.
//
// -#address - [IN] function memory address for checking break point.
//
// Supported platform: All Windows/Linux
//*/
bool __cdecl IsBPX(void* address);

///*!
// [Internal function. Do not call it.]
//
// Check has break point at specified memory address.
//
// Return value - [bool] true is exist, false is not.
//
// -#address - [IN] function memory address for checking break point.
//
// Supported platform: All Windows/Linux
//*/
bool __cdecl IsBPX_v2(void* address);

NS_TRLIB_END

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

///*!
// Check has break point at specified memory address. This can use to check if a potential debugger is debugging current program.
//
// Return value - None
//
// -#bool_variable - [IN/OUT] get return value, true is exist, or not.
// -#dword_variable - [IN] function memory address for checking break point.
//
// Supported platform:		All Windows/Linux
// Performance overhead:	Low
// Security level:			Low
// Usage scope:				Macro scope
//*/
#define iviTR_MEMORY_ADDRESS_BREAKPOINT_DETECT(bool_variable, dword_variable)\
{bool_variable =  IsBPX_v2(dword_variable); iviTR_DUMP_ERROR_TR_MACRO_ENTRY(bool_variable, iviTR_MEMORY_ADDRESS_BREAKPOINT_DETECT)}

#endif // _IVI_BREAKPOINT_DETECT_H


text:
const TMDB_API = "https://api.themoviedb.org/3/";
const SEARCH_API = `${TMDB_API}search/`;

export default {
  appSettings: {

  },
  endpoints: {
    MOVIE_SEARCH_API: `${SEARCH_API}movie?api_key=`,
    PEOPLE_SEARCH_API: `${SEARCH_API}person?api_key=`,
    TVSHOW_SEARCH_API: `${SEARCH_API}tv?api_key=`,
    COLLECTION_SEARCH_API: `${SEARCH_API}collection?api_key=`,
    TMDB_CONFIGURATION_API: `${TMDB_API}configuration?api_key=`,
    ISO639_1_SRC: "http://data.okfn.org/data/core/language-codes/r/language-codes.json",
    ISO3166_1_SRC: "http://data.okfn.org/data/core/country-list/r/data.json"
  }
};


text:
public class Spinach implements Veggies {

  public String toString() {
    return "Spinach";
  }
}