text:
//
//  Utilities.h
//  thermaleraser
//
//  Created by Mark Larus on 10/30/12.
//  Copyright (c) 2012 Kenyon College. All rights reserved.
//

#ifndef __thermaleraser__Utilities__
#define __thermaleraser__Utilities__

#include <iostream>
#include <gsl/gsl_rng.h>
#include <set>
#include <boost/iterator/iterator_facade.hpp>
#include "Reservoir.h"

namespace DemonBase {
    typedef std::set<DemonBase::SystemState *> StateSet;
    StateSet getValidStates();
}
unsigned int randomShortIntWithBitDistribution(double ratioOfOnesToZeroes, int nbits, gsl_rng* generator);
int bitCount(unsigned int number, int nbits);

template <class BooleanIterator>
class PackedBooleanIterator : public boost::iterator_facade<PackedBooleanIterator<BooleanIterator>, const char, boost::forward_traversal_tag>{
public:
    PackedBooleanIterator(BooleanIterator b, BooleanIterator e) : iterator(b), end(e) {
        currentValue = getEightBits();
    }
private:
    BooleanIterator iterator;
    BooleanIterator end;
    char currentValue;
    friend class boost::iterator_core_access;

    void increment() {
        currentValue = getEightBits();
    }

    inline char getEightBits() {
        int count = 0;
        char result = '\0';
        while (iterator!=end && count != 8) {
            int bit = *iterator ? 1 : 0;
            result |= (bit << count);
            ++iterator;
            ++count;
        }
        return result;
    }

    const char &dereference() const { return currentValue; }

    bool equal(PackedBooleanIterator<BooleanIterator> const& other) const {
        return iterator == other.iterator;
    }
};

gsl_rng *GSLRandomNumberGenerator();

#endif /* defined(__thermaleraser__Utilities__) */


text:
title: "Best Practice For Broker"
permalink: /docs/best-practice-broker/
modified: 2016-12-24T15:01:43-04:00
---

Some useful tips for users.

{% include toc %}

## Broker Role
Broker Role is ASYNC_MASTER, SYNC_MASTER or SLAVE.
If you cannot tolerate message missing, we suggest you deploy SYNC_MASTER and attach a SLAVE to it.
If you feel ok about missing, but you want the Broker to be always available, you may deploy ASYNC_MASTER with SLAVE.
If you just want to make it easy, you may only need a ASYNC_MASTER without SLAVE.
## FlushDiskType
ASYNC_FLUSH is recommended, for SYNC_FLUSH is expensive and will cause too much performance loss. If you want reliability, we recommend you use SYNC_MASTER with SLAVE.
## ReentrantLock vs CAS
to be finished
## os.sh
to be finished

redpajama_set_name: RedPajamaGithub


text:
import { findActionType } from 'utils/asyncSagaConstants';

/*
 * Home Actions
 *
 * Actions change things in your application
 * Since this boilerplate uses a uni-directional data flow, specifically redux,
 * we have these actions which are the only way your application interacts with
 * your application state. This guarantees that your state is up to date and nobody
 * messes it up weirdly somewhere.
 *
 * To add a new Action:
 * 1) Import your constant
 * 2) Add a function like this:
 *    export function yourAction(var) {
 *        return { type: YOUR_ACTION_CONSTANT, var: var }
 *    }
 */

import c from './constants';

export function loadDatas1Start(id) {
  return {
    type: findActionType('load_datas_1', c, 'START'),
    url: `loadDatas1/${id}`,
    id,
  };
}

export function loadDatas2Start(id) {
  return {
    type: findActionType('load_datas_2', c, 'START'),
    url: `loadDatas2/${id}`,
    id,
    msgPending: 'Chargement des données 2',
    msgSuccess: 'Données 2 chargées',
    // msgError: 'Message personalisé !', // msg perso override server message
  };
}


text:
(function(){
  function config($stateProvider, $locationProvider){
    $locationProvider
      .html5Mode({
          enabled: true,
          requireBase: false
      });

      $stateProvider
        .state('home', {
          url: '/',
          controller: 'HomeCtrl as home',
          templateUrl: '/templates/home.html'
        })
        .state('old', {
          url: '/template2',
          controller: 'HomeCtrl as home',
          templateUrl: '/templates/old.html'
        });
  }

  angular
    .module('todoList', ['ui.router', 'firebase'])
    .config(config);
})();


text:
!function(){

	var   Class 		= require('ee-class')
		, log 			= require('ee-log')
		, proxy 		= require('http-proxy');

	module.exports = new Class({

		init: function(options) {
			this.proxy = new proxy.createProxyServer(options);
			this.proxy.on('error', function(err){
				log('Error in proxy module: '+err.message);
			}.bind(this));
		}

		, request: function(request, response, next) {
			this.proxy.web(request.getRequest(), response.getResponse());
		}

	});
}();


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

package org.flowable.job.service.impl.asyncexecutor;

import org.flowable.job.api.JobInfo;
import org.flowable.job.service.JobServiceConfiguration;

/**
 * @author Joram Barrez
 */
public interface ExecuteAsyncRunnableFactory {

    Runnable createExecuteAsyncRunnable(JobInfo job, JobServiceConfiguration jobServiceConfiguration);

}


text:
#include "../fayecpp.h"

#if defined(HAVE_FAYECPP_CONFIG_H)
#include "fayecpp_config.h"
#endif

#include "FCJsonUtils.h"

#ifndef SAFE_DELETE
#define SAFE_DELETE(o) if(o){delete o;o=NULL;}
#endif

namespace FayeCpp {

	Error * Responce::error() const
	{
		return _error;
	}

	REVariantList * Responce::messageList() const
	{
		return _messageList;
	}

	REVariantMap * Responce::messageMap() const
	{
		return _messageMap;
	}

	REBuffer * Responce::messageBuffer() const
	{
		return _messageBuffer;
	}

	Responce::ResponceType Responce::type() const
	{
		return _type;
	}

	Responce & Responce::setType(Responce::ResponceType type)
	{
		_type = type;
		return *this;
	}

	Responce & Responce::setError(const Error & error)
	{
		SAFE_DELETE(_error)
		_error = new Error(error);
		return *this;
	}

	Responce & Responce::setMessageText(const char * text)
	{
		if (text)
		{
			this->setMessageData((const unsigned char *)text, strlen(text) + 1);
		}
		return *this;
	}

	Responce & Responce::setMessageData(const unsigned char * data, const size_t dataSize)
	{
		if (data && dataSize > 0)
		{
			bool isOk = false;
			JsonParser parser((const char *)data);
			if (parser.isList())
			{
				_messageList = new REVariantList();
				if (_messageList) isOk = parser.toList(*_messageList);
			}
			else if (parser.isMap())
			{
				_messageMap = new REVariantMap();
				if (_messageMap) isOk = parser.toMap(*_messageMap);
			}

			if (!isOk)
			{
				_messageBuffer = new REBuffer(data, (REUInt32)dataSize);
			}
		}
		return *this;
	}

	Responce::Responce(const Responce::ResponceType type) :
		_messageList(NULL),
		_messageMap(NULL),
		_messageBuffer(NULL),
		_error(NULL),
		_type(type)
	{

	}

	Responce::Responce() :
		_messageList(NULL),
		_messageMap(NULL),
		_messageBuffer(NULL),
		_error(NULL),
		_type(ResponceNone)
	{

	}

	Responce::~Responce()
	{
		SAFE_DELETE(_messageList)
		SAFE_DELETE(_messageMap)
		SAFE_DELETE(_messageBuffer)
		SAFE_DELETE(_error)
	}

}


text:
module RuboCop
  module AST
    # A node extension for `when` nodes. This will be used in place of a plain
    # node when the builder constructs the AST, making its methods available
    # to all `when` nodes within RuboCop.
    class WhenNode < Node
      # Returns an array of all the conditions in the `when` branch.
      #
      # @return [Array<Node>] an array of condition nodes
      def conditions
        node_parts[0...-1]
      end

      # Calls the given block for each condition node in the `when` branch.
      # If no block is given, an `Enumerator` is returned.
      #
      # @return [self] if a block is given
      # @return [Enumerator] if no block is given
      def each_condition
        return conditions.to_enum(__method__) unless block_given?

        conditions.each do |condition|
          yield condition
        end

        self
      end

      # Returns the index of the `when` branch within the `case` statement.
      #
      # @return [Integer] the index of the `when` branch
      def branch_index
        parent.when_branches.index(self)
      end

      # Checks whether the `when` node has a `then` keyword.
      #
      # @return [Boolean] whether the `when` node has a `then` keyword
      def then?
        loc.begin&.is?('then')
      end

      # Returns the body of the `when` node.
      #
      # @return [Node, nil] the body of the `when` node
      def body
        node_parts[-1]
      end
    end
  end
end


text:
using namespace impala;

