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 com.facebook.presto.verifier.prestoaction;

import com.facebook.presto.connector.thrift.ThriftErrorCode;
import com.facebook.presto.hive.HiveErrorCode;
import com.facebook.presto.jdbc.QueryStats;
import com.facebook.presto.plugin.jdbc.JdbcErrorCode;
import com.facebook.presto.spi.ErrorCodeSupplier;
import com.facebook.presto.spi.StandardErrorCode;
import com.facebook.presto.verifier.framework.ClusterConnectionException;
import com.facebook.presto.verifier.framework.PrestoQueryException;
import com.facebook.presto.verifier.framework.QueryException;
import com.facebook.presto.verifier.framework.QueryStage;
import com.google.common.collect.ImmutableSet;

import java.io.EOFException;
import java.io.UncheckedIOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.sql.SQLException;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeoutException;
import java.util.regex.Pattern;

import static com.facebook.presto.connector.thrift.ThriftErrorCode.THRIFT_SERVICE_CONNECTION_ERROR;
import static com.facebook.presto.hive.HiveErrorCode.HIVE_CANNOT_OPEN_SPLIT;
import static com.facebook.presto.hive.HiveErrorCode.HIVE_CURSOR_ERROR;
import static com.facebook.presto.hive.HiveErrorCode.HIVE_FILESYSTEM_ERROR;
import static com.facebook.presto.hive.HiveErrorCode.HIVE_FILE_NOT_FOUND;
import static com.facebook.presto.hive.HiveErrorCode.HIVE_METASTORE_ERROR;
import static com.facebook.presto.hive.HiveErrorCode.HIVE_PARTITION_DROPPED_DURING_QUERY;
import static com.facebook.presto.hive.HiveErrorCode.HIVE_TABLE_DROPPED_DURING_QUERY;
import static com.facebook.presto.hive.HiveErrorCode.HIVE_TOO_MANY_OPEN_PARTITIONS;
import static com.facebook.presto.hive.HiveErrorCode.HIVE_WRITER_CLOSE_ERROR;
import static com.facebook.presto.hive.HiveErrorCode.HIVE_WRITER_DATA_ERROR;
import static com.facebook.presto.hive.HiveErrorCode.HIVE_WRITER_OPEN_ERROR;
import static com.facebook.presto.plugin.jdbc.JdbcErrorCode.JDBC_ERROR;
import static com.facebook.presto.spi.StandardErrorCode.ABANDONED_TASK;
import static com.facebook.presto.spi.StandardErrorCode.ADMINISTRATIVELY_PREEMPTED;
import static com.facebook.presto.spi.StandardErrorCode.CLUSTER_OUT_OF_MEMORY;
import static com.facebook.presto.spi.StandardErrorCode.EXCEEDED_TIME_LIMIT;
import static com.facebook.presto.spi.StandardErrorCode.NO_NODES_AVAILABLE;
import static com.facebook.presto.spi.StandardErrorCode.PAGE_TRANSPORT_ERROR;
import static com.facebook.presto.spi.StandardErrorCode.PAGE_TRANSPORT_TIMEOUT;
import static com.facebook.presto.spi.StandardErrorCode.REMOTE_HOST_GONE;
import static com.facebook.presto.spi.StandardErrorCode.REMOTE_TASK_ERROR;
import static com.facebook.presto.spi.StandardErrorCode.SERVER_SHUTTING_DOWN;
import static com.facebook.presto.spi.StandardErrorCode.SERVER_STARTING_UP;
import static com.facebook.presto.spi.StandardErrorCode.SYNTAX_ERROR;
import static com.facebook.presto.spi.StandardErrorCode.TOO_MANY_REQUESTS_FAILED;
import static com.facebook.presto.verifier.framework.QueryStage.CONTROL_SETUP;
import static com.facebook.presto.verifier.framework.QueryStage.DESCRIBE;
import static com.facebook.presto.verifier.framework.QueryStage.TEST_SETUP;
import static com.google.common.base.Functions.identity;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static java.util.Arrays.asList;
import static java.util.Objects.requireNonNull;
import static java.util.regex.Pattern.CASE_INSENSITIVE;

public class PrestoExceptionClassifier
        implements SqlExceptionClassifier
{
    private static final Pattern TABLE_ALREADY_EXISTS_PATTERN = Pattern.compile("table.*already exists", CASE_INSENSITIVE);

    private final Map<Integer, ErrorCodeSupplier> errorByCode;
    private final Set<ErrorCodeSupplier> retryableErrors;
    private final Set<ErrorMatcher> conditionalRetryableErrors;
    private final Set<ErrorCodeSupplier> resubmittedErrors;
    private final Set<ErrorMatcher> conditionalResubmittedErrors;

    private PrestoExceptionClassifier(
            Set<ErrorCodeSupplier> recognizedErrors,
            Set<ErrorCodeSupplier> retryableErrors,
            Set<ErrorMatcher> conditionalRetryableErrors,
            Set<ErrorCodeSupplier> resubmittedErrors,
            Set<ErrorMatcher> conditionalResubmittedErrors)
    {
        this.errorByCode = recognizedErrors.stream()
                .collect(toImmutableMap(errorCode -> errorCode.toErrorCode().getCode(), identity()));
        this.retryableErrors = ImmutableSet.copyOf(retryableErrors);
        this.conditionalRetryableErrors = ImmutableSet.copyOf(conditionalRetryableErrors);
        this.resubmittedErrors = ImmutableSet.copyOf(resubmittedErrors);
        this.conditionalResubmittedErrors = ImmutableSet.copyOf(conditionalResubmittedErrors);
    }

    public static Builder defaultBuilder()
    {
        return new Builder()
                .addRecognizedErrors(asList(StandardErrorCode.values()))
                .addRecognizedErrors(asList(HiveErrorCode.values()))
                .addRecognizedErrors(asList(JdbcErrorCode.values()))
                .addRecognizedErrors(asList(ThriftErrorCode.values()))
                // From StandardErrorCode
                .addRetryableError(NO_NODES_AVAILABLE)
                .addRetryableError(REMOTE_TASK_ERROR)
                .addRetryableError(SERVER_SHUTTING_DOWN)
                .addRetryableError(SERVER_STARTING_UP)
                .addRetryableError(TOO_MANY_REQUESTS_FAILED)
                .addRetryableError(PAGE_TRANSPORT_ERROR)
                .addRetryableError(PAGE_TRANSPORT_TIMEOUT)
                .addRetryableError(REMOTE_HOST_GONE)
                .addRetryableError(ABANDONED_TASK)
                // From HiveErrorCode
                .addRetryableError(HIVE_CURSOR_ERROR)
                .addRetryableError(HIVE_FILE_NOT_FOUND)
                .addRetryableError(HIVE_TOO_MANY_OPEN_PARTITIONS)
                .addRetryableError(HIVE_WRITER_OPEN_ERROR)
                .addRetryableError(HIVE_WRITER_CLOSE_ERROR)
                .addRetryableError(HIVE_WRITER_DATA_ERROR)
                .addRetryableError(HIVE_FILESYSTEM_ERROR)
                .addRetryableError(HIVE_CANNOT_OPEN_SPLIT)
                .addRetryableError(HIVE_METASTORE_ERROR)
                // From JdbcErrorCode
                .addRetryableError(JDBC_ERROR)
                // From ThriftErrorCode
                .addRetryableError(THRIFT_SERVICE_CONNECTION_ERROR)
                // Conditional Retryable Errors
                .addRetryableError(EXCEEDED_TIME_LIMIT, Optional.of(DESCRIBE), Optional.empty())
                // Resubmitted Errors
                .addResubmittedError(HIVE_PARTITION_DROPPED_DURING_QUERY)
                .addResubmittedError(HIVE_TABLE_DROPPED_DURING_QUERY)
                .addResubmittedError(CLUSTER_OUT_OF_MEMORY)
                .addResubmittedError(ADMINISTRATIVELY_PREEMPTED)
                // Conditional Resubmitted Errors
                .addResubmittedError(SYNTAX_ERROR, Optional.of(CONTROL_SETUP), Optional.of(TABLE_ALREADY_EXISTS_PATTERN))
                .addResubmittedError(SYNTAX_ERROR, Optional.of(TEST_SETUP), Optional.of(TABLE_ALREADY_EXISTS_PATTERN));
    }

    public QueryException createException(QueryStage queryStage, Optional<QueryStats> queryStats, SQLException cause)
    {
        Optional<Throwable> clusterConnectionExceptionCause = getClusterConnectionExceptionCause(cause);
        if (clusterConnectionExceptionCause.isPresent()) {
            return new ClusterConnectionException(clusterConnectionExceptionCause.get(), queryStage);
        }

        Optional<ErrorCodeSupplier> errorCode = Optional.ofNullable(errorByCode.get(cause.getErrorCode()));
        boolean retryable = errorCode.isPresent()
                && (retryableErrors.contains(errorCode.get())
                || conditionalRetryableErrors.stream().anyMatch(matcher -> matcher.matches(errorCode.get(), queryStage, cause.getMessage())));
        return new PrestoQueryException(cause, retryable, queryStage, errorCode, queryStats);
    }

    public boolean shouldResubmit(Throwable throwable)
    {
        if (!(throwable instanceof PrestoQueryException)) {
            return false;
        }
        PrestoQueryException queryException = (PrestoQueryException) throwable;
        Optional<ErrorCodeSupplier> errorCode = queryException.getErrorCode();
        return errorCode.isPresent()
                && (resubmittedErrors.contains(errorCode.get())
                || conditionalResubmittedErrors.stream().anyMatch(matcher -> matcher.matches(errorCode.get(), queryException.getQueryStage(), queryException.getMessage())));
    }

    public static boolean isClusterConnectionException(Throwable t)
    {
        return getClusterConnectionExceptionCause(t).isPresent();
    }

    private static Optional<Throwable> getClusterConnectionExceptionCause(Throwable t)
    {
        while (t != null) {
            if (t instanceof SocketTimeoutException ||
                    t instanceof SocketException ||
                    t instanceof EOFException ||
                    t instanceof UncheckedIOException ||
                    t instanceof TimeoutException ||
                    (t.getClass().equals(RuntimeException.class) && t.getMessage() != null && t.getMessage().contains("Error fetching next at"))) {
                return Optional.of(t);
            }
            t = t.getCause();
        }
        return Optional.empty();
    }

    public static class Builder
    {
        private final ImmutableSet.Builder<ErrorCodeSupplier> recognizedErrors = ImmutableSet.builder();
        private final ImmutableSet.Builder<ErrorCodeSupplier> retryableErrors = ImmutableSet.builder();
        private final ImmutableSet.Builder<ErrorMatcher> conditionalRetryableErrors = ImmutableSet.builder();
        private final ImmutableSet.Builder<ErrorCodeSupplier> resubmittedErrors = ImmutableSet.builder();
        private final ImmutableSet.Builder<ErrorMatcher> conditionalResubmittedErrors = ImmutableSet.builder();

        private Builder()
        {
        }

        public Builder addRecognizedErrors(Iterable<ErrorCodeSupplier> errors)
        {
            this.recognizedErrors.addAll(errors);
            return this;
        }

        public Builder addRetryableError(ErrorCodeSupplier error)
        {
            this.retryableErrors.add(error);
            return this;
        }

        public Builder addRetryableError(ErrorCodeSupplier errorCode, Optional<QueryStage> queryStage, Optional<Pattern> errorMessagePattern)
        {
            this.conditionalRetryableErrors.add(new ErrorMatcher(errorCode, queryStage, errorMessagePattern));
            return this;
        }

        public Builder addResubmittedError(ErrorCodeSupplier error)
        {
            this.resubmittedErrors.add(error);
            return this;
        }

        public Builder addResubmittedError(ErrorCodeSupplier errorCode, Optional<QueryStage> queryStage, Optional<Pattern> errorMessagePattern)
        {
            this.conditionalResubmittedErrors.add(new ErrorMatcher(errorCode, queryStage, errorMessagePattern));
            return this;
        }

        public PrestoExceptionClassifier build()
        {
            Set<ErrorCodeSupplier> recognizedErrors = this.recognizedErrors.build();
            Set<ErrorCodeSupplier> retryableErrors = this.retryableErrors.build();
            Set<ErrorMatcher> conditionalRetryableErrors = this.conditionalRetryableErrors.build();
            Set<ErrorCodeSupplier> resubmittedErrors = this.resubmittedErrors.build();
            Set<ErrorMatcher> conditionalResubmittedErrors = this.conditionalResubmittedErrors.build();

            retryableErrors.forEach(error -> checkArgument(recognizedErrors.contains(error), "Error not recognized: %s", error));
            conditionalRetryableErrors.forEach(
                    errorMatcher -> checkArgument(recognizedErrors.contains(errorMatcher.getErrorCode()), "Error not recognized: %s", errorMatcher.getErrorCode()));
            resubmittedErrors.forEach(error -> checkArgument(recognizedErrors.contains(error), "Error not recognized: %s", error));
            conditionalResubmittedErrors.forEach(
                    errorMatcher -> checkArgument(recognizedErrors.contains(errorMatcher.getErrorCode()), "Error not recognized: %s", errorMatcher.getErrorCode()));

            return new PrestoExceptionClassifier(
                    recognizedErrors,
                    retryableErrors,
                    conditionalRetryableErrors,
                    resubmittedErrors,
                    conditionalResubmittedErrors);
        }
    }

    private static class ErrorMatcher
    {
        private final ErrorCodeSupplier errorCode;
        private final Optional<QueryStage> queryStage;
        private final Optional<Pattern> errorMessagePattern;

        public ErrorMatcher(
                ErrorCodeSupplier errorCode,
                Optional<QueryStage> queryStage,
                Optional<Pattern> errorMessagePattern)
        {
            this.errorCode = requireNonNull(errorCode, "errorCode is null");
            this.queryStage = requireNonNull(queryStage, "queryStage is null");
            this.errorMessagePattern = requireNonNull(errorMessagePattern, "errorMessagePattern is null");
        }

        public ErrorCodeSupplier getErrorCode()
        {
            return errorCode;
        }

        public boolean matches(ErrorCodeSupplier errorCode, QueryStage queryStage, String errorMessage)
        {
            return this.errorCode.equals(errorCode)
                    && (!this.queryStage.isPresent() || this.queryStage.get().equals(queryStage))
                    && (!this.errorMessagePattern.isPresent() || this.errorMessagePattern.get().matcher(errorMessage).find());
        }

        @Override
        public boolean equals(Object obj)
        {
            if (this == obj) {
                return true;
            }
            if (obj == null || getClass() != obj.getClass()) {
                return false;
            }
            ErrorMatcher o = (ErrorMatcher) obj;
            return Objects.equals(errorCode, o.errorCode) &&
                    Objects.equals(queryStage, o.queryStage) &&
                    Objects.equals(errorMessagePattern, o.errorMessagePattern);
        }

        @Override
        public int hashCode()
        {
            return Objects.hash(errorCode, queryStage, errorMessagePattern);
        }

        @Override
        public String toString()
        {
            return toStringHelper(this)
                    .add("errorCode", errorCode)
                    .add("queryStage", queryStage)
                    .add("errorMessagePattern", errorMessagePattern)
                    .toString();
        }
    }
}


