text:
// -----------------------------------------------------------------------
//  <copyright file="AuthorizationResult.cs" company="OSharp开源团队">
//      Copyright (c) 2014-2018 OSharp. All rights reserved.
//  </copyright>
//  <site>http://www.osharp.org</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2018-05-10 19:45</last-date>
// -----------------------------------------------------------------------

using System.Diagnostics;

using OSharp.Data;
using OSharp.Extensions;

namespace OSharp.Authorization
{
    /// <summary>
    /// 权限检查结果
    /// </summary>
    [DebuggerDisplay("{ResultType}-{Message}")]
    public sealed class AuthorizationResult : OsharpResult<AuthorizationStatus>
    {
        /// <summary>
        /// 初始化一个<see cref="AuthorizationResult"/>类型的新实例
        /// </summary>
        public AuthorizationResult(AuthorizationStatus status)
            : this(status, null)
        { }

        /// <summary>
        /// 初始化一个<see cref="AuthorizationResult"/>类型的新实例
        /// </summary>
        public AuthorizationResult(AuthorizationStatus status, string message)
            : this(status, message, null)
        { }

        /// <summary>
        /// 初始化一个<see cref="AuthorizationResult"/>类型的新实例
        /// </summary>
        public AuthorizationResult(AuthorizationStatus status, string message, object data)
            : base(status, message, data)
        { }

        /// <summary>
        /// 获取或设置 返回消息
        /// </summary>
        public override string Message
        {
            get { return _message ?? ResultType.ToDescription(); }
            set { _message = value; }
        }

        /// <summary>
        /// 获取 是否 <see cref="AuthorizationStatus.OK"/>
        /// </summary>
        public bool IsOk
        {
            get { return ResultType == AuthorizationStatus.OK; }
        }

        /// <summary>
        /// 获取 是否 <see cref="AuthorizationStatus.OK"/>
        /// </summary>
        public bool IsUnauthorized
        {
            get { return ResultType == AuthorizationStatus.Unauthorized; }
        }

        /// <summary>
        /// 获取 是否 <see cref="AuthorizationStatus.OK"/>
        /// </summary>
        public bool IsForbidden
        {
            get { return ResultType == AuthorizationStatus.Forbidden; }
        }

        /// <summary>
        /// 获取 是否 <see cref="AuthorizationStatus.OK"/>
        /// </summary>
        public bool IsNoFound
        {
            get { return ResultType == AuthorizationStatus.NoFound; }
        }

        /// <summary>
        /// 获取 是否 <see cref="AuthorizationStatus.OK"/>
        /// </summary>
        public bool IsLocked
        {
            get { return ResultType == AuthorizationStatus.Locked; }
        }

        /// <summary>
        /// 获取 是否 <see cref="AuthorizationStatus.OK"/>
        /// </summary>
        public bool IsError
        {
            get { return ResultType == AuthorizationStatus.Error; }
        }

        /// <summary>
        /// 获取 检查成功的结果
        /// </summary>
        public static AuthorizationResult OK { get; } = new AuthorizationResult(AuthorizationStatus.OK);
    }
}

redpajama_set_name: RedPajamaGithub


text:
/* jshint ignore:start */
if (typeof define !== 'function') { var define = require('amdefine')(module) }
/* jshint ignore:end */
define([], function () {
  function deg2rad(deg) {
    return deg * (Math.PI / 180);
  }

  var Geolocation = {
    getDistanceFromLatLon: function (latitude1, longitude1, latitude2, longitude2, metric) {
      var lat1 = parseFloat(latitude1, 10), lon1 = parseFloat(longitude1, 10), lat2 = parseFloat(latitude2, 10), lon2 = parseFloat(longitude2, 10);
      var R = 6371; // Radius of the earth in km
      var dLat = deg2rad(lat2 - lat1);
      var dLon = deg2rad(lon2 - lon1);
      var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
      var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      return R * c / (metric ? 1 : 1.609344);
    }
  };

  return Geolocation;
});


text:
namespace media {
namespace cast {

namespace {

void SaveOperationalStatus(OperationalStatus* out_status,
                           OperationalStatus in_status) {
  DVLOG(1) << "OperationalStatus transitioning from " << *out_status << " to "
           << in_status;
  *out_status = in_status;
}

class TransportClient : public CastTransport::Client {
 public:
  TransportClient() {}

  void OnStatusChanged(CastTransportStatus status) final {
    EXPECT_EQ(TRANSPORT_AUDIO_INITIALIZED, status);
  };
  void OnLoggingEventsReceived(
      std::unique_ptr<std::vector<FrameEvent>> frame_events,
      std::unique_ptr<std::vector<PacketEvent>> packet_events) final{};
  void ProcessRtpPacket(std::unique_ptr<Packet> packet) final{};

  DISALLOW_COPY_AND_ASSIGN(TransportClient);
};

}  // namespace

class TestPacketSender : public PacketTransport {
 public:
  TestPacketSender() : number_of_rtp_packets_(0), number_of_rtcp_packets_(0) {}

  bool SendPacket(PacketRef packet, const base::Closure& cb) final {
    if (IsRtcpPacket(&packet->data[0], packet->data.size())) {
      ++number_of_rtcp_packets_;
    } else {
      // Check that at least one RTCP packet was sent before the first RTP
      // packet.  This confirms that the receiver will have the necessary lip
      // sync info before it has to calculate the playout time of the first
      // frame.
      if (number_of_rtp_packets_ == 0)
        EXPECT_LE(1, number_of_rtcp_packets_);
      ++number_of_rtp_packets_;
    }
    return true;
  }

  int64_t GetBytesSent() final { return 0; }

  void StartReceiving(
      const PacketReceiverCallbackWithStatus& packet_receiver) final {}

  void StopReceiving() final {}

  int number_of_rtp_packets() const { return number_of_rtp_packets_; }

  int number_of_rtcp_packets() const { return number_of_rtcp_packets_; }

 private:
  int number_of_rtp_packets_;
  int number_of_rtcp_packets_;

  DISALLOW_COPY_AND_ASSIGN(TestPacketSender);
};

class AudioSenderTest : public ::testing::Test {
 protected:
  AudioSenderTest() {
    InitializeMediaLibrary();
    testing_clock_ = new base::SimpleTestTickClock();
    testing_clock_->Advance(base::TimeTicks::Now() - base::TimeTicks());
    task_runner_ = new FakeSingleThreadTaskRunner(testing_clock_);
    cast_environment_ =
        new CastEnvironment(std::unique_ptr<base::TickClock>(testing_clock_),
                            task_runner_, task_runner_, task_runner_);
    audio_config_.codec = CODEC_AUDIO_OPUS;
    audio_config_.use_external_encoder = false;
    audio_config_.frequency = kDefaultAudioSamplingRate;
    audio_config_.channels = 2;
    audio_config_.bitrate = kDefaultAudioEncoderBitrate;
    audio_config_.rtp_payload_type = 127;

    transport_ = new TestPacketSender();
    transport_sender_.reset(
        new CastTransportImpl(testing_clock_, base::TimeDelta(),
                              base::WrapUnique(new TransportClient()),
                              base::WrapUnique(transport_), task_runner_));
    OperationalStatus operational_status = STATUS_UNINITIALIZED;
    audio_sender_.reset(new AudioSender(
        cast_environment_,
        audio_config_,
        base::Bind(&SaveOperationalStatus, &operational_status),
        transport_sender_.get()));
    task_runner_->RunTasks();
    CHECK_EQ(STATUS_INITIALIZED, operational_status);
  }

  ~AudioSenderTest() override {}

  base::SimpleTestTickClock* testing_clock_;  // Owned by CastEnvironment.
  TestPacketSender* transport_;               // Owned by CastTransport.
  std::unique_ptr<CastTransportImpl> transport_sender_;
  scoped_refptr<FakeSingleThreadTaskRunner> task_runner_;
  std::unique_ptr<AudioSender> audio_sender_;
  scoped_refptr<CastEnvironment> cast_environment_;
  AudioSenderConfig audio_config_;
};

TEST_F(AudioSenderTest, Encode20ms) {
  const base::TimeDelta kDuration = base::TimeDelta::FromMilliseconds(20);
  std::unique_ptr<AudioBus> bus(
      TestAudioBusFactory(audio_config_.channels, audio_config_.frequency,
                          TestAudioBusFactory::kMiddleANoteFreq, 0.5f)
          .NextAudioBus(kDuration));

  audio_sender_->InsertAudio(std::move(bus), testing_clock_->NowTicks());
  task_runner_->RunTasks();
  EXPECT_LE(1, transport_->number_of_rtp_packets());
  EXPECT_LE(1, transport_->number_of_rtcp_packets());
}

TEST_F(AudioSenderTest, RtcpTimer) {
  const base::TimeDelta kDuration = base::TimeDelta::FromMilliseconds(20);
  std::unique_ptr<AudioBus> bus(
      TestAudioBusFactory(audio_config_.channels, audio_config_.frequency,
                          TestAudioBusFactory::kMiddleANoteFreq, 0.5f)
          .NextAudioBus(kDuration));

  audio_sender_->InsertAudio(std::move(bus), testing_clock_->NowTicks());
  task_runner_->RunTasks();

  // Make sure that we send at least one RTCP packet.
  base::TimeDelta max_rtcp_timeout =
      base::TimeDelta::FromMilliseconds(1 + kRtcpReportIntervalMs * 3 / 2);
  testing_clock_->Advance(max_rtcp_timeout);
  task_runner_->RunTasks();
  EXPECT_LE(1, transport_->number_of_rtp_packets());
  EXPECT_LE(1, transport_->number_of_rtcp_packets());
}

}  // namespace cast
}  // namespace media


text:
package com.roncoo.pay.common.core.enums;

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

/**
 * 支付类型枚举类
 * @company:广州领课网络科技有限公司(龙果学院 www.roncoo.com).
 * @author Peter
 */
public enum PayTypeEnum {

    SCANPAY("WEIXIN","扫码支付"),

    H5PAY("WEIXIN","H5支付"),

    DIRECT_PAY("ALIPAY","即时到账"),

    HUA_BEI_FEN_QI_PAY("ALIPAY","花呗分期"),

    MICRO_PAY("WEIXIN","刷卡支付"),

    WX_PROGRAM_PAY("WEIXIN","微信小程序"),

    F2F_PAY("ALIPAY","条码支付"),

	ALI_TEST("ALIPAY","支付宝测试");

	/** 所属支付方式 */
    private String way;
    public String getWay() {
		return way;
	}

	public void setWay(String way) {
		this.way = way;
	}

	/** 描述 */
    private String desc;