int IR_ALWAYS_INLINE RawValue::Compare(
    const void* v1, const void* v2, const ColumnType& type) noexcept {
  const StringValue* string_value1;
  const StringValue* string_value2;
  const TimestampValue* ts_value1;
  const TimestampValue* ts_value2;
  float f1, f2;
  double d1, d2;
  int32_t i1, i2;
  int64_t b1, b2;
  switch (type.type) {
    case TYPE_NULL:
      return 0;
    case TYPE_BOOLEAN:
      return *reinterpret_cast<const bool*>(v1) - *reinterpret_cast<const bool*>(v2);
    case TYPE_TINYINT:
      return *reinterpret_cast<const int8_t*>(v1) - *reinterpret_cast<const int8_t*>(v2);
    case TYPE_SMALLINT:
      return *reinterpret_cast<const int16_t*>(v1) -
             *reinterpret_cast<const int16_t*>(v2);
    case TYPE_INT:
      i1 = *reinterpret_cast<const int32_t*>(v1);
      i2 = *reinterpret_cast<const int32_t*>(v2);
      return i1 > i2 ? 1 : (i1 < i2 ? -1 : 0);
    case TYPE_BIGINT:
      b1 = *reinterpret_cast<const int64_t*>(v1);
      b2 = *reinterpret_cast<const int64_t*>(v2);
      return b1 > b2 ? 1 : (b1 < b2 ? -1 : 0);
    case TYPE_FLOAT:
      // TODO: can this be faster? (just returning the difference has underflow problems)
      f1 = *reinterpret_cast<const float*>(v1);
      f2 = *reinterpret_cast<const float*>(v2);
      if (UNLIKELY(std::isnan(f1) && std::isnan(f2))) return 0;
      if (UNLIKELY(std::isnan(f1))) return -1;
      if (UNLIKELY(std::isnan(f2))) return 1;
      return f1 > f2 ? 1 : (f1 < f2 ? -1 : 0);
    case TYPE_DOUBLE:
      // TODO: can this be faster?
      d1 = *reinterpret_cast<const double*>(v1);
      d2 = *reinterpret_cast<const double*>(v2);
      if (std::isnan(d1) && std::isnan(d2)) return 0;
      if (std::isnan(d1)) return -1;
      if (std::isnan(d2)) return 1;
      return d1 > d2 ? 1 : (d1 < d2 ? -1 : 0);
    case TYPE_STRING:
    case TYPE_VARCHAR:
      string_value1 = reinterpret_cast<const StringValue*>(v1);
      string_value2 = reinterpret_cast<const StringValue*>(v2);
      return string_value1->Compare(*string_value2);
    case TYPE_TIMESTAMP:
      ts_value1 = reinterpret_cast<const TimestampValue*>(v1);
      ts_value2 = reinterpret_cast<const TimestampValue*>(v2);
      return *ts_value1 > *ts_value2 ? 1 : (*ts_value1 < *ts_value2 ? -1 : 0);
    case TYPE_CHAR: {
      const char* v1ptr = reinterpret_cast<const char*>(v1);
      const char* v2ptr = reinterpret_cast<const char*>(v2);
      int64_t l1 = StringValue::UnpaddedCharLength(v1ptr, type.len);
      int64_t l2 = StringValue::UnpaddedCharLength(v2ptr, type.len);
      return StringCompare(v1ptr, l1, v2ptr, l2, std::min(l1, l2));
    }
    case TYPE_DECIMAL:
      switch (type.GetByteSize()) {
        case 4:
          return reinterpret_cast<const Decimal4Value*>(v1)->Compare(
                 *reinterpret_cast<const Decimal4Value*>(v2));
        case 8:
          return reinterpret_cast<const Decimal8Value*>(v1)->Compare(
                 *reinterpret_cast<const Decimal8Value*>(v2));
        case 16:
          return reinterpret_cast<const Decimal16Value*>(v1)->Compare(
                 *reinterpret_cast<const Decimal16Value*>(v2));
        default:
          DCHECK(false) << type;
          return 0;
      }
    default:
      DCHECK(false) << "invalid type: " << type.DebugString();
      return 0;
  };
}

uint32_t IR_ALWAYS_INLINE RawValue::GetHashValue(
    const void* v, const ColumnType& type, uint32_t seed) noexcept {
  // The choice of hash function needs to be consistent across all hosts of the cluster.

  // Use HashCombine with arbitrary constant to ensure we don't return seed.
  if (v == NULL) return HashUtil::HashCombine32(HASH_VAL_NULL, seed);

  switch (type.type) {
    case TYPE_CHAR:
    case TYPE_STRING:
    case TYPE_VARCHAR:
      return RawValue::GetHashValueNonNull<impala::StringValue>(
        reinterpret_cast<const StringValue*>(v), type, seed);
    case TYPE_BOOLEAN:
      return RawValue::GetHashValueNonNull<bool>(
        reinterpret_cast<const bool*>(v), type, seed);
    case TYPE_TINYINT:
      return RawValue::GetHashValueNonNull<int8_t>(
        reinterpret_cast<const int8_t*>(v), type, seed);
    case TYPE_SMALLINT:
      return RawValue::GetHashValueNonNull<int16_t>(
        reinterpret_cast<const int16_t*>(v), type, seed);
    case TYPE_INT:
      return RawValue::GetHashValueNonNull<int32_t>(
        reinterpret_cast<const int32_t*>(v), type, seed);
    case TYPE_BIGINT:
      return RawValue::GetHashValueNonNull<int64_t>(
        reinterpret_cast<const int64_t*>(v), type, seed);
    case TYPE_FLOAT:
      return  RawValue::GetHashValueNonNull<float>(
        reinterpret_cast<const float*>(v), type, seed);
    case TYPE_DOUBLE:
      return RawValue::GetHashValueNonNull<double>(
        reinterpret_cast<const double*>(v), type, seed);
    case TYPE_TIMESTAMP:
      return  RawValue::GetHashValueNonNull<TimestampValue>(
        reinterpret_cast<const TimestampValue*>(v), type, seed);
    case TYPE_DECIMAL:
      switch(type.GetByteSize()) {
        case 4: return
          RawValue::GetHashValueNonNull<Decimal4Value>(
            reinterpret_cast<const impala::Decimal4Value*>(v), type, seed);
        case 8:
          return RawValue::GetHashValueNonNull<Decimal8Value>(
            reinterpret_cast<const Decimal8Value*>(v), type, seed);
        case 16:
          return RawValue::GetHashValueNonNull<Decimal16Value>(
            reinterpret_cast<const Decimal16Value*>(v), type, seed);
        DCHECK(false);
    }
    default:
      DCHECK(false);
      return 0;
  }
}

uint64_t IR_ALWAYS_INLINE RawValue::GetHashValueFastHash(const void* v,
    const ColumnType& type, uint64_t seed) {
  // Hash with an arbitrary constant to ensure we don't return seed.
  if (v == nullptr) {
    return HashUtil::FastHash64(&HASH_VAL_NULL, sizeof(HASH_VAL_NULL), seed);
  }
  switch (type.type) {
    case TYPE_STRING:
    case TYPE_VARCHAR: {
      const StringValue* string_value = reinterpret_cast<const StringValue*>(v);
      return HashUtil::FastHash64(string_value->ptr,
          static_cast<size_t>(string_value->len), seed);
    }
    case TYPE_BOOLEAN: return HashUtil::FastHash64(v, 1, seed);
    case TYPE_TINYINT: return HashUtil::FastHash64(v, 1, seed);
    case TYPE_SMALLINT: return HashUtil::FastHash64(v, 2, seed);
    case TYPE_INT: return HashUtil::FastHash64(v, 4, seed);
    case TYPE_BIGINT: return HashUtil::FastHash64(v, 8, seed);
    case TYPE_FLOAT: return HashUtil::FastHash64(v, 4, seed);
    case TYPE_DOUBLE: return HashUtil::FastHash64(v, 8, seed);
    case TYPE_TIMESTAMP: return HashUtil::FastHash64(v, 12, seed);
    case TYPE_CHAR: return HashUtil::FastHash64(v, type.len, seed);
    case TYPE_DECIMAL: return HashUtil::FastHash64(v, type.GetByteSize(), seed);
    default: DCHECK(false); return 0;
  }
}


text:
package org.gradle.test.performance.mediummonolithicjavaproject.p266;

import org.gradle.test.performance.mediummonolithicjavaproject.p265.Production5318;

public class Production5327 {

    private Production5318 property0;

    public Production5318 getProperty0() {
        return property0;
    }

    public void setProperty0(Production5318 value) {
        property0 = value;
    }

    private Production5322 property1;

    public Production5322 getProperty1() {
        return property1;
    }

    public void setProperty1(Production5322 value) {
        property1 = value;
    }

    private Production5326 property2;

    public Production5326 getProperty2() {
        return property2;
    }

    public void setProperty2(Production5326 value) {
        property2 = value;
    }

    private String property3;

    public String getProperty3() {
        return property3;
    }

    public void setProperty3(String value) {
        property3 = value;
    }

    private String property4;

    public String getProperty4() {
        return property4;
    }

    public void setProperty4(String value) {
        property4 = value;
    }

    private String property5;

    public String getProperty5() {
        return property5;
    }

    public void setProperty5(String value) {
        property5 = value;
    }

    private String property6;

    public String getProperty6() {
        return property6;
    }

    public void setProperty6(String value) {
        property6 = value;
    }

    private String property7;

    public String getProperty7() {
        return property7;
    }

    public void setProperty7(String value) {
        property7 = value;
    }

    private String property8;

    public String getProperty8() {
        return property8;
    }

    public void setProperty8(String value) {
        property8 = value;
    }

    private String property9;

    public String getProperty9() {
        return property9;
    }

    public void setProperty9(String value) {
        property9 = value;
    }

}


text:
package org.wso2.carbon.apimgt.core.dao.impl;

import org.apache.commons.io.IOUtils;
import org.wso2.carbon.apimgt.core.dao.ApiType;
import org.wso2.carbon.apimgt.core.models.ResourceCategory;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;

class ApiResourceDAO {

    static boolean isResourceExistsForCategory(Connection connection, String apiID,
                                               ResourceCategory category) throws SQLException {
        final String query = "SELECT 1 FROM AM_API_RESOURCES WHERE API_ID = ? AND RESOURCE_CATEGORY_ID = ?";

        try (PreparedStatement statement = connection.prepareStatement(query)) {
            statement.setString(1, apiID);
            statement.setInt(2, ResourceCategoryDAO.getResourceCategoryID(connection, category));
            statement.execute();

            try (ResultSet rs =  statement.getResultSet()) {
                if (rs.next()) {
                    return true;
                }
            }
        }

        return false;
    }

    static void addResourceWithoutValue(Connection connection, String apiID, String resourceID,
                                        ResourceCategory category) throws SQLException {
        final String query = "INSERT INTO AM_API_RESOURCES (UUID, API_ID, RESOURCE_CATEGORY_ID) VALUES (?,?,?)";

        try (PreparedStatement statement = connection.prepareStatement(query)) {
            statement.setString(1, resourceID);
            statement.setString(2, apiID);
            statement.setInt(3, ResourceCategoryDAO.getResourceCategoryID(connection, category));

            statement.execute();
        }
    }

    static void addTextResource(Connection connection, String apiID, String resourceID,
            ResourceCategory category, String dataType, String textValue, String createdBy)
            throws SQLException {
        final String query = "INSERT INTO AM_API_RESOURCES (UUID, API_ID, RESOURCE_CATEGORY_ID, " +
                "DATA_TYPE, RESOURCE_TEXT_VALUE, CREATED_BY, CREATED_TIME, UPDATED_BY, LAST_UPDATED_TIME) "
                + "VALUES (?,?,?,?,?,?,?,?,?)";

        try (PreparedStatement statement = connection.prepareStatement(query)) {
            statement.setString(1, resourceID);
            statement.setString(2, apiID);
            statement.setInt(3, ResourceCategoryDAO.getResourceCategoryID(connection, category));
            statement.setString(4, dataType);
            statement.setString(5, textValue);
            statement.setString(6, createdBy);
            statement.setTimestamp(7, Timestamp.valueOf(LocalDateTime.now()));
            statement.setString(8, createdBy);
            statement.setTimestamp(9, Timestamp.valueOf(LocalDateTime.now()));
            statement.execute();
        }
    }