text:
require 'gosu'
require_relative 'tile'
require_relative 'player'

class Level
  def initialize(window, player, level_data)
    @window = window
    @tiles = []
    @player = player
    @level_data = level_data
    @total_rows = 0
    @total_columns = 0
    @exit_reached = false
    if @level_data
      @total_rows = @level_data.length
      if @total_rows > 0
        @total_columns = @level_data.first.length
      end
      setup_level
    end
  end

  def setup_level
    @level_data.each_with_index do |row_data, row|
      column = 0
      row_data.each_char do |cell_type|
        tile = Tile.new(@window, column, row, cell_type)
        # change behavior depending on cell_type
        if tile.is_start?
          @player.move_to(column, row)
        end
        @tiles.push(tile)
        column += 1
      end
    end
  end

  def button_down(id)
    if level_over?
      return
    end
    column_delta = 0
    row_delta = 0
    if id == Gosu::KbLeft
      column_delta = -1
    elsif id == Gosu::KbRight
      column_delta = 1
    end
    if id == Gosu::KbUp
      row_delta = -1
    elsif id == Gosu::KbDown
      row_delta = 1
    end
    if move_valid?(@player, column_delta, row_delta)
      @player.move_by(column_delta, row_delta)
      tile = get_tile(@player.column, @player.row)
      if tile.is_exit?
        @exit_reached = true
        tile.hide!
      else
        @player.pick_up(tile)
      end
    end
  end

  def get_tile(column, row)
    if column < 0 || column >= @total_columns || row < 0 || row >= @total_rows
      nil
    else
      @tiles[row * @total_columns + column]
    end
  end

  def move_valid?(player, column_delta, row_delta)
    destination = get_tile(player.column + column_delta, player.row + row_delta)
    if destination && destination.tile_can_be_entered?
      true
    else
      false
    end
  end

  def level_over?
    @exit_reached
  end

  def update
  end

  def draw
    @tiles.each do |tile|
      tile.draw
    end
    @player.draw
  end

end

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace common\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

/**
 * User model
 *
 * @property integer $id
 * @property string $username
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property string $auth_key
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 * @property string $password write-only password
 */
class User extends ActiveRecord implements IdentityInterface
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%user}}';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
        ];
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * Finds user by username
     * 通过username查找用户
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * Finds user by password reset token
     * 根据重置密码token查找用户
     *
     * @param string $token password reset token
     * 参数 字符串 重置密码token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     * 检测重置密码token是否合法
     *
     * @param string $token password reset token
     * 参数 字符串 重置密码token
     * @return boolean
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     * 验证密码
     *
     * @param string $password password to validate
     * 参数 字符串 需要验证的密码
     *
     * @return boolean if password provided is valid for current user
     * 返回值 boolean 用户提供的密码是否合法
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     * 根据密码生成密码hash并把它赋值到当前模型
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     * 生成'记住我'的认证key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     * 生成新的充值密码token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     * 删除充值密码token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }
}


text:
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace MassTransit.AutomatonymousIntegration.Tests
{
    using System;
    using System.Threading.Tasks;
    using Automatonymous;
    using NUnit.Framework;
    using Saga;
    using TestFramework;

    namespace Request_Specs
    {
        [TestFixture]
        public class Sending_a_request_from_a_state_machine :
            StateMachineTestFixture
        {
            [Test]
            public async Task Should_handle_the_response()
            {
                Task<ConsumeContext<MemberRegistered>> handler = SubscribeHandler<MemberRegistered>();

                RegisterMember registerMember = new RegisterMemberCommand
                {
                    MemberNumber = Guid.NewGuid().ToString(),
                    Name = "Frank",
                    Address = "123 american way",
                };

                await InputQueueSendEndpoint.Send(registerMember);

                ConsumeContext<MemberRegistered> registered = await handler;

                Guid? saga = await _repository.ShouldContainSaga(x => x.MemberNumber == registerMember.MemberNumber
                    && GetCurrentState(x) == _machine.Registered, TestTimeout);
                Assert.IsTrue(saga.HasValue);

                TestState sagaInstance = _repository[saga.Value].Instance;
                Assert.IsFalse(sagaInstance.ValidateAddressRequestId.HasValue);
            }

            InMemorySagaRepository<TestState> _repository;
            TestStateMachine _machine;

            State GetCurrentState(TestState state)
            {
                return _machine.GetState(state).Result;
            }

            public Sending_a_request_from_a_state_machine()
            {
                _serviceQueueAddress = new Uri("loopback://localhost/service_queue");
            }

            Uri _serviceQueueAddress;

            Uri ServiceQueueAddress
            {
                get { return _serviceQueueAddress; }
                set
                {
                    if (Bus != null)
                        throw new InvalidOperationException("The LocalBus has already been created, too late to change the URI");

                    _serviceQueueAddress = value;
                }
            }

            protected override void ConfigureBus(IInMemoryBusFactoryConfigurator configurator)
            {
                base.ConfigureBus(configurator);

                configurator.ReceiveEndpoint("service_queue", ConfigureServiceQueueEndpoint);
            }

            protected override void ConfigureInputQueueEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
            {
                base.ConfigureInputQueueEndpoint(configurator);

                _repository = new InMemorySagaRepository<TestState>();

                var settings = new RequestSettingsImpl(ServiceQueueAddress, QuartzQueueAddress, TestTimeout);

                _machine = new TestStateMachine(settings);

                configurator.StateMachineSaga(_machine, _repository);
            }

            protected virtual void ConfigureServiceQueueEndpoint(IReceiveEndpointConfigurator configurator)
            {
                configurator.Handler<ValidateAddress>(async context =>
                {
                    Console.WriteLine("Address validated: {0}", context.Message.CorrelationId);

                    context.Respond(new AddressValidatedResponse(context.Message));
                });
            }
        }

        class RegisterMemberCommand :
            RegisterMember
        {
            public string MemberNumber { get; set; }
            public string Name { get; set; }
            public string Address { get; set; }
        }

        class RequestSettingsImpl :
            RequestSettings
        {
            readonly Uri _schedulingServiceAddress;
            readonly Uri _serviceAddress;
            readonly TimeSpan _timeout;

            public RequestSettingsImpl(Uri serviceAddress, Uri schedulingServiceAddress, TimeSpan timeout)
            {
                _serviceAddress = serviceAddress;
                _schedulingServiceAddress = schedulingServiceAddress;
                _timeout = timeout;
            }

            public Uri ServiceAddress
            {
                get { return _serviceAddress; }
            }

            public Uri SchedulingServiceAddress
            {
                get { return _schedulingServiceAddress; }
            }

            public TimeSpan Timeout
            {
                get { return _timeout; }
            }
        }

        class AddressValidatedResponse :
            AddressValidated
        {
            readonly ValidateAddress _message;

            public AddressValidatedResponse(ValidateAddress message)
            {
                _message = message;
            }

            public string Address
            {
                get { return _message.Address.ToUpperInvariant(); }
            }

            public string RequestAddress
            {
                get { return _message.Address; }
            }

            public Guid CorrelationId
            {
                get { return _message.CorrelationId; }
            }
        }

        class TestState :
            SagaStateMachineInstance
        {
            public State CurrentState { get; set; }

            public string MemberNumber { get; set; }
            public string Name { get; set; }
            public string Address { get; set; }

            public Guid? ValidateAddressRequestId { get; set; }

            public Guid CorrelationId { get; set; }
        }

        public interface RegisterMember
        {
            string MemberNumber { get; }
            string Name { get; }
            string Address { get; }
        }

        public interface MemberRegistered
        {
            string Name { get; }
            string Address { get; }
        }

        class MemberRegisteredImpl :
            MemberRegistered
        {
            readonly TestState _state;

            public MemberRegisteredImpl(TestState state)
            {
                _state = state;
            }

            public string Name
            {
                get { return _state.Name; }
            }

            public string Address
            {
                get { return _state.Address; }
            }
        }

        public interface ValidateAddress :
            CorrelatedBy<Guid>
        {
            string Address { get; }
        }

        public interface AddressValidated :
            CorrelatedBy<Guid>
        {
            string Address { get; }

            string RequestAddress { get; }
        }

        class ValidateAddressRequest :
            ValidateAddress
        {
            readonly TestState _instance;

            public ValidateAddressRequest(TestState instance)
            {
                _instance = instance;
            }

            public Guid CorrelationId
            {
                get { return _instance.CorrelationId; }
            }

            public string Address
            {
                get { return _instance.Address; }
            }
        }

        class TestStateMachine :
            MassTransitStateMachine<TestState>
        {
            public TestStateMachine(RequestSettings settings)
            {
                Event(() => Register, x =>
                    x.CorrelateBy(p => p.MemberNumber, p => p.Message.MemberNumber)
                    .SelectId(context => NewId.NextGuid()));

                Request(() => ValidateAddress, x => x.ValidateAddressRequestId, settings);

                Initially(
                    When(Register)
                        .Then(context =>
                        {
                            Console.WriteLine("Registration received: {0}", context.Data.MemberNumber);

                            Console.WriteLine("TestState ID: {0}", context.Instance.CorrelationId);

                            context.Instance.Name = context.Data.Name;
                            context.Instance.Address = context.Data.Address;
                            context.Instance.MemberNumber = context.Data.MemberNumber;
                        })
                        .Request(ValidateAddress, context => new ValidateAddressRequest(context.Instance))
                        .TransitionTo(ValidateAddress.Pending));

                During(ValidateAddress.Pending,
                    When(ValidateAddress.Completed)
                        .ThenAsync(async context =>
                        {
                            await Console.Out.WriteLineAsync("Request Completed!");

                            context.Instance.Address = context.Data.Address;
                        })
                        .Publish(context => new MemberRegisteredImpl(context.Instance))
                        .TransitionTo(Registered),
                    When(ValidateAddress.Faulted)
                        .ThenAsync(async context => await Console.Out.WriteLineAsync("Request Faulted"))
                        .TransitionTo(AddressValidationFaulted),
                    When(ValidateAddress.TimeoutExpired)
                        .ThenAsync(async context => await Console.Out.WriteLineAsync("Request timed out"))
                        .TransitionTo(AddressValidationTimeout));
            }

            public Request<TestState, ValidateAddress, AddressValidated> ValidateAddress { get; private set; }

            public Event<RegisterMember> Register { get; private set; }

            public State Registered { get; private set; }
            public State AddressValidationFaulted { get; private set; }
            public State AddressValidationTimeout { get; private set; }
        }
    }
}