    private PayTypeEnum(String way,String desc) {
        this.desc = desc;
        this.way = way;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public static Map<String, Map<String, Object>> toMap() {
        PayTypeEnum[] ary = PayTypeEnum.values();
        Map<String, Map<String, Object>> enumMap = new HashMap<String, Map<String, Object>>();
        for (int num = 0; num < ary.length; num++) {
            Map<String, Object> map = new HashMap<String, Object>();
            String key = ary[num].name();
            map.put("desc", ary[num].getDesc());
            enumMap.put(key, map);
        }
        return enumMap;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static List toList() {
        PayTypeEnum[] ary = PayTypeEnum.values();
        List list = new ArrayList();
        for (int i = 0; i < ary.length; i++) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("desc", ary[i].getDesc());
            map.put("name", ary[i].name());
            list.add(map);
        }
        return list;
    }

    public static PayTypeEnum getEnum(String name) {
        PayTypeEnum[] arry = PayTypeEnum.values();
        for (int i = 0; i < arry.length; i++) {
            if (arry[i].name().equalsIgnoreCase(name)) {
                return arry[i];
            }
        }
        return null;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static List getWayList(String way) {
    	PayTypeEnum[] ary = PayTypeEnum.values();
        List list = new ArrayList();
        for (int i = 0; i < ary.length; i++) {
        	if(ary[i].way.equals(way)){
        		Map<String, String> map = new HashMap<String, String>();
                map.put("desc", ary[i].getDesc());
                map.put("name", ary[i].name());
                list.add(map);
        	}
        }
        return list;
    }

    /**
     * 取枚举的json字符串
     *
     * @return
     */
    public static String getJsonStr() {
        PayTypeEnum[] enums = PayTypeEnum.values();
        StringBuffer jsonStr = new StringBuffer("[");
        for (PayTypeEnum senum : enums) {
            if (!"[".equals(jsonStr.toString())) {
                jsonStr.append(",");
            }
            jsonStr.append("{id:'").append(senum).append("',desc:'").append(senum.getDesc()).append("'}");
        }
        jsonStr.append("]");
        return jsonStr.toString();
    }

}


text:
using System;
using Nop.Core.Domain.Customers;

namespace Nop.Core.Domain.Orders
{
    /// <summary>
    /// Represents a return request
    /// </summary>
    public partial class ReturnRequest : BaseEntity
    {
        /// <summary>
        /// Gets or sets the order product variant identifier
        /// </summary>
        public virtual int OrderProductVariantId { get; set; }

        /// <summary>
        /// Gets or sets the customer identifier
        /// </summary>
        public virtual int CustomerId { get; set; }

        /// <summary>
        /// Gets or sets the quantity
        /// </summary>
        public virtual int Quantity { get; set; }

        /// <summary>
        /// Gets or sets the reason to return
        /// </summary>
        public virtual string ReasonForReturn { get; set; }

        /// <summary>
        /// Gets or sets the requested action
        /// </summary>
        public virtual string RequestedAction { get; set; }

        /// <summary>
        /// Gets or sets the customer comments
        /// </summary>
        public virtual string CustomerComments { get; set; }

        /// <summary>
        /// Gets or sets the staff notes
        /// </summary>
        public virtual string StaffNotes { get; set; }

        /// <summary>
        /// Gets or sets the return status identifier
        /// </summary>
        public virtual int ReturnRequestStatusId { get; set; }

        /// <summary>
        /// Gets or sets the date and time of entity creation
        /// </summary>
        public virtual DateTime CreatedOnUtc { get; set; }

        /// <summary>
        /// Gets or sets the date and time of entity update
        /// </summary>
        public virtual DateTime UpdatedOnUtc { get; set; }

        /// <summary>
        /// Gets or sets the return status
        /// </summary>
        public virtual ReturnRequestStatus ReturnRequestStatus
        {
            get
            {
                return (ReturnRequestStatus)this.ReturnRequestStatusId;
            }
            set
            {
                this.ReturnRequestStatusId = (int)value;
            }
        }

        /// <summary>
        /// Gets or sets the customer
        /// </summary>
        public virtual Customer Customer { get; set; }
    }
}


text:
import tensorflow as tf
from deep_architect.helpers.tensorflow_eager_support import siso_tensorflow_eager_module

# The WeightSharer object is a simple wrapper around a dictionary that stores a
# mapping from a layer name to the shared layer used by the DeepArchitect modules.
class WeightSharer:

    def __init__(self):
        self.name_to_weight = {}

    def get(self, name, weight_fn):
        if name not in self.name_to_weight:
            self.name_to_weight[name] = weight_fn()
        return self.name_to_weight[name]

weight_sharer = WeightSharer()

# Now to share weights or any other object, simply use a common name for the object
# you wish to share, and pass in a function to initialize the object. The first
# time the function is called, the convolution layer will be created. Subsequent
# calls will simply retrieve the layer from the WeightSharer object.
def conv2D(filter_size, channels, name):

    def compile_fn(di, dh):
        conv_fn = lambda: tf.keras.layers.Conv2D(channels, filter_size)
        conv = weight_sharer.get(name, conv_fn)

        def fn(di, is_training=True):
            return {'out': conv(di['in'])}

        return fn

    return siso_tensorflow_eager_module('Conv2D', compile_fn, {})

conv_original = conv2D(3, 32, 'conv_layer')

# Now, calling the function again with the same 'name' argument will return
# a DeepArchitect module with the same internal convolutional layer
conv_shared = conv2D(3, 32, 'conv_layer')

# Implementing such a weight sharing scheme with another dynamic framework such
# as Pytorch is just as straightforward as above. To implement a weight sharing
# scheme with a graph based framework like Tensorflow, you must run the tensors
# that you wish to store and store the actual weights.


text: $EXEC("docker run -d -p 8080:8080 --name pinkie altenerdingbiber/pinkie");


text:
#define BOOST_TEST_MAIN

#include <limits>

#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/unit_test.hpp>

#include <Eigen/Core>

#include "Tudat/SimulationSetup/tudatSimulationHeader.h"

namespace tudat
{
namespace unit_tests
{

BOOST_AUTO_TEST_SUITE( test_gravitational_torque )

//! Test to check degree two gravitational torque
BOOST_AUTO_TEST_CASE( testDegreeTwoGravitationalTorque )
{
    using namespace tudat::simulation_setup;
    using namespace tudat::basic_astrodynamics;
    using namespace tudat::gravitation;

    // Load Spice kernels.
    spice_interface::loadStandardSpiceKernels( );

    // Set simulation time settings.
    const double simulationStartEpoch = 0.0;
    const double simulationEndEpoch = tudat::physical_constants::JULIAN_DAY;

    // Define body settings for simulation.
    std::vector< std::string > bodiesToCreate;
    bodiesToCreate.push_back( "Earth" );
    bodiesToCreate.push_back( "Moon" );

    //! Test torque for various inertia tensors
    for( unsigned int testCase = 0; testCase < 7; testCase++ )
    {

        // Create body objects.
        std::map< std::string, std::shared_ptr< BodySettings > > bodySettings =
                getDefaultBodySettings( bodiesToCreate );

        // Define degree two coefficients
        Eigen::Matrix3d cosineCoefficients = Eigen::Matrix3d::Zero( );
        Eigen::Matrix3d sineCoefficients = Eigen::Matrix3d::Zero( );
        Eigen::Matrix3d inertiaTensorDeviation = Eigen::Matrix3d::Zero( );
        if( testCase > 0 )
        {
            cosineCoefficients( 0, 0 ) = 1.0;

            if( testCase == 2 )
            {
                cosineCoefficients( 2, 0 ) = 0.01;
            }
            else if( testCase == 3 )
            {
                cosineCoefficients( 2, 2 ) = 0.01;
            }
            else if( testCase == 4 )
            {
                sineCoefficients( 2, 2 ) = 0.01;
            }
            else if( testCase == 5 )
            {
                cosineCoefficients( 2, 1 ) = 0.01;
            }
            else if( testCase == 6 )
            {
                sineCoefficients( 2, 1 ) = 0.01;
            }

            bodySettings[ "Moon" ]->gravityFieldSettings = std::make_shared< SphericalHarmonicsGravityFieldSettings >(
                        spice_interface::getBodyGravitationalParameter( "Moon" ), spice_interface::getAverageRadius( "Moon" ),
                        cosineCoefficients, sineCoefficients, "IAU_Moon" );
        }

        if( testCase > 0 )
        {
            double c20InertiaContribution  = cosineCoefficients( 2, 0 ) *
                    tudat::basic_mathematics::calculateLegendreGeodesyNormalizationFactor( 2, 0 ) / 3.0;
            inertiaTensorDeviation( 0, 0 ) += c20InertiaContribution;
            inertiaTensorDeviation( 1, 1 ) += c20InertiaContribution;
            inertiaTensorDeviation( 2, 2 ) -= 2.0 * c20InertiaContribution;

            double c21InertiaContribution  = cosineCoefficients( 2, 1 ) *
                    tudat::basic_mathematics::calculateLegendreGeodesyNormalizationFactor( 2, 1 );
            inertiaTensorDeviation( 0, 2 ) -= c21InertiaContribution;
            inertiaTensorDeviation( 2, 0 ) -= c21InertiaContribution;

            double c22InertiaContribution  = 2.0 * cosineCoefficients( 2, 2 ) *
                    tudat::basic_mathematics::calculateLegendreGeodesyNormalizationFactor( 2, 2 );
            inertiaTensorDeviation( 0, 0 ) -= c22InertiaContribution;
            inertiaTensorDeviation( 1, 1 ) += c22InertiaContribution;

            double s21InertiaContribution  = sineCoefficients( 2, 1 ) *
                    tudat::basic_mathematics::calculateLegendreGeodesyNormalizationFactor( 2, 1 );
            inertiaTensorDeviation( 1, 2 ) -= s21InertiaContribution;
            inertiaTensorDeviation( 2, 1 ) -= s21InertiaContribution;

            double s22InertiaContribution  = 2.0 * sineCoefficients( 2, 2 ) *
                    tudat::basic_mathematics::calculateLegendreGeodesyNormalizationFactor( 2, 2 );
            inertiaTensorDeviation( 0, 1 ) -= s22InertiaContribution;
            inertiaTensorDeviation( 1, 0 ) -= s22InertiaContribution;

            inertiaTensorDeviation *= spice_interface::getAverageRadius( "Moon" ) * spice_interface::getAverageRadius( "Moon" ) *
                    spice_interface::getBodyGravitationalParameter( "Moon" ) / physical_constants::GRAVITATIONAL_CONSTANT;
        }

        // Create bodies
        NamedBodyMap bodyMap = createBodies( bodySettings );
        setGlobalFrameBodyEphemerides( bodyMap, "SSB", "ECLIPJ2000" );

        // Crate torque model
        SelectedTorqueMap selectedTorqueModelMap;
        selectedTorqueModelMap[ "Moon" ][ "Earth" ].push_back(
                    std::make_shared< TorqueSettings >( second_order_gravitational_torque ) );
        basic_astrodynamics::TorqueModelMap torqueModelMap = createTorqueModelsMap(
                    bodyMap, selectedTorqueModelMap, { "Moon" } );
        std::shared_ptr< TorqueModel > secondDegreeGravitationalTorque =
                torqueModelMap.at( "Moon" ).at( "Earth" ).at( 0 );

        // Update environment to current time
        double evaluationTime = tudat::physical_constants::JULIAN_DAY / 2.0;

        bodyMap.at( "Moon" )->setStateFromEphemeris( evaluationTime );
        bodyMap.at( "Moon" )->setCurrentRotationalStateToLocalFrameFromEphemeris( evaluationTime );
        bodyMap.at( "Moon" )->setBodyInertiaTensorFromGravityField( 0.4 );

        bodyMap.at( "Earth" )->setStateFromEphemeris( evaluationTime );
        bodyMap.at( "Earth" )->setCurrentRotationalStateToLocalFrameFromEphemeris( evaluationTime );
        bodyMap.at( "Earth" )->setBodyInertiaTensorFromGravityField( 0.4 );

        if( testCase == 0 )
        {
            // Test id gravity field coefficients are correctly reconstructed
            inertiaTensorDeviation = bodyMap.at( "Moon" )->getBodyInertiaTensor( );
            std::shared_ptr< SphericalHarmonicsGravityField > moonGravityField =
                    std::dynamic_pointer_cast< SphericalHarmonicsGravityField >(
                        bodyMap.at( "Moon" )->getGravityFieldModel( ) );

            double recomputedC20 = std::sqrt( 0.2 ) /
                    ( moonGravityField->getGravitationalParameter( ) * moonGravityField->getReferenceRadius( ) *
                      moonGravityField->getReferenceRadius( ) / tudat::physical_constants::GRAVITATIONAL_CONSTANT ) * (
                        0.5 * ( inertiaTensorDeviation( 0, 0 ) + inertiaTensorDeviation( 1, 1 ) ) -
                        inertiaTensorDeviation( 2, 2 ) );
            BOOST_CHECK_CLOSE_FRACTION( recomputedC20, moonGravityField->getCosineCoefficients( )( 2, 0 ), 1.0E-12 );

            double recomputedC21 = -std::sqrt( 3.0 / 5.0 ) /
                    ( moonGravityField->getGravitationalParameter( ) * moonGravityField->getReferenceRadius( ) *
                      moonGravityField->getReferenceRadius( ) / tudat::physical_constants::GRAVITATIONAL_CONSTANT ) * (
                        inertiaTensorDeviation( 0, 2 ) );
            BOOST_CHECK_CLOSE_FRACTION( recomputedC21, moonGravityField->getCosineCoefficients( )( 2, 1 ), 1.0E-12 );

            double recomputedC22 = std::sqrt( 3.0 / 20.0 ) /
                    ( moonGravityField->getGravitationalParameter( ) * moonGravityField->getReferenceRadius( ) *
                      moonGravityField->getReferenceRadius( ) / tudat::physical_constants::GRAVITATIONAL_CONSTANT ) * (
                        inertiaTensorDeviation( 1, 1 ) - inertiaTensorDeviation( 0, 0 ) );
            BOOST_CHECK_CLOSE_FRACTION( recomputedC22, moonGravityField->getCosineCoefficients( )( 2, 2 ), 1.0E-12 );

            double recomputedS21 = -std::sqrt( 3.0 / 5.0 ) /
                    ( moonGravityField->getGravitationalParameter( ) * moonGravityField->getReferenceRadius( ) *
                      moonGravityField->getReferenceRadius( ) / tudat::physical_constants::GRAVITATIONAL_CONSTANT ) * (
                        inertiaTensorDeviation( 1, 2 ) );
            BOOST_CHECK_CLOSE_FRACTION( recomputedS21, moonGravityField->getSineCoefficients( )( 2, 1 ), 1.0E-12 );

            double recomputedS22 = -std::sqrt( 12.0 / 5.0 ) /
                    ( 2.0 * moonGravityField->getGravitationalParameter( ) * moonGravityField->getReferenceRadius( ) *
                      moonGravityField->getReferenceRadius( ) / tudat::physical_constants::GRAVITATIONAL_CONSTANT ) * (
                        inertiaTensorDeviation( 0, 1 ) );
            BOOST_CHECK_CLOSE_FRACTION( recomputedS22, moonGravityField->getSineCoefficients( )( 2, 2 ), 1.0E-12 );
        }

        // Update torque model to current time.
        secondDegreeGravitationalTorque->updateMembers( evaluationTime );

        // Compute torque manually, and test against computed result
        Eigen::Vector3d earthRelativePosition =
                bodyMap.at( "Moon" )->getCurrentRotationToLocalFrame( ) *
                ( bodyMap.at( "Earth" )->getPosition( ) - bodyMap.at( "Moon" )->getPosition( ) );
        Eigen::Vector3d manualTorque = 3.0 * earthRelativePosition.cross( inertiaTensorDeviation * earthRelativePosition ) *
                bodyMap.at( "Earth" )->getGravityFieldModel( )->getGravitationalParameter( ) /
                std::pow( earthRelativePosition.norm( ), 5.0 );

        Eigen::Vector3d currentTorque = secondDegreeGravitationalTorque->getTorque( );
        Eigen::Vector3d torqueError = ( currentTorque - manualTorque );

        std::cout<<"Current torques "<<currentTorque.transpose( )<<std::endl<<
                   torqueError<<std::endl;

        for( unsigned int i = 0; i < 3; i++ )
        {
            BOOST_CHECK_SMALL( std::fabs( torqueError( i ) ), 1.0E-14 * currentTorque.norm( ) );
        }
    }
}

//! Test to check spherical harmonic torque.
BOOST_AUTO_TEST_CASE( testSphericalGravitationalTorque )
{
    using namespace tudat::simulation_setup;
    using namespace tudat::basic_astrodynamics;
    using namespace tudat::gravitation;

    // Load Spice kernels.
    spice_interface::loadStandardSpiceKernels( );

    // Set simulation time settings.
    const double simulationStartEpoch = 0.0;
    const double simulationEndEpoch = tudat::physical_constants::JULIAN_DAY;

    //! Test for zero and non-zero spherical harmonic coefficients
    for( unsigned int testCase = 0; testCase < 2; testCase++ )
    {
        // Define body settings for simulation.
        std::vector< std::string > bodiesToCreate;
        bodiesToCreate.push_back( "Earth" );
        bodiesToCreate.push_back( "Moon" );

        // Create body objects.
        std::map< std::string, std::shared_ptr< BodySettings > > bodySettings =
                getDefaultBodySettings( bodiesToCreate );

        // Set effective point-mass gravity
        if( testCase == 0 )
        {
            Eigen::Matrix3d cosineCoefficients = Eigen::Matrix3d::Zero( );
            Eigen::Matrix3d sineCoefficients = Eigen::Matrix3d::Zero( );
            cosineCoefficients( 0, 0 ) = 1.0;

            bodySettings[ "Moon" ]->gravityFieldSettings = std::make_shared< SphericalHarmonicsGravityFieldSettings >(
                        spice_interface::getBodyGravitationalParameter( "Moon" ), spice_interface::getAverageRadius( "Moon" ),
                        cosineCoefficients, sineCoefficients, "IAU_Moon" );
        }

        NamedBodyMap bodyMap = createBodies( bodySettings );
        setGlobalFrameBodyEphemerides( bodyMap, "SSB", "ECLIPJ2000" );

        // Create two torque models
        SelectedTorqueMap selectedTorqueModelMap;
        selectedTorqueModelMap[ "Moon" ][ "Earth" ].push_back(
                    std::make_shared< TorqueSettings >( second_order_gravitational_torque ) );
        selectedTorqueModelMap[ "Moon" ][ "Earth" ].push_back(
                    std::make_shared< SphericalHarmonicTorqueSettings >( 2, 2 ) );
        basic_astrodynamics::TorqueModelMap torqueModelMap = createTorqueModelsMap(
                    bodyMap, selectedTorqueModelMap, { "Moon" } );
        std::shared_ptr< TorqueModel > secondDegreeGravitationalTorque =
                torqueModelMap.at( "Moon" ).at( "Earth" ).at( 0 );
        std::shared_ptr< TorqueModel > sphercialHarmonicGravitationalTorque =
                torqueModelMap.at( "Moon" ).at( "Earth" ).at( 1 );

        // Update Moon to current time.
        double evaluationTime = tudat::physical_constants::JULIAN_DAY / 2.0;
        bodyMap.at( "Moon" )->setStateFromEphemeris( evaluationTime );
        bodyMap.at( "Moon" )->setCurrentRotationalStateToLocalFrameFromEphemeris( evaluationTime );
        bodyMap.at( "Moon" )->setBodyInertiaTensorFromGravityField( 0.0 );

        {
            // Test reconstructed spherical harmonic coefficients
            Eigen::Matrix3d moonCosineCoefficients =
                    std::dynamic_pointer_cast< tudat::gravitation::SphericalHarmonicsGravityField >(
                        bodyMap.at( "Moon" )->getGravityFieldModel( ) )->getCosineCoefficients( ).block( 0, 0, 3, 3 );
            Eigen::Matrix3d moonSineCoefficients =
                    std::dynamic_pointer_cast< tudat::gravitation::SphericalHarmonicsGravityField >(
                        bodyMap.at( "Moon" )->getGravityFieldModel( ) )->getSineCoefficients( ).block( 0, 0, 3, 3 );
            Eigen::MatrixXd moonReconstructedCosineCoefficients = Eigen::Matrix3d::Zero( ),
                    moonReconstructedSineCoefficients = Eigen::Matrix3d::Zero( );

            double reconstructedScaledMeanMomentOfInertia;
            gravitation::getDegreeTwoSphericalHarmonicCoefficients(
                        bodyMap.at( "Moon" )->getBodyInertiaTensor( ),
                        bodyMap.at( "Moon" )->getGravityFieldModel( )->getGravitationalParameter( ),
                        std::dynamic_pointer_cast< SphericalHarmonicsGravityField >(
                            bodyMap.at( "Moon" )->getGravityFieldModel( ) )->getReferenceRadius( ), true,
                        moonReconstructedCosineCoefficients, moonReconstructedSineCoefficients,
                        reconstructedScaledMeanMomentOfInertia );

            for( unsigned int j = 0; j < 3; j++ )
            {
                for( unsigned int k = 0; k <= j; k++ )
                {
                    BOOST_CHECK_SMALL( std::fabs( moonReconstructedCosineCoefficients( j, k ) -
                                                  moonCosineCoefficients( j, k ) ), 1.0E-20 );

                    BOOST_CHECK_SMALL( std::fabs( moonReconstructedSineCoefficients( j, k ) -
                                                  moonSineCoefficients( j, k ) ), 1.0E-20 );
                }
            }
        }

        // Update Earth to current time.
        bodyMap.at( "Earth" )->setStateFromEphemeris( evaluationTime );
        bodyMap.at( "Earth" )->setCurrentRotationalStateToLocalFrameFromEphemeris( evaluationTime );
        bodyMap.at( "Earth" )->setBodyInertiaTensorFromGravityField( 0.0 );

        // Update and compute torque values
        secondDegreeGravitationalTorque->updateMembers( evaluationTime );
        Eigen::Vector3d currentExplicitTorque = secondDegreeGravitationalTorque->getTorque( );
        sphercialHarmonicGravitationalTorque->updateMembers( evaluationTime );
        Eigen::Vector3d currentSphericalHarmonicTorque = sphercialHarmonicGravitationalTorque->getTorque( );

        // Test difference between models (should be equivalent)
        Eigen::Vector3d torqueError = currentExplicitTorque - currentSphericalHarmonicTorque;
        for( unsigned int i = 0; i < 3; i++ )
        {
            BOOST_CHECK_SMALL( std::fabs( torqueError( i ) ), 1.0E-14 * currentExplicitTorque.norm( ) );
        }
    }
}

BOOST_AUTO_TEST_SUITE_END( )

} // namespace unit_tests

} // namespace tudat


text:
#ifndef XENIA_GPU_REGISTER_FILE_H_
#define XENIA_GPU_REGISTER_FILE_H_

#include <cstdint>
#include <cstdlib>

namespace xe {
namespace gpu {

enum Register {
#define XE_GPU_REGISTER(index, type, name) XE_GPU_REG_##name = index,
#include "xenia/gpu/register_table.inc"
#undef XE_GPU_REGISTER
};

struct RegisterInfo {
  enum class Type {
    kDword,
    kFloat,
  };
  Type type;
  const char* name;
};

class RegisterFile {
 public:
  RegisterFile();

  static const RegisterInfo* GetRegisterInfo(uint32_t index);

  static const size_t kRegisterCount = 0x5003;
  union RegisterValue {
    uint32_t u32;
    float f32;
  };
  RegisterValue values[kRegisterCount];

  RegisterValue& operator[](int reg) { return values[reg]; }
  RegisterValue& operator[](Register reg) { return values[reg]; }
};

}  // namespace gpu
}  // namespace xe

#endif  // XENIA_GPU_REGISTER_FILE_H_


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Group Share</title>

    <link href="css/bootstrap.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Group Share

                                Group Requests 2

Group Name 1
                                <button class="btn btn-info btn-sm margin-left" type="button">Accept</button>
                                <button class="btn btn-default btn-sm" type="button">Decline Request</button>

Group Name 2
                                <button class="btn btn-info btn-sm margin-left" type="button">Accept</button>
                                <button class="btn btn-default btn-sm" type="button">Decline Request</button>

 Profile

 Login

 Logout

                                <input type="text" class="form-control input-sm" placeholder="Search for a group" />
                                <button class="btn btn-info dropdown-toggle btn-sm" type="button" data-toggle="dropdown">

                                </button>

Group Name 1
                                        <button class="btn btn-info btn-sm margin-left" type="button"> Join </button>

Group Name 2
                                        <button class="btn btn-info btn-sm margin-left" type="button"> Join </button>

 Dashboard

 Groups

<button class="btn btn-info btn-sm" type="button"> Create New Group</button>

                                        Group Name 1

  Group Details

  Files

  Calendar

  Chat

                                        Group Management

Add Member

Delete Member

Assign an Admin

Review Requests

                                        Group Name 2

                                        Group Details

        Files  2

                                        Calendar 1

                                        Chat  3

                                        Group Management

Add Member

Delete Member

Assign an Admin

Review Requests
                                                    1

                                        1

                                        Group Name 3

  Group Details

  Files

  Calendar

  Chat

 Private Files

There are no files.

                Manage Private Files

 Calendar

                         Mar - 2017
                        ">

                        S
                        M
                        T
                        W
                        T
                        F
                        S

                        1
                        2
                        3
                        4
                        5
                        6
                        7

                        8
                        9
                        10
                        11
                        12
                        13
                        14

                        15
                        16
                        17
                        18
                        19
                        20
                        21

                        22
                        23
                        24
                        25
                        26
                        27
                        28

                        29
                        30
                        31

                Manage Calendar


text:
HRESULT LoadMscorpeDll(HMODULE * phModule);

// Wrapper for mscorpe.dll calls
typedef MscorpeSxSWrapper<LoadMscorpeDll> MscorpeSxS;


text:
var searchData=
[
  ['screenmanager_2ecs',['ScreenManager.cs',['../_screen_manager_8cs.html',1,'']]]
];


text:
package com.googlecode.jmxtrans.model.output;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.MoreObjects;
import com.googlecode.jmxtrans.model.Query;
import com.googlecode.jmxtrans.model.Result;
import com.googlecode.jmxtrans.model.Server;
import com.googlecode.jmxtrans.model.naming.KeyUtils;

import java.util.List;

/**
 * Format results in the form

 *     [MBean Id].[Type Name].[Attribute Name]=[Value]
 *

 */
public class KeyValueResultSerializer implements ResultSerializer {
	private static final String DEFAULT_FORMAT = "%s=%s";
	private final String format;
	private final List<String> typeNames;

	public KeyValueResultSerializer(@JsonProperty("format") String format, @JsonProperty List<String> typeNames) {
		this.format = MoreObjects.firstNonNull(format, DEFAULT_FORMAT);
		this.typeNames = typeNames;
	}

	public static KeyValueResultSerializer createDefault(List<String> typeNames) {
		return new KeyValueResultSerializer(DEFAULT_FORMAT, typeNames);
	}

	@Override
	public String serialize(Server server, Query query, Result result) {
		return String.format(format, KeyUtils.getKeyString(query, result, typeNames), result.getValue());
	}
}


text:
package com.wuyu.plugin.mvc.advice;

import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice;

/**
 * organization www.wuyushuo.com
 * created on 2016/02/04 by elon su
 * email addr (git_wuyu@163.com)
 * @version 1.0.0
 */
@Controller
@ControllerAdvice
public class JsonpResponseAdvice extends AbstractJsonpResponseBodyAdvice {

    public JsonpResponseAdvice() {
        super("callback");
    }

    @Override
    protected MediaType getContentType(MediaType contentType, ServerHttpRequest request, ServerHttpResponse response) {
        return new MediaType("application", "javascript", contentType.getCharSet());
    }
}


text:
package com.bosboy.repository;

import org.springframework.stereotype.Repository;

import com.bosboy.entity.Organization;

@Repository
public class OrganizationRepository extends BaseRepository<Organization> {
}


text:
from typing import List  # noqa

from mitmproxy.utils import strutils
from . import base

class ViewRaw(base.View):
    name = "Raw"

    def __call__(self, data, **metadata):
        return "Raw", base.format_text(strutils.bytes_to_escaped_str(data, True))

    def render_priority(self, data: bytes, **metadata) -> float:
        return 0.1 * float(bool(data))


text:
namespace uFluent.Consts
{
    public static class Icons
    {
        public const string Folder = "folder.gif";
        public const string Document = "doc.gif";
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
        <title>Page not found</title>
        <link rel="stylesheet" type="text/css" href="/css/reset.css">
        <link rel="stylesheet" type="text/css" href="/css/global.css">
        <link rel="shortcut icon" href="/images/favicon.ico">

Page not found

The page you requested could not be found. Try returning to the home page.


text:
import logging
from pandas import Series, DataFrame, concat

from ramp.builders import build_target_safe
from ramp.features.base import to_feature, ComboFeature, Feature, AllDataFeature
from ramp.modeling import fit_model, generate_test
from ramp.utils import get_single_column, reindex_safe

class TrainedFeature(Feature):

    def __init__(self):
        # For trained features, we will need access to all the data
        self.feature = AllDataFeature()
        super(TrainedFeature, self).__init__(self.feature)

class Predictions(TrainedFeature):
    # TODO: update for new context

    def __init__(self, model_def, name=None, external_data=None,
            cv_folds=None):
        """
        If cv-folds is specified, will use k-fold cross-validation to
        provide robust predictions.
        (The predictions returned are those predicted on hold-out sets only.)
        Will not provide overly-optimistic fit like Predictions will, but can
        increase runtime significantly (nested cross-validation).
        Can be int or iteratable of (train, test) indices
        """
        self.cv_folds = cv_folds
        self.model_def = model_def
        self.external_data = external_data
        super(Predictions, self).__init__()
        #TODO
        # if self.external_context is not none:
        #     # dont need to retrain if using external dataset to train
        #     self.trained = false
        if not name:
            name = 'predictions'
        self._name = '%s[%s,%d features]'%(name,
                model_def.estimator.__class__.__name__, len(model_def.features))

    def _train(self, train_data):
        x, y, fitted_model = fit_model(self.model_def, train_data)
        return fitted_model

    def _apply(self, data, fitted_feature):
        fitted_model = fitted_feature.trained_data

        #TODO
        # if self.cv_folds:
        #     if isinstance(self.cv_folds, int):
        #         folds = make_folds(context.train_index, self.cv_folds)
        #     else:
        #         folds = self.cv_folds
        #     preds = []
        #     for train, test in folds:
        #         ctx = context.copy()
        #         ctx.train_index = train
        #         preds.append(self._predict(ctx, test, fit_model=True))
        #     # if there is held-out data, use all of train to predict
        #     # (these predictions use more data, so will be "better",
        #     # not sure if that is problematic...)
        #     remaining = context.data.index - context.train_index
        #     if len(remaining):
        #         preds.append(self._predict(context, remaining))
        #     preds = concat(preds, axis=0)
        # else:
        preds = self._predict(fitted_model, data)
        preds = DataFrame(preds, index=data.index)
        return preds

    def _predict(self, fitted_model, predict_data):
        x_test, y_true = generate_test(self.model_def, predict_data, fitted_model)
        y_preds = self.model_def.estimator.predict(x_test)
        return y_preds

    def make_cross_validated_models(self, data, fitted_feature):
        pass

class Residuals(Predictions):

    def _predict(self, fitted_model, predict_data):
        x_test, y_true = generate_test(self.model_def, predict_data, fitted_model)
        y_preds = self.model_def.estimator.predict(x_test)
        return y_preds - y_true

class FeatureSelector(ComboFeature):

    def __init__(self, features, selector, target, data, n_keep=50,
                 threshold_arg=None):
        """
        """
        super(FeatureSelector, self).__init__(features)
        self.selector = selector
        self.n_keep = n_keep
        self.threshold_arg = threshold_arg
        self.target = target
        self.data = data
        self._name = self._name + '_%d_%s'%(threshold_arg or n_keep, selector.__class__.__name__)

    def _train(self, train_datas):
        train_data = concat(train_datas, axis=1)
        y, ff = build_target_safe(self.target, self.data)
        y = reindex_safe(y, train_data.index)
        arg = self.threshold_arg
        if arg is None:
            arg = self.n_keep
        cols = self.selector.select(train_data, y, arg)
        return cols

    def _combine_apply(self, datas, fitted_feature):
        data = concat(datas, axis=1)
        selected_columns = fitted_feature.trained_data
        return data[selected_columns]

class TargetAggregationByFactor(TrainedFeature):
    """
    """
    def __init__(self, group_by, func=None, target=None,
                 min_sample=10, regularize=True):
        super(TargetAggregationByFactor, self).__init__()
        self.group_by = group_by
        self.func = func
        self.target = to_feature(target)
        self.min_sample = min_sample
        self.regularize = regularize

    def __str__(self):
        return '%s(%s, %s)' % (self.__class__.__name__, self.group_by, self.target)

    def _train(self, train_data):
        y, ff = build_target_safe(self.target, train_data)
        train_data['__target'] = y
        global_value = self.func(y)
        if self.regularize:
            keys = train_data[self.group_by].unique()
            f = lambda x: (self.func(x) * x.size + global_value * self.min_sample) / (x.size + self.min_sample)
            vals = train_data.groupby(self.group_by).agg({'__target': f})['__target'].to_dict()
        else:
            vc = train_data[self.group_by].value_counts()
            keys = [k for k, v in vc.iterkv() if v >= self.min_sample]
            train_data['__grouping'] = train_data[self.group_by].map(lambda x: x if x in keys else '__other')
            vals = train_data.groupby('__grouping').agg({'__target': self.func})['__target'].to_dict()
            del train_data['__grouping']
        if '__other' not in vals:
            vals['__other'] = global_value
        logging.debug("Preparing Target Aggregations:")
        logging.debug(str(vals.items()[:10]))
        del train_data['__target']
        return vals

    def _apply(self, data, fitted_feature):
        vals = fitted_feature.trained_data
        logging.debug("Loading Target aggs")
        logging.debug(str(vals.items()[:10]))
        # logging.debug(str(keys))
        logging.debug(str(data.columns))
        data = data[[self.group_by]]
        data = data.applymap(lambda x: vals.get(x, vals['__other']))
        return data


text:
<!--
  Author:	Sam Ruby (http://intertwingly.net/) and Mark Pilgrim (http://diveintomark.org/)
  Copyright:	Copyright (c) 2002 Sam Ruby and Mark Pilgrim
  License:	Python
-->

<!--
  Description:	RSS 0.91 plain text description
  Expect:	!Warning
-->

<rss version="0.91">
  <channel>
    <title>title</title>
    <link>http://www.example.com/blog/</link>
    <description>description</description>
    <item>
       <title>title</title>
       <link>http://www.example.com/blog/246</link>
       <description><![CDATA[<plaintext>]]></description>
    </item>
  </channel>
</rss>


text:
import * as types from '../actions/types';

const initialState = {
    isHovered: false
};

export const home = (state = initialState, action) => {
    switch (action.type) {

        case types.SET_HOVER_WIDTH:
            const { isHovered } = action;
            return {
                ...state,
                isHovered
            };

        default:
            return state;
    }
};


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>SideCar: SideCar::GUI::HealthAndStatus::ChannelConnection Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="DoxygenStyleSheet.css" rel="stylesheet" type="text/css" />

SideCar

Main Page

Related Pages

Modules

Namespaces

Data Structures

Files

Data Structures

Class Hierarchy

Data Fields

SideCar

GUI

HealthAndStatus

ChannelConnection

Public Slots |
Signals |
Public Member Functions |
Static Public Member Functions

SideCar::GUI::HealthAndStatus::ChannelConnection Class Reference

Inheritance diagram for SideCar::GUI::HealthAndStatus::ChannelConnection:

[legend]

Public Slots

void 	shutdown ()

Signals

void 	connected ()

void 	incoming (const MessageList &msgs)

void 	disconnected ()

Public Member Functions

 	ChannelConnection (const QString &name, QObject *parent=0)

const QString & 	getName () const

void 	useServiceEntry (ServiceEntry *serviceEntry)

bool 	isConnected () const

void 	setMinimumSizeHint (const QSize &size)

const QSize & 	getMinimumSizeHint () const

ChannelPlotSettings * 	getSettings () const

Static Public Member Functions

static Logger::Log & 	Log ()

Detailed Description

Definition at line 20 of file ChannelConnection.h.

The documentation for this class was generated from the following files:

/Users/howes/src/sidecar/GUI/HealthAndStatus/ChannelConnection.h

/Users/howes/src/sidecar/GUI/HealthAndStatus/ChannelConnection.cc

<address class="footer">
Generated by

 1.8.11
</address>


text:
"use strict";

describe('utility service', function(){
  beforeEach(module('daApp'));

  var util;
  beforeEach(inject(function(_utilityService_){
    // The injector unwraps the underscores (_) from around the parameter names when matching
    util = _utilityService_;
  }));

  describe('getIdxFromPath', function(){
    it('should correctly extract id', function() {
      var paths = ['localDb/sessions/0',
                   'localDb/sessions/102',
                   'localDb/sessions/-1',
                   'localDb/sessions/0/blobs/6',
                   'localDb/sessions/100/blobs/70',
                   ['should produce an error since it\'s an array']
                  ];
      var expectedIdxs = [0, 102, -1, 6, 70, -1];

      expect(paths.length).toEqual(expectedIdxs.length);

      for (var i = 0; i < paths.length; i++) {
        var idx = util.getIdxFromPath(paths[i]);
        expect(idx).toEqual(expectedIdxs[i]);
      }
    });
  });

  describe('getConstant', function(){
    it('should return correct constants/types', function(){
      var currentKeys = [
        'invalidTitle',
        'tokenThreshold',
        'tokenGetCount',
        'QCAccThreshold',
        'QCFrequency',
        'QCInitRecThreshold',
        'tokenAnnouncementFreq',
        'tokenCountGoal',
        'syncRecCountPerSend',
        'evalBufferSize'
      ];
      var valueTypes = [
        'string',
        'number',
        'number',
        'number',
        'number',
        'number',
        'number',
        'number',
        'number',
        'number'
      ];

      expect(currentKeys.length).toEqual(valueTypes.length);

      for (var i = 0; i < currentKeys.length; i++) {
        var constant = util.getConstant(currentKeys[i]);
        expect(typeof(constant)).toEqual(valueTypes[i]);
      }
    });
  });

  describe('generateUUID', function(){
    it('should generate uuid on rfc4122 version 4 format', function(){
      var uuid = util.generateUUID();
      // match RFC 4122: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
      // https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_.28random.29
      //[0-9A-Fa-f]{6}
      expect(uuid.match(/^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-4[0-9A-Fa-f]{3}-[89ab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$/)).toBeTruthy();
    });

    it('should not be the same if repeated many times', function(){
      var REPEAT = 300; // lets not go overboard here.
      var uuids = [];
      for (var i = 0; i < REPEAT; i++) {
        uuids.push(util.generateUUID());
        for (var j = 0; j < i; j++) {
          expect(uuids[j]).not.toEqual(uuids[i]);
        }
      }
    });
  });

  describe('percentage', function(){
    it('should return correct numbers', function(){
      var args = [
        [3,9,2],
        [5,10,3]
      ];
      var expected = [
        33.33,
        50
      ];

      expect(args.length).toEqual(expected.length);

      for (var i = 0; i < args.length; i++) {
        var pr = util.percentage.apply(this, args[i]);
        expect(pr).toEqual(expected[i]);
      }
    });
  });

  describe('stdErrCallback', function(){
    it('should be defined', function(){
      expect(util.stdErrCallback).toBeDefined();
    });
  });
});


text:
The Kubernetes Helm project accepts contributions via GitHub pull requests. This document outlines the process to help get your contribution accepted.

## Reporting a Security Issue

Most of the time, when you find a bug in Helm, it should be reported
using [GitHub issues](https://github.com/helm/helm/issues). However, if
you are reporting a _security vulnerability_, please email a report to
[cncf-kubernetes-helm-security@lists.cncf.io](mailto:cncf-kubernetes-helm-security@lists.cncf.io). This will give
us a chance to try to fix the issue before it is exploited in the wild.

## Sign Your Work

The sign-off is a simple line at the end of the explanation for a commit. All
commits needs to be signed. Your signature certifies that you wrote the patch or
otherwise have the right to contribute the material. The rules are pretty simple,
if you can certify the below (from [developercertificate.org](http://developercertificate.org/)):

```
Developer Certificate of Origin
Version 1.1

Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
1 Letterman Drive
Suite D4700
San Francisco, CA, 94129

Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.

Developer's Certificate of Origin 1.1

By making a contribution to this project, I certify that:

(a) The contribution was created in whole or in part by me and I
    have the right to submit it under the open source license
    indicated in the file; or

(b) The contribution is based upon previous work that, to the best
    of my knowledge, is covered under an appropriate open source
    license and I have the right under that license to submit that
    work with modifications, whether created in whole or in part
    by me, under the same open source license (unless I am
    permitted to submit under a different license), as indicated
    in the file; or

(c) The contribution was provided directly to me by some other
    person who certified (a), (b) or (c) and I have not modified
    it.

(d) I understand and agree that this project and the contribution
    are public and that a record of the contribution (including all
    personal information I submit with it, including my sign-off) is
    maintained indefinitely and may be redistributed consistent with
    this project or the open source license(s) involved.
```

Then you just add a line to every git commit message:

    Signed-off-by: Joe Smith <joe.smith@example.com>

Use your real name (sorry, no pseudonyms or anonymous contributions.)

If you set your `user.name` and `user.email` git configs, you can sign your
commit automatically with `git commit -s`.

Note: If your git config information is set properly then viewing the
 `git log` information for your commit will look something like this:

```
Author: Joe Smith <joe.smith@example.com>
Date:   Thu Feb 2 11:41:15 2018 -0800

    Update README

    Signed-off-by: Joe Smith <joe.smith@example.com>
```

Notice the `Author` and `Signed-off-by` lines match. If they don't
your PR will be rejected by the automated DCO check.

## Support Channels

Whether you are a user or contributor, official support channels include:

- [Issues](https://github.com/helm/helm/issues)
- Slack:
  - User: [#helm-users](https://kubernetes.slack.com/messages/C0NH30761/details/)
  - Contributor: [#helm-dev](https://kubernetes.slack.com/messages/C51E88VDG/)

Before opening a new issue or submitting a new pull request, it's helpful to search the project - it's likely that another user has already reported the issue you're facing, or it's a known issue that we're already aware of. It is also worth asking on the Slack channels.

## Milestones

We use milestones to track progress of releases. There are also 2 special milestones
used for helping us keep work organized: `Upcoming - Minor` and `Upcoming - Major`

`Upcoming - Minor` is used for keeping track of issues that aren't assigned to a specific
release but could easily be addressed in a minor release. `Upcoming - Major` keeps track
of issues that will need to be addressed in a major release. For example, if the current
version is `2.2.0` an issue/PR could fall in to one of 4 different active milestones:
`2.2.1`, `2.3.0`, `Upcoming - Minor`, or `Upcoming - Major`. If an issue pertains to a
specific upcoming bug or minor release, it would go into `2.2.1` or `2.3.0`. If the issue/PR
does not have a specific milestone yet, but it is likely that it will land in a `2.X` release,
it should go into `Upcoming - Minor`. If the issue/PR is a large functionality add or change
and/or it breaks compatibility, then it should be added to the `Upcoming - Major` milestone.
An issue that we are not sure we will be doing will not be added to any milestone.

A milestone (and hence release) is considered done when all outstanding issues/PRs have been closed or moved to another milestone.

## Semantic Versioning

Helm maintains a strong commitment to backward compatibility. All of our changes to protocols and formats are backward compatible from Helm 2.0 until Helm 3.0. No features, flags, or commands are removed or substantially modified (other than bug fixes).

We also try very hard to not change publicly accessible Go library definitions inside of the `pkg/` directory of our source code.

For a quick summary of our backward compatibility guidelines for releases between 2.0 and 3.0:

- Protobuf and gRPC changes MUST be backward compatible.
- Command line commands, flags, and arguments MUST be backward compatible
- File formats (such as Chart.yaml, repositories.yaml, and requirements.yaml) MUST be backward compatible
- Any chart that worked on a previous version of Helm MUST work on a new version of Helm (barring the cases where (a) Kubernetes itself changed, and (b) the chart worked because it exploited a bug)
- Chart repository functionality MUST be backward compatible
- Go libraries inside of `pkg/` SHOULD remain backward compatible (though code inside of `cmd/` may be changed from release to release without notice).

## Issues

Issues are used as the primary method for tracking anything to do with the Helm project.

### Issue Types

There are 4 types of issues (each with their own corresponding [label](#labels)):
- Question: These are support or functionality inquiries that we want to have a record of for
future reference. Generally these are questions that are too complex or large to store in the
Slack channel or have particular interest to the community as a whole. Depending on the discussion,
these can turn into "Feature" or "Bug" issues.
- Proposal: Used for items (like this one) that propose a new ideas or functionality that require
a larger community discussion. This allows for feedback from others in the community before a
feature is actually  developed. This is not needed for small additions. Final word on whether or
not a feature needs a proposal is up to the core maintainers. All issues that are proposals should
both have a label and an issue title of "Proposal: [the rest of the title]." A proposal can become
a "Feature" and does not require a milestone.
- Features: These track specific feature requests and ideas until they are complete. They can evolve
from a "Proposal" or can be submitted individually depending on the size.
- Bugs: These track bugs with the code or problems with the documentation (i.e. missing or incomplete)

### Issue Lifecycle

The issue lifecycle is mainly driven by the core maintainers, but is good information for those
contributing to Helm. All issue types follow the same general lifecycle. Differences are noted below.
1. Issue creation
2. Triage
    - The maintainer in charge of triaging will apply the proper labels for the issue. This
    includes labels for priority, type, and metadata (such as "starter"). The only issue
    priority we will be tracking is whether or not the issue is "critical." If additional
    levels are needed in the future, we will add them.
    - (If needed) Clean up the title to succinctly and clearly state the issue. Also ensure
    that proposals are prefaced with "Proposal".
    - Add the issue to the correct milestone. If any questions come up, don't worry about
    adding the issue to a milestone until the questions are answered.
    - We attempt to do this process at least once per work day.
3. Discussion
    - "Feature" and "Bug" issues should be connected to the PR that resolves it.
    - Whoever is working on a "Feature" or "Bug" issue (whether a maintainer or someone from
    the community), should either assign the issue to them self or make a comment in the issue
    saying that they are taking it.
    - "Proposal" and "Question" issues should stay open until resolved or if they have not been
    active for more than 30 days. This will help keep the issue queue to a manageable size and
    reduce noise. Should the issue need to stay open, the `keep open` label can be added.
4. Issue closure

## How to Contribute a Patch

1. Fork the repo, develop and test your code changes.
1. Use sign-off when making each of your commits (see [above](#sign-your-work)).
   If you forgot to sign some commits that are part of the contribution, you can ask [git to rewrite your commit history](https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History).
1. Submit a pull request.

Coding conventions and standards are explained in the official developer docs:
[Developers Guide](docs/developers.md)

The next section contains more information on the workflow followed for Pull Requests.

## Pull Requests

Like any good open source project, we use Pull Requests (PRs) to track code changes.

### PR Lifecycle

1. PR creation
    - PRs are usually created to fix or else be a subset of other PRs that fix a particular issue.
    - We more than welcome PRs that are currently in progress. They are a great way to keep track of
    important work that is in-flight, but useful for others to see. If a PR is a work in progress,
    it **must** be prefaced with "WIP: [title]". Once the PR is ready for review, remove "WIP" from
    the title.
    - It is preferred, but not required, to have a PR tied to a specific issue. There can be
    circumstances where if it is a quick fix then an issue might be overkill. The details provided
    in the PR description would suffice in this case.
2. Triage
    - The maintainer in charge of triaging will apply the proper labels for the issue. This should
    include at least a size label, `bug` or `feature`, and `awaiting review` once all labels are applied.
    See the [Labels section](#labels) for full details on the definitions of labels.
    - Add the PR to the correct milestone. This should be the same as the issue the PR closes.
3. Assigning reviews
    - Once a review has the `awaiting review` label, maintainers will review them as schedule permits.
    The maintainer who takes the issue should self-request a review.
    - Any PR with the `size/large` label requires 2 review approvals from maintainers before it can be
    merged. Those with `size/medium` or `size/small` are per the judgement of the maintainers.
4. Reviewing/Discussion
    - Once a maintainer begins reviewing a PR, they will remove the `awaiting review` label and add
    the `in progress` label so the person submitting knows that it is being worked on. This is
    especially helpful when the review may take awhile.
    - All reviews will be completed using Github review tool.
    - A "Comment" review should be used when there are questions about the code that should be
    answered, but that don't involve code changes. This type of review does not count as approval.
    - A "Changes Requested" review indicates that changes to the code need to be made before they will be
    merged.
    - Reviewers (maintainers) should update labels as needed (such as `needs rebase`).
    - Reviews are also welcome from others in the community, especially those who have encountered a bug or
    have requested a feature. In the code review, a message can be added, as well as `LGTM` if the PR is
    good to merge. It's also possible to add comments to specific lines in a file, for giving context
    to the comment.
5. PR owner should try to be responsive to comments by answering questions or changing code. If the
   owner is unsure of any comment, reach out to the person who added the comment in
   [#helm-dev](https://kubernetes.slack.com/messages/C51E88VDG/). Once all comments have been addressed,
   the PR is ready to be merged.
6. Merge or close
    - PRs should stay open until merged or if they have not been active for more than 30 days.
    This will help keep the PR queue to a manageable size and reduce noise. Should the PR need
    to stay open (like in the case of a WIP), the `keep open` label can be added.
    - If the owner of the PR is listed in `OWNERS`, that user **must** merge their own PRs or explicitly
    request another OWNER do that for them.
    - If the owner of a PR is _not_ listed in `OWNERS`, any maintainer may merge the PR once it is approved.

#### Documentation PRs

Documentation PRs will follow the same lifecycle as other PRs. They will also be labeled with the
`docs` label. For documentation, special attention will be paid to spelling, grammar, and clarity
(whereas those things don't matter *as* much for comments in code).

## The Triager

Each week, one of the core maintainers will serve as the designated "triager" starting after the
public standup meetings on Thursday. This person will be in charge triaging new PRs and issues
throughout the work week.

## Labels

The following tables define all label types used for Helm. It is split up by category.

### Common

| Label | Description |
| ----- | ----------- |
| `bug` | Marks an issue as a bug or a PR as a bugfix |
| `critical` | Marks an issue or PR as critical. This means that addressing the PR or issue is top priority and will be handled first by maintainers |
| `docs` | Indicates the issue or PR is a documentation change |
| `duplicate` | Indicates that the issue or PR is a duplicate of another |
| `feature` | Marks the issue as a feature request or a PR as a feature implementation |
| `keep open` | Denotes that the issue or PR should be kept open past 30 days of inactivity |
| `refactor` | Indicates that the issue is a code refactor and is not fixing a bug or adding additional functionality |

### Issue Specific

| Label | Description |
| ----- | ----------- |
| `help wanted` | This issue is one the core maintainers cannot get to right now and would appreciate help with |
| `proposal` | This issue is a proposal |
| `question/support` | This issue is a support request or question |
| `starter` | This issue is a good for someone new to contributing to Helm |
| `wont fix` | The issue has been discussed and will not be implemented (or accepted in the case of a proposal) |

### PR Specific

| Label | Description |
| ----- | ----------- |
| `awaiting review` | The PR has been triaged and is ready for someone to review |
| `breaking` | The PR has breaking changes (such as API changes) |
| `in progress` | Indicates that a maintainer is looking at the PR, even if no review has been posted yet |
| `needs pick` | Indicates that the PR needs to be picked into a feature branch (generally bugfix branches). Once it has been, the `picked` label should be applied and this one removed |
| `needs rebase` | A helper label used to indicate that the PR needs to be rebased before it can be merged. Used for easy filtering |
| `picked` | This PR has been picked into a feature branch |

#### Size labels

Size labels are used to indicate how "dangerous" a PR is. The guidelines below are used to assign the
labels, but ultimately this can be changed by the maintainers. For example, even if a PR only makes
30 lines of changes in 1 file, but it changes key functionality, it will likely be labeled as `size/large`
because it requires sign off from multiple people. Conversely, a PR that adds a small feature, but requires
another 150 lines of tests to cover all cases, could be labeled as `size/small` even though the number
lines is greater than defined below.

| Label | Description |
| ----- | ----------- |
| `size/small` | Anything less than or equal to 4 files and 150 lines. Only small amounts of manual testing may be required |
| `size/medium` | Anything greater than `size/small` and less than or equal to 8 files and 300 lines. Manual validation should be required. |
| `size/large` | Anything greater than `size/medium`. This should be thoroughly tested before merging and always requires 2 approvals. This also should be applied to anything that is a significant logic change. |


text:
<Type Name="IInteractiveCell" FullName="Hyena.Data.Gui.IInteractiveCell">
  <TypeSignature Language="C#" Value="public interface IInteractiveCell" />
  <AssemblyInfo>
    <AssemblyName>Hyena.Gui</AssemblyName>
    <AssemblyVersion>1.3.1.0</AssemblyVersion>
    <AssemblyVersion>1.4.0.0</AssemblyVersion>
  </AssemblyInfo>
  <Interfaces />
  <Docs>
    To be added.
    <remarks>To be added.</remarks>
  </Docs>
  <Members>

    <Member MemberName="ButtonEvent">
      <MemberSignature Language="C#" Value="public bool ButtonEvent (int x, int y, bool pressed, Gdk.EventButton evnt);" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>

      <AssemblyVersion>1.3.1.0</AssemblyVersion><AssemblyVersion>1.4.0.0</AssemblyVersion></AssemblyInfo>
      <ReturnValue><ReturnType>System.Boolean</ReturnType></ReturnValue>
      <Parameters><Parameter Name="x" Type="System.Int32" /><Parameter Name="y" Type="System.Int32" /><Parameter Name="pressed" Type="System.Boolean" /><Parameter Name="evnt" Type="Gdk.EventButton" /></Parameters>
      <Docs><param name="x">To be added.</param><param name="y">To be added.</param><param name="pressed">To be added.</param><param name="evnt">To be added.</param>To be added.<returns>To be added.</returns><remarks>To be added.</remarks></Docs>
    </Member><Member MemberName="MotionEvent">
      <MemberSignature Language="C#" Value="public bool MotionEvent (int x, int y, Gdk.EventMotion evnt);" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>

      <AssemblyVersion>1.3.1.0</AssemblyVersion><AssemblyVersion>1.4.0.0</AssemblyVersion></AssemblyInfo>
      <ReturnValue><ReturnType>System.Boolean</ReturnType></ReturnValue>
      <Parameters><Parameter Name="x" Type="System.Int32" /><Parameter Name="y" Type="System.Int32" /><Parameter Name="evnt" Type="Gdk.EventMotion" /></Parameters>
      <Docs><param name="x">To be added.</param><param name="y">To be added.</param><param name="evnt">To be added.</param>To be added.<returns>To be added.</returns><remarks>To be added.</remarks></Docs>
    </Member><Member MemberName="PointerLeaveEvent">
      <MemberSignature Language="C#" Value="public bool PointerLeaveEvent ();" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>

      <AssemblyVersion>1.3.1.0</AssemblyVersion><AssemblyVersion>1.4.0.0</AssemblyVersion></AssemblyInfo>
      <ReturnValue><ReturnType>System.Boolean</ReturnType></ReturnValue>
      <Parameters />
      <Docs>To be added.<returns>To be added.</returns><remarks>To be added.</remarks></Docs>
    </Member>
  </Members>
</Type>


text:
touch temp_input.1
rm -f temp_input.*

input_data=`echo $1`
output_name=`echo $2`
num_files=${3}
config_name=${4}

touch Prepare_${output_name}.sh
rm -f Prepare_${output_name}.sh

echo "touch Run_${output_name}.sh "  > Prepare_${output_name}.sh
echo "rm -f Run_${output_name}.sh " >> Prepare_${output_name}.sh
echo "touch Run_${output_name}.sh " >> Prepare_${output_name}.sh

more ${config_name} | sort > temp_input.1
#sed -i 's/\///g' temp_input.1
#more temp_input.1 | tr '/' '' > temp_input.2
counter=0
more temp_input.1 |while read line
do
  file=`echo $line`
  counter=`expr $counter + 1`
  echo "source PrepareJobs.sh ${input_data} ${output_name}_${counter} ${num_files} ${file}" >> Prepare_${output_name}.sh
  echo "echo \"./SubmitAll_${output_name}_${counter}.sh\" >> Run_${output_name}.sh" >> Prepare_${output_name}.sh
done
#source PrepareJobs.sh /pnfs/iihe/cms/store/user/jez/ZHttNtuples/53X/MC/ZZJetsTo4L_TuneZ2star_8TeV-madgraph-tauola/ test 50 Analysis_config_T2_MC_53.xml

echo "chmod +x Run_${output_name}.sh " >> Prepare_${output_name}.sh
echo "echo \"To run all execute ./Run_${output_name}.sh\" " >> Prepare_${output_name}.sh

chmod +x Prepare_${output_name}.sh
echo "To prepare jobs do ./Prepare_${output_name}.sh"

rm -f temp_input*


text:
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(UIWrapContent), true)]
public class UIWrapContentEditor : Editor
{
	public override void OnInspectorGUI ()
	{
		GUILayout.Space(6f);
		NGUIEditorTools.SetLabelWidth(90f);

		string fieldName = "Item Size";
		string error = null;
		UIScrollView sv = null;

		if (!serializedObject.isEditingMultipleObjects)
		{
			UIWrapContent list = target as UIWrapContent;
			sv = NGUITools.FindInParents<UIScrollView>(list.gameObject);

			if (sv == null)
			{
				error = "UIWrappedList needs a Scroll View on its parent in order to work properly";
			}
			else if (sv.movement == UIScrollView.Movement.Horizontal) fieldName = "Item Width";
			else if (sv.movement == UIScrollView.Movement.Vertical) fieldName = "Item Height";
			else
			{
				error = "Scroll View needs to be using Horizontal or Vertical movement";
			}
		}

		serializedObject.Update();
		GUILayout.BeginHorizontal();
		NGUIEditorTools.DrawProperty(fieldName, serializedObject, "itemSize", GUILayout.Width(130f));
		GUILayout.Label("pixels");
		GUILayout.EndHorizontal();

		GUILayout.BeginHorizontal();
		SerializedProperty sp1 = NGUIEditorTools.DrawProperty("Range Limit", serializedObject, "minIndex", GUILayout.Width(130f));
		NGUIEditorTools.SetLabelWidth(20f);
		SerializedProperty sp2 = NGUIEditorTools.DrawProperty("to", serializedObject, "maxIndex", GUILayout.Width(60f));
		NGUIEditorTools.SetLabelWidth(90f);
		if (sp1.intValue == sp2.intValue) GUILayout.Label("unlimited");
		GUILayout.EndHorizontal();

		NGUIEditorTools.DrawProperty("Cull Content", serializedObject, "cullContent");

		if (!string.IsNullOrEmpty(error))
		{
			EditorGUILayout.HelpBox(error, MessageType.Error);
			if (sv != null && GUILayout.Button("Select the Scroll View"))
				Selection.activeGameObject = sv.gameObject;
		}

		serializedObject.ApplyModifiedProperties();

		if (sp1.intValue != sp2.intValue)
		{
			if ((target as UIWrapContent).GetComponent<UICenterOnChild>() != null)
			{
				EditorGUILayout.HelpBox("Limiting indices doesn't play well with UICenterOnChild. You should either not limit the indices, or not use UICenterOnChild.", MessageType.Warning);
			}
		}
	}
}


text:
using namespace GameServer::Common;
using namespace GameServer::Turn;

namespace GameServer
{
namespace Epoch
{

TickEpochOperatorAutPtr TickEpochOperatorFactory::createTickEpochOperator(
    IManagerAbstractFactoryShrPtr           a_manager_abstract_factory,
    IPersistenceFacadeAbstractFactoryShrPtr a_persistence_facade_abstract_factory
)
{
    return TickEpochOperatorAutPtr(
               new TickEpochOperator(a_persistence_facade_abstract_factory->createEpochPersistenceFacade(),
                                     a_persistence_facade_abstract_factory->createWorldPersistenceFacade(),
                                     a_manager_abstract_factory->createAchievementManager(),
                                     a_manager_abstract_factory->createTurnManager())
           );
}

} // namespace Epoch
} // namespace GameServer


text:
Imports System
Imports System.Text
Imports System.Collections.Generic
Imports System.Web.Mvc
Imports Gallio.Framework
Imports MbUnit.Framework
Imports $mvcprojectnamespace$
Imports $mvcprojectnamespace$.Controllers

<TestFixture()> _
Public Class HomeControllerTest
    <Test()> _
    Public Sub Index()
        ' Setup
        Dim controller As HomeController = New HomeController()

        ' Execute
        Dim result As ViewResult = controller.Index()

        ' Verify
        Dim viewData As ViewDataDictionary = result.ViewData

        Assert.AreEqual("Home Page", viewData("Title"))
        Assert.AreEqual("Welcome to ASP.NET MVC!", viewData("Message"))
    End Sub

    <Test()> _
    Public Sub About()
        ' Setup
        Dim controller As HomeController = New HomeController()

        ' Execute
        Dim result As ViewResult = controller.About()

        ' Verify
        Dim viewData As ViewDataDictionary = result.ViewData

        Assert.AreEqual("About Page", viewData("Title"))
    End Sub
End Class


text:
using System;
using System.ComponentModel;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Win;
using System.Collections.Generic;
using System.Diagnostics;
using DevExpress.ExpressApp.Updating;
using DevExpress.ExpressApp.Xpo;
using System.Linq;
using DevExpress.ExpressApp.Templates;
using DevExpress.ExpressApp.Win.Templates.Ribbon;
using DevExpress.ExpressApp.Win.SystemModule;
using DevExpress.Xpo;
using DevExpress.XtraBars.Docking;
using CIIP;
using CIIP.Module.BusinessObjects;
using DevExpress.ExpressApp.Actions;
using CIIP.Module.BusinessObjects.SYS;
using System.Windows.Forms;
using DevExpress.ExpressApp.Win.Core.ModelEditor;
using DevExpress.ExpressApp.Utils;

namespace CIIP.Win {
    // For more typical usage scenarios, be sure to check out https://documentation.devexpress.com/eXpressAppFramework/DevExpressExpressAppWinWinApplicationMembersTopicAll.aspx
    public partial class CIIPDesignerWindowsFormsApplication : WinApplication,IRestartApplication {
        public CIIPDesignerWindowsFormsApplication()
        {
            InitializeComponent();
            InitializeDefaults();
        }

        protected override Form CreateModelEditorForm()
        {
            ModelEditorViewController controller = new ModelEditorViewController(this.Model, base.CreateUserModelDifferenceStore());
            ModelDifferenceStore moduleStore = base.CreateModelDifferenceStore();
            if (moduleStore != null)
            {
                List<ModuleDiffStoreInfo> modulesDiffStoreInfo = new List<ModuleDiffStoreInfo> {
            new ModuleDiffStoreInfo(null, moduleStore, "Model")
        };
                controller.SetModuleDiffStore(modulesDiffStoreInfo);
            }
            return new ModelEditor.ModelEditorForm(controller, new SettingsStorageOnModel(((IModelApplicationModelEditor)this.Model).ModelEditorSettings));

        }

        private void InitializeDefaults()
        {
            LinkNewObjectToParentImmediately = false;
            OptimizedControllersCreation = true;
            UseLightStyle = true;
            UseOldTemplates = false;
        }
        protected override void CreateDefaultObjectSpaceProvider(CreateCustomObjectSpaceProviderEventArgs args) {
            args.ObjectSpaceProvider =  new XPObjectSpaceProvider(args.ConnectionString, args.Connection, false);
            args.ObjectSpaceProviders.Add(new NonPersistentObjectSpaceProvider(TypesInfo, null));
        }

        protected override IFrameTemplate CreateDefaultTemplate(TemplateContext context)
        {
            var ribbon = base.CreateDefaultTemplate(context);
            if (ribbon is IDockManagerHolder)
            {
                var r = ribbon as IDockManagerHolder;
                var rp = r.DockManager.AddPanel(DockingStyle.Right);
                rp.Visibility = DockVisibility.Hidden;
                rp.Text = "搜索";
                rp.Width = 200;
            }
            return ribbon;
        }

        private void ERPWindowsFormsApplication_CustomizeLanguagesList(object sender, CustomizeLanguagesListEventArgs e) {
            string userLanguageName = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
            if(userLanguageName != "en-US" && e.Languages.IndexOf(userLanguageName) == -1) {
                e.Languages.Add(userLanguageName);
            }
        }

        public bool IsRestartApplication { get; set; }

        private void ERPWindowsFormsApplication_DatabaseVersionMismatch(object sender, DevExpress.ExpressApp.DatabaseVersionMismatchEventArgs e) {
#if EASYTEST
            e.Updater.Update();
            e.Handled = true;
#else
            if (true)
            {
                //System.Diagnostics.Debugger.IsAttached) {
                e.Updater.Update();
                e.Handled = true;
            }
            else
            {
                throw new InvalidOperationException(
                    "The application cannot connect to the specified database, because the latter doesn't exist or its version is older than that of the application.\r\n" +
                    "This error occurred  because the automatic database update was disabled when the application was started without debugging.\r\n" +
                    "目标仓库 avoid this error, you should either start the application under Visual Studio in debug mode, or modify the " +
                    "source code of the 'DatabaseVersionMismatch' event handler to enable automatic database update, " +
                    "or manually create a database using the 'DBUpdater' tool.\r\n" +
                    "Anyway, refer to the 'Update Application and Database Versions' help topic at http://help.devexpress.com/#Xaf/CustomDocument2795 " +
                    "for more detailed information. If this doesn't help, please contact our Support Team at http://www.devexpress.com/Support/Center/");
            }
#endif
        }

        public void RestartApplication()
        {
            IsRestartApplication = true;
            this.Exit();

            //var path = System.Windows.Forms.Application.ExecutablePath;
            //Process.Start(path);

            //this.Exit();

        }
    }
}


text:
module WASH.CGI.Style (Style(..), using) where

import WASH.HTML.HTMLMonad hiding (map, div, head, span)
import Data.List

infixl 5 :^:
infix 9 :=:

-- |First class style elements. Intended for CSS2.
data Style
  = NoStyle
  | String :=: String	    -- ^primitive style @name :=: value@
  | Style  :^: Style	    -- ^combine two styles
  | Named String	    -- ^reference to style sheet

instance Show Style where
  showsPrec n NoStyle = id
  showsPrec n (s1 :=: s2) = showString s1 . showString ": " . showString s2
  showsPrec n (s1 :^: s2) = shows s1 . showString "; " . shows s2
  showsPrec n (Named s) = id

-- |collects a style into a list of class names and primitive styles
collect :: Style -> ([String], Style)
collect st = g ([],NoStyle) st
  where
    g acc NoStyle = acc
    g (cls, sts) st@(n :=: v) = (cls, st :^: sts)
    g acc (st1 :^: st2) = g (g acc st2) st1
    g (cls, sts) (Named n) = (n : cls, st)

attach :: (Monad m) => Style -> WithHTML x m ()
attach sty =
  let (cls, st) = collect sty in
  do case cls of
       [] -> empty
       _  -> attr "class" (concat $ intersperse " " cls)
     case st of NoStyle -> empty
		_       -> attr "style" (show st)

-- |Attaches a style to a field constructor.
using :: (Monad m)
	=> Style
	-> (WithHTML x m b -> c)	-- ^a field constructor, typically 'HTMLField'
	-> WithHTML x m b -> c		-- ^styled version of this constructor
using style elem x = elem (x ## attach style)


text:
angular.module('schools')
    .controller('appsRootController',
    ['apps', 'AppDataProvider', '$scope', 'AuthService', '$location',
        function (apps, AppDataProvider, $scope, AuthService, $location) {
            $scope.apps = apps;
            $scope.temp = {};
            var me = AuthService.me;
            $scope.seletedApp = [];
            $scope.newAppName = '';

            $scope.createApp = function() {
                $scope.temp.error = '';
                if (($scope.newAppName == "") || ($scope.newAppName === undefined)) {
                    $scope.temp.error = 'noName';
                    return;
                }
                var apps = $scope.apps;
                for (var i = 0; i < apps.length; i++) {
                    if (apps[i].name == $scope.newAppName.trim()) {
                        $scope.temp.error = 'alreadyHave';
                        return;
                    }
                }
                $('#createAppDialog').modal('hide');
                AppDataProvider.createApp($scope.newAppName.trim(), me, 'root')
                    .success(function(newApp) {
                        $('#createAppModal').modal('hide');
                        $location.path('/apps/' + newApp._id)
                    }).error(function(err) {
                        $scope.temp.error = 'failure';
                        console.error(err);
                    })
            };

            $scope.filterOptions = {
                filterText: ''
            };

            $scope.gridOptions =
            {
                data: 'apps',
                multiSelect: false,
                filterOptions: $scope.filterOptions,
                rowTemplate: '

',
                columnDefs: [
                    {field: '_id', visible: false},
                    {field: 'name', displayName: '应用程序名称'},// cellTemplate:'
{{row.getProperty(col.field)}}
'},
                    {field: 'package', displayName: '应用的包名'},
                    {field: '', displayName: '操作',cellTemplate:
                    '
' +
                    '
'}
                ],
                selectedItems: $scope.seletedApp
            };

            $scope.selectApp = function () {
                $location.path('/apps/' + $scope.gridOptions.selectedItems[0]._id);
            };

            $scope.deleteApp = function (event, row) {
                event.stopPropagation();
                swal({
                    title: "您确定要删除此应用程序吗?",
                    //text: "",
                    type: "warning",
                    showCancelButton: true,
                        cancelButtonText: "取消",
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "删除",
                    closeOnConfirm: false },
                    function(){
                        AppDataProvider.deleteApp(row.entity._id)
                            .success(function(app){
                                swal({title: "删除成功", type: "success", timer: 1000 });
                                $scope.apps.splice($scope.apps.indexOf(row.entity),1);
                        })
                            .error(function(err){
                                console.error(err);
                                swal({title: "删除失败", text: "请重试", type: 'error', timer: 1000})

                        })
                    });
            }
        }]);


text:
<?php

namespace OpenCloud\ObjectStore\Resource;

use OpenCloud\Common\Service as AbstractService;
use OpenCloud\Common\Lang;
use OpenCloud\Common\Exceptions;
use OpenCloud\ObjectStore\AbstractService as AbstractObjectService;

/**
 * A container that has been CDN-enabled. Each CDN-enabled container has a unique
 * Uniform Resource Locator (URL) that can be combined with its object names and
 * openly distributed in web pages, emails, or other applications.
 */
class CDNContainer extends AbstractStorageObject
{
    /**
     * The name of the container.
     *
     * The only restrictions on container names is that they cannot contain a
     * forward slash (/) and must be less than 256 bytes in length. Please note
     * that the length restriction applies to the name after it has been URL
     * encoded. For example, a container named Course Docs would be URL encoded
     * as Course%20Docs - which is 13 bytes in length rather than the expected 11.
     *
     * @var string
     */
    public $name;

    /**
     * Count of how many objects exist in the container.
     *
     * @var int
     */
    public $count = 0;

    /**
     * The total bytes used in the container.
     *
     * @var int
     */
    public $bytes = 0;

    /**
     * The service object.
     *
     * @var AbstractService
     */
    private $service;

    /**
     * URL of the container.
     *
     * @var string
     */
    private $containerUrl;

    /**
     * Creates the container object
     *
     * Creates a new container object or, if the $cdata object is a string,
     * retrieves the named container from the object store. If $cdata is an
     * array or an object, then its values are used to set this object.
     *
     * @param OpenCloud\ObjectStore $service - the ObjectStore service
     * @param mixed $cdata - if supplied, the name of the object
     */
    public function __construct(AbstractService $service, $cdata = null)
    {
        $this->getLogger()->info('Initializing CDN Container Service...');

        parent::__construct();

        $this->service = $service;

        // Populate data if set
        $this->populate($cdata);
    }

    /**
     * Allow other objects to know what the primary key is.
     *
     * @return string
     */
    public function primaryKeyField()
    {
        return 'name';
    }

    /**
     * Returns the Service associated with the Container
     */
    public function getService()
    {
        return $this->service;
    }

    /**
     * Returns the URL of the container
     *
     * @return string
	 * @param string $subresource not used; required for compatibility
     * @throws NoNameError
     */
    public function url($subresource = '')
    {
        if (strlen($this->name) == 0) {
            throw new Exceptions\NoNameError(
            	Lang::translate('Container does not have an identifier')
            );
        }

        return Lang::noslash($this->getService()->url(rawurlencode($this->name)));
    }

    /**
     * Creates a new container with the specified attributes
     *
     * @param array $params array of parameters
     * @return boolean TRUE on success; FALSE on failure
     * @throws ContainerCreateError
     */
    public function create($params = array())
    {
        // Populate object and check container name
        $this->populate($params);
        $this->isValidName($this->name);

        // Dispatch
        $this->containerUrl = $this->url();
        $response = $this->getService()->request($this->url(), 'PUT', $this->metadataHeaders());

        // Check return code
        // @codeCoverageIgnoreStart
        if ($response->httpStatus() > 202) {
            throw new Exceptions\ContainerCreateError(sprintf(
                Lang::translate('Problem creating container [%s] status [%d] response [%s]'),
                $this->url(),
                $response->httpStatus(),
                $response->httpBody()
            ));
        }
        // @codeCoverageIgnoreEnd

        return true;
    }

    /**
     * Updates the metadata for a container
     *
     * @return boolean TRUE on success; FALSE on failure
     * @throws ContainerCreateError
     */
    public function update()
    {
        $response = $this->getService()->request($this->url(), 'POST', $this->metadataHeaders());

        // check return code
        // @codeCoverageIgnoreStart
        if ($response->httpStatus() > 204) {
            throw new Exceptions\ContainerCreateError(sprintf(
                Lang::translate('Problem updating container [%s] status [%d] response [%s]'),
                $this->Url(),
                $response->httpStatus(),
                $response->httpBody()
            ));
        }
        // @codeCoverageIgnoreEnd

        return true;
    }

    /**
     * Deletes the specified container
     *
     * @return boolean TRUE on success; FALSE on failure
     * @throws ContainerDeleteError
     */
    public function delete()
    {
        $response = $this->getService()->request($this->url(), 'DELETE');

        // validate the response code
        // @codeCoverageIgnoreStart
        if ($response->httpStatus() == 404) {
            throw new Exceptions\ContainerNotFoundError(sprintf(
                Lang::translate('Container [%s] not found'),
                $this->name
            ));
        }

        if ($response->httpStatus() == 409) {
            throw new Exceptions\ContainerNotEmptyError(sprintf(
                Lang::translate('Container [%s] must be empty before deleting'),
                $this->name
            ));
        }

        if ($response->httpStatus() >= 300) {
            throw new Exceptions\ContainerDeleteError(sprintf(
                Lang::translate('Problem deleting container [%s] status [%d] response [%s]'),
                $this->url(),
                $response->httpStatus(),
                $response->httpBody()
            ));
            return false;
        }
        // @codeCoverageIgnoreEnd

        return true;
    }

    /**
     * Loads the object from the service
     *
     * @return void
     */
    public function refresh($name = null, $url = null)
    {
        $response = $this->getService()->request(
        	$this->url($name), 'HEAD', array('Accept' => '*/*')
        );

        // validate the response code
        // @codeCoverageIgnoreStart
        if ($response->HttpStatus() == 404) {
            throw new Exceptions\ContainerNotFoundError(sprintf(
                'Container [%s] (%s) not found',
                $this->name,
                $this->url()
            ));
        }

        if ($response->HttpStatus() >= 300) {
            throw new Exceptions\HttpError(sprintf(
                'Error retrieving Container, status [%d] response [%s]',
                $response->httpStatus(),
                $response->httpBody()
            ));
        }

		// check for headers (not metadata)
		foreach($response->headers() as $header => $value) {
			switch($header) {
                case 'X-Container-Object-Count':
                    $this->count = $value;
                    break;
                case 'X-Container-Bytes-Used':
                    $this->bytes = $value;
                    break;
			}
		}
        // @codeCoverageIgnoreEnd

        // parse the returned object
        $this->getMetadata($response);
    }

    /**
     * Validates that the container name is acceptable
     *
     * @param string $name the container name to validate
     * @return boolean TRUE if ok; throws an exception if not
     * @throws ContainerNameError
     */
    public function isValidName($name)
    {
        if (strlen($name) == 0) {
            throw new Exceptions\ContainerNameError(
            	'Container name cannot be blank'
            );
        }

        if (strpos($name, '/') !== false) {
            throw new Exceptions\ContainerNameError(
            	'Container name cannot contain "/"'
            );
        }

        if (strlen($name) > AbstractObjectService::MAX_CONTAINER_NAME_LEN) {
            throw new Exceptions\ContainerNameError(
            	'Container name is too long'
            );
        }

        return true;
    }

}


text:
<!--
  ~ Copyright (c) 2014 Coinposit, Inc. - All Rights Reserved.
  ~ Unauthorized copying of this file, via any medium is strictly prohibited.
  ~ This file is proprietary and confidential.
  ~ Last modified by rconrad, 8/5/14 11:12 PM
  -->

<script>
var qp = null;
if(window.location.hash) {
  qp = location.hash.substring(1);
}
else {
  qp = location.search.substring(1);
}
qp = qp ? JSON.parse('{"' + qp.replace(/&/g, '","').replace(/=/g,'":"') + '"}',
  function(key, value) {
    return key===""?value:decodeURIComponent(value) }
  ):{}
window.opener.onOAuthComplete(qp);
window.close();
</script>


text:
import contextlib

import eventlet

from neutron.agent.linux import ovsdb_monitor
from neutron.plugins.openvswitch.common import constants

@contextlib.contextmanager
def get_polling_manager(minimize_polling=False,
                        root_helper=None,
                        ovsdb_monitor_respawn_interval=(
                            constants.DEFAULT_OVSDBMON_RESPAWN)):
    if minimize_polling:
        pm = InterfacePollingMinimizer(
            root_helper=root_helper,
            ovsdb_monitor_respawn_interval=ovsdb_monitor_respawn_interval)
        pm.start()
    else:
        pm = AlwaysPoll()
    try:
        yield pm
    finally:
        if minimize_polling:
            pm.stop()

class BasePollingManager(object):

    def __init__(self):
        self._force_polling = False
        self._polling_completed = True

    def force_polling(self):
        self._force_polling = True

    def polling_completed(self):
        self._polling_completed = True

    def _is_polling_required(self):
        raise NotImplemented

    @property
    def is_polling_required(self):
        # Always consume the updates to minimize polling.
        polling_required = self._is_polling_required()

        # Polling is required regardless of whether updates have been
        # detected.
        if self._force_polling:
            self._force_polling = False
            polling_required = True

        # Polling is required if not yet done for previously detected
        # updates.
        if not self._polling_completed:
            polling_required = True

        if polling_required:
            # Track whether polling has been completed to ensure that
            # polling can be required until the caller indicates via a
            # call to polling_completed() that polling has been
            # successfully performed.
            self._polling_completed = False

        return polling_required

class AlwaysPoll(BasePollingManager):

    @property
    def is_polling_required(self):
        return True

class InterfacePollingMinimizer(BasePollingManager):
    """Monitors ovsdb to determine when polling is required."""

    def __init__(self, root_helper=None,
                 ovsdb_monitor_respawn_interval=(
                     constants.DEFAULT_OVSDBMON_RESPAWN)):

        super(InterfacePollingMinimizer, self).__init__()
        self._monitor = ovsdb_monitor.SimpleInterfaceMonitor(
            root_helper=root_helper,
            respawn_interval=ovsdb_monitor_respawn_interval)

    def start(self):
        self._monitor.start()

    def stop(self):
        self._monitor.stop()

    def _is_polling_required(self):
        # Maximize the chances of update detection having a chance to
        # collect output.
        eventlet.sleep()
        return self._monitor.has_updates