    static void addBinaryResource(Connection connection, String apiID, String resourceID, ResourceCategory category,
            String dataType, InputStream binaryValue, String createdBy) throws SQLException {
        final String query = "INSERT INTO AM_API_RESOURCES (UUID, API_ID, RESOURCE_CATEGORY_ID, " +
                "DATA_TYPE, RESOURCE_BINARY_VALUE, CREATED_BY, CREATED_TIME, UPDATED_BY, LAST_UPDATED_TIME) "
                + "VALUES (?,?,?,?,?,?,?,?,?)";

        try (PreparedStatement statement = connection.prepareStatement(query)) {
            statement.setString(1, resourceID);
            statement.setString(2, apiID);
            statement.setInt(3, ResourceCategoryDAO.getResourceCategoryID(connection, category));
            statement.setString(4, dataType);
            statement.setBinaryStream(5, binaryValue);
            statement.setString(6, createdBy);
            statement.setTimestamp(7, Timestamp.valueOf(LocalDateTime.now()));
            statement.setString(8, createdBy);
            statement.setTimestamp(9, Timestamp.valueOf(LocalDateTime.now()));
            statement.execute();
        }
    }

    static String getTextValueForCategory(Connection connection, String apiID,
                                          ResourceCategory resourceCategory) throws SQLException {
        final String query = "SELECT RESOURCE_TEXT_VALUE FROM AM_API_RESOURCES WHERE API_ID = ? AND " +
                "RESOURCE_CATEGORY_ID = ?";
        try (PreparedStatement statement = connection.prepareStatement(query)) {
            statement.setString(1, apiID);
            statement.setInt(2, ResourceCategoryDAO.getResourceCategoryID(connection, resourceCategory));
            statement.execute();

            try (ResultSet rs =  statement.getResultSet()) {
                if (rs.next()) {
                    return rs.getString("RESOURCE_TEXT_VALUE");
                }
            }
        }

        return null;
    }

    static void updateTextValueForCategory(Connection connection, String apiID,
                                           ResourceCategory category,
                                           String resourceValue, String updatedBy) throws SQLException {
        final String query = "UPDATE AM_API_RESOURCES SET RESOURCE_TEXT_VALUE = ?, UPDATED_BY = ?, "
                + "LAST_UPDATED_TIME = ? WHERE API_ID = ? AND RESOURCE_CATEGORY_ID = ?";
        try (PreparedStatement statement = connection.prepareStatement(query)) {
            statement.setString(1, resourceValue);
            statement.setString(2, updatedBy);
            statement.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now()));
            statement.setString(4, apiID);
            statement.setInt(5, ResourceCategoryDAO.getResourceCategoryID(connection, category));

            statement.execute();
        }
    }

    static InputStream getBinaryValueForCategory(Connection connection, String apiID,
                                                 ResourceCategory category, ApiType apiType)
                                                                                throws SQLException, IOException {
        final String query = "SELECT res.RESOURCE_BINARY_VALUE FROM AM_API_RESOURCES res " +
                "INNER JOIN AM_API api ON res.API_ID = api.UUID " +
                "WHERE res.API_ID = ? AND res.RESOURCE_CATEGORY_ID = ? AND " +
                "api.API_TYPE_ID = (SELECT TYPE_ID FROM AM_API_TYPES WHERE TYPE_NAME = ?)";

        try (PreparedStatement statement = connection.prepareStatement(query)) {
            statement.setString(1, apiID);
            statement.setInt(2, ResourceCategoryDAO.getResourceCategoryID(connection, category));
            statement.setString(3, apiType.toString());
            statement.execute();

            try (ResultSet rs =  statement.getResultSet()) {
                if (rs.next()) {
                    InputStream inputStream = new ByteArrayInputStream(IOUtils.toByteArray(rs.getBinaryStream
                            ("RESOURCE_BINARY_VALUE")));
                    return inputStream;
                }
            }
        }

        return null;
    }

    static InputStream getBinaryResource(Connection connection, String resourceID) throws SQLException, IOException {
        final String query = "SELECT RESOURCE_BINARY_VALUE FROM AM_API_RESOURCES WHERE UUID = ?";

        try (PreparedStatement statement = connection.prepareStatement(query)) {
            statement.setString(1, resourceID);
            statement.execute();

            try (ResultSet rs = statement.getResultSet()) {
                if (rs.next()) {
                    InputStream inputStream = rs.getBinaryStream("RESOURCE_BINARY_VALUE");
                    if (inputStream != null) {
                        return new ByteArrayInputStream(IOUtils.toByteArray(inputStream));
                    }
                }
            }
        }
        return null;
    }

    static String getTextResource(Connection connection, String resourceID) throws SQLException {
        final String query = "SELECT RESOURCE_TEXT_VALUE FROM AM_API_RESOURCES WHERE UUID = ?";

        try (PreparedStatement statement = connection.prepareStatement(query)) {
            statement.setString(1, resourceID);
            statement.execute();

            try (ResultSet rs =  statement.getResultSet()) {
                if (rs.next()) {
                    return rs.getString("RESOURCE_TEXT_VALUE");
                }
            }
        }

        return null;
    }

    static void updateBinaryResourceForCategory(Connection connection, String apiID, ResourceCategory category,
                                                InputStream resourceValue, String updatedBy)
                                                                                throws SQLException {
        final String query = "UPDATE AM_API_RESOURCES SET RESOURCE_BINARY_VALUE = ?, UPDATED_BY = ?, "
                + "LAST_UPDATED_TIME = ? WHERE API_ID = ? AND RESOURCE_CATEGORY_ID = ?";

        try (PreparedStatement statement = connection.prepareStatement(query)) {
            statement.setBinaryStream(1, resourceValue);
            statement.setString(2, updatedBy);
            statement.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now()));
            statement.setString(4, apiID);
            statement.setInt(5, ResourceCategoryDAO.getResourceCategoryID(connection, category));

            statement.execute();
        }
    }

    static String getResourceLastUpdatedTime(Connection connection, String apiId, String resourceID,
            ResourceCategory category) throws SQLException {
        final String query = "SELECT LAST_UPDATED_TIME FROM AM_API_RESOURCES WHERE API_ID = ? AND UUID = ? AND " +
                "RESOURCE_CATEGORY_ID = ?";
        try (PreparedStatement statement = connection.prepareStatement(query)) {
            statement.setString(1, apiId);
            statement.setString(2, resourceID);
            statement.setInt(3, ResourceCategoryDAO.getResourceCategoryID(connection, category));
            statement.execute();

            try (ResultSet rs = statement.getResultSet()) {
                if (rs.next()) {
                    return rs.getString("LAST_UPDATED_TIME");
                }
            }
        }
        return null;
    }

    static String getAPIUniqueResourceLastUpdatedTime(Connection connection, String apiID, ResourceCategory category)
            throws SQLException {
        final String query = "SELECT LAST_UPDATED_TIME FROM AM_API_RESOURCES WHERE API_ID = ? AND " +
                "RESOURCE_CATEGORY_ID = ?";
        try (PreparedStatement statement = connection.prepareStatement(query)) {
            statement.setString(1, apiID);
            statement.setInt(2, ResourceCategoryDAO.getResourceCategoryID(connection, category));
            statement.execute();

            try (ResultSet rs = statement.getResultSet()) {
                if (rs.next()) {
                    return rs.getString("LAST_UPDATED_TIME");
                }
            }
        }
        return null;
    }

    static int updateBinaryResource(Connection connection, String resourceID, InputStream resourceValue, String
            dataType, String updatedBy) throws SQLException {
        final String query = "UPDATE AM_API_RESOURCES SET RESOURCE_BINARY_VALUE = ?, DATA_TYPE = ?, UPDATED_BY = ?, "
                + "LAST_UPDATED_TIME = ? WHERE UUID = ?";
        try (PreparedStatement statement = connection.prepareStatement(query)) {
            statement.setBinaryStream(1, resourceValue);
            statement.setString(2, dataType);
            statement.setString(3, updatedBy);
            statement.setTimestamp(4, Timestamp.valueOf(LocalDateTime.now()));
            statement.setString(5, resourceID);
            return statement.executeUpdate();
        }
    }

    static int updateTextResource(Connection connection, String resourceID, String resourceValue, String updatedBy)
            throws SQLException {
        final String query = "UPDATE AM_API_RESOURCES SET RESOURCE_TEXT_VALUE = ?, UPDATED_BY = ?, "
                + "LAST_UPDATED_TIME = ? WHERE UUID = ?";
        try (PreparedStatement statement = connection.prepareStatement(query)) {
            statement.setString(1, resourceValue);
            statement.setString(2, updatedBy);
            statement.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now()));
            statement.setString(4, resourceID);

            return statement.executeUpdate();
        }
    }

    static void deleteUniqueResourceForCategory(Connection connection, String apiID, ResourceCategory resourceCategory)
            throws SQLException {
        final String query = "DELETE FROM AM_API_RESOURCES WHERE API_ID = ? AND RESOURCE_CATEGORY_ID = ?";
        try (PreparedStatement statement = connection.prepareStatement(query)) {
            statement.setString(1, apiID);
            statement.setInt(2, ResourceCategoryDAO.getResourceCategoryID(connection, resourceCategory));

            statement.execute();
        }
    }

    static void deleteResource(Connection connection, String resourceID)
            throws SQLException {
        final String query = "DELETE FROM AM_API_RESOURCES WHERE UUID = ?";
        try (PreparedStatement statement = connection.prepareStatement(query)) {
            statement.setString(1, resourceID);

            statement.execute();
        }
    }
}


text:
package com.truemesh.squiggle.tests;

import com.truemesh.squiggle.*;
import static com.truemesh.squiggle.tests.support.SqlMatcher.generatesSql;
import org.junit.Test;
import static org.junit.Assert.assertThat;

public class Example006TableAliases {
    @Test
    public void tableAliases() {
        Table employees = new Table("people", "employees");
        Table managers = new Table("people", "managers");

        SelectQuery select = new SelectQuery(); // base table

        select.addColumn(employees, "firstname");
        select.addColumn(managers, "firstname");

        select.addJoin(employees, "managerID", managers, "id");

        assertThat(select, generatesSql(
                "SELECT " +
                "    employees.firstname , " +
                "    managers.firstname " +
                "FROM " +
                "    people employees , " +
                "    people managers " +
                "WHERE " +
                "    employees.managerID = managers.id"));
    }
}


text:
<?php

/**
 * This is the model class for table "usuario".
 *
 * The followings are the available columns in table 'usuario':
 * @property string $id
 * @property string $login
 * @property string $pass
 * @property string $nombre
 * @property string $ap
 * @property string $am
 * @property string $mail
 *
 * The followings are the available model relations:
 * @property Aprobacion[] $aprobacions
 * @property Cambios[] $cambioses
 * @property Version[] $versions
 */