text:
class TypeController;
class TypeUiRecordExplorer;
class TypeUiRecordTableModel;
class TypeUiEditorContainer;
class TypeUiFileExplorer;
class TypeConfig;
class TypeDocument;
class TypeUiEditor;
class TypeUiHtmlTextView;
class TypeRecord;

namespace Ui
{
class TypeUiMainWindow;
}

class TypeUiMainWindow : public QMainWindow, public TypeVariant
{
    Q_OBJECT

public:

    explicit TypeUiMainWindow( TypeController& controller, QWidget* parent = 0 );
    ~TypeUiMainWindow() override;

    void                          UpdateRecordExplorer();
    void                          UpdateFileExplorer();
    void                          UpdateHtmlTextView();
    void                          UpdateHtmlWebView();
    void                          UpdateSceneView();
    void                          UpdateActions();

    void                          InitConnections();
    void                          closeEvent( QCloseEvent* ) override;
    void                          SetTitle( QString title );
    void                          SetCurrentTab( int index );

    M_REFERENCE                   ( Controller,          TypeController )
    M_REFERENCE                   ( RecordExplorer,      TypeUiRecordExplorer )
    M_REFERENCE                   ( FileExplorer,        TypeUiFileExplorer )
    M_REFERENCE                   ( EditorContainer,     TypeUiEditorContainer )
    M_REFERENCE                   ( HtmlTextView,        TypeUiHtmlTextView )

    void                          SetPropertyWidgetRecord( TypeRecord* record );
    void                          SetPropertyWidget( QWidget* widget );
    void                          OpenEditorWidget( TypeUiEditor* widget );

private:

    QWidget*                      m_PropertiesWidget;
    Ui::TypeUiMainWindow*         ui;

};

#define MAINWINDOW_TAB_SCENE   0
#define MAINWINDOW_TAB_EDITOR  1
#define MAINWINDOW_TAB_HTML  2
#define MAINWINDOW_TAB_OUTPUT  3

#endif // UIMAINWINDOW_H


text:
<?php
class Kwc_Favourites_PageTest extends Kwc_TestAbstract
{
    private $_previousUserModel;
    public function setUp()
    {
        parent::setUp('Kwc_Favourites_Root');

        //use custom user model
        $this->_previousUserModel = Kwf_Registry::get('config')->user->model;
        Kwf_Registry::get('config')->user->model = 'Kwc_Favourites_UserModel';

        //unset existing userModel instance to get new one
        $reg = Kwf_Registry::getInstance()->set('userModel',
            Kwf_Model_Abstract::getInstance('Kwc_Favourites_UserModel')
        );
    }

    public function tearDown()
    {
        parent::tearDown();
        Kwf_Registry::get('config')->user->model = $this->_previousUserModel;
        Kwf_Registry::getInstance()->offsetUnset('userModel');
    }

    //tests if the in this test overwritten userModel works correctly
    public function testUserModel()
    {
        $u = Kwf_Registry::get('userModel')->getAuthedUser();
        $this->assertEquals($u->id, 1);
    }

    public function testGetFavouriteComponentIds()
    {
        $componentIds = Kwc_Favourites_Component::getFavouriteComponentIds('Kwc_Favourites_Favourite_Model');
        $this->assertEquals(count($componentIds), 2);
    }

