text:
<?php
/*
 *  Compatibility layer to DataStorage2
*/

class DataStorage extends DataStorage2
{
    public function __construct($args, $sid = null, $lockDB = null, $format = null, $lockTimeout = null, $secure = null)
    {
        if ($sid !== null) {
            if (is_string($args)) {
                $args = ['dataFile' => $args];
            }
            $args = array_merge($args, ['sid' => $sid, 'lockDB' => $lockDB, 'format' => $format,'secure' => $secure]);
        }
        parent::__construct($args);
    }

    public function read( $arg = null )
    {
        if (!$arg || ($arg === '*')) {
            return parent::read();
        } else {
            return parent::readElement($arg);
        }
    }

    public function write($data, $replace = true)
    {
        if (is_array($data)) {
            return parent::write($data, $replace);
        } else {
            // $value == $replace;
            return parent::writeElement(data, $replace);
        }
    }

} // DataStorage


text:
require_relative 'spec_helper'

describe Uptyped::InterfaceValidator do
  before(:each) do
    class TestSuperClass
    end

    class TestSubClass < TestSuperClass
    end
  end

  context 'checking public methods' do
    context 'extra method on the subclass' do
      it 'fails and sets an error message' do
        class TestSubClass
          def extra_instance_method
          end
        end

        validated_class = TestSubClass
        superclass = TestSuperClass
        interface_validator = Uptyped::InterfaceValidator.new(TestSubClass)
        expect(interface_validator).to_not be_success
        expect(interface_validator.public_instance_method_errors).to eq(["expected #{validated_class} to have the same public instance methods as #{superclass}, got [:extra_instance_method]."])

        class TestSubClass
          undef extra_instance_method
        end
      end
    end

    context 'extra class method on subclass' do
      it 'fails and sets an error message' do
        class TestSubClass
          def self.extra_class_method
          end
        end
        validated_class = TestSubClass
        superclass = TestSuperClass
        interface_validator = Uptyped::InterfaceValidator.new(TestSubClass)
        expect(interface_validator).to_not be_success
        expect(interface_validator.public_class_method_errors).to eq(["expected #{validated_class} to have the same public class methods as #{superclass}, got [:extra_class_method]."])

        class << TestSubClass
          remove_method :extra_class_method
        end
      end
    end
  end

  context 'checking arity' do
    context 'mismatch on public instance methods' do
      it 'fails and sets an error message' do

        class TestSuperClass
          def foo
          end
        end

        class TestSubClass < TestSuperClass
          def foo(bar)
          end
        end

        interface_validator = Uptyped::InterfaceValidator.new(TestSubClass)
        expect(interface_validator).to_not be_success
        expect(interface_validator.instance_method_arity_errors).to eq(["TestSubClass#foo takes 1 argument(s) while TestSuperClass#foo takes 0 argument(s)."])

        class TestSubClass
          undef foo
        end

        class TestSuperClass
          undef foo
        end
      end
    end
  end

  context 'mismatch on public class methods' do
    it 'fails and sets an error message' do

      class TestSuperClass
        def self.foo
        end
      end

      class TestSubClass
        def self.foo(bar)
        end
      end

      interface_validator = Uptyped::InterfaceValidator.new(TestSubClass)
      expect(interface_validator).to_not be_success
      expect(interface_validator.class_method_arity_errors).to eq(["TestSubClass.foo takes 1 argument(s) while TestSuperClass.foo takes 0 argument(s)."])
    end
  end
end

redpajama_set_name: RedPajamaGithub


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

import java.util.List;

import org.flowable.cmmn.api.delegate.DelegatePlanItemInstance;
import org.flowable.cmmn.api.listener.PlanItemInstanceLifecycleListener;
import org.flowable.cmmn.engine.impl.util.DelegateExpressionUtil;
import org.flowable.cmmn.model.FieldExtension;
import org.flowable.common.engine.api.FlowableIllegalArgumentException;
import org.flowable.common.engine.api.delegate.Expression;

/**
 * @author Joram Barrez
 */
public class DelegateExpressionPlanItemLifecycleListener implements PlanItemInstanceLifecycleListener {

    protected String sourceState;
    protected String targetState;
    protected Expression expression;
    protected List<FieldExtension> fieldExtensions;

    public DelegateExpressionPlanItemLifecycleListener(String sourceState, String targetState, Expression expression,
        List<FieldExtension> fieldExtensions) {
        this.sourceState = sourceState;
        this.targetState = targetState;
        this.expression = expression;
        this.fieldExtensions = fieldExtensions;
    }

    @Override
    public String getSourceState() {
        return sourceState;
    }

    @Override
    public String getTargetState() {
        return targetState;
    }

    @Override
    public void stateChanged(DelegatePlanItemInstance planItemInstance, String oldState, String newState) {
        Object delegate = DelegateExpressionUtil.resolveDelegateExpression(expression, planItemInstance, fieldExtensions);

        if (delegate instanceof PlanItemInstanceLifecycleListener) {
            PlanItemInstanceLifecycleListener listener = (PlanItemInstanceLifecycleListener) delegate;
            listener.stateChanged(planItemInstance, oldState, newState);
        } else {
            throw new FlowableIllegalArgumentException("Delegate expression " + expression + " did not resolve to an implementation of " + PlanItemInstanceLifecycleListener.class);
        }
    }

    /**
     * returns the expression text for this planItemInstance lifecycle listener.
     */
    public String getExpressionText() {
        return expression.getExpressionText();
    }

}


text:
$(document).ready(function() {
    var url = "/direct/sakai-oaai/";

    $(".csv").click(function() {
        $("#action").val(this.id);
        $("#downloadForm").submit();
    });

    $("#generate").click(function() {
        var criteria = $("#criteria").serialize();
        generateNewData(this.id, criteria, function(data) {
            outputResponse(data);
        });
    });

    /*function getData(endpoint, directory, callback) {
        var request = $.ajax({
            type: "GET",
            url:  url + endpoint + "/" + directory,
            data: {}
         });

        request.success(function(data, status, jqXHR) {
            callback(data);
        });

        request.error(function(jqXHR, textStatus, errorThrown) {
            callback("Request failed: " + textStatus + ", error : " + errorThrown);
        });
    }*/

    function generateNewData(endpoint, criteria, callback) {
        console.log(criteria);
        var request = $.ajax({
            type: "POST",
            url:  url + endpoint,
            data: criteria
         });

        request.success(function(data, status, jqXHR) {
            callback(data);
        });

        request.error(function(jqXHR, textStatus, errorThrown) {
            callback("Request failed: " + textStatus + ", error : " + errorThrown);
        });
    }

    // temp function for testing
    function outputResponse(data) {
        $("#jsonResponse").html(JSON.stringify(data, null, 2));
    }
});


text:
package de.zh32.teleportsigns;

import de.zh32.teleportsigns.ping.ServerInfo;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;

/**
 *
 * @author zh32 <zh32 at zh32.de>
 */
@Data
@EqualsAndHashCode(callSuper = false)
public class ProxyTeleportEvent extends Event implements Cancellable {

    private boolean cancelled;
    private final Player player;
    private final ServerInfo serverInfo;
    private static final HandlerList handlers = new HandlerList();

    @Override
    public HandlerList getHandlers() {
            return handlers;
    }

    public static HandlerList getHandlerList() {
            return handlers;
    }
}


text:
The [`Unit`] is the primary data structure representing a single execution of
the compiler. It (mostly) contains all the information needed to determine
which flags to pass to the compiler.

The entry to the compilation process is located in the [`cargo_compile`]
module. The compilation can be conceptually broken into these steps:

1. Perform dependency resolution (see [the resolution chapter]).
2. Generate the root `Unit`s, the things the user requested to compile on the
   command-line. This is done in [`generate_targets`].
3. Starting from the root `Unit`s, generate the [`UnitGraph`] by walking the
   dependency graph from the resolver. The `UnitGraph` contains all of the
   `Unit` structs, and information about the dependency relationships between
   units. This is done in the [`unit_dependencies`] module.
4. Construct the [`BuildContext`] with all of the information collected so
   far. This is the end of the "front end" of compilation.
5. Create a [`Context`], a large, mutable data structure that coordinates the
   compilation process.
6. The [`Context`] will create a [`JobQueue`], a data structure that tracks
   which units need to be built.
7. [`drain_the_queue`] does the compilation process. This is the only point in
   Cargo that currently uses threads.
8. The result of the compilation is stored in the [`Compilation`] struct. This
   can be used for various things, such as running tests after the compilation
   has finished.

[`cargo_compile`]: https://github.com/rust-lang/cargo/blob/master/src/cargo/ops/cargo_compile.rs
[`generate_targets`]: https://github.com/rust-lang/cargo/blob/e4b65bdc80f2a293447f2f6a808fa7c84bf9a357/src/cargo/ops/cargo_compile.rs#L725-L739
[`UnitGraph`]: https://github.com/rust-lang/cargo/blob/master/src/cargo/core/compiler/unit_graph.rs
[the resolution chapter]: packages.md
[`Unit`]: https://github.com/rust-lang/cargo/blob/master/src/cargo/core/compiler/unit.rs
[`unit_dependencies`]: https://github.com/rust-lang/cargo/blob/master/src/cargo/core/compiler/unit_dependencies.rs
[`BuildContext`]: https://github.com/rust-lang/cargo/blob/master/src/cargo/core/compiler/build_context/mod.rs
[`Context`]: https://github.com/rust-lang/cargo/blob/master/src/cargo/core/compiler/context/mod.rs
[`JobQueue`]: https://github.com/rust-lang/cargo/blob/master/src/cargo/core/compiler/job_queue.rs
[`drain_the_queue`]: https://github.com/rust-lang/cargo/blob/e4b65bdc80f2a293447f2f6a808fa7c84bf9a357/src/cargo/core/compiler/job_queue.rs#L623-L634
[`Compilation`]: https://github.com/rust-lang/cargo/blob/master/src/cargo/core/compiler/compilation.rs