class Usuario extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @return Usuario the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'usuario';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('login, pass, nombre, ap, am, mail', 'required'),
			array('login', 'length', 'max'=>16),
			array('pass', 'length', 'max'=>50),
			array('nombre', 'length', 'max'=>30),
			array('ap, am', 'length', 'max'=>20),
			array('mail', 'length', 'max'=>80),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, login, pass, nombre, ap, am, mail', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'aprobacions' => array(self::HAS_MANY, 'Aprobacion', 'usuario_id'),
			'cambioses' => array(self::HAS_MANY, 'Cambios', 'usuario_id'),
			'versions' => array(self::HAS_MANY, 'Version', 'genera'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'login' => 'Login',
			'pass' => 'Pass',
			'nombre' => 'Nombre',
			'ap' => 'Ap',
			'am' => 'Am',
			'mail' => 'Mail',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id,true);
		$criteria->compare('login',$this->login,true);
		$criteria->compare('pass',$this->pass,true);
		$criteria->compare('nombre',$this->nombre,true);
		$criteria->compare('ap',$this->ap,true);
		$criteria->compare('am',$this->am,true);
		$criteria->compare('mail',$this->mail,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
}


text:
import { NO_ERRORS_SCHEMA } from '@angular/core';
import {
  inject,
  async,
  TestBed,
  ComponentFixture,
  getTestBed
} from '@angular/core/testing';
import { Component } from '@angular/core';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

/**
 * Load the implementations that should be tested.
 */
import { AppState } from '../app.service';
import { HomeComponent } from './home.component';
import { Title } from './title';

describe(`Home`, () => {
  let comp: HomeComponent;
  let fixture: ComponentFixture<HomeComponent>;
  let injector: TestBed;
  let service: AppState;
  let httpMock: HttpTestingController;

  /**
   * async beforeEach.
   */
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [HomeComponent],
      schemas: [NO_ERRORS_SCHEMA],
      imports: [HttpClientTestingModule],
      providers: [AppState, Title]
    })

      /**
       * Compile template and css.
       */
      .compileComponents();
    injector = getTestBed();
    service = injector.get(AppState);
    httpMock = injector.get(HttpTestingController);
  }));

  /**
   * Synchronous beforeEach.
   */
  beforeEach(() => {
    fixture = TestBed.createComponent(HomeComponent);
    comp = fixture.componentInstance;

    /**
     * Trigger initial data binding.
     */
    fixture.detectChanges();
  });

  it('should have default data', () => {
    expect(comp.localState).toEqual({ value: '' });
  });

  it('should have a title', () => {
    expect(!!comp.title).toEqual(true);
  });

  it('should log ngOnInit', () => {
    spyOn(console, 'log');
    expect(console.log).not.toHaveBeenCalled();

    comp.ngOnInit();
    expect(console.log).toHaveBeenCalled();
  });

});


text:
<?php

/** Zend_Controller_Dispatcher_Interface */
require_once 'Zend/Controller/Dispatcher/Interface.php';

/**
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage Dispatcher
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_Controller_Dispatcher_Abstract implements Zend_Controller_Dispatcher_Interface
{
    /**
     * Default action
     * @var string
     */
    protected $_defaultAction = 'index';

    /**
     * Default controller
     * @var string
     */
    protected $_defaultController = 'index';

    /**
     * Default module
     * @var string
     */
    protected $_defaultModule = 'default';

    /**
     * Front Controller instance
     * @var Zend_Controller_Front
     */
    protected $_frontController;

    /**
     * Array of invocation parameters to use when instantiating action
     * controllers
     * @var array
     */
    protected $_invokeParams = array();

    /**
     * Path delimiter character
     * @var string
     */
    protected $_pathDelimiter = '_';

    /**
     * Response object to pass to action controllers, if any
     * @var Zend_Controller_Response_Abstract|null
     */
    protected $_response = null;

    /**
     * Word delimiter characters
     * @var array
     */
    protected $_wordDelimiter = array('-', '.');

    /**
     * Constructor
     *
     * @return void
     */
    public function __construct(array $params = array())
    {
        $this->setParams($params);
    }

    /**
     * Formats a string into a controller name.  This is used to take a raw
     * controller name, such as one stored inside a Zend_Controller_Request_Abstract
     * object, and reformat it to a proper class name that a class extending
     * Zend_Controller_Action would use.
     *
     * @param string $unformatted
     * @return string
     */
    public function formatControllerName($unformatted)
    {
        return ucfirst($this->_formatName($unformatted)) . 'Controller';
    }

    /**
     * Formats a string into an action name.  This is used to take a raw
     * action name, such as one that would be stored inside a Zend_Controller_Request_Abstract
     * object, and reformat into a proper method name that would be found
     * inside a class extending Zend_Controller_Action.
     *
     * @param string $unformatted
     * @return string
     */
    public function formatActionName($unformatted)
    {
        $formatted = $this->_formatName($unformatted, true);
        return strtolower(substr($formatted, 0, 1)) . substr($formatted, 1) . 'Action';
    }

    /**
     * Verify delimiter
     *
     * Verify a delimiter to use in controllers or actions. May be a single
     * string or an array of strings.
     *
     * @param string|array $spec
     * @return array
     * @throws Zend_Controller_Dispatcher_Exception with invalid delimiters
     */
    public function _verifyDelimiter($spec)
    {
        if (is_string($spec)) {
            return (array) $spec;
        } elseif (is_array($spec)) {
            $allStrings = true;
            foreach ($spec as $delim) {
                if (!is_string($delim)) {
                    $allStrings = false;
                    break;
                }
            }

            if (!$allStrings) {
                require_once 'Zend/Controller/Dispatcher/Exception.php';
                throw new Zend_Controller_Dispatcher_Exception('Word delimiter array must contain only strings');
            }

            return $spec;
        }

        require_once 'Zend/Controller/Dispatcher/Exception.php';
        throw new Zend_Controller_Dispatcher_Exception('Invalid word delimiter');
    }

    /**
     * Retrieve the word delimiter character(s) used in
     * controller or action names
     *
     * @return array
     */
    public function getWordDelimiter()
    {
        return $this->_wordDelimiter;
    }

    /**
     * Set word delimiter
     *
     * Set the word delimiter to use in controllers and actions. May be a
     * single string or an array of strings.
     *
     * @param string|array $spec
     * @return Zend_Controller_Dispatcher_Abstract
     */
    public function setWordDelimiter($spec)
    {
        $spec = $this->_verifyDelimiter($spec);
        $this->_wordDelimiter = $spec;

        return $this;
    }

    /**
     * Retrieve the path delimiter character(s) used in
     * controller names
     *
     * @return array
     */
    public function getPathDelimiter()
    {
        return $this->_pathDelimiter;
    }

    /**
     * Set path delimiter
     *
     * Set the path delimiter to use in controllers. May be a single string or
     * an array of strings.
     *
     * @param string $spec
     * @return Zend_Controller_Dispatcher_Abstract
     */
    public function setPathDelimiter($spec)
    {
        if (!is_string($spec)) {
            require_once 'Zend/Controller/Dispatcher/Exception.php';
            throw new Zend_Controller_Dispatcher_Exception('Invalid path delimiter');
        }
        $this->_pathDelimiter = $spec;

        return $this;
    }

    /**
     * Formats a string from a URI into a PHP-friendly name.
     *
     * By default, replaces words separated by the word separator character(s)
     * with camelCaps. If $isAction is false, it also preserves replaces words
     * separated by the path separation character with an underscore, making
     * the following word Title cased. All non-alphanumeric characters are
     * removed.
     *
     * @param string $unformatted
     * @param boolean $isAction Defaults to false
     * @return string
     */
    protected function _formatName($unformatted, $isAction = false)
    {
        // preserve directories
        if (!$isAction) {
            $segments = explode($this->getPathDelimiter(), $unformatted);
        } else {
            $segments = (array) $unformatted;
        }

        foreach ($segments as $key => $segment) {
            $segment        = str_replace($this->getWordDelimiter(), ' ', strtolower($segment));
            $segment        = preg_replace('/[^a-z0-9 ]/', '', $segment);
            $segments[$key] = str_replace(' ', '', ucwords($segment));
        }

        return implode('_', $segments);
    }

    /**
     * Retrieve front controller instance
     *
     * @return Zend_Controller_Front
     */
    public function getFrontController()
    {
        if (null === $this->_frontController) {
            require_once 'Zend/Controller/Front.php';
            $this->_frontController = Zend_Controller_Front::getInstance();
        }

        return $this->_frontController;
    }

    /**
     * Set front controller instance
     *
     * @param Zend_Controller_Front $controller
     * @return Zend_Controller_Dispatcher_Abstract
     */
    public function setFrontController(Zend_Controller_Front $controller)
    {
        $this->_frontController = $controller;
        return $this;
    }

    /**
     * Add or modify a parameter to use when instantiating an action controller
     *
     * @param string $name
     * @param mixed $value
     * @return Zend_Controller_Dispatcher_Abstract
     */
    public function setParam($name, $value)
    {
        $name = (string) $name;
        $this->_invokeParams[$name] = $value;
        return $this;
    }

    /**
     * Set parameters to pass to action controller constructors
     *
     * @param array $params
     * @return Zend_Controller_Dispatcher_Abstract
     */
    public function setParams(array $params)
    {
        $this->_invokeParams = array_merge($this->_invokeParams, $params);
        return $this;
    }

    /**
     * Retrieve a single parameter from the controller parameter stack
     *
     * @param string $name
     * @return mixed
     */
    public function getParam($name)
    {
        if(isset($this->_invokeParams[$name])) {
            return $this->_invokeParams[$name];
        }

        return null;
    }

    /**
     * Retrieve action controller instantiation parameters
     *
     * @return array
     */
    public function getParams()
    {
        return $this->_invokeParams;
    }

    /**
     * Clear the controller parameter stack
     *
     * By default, clears all parameters. If a parameter name is given, clears
     * only that parameter; if an array of parameter names is provided, clears
     * each.
     *
     * @param null|string|array single key or array of keys for params to clear
     * @return Zend_Controller_Dispatcher_Abstract
     */
    public function clearParams($name = null)
    {
        if (null === $name) {
            $this->_invokeParams = array();
        } elseif (is_string($name) && isset($this->_invokeParams[$name])) {
            unset($this->_invokeParams[$name]);
        } elseif (is_array($name)) {
            foreach ($name as $key) {
                if (is_string($key) && isset($this->_invokeParams[$key])) {
                    unset($this->_invokeParams[$key]);
                }
            }
        }

        return $this;
    }

    /**
     * Set response object to pass to action controllers
     *
     * @param Zend_Controller_Response_Abstract|null $response
     * @return Zend_Controller_Dispatcher_Abstract
     */
    public function setResponse(Zend_Controller_Response_Abstract $response = null)
    {
        $this->_response = $response;
        return $this;
    }

    /**
     * Return the registered response object
     *
     * @return Zend_Controller_Response_Abstract|null
     */
    public function getResponse()
    {
        return $this->_response;
    }

    /**
     * Set the default controller (minus any formatting)
     *
     * @param string $controller
     * @return Zend_Controller_Dispatcher_Abstract
     */
    public function setDefaultControllerName($controller)
    {
        $this->_defaultController = (string) $controller;
        return $this;
    }

    /**
     * Retrieve the default controller name (minus formatting)
     *
     * @return string
     */
    public function getDefaultControllerName()
    {
        return $this->_defaultController;
    }

    /**
     * Set the default action (minus any formatting)
     *
     * @param string $action
     * @return Zend_Controller_Dispatcher_Abstract
     */
    public function setDefaultAction($action)
    {
        $this->_defaultAction = (string) $action;
        return $this;
    }

    /**
     * Retrieve the default action name (minus formatting)
     *
     * @return string
     */
    public function getDefaultAction()
    {
        return $this->_defaultAction;
    }

    /**
     * Set the default module
     *
     * @param string $module
     * @return Zend_Controller_Dispatcher_Abstract
     */
    public function setDefaultModule($module)
    {
        $this->_defaultModule = (string) $module;
        return $this;
    }

    /**
     * Retrieve the default module
     *
     * @return string
     */
    public function getDefaultModule()
    {
        return $this->_defaultModule;
    }
}