    public function testComponentLink()
    {
        $c2 = $this->_root->getComponentById(2005)->getComponent();
        $html = $c2->getData()->render();
        $this->assertRegExp("#
2
#", $html, 'Does match with the complete div because this div is needed by JavaScript');
    }

    private function getFavouriteCountFromFavouritesPage($component)
    {
        $html = $component->getData()->render();
        preg_match_all('#
#', $html, $matches);
        return count($matches[0]);
    }

    public function testComponentRemoveAdd()
    {
        $c = $this->_root->getComponentById(2004)->getComponent();
        $count = $this->getFavouriteCountFromFavouritesPage($c);

        $row = $this->_root->getGenerator('page')->getModel()->getRow(2002);
        $row->visible = 0;
        $row->save();
        $this->_process();

        $c = $this->_root->getComponentById(2004)->getComponent();
        $countAfter = $this->getFavouriteCountFromFavouritesPage($c);

        $this->assertEquals($count-1, $countAfter);

        $row = $this->_root->getGenerator('page')->getModel()->getRow(2002);
        $row->visible = 1;
        $row->save();
        $this->_process();

        $c = $this->_root->getComponentById(2004)->getComponent();
        $countAfterAfter = $this->getFavouriteCountFromFavouritesPage($c);

        $this->assertEquals($count, $countAfterAfter);
    }

    public function testComponentRecursiveRemoveAdd()
    {
        $c = $this->_root->getComponentById(2004)->getComponent();
        $count = $this->getFavouriteCountFromFavouritesPage($c);

        $row = $this->_root->getGenerator('page')->getModel()->getRow(2001);
        $row->visible = 0;
        $row->save();
        $this->_process();

        // RecursiveRemove isn't handled correctly and RecusiveAdd is never fired this way
        $c = $this->_root->getComponentById(2004)->getComponent();
        $countAfter = $this->getFavouriteCountFromFavouritesPage($c);

        $this->assertEquals($count-1, $countAfter);

        $row = $this->_root->getGenerator('page')->getModel()->getRow(2001);
        $row->visible = 1;
        $row->save();
        $this->_process();

        $c = $this->_root->getComponentById(2004)->getComponent();
        $countAfterAfter = $this->getFavouriteCountFromFavouritesPage($c);

        $this->assertEquals($count, $countAfterAfter);
    }

    public function testUserAddFavourite()
    {
        $c = $this->_root->getComponentById(2004)->getComponent();
        $count = $this->getFavouriteCountFromFavouritesPage($c);

        $model = Kwf_Model_Abstract::getInstance('Kwc_Favourites_Favourite_Model');
        $row = $model->createRow();
        $row->user_id = 1;
        $row->component_id = '2003';
        $row->save();

        $c = $this->_root->getComponentById(2004)->getComponent();
        $countAfter = $this->getFavouriteCountFromFavouritesPage($c);

        $this->assertEquals($count+1, $countAfter);
    }

    public function testUserRemoveFavourite()
    {
        $c = $this->_root->getComponentById(2004)->getComponent();
        $count = $this->getFavouriteCountFromFavouritesPage($c);

        $model = Kwf_Model_Abstract::getInstance('Kwc_Favourites_Favourite_Model');
        $row = $model->getRow(1);
        $row->delete();

        $c = $this->_root->getComponentById(2004)->getComponent();
        $countAfter = $this->getFavouriteCountFromFavouritesPage($c);

        $this->assertEquals($count-1, $countAfter);
    }
}


text:
<?php
require 'vendor/autoload.php';
require_once 'config.php';

use Aws\Route53\Route53Client;

$r53 = Route53Client::factory(array(
    'key'    => AWSACCESSKEY,
    'secret' => AWSSECRETKEY
));

// Example code from: https://github.com/aws/aws-sdk-php/blob/master/tests/Aws/Tests/Route53/Integration/BasicOperationsTest.php

$command="/sbin/ifconfig " . ETHFACE . " | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'";
$localIP = exec ($command);

// Pull a list of existing records, 100 should be MORE than enough
$set = $r53->listResourceRecordSets(array(
	'HostedZoneId' => R53ZONEID,
	'StartRecordType' => "A",
	'StartRecordName' => R53DOMAINNAME,
	'MaxItems' => "100",
));

// See if there is an existing record
$old = null;
foreach($set['ResourceRecordSets'] as $res){
	if($res['Name'] == R53DOMAINNAME . "." && $res['Type'] == "A"){
		$old = $res;
		break;
		print "found\n";
	}
}

if($old['ResourceRecords'][0]['Value'] != $localIP){
	//The IP Addresses are no longer the same - Update them

	// Delete the old record
	if(!is_null($old)){
		$r53->ChangeResourceRecordSets(array(
			'HostedZoneId' => R53ZONEID,
			'ChangeBatch' => array(
				'Changes' => array(
					array(
						'Action'=> 'DELETE',
						'ResourceRecordSet' => $old
					),
				),
			),
		));
	}

	// Create the new record
	$r53->ChangeResourceRecordSets(array(
		'HostedZoneId' => R53ZONEID,
		'ChangeBatch' => array(
			'Changes' => array(
				array(
					'Action'=> 'CREATE',
					'ResourceRecordSet' => array(
						'Name' => R53DOMAINNAME,
						'Type' => "A",
						'TTL' => 300,
						'ResourceRecords' => array(
							array('Value' => $localIP)
						),
					),
				),
			),
		),
	));

}else{
	//No Change - Do we need to do anything?

}


text:
from twisted.trial import unittest
from buildbot.steps.package.rpm import mock
from buildbot.status.results import SUCCESS
from buildbot.test.util import steps
from buildbot.test.fake.remotecommand import ExpectShell, Expect
from buildbot import config

class TestMock(steps.BuildStepMixin, unittest.TestCase):

    def setUp(self):
        return self.setUpBuildStep()

    def tearDown(self):
        return self.tearDownBuildStep()

    def test_no_root(self):
        self.assertRaises(config.ConfigErrors, lambda :
                mock.Mock())

    def test_class_attrs(self):
        step = self.setupStep(mock.Mock(root='TESTROOT'))
        self.assertEqual(step.command, ['mock', '--root', 'TESTROOT'])

    def test_success(self):
        self.setupStep(mock.Mock(root='TESTROOT'))
        self.expectCommands(
            Expect('rmdir', {'dir': ['build/build.log', 'build/root.log',
                                     'build/state.log']})
            + 0,
            ExpectShell(workdir='wkdir', usePTY='slave-config',
                    command=['mock', '--root', 'TESTROOT'],
                    logfiles={'build.log': 'build.log',
                              'root.log': 'root.log',
                              'state.log': 'state.log'})
            +0)
        self.expectOutcome(result=SUCCESS, status_text=["'mock", '--root', "...'"])
        return self.runStep()

    def test_resultdir_success(self):
        self.setupStep(mock.Mock(root='TESTROOT', resultdir='RESULT'))
        self.expectCommands(
            Expect('rmdir', {'dir': ['build/RESULT/build.log',
                                     'build/RESULT/root.log',
                                     'build/RESULT/state.log']})
            + 0,
            ExpectShell(workdir='wkdir', usePTY='slave-config',
                        command=['mock', '--root', 'TESTROOT',
                                 '--resultdir', 'RESULT'],
                        logfiles={'build.log': 'RESULT/build.log',
                                  'root.log': 'RESULT/root.log',
                                  'state.log': 'RESULT/state.log'})
            +0)
        self.expectOutcome(result=SUCCESS, status_text=["'mock", '--root', "...'"])
        return self.runStep()

class TestMockBuildSRPM(steps.BuildStepMixin, unittest.TestCase):

    def setUp(self):
        return self.setUpBuildStep()

    def tearDown(self):
        return self.tearDownBuildStep()

    def test_no_spec(self):
        self.assertRaises(config.ConfigErrors, lambda :
                mock.MockBuildSRPM(root='TESTROOT'))

    def test_success(self):
        self.setupStep(mock.MockBuildSRPM(root='TESTROOT', spec="foo.spec"))
        self.expectCommands(
                Expect('rmdir', {'dir': ['build/build.log', 'build/root.log',
                                         'build/state.log']})
                + 0,
                ExpectShell(workdir='wkdir', usePTY='slave-config',
                            command=['mock', '--root', 'TESTROOT',
                                     '--buildsrpm', '--spec', 'foo.spec',
                                     '--sources', '.'],
                            logfiles={'build.log': 'build.log',
                                      'root.log': 'root.log',
                                      'state.log': 'state.log'},)
                +0)
        self.expectOutcome(result=SUCCESS, status_text=['mock buildsrpm'])
        return self.runStep()

class TestMockRebuild(steps.BuildStepMixin, unittest.TestCase):

    def setUp(self):
        return self.setUpBuildStep()

    def tearDown(self):
        return self.tearDownBuildStep()

    def test_no_srpm(self):
        self.assertRaises(config.ConfigErrors, lambda :
                mock.MockRebuild(root='TESTROOT'))

    def test_success(self):
        self.setupStep(mock.MockRebuild(root='TESTROOT', srpm="foo.src.rpm"))
        self.expectCommands(
                Expect('rmdir', {'dir': ['build/build.log', 'build/root.log',
                                         'build/state.log']})
                + 0,
                ExpectShell(workdir='wkdir', usePTY='slave-config',
                            command=['mock', '--root', 'TESTROOT',
                                     '--rebuild', 'foo.src.rpm'],
                            logfiles={'build.log': 'build.log',
                                      'root.log': 'root.log',
                                      'state.log': 'state.log'},)
                +0)
        self.expectOutcome(result=SUCCESS, status_text=['mock rebuild srpm'])
        return self.runStep()


text:
package io.sarl.eclipse.runtime;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import com.google.common.base.Objects;
import com.google.common.base.Strings;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jdt.launching.LibraryLocation;
import org.eclipse.jdt.launching.PropertyChangeEvent;
import org.osgi.framework.Bundle;
import org.osgi.framework.Version;

import io.sarl.eclipse.SARLEclipsePlugin;
import io.sarl.eclipse.util.Utilities;

/**
 * Abstract implementation of a SRE install.
 *
 *
Clients implementing SRE installs must subclass this class.
 *
 * @author $Author: sgalland$
 * @version $FullVersion$
 * @mavengroupid $GroupId$
 * @mavenartifactid $ArtifactId$
 */
public abstract class AbstractSREInstall implements ISREInstall {

	private String id;

	private String name;

	private String minimalSarlVersion;

	private String maximalSarlVersion;

	private String mainClass;

	private boolean isStandalone;

	private LibraryLocation[] libraryLocations;

	private Map<String, String> attributeMap;

	private boolean dirty = true;

	/** Whether change events should be fired.
	 */
	private boolean notify = true;

	/** Construct a SRE installation.
	 *
	 * @param id - the identifier of this SRE installation.
	 */
	public AbstractSREInstall(String id) {
		this.id = id;
	}

	@Override
	public AbstractSREInstall clone() {
		try {
			final AbstractSREInstall clone = (AbstractSREInstall) super.clone();
			clone.attributeMap = this.attributeMap == null ? null
					: new HashMap<>(this.attributeMap);
			if (this.libraryLocations != null) {
				clone.libraryLocations = this.libraryLocations.clone();
			}
			if (this.libraryLocations != null) {
				clone.libraryLocations = this.libraryLocations.clone();
			}
			return clone;
		} catch (CloneNotSupportedException e) {
			throw new Error(e);
		}
	}

	@Override
	public ISREInstall copy(String id) {
		final AbstractSREInstall copy = clone();
		copy.id = id;
		return copy;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}

		if (obj == null) {
			return false;
		}

		if (this.getClass() == obj.getClass()) {
			return getId().equals(((ISREInstall) obj).getId());
		}
		return false;
	}

	@Override
	public int hashCode() {
		return getId().hashCode();
	}

	@Override
	public String toString() {
		return getName();
	}

	@Override
	public void setNotify(boolean notify) {
		this.notify = notify;
	}

	@Override
	public boolean getNotify() {
		return this.notify;
	}

	/** Replies if this installation has one of its field unresolved.
	 *
	 * @return true if one field has a too old value.
	 */
	protected boolean isDirty() {
		return this.dirty;
	}

	/** Set if this installation has one of its field unresolved.
	 *
	 * @param dirty - true if one field has a too old value.
	 */
	protected void setDirty(boolean dirty) {
		this.dirty = dirty;
	}

	/** Force the computation of the installation validity.
	 *
	 * @param ignoreCauses - a set of bits that indicates the invalidity causes to ignore.
	 * @return the validity status.
	 */
	protected IStatus revalidate(int ignoreCauses) {
		try {
			setDirty(false);
			resolveDirtyFields(false);
			return getValidity(ignoreCauses);
		} catch (Throwable e) {
			if ((ignoreCauses & CODE_GENERAL) == 0) {
				return SARLEclipsePlugin.getDefault().createStatus(IStatus.ERROR, CODE_GENERAL, e);
			}
			return SARLEclipsePlugin.getDefault().createOkStatus();
		}
	}

	@Override
	public final IStatus revalidate() {
		return revalidate(0);
	}

	@Override
	public final IStatus getValidity() {
		return getValidity(0);
	}

	@Override
	public IStatus getValidity(int ignoreCauses) {
		if (isDirty()) {
			return revalidate(ignoreCauses);
		}
		IStatus status = null;
		try {
			if (!isStandalone() && (ignoreCauses & CODE_STANDALONE_SRE) == 0) {
				return SARLEclipsePlugin.getDefault().createStatus(IStatus.ERROR, CODE_STANDALONE_SRE,
						Messages.AbstractSREInstall_5);
			}
			final String mainClass = getMainClass();
			if (Strings.isNullOrEmpty(mainClass) && (ignoreCauses & CODE_MAIN_CLASS) == 0) {
				return SARLEclipsePlugin.getDefault().createStatus(IStatus.ERROR, CODE_MAIN_CLASS,
						Messages.AbstractSREInstall_2);
			}
			final String name = getName();
			if (Strings.isNullOrEmpty(name) && (ignoreCauses & CODE_NAME) == 0) {
				return SARLEclipsePlugin.getDefault().createStatus(IStatus.ERROR, CODE_NAME,
						Messages.AbstractSREInstall_3);
			}
			status = getLibraryLocationValidity(ignoreCauses);
			if (status == null) {
				status = getSARLVersionValidity(ignoreCauses);
			}
		} catch (Throwable e) {
			//
		}
		if (status == null) {
			status = SARLEclipsePlugin.getDefault().createOkStatus();
		}
		return status;
	}

	private IStatus getLibraryLocationValidity(int ignoreCauses) {
		final LibraryLocation[] locations = getLibraryLocations();
		if ((locations == null || locations.length == 0) &&  (ignoreCauses & CODE_LIBRARY_LOCATION) == 0) {
			return SARLEclipsePlugin.getDefault().createStatus(IStatus.ERROR, CODE_LIBRARY_LOCATION,
					Messages.AbstractSREInstall_4);
		}
		return null;
	}

	private IStatus getSARLVersionValidity(int ignoreCauses) {
		final Bundle bundle = Platform.getBundle("io.sarl.lang"); //$NON-NLS-1$
		if (bundle != null) {
			final Version sarlVersion = bundle.getVersion();
			final Version minVersion = Utilities.parseVersion(getMinimalSARLVersion());
			final Version maxVersion = Utilities.parseVersion(getMaximalSARLVersion());
			final int cmp = Utilities.compareVersionToRange(sarlVersion, minVersion, maxVersion);
			if (cmp < 0 && (ignoreCauses & CODE_SARL_VERSION) == 0) {
				return SARLEclipsePlugin.getDefault().createStatus(IStatus.ERROR,
						CODE_SARL_VERSION,
						MessageFormat.format(
								Messages.AbstractSREInstall_0,
								sarlVersion.toString(),
								minVersion.toString()));
			} else if (cmp > 0 && (ignoreCauses & CODE_SARL_VERSION) == 0) {
				return SARLEclipsePlugin.getDefault().createStatus(IStatus.ERROR,
						CODE_SARL_VERSION,
						MessageFormat.format(
								Messages.AbstractSREInstall_1,
								sarlVersion.toString(),
								maxVersion.toString()));
			}
		}
		return null;
	}

	/** Invoked when the JAR file has changed for updating the other
	 * fields.
	 *
	 * @param forceSettings - indicates if the fields of this SRE must be set.
	 */
	protected abstract void resolveDirtyFields(boolean forceSettings);

	@Override
	public String getId() {
		return this.id;
	}

	@Override
	public String getName() {
		if (isDirty()) {
			setDirty(false);
			resolveDirtyFields(true);
		}
		return this.name;
	}

	@Override
	public String getMinimalSARLVersion() {
		if (isDirty()) {
			setDirty(false);
			resolveDirtyFields(true);
		}
		return this.minimalSarlVersion;
	}

	@Override
	public String getMaximalSARLVersion() {
		if (isDirty()) {
			setDirty(false);
			resolveDirtyFields(true);
		}
		return this.maximalSarlVersion;
	}

	@Override
	public String getMainClass() {
		if (isDirty()) {
			setDirty(false);
			resolveDirtyFields(true);
		}
		return this.mainClass;
	}

	@Override
	public LibraryLocation[] getLibraryLocations() {
		if (isDirty()) {
			setDirty(false);
			resolveDirtyFields(true);
		}
		if (this.libraryLocations == null) {
			return new LibraryLocation[0];
		}
		return this.libraryLocations;
	}

	@Override
	public Map<String, String> getVMSpecificAttributesMap() {
		if (isDirty()) {
			setDirty(false);
			resolveDirtyFields(true);
		}
		if (this.attributeMap == null) {
			return Collections.emptyMap();
		}
		return Collections.unmodifiableMap(this.attributeMap);
	}

	@Override
	public void setName(String name) {
		if (isDirty()) {
			setDirty(false);
			resolveDirtyFields(true);
		}
		final String normalizedName = Strings.nullToEmpty(name);
		if (!name.equals(Strings.nullToEmpty(this.name))) {
			final PropertyChangeEvent event = new PropertyChangeEvent(
					this, ISREInstallChangedListener.PROPERTY_NAME, this.name, normalizedName);
			this.name = normalizedName;
			if (this.notify) {
				SARLRuntime.fireSREChanged(event);
			}
		}
	}

	/**
	 * Change the library locations of this ISREInstall.
	 *
	 * @param libraries - The library locations of this ISREInstall.
	 *     Must not be null.
	 */
	@Override
	public void setLibraryLocations(LibraryLocation... libraries) {
		if (isDirty()) {
			setDirty(false);
			resolveDirtyFields(true);
		}
		if ((libraries == null && this.libraryLocations != null)
				|| (libraries != null
				&& (this.libraryLocations == null
				|| Arrays.equals(libraries, this.libraryLocations)))) {
			final PropertyChangeEvent event = new PropertyChangeEvent(
					this, ISREInstallChangedListener.PROPERTY_LIBRARY_LOCATIONS,
					this.libraryLocations, libraries);
			this.libraryLocations = libraries;
			if (this.notify) {
				SARLRuntime.fireSREChanged(event);
			}
		}
	}

	@Override
	public void setMinimalSARLVersion(String version) {
		if (isDirty()) {
			setDirty(false);
			resolveDirtyFields(true);
		}
		final String newVersion = Strings.nullToEmpty(version);
		if (!newVersion.isEmpty()) {
			// Check version number
			try {
				Version.parseVersion(newVersion);
			} catch (Throwable exception) {
				return;
			}
		}
		if (!newVersion.equals(Strings.nullToEmpty(this.minimalSarlVersion))) {
			final PropertyChangeEvent event = new PropertyChangeEvent(
					this, ISREInstallChangedListener.PROPERTY_MINIMAL_SARL_VERSION,
					this.minimalSarlVersion, newVersion);
			this.minimalSarlVersion = newVersion;
			if (this.notify) {
				SARLRuntime.fireSREChanged(event);
			}
		}
	}

	@Override
	public void setMaximalSARLVersion(String version) {
		if (isDirty()) {
			setDirty(false);
			resolveDirtyFields(true);
		}
		final String newVersion = Strings.nullToEmpty(version);
		if (!newVersion.isEmpty()) {
			// Check version number
			try {
				Version.parseVersion(newVersion);
			} catch (Throwable exception) {
				return;
			}
		}
		if (!newVersion.equals(Strings.nullToEmpty(this.maximalSarlVersion))) {
			final PropertyChangeEvent event = new PropertyChangeEvent(
					this, ISREInstallChangedListener.PROPERTY_MAXIMAL_SARL_VERSION,
					this.maximalSarlVersion, newVersion);
			this.maximalSarlVersion = newVersion;
			if (this.notify) {
				SARLRuntime.fireSREChanged(event);
			}
		}
	}

	@Override
	public void setVMSpecificAttributesMap(Map<String, String> attributes) {
		if (isDirty()) {
			setDirty(false);
			resolveDirtyFields(true);
		}
		if (!Objects.equal(attributes, this.attributeMap)) {
			final Map<String, String> oldValues;
			final Map<String, String> newValues;
			if (attributes == null) {
				newValues = Collections.emptyMap();
			} else {
				newValues = attributes;
			}
			if (this.attributeMap == null) {
				oldValues = Collections.emptyMap();
			} else {
				oldValues = this.attributeMap;
			}
			final PropertyChangeEvent event = new PropertyChangeEvent(
					this, ISREInstallChangedListener.PROPERTY_VM_ATTRIBUTES,
					oldValues, newValues);
			this.attributeMap = attributes;
			if (this.notify) {
				SARLRuntime.fireSREChanged(event);
			}
		}
	}

	@Override
	public void setMainClass(String mainClass) {
		if (isDirty()) {
			setDirty(false);
			resolveDirtyFields(true);
		}
		final String normalizedName = Strings.nullToEmpty(mainClass);
		if (!normalizedName.equals(Strings.nullToEmpty(this.mainClass))) {
			final PropertyChangeEvent event = new PropertyChangeEvent(
					this, ISREInstallChangedListener.PROPERTY_NAME, this.mainClass, normalizedName);
			this.mainClass = normalizedName;
			if (this.notify) {
				SARLRuntime.fireSREChanged(event);
			}
		}
	}

	@Override
	public void setStandalone(boolean isStandalone) {
		if (isDirty()) {
			setDirty(false);
			resolveDirtyFields(true);
		}
		if (isStandalone != this.isStandalone) {
			final PropertyChangeEvent event = new PropertyChangeEvent(
					this, ISREInstallChangedListener.PROPERTY_STANDALONE_SRE, this.isStandalone, isStandalone);
			this.isStandalone = isStandalone;
			if (this.notify) {
				SARLRuntime.fireSREChanged(event);
			}
		}
	}

	@Override
	public boolean isStandalone() {
		if (isDirty()) {
			setDirty(false);
			resolveDirtyFields(true);
		}
		return this.isStandalone;
	}

}


text:
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;

namespace AwfulForumsLibrary.Tools
{
    public static class Extensions
    {
		public static string RemoveAutoplayGif(string html)
		{
			var doc2 = new HtmlDocument();
			doc2.LoadHtml(html);
			HtmlNode bodyNode = doc2.DocumentNode.Descendants("body").FirstOrDefault();
			var images = bodyNode.Descendants("img").Where(node => node.GetAttributeValue("class", string.Empty) != "av");
			foreach (var image in images)
			{
				var src = image.Attributes["src"].Value;
				if (Path.GetExtension(src) != ".gif")
					continue;
				if (src.Contains("somethingawful.com"))
					continue;
				if (src.Contains("emoticons"))
					continue;
				if (src.Contains("smilies"))
					continue;
				image.Attributes.Add("data-gifffer", image.Attributes["src"].Value);
				image.Attributes.Remove("src");
			}
			html = doc2.DocumentNode.OuterHtml;
			return html;
		}
        public static Dictionary<string, string> ParseQueryString(string s)
        {
            var nvc = new Dictionary<string, string>();

            // remove anything other than query string from url
            if (s.Contains("?"))
            {
                s = s.Substring(s.IndexOf('?') + 1);
            }

            foreach (string vp in Regex.Split(s, "&"))
            {
                string[] singlePair = Regex.Split(vp, "=");
                if (singlePair.Length == 2)
                {
                    nvc.Add(singlePair[0], singlePair[1]);
                }
                else
                {
                    // only one key with no value specified in query string
                    nvc.Add(singlePair[0], string.Empty);
                }
            }

            return nvc;
        }