text:
package com.che.base_util;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.text.TextUtils;
import android.util.Log;

import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * 多渠道打包工具类
 * <p>
 * 需配合Python脚本使用
 */
public class ChannelUtil {

    /**
     * 初始化渠道
     */
    public static void init(Context context, ChannelListener listener) {
        String channelId = getChannelFromApk(context, "channel-");
        if (TextUtils.isEmpty(channelId)) {
            channelId = "test";
        }
        Log.v("channel", "当前渠道:" + channelId);
        if (listener != null) {
            listener.onResult(channelId);
        }
    }

    /**
     * 从apk中获取渠道信息
     *
     * @param context
     * @param channelPrefix 渠道前缀
     * @return
     */
    private static String getChannelFromApk(Context context, String channelPrefix) {
        //从apk包中获取
        ApplicationInfo appinfo = context.getApplicationInfo();
        String sourceDir = appinfo.sourceDir;
        //默认放在meta-inf/里, 所以需要再拼接一下
        String key = "META-INF/" + channelPrefix;
        String ret = "";
        ZipFile zipfile = null;
        try {
            zipfile = new ZipFile(sourceDir);
            Enumeration<?> entries = zipfile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = ((ZipEntry) entries.nextElement());
                String entryName = entry.getName();
                if (entryName.startsWith(key)) {
                    ret = entryName;
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (zipfile != null) {
                try {
                    zipfile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        String[] split = ret.split(channelPrefix);
        String channel = "";
        if (split != null && split.length >= 2) {
            channel = ret.substring(key.length());
        }
        return channel;
    }

    /**
     * 渠道回调
     */
    public interface ChannelListener {
        void onResult(String channelId);
    }

}


text:
'use strict';

import React from 'react';
import ReactDOM from 'react-dom';
import AlizeViewer from './AlizeViewer';

const config = {
  urls: [
    {
      url: '/api/v1/hello',
      method: 'get',
    },
    {
      url: '/api/v1/hello',
      method: 'post',
    },
    {
      url: '/api/v1/hello/:id',
      method: 'delete',
    },
  ],
};

ReactDOM.render(React.createElement(AlizeViewer, { config }), document.getElementById('main'));


text:
package org.locationtech.geowave.core.store.statistics.binning;

import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.List;
import java.util.OptionalInt;
import java.util.Set;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.apache.commons.lang3.tuple.Pair;
import org.locationtech.geowave.core.index.ByteArray;
import org.locationtech.geowave.core.index.VarintUtils;
import org.locationtech.geowave.core.index.persist.Persistable;
import org.locationtech.geowave.core.index.persist.PersistenceUtils;
import org.locationtech.geowave.core.store.api.BinConstraints.ByteArrayConstraints;
import org.locationtech.geowave.core.store.api.DataTypeAdapter;
import org.locationtech.geowave.core.store.api.StatisticBinningStrategy;
import org.locationtech.geowave.core.store.entities.GeoWaveRow;
import org.locationtech.geowave.core.store.statistics.query.BinConstraintsImpl.ExplicitConstraints;
import com.google.common.collect.Lists;

/**
 * Statistic binning strategy that combines two or more other binning strategies.
 */
public class CompositeBinningStrategy implements StatisticBinningStrategy {

  public static final String NAME = "COMPOSITE";
  public static final byte[] WILDCARD_BYTES = new byte[0];

  private StatisticBinningStrategy[] childBinningStrategies;

  public CompositeBinningStrategy() {
    childBinningStrategies = new StatisticBinningStrategy[0];
  }

  public CompositeBinningStrategy(final StatisticBinningStrategy... childBinningStrategies) {
    this.childBinningStrategies = childBinningStrategies;
  }

  @Override
  public String getStrategyName() {
    return NAME;
  }

  @Override
  public String getDescription() {
    return "Bin the statistic using multiple strategies.";
  }

  @Override
  public <T> ByteArray[] getBins(
      final DataTypeAdapter<T> adapter,
      final T entry,
      final GeoWaveRow... rows) {
    final ByteArray[][] perStrategyBins =
        Arrays.stream(childBinningStrategies).map(s -> s.getBins(adapter, entry, rows)).toArray(
            ByteArray[][]::new);
    return getAllCombinations(perStrategyBins);
  }

  @Override
  public String getDefaultTag() {
    return Arrays.stream(childBinningStrategies).map(s -> s.getDefaultTag()).collect(
        Collectors.joining("|"));
  }

  @Override
  public void addFieldsUsed(final Set<String> fieldsUsed) {
    for (final StatisticBinningStrategy child : childBinningStrategies) {
      child.addFieldsUsed(fieldsUsed);
    }
  }

  @Override
  public byte[] toBinary() {
    return PersistenceUtils.toBinary(Lists.newArrayList(childBinningStrategies));
  }

  @Override
  public void fromBinary(final byte[] bytes) {
    final List<Persistable> strategies = PersistenceUtils.fromBinaryAsList(bytes);
    childBinningStrategies = strategies.toArray(new StatisticBinningStrategy[strategies.size()]);
  }

  @Override
  public String binToString(final ByteArray bin) {
    if (bin == null || bin.getBytes() == null || bin.getBytes().length == 0) {
      return "None";
    }
    final ByteBuffer buffer = ByteBuffer.wrap(bin.getBytes());
    buffer.position(buffer.limit() - 1);
    final int[] byteLengths =
        Arrays.stream(childBinningStrategies).mapToInt(
            s -> VarintUtils.readUnsignedIntReversed(buffer)).toArray();
    buffer.rewind();
    final StringBuffer strVal = new StringBuffer();
    for (int i = 0; i < childBinningStrategies.length; i++) {
      if (i != 0) {
        strVal.append("|");
      }
      final byte[] subBin = new byte[byteLengths[i]];
      buffer.get(subBin);
      strVal.append(childBinningStrategies[i].binToString(new ByteArray(subBin)));
    }
    return strVal.toString();
  }

  public Pair<StatisticBinningStrategy, ByteArray>[] getSubBins(final ByteArray bin) {
    final ByteBuffer buffer = ByteBuffer.wrap(bin.getBytes());
    buffer.position(buffer.limit() - 1);
    final int[] byteLengths =
        Arrays.stream(childBinningStrategies).mapToInt(
            s -> VarintUtils.readUnsignedIntReversed(buffer)).toArray();
    buffer.rewind();
    @SuppressWarnings("unchecked")
    final Pair<StatisticBinningStrategy, ByteArray>[] retVal =
        new Pair[childBinningStrategies.length];
    for (int i = 0; i < childBinningStrategies.length; i++) {
      final byte[] subBin = new byte[byteLengths[i]];
      buffer.get(subBin);
      retVal[i] = Pair.of(childBinningStrategies[i], new ByteArray(subBin));
    }
    return retVal;
  }

  public boolean binMatches(
      final Class<? extends StatisticBinningStrategy> binningStrategyClass,
      final ByteArray bin,
      final ByteArray subBin) {
    // this logic only seems to be valid if the child binning strategy classes are different
    final ByteBuffer buffer = ByteBuffer.wrap(bin.getBytes());
    // first look to see if the strategy is directly assignable and at which position
    final OptionalInt directlyAssignable =
        IntStream.range(0, childBinningStrategies.length).filter(
            i -> binningStrategyClass.isAssignableFrom(
                childBinningStrategies[i].getClass())).findFirst();
    if (directlyAssignable.isPresent()) {
      return Arrays.equals(
          getSubBinAtIndex(directlyAssignable.getAsInt(), buffer),
          subBin.getBytes());
    }
    final OptionalInt composite =
        IntStream.range(0, childBinningStrategies.length).filter(
            i -> (childBinningStrategies[i] instanceof CompositeBinningStrategy)
                && ((CompositeBinningStrategy) childBinningStrategies[i]).usesStrategy(
                    binningStrategyClass)).findFirst();
    if (composite.isPresent()) {
      // get the subBin from the buffer at this position
      return ((CompositeBinningStrategy) childBinningStrategies[composite.getAsInt()]).binMatches(
          binningStrategyClass,
          new ByteArray(getSubBinAtIndex(directlyAssignable.getAsInt(), buffer)),
          subBin);
    }
    return false;
  }

  private static byte[] getSubBinAtIndex(final int index, final ByteBuffer buffer) {
    // get the subBin from the buffer at this position
    buffer.position(buffer.limit() - 1);
    final int skipBytes =
        IntStream.range(0, index - 1).map(i -> VarintUtils.readUnsignedIntReversed(buffer)).sum();
    final byte[] subBin = new byte[VarintUtils.readUnsignedIntReversed(buffer)];
    buffer.position(skipBytes);
    buffer.get(subBin);
    return subBin;
  }

  public boolean usesStrategy(
      final Class<? extends StatisticBinningStrategy> binningStrategyClass) {
    return Arrays.stream(childBinningStrategies).anyMatch(
        s -> binningStrategyClass.isAssignableFrom(s.getClass())
            || ((s instanceof CompositeBinningStrategy)
                && ((CompositeBinningStrategy) s).usesStrategy(binningStrategyClass)));
  }

  public boolean isOfType(final Class<?>... strategyClasses) {
    if (strategyClasses.length == childBinningStrategies.length) {
      return IntStream.range(0, strategyClasses.length).allMatch(
          i -> strategyClasses[i].isAssignableFrom(childBinningStrategies[i].getClass()));
    }
    return false;
  }

  public static ByteArray getBin(final ByteArray... bins) {
    final int byteLength =
        Arrays.stream(bins).map(ByteArray::getBytes).mapToInt(
            b -> b.length + VarintUtils.unsignedIntByteLength(b.length)).sum();
    final ByteBuffer bytes = ByteBuffer.allocate(byteLength);
    Arrays.stream(bins).map(ByteArray::getBytes).forEach(b -> {
      bytes.put(b);
    });
    // write the lengths at the back for deserialization purposes only (and so prefix scans don't
    // need to account for this)

    // also we want to iterate in reverse order so this reverses the order
    final Deque<ByteArray> output =
        Arrays.stream(bins).collect(
            Collector.of(ArrayDeque::new, (deq, t) -> deq.addFirst(t), (d1, d2) -> {
              d2.addAll(d1);
              return d2;
            }));
    output.stream().map(ByteArray::getBytes).forEach(b -> {
      VarintUtils.writeUnsignedIntReversed(b.length, bytes);
    });
    return new ByteArray(bytes.array());
  }

  @Override
  public ByteArrayConstraints constraints(final Object constraint) {
    if ((constraint != null) && (constraint instanceof Object[])) {
      return constraints((Object[]) constraint, childBinningStrategies);
    }
    return StatisticBinningStrategy.super.constraints(constraint);
  }

  private ByteArrayConstraints constraints(
      final Object[] constraints,
      final StatisticBinningStrategy[] binningStrategies) {
    // this will handle merging bins together per constraint-binningStrategy pair
    if (constraints.length == binningStrategies.length) {
      final List<ByteArrayConstraints> perStrategyConstraints =
          IntStream.range(0, constraints.length).mapToObj(
              i -> binningStrategies[i].constraints(constraints[i])).collect(Collectors.toList());
      return concat(perStrategyConstraints);
    }
    // if there's not the same number of constraints as binning strategies, use default logic
    return StatisticBinningStrategy.super.constraints(constraints);
  }

  private ByteArrayConstraints concat(final List<ByteArrayConstraints> perStrategyConstraints) {
    final ByteArray[][] c = new ByteArray[perStrategyConstraints.size()][];
    boolean allBins = true;
    for (int i = 0; i < perStrategyConstraints.size(); i++) {
      final ByteArrayConstraints constraints = perStrategyConstraints.get(i);
      if (constraints.isAllBins()) {
        if (!allBins) {
          throw new IllegalArgumentException(
              "Cannot use 'all bins' query for one strategy and not the other");
        }
      } else {
        allBins = false;
      }
      if (constraints.isPrefix()) {
        // can only use a prefix if its the last field or the rest of the fields are 'all bins'
        boolean isValid = true;
        for (final int j = i + 1; i < perStrategyConstraints.size(); i++) {
          final ByteArrayConstraints innerConstraints = perStrategyConstraints.get(j);
          if (!innerConstraints.isAllBins()) {
            isValid = false;
            break;
          } else {
            c[i] = new ByteArray[] {new ByteArray()};
          }
        }
        if (isValid) {
          return new ExplicitConstraints(getAllCombinations(c), true);
        } else {
          throw new IllegalArgumentException(
              "Cannot use 'prefix' query for a strategy that is also using exact constraints on a subsequent strategy");
        }
      }
      c[i] = constraints.getBins();
    }
    return new ExplicitConstraints(getAllCombinations(c), false);
  }

  private static ByteArray[] getAllCombinations(final ByteArray[][] perStrategyBins) {
    return BinningStrategyUtils.getAllCombinations(
        perStrategyBins,
        CompositeBinningStrategy::getBin);
  }

}


text:
import * as React from "react"

export interface QueryInputProps {
  onUpdate: (text: string) => void
  disabled: boolean
}

export default class QueryInput extends React.Component<QueryInputProps, any> {
  textInput: HTMLTextAreaElement

  constructor(props: QueryInputProps) {
    super(props)

    this.onSubmit = this.onSubmit.bind(this)
  }

  onSubmit(e?) {
    if (e) e.preventDefault()
    console.info("Submitting:", this.textInput.value)
    this.props.onUpdate(this.textInput.value)
  }
  render() {
    return (
      <div id="query-input-wrapper">
        <textarea
          id="query-input"
          placeholder="Query..."
          cols={80}
          rows={10}
          ref={(input: HTMLTextAreaElement) => {this.textInput = input}}
        />
        <button
          disabled={this.props.disabled}
          onClick={this.onSubmit}
        >Parse Query</button>
      </div>
    )
  }
}


text:
namespace Microsoft.Azure.Management.ResourceManager.Fluent.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Tag information.
    /// </summary>
    public partial class TagValueInner
    {
        /// <summary>
        /// Initializes a new instance of the TagValueInner class.
        /// </summary>
        public TagValueInner()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the TagValueInner class.
        /// </summary>
        /// <param name="id">The tag ID.</param>
        /// <param name="tagValueProperty">The tag value.</param>
        /// <param name="count">The tag value count.</param>
        public TagValueInner(string id = default(string), string tagValueProperty = default(string), TagCount count = default(TagCount))
        {
            Id = id;
            TagValueProperty = tagValueProperty;
            Count = count;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the tag ID.
        /// </summary>
        [JsonProperty(PropertyName = "id")]
        public string Id { get; set; }

        /// <summary>
        /// Gets or sets the tag value.
        /// </summary>
        [JsonProperty(PropertyName = "tagValue")]
        public string TagValueProperty { get; set; }

        /// <summary>
        /// Gets or sets the tag value count.
        /// </summary>
        [JsonProperty(PropertyName = "count")]
        public TagCount Count { get; set; }

    }
}


text:
package com.opengamma.strata.collect.named;

/**
 * Mock named object.
 */
public interface SampleInvalid4 extends Named {

}


text:
"""
Rejected AMQP Consumer Framework

A multi-threaded consumer application and how!

Copyright (c) 2009,  Insider Guides, Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the Insider Guides, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

__author__  = "Gavin M. Roy"
__email__   = "gmr@myyearbook.com"
__date__    = "2009-09-10"
__version__ = 0.2

import amqplib.client_0_8 as amqp
import atexit
import signal
import exceptions
import logging
import sys
import optparse
import os
import signal
import threading
import time
import traceback
import yaml
import zlib
import _mssql

# Number of seconds to sleep between polls
mcp_poll_delay = 10
is_quitting = False

# Process name will be overriden by the config file
process = 'Unknown'

# pidfile
pidfile = '/usr/local/rejected/rejected.pid'

class ConnectionException( exceptions.Exception ):

    def __str__(self):
        return "Connection Failed"

class ConsumerThread( threading.Thread ):
    """ Consumer Class, Handles the actual AMQP work """

    def __init__( self, configuration, binding_name, connect_name ):

        logging.debug( 'Initializing a Consumer Thread' )

        # Rejected full Configuration
        self.config = configuration

        # Binding to make code more readable
        binding = self.config['Bindings'][binding_name]
	self.binding = binding

        # Initialize object wide variables
        self.auto_ack = binding['consumers']['auto_ack']
        self.binding_name = binding_name
        if binding.has_key('compressed'):
            self.compressed = binding['compressed']
        else:
            self.compressed = False
        self.connect_name = connect_name
        self.connection = None
        self.errors = 0
        self.interval_count = 0
        self.interval_start = None
        self.locked = False
        self.monitor_port = None
        self.max_errors = binding['consumers']['max_errors']
        self.messages_processed = 0
        self.error_queue = binding['consumers']['error_queue']
	self.use_error_queue = binding['consumers']['use_error_queue']
        self.requeue_on_error = binding['consumers']['requeue_on_error']
        self.running = True
        self.queue_name = None
	self.mssql_conn = None

        # If we have throttle config use it
        self.throttle = False
        self.throttle_count = 0
        self.throttle_duration = 0
        if binding['consumers'].has_key('throttle'):
            logging.debug( 'Setting message throttle to %i message(s) per second' %
                            binding['consumers']['throttle'] )
            self.throttle = True
            self.throttle_threshold = binding['consumers']['throttle']

	# check for mssql connection and connect
        mssql_server = str(binding['mssqlserver'])
        mssql_user = str(binding['mssqluser'])
        mssql_password = str(binding['mssqlpassword'])
        mssql_database = str(binding['mssqldatabase'])

	if mssql_server != "":
            try:
                self.mssql_conn = _mssql.connect(server=mssql_server, user=mssql_user, password=mssql_password, database=mssql_database)
            except:
                e = sys.exc_info()[1]
                logging.error('Error connecting to mssql database: %s' % e)

        # Init the Thread Object itself
        threading.Thread.__init__(self)

    def connect( self, configuration ):
        """ Connect to an AMQP Broker  """

        logging.debug( 'Creating a new connection for "%s" in thread "%s"' %
                        ( self.binding_name, self.getName() ) )

        try:
            # Try and create our new AMQP connection
            connection = amqp.Connection( host ='%s:%s' % ( configuration['host'], configuration['port'] ),
                                userid = configuration['user'],
                                password = configuration['pass'],
                                ssl = configuration['ssl'],
                                virtual_host = configuration['vhost'] )
            return connection

        # amqp lib is only raising a generic exception which is odd since it has a AMQPConnectionException class
        except IOError, e:
            logging.error( 'Connection error #%i: %s' % (e.errno, e.message) )
            raise ConnectionException

    def get_information(self):
        """ Grab Information from the Thread """

        return {
                 'connection': self.connect_name,
                 'binding': self.binding_name,
                 'queue': self.queue_name,
                 'monitor_port': self.monitor_port,
                 'processed': self.messages_processed,
                 'throttle_count': self.throttle_count
               }

    def is_locked( self ):
        """ What is the lock status for the MCP? """

        return self.locked

    def lock( self ):
        """ Lock the thread so the MCP does not destroy it until we're done processing a message """

        self.locked = True

    def process(self, message):
        """ Process a message from Rabbit"""

        # If we're throttling
        if self.throttle and self.interval_start is None:
           self.interval_start = time.time()

        # Lock while we're processing
        self.lock()

        # If we're compressed in message body, decompress it
        if self.compressed:
            try:
            	message.body = zlib.decompress(message.body)
            except:
                logging.warning('Invalid zlib compressed message.body')

        # Process the message, if it returns True, we're all good
        try:
            if self.processor.process(self, message):
                self.messages_processed += 1

                logging.warning("Processor returned true")

                # If we're not auto-acking at the broker level, do so here, but why?
                if not self.auto_ack:
                    self.channel.basic_ack( message.delivery_tag )

            # It's returned False, so we should check our our check
            # We don't want to have out-of-control errors
            else:
               logging.warning("Processor returned false")
               # Unlock
               self.unlock()

               # Do we need to requeue?  If so, lets send it
               if self.use_error_queue:
		   logging.warning("Sending message to error queue : " + self.exchange + "." + self.error_queue)

                   msg = amqp.Message(message.body)
                   msg.properties['delivery_mode'] = 2
                   self.channel.basic_publish( msg,
                                               exchange = self.exchange,
                                               routing_key = self.exchange + '.' + self.error_queue )
	           logging.debug("Message sent to error queue")

               # Keep track of how many errors we've had
               # Do we need to requeue?  If so, lets send it
               if self.requeue_on_error:
		   logging.warning("Requeuing message...")

                   msg = amqp.Message(message.body)
                   msg.properties['delivery_mode'] = 2
                   self.channel.basic_publish( msg,
                                               exchange = self.exchange,
                                               routing_key = self.binding_name )

               # Keep track of how many errors we've had
               self.errors += 1

        except Exception as e:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            formatted_lines = traceback.format_exc().splitlines()
            logging.critical('ConsumerThread: Processor threw an uncaught exception')
            logging.critical('ConsumerThread: %s' % str(e))
            logging.critical('ConsumerThread: %s' % formatted_lines[3].strip())
            logging.critical('ConsumerThread: %s' % formatted_lines[4].strip())

            logging.warning("Processor Exception!")

            # Unlock
            self.unlock()

            # Do we need to requeue?  If so, lets send it
            if self.requeue_on_error:
	       logging.warning("Requeuing message...")
               msg = amqp.Message(message.body)
               msg.properties['delivery_mode'] = 2
               self.channel.basic_publish( msg,
                                           exchange = self.exchange,
                                           routing_key = self.binding_name )

            # Keep track of how many errors we've had
            self.errors += 1

            # If we've had too many according to the configuration, shutdown
            if self.errors >= self.max_errors:
                logging.error( 'Received %i errors, shutting down thread "%s"' % ( self.errors, self.getName() ) )
                self.shutdown()
                return

        # Unlock the thread, safe to shutdown
        self.unlock()

        # If we're throttling
        if self.throttle:

           # Get the duration from when we starting this interval to now
           self.throttle_duration += time.time() - self.interval_start
           self.interval_count += 1

           # If the duration is less than 1 second and we've processed up to (or over) our max
           if self.throttle_duration <= 1 and self.interval_count >= self.throttle_threshold:

               # Increment our throttle count
               self.throttle_count += 1

               # Figure out how much time to sleep
               sleep_time = 1 - self.throttle_duration

               logging.debug( '%s: Throttling to %i message(s) per second, waiting %.2f seconds.' %
                              ( self.getName(), self.throttle_threshold, sleep_time ) )

               # Sleep and setup for the next interval
               time.sleep(sleep_time)

               # Reset our counters
               self.interval_count = 0
               self.interval_start = None
               self.throttle_duration = 0

           # Else if our duration is more than a second restart our counters
           elif self.throttle_duration >= 1:
               self.interval_count = 0
               self.interval_start = None
               self.throttle_duration = 0

    def run( self ):
        """ Meat of the queue consumer code """

        logging.debug( '%s: Running thread' % self.getName() )

        # Import our processor class
        import_name = self.config['Bindings'][self.binding_name]['import']
        class_name = self.config['Bindings'][self.binding_name]['processor']

        # Try and import the module
        try:
            processor_module = __import__(import_name)
        except ImportError:
            logging.error( '%s: Could not import the "%s" module.' % ( self.getName(), import_name ) )
            self.running = False
            return

        file_parts = import_name.split('.')
        processor_class = getattr(processor_module.__dict__[file_parts[len(file_parts)-1]], class_name)
        logging.info( '%s: Creating message processor: %s.%s' %
                      ( self.getName(), import_name, class_name ) )

        # If we have a config, pass it in to the constructor
        if self.config['Bindings'][self.binding_name].has_key('config'):
            self.processor = processor_class(self.config['Bindings'][self.binding_name]['config'])
        else:
            self.processor = processor_class()

        # Assign the port to monitor the queues on
        self.monitor_port = self.config['Connections'][self.connect_name]['monitor_port']

        # Connect to the AMQP Broker
        try:
            self.connection = self.connect( self.config['Connections'][self.connect_name] )
        except ConnectionException:
            self.running = False
            return

        # Create the Channel
        self.channel = self.connection.channel()

        # Create / Connect to the Queue
        self.queue_name = self.config['Bindings'][self.binding_name]['queue']
        queue_auto_delete = self.config['Queues'][self.queue_name ]['auto_delete']
        queue_durable = self.config['Queues'][self.queue_name ]['durable']
        queue_exclusive = self.config['Queues'][self.queue_name ]['exclusive']

        self.channel.queue_declare( queue = self.queue_name ,
                                    durable = queue_durable,
                                    exclusive = queue_exclusive,
                                    auto_delete = queue_auto_delete )

        # Create / Connect to the Exchange
        self.exchange = self.config['Bindings'][self.binding_name]['exchange']
        exchange_auto_delete = self.config['Exchanges'][self.exchange]['auto_delete']
        exchange_durable = self.config['Exchanges'][self.exchange]['durable']
        exchange_type = self.config['Exchanges'][self.exchange]['type']

        self.channel.exchange_declare( exchange = self.exchange,
                                       type = exchange_type,
                                       durable = exchange_durable,
                                       auto_delete = exchange_auto_delete)

        # Bind to the Queue / Exchange
        self.channel.queue_bind( queue = self.queue_name,
                                 exchange = self.exchange,
                                 routing_key = self.binding_name )

        # Allow the processor to use additional binding keys
        if "BindingKeys" in self.config['Bindings'][self.binding_name]:
            for key in self.config['Bindings'][self.binding_name]['BindingKeys']:
                self.channel.queue_bind( queue = self.queue_name,
                                         exchange = self.exchange,
                                         routing_key = key )

        # Wait for messages
        logging.debug( '%s: Waiting on messages' %  self.getName() )

        # Let AMQP know to send us messages
        self.channel.basic_consume( queue = self.queue_name,
                                    no_ack = self.auto_ack,
                                    callback = self.process,
                                    consumer_tag = self.getName() )

        # Initialize our throttle variable if we need it
        interval_start = None

        # Loop as long as the thread is running
        while self.running:

            # Wait on messages
            if is_quitting:
                logging.info('Not wait()ing because is_quitting is set!')
                break
            try:
                self.channel.wait()
            except IOError:
                logging.error('%s: IOError received' % self.getName() )
            except AttributeError:
                logging.error('%s: AttributeError received' % self.getName() )
                break
            except TypeError:
                logging.error('%s: TypeError received' % self.getName() )

        logging.info( '%s: Exiting ConsumerThread.run()' % self.getName() )

    def shutdown(self):
        """ Gracefully close the connection """

        if self.running:
            logging.debug( 'Shutting down consumer thread "%s"' % self.getName() )
            self.running = False
            return False

        """
        This hangs because channel.wait in the thread is blocking on socket.recv.
        channel.close sends the close message, then enters ultimately into
        socket.recv to get the close_ok response.  Depending on the timing,
        the channel.wait has picked up the close_ok after channel.close (on main
        thread) entered socket.recv.

        I was looking at a nonblocking method to deal with this properly:
        http://www.lshift.net/blog/2009/02/18/evserver-part2-rabbit-and-comet
        """
	# close msssql connection
	if self.mssql_conn != None and self.mssql_conn.connected == True:
		self.mssql_conn.close()

        #self.channel.close()
        if self.connection:
            try:
                logging.debug('%s: Closing the AMQP connection' % self.getName())
                self.connection.close()
                logging.debug('%s: AMQP connection closed' % self.getName())
            except IOError, e:
                # We're already closed
                logging.debug('%s: Error closing the AMQP connection.' % self.getName())
            except TypeError, e:
                # Bug
                logging.debug('%s: Error closing the AMQP connection.' % self.getName())

        logging.debug('%s: Shutting down processor' % self.getName())
        try:
            self.processor.shutdown()
        except AttributeError:
            logging.debug('%s: Processor does not have a shutdown method' % self.getName())

        return True

    def unlock( self ):
        """ Unlock the thread so MCP can shut us down """

        self.locked = False

class MasterControlProgram:
    """ Master Control Program keeps track of threads and threading needs """

    def __init__(self, config, options):

        logging.debug( 'MCP: Master Control Program Created' )

        # If we have monitoring enabled for elasic resizing
        if config['Monitor']['enabled']:
            #TODO: Make this more generic. Just import whatever the user puts here dynamically.
            #TODO: Replace 'alice' with 'monitor' or something throughout.
            if config['Monitor']['module'] == 'Rabbit':
                from rejected.monitors import Rabbit
                self.alice = Rabbit()
            else:
                from rejected.monitors import Alice
                self.alice = Alice()
        else:
            self.alice = None

        self.bindings = []
        self.config = config
        self.last_poll = None
        self.shutdown_pending = False
        self.thread_stats = {}

    def get_information(self):
        """ Return the stats data collected from Poll """

        pass

    def poll(self):
        """ Check the Alice daemon for queue depths for each binding """
        global mcp_poll_delay

        logging.debug( 'MCP: Master Control Program Polling' )

        # Cache the monitor queue depth checks
        cache_lookup = {}

        # default total counts
        total_processed = 0
        total_throttled = 0

        # Get our delay since last poll
        if self.last_poll:
            duration_since_last_poll = time.time() - self.last_poll
        else:
            duration_since_last_poll = mcp_poll_delay

        # If we're shutting down, no need to do this, can make it take longer
        if self.shutdown_pending:
            return

        # Loop through each binding to ensure all our threads are running
        offset = 0
        for binding in self.bindings:

            # Go through the threads to check the queue depths for each server
            dead_threads = []
            for x in xrange(0, len(binding['threads'])):

                # Make sure the thread is still alive, otherwise remove it and move on
                if not binding['threads'][x].isAlive():
                    logging.error( 'MCP: Encountered a dead thread, removing.' )
                    dead_threads.append(x)

            # Remove dead threads
            for list_offset in dead_threads:
                logging.error( 'MCP: Removing the dead thread from the stack' )
                binding['threads'].pop(list_offset)

            # If we don't have any consumer threads, remove the binding
            if not len(binding['threads']):
                logging.error( 'MCP: We have no working consumers, removing down this binding.' )
                del self.bindings[offset]

            # Increment our list offset
            offset += 1

        # If we have removed all of our bindings because they had no working threads, shutdown
        if not len(self.bindings):
            logging.error( 'MCP: We have no working bindings, shutting down.' )
            shutdown()
            return

        # If we're monitoring, then run through here
        if self.alice:

            # Loop through each binding
            offset = 0
            for binding in self.bindings:

                # Go through the threads to check the queue depths for each server
                for thread in binding['threads']:

                    # Get our thread data such as the connection and queue it's using
                    info = thread.get_information()

                    # Stats are keyed on thread name
                    thread_name = thread.getName()

                    # Check our stats info
                    if thread_name in self.thread_stats:

                        # Calculate our processed & throttled amount
                        processed = info['processed'] - self.thread_stats[thread_name]['processed']
                        throttled = info['throttle_count'] - self.thread_stats[thread_name]['throttle_count']

                        # Totals for MCP Stats
                        total_processed += processed
                        total_throttled += throttled

                        logging.debug( '%s processed %i messages and throttled %i messages in %.2f seconds at a rate of %.2f mps.' %
                            ( thread_name,
                              processed,
                              throttled,
                              duration_since_last_poll,
                              ( float(processed) / duration_since_last_poll ) ) )
                    else:
                        # Initialize our thread stats dictionary
                        self.thread_stats[thread_name] = {}

                        # Totals for MCP Stats
                        total_processed += info['processed']
                        total_throttled += info['throttle_count']

                    # Set our thread processed # count for next time
                    self.thread_stats[thread_name]['processed'] = info['processed']
                    self.thread_stats[thread_name]['throttle_count'] = info['throttle_count']

                    # Check the queue depth for the connection and queue
                    cache_name = '%s-%s' % ( info['connection'], info['queue'] )
                    if cache_name in cache_lookup:
                        data = cache_lookup[cache_name]
                    else:
                        # Get the value from Alice
                        data = self.alice.get_queue_depth(info['connection'], info['monitor_port'], info['queue'])
                        cache_lookup[cache_name] = data

                    # Easier to work with variables
                    queue_depth = int(data['depth'])
                    min_threads = self.config['Bindings'][info['binding']]['consumers']['min']
                    max_threads = self.config['Bindings'][info['binding']]['consumers']['max']
                    threshold = self.config['Bindings'][info['binding']]['consumers']['threshold']

                    # If our queue depth exceeds the threshold and we haven't maxed out make a new worker
                    if queue_depth > threshold and len(binding['threads']) < max_threads:

                        logging.info( 'MCP: Spawning worker thread for connection "%s" binding "%s": %i messages pending, %i threshold, %i min, %i max, %i consumers active.' %
                                        ( info['connection'],
                                          info['binding'],
                                          queue_depth,
                                          threshold,
                                          min_threads,
                                          max_threads,
                                          len(binding['threads']) ) )

                        # Create the new thread making it use self.consume
                        new_thread = ConsumerThread( self.config,
                                                     info['binding'],
                                                     info['connection'] )

                        # Add to our dictionary of active threads
                        binding['threads'].append(new_thread)

                        # Start the thread
                        new_thread.start()

                        # We only want 1 new thread per poll as to not overwhelm the consumer system
                        break

                # Check if our queue depth is below our threshold and we have more than the min amount
                if queue_depth < threshold and len(binding['threads']) > min_threads:

                    logging.info( 'MCP: Removing worker thread for connection "%s" binding "%s": %i messages pending, %i threshold, %i min, %i max, %i threads active.' %
                                    ( info['connection'],
                                      info['binding'],
                                      queue_depth,
                                      threshold,
                                      min_threads,
                                      max_threads,
                                      len(binding['threads']) ) )

                    # Remove a thread
                    thread =  binding['threads'].pop()

                    while thread.is_locked():
                        logging.debug( 'MCP: Waiting on %s to unlock so we can shut it down' % thread.getName() )
                        time.sleep(1)

                    # Shutdown the thread gracefully
                    thread.shutdown()

                    # We only want to remove one thread per poll
                    break;

                logging.info('MCP: Binding #%i processed %i total messages in %.2f seconds at a rate of %.2f mps.' %
                               ( offset,
                                 total_processed,
                                 duration_since_last_poll,
                                 ( float(total_processed) / duration_since_last_poll ) ) )

                if len(binding['threads']) > 1:
                    logging.info('MCP: Binding #%i has %i threads which throttled themselves %i times.' %
                              ( offset,
                                len(binding['threads']),
                                total_throttled ) )
                else:
                    logging.info('MCP: Binding #%i has 1 thread which throttled itself %i times.' %
                              ( offset, total_throttled ) )

                offset += 1

            # Get our last poll time
            self.last_poll = time.time()

    def shutdown(self):
        """ Graceful shutdown of the MCP means shutting down threads too """

        logging.debug( 'MCP: Master Control Program Shutting Down' )

        # Get the thread count
        threads = self.threadCount()

        # Keep track of the fact we're shutting down
        self.shutdown_pending = True

        # Loop as long as we have running threads
        while threads:

            # Loop through all of the bindings and try and shutdown their threads
            for binding in self.bindings:

                # Loop through all the threads in this binding
                for x in xrange(0, len(binding['threads'])):

                    # Let the thread know we want to shutdown
                    thread = binding['threads'].pop()
                    while not thread.shutdown():
                        logging.debug('MCP: Waiting on %s to shutdown properly' % thread.getName())
                        time.sleep(1)

            # Get our updated thread count and only sleep then loop if it's > 0,
            threads = self.threadCount()

            # If we have any threads left, sleep for a second before trying again
            if threads:
                logging.debug( 'MCP: Waiting on %i threads to cleanly shutdown.' % threads )
                time.sleep(1)

    def start(self):
        """ Initialize all of the consumer threads when the MCP comes to life """
        logging.debug( 'MCP: Master Control Program Starting Up' )

        # Loop through all of the bindings
        for binding_name in self.config['Bindings']:

            # Create the dictionary values for this binding
            binding = { 'name': binding_name }
            binding['queue'] = self.config['Bindings'][binding_name]['queue']
            binding['threads'] = []

            # For each connection, kick off the min consumers and start consuming
            for connect_name in self.config['Bindings'][binding_name]['connections']:
                for i in xrange( 0, self.config['Bindings'][binding_name]['consumers']['min'] ):
                    logging.debug( 'MCP: Creating worker thread #%i for connection "%s" binding "%s"' % ( i, connect_name, binding_name ) )

                    # Create the new thread making it use self.consume
                    thread = ConsumerThread( self.config,
                                             binding_name,
                                             connect_name );

                    # Start the thread
                    thread.start()

                    # Check to see if the thread is alive before adding it to our stack
                    if thread.isAlive():

                        # Add to our dictionary of active threads
                        binding['threads'].append(thread)

            # Append this binding to our binding stack
            self.bindings.append(binding)

    def threadCount(self):
        """ Return the total number of working threads managed by the MCP """

        count = 0
        for binding in self.bindings:
            count += len(binding['threads'])
        return count

def shutdown(signum = 0, frame = None):
    """ Application Wide Graceful Shutdown """
    global mcp, process
    is_quitting = True

    #remove pid
    try:
        os.remove(pidfile)
    except:
        log.warning("pidfile already deleted")

    logging.info( 'Graceful shutdown of rejected.py running "%s" initiated.' % process )
    mcp.shutdown()
    logging.debug( 'Graceful shutdown of rejected.py running "%s" complete' % process )
    #os._exit(signum)
    sys.exit()

def main():
    """ Main Application Handler """
    global mcp, mcp_poll_delay, process

    usage = "usage: %prog [options]"
    version_string = "%%prog %s" % __version__
    description = "rejected.py consumer daemon"

	# write pidfile
    pid = str(os.getpid())
    file(pidfile,'w+').write("%s\n" % pid)
    #atexit.register(delpid)

    # Create our parser and setup our command line options
    parser = optparse.OptionParser(usage=usage,
                         version=version_string,
                         description=description)

    parser.add_option("-c", "--config",
                        action="store", type="string", default="rejected.yaml",
                        help="Specify the configuration file to load.")

    parser.add_option("-b", "--binding",
                        action="store", dest="binding",
                        help="Binding name to use to when used in conjunction \
                        with the broker and single settings. All other \
                        configuration data will be derived from the\
                        combination of the broker and queue settings.")

    parser.add_option("-C", "--connection",
                        action="store", dest="connection",
                        help="Specify the broker connection name as defined in the \
                        configuration file. Used in conjunction with the \
                        single and binding command line options. All other \
                        configuration data such as the user credentials and \
                        exchange will be derived from the configuration file.")

    parser.add_option("-d", "--detached",
                        action="store_true", dest="detached", default=False,
                        help="Run in daemon mode")

    parser.add_option("-m", "--monitor",
                        action="store_true", dest="monitor",
                        default=False,
                        help="Poll Alice for scaling consumer threads.")

    parser.add_option("-s", "--single",
                        action="store_true", dest="single_thread",
                        default=False,
                        help="Only runs with one thread worker, requires setting \
                        the broker and queue to subscribe to.    All other \
                        configuration data will be derived from the \
                        configuration settings matching the broker and queue.")

    parser.add_option("-v", "--verbose",
                        action="store_true", dest="verbose", default=False,
                        help="use debug to stdout instead of logging settings")

    # Parse our options and arguments
    options, args = parser.parse_args()

    # Get the config file only for logging options
    parts = options.config.split('/')
    process = parts[len(parts) - 1]
    parts = process.split('.')
    process = parts[0]

    # Load the Configuration file
    try:
            stream = file(options.config, 'r')
            config = yaml.load(stream)
            stream.close()

    except IOError:
            print "\nError: Invalid or missing configuration file \"%s\"\n" % options.config
            sys.exit(1)

    # Set logging levels dictionary
    logging_levels = {
                        'debug':    logging.DEBUG,
                        'info':     logging.INFO,
                        'warning':  logging.WARNING,
                        'error':    logging.ERROR,
                        'critical': logging.CRITICAL
                     }

    # Get the logging value from the dictionary
    logging_level = config['Logging']['level']
    config['Logging']['level'] = logging_levels.get( config['Logging']['level'],
                                                     logging.NOTSET )

    # If the user says verbose overwrite the settings.
    if options.verbose:

        # Set the debugging level to verbose
        config['Logging']['level'] = logging.DEBUG

        # If we have specified a file, remove it so logging info goes to stdout
        if config['Logging'].has_key('filename'):
            del config['Logging']['filename']

    else:
        # Build a specific path to our log file
        if config['Logging'].has_key('filename'):
            config['Logging']['filename'] = os.path.join( os.path.dirname(__file__),
                                                          config['Logging']['directory'],
                                                          config['Logging']['filename'] )

    #cache PATLive unified log events in dict
    #conn = _mssql.connect(server='DSDEV', user='r_dpublic', password='1472', database='DB_LOG')

    #conn.execute_query('sp_List_LOG_EVENT')
    #for row in conn:
    #    config["LogEvents"][row['c_name']] = row['pk_log_event']
    #    print "pk=%d, event=%s" % (row['pk_log_event'], row['c_name'])

    # Pass in our logging config
    logging.basicConfig(**config['Logging'])
    logging.info('Log level set to %s' % logging_level)

    # If we have supported handler
    if config['Logging'].has_key('handler'):

        # If we want to syslog
        if config['Logging']['handler'] == 'syslog':

            from logging.handlers import SysLogHandler

            # Create the syslog handler
            logging_handler = SysLogHandler( address='/dev/log', facility = SysLogHandler.LOG_LOCAL6 )

            # Add the handler
            logger = logging.getLogger()
            logger.addHandler(logging_handler)
            logger.debug('Sending message')

    # Make sure if we specified single thread that we specified connection and binding
    if options.single_thread == True:
        if not options.connection or not options.binding:
            print "\nError: Specify the connection and binding when using single threaded.\n"
            parser.print_help()
            sys.exit(1)

    # If our config has monitoring disabled but we enable via cli, enable it
    if options.monitor and not config['Monitor']['enabled']:
        config['Monitor']['enabled'] = True

    # Fork our process to detach if not told to stay in foreground
    if options.detached:
        try:
            pid = os.fork()
            if pid > 0:
                logging.info('Parent process ending.')
                sys.exit(0)
        except OSError, e:
            sys.stderr.write("Could not fork: %d (%s)\n" % (e.errno, e.strerror))
            sys.exit(1)

        # Second fork to put into daemon mode
        try:
            pid = os.fork()
            if pid > 0:
                # exit from second parent, print eventual PID before
                print 'rejected.py daemon has started - PID # %d.' % pid
                logging.info('Child forked as PID # %d' % pid)
                sys.exit(0)
        except OSError, e:
            sys.stderr.write("Could not fork: %d (%s)\n" % (e.errno, e.strerror))
            sys.exit(1)

        # Let the debugging person know we've forked
        logging.debug( 'rejected.py has forked into the background.' )

        # Detach from parent environment
        os.chdir( os.path.dirname(__file__) )
        os.setsid()
        os.umask(0)

        # Close stdin
        sys.stdin.close()

        # Redirect stdout, stderr
        sys.stdout = open(os.path.join(os.path.dirname(__file__),
                          config['Logging']['directory'], "stdout.log"), 'w')
        sys.stderr = open(os.path.join(os.path.dirname(__file__),
                          config['Logging']['directory'], "stderr.log"), 'w')

    # Set our signal handler so we can gracefully shutdown
    signal.signal(signal.SIGTERM, shutdown)

    # Start the Master Control Program ;-)
    mcp = MasterControlProgram(config, options)

    # Kick off our core connections
    mcp.start()

    # Loop until someone wants us to stop
    do_poll = config['Monitor']['enabled'] and not options.single_thread

    # Override the poll delay if set
    if do_poll:
        if config['Monitor'].has_key('interval'):
            mcp_poll_delay = config['Monitor']['interval']
            logging.debug('rejected.py: Set mcp_poll_delay to %i seconds.' % mcp_poll_delay)

    while 1:

        # Have the Master Control Process poll
        try:
            # Check to see if we need to adjust our threads
            if do_poll:
                mcp.poll()
                logging.debug('rejected.py:Thread Count: %i' % threading.active_count())

            # Sleep is so much more CPU friendly than pass
            time.sleep(mcp_poll_delay)

        except (KeyboardInterrupt, SystemExit):
            # The user has sent a kill or ctrl-c
            shutdown()

# Only execute the code if invoked as an application
if __name__ == '__main__':

    # Get our sub-path going for processor imports
    sys.path.insert(0, 'processors')

    # Run the main function
    main()


text:
package quickfix.fix50.component;
import quickfix.FieldNotFound;

public class InstrumentLeg extends quickfix.MessageComponent
{

  static final long serialVersionUID = 20050617;
  public static final String MSGTYPE = "";

  private int[] componentFields = { 600, 601, 602, 603, 604, 607, 608, 609, 764, 610, 611, 248, 249, 250, 251, 252, 253, 257, 599, 596, 597, 598, 254, 612, 942, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 556, 740, 739, 955, 956, 999, 1001,  };
  protected int[] getFields() { return componentFields; }
  private int[] componentGroups = {  };
  protected int[] getGroupFields() { return componentGroups; }

  public InstrumentLeg()
  {
    super();
  }

  public void set(quickfix.field.LegSymbol value)
  {
    setField(value);
  }

  public quickfix.field.LegSymbol get(quickfix.field.LegSymbol  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegSymbol getLegSymbol() throws FieldNotFound
  {
    quickfix.field.LegSymbol value = new quickfix.field.LegSymbol();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegSymbol field)
  {
    return isSetField(field);
  }

  public boolean isSetLegSymbol()
  {
    return isSetField(600);
  }

  public void set(quickfix.field.LegSymbolSfx value)
  {
    setField(value);
  }

  public quickfix.field.LegSymbolSfx get(quickfix.field.LegSymbolSfx  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegSymbolSfx getLegSymbolSfx() throws FieldNotFound
  {
    quickfix.field.LegSymbolSfx value = new quickfix.field.LegSymbolSfx();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegSymbolSfx field)
  {
    return isSetField(field);
  }

  public boolean isSetLegSymbolSfx()
  {
    return isSetField(601);
  }

  public void set(quickfix.field.LegSecurityID value)
  {
    setField(value);
  }

  public quickfix.field.LegSecurityID get(quickfix.field.LegSecurityID  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegSecurityID getLegSecurityID() throws FieldNotFound
  {
    quickfix.field.LegSecurityID value = new quickfix.field.LegSecurityID();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegSecurityID field)
  {
    return isSetField(field);
  }

  public boolean isSetLegSecurityID()
  {
    return isSetField(602);
  }

  public void set(quickfix.field.LegSecurityIDSource value)
  {
    setField(value);
  }

  public quickfix.field.LegSecurityIDSource get(quickfix.field.LegSecurityIDSource  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegSecurityIDSource getLegSecurityIDSource() throws FieldNotFound
  {
    quickfix.field.LegSecurityIDSource value = new quickfix.field.LegSecurityIDSource();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegSecurityIDSource field)
  {
    return isSetField(field);
  }

  public boolean isSetLegSecurityIDSource()
  {
    return isSetField(603);
  }

  public void set(quickfix.fix50.component.LegSecAltIDGrp component)
  {
    setComponent(component);
  }

  public quickfix.fix50.component.LegSecAltIDGrp get(quickfix.fix50.component.LegSecAltIDGrp  component) throws FieldNotFound
  {
    getComponent(component);
    return component;
  }

  public quickfix.fix50.component.LegSecAltIDGrp getLegSecAltIDGrp() throws FieldNotFound
  {
    quickfix.fix50.component.LegSecAltIDGrp component = new quickfix.fix50.component.LegSecAltIDGrp();
    getComponent(component);
    return component;
  }

  public void set(quickfix.field.NoLegSecurityAltID value)
  {
    setField(value);
  }

  public quickfix.field.NoLegSecurityAltID get(quickfix.field.NoLegSecurityAltID  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.NoLegSecurityAltID getNoLegSecurityAltID() throws FieldNotFound
  {
    quickfix.field.NoLegSecurityAltID value = new quickfix.field.NoLegSecurityAltID();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.NoLegSecurityAltID field)
  {
    return isSetField(field);
  }

  public boolean isSetNoLegSecurityAltID()
  {
    return isSetField(604);
  }

  public void set(quickfix.field.LegProduct value)
  {
    setField(value);
  }

  public quickfix.field.LegProduct get(quickfix.field.LegProduct  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegProduct getLegProduct() throws FieldNotFound
  {
    quickfix.field.LegProduct value = new quickfix.field.LegProduct();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegProduct field)
  {
    return isSetField(field);
  }

  public boolean isSetLegProduct()
  {
    return isSetField(607);
  }

  public void set(quickfix.field.LegCFICode value)
  {
    setField(value);
  }

  public quickfix.field.LegCFICode get(quickfix.field.LegCFICode  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegCFICode getLegCFICode() throws FieldNotFound
  {
    quickfix.field.LegCFICode value = new quickfix.field.LegCFICode();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegCFICode field)
  {
    return isSetField(field);
  }

  public boolean isSetLegCFICode()
  {
    return isSetField(608);
  }

  public void set(quickfix.field.LegSecurityType value)
  {
    setField(value);
  }

  public quickfix.field.LegSecurityType get(quickfix.field.LegSecurityType  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegSecurityType getLegSecurityType() throws FieldNotFound
  {
    quickfix.field.LegSecurityType value = new quickfix.field.LegSecurityType();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegSecurityType field)
  {
    return isSetField(field);
  }

  public boolean isSetLegSecurityType()
  {
    return isSetField(609);
  }

  public void set(quickfix.field.LegSecuritySubType value)
  {
    setField(value);
  }

  public quickfix.field.LegSecuritySubType get(quickfix.field.LegSecuritySubType  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegSecuritySubType getLegSecuritySubType() throws FieldNotFound
  {
    quickfix.field.LegSecuritySubType value = new quickfix.field.LegSecuritySubType();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegSecuritySubType field)
  {
    return isSetField(field);
  }

  public boolean isSetLegSecuritySubType()
  {
    return isSetField(764);
  }

  public void set(quickfix.field.LegMaturityMonthYear value)
  {
    setField(value);
  }

  public quickfix.field.LegMaturityMonthYear get(quickfix.field.LegMaturityMonthYear  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegMaturityMonthYear getLegMaturityMonthYear() throws FieldNotFound
  {
    quickfix.field.LegMaturityMonthYear value = new quickfix.field.LegMaturityMonthYear();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegMaturityMonthYear field)
  {
    return isSetField(field);
  }

  public boolean isSetLegMaturityMonthYear()
  {
    return isSetField(610);
  }

  public void set(quickfix.field.LegMaturityDate value)
  {
    setField(value);
  }

  public quickfix.field.LegMaturityDate get(quickfix.field.LegMaturityDate  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegMaturityDate getLegMaturityDate() throws FieldNotFound
  {
    quickfix.field.LegMaturityDate value = new quickfix.field.LegMaturityDate();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegMaturityDate field)
  {
    return isSetField(field);
  }

  public boolean isSetLegMaturityDate()
  {
    return isSetField(611);
  }

  public void set(quickfix.field.LegCouponPaymentDate value)
  {
    setField(value);
  }

  public quickfix.field.LegCouponPaymentDate get(quickfix.field.LegCouponPaymentDate  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegCouponPaymentDate getLegCouponPaymentDate() throws FieldNotFound
  {
    quickfix.field.LegCouponPaymentDate value = new quickfix.field.LegCouponPaymentDate();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegCouponPaymentDate field)
  {
    return isSetField(field);
  }

  public boolean isSetLegCouponPaymentDate()
  {
    return isSetField(248);
  }

  public void set(quickfix.field.LegIssueDate value)
  {
    setField(value);
  }

  public quickfix.field.LegIssueDate get(quickfix.field.LegIssueDate  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegIssueDate getLegIssueDate() throws FieldNotFound
  {
    quickfix.field.LegIssueDate value = new quickfix.field.LegIssueDate();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegIssueDate field)
  {
    return isSetField(field);
  }

  public boolean isSetLegIssueDate()
  {
    return isSetField(249);
  }

  public void set(quickfix.field.LegRepoCollateralSecurityType value)
  {
    setField(value);
  }

  public quickfix.field.LegRepoCollateralSecurityType get(quickfix.field.LegRepoCollateralSecurityType  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegRepoCollateralSecurityType getLegRepoCollateralSecurityType() throws FieldNotFound
  {
    quickfix.field.LegRepoCollateralSecurityType value = new quickfix.field.LegRepoCollateralSecurityType();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegRepoCollateralSecurityType field)
  {
    return isSetField(field);
  }

  public boolean isSetLegRepoCollateralSecurityType()
  {
    return isSetField(250);
  }

  public void set(quickfix.field.LegRepurchaseTerm value)
  {
    setField(value);
  }

  public quickfix.field.LegRepurchaseTerm get(quickfix.field.LegRepurchaseTerm  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegRepurchaseTerm getLegRepurchaseTerm() throws FieldNotFound
  {
    quickfix.field.LegRepurchaseTerm value = new quickfix.field.LegRepurchaseTerm();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegRepurchaseTerm field)
  {
    return isSetField(field);
  }

  public boolean isSetLegRepurchaseTerm()
  {
    return isSetField(251);
  }

  public void set(quickfix.field.LegRepurchaseRate value)
  {
    setField(value);
  }

  public quickfix.field.LegRepurchaseRate get(quickfix.field.LegRepurchaseRate  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegRepurchaseRate getLegRepurchaseRate() throws FieldNotFound
  {
    quickfix.field.LegRepurchaseRate value = new quickfix.field.LegRepurchaseRate();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegRepurchaseRate field)
  {
    return isSetField(field);
  }

  public boolean isSetLegRepurchaseRate()
  {
    return isSetField(252);
  }

  public void set(quickfix.field.LegFactor value)
  {
    setField(value);
  }

  public quickfix.field.LegFactor get(quickfix.field.LegFactor  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegFactor getLegFactor() throws FieldNotFound
  {
    quickfix.field.LegFactor value = new quickfix.field.LegFactor();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegFactor field)
  {
    return isSetField(field);
  }

  public boolean isSetLegFactor()
  {
    return isSetField(253);
  }

  public void set(quickfix.field.LegCreditRating value)
  {
    setField(value);
  }

  public quickfix.field.LegCreditRating get(quickfix.field.LegCreditRating  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegCreditRating getLegCreditRating() throws FieldNotFound
  {
    quickfix.field.LegCreditRating value = new quickfix.field.LegCreditRating();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegCreditRating field)
  {
    return isSetField(field);
  }

  public boolean isSetLegCreditRating()
  {
    return isSetField(257);
  }

  public void set(quickfix.field.LegInstrRegistry value)
  {
    setField(value);
  }

  public quickfix.field.LegInstrRegistry get(quickfix.field.LegInstrRegistry  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegInstrRegistry getLegInstrRegistry() throws FieldNotFound
  {
    quickfix.field.LegInstrRegistry value = new quickfix.field.LegInstrRegistry();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegInstrRegistry field)
  {
    return isSetField(field);
  }

  public boolean isSetLegInstrRegistry()
  {
    return isSetField(599);
  }

  public void set(quickfix.field.LegCountryOfIssue value)
  {
    setField(value);
  }

  public quickfix.field.LegCountryOfIssue get(quickfix.field.LegCountryOfIssue  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegCountryOfIssue getLegCountryOfIssue() throws FieldNotFound
  {
    quickfix.field.LegCountryOfIssue value = new quickfix.field.LegCountryOfIssue();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegCountryOfIssue field)
  {
    return isSetField(field);
  }

  public boolean isSetLegCountryOfIssue()
  {
    return isSetField(596);
  }

  public void set(quickfix.field.LegStateOrProvinceOfIssue value)
  {
    setField(value);
  }

  public quickfix.field.LegStateOrProvinceOfIssue get(quickfix.field.LegStateOrProvinceOfIssue  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegStateOrProvinceOfIssue getLegStateOrProvinceOfIssue() throws FieldNotFound
  {
    quickfix.field.LegStateOrProvinceOfIssue value = new quickfix.field.LegStateOrProvinceOfIssue();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegStateOrProvinceOfIssue field)
  {
    return isSetField(field);
  }

  public boolean isSetLegStateOrProvinceOfIssue()
  {
    return isSetField(597);
  }

  public void set(quickfix.field.LegLocaleOfIssue value)
  {
    setField(value);
  }

  public quickfix.field.LegLocaleOfIssue get(quickfix.field.LegLocaleOfIssue  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegLocaleOfIssue getLegLocaleOfIssue() throws FieldNotFound
  {
    quickfix.field.LegLocaleOfIssue value = new quickfix.field.LegLocaleOfIssue();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegLocaleOfIssue field)
  {
    return isSetField(field);
  }

  public boolean isSetLegLocaleOfIssue()
  {
    return isSetField(598);
  }

  public void set(quickfix.field.LegRedemptionDate value)
  {
    setField(value);
  }

  public quickfix.field.LegRedemptionDate get(quickfix.field.LegRedemptionDate  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegRedemptionDate getLegRedemptionDate() throws FieldNotFound
  {
    quickfix.field.LegRedemptionDate value = new quickfix.field.LegRedemptionDate();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegRedemptionDate field)
  {
    return isSetField(field);
  }

  public boolean isSetLegRedemptionDate()
  {
    return isSetField(254);
  }

  public void set(quickfix.field.LegStrikePrice value)
  {
    setField(value);
  }

  public quickfix.field.LegStrikePrice get(quickfix.field.LegStrikePrice  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegStrikePrice getLegStrikePrice() throws FieldNotFound
  {
    quickfix.field.LegStrikePrice value = new quickfix.field.LegStrikePrice();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegStrikePrice field)
  {
    return isSetField(field);
  }

  public boolean isSetLegStrikePrice()
  {
    return isSetField(612);
  }

  public void set(quickfix.field.LegStrikeCurrency value)
  {
    setField(value);
  }

  public quickfix.field.LegStrikeCurrency get(quickfix.field.LegStrikeCurrency  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegStrikeCurrency getLegStrikeCurrency() throws FieldNotFound
  {
    quickfix.field.LegStrikeCurrency value = new quickfix.field.LegStrikeCurrency();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegStrikeCurrency field)
  {
    return isSetField(field);
  }

  public boolean isSetLegStrikeCurrency()
  {
    return isSetField(942);
  }

  public void set(quickfix.field.LegOptAttribute value)
  {
    setField(value);
  }

  public quickfix.field.LegOptAttribute get(quickfix.field.LegOptAttribute  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegOptAttribute getLegOptAttribute() throws FieldNotFound
  {
    quickfix.field.LegOptAttribute value = new quickfix.field.LegOptAttribute();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegOptAttribute field)
  {
    return isSetField(field);
  }

  public boolean isSetLegOptAttribute()
  {
    return isSetField(613);
  }

  public void set(quickfix.field.LegContractMultiplier value)
  {
    setField(value);
  }

  public quickfix.field.LegContractMultiplier get(quickfix.field.LegContractMultiplier  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegContractMultiplier getLegContractMultiplier() throws FieldNotFound
  {
    quickfix.field.LegContractMultiplier value = new quickfix.field.LegContractMultiplier();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegContractMultiplier field)
  {
    return isSetField(field);
  }

  public boolean isSetLegContractMultiplier()
  {
    return isSetField(614);
  }

  public void set(quickfix.field.LegCouponRate value)
  {
    setField(value);
  }

  public quickfix.field.LegCouponRate get(quickfix.field.LegCouponRate  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegCouponRate getLegCouponRate() throws FieldNotFound
  {
    quickfix.field.LegCouponRate value = new quickfix.field.LegCouponRate();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegCouponRate field)
  {
    return isSetField(field);
  }

  public boolean isSetLegCouponRate()
  {
    return isSetField(615);
  }

  public void set(quickfix.field.LegSecurityExchange value)
  {
    setField(value);
  }

  public quickfix.field.LegSecurityExchange get(quickfix.field.LegSecurityExchange  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegSecurityExchange getLegSecurityExchange() throws FieldNotFound
  {
    quickfix.field.LegSecurityExchange value = new quickfix.field.LegSecurityExchange();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegSecurityExchange field)
  {
    return isSetField(field);
  }

  public boolean isSetLegSecurityExchange()
  {
    return isSetField(616);
  }

  public void set(quickfix.field.LegIssuer value)
  {
    setField(value);
  }

  public quickfix.field.LegIssuer get(quickfix.field.LegIssuer  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegIssuer getLegIssuer() throws FieldNotFound
  {
    quickfix.field.LegIssuer value = new quickfix.field.LegIssuer();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegIssuer field)
  {
    return isSetField(field);
  }

  public boolean isSetLegIssuer()
  {
    return isSetField(617);
  }

  public void set(quickfix.field.EncodedLegIssuerLen value)
  {
    setField(value);
  }

  public quickfix.field.EncodedLegIssuerLen get(quickfix.field.EncodedLegIssuerLen  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.EncodedLegIssuerLen getEncodedLegIssuerLen() throws FieldNotFound
  {
    quickfix.field.EncodedLegIssuerLen value = new quickfix.field.EncodedLegIssuerLen();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.EncodedLegIssuerLen field)
  {
    return isSetField(field);
  }

  public boolean isSetEncodedLegIssuerLen()
  {
    return isSetField(618);
  }

  public void set(quickfix.field.EncodedLegIssuer value)
  {
    setField(value);
  }

  public quickfix.field.EncodedLegIssuer get(quickfix.field.EncodedLegIssuer  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.EncodedLegIssuer getEncodedLegIssuer() throws FieldNotFound
  {
    quickfix.field.EncodedLegIssuer value = new quickfix.field.EncodedLegIssuer();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.EncodedLegIssuer field)
  {
    return isSetField(field);
  }

  public boolean isSetEncodedLegIssuer()
  {
    return isSetField(619);
  }

  public void set(quickfix.field.LegSecurityDesc value)
  {
    setField(value);
  }

  public quickfix.field.LegSecurityDesc get(quickfix.field.LegSecurityDesc  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegSecurityDesc getLegSecurityDesc() throws FieldNotFound
  {
    quickfix.field.LegSecurityDesc value = new quickfix.field.LegSecurityDesc();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegSecurityDesc field)
  {
    return isSetField(field);
  }

  public boolean isSetLegSecurityDesc()
  {
    return isSetField(620);
  }

  public void set(quickfix.field.EncodedLegSecurityDescLen value)
  {
    setField(value);
  }

  public quickfix.field.EncodedLegSecurityDescLen get(quickfix.field.EncodedLegSecurityDescLen  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.EncodedLegSecurityDescLen getEncodedLegSecurityDescLen() throws FieldNotFound
  {
    quickfix.field.EncodedLegSecurityDescLen value = new quickfix.field.EncodedLegSecurityDescLen();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.EncodedLegSecurityDescLen field)
  {
    return isSetField(field);
  }

  public boolean isSetEncodedLegSecurityDescLen()
  {
    return isSetField(621);
  }

  public void set(quickfix.field.EncodedLegSecurityDesc value)
  {
    setField(value);
  }

  public quickfix.field.EncodedLegSecurityDesc get(quickfix.field.EncodedLegSecurityDesc  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.EncodedLegSecurityDesc getEncodedLegSecurityDesc() throws FieldNotFound
  {
    quickfix.field.EncodedLegSecurityDesc value = new quickfix.field.EncodedLegSecurityDesc();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.EncodedLegSecurityDesc field)
  {
    return isSetField(field);
  }

  public boolean isSetEncodedLegSecurityDesc()
  {
    return isSetField(622);
  }

  public void set(quickfix.field.LegRatioQty value)
  {
    setField(value);
  }

  public quickfix.field.LegRatioQty get(quickfix.field.LegRatioQty  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegRatioQty getLegRatioQty() throws FieldNotFound
  {
    quickfix.field.LegRatioQty value = new quickfix.field.LegRatioQty();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegRatioQty field)
  {
    return isSetField(field);
  }

  public boolean isSetLegRatioQty()
  {
    return isSetField(623);
  }

  public void set(quickfix.field.LegSide value)
  {
    setField(value);
  }

  public quickfix.field.LegSide get(quickfix.field.LegSide  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegSide getLegSide() throws FieldNotFound
  {
    quickfix.field.LegSide value = new quickfix.field.LegSide();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegSide field)
  {
    return isSetField(field);
  }

  public boolean isSetLegSide()
  {
    return isSetField(624);
  }

  public void set(quickfix.field.LegCurrency value)
  {
    setField(value);
  }

  public quickfix.field.LegCurrency get(quickfix.field.LegCurrency  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegCurrency getLegCurrency() throws FieldNotFound
  {
    quickfix.field.LegCurrency value = new quickfix.field.LegCurrency();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegCurrency field)
  {
    return isSetField(field);
  }

  public boolean isSetLegCurrency()
  {
    return isSetField(556);
  }

  public void set(quickfix.field.LegPool value)
  {
    setField(value);
  }

  public quickfix.field.LegPool get(quickfix.field.LegPool  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegPool getLegPool() throws FieldNotFound
  {
    quickfix.field.LegPool value = new quickfix.field.LegPool();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegPool field)
  {
    return isSetField(field);
  }

  public boolean isSetLegPool()
  {
    return isSetField(740);
  }

  public void set(quickfix.field.LegDatedDate value)
  {
    setField(value);
  }

  public quickfix.field.LegDatedDate get(quickfix.field.LegDatedDate  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegDatedDate getLegDatedDate() throws FieldNotFound
  {
    quickfix.field.LegDatedDate value = new quickfix.field.LegDatedDate();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegDatedDate field)
  {
    return isSetField(field);
  }

  public boolean isSetLegDatedDate()
  {
    return isSetField(739);
  }

  public void set(quickfix.field.LegContractSettlMonth value)
  {
    setField(value);
  }

  public quickfix.field.LegContractSettlMonth get(quickfix.field.LegContractSettlMonth  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegContractSettlMonth getLegContractSettlMonth() throws FieldNotFound
  {
    quickfix.field.LegContractSettlMonth value = new quickfix.field.LegContractSettlMonth();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegContractSettlMonth field)
  {
    return isSetField(field);
  }

  public boolean isSetLegContractSettlMonth()
  {
    return isSetField(955);
  }

  public void set(quickfix.field.LegInterestAccrualDate value)
  {
    setField(value);
  }

  public quickfix.field.LegInterestAccrualDate get(quickfix.field.LegInterestAccrualDate  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegInterestAccrualDate getLegInterestAccrualDate() throws FieldNotFound
  {
    quickfix.field.LegInterestAccrualDate value = new quickfix.field.LegInterestAccrualDate();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegInterestAccrualDate field)
  {
    return isSetField(field);
  }

  public boolean isSetLegInterestAccrualDate()
  {
    return isSetField(956);
  }

  public void set(quickfix.field.LegUnitofMeasure value)
  {
    setField(value);
  }

  public quickfix.field.LegUnitofMeasure get(quickfix.field.LegUnitofMeasure  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegUnitofMeasure getLegUnitofMeasure() throws FieldNotFound
  {
    quickfix.field.LegUnitofMeasure value = new quickfix.field.LegUnitofMeasure();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegUnitofMeasure field)
  {
    return isSetField(field);
  }

  public boolean isSetLegUnitofMeasure()
  {
    return isSetField(999);
  }

  public void set(quickfix.field.LegTimeUnit value)
  {
    setField(value);
  }

  public quickfix.field.LegTimeUnit get(quickfix.field.LegTimeUnit  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LegTimeUnit getLegTimeUnit() throws FieldNotFound
  {
    quickfix.field.LegTimeUnit value = new quickfix.field.LegTimeUnit();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LegTimeUnit field)
  {
    return isSetField(field);
  }

  public boolean isSetLegTimeUnit()
  {
    return isSetField(1001);
  }

}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\modules\admin\models\Anekdots */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'id_user')->textInput() ?>

    <?= $form->field($model, 'anekdot')->textarea(['rows' => 6]) ?>

    <?= $form->field($model, 'autor')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'date')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'utime')->textInput() ?>

    <?= $form->field($model, 'censor')->textInput() ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>