text:
<<selection>t<caret>ag</selection> attr="value" another="value">

  some Text

</tag>


text:
<?php return [
  'pagination' => [
    'DescribeCases' => [
      'input_token' => 'nextToken',
      'output_token' => 'nextToken',
      'limit_key' => 'maxResults',
      'result_key' => 'cases',
    ],
    'DescribeCommunications' => [
      'input_token' => 'nextToken',
      'output_token' => 'nextToken',
      'limit_key' => 'maxResults',
      'result_key' => 'communications',
    ],
    'DescribeServices' => [
      'result_key' => 'services',
    ],
    'DescribeTrustedAdvisorCheckRefreshStatuses' => [
      'result_key' => 'statuses',
    ],
    'DescribeTrustedAdvisorCheckSummaries' => [
      'result_key' => 'summaries',
    ],
  ],
];


text:
export { RegistChoiceComponent } from './choice.component'
export { RegistrationComponent } from './registration.component'
export { AccontSettingComponent } from './setting.component'


text:
package mcjty.rftools.blocks.teleporter;

import mcjty.lib.container.GenericItemBlock;
import mcjty.lib.varia.GlobalCoordinate;
import mcjty.lib.varia.Logging;
import mcjty.rftools.dimension.RfToolsDimensionManager;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.world.World;

public class SimpleDialerItemBlock extends GenericItemBlock {
    public SimpleDialerItemBlock(Block block) {
        super(block);
    }

    @Override
    public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float sx, float sy, float sz) {
        TileEntity te = world.getTileEntity(x, y, z);
        NBTTagCompound tagCompound = stack.getTagCompound();
        if (tagCompound == null) {
            tagCompound = new NBTTagCompound();
        }

        if (te instanceof MatterTransmitterTileEntity) {
            if (!world.isRemote) {
                MatterTransmitterTileEntity matterTransmitterTileEntity = (MatterTransmitterTileEntity) te;

                if (!matterTransmitterTileEntity.checkAccess(player.getDisplayName())) {
                    Logging.message(player, EnumChatFormatting.RED + "You have no access to this matter transmitter!");
                    return true;
                }

                tagCompound.setInteger("transX", matterTransmitterTileEntity.xCoord);
                tagCompound.setInteger("transY", matterTransmitterTileEntity.yCoord);
                tagCompound.setInteger("transZ", matterTransmitterTileEntity.zCoord);
                tagCompound.setInteger("transDim", world.provider.dimensionId);

                if (matterTransmitterTileEntity.isDialed()) {
                    Integer id = matterTransmitterTileEntity.getTeleportId();
                    boolean access = checkReceiverAccess(player, world, id);
                    if (!access) {
                        Logging.message(player, EnumChatFormatting.RED + "You have no access to the matter receiver!");
                        return true;
                    }

                    tagCompound.setInteger("receiver", id);
                    Logging.message(player, EnumChatFormatting.YELLOW + "Receiver set!");
                }

                Logging.message(player, EnumChatFormatting.YELLOW + "Transmitter set!");
            }
        } else if (te instanceof MatterReceiverTileEntity) {
            if (!world.isRemote) {
                MatterReceiverTileEntity matterReceiverTileEntity = (MatterReceiverTileEntity) te;

                Integer id  = matterReceiverTileEntity.getOrCalculateID();
                boolean access = checkReceiverAccess(player, world, id);
                if (!access) {
                    Logging.message(player, EnumChatFormatting.RED + "You have no access to this matter receiver!");
                    return true;
                }

                tagCompound.setInteger("receiver", id);
                Logging.message(player, EnumChatFormatting.YELLOW + "Receiver set!");
            }
        } else {
            return super.onItemUse(stack, player, world, x, y, z, side, sx, sy, sz);
        }

        stack.setTagCompound(tagCompound);
        return true;
    }

    private boolean checkReceiverAccess(EntityPlayer player, World world, Integer id) {
        boolean access = true;
        TeleportDestinations destinations = TeleportDestinations.getDestinations(world);
        GlobalCoordinate coordinate = destinations.getCoordinateForId(id);
        if (coordinate != null) {
            TeleportDestination destination = destinations.getDestination(coordinate);
            if (destination != null) {
                World worldForDimension = RfToolsDimensionManager.getWorldForDimension(destination.getDimension());
                if (worldForDimension != null) {
                    TileEntity recTe = worldForDimension.getTileEntity(
                            destination.getCoordinate().getX(),
                            destination.getCoordinate().getY(),
                            destination.getCoordinate().getZ());
                    if (recTe instanceof MatterReceiverTileEntity) {
                        MatterReceiverTileEntity matterReceiverTileEntity = (MatterReceiverTileEntity) recTe;
                        if (!matterReceiverTileEntity.checkAccess(player.getDisplayName())) {
                            access = false;
                        }
                    }
                }
            }
        }
        return access;
    }
}


text:
package capstone.element;

import capstone.data.Representation;
import capstone.utility.Delta;
import capstone.utility.Point;
import capstone.utility.Region;

import java.util.Random;
import java.util.Set;

/**
 * Abstract class for all dynamic-obstacles, i.e. all obstacles that move.
 *
 * It defines all operations a DynamicObstacle needs on the outside. Minimally,
 * a concrete subclass of this class need only implement the _next method to
 * return the next safe delta according to its dynamic motion.
 */
public abstract class DynamicObstacle extends Element
{
    /**
     *
     * Factory-method to create a random dynamic-obstacle concrete-object.
     *
     * All dynamic-obstacle types except IntelligentObstacle
     * are deprecated so basically don't use this method.
     *
     * @param point The point to construct the dynamic-obstacle at.
     *
     * @param representation The representation to construct
     *                       the dynamic-obstacle with.
     *
     * @return An instance of one of the subclasses of DynamicObstacle.
     *         Which subclass it is is random.
     */
    @Deprecated public static DynamicObstacle
    Random(Point point, Representation representation)
    {
        switch (_random.nextInt(3))
        {
            case 0: return new PatternObstacle   (point, representation);
            case 1: return new RandomizedObstacle(point, representation);
            case 2: return new IntelligentObstacle(point, representation);
        }

        throw new AssertionError();
    }

    /**
     *
     * Constructs a new dynamic-obstacle from a Point and an Representation.
     *
     * So subclasses don't have to specify their kind anymore.
     *
     * @param point The point of the dynamic-obstacle.
     *
     * @param representation The representation of the dynamic-obstacle.
     */
    public DynamicObstacle(Point point, Representation representation)
    {
        super(Kind.DYNAMIC_OBSTACLE, point, representation);
    }

    /**
     *
     * Updates the point in a safe way.
     *
     * Safety here means that any update to the dynamic-obstacle's
     * point will result in the point being:
     *
     * 1. Within the given region.
     * 2. Not on any point included in the given set of taken points.
     *
     * What that update means depends on the concrete class. The
     * dynamic-obstacle could move randomly, according to some pattern etc.
     *
     * @param region The region the point of the dynamic-obstacle
     *               must be in after updating.
     *
     * @param taken The set of points the point of the dynamic-obstacle
     *              must not be on after updating.
     *
     * @return A valid point fitting both constraints.
     */
    public Point update(Region region, Set<Point> taken)
    {
        return _point = peekPoint(region, taken);
    }

    /**
     *
     * Returns the next safe Delta, i.e. by what Delta the point
     * of the dynamic-obstacle will move when calling update().
     *
     * @param region The region the point of the dynamic-obstacle
     *               must be in after the delta would be applied.
     *
     * @param taken The set of points the point of the dynamic-obstacle
     *              must not be on after the delta would be applied.
     *
     * @return A valid delta fitting both constraints.
     */
    public Delta peekDelta(Region region, Set<Point> taken)
    {
        // Check if there can even be a valid delta!
        if (taken.size() == region.area())
        {
            // Badness
            assert(! taken.contains(_point));

            return Delta.Stay();
        }

        return _next(region, taken);
    }

    /**
     *
     * Returns the next safe point, i.e. the point the
     * dynamic-obstacle's point will be when calling update.
     *
     * @param region The region the point returned must be in.
     *
     * @param taken The set of points the point returned must not be on.
     *
     * @return A valid point fitting both constraints.
     */
    public Point peekPoint(Region region, Set<Point> taken)
    {
        return new Point(_point).move(peekDelta(region, taken));
    }

    /**
     *
     * The method concrete subclasses must implement to yield the
     * next Delta according to their dynamic motion.
     *
     * @param region The region the point of the dynamic-obstacle
     *               must be in after the delta would be applied.
     *
     * @param taken The set of points the point of the dynamic-obstacle
     *              must not be on after the delta would be applied.
     *
     * @return A valid delta fitting both constraints.
     */
    protected abstract Delta _next(Region region, Set<Point> taken);

    /**
     *
     * A verification method subclasses can use to check if a delta, applied
     * to the current point, would be valid.
     *
     * @param delta The delta to test.
     *
     * @param region The region the point of the dynamic-obstacle
     *               must be in after the delta would be applied.
     *
     * @param taken The set of points the point of the dynamic-obstacle
     *              must not be on after the delta would be applied.
     *
     * @return A valid delta fitting both constraints.
     */
    protected boolean _valid(Delta delta, Region region, Set<Point> taken)
    {
        if (_point.wouldGoOutside(delta, region)) return false;

        Point next = new Point(_point).move(delta);

        return ! taken.contains(next);
    }

    private static Random _random = new Random();
}


text:
<?php

namespace Zend\Http\Exception;

interface ExceptionInterface
{
}


text:
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

using MsgPack;

using Tarantool.Client.Models;
using Tarantool.Client.Models.ClientMessages;