        public static CookieContainer ReadCookies(this HttpResponseMessage response)
        {
            var pageUri = response.RequestMessage.RequestUri;

            var cookieContainer = new CookieContainer();
            IEnumerable<string> cookies;
            if (response.Headers.TryGetValues("set-cookie", out cookies))
            {
                foreach (var c in cookies)
                {
                    cookieContainer.SetCookies(pageUri, c);
                }
            }

            return cookieContainer;
        }

        public static string WithoutNewLines(this string text)
        {
            var sb = new StringBuilder(text.Length);
            foreach (char i in text)
            {
                if (i != '\n' && i != '\r' && i != '\t' && i != '#' && i != '?')
                {
                    sb.Append(i);
                }
                else if (i == '\n')
                {
                    sb.Append(' ');
                }
            }
            return sb.ToString();
        }

        public static string HtmlEncode(string text)
        {
            // In order to get Unicode characters fully working, we need to first encode the entire post.
            // THEN we decode the bits we can safely pass in, like single/double quotes.
            // If we don't, the post format will be screwed up.
            char[] chars = WebUtility.HtmlEncode(text).ToCharArray();
            var result = new StringBuilder(text.Length + (int)(text.Length * 0.1));

            foreach (char c in chars)
            {
                int value = Convert.ToInt32(c);
                if (value > 127)
                    result.AppendFormat("&#{0};", value);
                else
                    result.Append(c);
            }

            result.Replace(""", "\"");
            result.Replace("'", @"'");
            result.Replace("<", @"<");
            result.Replace(">", @">");
            return result.ToString();
        }
    }
}


text:
#include "Exec.h"
#include "../Hand/Hand.h"

//
// Enumerate the valid types
//
UINT32 mEventTable[] = {
  //
  // 0x80000200       Timer event with a notification function that is
  // queue when the event is signaled with SignalEvent()
  //
  EFI_EVENT_TIMER | EFI_EVENT_NOTIFY_SIGNAL,
  //
  // 0x80000000       Timer event without a notification function. It can be
  // signaled with SignalEvent() and checked with CheckEvent() or WaitForEvent().
  //
  EFI_EVENT_TIMER,
  //
  // 0x00000100       Generic event with a notification function that
  // can be waited on with CheckEvent() or WaitForEvent()
  //
  EFI_EVENT_NOTIFY_WAIT,
  //
  // 0x00000200       Generic event with a notification function that
  // is queue when the event is signaled with SignalEvent()
  //
  EFI_EVENT_NOTIFY_SIGNAL,
  //
  // 0x00000201       ExitBootServicesEvent.
  //
  EFI_EVENT_SIGNAL_EXIT_BOOT_SERVICES,
  //
  // 0x60000202       SetVirtualAddressMapEvent.
  //
  EFI_EVENT_SIGNAL_VIRTUAL_ADDRESS_CHANGE,
#if (EFI_SPECIFICATION_VERSION < 0x00020000)
  //
  // 0x00000203       ReadyToBootEvent.
  //
  EFI_EVENT_SIGNAL_READY_TO_BOOT,
  //
  // 0x00000204       LegacyBootEvent.
  //
  EFI_EVENT_SIGNAL_LEGACY_BOOT,
  //
  // 0x00000603       Signal all ReadyToBootEvents.
  //
  EFI_EVENT_NOTIFY_SIGNAL_ALL | EFI_EVENT_SIGNAL_READY_TO_BOOT,
  //
  // 0x00000604       Signal all LegacyBootEvents.
  //
  EFI_EVENT_NOTIFY_SIGNAL_ALL | EFI_EVENT_SIGNAL_LEGACY_BOOT,
  //
  // 0x00000000       Generic event without a notification function.
  // It can be signaled with SignalEvent() and checked with CheckEvent()
  // or WaitForEvent().
  //
#endif
  0x00000000,
  //
  // 0x80000100       Timer event with a notification function that can be
  // waited on with CheckEvent() or WaitForEvent()
  //
  EFI_EVENT_TIMER | EFI_EVENT_NOTIFY_WAIT,
};

VOID
CoreAcquireEventLock (
  VOID
  )
/*++

Routine Description:

  Enter critical section by acquiring the lock on gEventQueueLock.

Arguments:

  None

Returns:

  None

--*/
{
  CoreAcquireLock (&gEventQueueLock);
}

VOID
CoreReleaseEventLock (
  VOID
  )
/*++

Routine Description:

  Exit critical section by releasing the lock on gEventQueueLock.

Arguments:

  None

Returns:

  None

--*/
{
  CoreReleaseLock (&gEventQueueLock);
}

EFI_STATUS
CoreInitializeEventServices (
  VOID
  )
/*++

Routine Description:

  Initializes "event" support and populates parts of the System and Runtime Table.

Arguments:

  None

Returns:

  EFI_SUCCESS - Always return success

--*/
{
  UINTN        Index;

  for (Index=0; Index <= EFI_TPL_HIGH_LEVEL; Index ++) {
    InitializeListHead (&gEventQueue[Index]);
  }

  CoreInitializeTimer ();

  return EFI_SUCCESS;
}

VOID
CoreDispatchEventNotifies (
  IN EFI_TPL      Priority
  )
/*++

Routine Description:

  Dispatches all pending events.

Arguments:

  Priority - The task priority level of event notifications to dispatch

Returns:

  None

--*/
{
  IEVENT          *Event;
  EFI_LIST_ENTRY  *Head;

  CoreAcquireEventLock ();
  ASSERT (gEventQueueLock.OwnerTpl == Priority);
  Head = &gEventQueue[Priority];

  //
  // Dispatch all the pending notifications
  //
  while (!IsListEmpty (Head)) {

    Event = CR (Head->ForwardLink, IEVENT, NotifyLink, EVENT_SIGNATURE);
    RemoveEntryList (&Event->NotifyLink);

    Event->NotifyLink.ForwardLink = NULL;

    //
    // Only clear the SIGNAL status if it is a SIGNAL type event.
    // WAIT type events are only cleared in CheckEvent()
    //
    if (Event->Type & EFI_EVENT_NOTIFY_SIGNAL) {
      Event->SignalCount = 0;
    }

    CoreReleaseEventLock ();

    //
    // Notify this event
    //
    Event->NotifyFunction (Event, Event->NotifyContext);

    //
    // Check for next pending event
    //
    CoreAcquireEventLock ();
  }

  gEventPending &= ~(1 << Priority);
  CoreReleaseEventLock ();
}

VOID
STATIC
CoreNotifyEvent (
  IN  IEVENT      *Event
  )
/*++

Routine Description:

  Queues the event's notification function to fire

Arguments:

  Event       - The Event to notify

Returns:

  None

--*/
{

  //
  // Event database must be locked
  //
  ASSERT_LOCKED (&gEventQueueLock);

  //
  // If the event is queued somewhere, remove it
  //

  if (Event->NotifyLink.ForwardLink != NULL) {
    RemoveEntryList (&Event->NotifyLink);
    Event->NotifyLink.ForwardLink = NULL;
  }

  //
  // Queue the event to the pending notification list
  //

  InsertTailList (&gEventQueue[Event->NotifyTpl], &Event->NotifyLink);
  gEventPending |= 1 << Event->NotifyTpl;
}

VOID
CoreNotifySignalList (
  IN EFI_GUID     *EventGroup
  )
/*++

Routine Description:

  Signals all events on the requested list

Arguments:

  SignalType      - The list to signal

Returns:

  None

--*/
{
  EFI_LIST_ENTRY          *Link;
  EFI_LIST_ENTRY          *Head;
  IEVENT                  *Event;

  CoreAcquireEventLock ();

  Head = &gEventSignalQueue;
  for (Link = Head->ForwardLink; Link != Head; Link = Link->ForwardLink) {
    Event = CR (Link, IEVENT, SignalLink, EVENT_SIGNATURE);
    if ((Event->ExFlag) && EfiCompareGuid (&Event->EventGroup, EventGroup)) {
      CoreNotifyEvent (Event);
    }
  }

  CoreReleaseEventLock ();
}

#if (EFI_SPECIFICATION_VERSION < 0x00020000)

static
VOID
EFIAPI
EventNotifySignalAllNullEvent (
  IN EFI_EVENT                Event,
  IN VOID                     *Context
  )
{
  //
  // This null event is a size efficent way to enusre that
  // EFI_EVENT_NOTIFY_SIGNAL_ALL is error checked correctly.
  // EFI_EVENT_NOTIFY_SIGNAL_ALL is now mapped into
  // CreateEventEx() and this function is used to make the
  // old error checking in CreateEvent() for Tiano extensions
  // function.
  //
  return;
}

#endif

EFI_BOOTSERVICE
EFI_STATUS
EFIAPI
CoreCreateEvent (
  IN UINT32                   Type,
  IN EFI_TPL                  NotifyTpl,
  IN EFI_EVENT_NOTIFY         NotifyFunction,
  IN VOID                     *NotifyContext,
  OUT EFI_EVENT               *Event
  )
/*++

Routine Description:

  Creates a general-purpose event structure

Arguments:

  Type                - The type of event to create and its mode and attributes
  NotifyTpl           - The task priority level of event notifications
  NotifyFunction      - Pointer to the events notification function
  NotifyContext       - Pointer to the notification functions context; corresponds to
                        parameter "Context" in the notification function
  Event               - Pointer to the newly created event if the call succeeds; undefined otherwise

Returns:

  EFI_SUCCESS           - The event structure was created
  EFI_INVALID_PARAMETER - One of the parameters has an invalid value
  EFI_OUT_OF_RESOURCES  - The event could not be allocated

--*/
{
  EFI_GUID            *GuidPtr;
  EFI_EVENT_NOTIFY    Function;

  GuidPtr = NULL;
  Function = NotifyFunction;

#if (EFI_SPECIFICATION_VERSION < 0x00020000)
  //
  // Clear EFI_EVENT_NOFITY_SIGNAL_ALL (Tiano extension) as all events in the
  // EventGroup now have this property. So we need to filter it out.
  //
  if (Type & EFI_EVENT_NOTIFY_SIGNAL_ALL) {
    Type &= ~EFI_EVENT_NOTIFY_SIGNAL_ALL;
    Function = EventNotifySignalAllNullEvent;
  }

  //
  // Map the Tiano extensions Events to CreateEventEx form
  //
  if (Type == EFI_EVENT_SIGNAL_READY_TO_BOOT) {
    GuidPtr = &gEfiEventReadyToBootGuid;
  } else if (Type == EFI_EVENT_SIGNAL_LEGACY_BOOT) {
    GuidPtr = &gEfiEventLegacyBootGuid;
  }
#endif

  //
  // Convert EFI 1.10 Events to thier UEFI 2.0 CreateEventEx mapping
  //
  if (Type == EFI_EVENT_SIGNAL_EXIT_BOOT_SERVICES) {
    GuidPtr = &gEfiEventExitBootServicesGuid;
  } else if (Type == EFI_EVENT_SIGNAL_VIRTUAL_ADDRESS_CHANGE) {
    GuidPtr = &gEfiEventVirtualAddressChangeGuid;
  }

  return CoreCreateEventEx (Type, NotifyTpl, Function, NotifyContext, GuidPtr, Event);
}

EFI_BOOTSERVICE
EFI_STATUS
EFIAPI
CoreCreateEventEx (
  IN UINT32                   Type,
  IN EFI_TPL                  NotifyTpl,
  IN EFI_EVENT_NOTIFY         NotifyFunction,
  IN VOID                     *NotifyContext,
  IN CONST EFI_GUID           *EventGroup,    OPTIONAL
  OUT EFI_EVENT               *Event
  )
/*++

Routine Description:
  Creates a general-purpose event structure

Arguments:
  Type                - The type of event to create and its mode and attributes
  NotifyTpl           - The task priority level of event notifications
  NotifyFunction      - Pointer to the events notification function
  NotifyContext       - Pointer to the notification functions context; corresponds to
                        parameter "Context" in the notification function
  EventGrout          - GUID for EventGroup if NULL act the same as gBS->CreateEvent().
  Event               - Pointer to the newly created event if the call succeeds; undefined otherwise

Returns:
  EFI_SUCCESS           - The event structure was created
  EFI_INVALID_PARAMETER - One of the parameters has an invalid value
  EFI_OUT_OF_RESOURCES  - The event could not be allocated

--*/
{
  EFI_STATUS      Status;
  IEVENT          *IEvent;
  INTN            Index;

  if ((Event == NULL) || (NotifyTpl == EFI_TPL_APPLICATION)) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Check to make sure no reserved flags are set
  //
  Status = EFI_INVALID_PARAMETER;
  for (Index = 0; Index < (sizeof (mEventTable) / sizeof (UINT32)); Index++) {
    if (Type == mEventTable[Index]) {
      Status = EFI_SUCCESS;
      break;
    }
  }
  if(EFI_ERROR (Status)) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // If it's a notify type of event, check its parameters
  //
  if ((Type & (EFI_EVENT_NOTIFY_WAIT | EFI_EVENT_NOTIFY_SIGNAL))) {
    //
    // Check for an invalid NotifyFunction or NotifyTpl
    //
    if ((NotifyFunction == NULL) ||
        (NotifyTpl < EFI_TPL_APPLICATION) ||
       (NotifyTpl >= EFI_TPL_HIGH_LEVEL)) {
      return EFI_INVALID_PARAMETER;
    }

  } else {
    //
    // No notification needed, zero ignored values
    //
    NotifyTpl = 0;
    NotifyFunction = NULL;
    NotifyContext = NULL;
  }

  //
  // Allcoate and initialize a new event structure.
  //
  Status = CoreAllocatePool (
             (Type & EFI_EVENT_RUNTIME) ? EfiRuntimeServicesData: EfiBootServicesData,
             sizeof (IEVENT),
             (VOID **)&IEvent
             );
  if (EFI_ERROR (Status)) {
    return EFI_OUT_OF_RESOURCES;
  }

  EfiCommonLibSetMem (IEvent, sizeof (IEVENT), 0);

  IEvent->Signature      = EVENT_SIGNATURE;
  IEvent->Type           = Type;
  IEvent->NotifyTpl      = NotifyTpl;
  IEvent->NotifyFunction = NotifyFunction;
  IEvent->NotifyContext  = (VOID *)NotifyContext;
  if (EventGroup != NULL) {
    EfiCommonLibCopyMem (&IEvent->EventGroup, (VOID*)EventGroup, sizeof (EFI_GUID));
    IEvent->ExFlag = TRUE;
  }

  *Event = IEvent;

  if (Type & EFI_EVENT_RUNTIME) {
    //
    // Keep a list of all RT events so we can tell the RT AP.
    //
    IEvent->RuntimeData.Type           = Type;
    IEvent->RuntimeData.NotifyTpl      = NotifyTpl;
    IEvent->RuntimeData.NotifyFunction = NotifyFunction;
    IEvent->RuntimeData.NotifyContext  = NotifyContext;
    IEvent->RuntimeData.Event          = (EFI_EVENT *) IEvent;
    InsertTailList (&gRuntime->EventHead, &IEvent->RuntimeData.Link);
  }

  CoreAcquireEventLock ();

  if ((Type & EFI_EVENT_NOTIFY_SIGNAL) != 0x00000000) {
    //
    // The Event's NotifyFunction must be queued whenever the event is signaled
    //
    InsertHeadList (&gEventSignalQueue, &IEvent->SignalLink);
  }

  CoreReleaseEventLock ();

  //
  // Done
  //
  return EFI_SUCCESS;
}

EFI_BOOTSERVICE
EFI_STATUS
EFIAPI
CoreSignalEvent (
  IN EFI_EVENT    UserEvent
  )
/*++

Routine Description:

  Signals the event.  Queues the event to be notified if needed

Arguments:

  UserEvent - The event to signal

Returns:

  EFI_INVALID_PARAMETER - Parameters are not valid.

  EFI_SUCCESS - The event was signaled.

--*/
{
  IEVENT          *Event;

  Event = UserEvent;

  if (Event == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  if (Event->Signature != EVENT_SIGNATURE) {
    return EFI_INVALID_PARAMETER;
  }

  CoreAcquireEventLock ();

  //
  // If the event is not already signalled, do so
  //

  if (Event->SignalCount == 0x00000000) {
    Event->SignalCount ++;

    //
    // If signalling type is a notify function, queue it
    //
    if (Event->Type & EFI_EVENT_NOTIFY_SIGNAL) {
      if (Event->ExFlag) {
        //
        // The CreateEventEx() style requires all members of the Event Group
        //  to be signaled.
        //
        CoreReleaseEventLock ();
        CoreNotifySignalList (&Event->EventGroup);
        CoreAcquireEventLock ();
       } else {
        CoreNotifyEvent (Event);
      }
    }
  }

  CoreReleaseEventLock ();
  return EFI_SUCCESS;
}

EFI_BOOTSERVICE
EFI_STATUS
EFIAPI
CoreCheckEvent (
  IN EFI_EVENT        UserEvent
  )
/*++

Routine Description:

  Check the status of an event

Arguments:

  UserEvent - The event to check

Returns:

  EFI_SUCCESS           - The event is in the signaled state
  EFI_NOT_READY         - The event is not in the signaled state
  EFI_INVALID_PARAMETER - Event is of type EVT_NOTIFY_SIGNAL

--*/

{
  IEVENT      *Event;
  EFI_STATUS  Status;

  Event = UserEvent;

  if (Event == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  if (Event->Signature != EVENT_SIGNATURE) {
    return EFI_INVALID_PARAMETER;
  }

  if (Event->Type & EFI_EVENT_NOTIFY_SIGNAL) {
    return EFI_INVALID_PARAMETER;
  }

  Status = EFI_NOT_READY;

  if (!Event->SignalCount && (Event->Type & EFI_EVENT_NOTIFY_WAIT)) {

    //
    // Queue the wait notify function
    //

    CoreAcquireEventLock ();
    if (!Event->SignalCount) {
      CoreNotifyEvent (Event);
    }
    CoreReleaseEventLock ();
  }

  //
  // If the even looks signalled, get the lock and clear it
  //

  if (Event->SignalCount) {
    CoreAcquireEventLock ();

    if (Event->SignalCount) {
      Event->SignalCount = 0;
      Status = EFI_SUCCESS;
    }

    CoreReleaseEventLock ();
  }

  return Status;
}

EFI_BOOTSERVICE
EFI_STATUS
EFIAPI
CoreWaitForEvent (
  IN UINTN        NumberOfEvents,
  IN EFI_EVENT    *UserEvents,
  OUT UINTN       *UserIndex
  )
/*++

Routine Description:

  Stops execution until an event is signaled.

Arguments:

  NumberOfEvents  - The number of events in the UserEvents array
  UserEvents      - An array of EFI_EVENT
  UserIndex       - Pointer to the index of the event which satisfied the wait condition

Returns:

  EFI_SUCCESS           - The event indicated by Index was signaled.
  EFI_INVALID_PARAMETER - The event indicated by Index has a notification function or
                          Event was not a valid type
  EFI_UNSUPPORTED       - The current TPL is not TPL_APPLICATION

--*/

{
  EFI_STATUS      Status;
  UINTN           Index;

  //
  // Can only WaitForEvent at TPL_APPLICATION
  //
  if (gEfiCurrentTpl != EFI_TPL_APPLICATION) {
    return EFI_UNSUPPORTED;
  }

  for(;;) {

    for(Index = 0; Index < NumberOfEvents; Index++) {

      Status = CoreCheckEvent (UserEvents[Index]);

      //
      // provide index of event that caused problem
      //
      if (Status != EFI_NOT_READY) {
        *UserIndex = Index;
        return Status;
      }
    }

    //
    // This was the location of the Idle loop callback in EFI 1.x reference
    // code. We don't have that concept in this base at this point.
    //
  }
}

EFI_BOOTSERVICE
EFI_STATUS
EFIAPI
CoreCloseEvent (
  IN EFI_EVENT    UserEvent
  )
/*++

Routine Description:

  Closes an event and frees the event structure.

Arguments:

  UserEvent - Event to close

Returns:

  EFI_INVALID_PARAMETER - Parameters are not valid.

  EFI_SUCCESS - The event has been closed

--*/

{
  EFI_STATUS  Status;
  IEVENT      *Event;

  Event = UserEvent;

  if (Event == NULL) {
    return EFI_INVALID_PARAMETER;
  }

  if (Event->Signature != EVENT_SIGNATURE) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // If it's a timer event, make sure it's not pending
  //
  if (Event->Type & EFI_EVENT_TIMER) {
    CoreSetTimer (Event, TimerCancel, 0);
  }

  CoreAcquireEventLock ();

  //
  // If the event is queued somewhere, remove it
  //

  if (Event->RuntimeData.Link.ForwardLink != NULL) {
    RemoveEntryList (&Event->RuntimeData.Link);
  }

  if (Event->NotifyLink.ForwardLink != NULL) {
    RemoveEntryList (&Event->NotifyLink);
  }

  if (Event->SignalLink.ForwardLink != NULL) {
    RemoveEntryList (&Event->SignalLink);
  }

  CoreReleaseEventLock ();

  //
  // If the event is registered on a protocol notify,
  // then remove it from the protocol database
  //
  CoreUnregisterProtocolNotify (Event);

  Status = CoreFreePool (Event);
  ASSERT_EFI_ERROR (Status);

  return Status;
}


text:
require "test_helper"

class TestMapnikTextSymbolizer < Test::Unit::TestCase

  def setup
    expression = Mapnik::Expression.parse("([place]='town')")
    @symbolizer = Mapnik::TextSymbolizer.new(expression, "DejaVu Sans Book", 10, Mapnik::Color.new("#fff"))
  end

  def test_should_instantiate
    assert @symbolizer
  end

  def test_enums_should_exist
    assert Mapnik::LABEL_PLACEMENT::LINE_PLACEMENT
    assert Mapnik::LABEL_PLACEMENT::POINT_PLACEMENT
    assert Mapnik::LABEL_PLACEMENT::VERTEX_PLACEMENT
    assert Mapnik::LABEL_PLACEMENT::INTERIOR_PLACEMENT

    assert Mapnik::VERTICAL_ALIGNMENT::TOP
    assert Mapnik::VERTICAL_ALIGNMENT::MIDDLE
    assert Mapnik::VERTICAL_ALIGNMENT::BOTTOM
    assert Mapnik::VERTICAL_ALIGNMENT::AUTO

    assert Mapnik::HORIZONTAL_ALIGNMENT::LEFT
    assert Mapnik::HORIZONTAL_ALIGNMENT::MIDDLE
    assert Mapnik::HORIZONTAL_ALIGNMENT::RIGHT

    assert Mapnik::JUSTIFY_ALIGNMENT::LEFT
    assert Mapnik::JUSTIFY_ALIGNMENT::MIDDLE
    assert Mapnik::JUSTIFY_ALIGNMENT::RIGHT

    assert Mapnik::TEXT_TRANSFORM::NONE
    assert Mapnik::TEXT_TRANSFORM::UPPERCASE
    assert Mapnik::TEXT_TRANSFORM::LOWERCASE
    assert Mapnik::TEXT_TRANSFORM::CAPITALIZE
  end

  def test_should_get_and_set_allow_overlap
    @symbolizer.allow_overlap = true
    assert @symbolizer.allow_overlap?
    @symbolizer.allow_overlap = false
    assert !@symbolizer.allow_overlap?
  end

  def test_should_get_and_set_displacement
    assert @symbolizer.displacement
    new_vals = [1,2]
    @symbolizer.displacement = new_vals
    assert_equal new_vals, @symbolizer.displacement
  end

  def test_should_get_and_set_avoid_edges
    @symbolizer.avoid_edges = true
    assert @symbolizer.avoid_edges?
    @symbolizer.avoid_edges = false
    assert !@symbolizer.avoid_edges?
  end

  def test_should_get_and_set_character_spacing
    assert_equal 0, @symbolizer.character_spacing
    @symbolizer.character_spacing = 1
    assert_equal 1, @symbolizer.character_spacing
  end

  def test_should_get_and_set_face_name
    assert_equal "DejaVu Sans Book", @symbolizer.face_name
    @symbolizer.face_name = "DejaVu Sans"
    assert_equal "DejaVu Sans", @symbolizer.face_name
  end

  def test_should_get_and_set_fill
    assert @symbolizer.fill.instance_of?(Mapnik::Color)
    white = Mapnik::Color.new("#fff")
    @symbolizer.fill = white
    assert_equal white, @symbolizer.fill
  end

  # TODO: Need fontset
  # def test_should_get_and_set_fontset
  #   raise @symbolizer.fontset.inspect
  # end

  def test_should_get_and_set_force_odd_labels
    @symbolizer.force_odd_labels = true
    assert @symbolizer.force_odd_labels?
    @symbolizer.force_odd_labels = false
    assert !@symbolizer.force_odd_labels?
  end

  def test_should_get_and_set_halo_fill
    assert @symbolizer.halo_fill.instance_of?(Mapnik::Color)
    white = Mapnik::Color.new("#fff")
    @symbolizer.halo_fill = white
    assert_equal white, @symbolizer.halo_fill
  end

  def test_should_get_and_set_halo_radius
    assert_equal 0, @symbolizer.halo_radius
    @symbolizer.halo_radius = 1
    assert_equal 1, @symbolizer.halo_radius
  end

  def test_should_get_and_set_horizontal_alignment
    @symbolizer.horizontal_alignment = Mapnik::HORIZONTAL_ALIGNMENT::LEFT
    assert_equal Mapnik::HORIZONTAL_ALIGNMENT::LEFT, @symbolizer.horizontal_alignment

    @symbolizer.horizontal_alignment = Mapnik::HORIZONTAL_ALIGNMENT::MIDDLE
    assert_equal Mapnik::HORIZONTAL_ALIGNMENT::MIDDLE, @symbolizer.horizontal_alignment

    @symbolizer.horizontal_alignment = Mapnik::HORIZONTAL_ALIGNMENT::RIGHT
    assert_equal Mapnik::HORIZONTAL_ALIGNMENT::RIGHT, @symbolizer.horizontal_alignment
  end

  def test_should_get_and_set_justify_alignment
    check_constant_setting(Mapnik::JUSTIFY_ALIGNMENT, :justify_alignment)
  end

  def test_should_get_and_set_label_placement
    check_constant_setting(Mapnik::LABEL_PLACEMENT, :label_placement)
  end

  def test_should_get_and_set_label_position_tolerance
    assert_equal 0, @symbolizer.label_position_tolerance
    @symbolizer.label_position_tolerance = 1
    assert_equal 1, @symbolizer.label_position_tolerance
  end

  def test_should_get_and_set_label_spacing
    assert_equal 0, @symbolizer.label_spacing
    @symbolizer.label_spacing = 1
    assert_equal 1, @symbolizer.label_spacing
  end

  def test_should_get_and_set_line_spacing
    assert_equal 0, @symbolizer.line_spacing
    @symbolizer.line_spacing = 1
    assert_equal 1, @symbolizer.line_spacing
  end

  def test_should_get_and_set_max_char_angle_delta
    @symbolizer.max_char_angle_delta = 0.5
    assert_equal 0.5, @symbolizer.max_char_angle_delta
    @symbolizer.max_char_angle_delta = 0.7
    assert_equal 0.7, @symbolizer.max_char_angle_delta
  end

  def test_should_get_and_set_minimum_distance
    assert_equal 0, @symbolizer.minimum_distance
    @symbolizer.minimum_distance = 1
    assert_equal 1, @symbolizer.minimum_distance
  end

  def test_should_get_and_set_minimum_padding
    assert_equal 0, @symbolizer.minimum_padding
    @symbolizer.minimum_padding = 1
    assert_equal 1, @symbolizer.minimum_padding
  end

  def test_should_get_and_set_opactiy
    assert_equal 1, @symbolizer.opacity
    @symbolizer.opacity = 0
    assert_equal 0, @symbolizer.opacity
  end

  def test_should_get_and_set_text_transform
    check_constant_setting(Mapnik::TEXT_TRANSFORM, :text_transform)
  end

  def test_should_get_and_set_text_ratio
    assert_equal 0, @symbolizer.ratio
    @symbolizer.ratio = 3
    assert_equal 3, @symbolizer.ratio
  end

  def test_should_get_and_set_text_size
    assert_equal 10, @symbolizer.size
    @symbolizer.size = 0
    assert_equal 0, @symbolizer.size
  end

  def test_should_get_and_set_vertical_alignment
    check_constant_setting(Mapnik::VERTICAL_ALIGNMENT, :vertical_alignment)
  end

  def test_should_get_and_set_wrap_width
    assert_equal 0, @symbolizer.wrap_width
    @symbolizer.wrap_width = 30
    assert_equal 30, @symbolizer.wrap_width
  end

  def test_should_get_and_set_wrap_character
    @symbolizer.wrap_character = '|'
    assert_equal '|', @symbolizer.wrap_character
    @symbolizer.wrap_character = '%'
    assert_equal '%', @symbolizer.wrap_character
  end

  def test_should_get_and_set_wrap_before
    assert !@symbolizer.wrap_before
    @symbolizer.wrap_before = true
    assert @symbolizer.wrap_before
  end

private

  def check_constant_setting(enum, property)
    enum.constants.each do |const_name|
      const = enum.const_get(const_name)
      @symbolizer.send(property.to_s + '=', const)
      assert_equal const, @symbolizer.send(property)
    end
  end

end


text:
module Backup
  module Compressor
    class Gzip < Base

      ##
      # Tells Backup::Compressor::Gzip to compress
      # better rather than faster when set to true
      attr_accessor :best

      ##
      # Tells Backup::Compressor::Gzip to compress
      # faster rather than better when set to true
      attr_accessor :fast

      ##
      # Creates a new instance of Backup::Compressor::Gzip and
      # configures it to either compress faster or better
      def initialize(&block)
        super

        @best ||= false
        @fast ||= false

        instance_eval(&block) if block_given?
      end

      ##
      # Yields to the block the compressor command with options
      # and it's filename extension.
      def compress_with
        log!
        yield "#{ utility(:gzip) }#{ options }", '.gz'
      end

      private

      ##
      # Returns the gzip option syntax for compressing
      def options
        " #{ '--best ' if @best }#{ '--fast' if @fast }".rstrip
      end

    end
  end
end


text:
package com.github.danielflower.mavenplugins.release;

import org.apache.maven.project.MavenProject;

import java.util.List;

public class ReleasableModule {

    private final MavenProject project;
    private final VersionName version;
    private final String tagName;
    private final String equivalentVersion;
    private final String relativePathToModule;

    public ReleasableModule(MavenProject project, VersionName version, String equivalentVersion, String relativePathToModule) {
        this.project = project;
        this.version = version;
        this.equivalentVersion = equivalentVersion;
        this.relativePathToModule = relativePathToModule;
        this.tagName = project.getArtifactId() + "-" + version.releaseVersion();
    }

    public String getTagName() {
        return tagName;
    }

    public String getNewVersion() {
        return version.releaseVersion();
    }

    public String getArtifactId() {
        return project.getArtifactId();
    }

    public String getGroupId() {
        return project.getGroupId();
    }

    public MavenProject getProject() {
        return project;
    }

    public String getVersion() {
        return version.businessVersion();
    }

    public long getBuildNumber() {
        return version.buildNumber();
    }

    public boolean isOneOf(List<String> moduleNames) {
        String modulePath = project.getBasedir().getName();
        for (String moduleName : moduleNames) {
            if (modulePath.equals(moduleName)) {
                return true;
            }
        }
        return false;
    }

    public boolean willBeReleased() {
        return equivalentVersion == null;
    }

    public String getVersionToDependOn() {
        return willBeReleased() ? version.releaseVersion() : equivalentVersion;
    }

    public String getRelativePathToModule() {
        return relativePathToModule;
    }

    public ReleasableModule createReleasableVersion() {
        return new ReleasableModule(project, version, null, relativePathToModule);
    }
}


text:
'use strict';

var BaseModel = require('model-toolkit').BaseModel;

module.exports = class Role extends BaseModel {
    constructor(source) {
        super('role', '1.0.0');

        // Define properties.
        this.code = '';
        this.name = '';
        this.description = '';
        this.permissions = [];

        this.copy(source);
    }
};


text:
function [tf] = wmtsa_isscalar(x)
% wmtsa_isscalar -- Determine if item is a point.
%
%****f* wmtsa.utils/wmtsa_isscalar
%
% NAME
%   wmtsa_isscalar -- Determine if item is a scalar.
%
% USAGE
%   [tf] = isscalar(x)
%
% INPUTS
%   * x          -- item to check (object).
%
% OUTPUTS
%   * tf          -- flag indicating whether item is a point (numeric Boolean).
%
% DESCRIPTION
%   In MATLAB, points, vectors and matrices all have a dimensionality of two,
%   (i.e. ndims(x) = 2).  A point is the degenerate case where an array, has
%   size of one in all dimensions, i.e. the array is singleton in all dimensions.
%   Function checks whether item is a point by checking that its length
%   in all dimensions is one.
%
% ERRORS
%   WMTSA:InvalidNumArguments
%
% TOOLBOX
%   wmtsa/utils
%
% CATEGORY
%   WMTSA Utilities
%

% AUTHOR
%   Charlie Cornish
%
% CREATION DATE
%   2005-Feb-03
%
% COPYRIGHT
%
%
% CREDITS
%
%
% REVISION
%   $Revision: 612 $
%
%***

%   $Id: wmtsa_isscalar.m 612 2005-10-28 21:42:24Z ccornish $

usage_str = ['Usage:  [tf] = ', mfilename, '(x)'];

%%  Check input arguments and set defaults.
error(nargerr(mfilename, nargin, [1:2], nargout, [0:2], 1, usage_str, 'struct'));

sz = size(x);

if ( (sum(sz) / length(sz)) == 1)
  tf = 1;
else
  tf = 0;
end

return


text:
/**
 * @interface strange.extensions.mediation.api.IMediationBinding
 *
 * Interface for MediationBindings
 *
 * Adds porcelain method to clarify View/Mediator binding.
 */

using System;
using strange.framework.api;

namespace strange.extensions.mediation.api
{
	public interface IMediationBinding : IBinding
	{
		/// Porcelain for To<T> providing a little extra clarity and security.
		IMediationBinding ToMediator<T>();

		/// Provide an Interface or base Class adapter for the View.
		/// When the binding specifies ToAbstraction<T>, the Mediator will be expected to inject <T>
		/// instead of the concrete View class.
		IMediationBinding ToAbstraction<T>();

		/// Retrieve the abstracted value set by ToAbstraction<T>
		object abstraction { get; }

		new IMediationBinding Bind<T>();
		new IMediationBinding Bind(object key);
		new IMediationBinding To<T>();
		new IMediationBinding To(object o);
	}
}


text:
#pragma once

#include <aws/core/Core_EXPORTS.h>
#include <aws/core/utils/logging/LogSystemInterface.h>
#include <aws/core/utils/logging/LogLevel.h>

#include <atomic>

namespace Aws
{
    namespace Utils
    {
        namespace Logging
        {
            /**
             * Logger that formats log messages into [LEVEL] timestamp [threadid] message
             */
            class AWS_CORE_API FormattedLogSystem : public LogSystemInterface
            {
            public:
                using Base = LogSystemInterface;

                /**
                 * Initializes log system with logLevel
                 */
                FormattedLogSystem(LogLevel logLevel);
                virtual ~FormattedLogSystem() = default;

                /**
                 * Gets the currently configured log level.
                 */
                virtual LogLevel GetLogLevel(void) const override { return m_logLevel; }
                /**
                 * Set a new log level. This has the immediate effect of changing the log output to the new level.
                 */
                void SetLogLevel(LogLevel logLevel) { m_logLevel.store(logLevel); }

                /**
                 * Does a printf style output to ProcessFormattedStatement. Don't use this, it's unsafe. See LogStream
                 */
                virtual void Log(LogLevel logLevel, const char* tag, const char* formatStr, ...) override;

                /**
                 * Writes the stream to ProcessFormattedStatement.
                 */
                virtual void LogStream(LogLevel logLevel, const char* tag, const Aws::OStringStream &messageStream) override;

            protected:
                /**
                 * This is the method that most logger implementations will want to override.
                 * At this point the message is formatted and is ready to go to the output stream
                 */
                virtual void ProcessFormattedStatement(Aws::String&& statement) = 0;

            private:
                std::atomic<LogLevel> m_logLevel;
            };

        } // namespace Logging
    } // namespace Utils
} // namespace Aws


text:
<?php
include 'application/init.php';
header('Location: ' . HOST . 'dashboard');
?>


text:
package org.apache.drill.yarn.appMaster.http;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.drill.yarn.appMaster.http.WebUiPageTree.LogInLogOutPages;
import org.glassfish.jersey.server.model.AnnotatedMethod;

import javax.annotation.Priority;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.DynamicFeature;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.FeatureContext;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;

/**
 * Implementation of {@link DynamicFeature}. As part of the setup it adds the
 * auth check filter {@link AuthCheckFilter} for resources that need to have
 * user authenticated. If authentication is not done, request is forwarded to
 * login page.
 * <p>
 * Shameless copy of
 * {@link org.apache.drill.exec.server.rest.auth.DynamicFeature}; the two
 * implementations should be merged at some point. The difference is only the
 * log in/log out constant references.
 */

public class AuthDynamicFeature implements DynamicFeature {
  private static final Log LOG = LogFactory.getLog(AuthDynamicFeature.class);

  @Override
  public void configure(final ResourceInfo resourceInfo,
      final FeatureContext configuration) {
    AnnotatedMethod am = new AnnotatedMethod(resourceInfo.getResourceMethod());

    // RolesAllowed on the method takes precedence over PermitAll
    RolesAllowed ra = am.getAnnotation(RolesAllowed.class);
    if (ra != null) {
      configuration.register(AuthCheckFilter.INSTANCE);
      return;
    }

    // PermitAll takes precedence over RolesAllowed on the class
    if (am.isAnnotationPresent(PermitAll.class)) {
      // Do nothing.
      return;
    }

    // RolesAllowed on the class takes precedence over PermitAll
    ra = resourceInfo.getResourceClass().getAnnotation(RolesAllowed.class);
    if (ra != null) {
      configuration.register(AuthCheckFilter.INSTANCE);
    }
  }

  @Priority(Priorities.AUTHENTICATION) // authentication filter - should go
                                       // first before all other filters.
  private static class AuthCheckFilter implements ContainerRequestFilter {
    private static AuthCheckFilter INSTANCE = new AuthCheckFilter();

    @Override
    public void filter(ContainerRequestContext requestContext)
        throws IOException {
      final SecurityContext sc = requestContext.getSecurityContext();
      if (!isUserLoggedIn(sc)) {
        try {
          final String destResource = URLEncoder.encode(
              requestContext.getUriInfo().getRequestUri().toString(), "UTF-8");
          final URI loginURI = requestContext.getUriInfo().getBaseUriBuilder()
              .path(LogInLogOutPages.LOGIN_RESOURCE)
              .queryParam(LogInLogOutPages.REDIRECT_QUERY_PARM, destResource)
              .build();
          requestContext
              .abortWith(Response.temporaryRedirect(loginURI).build());
        } catch (final Exception ex) {
          final String errMsg = String.format(
              "Failed to forward the request to login page: %s",
              ex.getMessage());
          LOG.error(errMsg, ex);
          requestContext
              .abortWith(Response.serverError().entity(errMsg).build());
        }
      }
    }
  }

  public static boolean isUserLoggedIn(final SecurityContext sc) {
    return sc != null && sc.getUserPrincipal() != null;
  }
}


text:
'use strict';

angular.module('tamadroidApp', [
  'ngCookies',
  'ngResource',
  'ngSanitize',
  'ngRoute',
  'ui.bootstrap'
])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  });


text:
extern void fputd(FILE *fh, const char *data, unsigned long len);
extern void fput(FILE *fh, const char *data);
extern void fput_ch(FILE *fh, char ch);
extern void fput_long(FILE *fh, long x);
extern void fput_ulong(FILE *fh, unsigned long x);
extern void fput_double(FILE *fh, double x);
extern void fnl(FILE *fh);