namespace Tarantool.Client.Extensions
{
    public static class TarantoolClientExtensions
    {
        /// <exception cref="ArgumentException">parts is null or empty.</exception>
        /// <exception cref="IndexAlreadyExistsException"></exception>
        /// <exception cref="TarantoolResponseException"></exception>
        public static Task CreateIndexAsync(
            this ITarantoolClient tarantoolClient,
            string spaceName,
            string indexName,
            IndexType indexType,
            params IndexPart[] parts)
        {
            return tarantoolClient.CreateIndexAsync(spaceName, indexName, indexType, CancellationToken.None, parts);
        }

        /// <exception cref="ArgumentException">parts is null or empty.</exception>
        /// <exception cref="IndexAlreadyExistsException"></exception>
        /// <exception cref="TarantoolResponseException"></exception>
        public static Task CreateIndexAsync(
            this ITarantoolClient tarantoolClient,
            string spaceName,
            string indexName,
            IndexType indexType,
            bool unique,
            params IndexPart[] parts)
        {
            return tarantoolClient.CreateIndexAsync(spaceName, indexName, indexType, unique, CancellationToken.None, parts);
        }

        /// <exception cref="ArgumentException">parts is null or empty.</exception>
        /// <exception cref="IndexAlreadyExistsException"></exception>
        /// <exception cref="TarantoolResponseException"></exception>
        public static async Task CreateIndexAsync(
            this ITarantoolClient tarantoolClient,
            string spaceName,
            string indexName,
            IndexType indexType,
            CancellationToken cancellationToken,
            params IndexPart[] parts)
        {
            try
            {
                if (parts == null || !parts.Any()) throw new ArgumentException(nameof(parts));
                var partsString = string.Join(",", parts.Select(x => $"{x.FieldNumber + 1}, '{x.Type.ToString()}'"));
                await tarantoolClient.EvalAsync(
                        $"box.space.{spaceName}:create_index('{indexName}', {{type = '{indexType}', parts = {{{partsString}}}}})",
                        cancellationToken)
                    .ConfigureAwait(false);
            }
            catch (TarantoolResponseException ex)
            {
                if (ex.Message.StartsWith("Index") && ex.Message.EndsWith("already exists"))
                    throw new IndexAlreadyExistsException(ex.Message, ex);
                throw;
            }
        }

        /// <exception cref="ArgumentException">parts is null or empty.</exception>
        /// <exception cref="IndexAlreadyExistsException"></exception>
        /// <exception cref="TarantoolResponseException"></exception>
        public static async Task CreateIndexAsync(
            this ITarantoolClient tarantoolClient,
            string spaceName,
            string indexName,
            IndexType indexType,
            bool unique,
            CancellationToken cancellationToken,
            params IndexPart[] parts)
        {
            try
            {
                if (parts == null || !parts.Any()) throw new ArgumentException(nameof(parts));
                var partsString = string.Join(",", parts.Select(x => $"{x.FieldNumber + 1}, '{x.Type.ToString()}'"));
                await tarantoolClient.EvalAsync(
                        $"box.space.{spaceName}:create_index('{indexName}', {{type = '{indexType}', unique = {unique.ToString().ToLower()}, parts = {{{partsString}}}}})",
                        cancellationToken)
                    .ConfigureAwait(false);
            }
            catch (TarantoolResponseException ex)
            {
                if (ex.Message.StartsWith("Index") && ex.Message.EndsWith("already exists"))
                    throw new IndexAlreadyExistsException(ex.Message, ex);
                throw;
            }
        }

        /// <exception cref="TarantoolResponseException"></exception>
        public static Task CreateIndexIfNotExistsAsync(
            this ITarantoolClient tarantoolClient,
            string spaceName,
            string indexName,
            IndexType indexType,
            params IndexPart[] parts)
        {
            return tarantoolClient.CreateIndexIfNotExistsAsync(spaceName, indexName, indexType, CancellationToken.None, parts);
        }

        /// <exception cref="TarantoolResponseException"></exception>
        public static Task CreateIndexIfNotExistsAsync(
            this ITarantoolClient tarantoolClient,
            string spaceName,
            string indexName,
            IndexType indexType,
            bool unique,
            params IndexPart[] parts)
        {
            return tarantoolClient.CreateIndexIfNotExistsAsync(spaceName, indexName, indexType, unique, CancellationToken.None, parts);
        }

        /// <exception cref="TarantoolResponseException"></exception>
        public static async Task CreateIndexIfNotExistsAsync(
            this ITarantoolClient tarantoolClient,
            string spaceName,
            string indexName,
            IndexType indexType,
            CancellationToken cancellationToken,
            params IndexPart[] parts)
        {
            try
            {
                await tarantoolClient.CreateIndexAsync(spaceName, indexName, indexType, cancellationToken, parts)
                    .ConfigureAwait(false);
            }
            catch (IndexAlreadyExistsException)
            {
            }
        }

        /// <exception cref="TarantoolResponseException"></exception>
        public static async Task CreateIndexIfNotExistsAsync(
            this ITarantoolClient tarantoolClient,
            string spaceName,
            string indexName,
            IndexType indexType,
            bool unique,
            CancellationToken cancellationToken,
            params IndexPart[] parts)
        {
            try
            {
                await tarantoolClient.CreateIndexAsync(spaceName, indexName, indexType, unique, cancellationToken, parts)
                    .ConfigureAwait(false);
            }
            catch (IndexAlreadyExistsException)
            {
            }
        }

        /// <exception cref="SpaceAlreadyExistsException"></exception>
        /// <exception cref="TarantoolResponseException"></exception>
        public static async Task CreateSpaceAsync(
            this ITarantoolClient tarantoolClient,
            string spaceName,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                await tarantoolClient.EvalAsync($"box.schema.create_space('{spaceName}')", cancellationToken)
                    .ConfigureAwait(false);
            }
            catch (TarantoolResponseException ex)
            {
                if (ex.Message.StartsWith("Space") && ex.Message.EndsWith("already exists"))
                    throw new SpaceAlreadyExistsException(ex.Message, ex);
                throw;
            }
        }

        /// <exception cref="TarantoolResponseException"></exception>
        public static async Task CreateSpaceIfNotExistsAsync(
            this ITarantoolClient tarantoolClient,
            string spaceName,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                await tarantoolClient.CreateSpaceAsync(spaceName, cancellationToken).ConfigureAwait(false);
            }
            catch (SpaceAlreadyExistsException)
            {
            }
        }

        public static async Task DropIndexAsync(
            this ITarantoolClient tarantoolClient,
            string spaceName,
            string indexName,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            await tarantoolClient.EvalAsync($"box.space.{spaceName}.index.{indexName}:drop()", cancellationToken)
                .ConfigureAwait(false);
        }

        public static async Task DropSpaceAsync(
            this ITarantoolClient tarantoolClient,
            string spaceName,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            await tarantoolClient.EvalAsync($"box.space.{spaceName}:drop()", cancellationToken).ConfigureAwait(false);
        }

        public static Task<MessagePackObject> EvalAsync(
            this ITarantoolClient tarantoolClient,
            string expression,
            params object[] args)
        {
            return tarantoolClient.RequestAsync(new EvalRequest { Expression = expression, Args = args });
        }

        public static Task<MessagePackObject> EvalAsync(
            this ITarantoolClient tarantoolClient,
            string expression,
            CancellationToken cancellationToken,
            params object[] args)
        {
            return tarantoolClient.RequestAsync(
                new EvalRequest { Expression = expression, Args = args },
                cancellationToken);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CharacterCreator
{
    public class Character
    {
        private string name;
        public string Name { get { return name; } set { name = value; } }

        private ClassType characterClass;
        public ClassType CharacterClass { get { return characterClass; } set { characterClass = value; } }

        private int level;
        public int Level { get { return level; } set { level = value; } }

        private string str;
        public string Str { get { return str; } set { str = value; } }

        private string cos;
        public string Cos { get { return cos; } set { cos = value; } }

        private string des;
        public string Des { get { return des; } set { des = value; } }

        private string inte;
        public string Inte { get { return inte; } set { inte = value; } }

        private string sag;
        public string Sag { get { return sag; } set { sag = value; } }

        private string car;
        public string Car { get { return car; } set { car = value; } }

        public enum ClassType { Barbaro, Bardo, Chierico, Ladro, Ranger, Druido, Condottiero };

        public Character()
        {

        }
    }
}


text:
<?php

$yii=dirname(__FILE__).'/../yii-framework/yii.php';
$yiic=dirname(__FILE__).'/../../yii-framework/yiic.php';
$config=dirname(__FILE__).'/config/console.php';

require_once($yiic);


text: PayPal basically has two sides: a personal and a business side.


text:
local ActIndex = {
	[ "pistol" ] 		= ACT_HL2MP_IDLE_PISTOL,
	[ "smg" ] 			= ACT_HL2MP_IDLE_SMG1,
	[ "grenade" ] 		= ACT_HL2MP_IDLE_GRENADE,
	[ "ar2" ] 			= ACT_HL2MP_IDLE_AR2,
	[ "shotgun" ] 		= ACT_HL2MP_IDLE_SHOTGUN,
	[ "rpg" ]	 		= ACT_HL2MP_IDLE_RPG,
	[ "physgun" ] 		= ACT_HL2MP_IDLE_PHYSGUN,
	[ "crossbow" ] 		= ACT_HL2MP_IDLE_CROSSBOW,
	[ "melee" ] 		= ACT_HL2MP_IDLE_MELEE,
	[ "slam" ] 			= ACT_HL2MP_IDLE_SLAM,
	[ "normal" ]		= ACT_HL2MP_IDLE,
	[ "fist" ]			= ACT_HL2MP_IDLE_FIST,
	[ "melee2" ]		= ACT_HL2MP_IDLE_MELEE2,
	[ "passive" ]		= ACT_HL2MP_IDLE_PASSIVE,
	[ "knife" ]			= ACT_HL2MP_IDLE_KNIFE,
	[ "duel" ]			= ACT_HL2MP_IDLE_DUEL,
	[ "camera" ]		= ACT_HL2MP_IDLE_CAMERA,
	[ "revolver" ]		= ACT_HL2MP_IDLE_REVOLVER
}

--[[---------------------------------------------------------
   Name: SetWeaponHoldType
   Desc: Sets up the translation table, to translate from normal
			standing idle pose, to holding weapon pose.
-----------------------------------------------------------]]
function SWEP:SetWeaponHoldType( t )

	t = string.lower( t )
	local index = ActIndex[ t ]

	if ( index == nil ) then
		Msg( "SWEP:SetWeaponHoldType - ActIndex[ \""..t.."\" ] isn't set! (defaulting to normal)\n" )
		t = "normal"
		index = ActIndex[ t ]
	end

	self.ActivityTranslate = {}
	self.ActivityTranslate [ ACT_MP_STAND_IDLE ] 				= index
	self.ActivityTranslate [ ACT_MP_WALK ] 						= index+1
	self.ActivityTranslate [ ACT_MP_RUN ] 						= index+2
	self.ActivityTranslate [ ACT_MP_CROUCH_IDLE ] 				= index+3
	self.ActivityTranslate [ ACT_MP_CROUCHWALK ] 				= index+4
	self.ActivityTranslate [ ACT_MP_ATTACK_STAND_PRIMARYFIRE ] 	= index+5
	self.ActivityTranslate [ ACT_MP_ATTACK_CROUCH_PRIMARYFIRE ] = index+5
	self.ActivityTranslate [ ACT_MP_RELOAD_STAND ]		 		= index+6
	self.ActivityTranslate [ ACT_MP_RELOAD_CROUCH ]		 		= index+6
	self.ActivityTranslate [ ACT_MP_JUMP ] 						= index+7
	self.ActivityTranslate [ ACT_RANGE_ATTACK1 ] 				= index+8
	self.ActivityTranslate [ ACT_MP_SWIM_IDLE ] 				= index+8
	self.ActivityTranslate [ ACT_MP_SWIM ] 						= index+9

	-- "normal" jump animation doesn't exist
	if t == "normal" then
		self.ActivityTranslate [ ACT_MP_JUMP ] = ACT_HL2MP_JUMP_SLAM
	end

	self:SetupWeaponHoldTypeForAI( t )

end

-- Default hold pos is the pistol
SWEP:SetWeaponHoldType( "pistol" )

--[[---------------------------------------------------------
   Name: weapon:TranslateActivity( )
   Desc: Translate a player's Activity into a weapon's activity
		 So for example, ACT_HL2MP_RUN becomes ACT_HL2MP_RUN_PISTOL
		 Depending on how you want the player to be holding the weapon
-----------------------------------------------------------]]
function SWEP:TranslateActivity( act )

	if ( self.Owner:IsNPC() ) then
		if ( self.ActivityTranslateAI[ act ] ) then
			return self.ActivityTranslateAI[ act ]
		end
		return -1
	end

	if ( self.ActivityTranslate[ act ] != nil ) then
		return self.ActivityTranslate[ act ]
	end

	return -1

end


text:
/**
 * @author Anton Avtamonov
 * @version $Revision$
 */
package javax.swing;

import java.awt.Component;
import java.awt.Container;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.EventListener;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.BadLocationException;

import junit.framework.TestCase;

public abstract class BasicSwingTestCase extends TestCase {
    public static final long DEFAULT_TIMEOUT_DELAY = 10000;

    private boolean ignoreNotImplemented;
    private Robot robot;
    private LookAndFeel previousLF;

    private static long defaultTimeoutDelay;
    protected static long timeoutDelay;

    static {
        String timeoutProp = System.getProperty("test.timeout");
        if (timeoutProp == null || timeoutProp.length() == 0) {
            defaultTimeoutDelay = DEFAULT_TIMEOUT_DELAY;
        } else {
            defaultTimeoutDelay = Integer.parseInt(timeoutProp);
        }
    }

    @Override
    protected void setUp() throws Exception {
        timeoutDelay = defaultTimeoutDelay;
        previousLF = UIManager.getLookAndFeel();
        super.setUp();
    }

    @Override
    protected void tearDown() throws Exception {
        super.tearDown();
        UIManager.getDefaults().clear();
        if (previousLF != null) {
            UIManager.setLookAndFeel(previousLF);
        } else {
            UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
        }
        JFrame.setDefaultLookAndFeelDecorated(false);
        JDialog.setDefaultLookAndFeelDecorated(false);
        closeAllFrames();
    }

    public static void assertEquals(final Object[] expected, final Object[] actual) {
        if (expected == null && actual == null) {
            return;
        }
        if (expected == null || actual == null) {
            fail("Arrays are not same: one of them is null");
        }
        assertEquals("Arrays of different types", expected.getClass(), actual.getClass());
        assertEquals("Arrays of different lengths", expected.length, actual.length);
        for (int i = 0; i < expected.length; i++) {
            assertEquals("Arrays content at index " + i + " is not same", expected[i], actual[i]);
        }
    }

    public BasicSwingTestCase() {
    }

    public BasicSwingTestCase(final String name) {
        super(name);
    }

    protected void runBareSuper() throws Throwable {
        super.runBare();
    }

    protected Throwable runBareImpl() throws Throwable {
        try {
            runBareSuper();
        } catch (Throwable e) {
            return e;
        }

        return null;
    }

    @Override
    public void runBare() throws Throwable {
        final Throwable[] exception = new Throwable[1];
        Thread thread = new Thread(new Runnable() {
            public void run() {
                try {
                    exception[0] = runBareImpl();
                } catch (Throwable e) {
                }
            }
        });
        thread.start();
        thread.join(timeoutDelay);
        int interruptAttempts = 0;
        while (thread.isAlive()){
            thread.interrupt();
            if (interruptAttempts++ > 5) {
                fail("Test interrupted due timeout");
            }
        }
        if (exception[0] != null) {
            rethrow(exception[0]);
        }
    }

    public void setIgnoreNotImplemented(final boolean b) {
        ignoreNotImplemented = b;
    }

    protected static class Marker {
        private final boolean autoreset;

        private boolean occured;
        private Object auxiliary;

        public Marker() {
            this(false);
        }

        /**
         * If autoreset is turned on, then the call to isOccurred()
         * resets the state just before returning the value.
         *
         * @param autoreset enables the autoreset feature
         */
        public Marker(final boolean autoreset) {
            this.autoreset = autoreset;
        }

        public void setOccurred() {
            setOccurred(true);
        }

        public void setOccurred(final boolean occured) {
            this.occured = occured;
        }

        /**
         * Returns the state of this marker. If autoreset feature is enabled,
         * reset() method will be called before return. Beware that
         * any auxiliary data will also be reset, if the feature is enabled.
         *
         * @return true if an event occurred
         */
        public boolean isOccurred() {
            boolean result = occured;
            if (autoreset) {
                reset();
            }
            return result;
        }

        public void setAuxiliary(final Object aux) {
            auxiliary = aux;
        }

        public Object getAuxiliary() {
            return auxiliary;
        }

        public void reset() {
            occured = false;
            auxiliary = null;
        }

        public boolean isAutoreset() {
            return autoreset;
        }
    }

    private class FixedFontMetrics extends FontMetrics {
        private static final long serialVersionUID = 1L;
        private final int charWidth;
        private final int charHeight;

        public FixedFontMetrics(final Font fnt, final int charWidth) {
            super(fnt);
            this.charWidth = charWidth;
            charHeight = super.getHeight();
        }

        public FixedFontMetrics(final Font fnt, final int charWidth, final int charHeight) {
            super(fnt);
            this.charWidth = charWidth;
            this.charHeight = charHeight;
        }

        @Override
        public int stringWidth(final String str) {
            return ((str == null || str.equals("")) ? 0 : str.length() * charWidth);
        }

        @Override
        public int charWidth(final int ch) {
            return charWidth;
        }

        @Override
        public int charWidth(final char ch) {
            return charWidth;
        }

        @Override
        public int getAscent() {
            return charWidth;
        }

        @Override
        public int getDescent() {
            return charWidth*2;
        }

        @Override
        public int getLeading() {
            return 2;
        }

        @Override
        public int getHeight() {
            return charHeight;
        }
    };

    protected abstract class ExceptionalCase {
        private Class<?> clazz;
        private String msg;

        public abstract void exceptionalAction() throws Exception;

        public ExceptionalCase() {
        }

        public ExceptionalCase(String msg, Class<?> clazz) {
            this.msg = msg;
            this.clazz = clazz;
        }

        public Class<?> expectedExceptionClass() {
            return clazz;
        }

        public String expectedExceptionMessage() {
            return msg;
        }
    }

    protected abstract class BadLocationCase extends ExceptionalCase {
        @Override
        public Class<?> expectedExceptionClass() {
            return BadLocationException.class;
        }
    }

    protected abstract class ClassCastCase extends ExceptionalCase {
        @Override
        public Class<?> expectedExceptionClass() {
            return ClassCastException.class;
        }
    }

    protected abstract class IllegalArgumentCase extends ExceptionalCase {
        @Override
        public Class<?> expectedExceptionClass() {
            return IllegalArgumentException.class;
        }
    }

    protected abstract class NullPointerCase extends ExceptionalCase {
        @Override
        public Class<?> expectedExceptionClass() {
            return NullPointerException.class;
        }
    }

    protected abstract class StringIndexOutOfBoundsCase extends ExceptionalCase {
        @Override
        public Class<?> expectedExceptionClass() {
            return StringIndexOutOfBoundsException.class;
        }
    }

    protected static class EventsController implements Serializable {
        private static final long serialVersionUID = 1L;
        private boolean isVerbose;
        private Object lastEventHappened;
        private final Map<Object, Object> events = new HashMap<Object, Object>();

        protected EventsController() {
            this(false);
        }

        protected EventsController(final boolean verbose) {
            isVerbose = verbose;
        }

        public void setVerbose(final boolean verbose) {
            isVerbose = verbose;
        }

        protected boolean isVerbose() {
            return isVerbose;
        }

        public void reset() {
            lastEventHappened = null;
            events.clear();
        }

        public boolean isChanged() {
            return events.size() != 0;
        }

        public boolean isChanged(final Object key) {
            if (!isChanged() || key == null) {
                return false;
            }
            for (Iterator<Object> it = events.keySet().iterator(); it.hasNext(); ) {
                String property = (String)it.next();
                if (key.equals(property)) {
                    return true;
                }
            }

            return false;
        }

        protected void addEvent(final Object key, final Object event) {
            events.put(key, event);
            lastEventHappened = event;
        }

        public Object getEvent(final Object key) {
            return events.get(key);
        }

        public Object getLastEvent() {
            return lastEventHappened;
        }

        public int getNumEvents() {
            return events.size();
        }

        public int findMe(final Object[] listenersArray) {
            int found = 0;
            for (Object element : listenersArray) {
                if (element == this) {
                    found++;
                }
            }

            return found;
        }
    }

    protected class PropertyChangeController extends EventsController implements PropertyChangeListener {
        private static final long serialVersionUID = 1L;
        public PropertyChangeController() {
            super(false);
        }

        public PropertyChangeController(final boolean verbose) {
            super(verbose);
        }

        public void propertyChange(final PropertyChangeEvent e) {
            addEvent(e.getPropertyName(), e);
            if (isVerbose()) {
                System.out.println("Changed property " + e.getPropertyName() + ", old value = '" + e.getOldValue() + "', new value = '" + e.getNewValue() + "'");
            }
        }

        public void checkLastPropertyFired(final Object source, final String propertyName,
                                        final Object oldValue, final Object newValue) {
            PropertyChangeEvent lastEvent = (PropertyChangeEvent)getLastEvent();
            checkEvent(lastEvent, source, propertyName, oldValue, newValue);
        }

        public void checkPropertyFired(final Object source, final String propertyName,
                                       final Object oldValue, final Object newValue) {
            PropertyChangeEvent e = (PropertyChangeEvent)getEvent(propertyName);
            checkEvent(e, source, propertyName, oldValue, newValue);
        }

        private void checkEvent(PropertyChangeEvent event, final Object source,
                               final String propertyName,
                               final Object oldValue, final Object newValue) {
               assertNotNull("event's been fired ", event);
               assertEquals("event's property name ", propertyName, event.getPropertyName());
               assertEquals("event's oldValue ", oldValue, event.getOldValue());
               assertEquals("event's newValue ", newValue, event.getNewValue());
               assertSame("event's source ", source, event.getSource());
           }
    }

    protected class ChangeController extends EventsController implements ChangeListener {
        private static final long serialVersionUID = 1L;

        public ChangeController() {
            super(false);
        }

        public ChangeController(final boolean verbose) {
            super(verbose);
        }

        public void stateChanged(ChangeEvent e) {
            addEvent(new Integer(getNumEvents()), e);
            if (isVerbose()) {
                System.out.println("Changed");
            }
        }

        public ChangeEvent getEvent() {
            return (ChangeEvent)getLastEvent();
        }
    }

    protected interface TraverseAction {
        void componentTraversed(Component c);
    }

    /**
     * PropertyChangeListener for test purposes to easily check that some property was changed
     */
    protected PropertyChangeController propertyChangeController;

    public static boolean isHarmony() {
        return Toolkit.getDefaultToolkit().getClass().getName().equals("java.awt.ToolkitImpl");
    }

    /**
     * Serializes an object and returns the deserialized version of this object.
     *
     * @param objectToWrite object to serialize
     * @return the deserialized object if successful
     * @throws IOException if write or read operation throws this exception.
     * @throws ClassNotFoundException if object cannot be read
     *                                from an input stream
     */
    public static Object serializeObject(final Object objectToWrite)
        throws IOException, ClassNotFoundException {

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(output);
        oos.writeObject(objectToWrite);
        oos.close();
        output.close();

        InputStream input = new ByteArrayInputStream(output.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(input);
        Object result = ois.readObject();
        ois.close();
        input.close();

        return result;
    }

    protected Graphics createTestGraphics() {
        return new BufferedImage(300, 300, BufferedImage.TYPE_3BYTE_BGR).createGraphics();
    }

    protected FontMetrics getFontMetrics(final Font fnt) {
        return new FixedFontMetrics(fnt, fnt.getSize());
    }

    protected FontMetrics getFontMetrics(final Font fnt, final int charWidth) {
        return new FixedFontMetrics(fnt, charWidth);
    }

    protected FontMetrics getFontMetrics(final Font fnt, final int charWidth, final int charHeight) {
        return new FixedFontMetrics(fnt, charWidth, charHeight);
    }

    protected void testExceptionalCase(final ExceptionalCase ec) {
        try {
            ec.exceptionalAction();
            fail("Exceptional case was not detected!");
        } catch (final Exception e) {
            if (ec.expectedExceptionClass() != null) {
                if (!ec.expectedExceptionClass().isAssignableFrom(e.getClass())) {
                    fail("Exception of wrong type " + e.getClass() + " is produced!");
                }
            }
            if (ec.expectedExceptionMessage() != null) {
                assertEquals("Wrong exception message", ec.expectedExceptionMessage(),
                             e.getMessage());
            }
        }
    }

    protected void traverseComponentTree(final Component root, final TraverseAction action) {
        action.componentTraversed(root);
        if (root instanceof Container) {
            for (int i = 0; i < ((Container)root).getComponentCount(); i++) {
                traverseComponentTree(((Container)root).getComponent(i), action);
            }
        }
    }

    protected void rethrow(final Throwable exception) throws Throwable {
        String msg = exception.getMessage();
        if (!ignoreNotImplemented || msg == null
                || exception.getMessage().indexOf("implemented") == -1) {
            throw exception;
        }
    }

    protected void waitForIdle() throws Exception {
        if (SwingUtilities.isEventDispatchThread()) {
            getRobot().waitForIdle();
        } else {
            SwingUtilities.invokeAndWait(new Thread());
        }
    }

    protected boolean hasListener(final EventListener[] listeners, final Class<?> listenerClass) {
        return getListener(listeners, listenerClass) != null;
    }

    protected EventListener getListener(final EventListener[] listeners, final Class<?> listenerClass) {
        for (EventListener element : listeners) {
            if (element.getClass().isAssignableFrom(listenerClass)) {
                return element;
            }
        }

        return null;
    }

    protected boolean waitForFocus(final Component c) throws Exception {
        int counter = 0;
        while(true) {
            if (isFocusOwner(c)) {
                return true;
            }
            Thread.sleep(100);
            counter++;
            if (counter > 10) {
                return false;
            }
        }
    }

    protected boolean isSystemWindow(final Frame f) {
        return "JUnit".equals(f.getTitle());
    }

    protected Component findComponent(final Container root, final Class<?> findClass, final boolean exactClassMatch) {
        if (exactClassMatch && findClass == root.getClass()
            || !exactClassMatch && findClass.isAssignableFrom(root.getClass())) {

            return root;
        }

        for (int i = 0; i < root.getComponentCount(); i++) {
            Component child = root.getComponent(i);
            if (child instanceof Container) {
                child = findComponent((Container)child, findClass, exactClassMatch);
                if (child != null) {
                    return child;
                }
            } else if (exactClassMatch && findClass == child.getClass()
                       || !exactClassMatch && findClass.isAssignableFrom(child.getClass())) {

                return child;
            }
        }

        return null;
    }

    private boolean isFocusOwner(final Component c) throws Exception {
        final Marker result = new Marker();
        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
                result.setOccurred(c.isFocusOwner());
            }
        });

        return result.isOccurred();
    }

    private Robot getRobot() throws Exception {
        if (robot == null) {
            robot = new Robot();
        }

        return robot;
    }

    private void closeAllFrames() {
        Frame[] frames = Frame.getFrames();
        for (Frame f : frames) {
            if (f.isDisplayable()) {
                if (!isSystemWindow(f)) {
                    f.dispose();
                }
            }
        }
    }
}


text:
using System;
using NFabric.Contracts;

namespace NFabric.Samples.Sales.Commands.SalesOrder.Lines
{
    public class ChangeOrderLinePrice
    {
        public Guid SalesOrder { get; private set; }

        public Guid Line { get; private set; }

        public MonetaryValue UnitPrice { get; private set; }

        public decimal Discount { get; private set; }

        public MonetaryValue DiscountedPrice { get; private set; }

        public ChangeOrderLinePrice(Guid salesOrder, Guid line, MonetaryValue unitPrice, decimal discount, MonetaryValue discountedPrice)
        {
            SalesOrder = salesOrder;
            Line = line;
            UnitPrice = unitPrice;
            Discount = discount;
            DiscountedPrice = discountedPrice;
        }
    }
}


text:
"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.NumberAttributeMock = void 0;
var attribute_mock_1 = require("../attribute/attribute.mock");
var NumberAttributeMock = /** @class */ (function (_super) {
    __extends(NumberAttributeMock, _super);
    function NumberAttributeMock(components) {
        var _this = _super.call(this, NumberAttributeMock.defaultComponents(components)) || this;
        _this.min = components.min;
        _this.max = components.max;
        _this.precision = components.precision;
        _this.validatePrecision();
        return _this;
    }
    NumberAttributeMock.defaultComponents = function (components) {
        components.format = components.format || "none";
        components.precision = components.precision || 0;
        if (!components.attributeType) {
            components.attributeType = "decimal";
        }
        return components;
    };
    NumberAttributeMock.prototype.getFormat = function () {
        return _super.prototype.getFormat.call(this);
    };
    NumberAttributeMock.prototype.getMax = function () {
        return this.max;
    };
    NumberAttributeMock.prototype.getMin = function () {
        return this.min;
    };
    NumberAttributeMock.prototype.getPrecision = function () {
        return this.precision;
    };
    NumberAttributeMock.prototype.setPrecision = function (value) {
        this.precision = value;
    };
    NumberAttributeMock.prototype.setValue = function (value) {
        if ((this.min || this.min === 0) && this.min > value) {
            throw new Error(("value cannot be below the min of " + this.min));
        }
        else if ((this.max || this.max === 0) && this.max < value) {
            throw new Error(("value cannot be above the max of " + this.max));
        }
        else {
            _super.prototype.setValue.call(this, value);
        }
    };
    NumberAttributeMock.prototype.validatePrecision = function () {
        if (this.precision > 10) {
            throw new Error(("precision cannot be greater than 10, but was " + this.precision));
        }
        else if (this.precision < 0) {
            throw new Error(("precision cannot be less than 0, but was " + this.precision));
        }
    };
    return NumberAttributeMock;
}(attribute_mock_1.AttributeMock));
exports.NumberAttributeMock = NumberAttributeMock;
//# sourceMappingURL=numberattribute.mock.js.map


text:
<?php

namespace KoolKode\BPMN\Gateway;

use KoolKode\BPMN\Test\BusinessProcessTestCase;

class LinkEventTest extends BusinessProcessTestCase
{
    public function test1()
    {
        $this->deployFile('LinkEvent1.bpmn');

        $this->runtimeService->startProcessInstanceByKey('LinkEvent1');

        $tasks = $this->taskService->createTaskQuery()->orderByTaskDefinitionKey()->findAll();
        $this->assertCount(2, $tasks);
        $this->assertEquals('task1', $tasks[0]->getDefinitionKey());
        $this->assertEquals('task2', $tasks[1]->getDefinitionKey());

        $this->taskService->complete($tasks[0]->getId());
        $this->taskService->complete($tasks[1]->getId());

        $this->assertEquals(0, $this->runtimeService->createExecutionQuery()->count());
    }

    public function test2()
    {
        $this->deployFile('LinkEvent2.bpmn');

        $this->runtimeService->startProcessInstanceByKey('LinkEvent2');

        $tasks = $this->taskService->createTaskQuery()->orderByTaskDefinitionKey()->findAll();
        $this->assertCount(2, $tasks);
        $this->assertEquals('task1', $tasks[0]->getDefinitionKey());
        $this->assertEquals('task1', $tasks[1]->getDefinitionKey());

        $this->taskService->complete($tasks[0]->getId());
        $this->taskService->complete($tasks[1]->getId());

        $this->assertEquals(0, $this->runtimeService->createExecutionQuery()->count());
    }
}