text:
#pragma once

#include <ortc/internal/types.h>

#include <ortc/IMediaStreamTrack.h>
#include <ortc/internal/ortc_RTPMediaEngine.h>

#include <zsLib/MessageQueueAssociator.h>
#include <zsLib/ITimer.h>

#include <zsLib/WeightedMovingAverage.h>

#include <webrtc/video_frame.h>

namespace ortc
{
  namespace internal
  {
    ZS_DECLARE_INTERACTION_PTR(IMediaStreamTrackForSettings);
    ZS_DECLARE_INTERACTION_PTR(IMediaStreamTrackForRTPSender);
    ZS_DECLARE_INTERACTION_PTR(IMediaStreamTrackForRTPSenderChannel);
    ZS_DECLARE_INTERACTION_PTR(IMediaStreamTrackForRTPSenderChannelMediaBase);
    ZS_DECLARE_INTERACTION_PTR(IMediaStreamTrackForRTPSenderChannelAudio);
    ZS_DECLARE_INTERACTION_PTR(IMediaStreamTrackForRTPSenderChannelVideo);
    ZS_DECLARE_INTERACTION_PTR(IMediaStreamTrackForRTPReceiver);
    ZS_DECLARE_INTERACTION_PTR(IMediaStreamTrackForRTPReceiverChannel);
    ZS_DECLARE_INTERACTION_PTR(IMediaStreamTrackForRTPReceiverChannelMediaBase);
    ZS_DECLARE_INTERACTION_PTR(IMediaStreamTrackForRTPReceiverChannelAudio);
    ZS_DECLARE_INTERACTION_PTR(IMediaStreamTrackForRTPReceiverChannelVideo);
    ZS_DECLARE_INTERACTION_PTR(IMediaStreamTrackForMediaDevices);

    ZS_DECLARE_INTERACTION_PTR(IRTPSenderForMediaStreamTrack);
    ZS_DECLARE_INTERACTION_PTR(IRTPSenderChannelForMediaStreamTrack);
    ZS_DECLARE_INTERACTION_PTR(IRTPReceiverForMediaStreamTrack);
    ZS_DECLARE_INTERACTION_PTR(IRTPReceiverChannelForMediaStreamTrack);
    ZS_DECLARE_INTERACTION_PTR(IRTPMediaEngineForMediaStreamTrack);

    ZS_DECLARE_INTERACTION_PROXY(IMediaStreamTrackAsyncDelegate);

    using zsLib::FLOAT;
    using zsLib::INT;

    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    #pragma mark
    #pragma mark IMediaStreamTrackForRTPSender
    #pragma mark

    interaction IMediaStreamTrackForRTPSender
    {
      ZS_DECLARE_TYPEDEF_PTR(IMediaStreamTrackForRTPSender, ForSender)

      ZS_DECLARE_TYPEDEF_PTR(IMediaStreamTrackTypes::Kinds, Kinds)

      virtual PUID getID() const = 0;

      virtual void setSender(IRTPSenderPtr sender) = 0;

      virtual Kinds kind() const = 0;

      virtual void notifyAttachSenderChannel(RTPSenderChannelPtr channel) = 0;
      virtual void notifyDetachSenderChannel(RTPSenderChannelPtr channel) = 0;
    };

    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    #pragma mark
    #pragma mark IMediaStreamTrackForRTPSenderChannel
    #pragma mark

    interaction IMediaStreamTrackForRTPSenderChannel
    {
      ZS_DECLARE_TYPEDEF_PTR(IMediaStreamTrackForRTPSenderChannel, ForSenderChannel)

      virtual PUID getID() const = 0;
    };

    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    #pragma mark
    #pragma mark IMediaStreamTrackForRTPSenderChannelMediaBase
    #pragma mark

    interaction IMediaStreamTrackForRTPSenderChannelMediaBase
    {
      ZS_DECLARE_TYPEDEF_PTR(IMediaStreamTrackForRTPSenderChannelMediaBase, ForSenderChannelMediaBase)

      virtual PUID getID() const = 0;
    };

    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    #pragma mark
    #pragma mark IMediaStreamTrackForRTPSenderChannelAudio
    #pragma mark

    interaction IMediaStreamTrackForRTPSenderChannelAudio : public IMediaStreamTrackForRTPSenderChannelMediaBase
    {
      ZS_DECLARE_TYPEDEF_PTR(IMediaStreamTrackForRTPSenderChannelAudio, ForSenderChannelAudio)

      virtual ~IMediaStreamTrackForRTPSenderChannelAudio() {}
    };

    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    #pragma mark
    #pragma mark IMediaStreamTrackForRTPSenderChannelVideo
    #pragma mark

    interaction IMediaStreamTrackForRTPSenderChannelVideo : public IMediaStreamTrackForRTPSenderChannelMediaBase
    {
      ZS_DECLARE_TYPEDEF_PTR(IMediaStreamTrackForRTPSenderChannelVideo, ForSenderChannelVideo)

      virtual ~IMediaStreamTrackForRTPSenderChannelVideo() {}
    };

    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    #pragma mark
    #pragma mark IMediaStreamTrackForRTPReceiver
    #pragma mark

    interaction IMediaStreamTrackForRTPReceiver
    {
      ZS_DECLARE_TYPEDEF_PTR(IMediaStreamTrackForRTPReceiver, ForReceiver)

      ZS_DECLARE_TYPEDEF_PTR(IMediaStreamTrackTypes::Kinds, Kinds)

      static MediaStreamTrackPtr create(Kinds kind);

      virtual PUID getID() const = 0;

      virtual void setReceiver(IRTPReceiverPtr receiver) = 0;

      virtual void notifyActiveReceiverChannel(RTPReceiverChannelPtr channel) = 0;

      virtual void setH264Rendering(bool h264Rendering) = 0;
      virtual bool isH264Rendering() = 0;
    };

    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    #pragma mark
    #pragma mark IMediaStreamTrackForRTPReceiverChannel
    #pragma mark

    interaction IMediaStreamTrackForRTPReceiverChannel
    {
      ZS_DECLARE_TYPEDEF_PTR(IMediaStreamTrackForRTPReceiverChannel, ForReceiverChannel)

      virtual PUID getID() const = 0;
    };

    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    #pragma mark
    #pragma mark IMediaStreamTrackForRTPReceiverChannelMediabase
    #pragma mark

    interaction IMediaStreamTrackForRTPReceiverChannelMediabase
    {
      ZS_DECLARE_TYPEDEF_PTR(IMediaStreamTrackForRTPReceiverChannelMediabase, ForReceiverChannelMediaBase)

      virtual PUID getID() const = 0;
    };

    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    #pragma mark
    #pragma mark IMediaStreamTrackForRTPReceiverChannelAudio
    #pragma mark

    interaction IMediaStreamTrackForRTPReceiverChannelAudio : public IMediaStreamTrackForRTPReceiverChannelMediabase
    {
      ZS_DECLARE_TYPEDEF_PTR(IMediaStreamTrackForRTPReceiverChannelAudio, ForReceiverChannelAudio)

      virtual ~IMediaStreamTrackForRTPReceiverChannelAudio() {}
    };

    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    #pragma mark
    #pragma mark IMediaStreamTrackForRTPReceiverChannelVideo
    #pragma mark

    interaction IMediaStreamTrackForRTPReceiverChannelVideo : public IMediaStreamTrackForRTPReceiverChannelMediabase
    {
      ZS_DECLARE_TYPEDEF_PTR(IMediaStreamTrackForRTPReceiverChannelVideo, ForReceiverChannelVideo)
      ZS_DECLARE_TYPEDEF_PTR(webrtc::VideoFrame, VideoFrame);

      virtual void renderVideoFrame(VideoFramePtr videoFrame) = 0;
    };

    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    #pragma mark
    #pragma mark IMediaStreamTrackForMediaDevices
    #pragma mark

    interaction IMediaStreamTrackForMediaDevices
    {
      ZS_DECLARE_TYPEDEF_PTR(IMediaStreamTrackForMediaDevices, ForMediaDevices)

      virtual ~IMediaStreamTrackForMediaDevices() {}
    };

    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    #pragma mark
    #pragma mark IMediaStreamTrackForRTPMediaEngine
    #pragma mark

    interaction IMediaStreamTrackForRTPMediaEngine
    {
      ZS_DECLARE_TYPEDEF_PTR(IMediaStreamTrackForRTPMediaEngine, ForMediaEngine)
      ZS_DECLARE_TYPEDEF_PTR(IMediaStreamTrackTypes::Kinds, Kinds)
      ZS_DECLARE_TYPEDEF_PTR(IMediaStreamTrackTypes::TrackConstraints, TrackConstraints)
      ZS_DECLARE_TYPEDEF_PTR(IMediaStreamTrackTypes::Settings, Settings)
      ZS_DECLARE_TYPEDEF_PTR(webrtc::VideoFrame, VideoFrame)

      virtual Kinds kind() const = 0;
      virtual String id() const = 0;
      virtual bool remote() const = 0;

      virtual TrackConstraintsPtr getConstraints() const = 0;
      virtual SettingsPtr getSettings() const = 0;

      virtual void renderVideoFrame(VideoFramePtr videoFrame) = 0;
      virtual void sendCapturedVideoFrame(VideoFramePtr videoFrame) = 0;
    };

    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    #pragma mark
    #pragma mark IMediaStreamTrackForMediaStream
    #pragma mark

    interaction IMediaStreamTrackForMediaStream
    {
      ZS_DECLARE_TYPEDEF_PTR(IMediaStreamTrackForMediaStream, ForMediaStream);

      ZS_DECLARE_TYPEDEF_PTR(IMediaStreamTrackTypes::Kinds, Kinds);

      virtual bool isEnded() const = 0;

      virtual Kinds kind() const = 0;
      virtual String id() const = 0;
      virtual ElementPtr toDebug() const = 0;
    };

    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    #pragma mark
    #pragma mark IMediaStreamTrackAsyncDelegate
    #pragma mark

    interaction IMediaStreamTrackAsyncDelegate
    {
      ZS_DECLARE_TYPEDEF_PTR(IMediaStreamTrackTypes::TrackConstraints, TrackConstraints);
      ZS_DECLARE_TYPEDEF_PTR(IRTPReceiverChannelForMediaStreamTrack, UseReceiverChannel);
      ZS_DECLARE_TYPEDEF_PTR(IRTPSenderChannelForMediaStreamTrack, UseSenderChannel);

      virtual void onResolveStatsPromise(IStatsProvider::PromiseWithStatsReportPtr promise, IStatsReportTypes::StatsTypeSet stats) = 0;

      virtual void onApplyConstraints(
                                      PromisePtr promise,
                                      TrackConstraintsPtr constraints
                                      ) = 0;

      virtual void onSetActiveReceiverChannel(UseReceiverChannelPtr channel) = 0;

      virtual void onAttachSenderChannel(UseSenderChannelPtr channel) = 0;
      virtual void onDetachSenderChannel(UseSenderChannelPtr channel) = 0;
    };

    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    #pragma mark
    #pragma mark MediaStreamTrack
    #pragma mark

    class MediaStreamTrack : public Noop,
                             public MessageQueueAssociator,
                             public SharedRecursiveLock,
                             public IMediaStreamTrack,
                             public IMediaStreamTrackForRTPSender,
                             public IMediaStreamTrackForRTPSenderChannel,
                             public IMediaStreamTrackForRTPSenderChannelAudio,
                             public IMediaStreamTrackForRTPSenderChannelVideo,
                             public IMediaStreamTrackForRTPReceiver,
                             public IMediaStreamTrackForRTPReceiverChannel,
                             public IMediaStreamTrackForRTPReceiverChannelAudio,
                             public IMediaStreamTrackForRTPReceiverChannelVideo,
                             public IMediaStreamTrackForMediaDevices,
                             public IMediaStreamTrackForRTPMediaEngine,
                             public IMediaStreamTrackForMediaStream,
                             public IWakeDelegate,
                             public zsLib::ITimerDelegate,
                             public zsLib::IPromiseSettledDelegate,
                             public IMediaStreamTrackAsyncDelegate
    {
    protected:
      struct make_private {};

    public:
      friend interaction IMediaStreamTrack;
      friend interaction IMediaStreamTrackFactory;
      friend interaction IMediaStreamTrackForRTPSender;
      friend interaction IMediaStreamTrackForRTPSenderChannel;
      friend interaction IMediaStreamTrackForRTPSenderChannelAudio;
      friend interaction IMediaStreamTrackForRTPSenderChannelVideo;
      friend interaction IMediaStreamTrackForRTPReceiver;
      friend interaction IMediaStreamTrackForRTPReceiverChannel;
      friend interaction IMediaStreamTrackForRTPReceiverChannelMediaBase;
      friend interaction IMediaStreamTrackForRTPReceiverChannelAudio;
      friend interaction IMediaStreamTrackForRTPReceiverChannelVideo;
      friend interaction IMediaStreamTrackForMediaDevices;
      friend interaction IMediaStreamTrackForRTPMediaEngine;
      friend interaction IMediaStreamTrackForMediaStream;

      ZS_DECLARE_CLASS_PTR(Transport)
      friend class Transport;

      ZS_DECLARE_TYPEDEF_PTR(IRTPSenderForMediaStreamTrack, UseSender)
      ZS_DECLARE_TYPEDEF_PTR(IRTPSenderChannelForMediaStreamTrack, UseSenderChannel)
      ZS_DECLARE_TYPEDEF_PTR(IRTPReceiverForMediaStreamTrack, UseReceiver)
      ZS_DECLARE_TYPEDEF_PTR(IRTPReceiverChannelForMediaStreamTrack, UseReceiverChannel)
      ZS_DECLARE_TYPEDEF_PTR(IRTPMediaEngineForMediaStreamTrack, UseMediaEngine)
      ZS_DECLARE_TYPEDEF_PTR(IRTPMediaEngineDeviceResource, UseDeviceResource)

      ZS_DECLARE_TYPEDEF_PTR(IMediaStreamTrackTypes::TrackConstraints, TrackConstraints)
      ZS_DECLARE_TYPEDEF_PTR(IMediaStreamTrackTypes::Constraints, Constraints)
      ZS_DECLARE_TYPEDEF_PTR(IMediaStreamTrackTypes::Settings, Settings)

      ZS_DECLARE_TYPEDEF_PTR(IMediaStreamTrackTypes::Kinds, Kinds)
      ZS_DECLARE_TYPEDEF_PTR(webrtc::VideoFrame, VideoFrame)

    public:
      MediaStreamTrack(
                       const make_private &,
                       IMessageQueuePtr queue,
                       Kinds kind,
                       bool remote,
                       TrackConstraintsPtr constraints
                       );

    protected:
      MediaStreamTrack(Noop, IMessageQueuePtr queue = IMessageQueuePtr()) :
        Noop(true),
        MessageQueueAssociator(queue),
        SharedRecursiveLock(SharedRecursiveLock::create())
      {}

      void init();

    public:
      virtual ~MediaStreamTrack();

      static MediaStreamTrackPtr create(
                                        Kinds kind,
                                        bool remote,
                                        TrackConstraintsPtr constraints
                                        );

      static MediaStreamTrackPtr convert(IMediaStreamTrackPtr object);
      static MediaStreamTrackPtr convert(ForSenderPtr object);
      static MediaStreamTrackPtr convert(ForSenderChannelPtr object);
      static MediaStreamTrackPtr convert(ForSenderChannelMediaBasePtr object);
      static MediaStreamTrackPtr convert(ForSenderChannelAudioPtr object);
      static MediaStreamTrackPtr convert(ForSenderChannelVideoPtr object);
      static MediaStreamTrackPtr convert(ForReceiverPtr object);
      static MediaStreamTrackPtr convert(ForReceiverChannelPtr object);
      static MediaStreamTrackPtr convert(ForReceiverChannelMediaBasePtr object);
      static MediaStreamTrackPtr convert(ForReceiverChannelAudioPtr object);
      static MediaStreamTrackPtr convert(ForReceiverChannelVideoPtr object);
      static MediaStreamTrackPtr convert(ForMediaDevicesPtr object);
      static MediaStreamTrackPtr convert(ForMediaEnginePtr object);
      static MediaStreamTrackPtr convert(ForMediaStreamPtr object);

    protected:
      //-----------------------------------------------------------------------
      #pragma mark
      #pragma mark MediaStreamTrack => IStatsProvider
      #pragma mark

      virtual PromiseWithStatsReportPtr getStats(const StatsTypeSet &stats = StatsTypeSet()) const override;

      //-----------------------------------------------------------------------
      #pragma mark
      #pragma mark MediaStreamTrack => IMediaStreamTrack
      #pragma mark

      static ElementPtr toDebug(MediaStreamTrackPtr object);

      virtual PUID getID() const override {return mID;}

      virtual IMediaStreamTrackSubscriptionPtr subscribe(IMediaStreamTrackDelegatePtr delegate) override;

      virtual Kinds kind() const override;
      virtual String id() const override;
      virtual String deviceID() const override;
      virtual String label() const override;
      virtual bool enabled() const override;
      virtual void enabled(bool enabled) override;
      virtual bool muted() const override;
      virtual void muted(bool muted) override;
      virtual bool remote() const override;
      virtual States readyState() const override;

      virtual IMediaStreamTrackPtr clone() const override;

      virtual void stop() override;

      virtual CapabilitiesPtr getCapabilities() const override;
      virtual TrackConstraintsPtr getConstraints() const override;
      virtual SettingsPtr getSettings() const override;

      virtual PromisePtr applyConstraints(const TrackConstraints &constraints) override;

      virtual void setVideoRenderCallback(IMediaStreamTrackRenderCallbackPtr callback) override;
      virtual void setH264Rendering(bool h264Rendering) override;
      virtual bool isH264Rendering() override;

      //-----------------------------------------------------------------------
      #pragma mark
      #pragma mark MediaStreamTrack => IMediaStreamTrackForSettings
      #pragma mark

      //-----------------------------------------------------------------------
      #pragma mark
      #pragma mark MediaStreamTrack => IMediaStreamTrackForRTPSender
      #pragma mark

      // (duplicate) virtual PUID getID() const = 0;

      // (duplicate) virtual Kinds kind() const = 0;

      virtual void setSender(IRTPSenderPtr sender) override;

      virtual void notifyAttachSenderChannel(RTPSenderChannelPtr channel) override;
      virtual void notifyDetachSenderChannel(RTPSenderChannelPtr channel) override;

      //-----------------------------------------------------------------------
      #pragma mark
      #pragma mark MediaStreamTrack => IMediaStreamTrackForRTPSenderChannel
      #pragma mark

      // (duplicate) virtual PUID getID() const = 0;

      //-----------------------------------------------------------------------
      #pragma mark
      #pragma mark MediaStreamTrack => IMediaStreamTrackForRTPSenderChannelMediaBase
      #pragma mark

      // (duplicate) virtual PUID getID() const = 0;

      //-----------------------------------------------------------------------
      #pragma mark
      #pragma mark MediaStreamTrack => IMediaStreamTrackForRTPSenderChannelAudio
      #pragma mark

      //-----------------------------------------------------------------------
      #pragma mark
      #pragma mark MediaStreamTrack => IMediaStreamTrackForRTPSenderChannelVideo
      #pragma mark

      //-----------------------------------------------------------------------
      #pragma mark
      #pragma mark MediaStreamTrack => IMediaStreamTrackForRTPReceiver
      #pragma mark

      static MediaStreamTrackPtr create(Kinds kind);

      // (duplicate) virtual PUID getID() const = 0;

      virtual void setReceiver(IRTPReceiverPtr receiver) override;

      virtual void notifyActiveReceiverChannel(RTPReceiverChannelPtr channel) override;

      // (duplicate) virtual void setH264Rendering(bool h264Rendering) = 0;
      // (duplicate) virtual bool isH264Rendering() = 0;

      //-----------------------------------------------------------------------
      #pragma mark
      #pragma mark MediaStreamTrack => IMediaStreamTrackForRTPReceiverChannel
      #pragma mark

      // (duplicate) virtual PUID getID() const = 0;

      //-----------------------------------------------------------------------
      #pragma mark
      #pragma mark MediaStreamTrack => IMediaStreamTrackForRTPReceiverChannelMediaBase
      #pragma mark

      // (duplicate) virtual PUID getID() const = 0;

      //-----------------------------------------------------------------------
      #pragma mark
      #pragma mark MediaStreamTrack => IMediaStreamTrackForRTPReceiverChannelAudio
      #pragma mark

      //-----------------------------------------------------------------------
      #pragma mark
      #pragma mark MediaStreamTrack => IMediaStreamTrackForRTPReceiverChannelVideo
      #pragma mark

      virtual void renderVideoFrame(VideoFramePtr videoFrame) override;

      //-----------------------------------------------------------------------
      #pragma mark
      #pragma mark MediaStreamTrack => IMediaStreamTrackForMediaDevices
      #pragma mark

      //-----------------------------------------------------------------------
      #pragma mark
      #pragma mark MediaStreamTrack => IMediaStreamTrackForMediaEngine
      #pragma mark

      // (duplicate) virtual Kinds kind() const = 0;
      // (duplicate) virtual String id() const = 0;
      // (duplicate) virtual bool remote() const = 0;

      // (duplicate) virtual TrackConstraintsPtr getConstraints() const = 0;
      // (duplicate) virtual SettingsPtr getSettings() const = 0;

      // (duplicate) virtual void renderVideoFrame(const webrtc::VideoFrame& videoFrame) = 0;

      virtual void sendCapturedVideoFrame(VideoFramePtr videoFrame) override;

      //-----------------------------------------------------------------------
      #pragma mark
      #pragma mark MediaStreamTrack => IMediaStreamTrackForRTPMediaEngine
      #pragma mark

      virtual bool isEnded() const override;
      // (duplicate) virtual Kinds kind() const = 0;
      // (duplicate) virtual String id() const = 0;
      // (duplicate) virtual ElementPtr toDebug() const = 0;

      //-----------------------------------------------------------------------
      #pragma mark
      #pragma mark MediaStreamTrack => IWakeDelegate
      #pragma mark

      virtual void onWake() override;

      //-----------------------------------------------------------------------
      #pragma mark
      #pragma mark MediaStreamTrack => ITimerDelegate
      #pragma mark

      virtual void onTimer(ITimerPtr timer) override;

      //-----------------------------------------------------------------------
      #pragma mark
      #pragma mark MediaStreamTrack => IPromiseSettledDelegate
      #pragma mark

      virtual void onPromiseSettled(PromisePtr promise) override;

      //-----------------------------------------------------------------------
      #pragma mark
      #pragma mark MediaStreamTrack => IMediaStreamTrackAsyncDelegate
      #pragma mark

      virtual void onResolveStatsPromise(IStatsProvider::PromiseWithStatsReportPtr promise, IStatsReportTypes::StatsTypeSet stats) override;

      virtual void onApplyConstraints(
                                      PromisePtr promise,
                                      TrackConstraintsPtr constraints
                                      ) override;

      virtual void onSetActiveReceiverChannel(UseReceiverChannelPtr channel) override;

      virtual void onAttachSenderChannel(UseSenderChannelPtr channel) override;
      virtual void onDetachSenderChannel(UseSenderChannelPtr channel) override;

    protected:
      //-----------------------------------------------------------------------
      #pragma mark
      #pragma mark MediaStreamTrack => (internal)
      #pragma mark

      Log::Params log(const char *message) const;
      static Log::Params slog(const char *message);
      Log::Params debug(const char *message) const;
      virtual ElementPtr toDebug() const;

      bool isShuttingDown() const;
      bool isShutdown() const;

      void step();
      bool stepDevicePromise();
      bool stepSetupDevice();

      void cancel();

      void setState(States state);
      void setError(WORD error, const char *reason = NULL);

    protected:
      //-----------------------------------------------------------------------
      #pragma mark
      #pragma mark MediaStreamTrack => (data)
      #pragma mark

      AutoPUID mID;
      MediaStreamTrackWeakPtr mThisWeak;
      MediaStreamTrackPtr mGracefulShutdownReference;

      IMediaStreamTrackDelegateSubscriptions mSubscriptions;

      States mCurrentState {State_Live};

      WORD mLastError {};
      String mLastErrorReason;

      String mTrackID;
      Kinds mKind {Kind_First};
      bool mRemote {false};
      String mDeviceID;
      bool mH264Rendering {false};

      UseSenderWeakPtr mSender;
      UseSenderChannelWeakPtr mSenderChannel;
      UseReceiverWeakPtr mReceiver;
      UseReceiverChannelWeakPtr mReceiverChannel;

      CapabilitiesPtr mCapabilities;
      TrackConstraintsPtr mConstraints;
      SettingsPtr mSettings;

      PromiseWithRTPMediaEngineDeviceResourcePtr mDeviceResourceLifetimeHolderPromise;
      UseDeviceResourcePtr mDeviceResource;
      IMediaStreamTrackRenderCallbackPtr mVideoRendererCallback;

      PromisePtr mCloseDevicePromise;

      ITimerPtr mStatsTimer;
    };

    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
    #pragma mark
    #pragma mark IMediaStreamTrackFactory
    #pragma mark

    interaction IMediaStreamTrackFactory
    {
      ZS_DECLARE_TYPEDEF_PTR(IMediaStreamTrackTypes::TrackConstraints, TrackConstraints)

      static IMediaStreamTrackFactory &singleton();

      virtual MediaStreamTrackPtr create(
                                         IMediaStreamTrackTypes::Kinds kind,
                                         bool remote,
                                         TrackConstraintsPtr constraints
                                         );
      virtual MediaStreamTrackPtr create(IMediaStreamTrackTypes::Kinds kind);
    };

    class MediaStreamTrackFactory : public IFactory<IMediaStreamTrackFactory> {};
  }
}

ZS_DECLARE_PROXY_BEGIN(ortc::internal::IMediaStreamTrackAsyncDelegate)
ZS_DECLARE_PROXY_TYPEDEF(ortc::IStatsProvider::PromiseWithStatsReportPtr, PromiseWithStatsReportPtr)
ZS_DECLARE_PROXY_TYPEDEF(ortc::IStatsReportTypes::StatsTypeSet, StatsTypeSet)
ZS_DECLARE_PROXY_TYPEDEF(zsLib::PromisePtr, PromisePtr)
ZS_DECLARE_PROXY_TYPEDEF(ortc::IMediaStreamTrackTypes::TrackConstraintsPtr, TrackConstraintsPtr)
ZS_DECLARE_PROXY_TYPEDEF(ortc::internal::IMediaStreamTrackAsyncDelegate::UseReceiverChannelPtr, UseReceiverChannelPtr)
ZS_DECLARE_PROXY_TYPEDEF(ortc::internal::IMediaStreamTrackAsyncDelegate::UseSenderChannelPtr, UseSenderChannelPtr)
ZS_DECLARE_PROXY_METHOD_2(onResolveStatsPromise, PromiseWithStatsReportPtr, StatsTypeSet)
ZS_DECLARE_PROXY_METHOD_2(onApplyConstraints, PromisePtr, TrackConstraintsPtr)
ZS_DECLARE_PROXY_METHOD_1(onSetActiveReceiverChannel, UseReceiverChannelPtr)
ZS_DECLARE_PROXY_METHOD_1(onAttachSenderChannel, UseSenderChannelPtr)
ZS_DECLARE_PROXY_METHOD_1(onDetachSenderChannel, UseSenderChannelPtr)
ZS_DECLARE_PROXY_END()


text:
var expect = require('expect.js'),
nunit = require('../tasks/nunit.js'),
path = require('path');

describe('nunit', function() {

    it('should find a default assembly', function() {

        var assemblies = nunit.findTestAssemblies(['test/Data/Solution/Solution.sln']);
        expect(assemblies.length).to.be(1);
        expect(assemblies[0]).to.be(path.normalize('test/Data/Solution/bin/Debug/Project.ClassLibrary.dll'));

    });

    it('should find the assemblies matching your configuration', function() {

        var assemblies = nunit.findTestAssemblies(['test/Data/Solution/Solution.sln'], { config: 'debug' });
        expect(assemblies.length).to.be(1);
        expect(assemblies[0]).to.be(path.normalize('test/Data/Solution/bin/Debug/Project.ClassLibrary.dll'));

    });

    it('should find no assemblies when matching your bad configuration', function() {

        expect(function () {
          nunit.findTestAssemblies(['test/Data/Solution/Solution.sln'], { config: 'release' });
        }).throwError();

    });

});

redpajama_set_name: RedPajamaGithub


text:
#ifndef _M32R_SECTIONS_H
#define _M32R_SECTIONS_H

/* nothing to see, move along */
#include <asm-generic/sections.h>

#endif	/* _M32R_SECTIONS_H */


text:
import { connect } from 'react-redux'

import ArchivedYear from './components/ArchivedYear'

export default connect()(ArchivedYear)


text:
package org.apache.calcite.util.mapping;

import java.util.Iterator;

/**
 * A <dfn>Mapping</dfn> is a relationship between a source domain to target
 * domain of integers.
 *
 *
This interface represents the most general possible mapping. Depending on
 * the {@link MappingType} of a particular mapping, some of the operations may
 * not be applicable. If you call the method, you will receive a runtime error.
 * For instance:
 *
 *

 *
If a target has more than one source, then the method
 *     {@link #getSource(int)} will throw
 *     {@link Mappings.TooManyElementsException}.
 *
If a source has no targets, then the method {@link #getTarget} will throw
 *     {@link Mappings.NoElementException}.
 *

 */
public interface Mapping
    extends Mappings.FunctionMapping,
    Mappings.SourceMapping,
    Mappings.TargetMapping,
    Iterable<IntPair> {
  //~ Methods ----------------------------------------------------------------

  /**
   * Returns an iterator over the elements in this mapping.
   *
   *
This method is optional; implementations may throw
   * {@link UnsupportedOperationException}.
   */
  Iterator<IntPair> iterator();

  /**
   * Returns the number of sources. Valid sources will be in the range 0 ..
   * sourceCount.
   */
  int getSourceCount();

  /**
   * Returns the number of targets. Valid targets will be in the range 0 ..
   * targetCount.
   */
  int getTargetCount();

  MappingType getMappingType();

  /**
   * Returns whether this mapping is the identity.
   */
  boolean isIdentity();

  /**
   * Removes all elements in the mapping.
   */
  void clear();

  /**
   * Returns the number of elements in the mapping.
   */
  int size();
}

// End Mapping.java


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

<layout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

        <variable
            name="model"
            type="jp.hazuki.yuzubrowser.bookmark.overflow.model.OverflowMenuModel"/>
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:background="?attr/selectableItemBackground">

        <TextView
            android:id="@+id/titleTextView"
            style="@style/TextAppearance.ListTitle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="16dp"
            android:layout_marginBottom="8dp"
            android:text="@{model.title}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/checkBox3"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.6"/>

        <CheckBox
            android:id="@+id/checkBox3"
            android:layout_width="40dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="8dp"
            android:checked="@{model.enable}"
            android:focusable="false"
            android:clickable="false"
            android:background="@android:color/transparent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>


text:
package gov.nih.nci.cagrid.introduce.upgrade.common;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class UpgradeStatus extends StatusBase {

    List introduceUpgradesStatus;

    public UpgradeStatus() {
        introduceUpgradesStatus = new ArrayList();
    }

    public void addIntroduceUpgradeStatus(IntroduceUpgradeStatus introduceUpgradeStatus) {
        this.introduceUpgradesStatus.add(introduceUpgradeStatus);
    }

    public List getIntroduceUpgradesStatus() {
        return this.introduceUpgradesStatus;
    }

    public String toString(){
        StringBuffer sb = new StringBuffer();
        Iterator iStatusI = introduceUpgradesStatus.iterator();
        while(iStatusI.hasNext()){
            IntroduceUpgradeStatus iStatus = (IntroduceUpgradeStatus)iStatusI.next();
            sb.append("Name: " + iStatus.getName() + "\n");
            sb.append("Type: " + iStatus.getType() + "\n");
            sb.append("From Version: " + iStatus.getFromVersion() + "\n");
            sb.append("To Version: " + iStatus.getToVersion() + "\n");
            sb.append("Status: " + iStatus.getStatus() + "\n\n");
            sb.append("Description: \n" + iStatus.getDescription() + "\n");
            List issues = iStatus.getIssues();
            Iterator issuesI = issues.iterator();
            while(issuesI.hasNext()){
                Issue issue = (Issue)issuesI.next();
                sb.append("\tIssue: " + issue.getIssue() + "\n");
                sb.append("\tResolution: " + issue.getResolution() + "\n\n");
            }
            sb.append("\n\n");

            Iterator eStatusI = iStatus.getExtensionUgradesStatus().iterator();
            while(eStatusI.hasNext()){
                ExtensionUpgradeStatus eStatus = (ExtensionUpgradeStatus)eStatusI.next();
                sb.append("  Name: " + eStatus.getName() + "\n");
                sb.append("  Type: " + eStatus.getType() + "\n");
                sb.append("  From Version: " + eStatus.getFromVersion() + "\n");
                sb.append("  To Version: " + eStatus.getToVersion() + "\n");
                sb.append("  Status: " + eStatus.getStatus() + "\n\n");
                sb.append("  Description: \n" + eStatus.getDescription() + "\n");
                issues = eStatus.getIssues();
                issuesI = issues.iterator();
                while(issuesI.hasNext()){
                    Issue issue = (Issue)issuesI.next();
                    sb.append("\tIssue: " + issue.getIssue() + "\n");
                    sb.append("\tResolution: " + issue.getResolution() + "\n\n");
                }
                sb.append("\n\n");

            }
        }

        return sb.toString();
    }

}


text:
FROM ubuntu:vivid
MAINTAINER craig.patten@ersa.edu.au

ENV DEBIAN_FRONTEND noninteractive
ENV INITRD No
ENV LANG en_AU.UTF-8

RUN echo "Acquire::http {No-Cache=True;};" > /etc/apt/apt.conf.d/no-cache
RUN echo force-unsafe-io > /etc/dpkg/dpkg.cfg.d/02apt-speedup

RUN apt-get update && apt-get -y install curl python3-dev language-pack-en-base postgresql-client libpq-dev build-essential
RUN apt-get clean

RUN curl -sL https://bootstrap.pypa.io/get-pip.py | python3

RUN pip install --no-cache-dir gunicorn

RUN adduser --gecos "" --disabled-password --disabled-login ubuntu

EXPOSE 5000


text:
/*global use */
"ODSA strict";
// Search slideshow
$(document).ready(function () {
  var av_name = "BSTsearchCON";
  var config = ODSA.UTILS.loadConfig({"av_name": av_name}),
      interpret = config.interpreter,       // get the interpreter
      code = config.code;                   // get the code object
  var av = new JSAV(av_name);
  var pseudo = av.code(code);

  var bstTop = 45;
  var bt = av.ds.binarytree({top: bstTop, left: 10, visible: true, nodegap: 15});
  bt.root(37);
  var rt = bt.root();
  rt.left(24);
  rt.left().left(7);
  rt.left().left().left(2);
  rt.left().right(32);
  rt.right(42);
  rt.right().left(42);
  rt.right().left().left(40);
  rt.right().right(120);
  bt.layout();

  var rt1 = av.pointer("rt", bt.root(), {anchor: "right top"});

  // Slide 1
  av.umsg(interpret("av_c1"));
  pseudo.setCurrentLine("sig");
  av.displayInit();

  // Slide 2
  av.umsg(interpret("av_c2"));
  pseudo.setCurrentLine("checknull");
  av.step();

  // Slide 3
  av.umsg(interpret("av_c3"));
  pseudo.setCurrentLine("checkgreater");
  av.step();

  // Slide 4
  av.umsg(interpret("av_c4"));
  pseudo.setCurrentLine("visitleft");
  av.step();

  // Slide 5
  av.umsg(interpret("av_c5"));
  pseudo.setCurrentLine("sig");
  bt.root().addClass("processing");
  rt1.target(bt.root().left(), {anchor: "left top"});
  av.step();

  // Slide 6
  av.umsg(interpret("av_c2"));
  pseudo.setCurrentLine("checknull");
  av.step();

  // Slide 7
  av.umsg(interpret("av_c16"));
  pseudo.setCurrentLine("checkgreater");
  av.step();

  // Slide 8
  av.umsg(interpret("av_c17"));
  pseudo.setCurrentLine("checkequal");
  av.step();

  // Slide 9
  av.umsg(interpret("av_c7"));
  pseudo.setCurrentLine("visitright");
  av.step();

  // Slide 10
  av.umsg(interpret("av_c9"));
  pseudo.setCurrentLine("sig");
  bt.root().left().addClass("processing");
  rt1.target(bt.root().left().right(), {anchor: "right top"});
  av.step();

  // Slide 11
  av.umsg(interpret("av_c2"));
  pseudo.setCurrentLine("checknull");
  av.step();

  // Slide 12
  av.umsg(interpret("av_c16"));
  pseudo.setCurrentLine("checkgreater");
  av.step();

  // Slide 13
  av.umsg(interpret("av_c11"));
  pseudo.setCurrentLine("checkequal");
  av.step();

  // Slide 14
  av.umsg(interpret("av_c12"));
  pseudo.setCurrentLine("found");
  av.step();

  // Slide 15
  av.umsg(interpret("av_c13"));
  bt.root().left().removeClass("processing");
  rt1.target(bt.root().left(), {anchor: "left top"});
  pseudo.setCurrentLine("visitright");
  av.step();

  // Slide 16
  av.umsg(interpret("av_c14"));
  bt.root().removeClass("processing");
  rt1.target(bt.root(), {anchor: "right top"});
  pseudo.setCurrentLine("visitleft");
  av.step();

  // Slide 17
  av.umsg(interpret("av_c15"));
  pseudo.setCurrentLine("end");
  av.recorded();
});


text:
/*

    A `gpii.express.middleware.error` component that uses the standard renderer to return an error to a user, see the
    documentation for details:

    https://github.com/GPII/gpii-handlebars/blob/master/docs/errorRenderingMiddleware.md

 */
/* eslint-env node */
"use strict";
var fluid = require("infusion");
var gpii  = fluid.registerNamespace("gpii");

fluid.require("gpii-express");

fluid.registerNamespace("gpii.handlebars.errorRenderingMiddleware");
gpii.handlebars.errorRenderingMiddleware.renderError = function (that, error, request, response, next) {
    if (gpii.handlebars.errorRenderingMiddleware.isOurContentType(that, request)) {
        // TODO: figure out the message bundle for this request and merge with the error so that we can use i18n in errors.
        response.status(that.options.statusCode).render(that.options.templateKey, error);
    }
    else {
        next(error);
    }
};

/**
 *
 * Confirm that this request matches our content type, if we have them.
 *
 * @param {Object} that - The middleware component itself.
 * @param {Object} request - The request object.
 * @return {Boolean} - Returns `true` if the request accepts a content type we support, or `false` if it doesn't.
 *
 */
gpii.handlebars.errorRenderingMiddleware.isOurContentType = function (that, request) {
    if (that.options.contentType) {
        var contentTypes = fluid.makeArray(that.options.contentType);
        return fluid.find(contentTypes, function (contentType) {
            if (request.accepts(contentType)) {
                return true;
            }
        }, false);
    }
    // If we have no content type, we respond to everything.
    else {
        return true;
    }
};

fluid.defaults("gpii.handlebars.errorRenderingMiddleware", {
    gradeNames:  ["gpii.express.middleware.error"],
    statusCode:  500,
    contentType: "text/html",
    namespace:   "errorRenderingMiddleware", // Namespace to make it easier for other routers to put themselves in the chain before or after us.
    method:      "use",
    invokers: {
        middleware: {
            funcName: "gpii.handlebars.errorRenderingMiddleware.renderError",
            args:     ["{that}", "{arguments}.0", "{arguments}.1", "{arguments}.2", "{arguments}.3"] // error, request, response, next
        }
    }
});


text:
package com.oneops.inductor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import org.apache.commons.exec.ExecuteStreamHandler;
import org.apache.log4j.Logger;

import com.google.gson.Gson;

public class OutputHandler implements ExecuteStreamHandler {
	private String logKey;
	private Logger logger;
	private static String REBOOT_FLAG = "***REBOOT_FLAG***";
	private static String RESULT_KEY = "***RESULT:";
	private static String FAULT_KEY = "***FAULT:";
	private static String TAG_KEY = "***TAG:";
	private static String RESULTJSON_KEY = "***RESULTJSON:";

	private static String ADDITIONAL_INFO_KEY = "***ADDITIONAL_INFO:";

	private ProcessResult result;

	final private Gson gson = new Gson();

	// limit amt of output a cmd can log
	private int rowCount = 0;
	private static int maxRowCount = 2000;

	public OutputHandler(Logger logger, String logKey, ProcessResult result) {
		this.logger = logger;
		this.logKey = logKey;
		this.result = result;
	}

	@Override
	public void setProcessOutputStream(InputStream is) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		try {

			for (String line = reader.readLine(); line != null; line = reader
					.readLine()) {

				if (rowCount < maxRowCount) {

					// no print private keys
					if (!line.contains("PRIVATE KEY")) {
						logger.info(logKey + "cmd out: " + line);
						result.appendStdOut(line + "\n");
					}

					if (line.indexOf(REBOOT_FLAG) > -1)
						result.setRebooting(true);

					int keyIndex = line.indexOf(RESULT_KEY);
					if (keyIndex == 0) {
						String withOutResultKey = line.substring(keyIndex + 10,
								line.length());
						String k = withOutResultKey.substring(0,
								withOutResultKey.indexOf("="));
						String v = withOutResultKey.substring(
								withOutResultKey.indexOf("=") + 1,
								withOutResultKey.length());
						result.getResultMap().put(k, v);
						logger.debug(logKey + " resultCi " + k + ": " + v);
					}

					keyIndex = line.indexOf(FAULT_KEY);
					if (keyIndex == 0) {
						String withOutResultKey = line.substring(keyIndex + 9,
								line.length());
						String k = withOutResultKey.substring(0,
								withOutResultKey.indexOf("="));
						String v = withOutResultKey.substring(
								withOutResultKey.indexOf("=") + 1,
								withOutResultKey.length());
						result.getFaultMap().put(k, v);
						logger.info(logKey + " fault: " + k + ": " + v);
					}

					keyIndex = line.indexOf(TAG_KEY);
					if (keyIndex == 0) {
						String withOutResultKey = line.substring(keyIndex + 7,
								line.length());
						String k = withOutResultKey.substring(0,
								withOutResultKey.indexOf("="));
						String v = withOutResultKey.substring(
								withOutResultKey.indexOf("=") + 1,
								withOutResultKey.length());
						result.getTagMap().put(k, v);
						logger.info(logKey + " tag: " + k + ": " + v);
					}

					// multi-line attributes encoded w/ json
					keyIndex = line.indexOf(RESULTJSON_KEY);
					if (keyIndex == 0) {
						int firstEquals = line.indexOf("=");
						String key = line.substring(keyIndex + 14, firstEquals);
						String val = line.substring(firstEquals + 1,
								line.length());

						MultiLineValue value = gson.fromJson(val,
								MultiLineValue.class);

						result.getResultMap().put(key, value.getValue());
						if (!value.getValue().contains("PRIVATE KEY"))
							logger.debug(logKey + " resultCi " + key + ": "
									+ val);

					}

					keyIndex = line.indexOf(ADDITIONAL_INFO_KEY);
					if (keyIndex > -1) {
						int firstEquals = line.indexOf("=", keyIndex);
						if (firstEquals > -1) {
							String key = line.substring(keyIndex + ADDITIONAL_INFO_KEY.length(), firstEquals).trim();
							String value = line.substring(firstEquals + 1);
							logger.info(ADDITIONAL_INFO_KEY + " key: " + key + ", value: " + value);
							result.getAdditionInfoMap().put(key, value);
						}
					}

					// set last error to use if faults are empty
					keyIndex = line.indexOf("ERROR:");
					if (keyIndex > -1) {
						result.setLastError(line.substring(keyIndex+6,line.length()));
					}

				} else if (rowCount > maxRowCount) {
					continue;
				} else if (rowCount == maxRowCount) {
					logger.warn(logKey
							+ " hit max amt of output per process of "
							+ maxRowCount
							+ " lines. Please run the workorder on the box: chef-solo -c /home/oneops/cookbooks/chef.rb -j /opt/oneops/workorder/someworkorder ");
				}

				rowCount++;
			}

		} catch (IOException e) {
			logger.error("Error parsing output of command: ", e);
		}

	}

	@Override
	public void setProcessErrorStream(InputStream is) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		try {

			for (String line = reader.readLine(); line != null; line = reader
					.readLine()) {

				// allow 2x to get errors
				if (rowCount < maxRowCount * 2) {

					logger.info(logKey + "cmd error: " + line);
					result.appendStdErr(line + "\n");

				} else if (rowCount > maxRowCount * 2) {
					continue;
				} else if (rowCount == maxRowCount * 2) {
					logger.warn(logKey
							+ " hit max amt of output per process of "
							+ maxRowCount
							+ " lines. Please run the workorder on the box: chef-solo -c /home/oneops/cookbooks/chef.rb -j /opt/oneops/workorder/someworkorder ");
				}

				rowCount++;
			}

		} catch (IOException e) {
			logger.error("Error parsing output of command: ", e);
		}
	}

	@Override
	public void start() throws IOException {

	}

	@Override
	public void stop() {

	}

	@Override
	public void setProcessInputStream(OutputStream arg0) throws IOException {
		// TODO Auto-generated method stub

	}

}


text:
import React from 'react';
import { shallow } from 'enzyme';
import Checkbox from './Checkbox';

describe('Checkbox', () => {
  const requiredProps = {
    id: 'testCheckbox',
    label: 'Still in role',
    checked: false,
    onChange: () => {}
  };

  it('should render with simple props', () => {
    const wrapper = shallow(<Checkbox {...requiredProps} />);
    expect(wrapper).toMatchSnapshot();
  });

  it('should render as checked', () => {
    const wrapper = shallow(<Checkbox {...requiredProps} checked={true} />);
    const inputChecked = wrapper.find('input').prop('checked');
    expect(inputChecked).toEqual(true);
  });

  it('should pass through the value', () => {
    const wrapper = shallow(
      <Checkbox {...requiredProps} value="foo" checked={true} />
    );
    const inputValue = wrapper.find('input').prop('value');
    expect(inputValue).toEqual('foo');
  });

  it('should render with className', () => {
    const className = 'testClassname';
    const wrapper = shallow(
      <Checkbox {...requiredProps} className={className} />
    );
    expect(wrapper).toMatchSnapshot();
  });

  it('should render the invalid style for tone="critical" even if the field is valid', () => {
    expect(
      shallow(<Checkbox {...requiredProps} tone="critical" valid={true} />)
    ).toMatchSnapshot();
  });

  it('should render the invalid style for valid={false} where no tone is set. It should also pass the valid prop', () => {
    expect(
      shallow(<Checkbox {...requiredProps} valid={false} />)
    ).toMatchSnapshot();
  });

  it('should not render the invalid style if tone is set to positive', () => {
    expect(
      shallow(<Checkbox {...requiredProps} valid={false} tone="positive" />)
    ).toMatchSnapshot();
  });

  it('should render with standard checkbox style', () => {
    const wrapper = shallow(<Checkbox {...requiredProps} type="standard" />);
    expect(wrapper).toMatchSnapshot();
  });

  it('should render with button style', () => {
    const wrapper = shallow(<Checkbox {...requiredProps} type="button" />);
    expect(wrapper).toMatchSnapshot();
  });

  it('should invoke the change handler', () => {
    const onChange = jest.fn();
    const props = { ...requiredProps, onChange, checked: false };
    const checkedEvent = { target: { checked: true } };
    const wrapper = shallow(<Checkbox {...props} />);
    wrapper.find('input').simulate('change', checkedEvent);
    expect(onChange).toBeCalledWith(checkedEvent);
  });

  it('should invoke the focus handler', () => {
    const onFocus = jest.fn();
    const props = { ...requiredProps, onFocus, checked: false };
    const wrapper = shallow(<Checkbox {...props} />);
    wrapper.find('input').simulate('focus');
    expect(onFocus.mock.calls.length).toEqual(1);
  });

  it('should invoke the blur handler', () => {
    const onBlur = jest.fn();
    const props = { ...requiredProps, onBlur, checked: false };
    const wrapper = shallow(<Checkbox {...props} />);
    wrapper.find('input').simulate('blur');
    expect(onBlur.mock.calls.length).toEqual(1);
  });

  describe('inputProps', () => {
    it('should invoke the change handler', () => {
      const handleChange = jest.fn();
      const props = {
        ...requiredProps,
        inputProps: { onChange: handleChange, checked: false }
      };
      const checkedEvent = { target: { checked: true } };
      const wrapper = shallow(<Checkbox {...props} />);
      wrapper.find('input').simulate('change', checkedEvent);
      expect(handleChange).toBeCalledWith(checkedEvent);
    });

    it('should render as checked', () => {
      const wrapper = shallow(
        <Checkbox {...requiredProps} inputProps={{ checked: true }} />
      );
      const inputChecked = wrapper.find('input').prop('checked');
      expect(inputChecked).toEqual(true);
    });

    it('should pass through other props to the input', () => {
      const wrapper = shallow(
        <Checkbox
          {...requiredProps}
          inputProps={{ 'data-automation': 'first-name-field' }}
        />
      );
      expect(wrapper).toMatchSnapshot();
    });
  });

  describe('FieldMessage', () => {
    it('should render field message when passed', () => {
      const wrapper = shallow(
        <Checkbox
          {...requiredProps}
          inputProps={{ checked: false }}
          message="Field is invalid"
          valid={false}
        />
      );
      expect(wrapper).toMatchSnapshot();
    });
  });
});


text:
package deburnat.transade.gui.components

import swing.{TextArea, TextField}

import java.awt.Color

import deburnat.transade.gui.admins.GuiAdmin.monoFont

/**
 * An algorithm for data transfer.
 * Project name: deburnat
 * Date: 9/4/13
 * Time: 8:19 PM
 * @author Patrick Meppe (tapmeppe@gmail.com)
 */
protected[gui] class MonoTextField(_text: String) extends TextField(_text){
  def this() = this("")
  font = monoFont

  protected val (off, on) = (Color.LIGHT_GRAY, Color.BLACK)
}

protected[gui] class MonoNotEditableTextArea(_text: String) extends TextArea(_text){
  editable = false
  font = monoFont
  background = new Color(240, 240, 240)
}


text:
#include "CSSStyleRuleImp.h"
#include "CSSStyleDeclarationImp.h"

namespace org { namespace w3c { namespace dom { namespace bootstrap {

using namespace css;

// CSSRule
unsigned short CSSStyleRuleImp::getType()
{
    return CSSRule::STYLE_RULE;
}

std::u16string CSSStyleRuleImp::getCssText()
{
    return getSelectorText() + u": " + styleDeclaration.getCssText();
}

// CSSStyleRule
std::u16string CSSStyleRuleImp::getSelectorText()
{
    std::u16string text;
    if (selectorsGroup)
        selectorsGroup->serialize(text);
    return text;
}

void CSSStyleRuleImp::setSelectorText(const std::u16string& selectorText)
{
    // TODO: implement me!
}

CSSStyleDeclaration CSSStyleRuleImp::getStyle()
{
    return styleDeclaration;
}

CSSStyleRuleImp::CSSStyleRuleImp(CSSSelectorsGroup* selectorsGroup, css::CSSStyleDeclaration styleDeclaration) :
    selectorsGroup(selectorsGroup),
    styleDeclaration(styleDeclaration)
{
    if (CSSStyleDeclarationImp* imp = dynamic_cast<CSSStyleDeclarationImp*>(styleDeclaration.self()))
        imp->setParentRule(this);
}

}}}}  // org::w3c::dom::bootstrap


text:
<!DOCTYPE html>

  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Example Page</title>
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="css/react-bootstrap-switch.css">

Loading...


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = instantiation;

var _assert = require('assert');

var _assert2 = _interopRequireDefault(_assert);

var _helpers = require('./helpers');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/* eslint no-unused-vars: 0 */
/**
 * Graphology Instantiation Specs
 * ===============================
 *
 * Testing the instantiation of the graph.
 */
var CONSTRUCTORS = ['DirectedGraph', 'UndirectedGraph', 'MultiDirectedGraph', 'MultiUndirectedGraph'];

var OPTIONS = [{ multi: false, type: 'directed' }, { multi: false, type: 'undirected' }, { multi: true, type: 'directed' }, { multi: true, type: 'undirected' }];

function instantiation(Graph, implementation, checkers) {
  var invalid = checkers.invalid;

  return {
    'Static #.from method': {

      'it should be possible to create a Graph from a Graph instance.': function itShouldBePossibleToCreateAGraphFromAGraphInstance() {
        var graph = new Graph();
        graph.addNodesFrom(['John', 'Thomas']);
        graph.addEdge('John', 'Thomas');

        var other = Graph.from(graph);

        _assert2.default.deepEqual(graph.nodes(), other.nodes());
        _assert2.default.deepEqual(graph.edges(), other.edges());
      },

      'it should be possible to create a Graph from a serialized graph': function itShouldBePossibleToCreateAGraphFromASerializedGraph() {
        var graph = Graph.from({
          nodes: [{ key: 'John' }, { key: 'Thomas' }],
          edges: [{ source: 'John', target: 'Thomas' }]
        });

        _assert2.default.deepEqual(graph.nodes(), ['John', 'Thomas']);
        _assert2.default.strictEqual(graph.hasEdge('John', 'Thomas'), true);
      },

      'it should be possible to provide options.': function itShouldBePossibleToProvideOptions() {
        var graph = Graph.from({
          node: [{ key: 'John' }],
          attributes: {
            name: 'Awesome graph'
          }
        }, { type: 'directed' });

        _assert2.default.strictEqual(graph.type, 'directed');
        _assert2.default.strictEqual(graph.getAttribute('name'), 'Awesome graph');
      }
    },

    'Options': {

      /**
       * allowSelfLoops
       */
      'allowSelfLoops': {

        'providing a non-boolean value should throw.': function providingANonBooleanValueShouldThrow() {
          _assert2.default.throws(function () {
            var graph = new Graph({ allowSelfLoops: 'test' });
          }, invalid());
        }
      },

      /**
       * defaultEdgeAttributes
       */
      'defaultEdgeAttributes': {

        'providing something other than a plain object should throw.': function providingSomethingOtherThanAPlainObjectShouldThrow() {
          _assert2.default.throws(function () {
            var graph = new Graph({ defaultEdgeAttributes: 'test' });
          }, invalid());
        },

        'it should set default attributes on edges.': function itShouldSetDefaultAttributesOnEdges() {
          var graph = new Graph({ defaultEdgeAttributes: { type: 'KNOWS' }, multi: true });

          graph.addNodesFrom(['John', 'Martha']);

          var edge = graph.addEdge('John', 'Martha');

          _assert2.default.deepEqual(graph.getEdgeAttributes(edge), { type: 'KNOWS' });

          edge = graph.addEdge('John', 'Martha', { weight: 3 });

          _assert2.default.deepEqual(graph.getEdgeAttributes(edge), { weight: 3, type: 'KNOWS' });

          edge = graph.addEdge('John', 'Martha', { type: 'LIKES' });

          _assert2.default.deepEqual(graph.getEdgeAttributes(edge), { type: 'LIKES' });
        }
      },

      /**
       * defaultNodeAttributes
       */
      'defaultNodeAttributes': {

        'providing something other than a plain object should throw.': function providingSomethingOtherThanAPlainObjectShouldThrow() {
          _assert2.default.throws(function () {
            var graph = new Graph({ defaultNodeAttributes: 'test' });
          }, invalid());
        },

        'it should set default attributes on nodes.': function itShouldSetDefaultAttributesOnNodes() {
          var graph = new Graph({ defaultNodeAttributes: { eyes: 'blue' } });

          graph.addNode('John');

          _assert2.default.deepEqual(graph.getNodeAttributes('John'), { eyes: 'blue' });

          graph.addNode('Thomas', { age: 23 });

          _assert2.default.deepEqual(graph.getNodeAttributes('Thomas'), { age: 23, eyes: 'blue' });

          graph.addNode('Martha', { eyes: 'green' });

          _assert2.default.deepEqual(graph.getNodeAttributes('Martha'), { eyes: 'green' });
        }
      },

      /**
       * edgeKeyGenerator
       */
      'edgeKeyGenerator': {

        'providing something other than a function should throw.': function providingSomethingOtherThanAFunctionShouldThrow() {
          _assert2.default.throws(function () {
            var graph = new Graph({ edgeKeyGenerator: 'test' });
          }, invalid());
        },

        'it should correctly give the edge an id.': function itShouldCorrectlyGiveTheEdgeAnId() {
          var edgeKeyGenerator = function edgeKeyGenerator(_ref) {
            var source = _ref.source,
                target = _ref.target;

            return source + '->' + target;
          };

          var graph = new Graph({ edgeKeyGenerator: edgeKeyGenerator });
          graph.addNodesFrom(['John', 'Martha', 'Clark']);
          graph.addEdge('John', 'Martha');
          graph.addEdge('Martha', 'Clark');

          _assert2.default.deepEqual(graph.edges(), ['John->Martha', 'Martha->Clark']);
        }
      },

      /**
       * multi
       */
      'multi': {

        'providing a non-boolean value should throw.': function providingANonBooleanValueShouldThrow() {
          _assert2.default.throws(function () {
            var graph = new Graph({ multi: 'test' });
          }, invalid());
        }
      },

      /**
       * type
       */
      'type': {

        'providing an invalid type should throw.': function providingAnInvalidTypeShouldThrow() {
          _assert2.default.throws(function () {
            var graph = new Graph({ type: 'test' });
          }, invalid());
        }
      }
    },

    'Constructors': {

      'all alternative constructors should be available.': function allAlternativeConstructorsShouldBeAvailable() {
        CONSTRUCTORS.forEach(function (name) {
          return (0, _assert2.default)(name in implementation);
        });
      },

      'alternative constructors should have the correct options.': function alternativeConstructorsShouldHaveTheCorrectOptions() {
        CONSTRUCTORS.forEach(function (name, index) {
          var graph = new implementation[name]();

          var _OPTIONS$index = OPTIONS[index],
              multi = _OPTIONS$index.multi,
              type = _OPTIONS$index.type;

          _assert2.default.strictEqual(graph.multi, multi);
          _assert2.default.strictEqual(graph.type, type);
        });
      }
    }
  };
}


text:
import bson
import pymongo
import json
from bson import ObjectId
from pymongo import MongoClient
import string
import tangelo

def run():
    # Create an empty response object.
    response = {}
    response['data'] = []
    response['header'] = []

    returneditems = []
    with open('/Users/clisle/proj/xdata/QCR/2015-12-02/LGOptimusG CCU 1235-14.json') as data_file:
        data = json.load(data_file)
        # add columns for the data categories, so first we discover what item types exist
        itemtypes = []
        for key in data:
            itemtypes.append(key)
        print 'found:',itemtypes

        itemcount = 0
        uppercount = 0
        for key in data:
            print "*******",key
            lowercount = 0
            for item in data[key]:
                # add set columns for type, with all set to zero initially
                for itemtype in itemtypes:
                    item[itemtype] = 0
                # indicate set membership for the set that matches this individual item.  This will establish this
                # type of this item by giving it set membership in the "type" set (messages,calls, etc.)
                item[key] = 1

                # now add  binary sets.  In each case, the identify of a multi-valued field is tested and turned
                # into an additional binary set attribute
                item['PhoneItemID'] = itemcount
                item['MatchedContact'] = 1 if ('From (Matched)'in item) else 0
                # not all records have this type, so short circuit to test it exists first
                item['Incoming'] = 1 if (('Direction' in item) and ('From (Matched)'in item)) else 0
                item['Sent'] = 1 if (('Status' in item) and (item['Status']=='Sent')) else 0
                item['Unsent'] = 1 if (('Status' in item) and (item['Status']=='Unsent')) else 0
                item['SendFailed'] = 1 if (('Status' in item) and (item['Status']=='Sending Failed')) else 0

                # handle the more complex text fields, which are not always present
                if ('Text' not in item.keys()):
                    item['Text'] = ""
                if ('Name' not in item.keys()):
                    item['Name'] = ""
                if ('Account Name' not in item.keys()):
                    item['Account Name'] = ""
                if ('Email' not in item.keys()):
                    item['Email'] = ""
                # add the extended row to the dataset returned for analysis
                response['data'].append(item)
                itemcount += 1

    # find the column headers
    headeritems = []
    for key in data:
        for item in data[key]:
            for col in item.keys():
                if (col not in headeritems):
                    headeritems.append(col)

    response['header'].append(headeritems)

    print "response:",response
    # convert to string to pass through URL callback
    #tangelo.log(str(response))
    return json.dumps(response)


text:
function ParseConstantExpression(tokens: ParenthesizedToken[]): BooleanExpression | IntegerExpression | FloatToken | undefined {
    if (tokens.length != 1) return undefined
    const onlyToken = tokens[0]
    switch (onlyToken.Type) {
        case "Boolean": return {
            Type: "Boolean",
            StartIndex: onlyToken.StartIndex,
            EndIndex: onlyToken.EndIndex,
            Value: onlyToken.Value
        }
        case "Integer": return {
            Type: "Integer",
            StartIndex: onlyToken.StartIndex,
            EndIndex: onlyToken.EndIndex,
            Value: onlyToken.Value
        }
        case "Float": return onlyToken // TODO: why was this not done above?
    }
    return undefined
}


text:
class UNIX_MorePersonInfoFixture :
	public CIMFixtureBase
{
public:
	UNIX_MorePersonInfoFixture();
	~UNIX_MorePersonInfoFixture();
	virtual void Run();

};


text:
import googlefinance
import unittest

class TestQuotes(unittest.TestCase):

    def test_one_symbol(self):
        appl = googlefinance.getQuotes('GOOG')[0]
        self.assertEqual(appl["Index"], "NASDAQ")
        self.assertEqual(appl["StockSymbol"], "GOOG")

    def test_symbols(self):
        quotes = googlefinance.getQuotes(['GOOG', 'VIE:BKS'])
        self.assertEqual(quotes[0]["Index"], "NASDAQ")
        self.assertEqual(quotes[0]["StockSymbol"], "GOOG")
        self.assertEqual(quotes[1]["Index"], "VIE")
        self.assertEqual(quotes[1]["StockSymbol"], "BKS")


text:
PostGraphQL makes full use of PostgreSQL roles, so in this article we will explain briefly how PostgreSQL roles and users work and how that relates to how we use them in PostGraphQL.

You can make any number of PostgreSQL roles with [`CREATE ROLE`](https://www.postgresql.org/docs/9.5/static/sql-createrole.html) command and assign permissions to those roles with the [`GRANT`](https://www.postgresql.org/docs/9.5/static/sql-grant.html) command. Permissions like select from the table `post` or insert rows into the `person` table.

PostgreSQL roles are also hierarchical. That is you can "grant" roles to other roles. For example if I had role `editor` which could change the data in our database and role `admin`, if I granted the `editor` role to `admin` with the command:

```sql
grant editor to admin;
```

Then the `admin` role would have the same permissions the `editor` role has. The `admin` role would also be able to *change* its role to the `editor` role. This means for the rest of the session you don't have any `admin` permissions, but only permissions given to the `editor` role.

In PostgreSQL you also have the idea of a user. A user is just a role that can login. So for example, the following are equivalent as the create an `admin` role that can log in (or a user):

```sql
create role admin login;
create user admin;
```

…and the following are also equivalent as they create a role that *can't* log in:

```sql
create role editor;
create role editor nologin;
```

"Logging in" just means we can use the role when authenticating in the PostgreSQL authentication section of the connection string. So with the above roles you could start a PostgreSQL connection with `postgres://admin@localhost:5432/mydb`, but not `postgres://editor@localhost:5432/mydb`.

## Roles in PostGraphQL
So how does this apply to PostGraphQL? PostGraphQL requires you to have at least one user (role that can log in) when connecting to the server. That role will be specified in your connection string and will from here on out be referred to as the `auth_user`. You'd connect with your `auth_user` as follows:

```bash
postgraphql -c postgres://auth_user@localhost:5432/mydb
```

The `auth_user` will have all the priveleges PostGraphQL might need.

You can also specify a `default_role` with PostGraphQL. The `default_role` will be used by PostGraphQL whenever no authorization token is provided or when the role claim in the authorization token is not specified. So all users that don't explicitly specify a role will automatically use the `default_role`.

So the `default_role` should have restricted priveleges to only your data that is publicly accessible.

After that you could also specify more roles like a `user_role` which should be included in the payload of your authorization tokens which may have more or less permissions then `default_role`.

In order to configure an default role just do the following:

```bash
postgraphql -c postgres://auth_user@localhost:5432/mydb --default-role default_role
```


text:
import stripe
from stripe.test.helper import (
    StripeResourceTest, DUMMY_INVOICE_ITEM
)

class InvoiceTest(StripeResourceTest):

    def test_add_invoice_item(self):
        customer = stripe.Customer(id="cus_invoice_items")
        customer.add_invoice_item(**DUMMY_INVOICE_ITEM)

        expected = DUMMY_INVOICE_ITEM.copy()
        expected['customer'] = 'cus_invoice_items'

        self.requestor_mock.request.assert_called_with(
            'post',
            '/v1/invoiceitems',
            expected,
            None,
        )

    def test_retrieve_invoice_items(self):
        customer = stripe.Customer(id="cus_get_invoice_items")
        customer.invoice_items()

        self.requestor_mock.request.assert_called_with(
            'get',
            '/v1/invoiceitems',
            {'customer': 'cus_get_invoice_items'},
        )

    def test_invoice_create(self):
        customer = stripe.Customer(id="cus_invoice")
        stripe.Invoice.create(customer=customer.id)

        self.requestor_mock.request.assert_called_with(
            'post',
            '/v1/invoices',
            {
                'customer': 'cus_invoice',
            },
            None
        )

    def test_retrieve_customer_invoices(self):
        customer = stripe.Customer(id="cus_invoice_items")
        customer.invoices()

        self.requestor_mock.request.assert_called_with(
            'get',
            '/v1/invoices',
            {
                'customer': 'cus_invoice_items',
            },
        )

    def test_pay_invoice(self):
        invoice = stripe.Invoice(id="ii_pay")
        invoice.pay()

        self.requestor_mock.request.assert_called_with(
            'post',
            '/v1/invoices/ii_pay/pay',
            {},
            None
        )

    def test_upcoming_invoice(self):
        stripe.Invoice.upcoming()

        self.requestor_mock.request.assert_called_with(
            'get',
            '/v1/invoices/upcoming',
            {},
        )

    def test_upcoming_invoice_subscription_items(self):
        stripe.Invoice.upcoming(subscription_items=[
            {"plan": "foo", "quantity": 3}
        ])
        self.requestor_mock.request.assert_called_with(
            'get',
            '/v1/invoices/upcoming',
            {
                'subscription_items': {
                    "0": {
                        "plan": "foo",
                        "quantity": 3,
                    },
                },
            },
        )


text:
require 'spec_helper'

describe Miletus::Harvest::FacetLink do

  it { should respond_to(:facet, :harvest_record) }

  # Ensure that jobs execute immediately for these tests
  before(:each) { Delayed::Worker.delay_jobs = false }

  describe "integration with Miletus::Harvest::Document::RIFCS" do
    let :fixture_url do
      fixture_file = File.expand_path(
        File.join(File.dirname(__FILE__),
          '..', 'fixtures', 'rifcs-activity-1.xml'))
      'file://%s' % fixture_file
    end

    it "should use with add, update and delete" do
      # Create new doc
      doc = Miletus::Harvest::Document::RIFCS.new
      VCR.use_cassette('ands_rifcs_example') do
        doc.should respond_to(:facet_links)
        doc.url = \
          'http://services.ands.org.au/documentation/rifcs/example/rif.xml'
        doc.save!
        doc.should have(0).facet_links
        # Populate record data and check that links are created
        doc.fetch
      end
      doc.should have(4).facet_links
      doc.facet_links.pluck(:facet_id).uniq.count.should be == 4
      doc.url = fixture_url
      doc.fetch
      doc.should have(1).facet_links
      # The links should delete when the record data does
      doc.clear
      doc.should be_changed
      doc.save!
      doc.should have(0).facet_links
    end
  end

  describe "integration with Miletus::Harvest::Document::RDCAtom" do

    it "should respond to :facet_links" do
      Miletus::Harvest::Document::RDCAtom.respond_to?(:facet_links)
    end

  end

  describe "integration with Miletus::Harvest::OAIPMH::RIFCS::Record" do
    let(:fixture) do
      # Load data from fixture
      fixture_file = File.join(File.dirname(__FILE__),
        '..', 'fixtures',"rifcs-party-1.xml")
      xml = File.open(fixture_file) { |f| f.read }
      # Create collection
      rc = Miletus::Harvest::OAIPMH::RIFCS::RecordCollection.create(
        :endpoint => 'http://example.test/oai'
      )
      # Create record
      Miletus::Harvest::OAIPMH::RIFCS::Record.new.tap do |r|
        r.record_collection = rc
        r.identifier = 'http://example.test/1'
        r.datestamp = Time.now
        r.metadata = Nokogiri::XML(xml).tap do |doc|
          old_root = doc.root
          doc.root = Nokogiri::XML::Node.new('metadata', doc)
          doc.root << old_root
        end.to_s
      end
    end

    it "should create a new concept for a new harvested record" do
      input_record = fixture
      input_record.should respond_to(:facet_links)
      input_record.save!
      # Check that facet links have been created
      input_record.should have(1).facet_links
      input_record.deleted = true
      input_record.save!
      # Check that facet links have been created
      input_record.should have(0).facet_links
    end
  end

end


text:
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <artifactId>kylo-nifi-provenance-repo-v1-nar</artifactId>
  <parent>
    <groupId>com.thinkbiganalytics.nifi.provenance</groupId>
    <artifactId>kylo-nifi-provenance-repo-bundle</artifactId>
    <version>0.8.1-SNAPSHOT</version>
  </parent>
  <packaging>nar</packaging>
  <properties>
    <maven.javadoc.skip>true</maven.javadoc.skip>
    <source.skip>true</source.skip>
    <nifi.version>1.1.0</nifi.version>
    <plugin.license.parentRelative>../../../../../</plugin.license.parentRelative>
  </properties>

  <dependencies>

    <dependency>
      <groupId>com.thinkbiganalytics.nifi.services</groupId>
      <artifactId>kylo-nifi-core-service-nar</artifactId>
      <version>${project.version}</version>
      <type>nar</type>
    </dependency>

    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>1.8.9</version>
    </dependency>

    <dependency>
      <groupId>com.thinkbiganalytics.nifi.provenance</groupId>
      <artifactId>kylo-nifi-provenance-repo</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>com.thinkbiganalytics.nifi.provenance</groupId>
      <artifactId>kylo-nifi-provenance-repo-v1</artifactId>
      <version>${project.version}</version>
    </dependency>
    <!--
    <dependency>
        <groupId>com.thinkbiganalytics.datalake</groupId>
        <artifactId>kylo-nifi-rest-client-v1</artifactId>
        <version>${project.version}</version>
    </dependency>
    -->
  </dependencies>

</project>


text:
package ua.com.fielden.platform.web.centre.api.crit.impl;

import static java.util.Optional.empty;
import static org.apache.commons.lang.StringUtils.isEmpty;
import static ua.com.fielden.platform.criteria.generator.impl.CriteriaReflector.critName;
import static ua.com.fielden.platform.criteria.generator.impl.CriteriaReflector.from;
import static ua.com.fielden.platform.criteria.generator.impl.CriteriaReflector.is;
import static ua.com.fielden.platform.criteria.generator.impl.CriteriaReflector.not;
import static ua.com.fielden.platform.criteria.generator.impl.CriteriaReflector.to;
import static ua.com.fielden.platform.domaintree.impl.AbstractDomainTree.isDoubleCriterion;
import static ua.com.fielden.platform.entity_centre.review.DynamicQueryBuilder.QueryProperty.critOnlyWithMnemonics;
import static ua.com.fielden.platform.reflection.AnnotationReflector.getPropertyAnnotationInHierarchy;
import static ua.com.fielden.platform.reflection.PropertyTypeDeterminator.determinePropertyType;
import static ua.com.fielden.platform.utils.EntityUtils.isBoolean;
import static ua.com.fielden.platform.utils.Pair.pair;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import ua.com.fielden.platform.criteria.generator.impl.CriteriaReflector;
import ua.com.fielden.platform.dom.DomElement;
import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.entity.annotation.CritOnly;
import ua.com.fielden.platform.entity_centre.review.DynamicQueryBuilder.QueryProperty;
import ua.com.fielden.platform.reflection.PropertyTypeDeterminator;
import ua.com.fielden.platform.utils.EntityUtils;
import ua.com.fielden.platform.utils.Pair;
import ua.com.fielden.platform.web.interfaces.IImportable;
import ua.com.fielden.platform.web.interfaces.IRenderable;
import ua.com.fielden.platform.web.view.master.api.widgets.impl.AbstractWidget;

/**
 * The base implementation box for generic information for all criterion widgets.
 *
 * All criterion widget implementations should be based on this one and should be extended by criterion-specific configuration data.
 *
 * @author TG Team
 *
 */
public abstract class AbstractCriterionWidget implements IRenderable, IImportable {

    private static final String sufixFrom = " (From)";
    private static final String sufixTo = " (To)";
    private static final String sufixYes = " (Yes)";
    private static final String sufixNo = " (No)";

    private final Class<? extends AbstractEntity<?>> root;
    private final String propertyName;
    private final String widgetName;
    private final String widgetPath;
    private boolean debug = false;
    private final Pair<AbstractWidget, AbstractWidget> editors;
    private final boolean mnemonicsVisible;
    private final boolean excludeMissing;
    private final boolean excludeNot;
    private final boolean excludeOrGroup;

    /**
     * Creates {@link AbstractCriterionWidget} from entityType type and propertyName and the name&path of widget.
     *
     * @param criteriaType
     * @param propertyName
     */
    public AbstractCriterionWidget(final Class<? extends AbstractEntity<?>> root, final String widgetPath, final String propertyName, final AbstractWidget... editors) {
        this.root = root;
        this.widgetName = extractNameFrom(widgetPath);
        this.widgetPath = widgetPath;
        this.propertyName = propertyName;

        final Optional<CritOnly> optionalCritOnlyAnnotation = isEmpty(propertyName) ? empty(): getPropertyAnnotationInHierarchy(CritOnly.class, root, propertyName);
        this.excludeMissing = optionalCritOnlyAnnotation.map(val -> val.excludeMissing()).orElse(false) || shouldExcludeMissing(root, propertyName);
        this.excludeNot = shouldExcludeNot(root, propertyName);
        this.excludeOrGroup = shouldExcludeOrGroup(root, propertyName); // 'or' mnemonic is always visible except when property is crit only without model
        this.mnemonicsVisible = optionalCritOnlyAnnotation.map(val -> critOnlyWithMnemonics(val)).orElse(true) && (!excludeMissing || !excludeNot || !excludeOrGroup);
        this.editors = pair(editors[0], null);
        if (editors.length > 1) {
            this.editors.setValue(editors[1]);
        }
    }

    private List<AbstractWidget> editors0() {
        return editors.getValue() == null ? Arrays.asList(editors.getKey()) : Arrays.asList(editors.getKey(), editors.getValue());
    }

    private DomElement[] editors() {
        final List<AbstractWidget> editors = editors0();
        final DomElement[] editorsDOM = new DomElement[editors.size()];
        for (int editorIndex = 0; editorIndex < editors.size(); editorIndex++) {
            final DomElement editorElement = editors.get(editorIndex).render().clazz(getCriterionClass(editorIndex)).attr("slot", getCriterionClass(editorIndex));
            editorElement.clazz("flex", true);
            editorsDOM[editorIndex] = editorElement;
        }
        return editorsDOM;
    }

    /**
     * Returns {@code true} if 'OR-group' mnemonic should be excluded for this criterion.
     *
     * @param root
     * @param propertyName
     * @return
     */
    private static boolean shouldExcludeOrGroup(final Class<? extends AbstractEntity<?>> root, final String propertyName) {
        try {
            final QueryProperty queryProperty = new QueryProperty(root, propertyName);
            return (queryProperty.isCritOnlyWithoutModel()) // 'crit only property without model' represents criteria values that are glued together inside custom query (AND, OR) and this can not be customised - will be excluded
                    || queryProperty.isAECritOnlyChild() // children of crit-only properties can be added to selection crit, but they will be treated as crit-only as well; so they should be excluded too
                    || queryProperty.isInUnionHierarchy() // union properties to be excluded
                    || queryProperty.isWithinCollectionalHierarchyOrOutsideCollectionWithANYorALL(); // collectional properties to be excluded; in future ANY/ALL aggregation expressions can be considered for inclusion, however they are not even possible in current Centre DSL
        } catch (final Exception ex) {
            return true; // in case where property is unsupported for dynamic query building or malformed -- exclude 'orGroup' mnemonic
        }
    }

    /**
     * Returns {@code true} if 'Not' mnemonic should be excluded for this criterion.
     *
     * @param root
     * @param propertyName
     * @return
     */
    private static boolean shouldExcludeNot(final Class<? extends AbstractEntity<?>> root, final String propertyName) {
        return isBoolean("".equals(propertyName) ? root : determinePropertyType(root, propertyName));
    }

    /**
     * Returns {@code true} if 'Missing' mnemonic should be excluded for this criterion.
     *
     * @param root
     * @param propertyName
     * @return
     */
    private static boolean shouldExcludeMissing(final Class<? extends AbstractEntity<?>> root, final String propertyName) {
        return isBoolean("".equals(propertyName) ? root : determinePropertyType(root, propertyName));
    }

    protected String getCriterionClass(final int editorIndex) {
        return "criterion-editors";
    }

    public List<String> editorsImportPaths() {
        return editors0().stream().map(widget -> widget.importPath()).collect(Collectors.toList());
    }

    /**
     * The name of the property to which this editor will be bound.
     *
     * Please, note that if the "property itself" is used -- the method returns "THIS".
     *
     * @return
     */
    protected String propertyName() {
        return "".equals(propertyName) ? "THIS" : propertyName.replace(".", ":"); // dots are converted to colons to conform to the 'propertyModel' naming convention
    }

    /**
     * Creates an attributes that will be used for widget component generation (generic attributes).
     *
     * @return
     */
    private Map<String, Object> createAttributes() {
        final LinkedHashMap<String, Object> attrs = new LinkedHashMap<>();
        if (isDebug()) {
            attrs.put("debug", "true");
        }
        attrs.put("id", "criterion_4_" + CriteriaReflector.critName(root, this.propertyName));
        attrs.put("validation-callback", "[[validate]]");
        if (mnemonicsVisible) {
            attrs.put("mnemonics-visible", null);
        }
        if (excludeMissing) {
            attrs.put("exclude-missing", null);
        }
        if (excludeNot) {
            attrs.put("exclude-not", null);
        }
        if (excludeOrGroup) {
            attrs.put("exclude-or-group", null);
        }
        return attrs;
    }

    /**
     * Creates attributes that will be used for widget component generation.
     *

     * This method needs to be overridden in descendants (i.e., concrete widgets) to extend the attributes set with widget-specific attributes.
     *
     * @return
     */
    protected Map<String, Object> createCustomAttributes() {
        final Map<String, Object> attrs = new LinkedHashMap<>();
        attrs.put("or-null", "{{propertyModel." + this.propertyName() + ".orNull}}");
        attrs.put("not", "{{propertyModel." + this.propertyName() + ".not}}");
        attrs.put("or-group", "{{propertyModel." + this.propertyName() + ".orGroup}}");
        return attrs;
    }

    @Override
    public final DomElement render() {
        return new DomElement(widgetName).attrs(createAttributes()).attrs(createCustomAttributes()).add(editors()).clazz("criterion-widget");
    }

    /**
     * Extracts widget name from its path.
     *
     * @param path
     * @return
     */
    public static String extractNameFrom(final String path) {
        final int lastSlashInd = path.lastIndexOf('/');
        if (lastSlashInd < 0) {
            return path;
        } else {
            return path.substring(lastSlashInd + 1);
        }
    }

    @Override
    public String importPath() {
        return widgetPath;
    }

    public boolean isDebug() {
        return debug;
    }

    public void setDebug(final boolean debug) {
        this.debug = debug;
    }

    public static Pair<String, String> generateNames(final Class<?> root, final Class<?> managedType, final String propertyName) {
        final boolean isEntityItself = "".equals(propertyName); // empty property means "entity itself"
        final Class<?> propertyType = isEntityItself ? managedType : determinePropertyType(managedType, propertyName);

        final String firstPropertyName, secondPropertyName;
        if (isDoubleCriterion(managedType, propertyName)) {
            firstPropertyName = critName(root, isBoolean(propertyType) ? is(propertyName) : from(propertyName));
            secondPropertyName = critName(root, isBoolean(propertyType) ? not(propertyName) : to(propertyName));
        } else {
            firstPropertyName = critName(root, propertyName);
            secondPropertyName = null;
        }
        return pair(firstPropertyName, secondPropertyName);
    }

    public static Pair<Pair<String, String>, Pair<String, String>> generateTitleDesc(final Class<?> root, final Class<?> managedType, final String propertyName) {
        final boolean isEntityItself = "".equals(propertyName); // empty property means "entity itself"
        final Class<?> propertyType = isEntityItself ? managedType : PropertyTypeDeterminator.determinePropertyType(managedType, propertyName);
        //        final CritOnly critOnlyAnnotation = isEntityItself ? null : AnnotationReflector.getPropertyAnnotation(CritOnly.class, managedType, propertyName);
        //        final Pair<String, String> titleAndDesc = CriteriaReflector.getCriteriaTitleAndDesc(managedType, propertyName);
        //        final List<NewProperty> generatedProperties = new ArrayList<NewProperty>();
        //
        //        if (AbstractDomainTree.isDoubleCriterionOrBoolean(managedType, propertyName)) {
        //            generatedProperties.addAll(generateRangeCriteriaProperties(root, managedType, propertyType, propertyName, titleAndDesc));
        //        } else {
        //            generatedProperties.add(generateSingleCriteriaProperty(root, managedType, propertyType, propertyName, titleAndDesc, critOnlyAnnotation));
        //        }
        //        return generatedProperties;

        //        final Pair<String, String> _firstTitleDesc = CriteriaReflector.getCriteriaTitleAndDesc(managedType, propertyName);
        //        final Pair<String, String> firstTitleDesc = Pair.pair(_firstTitleDesc.getKey() + sufixFrom, _firstTitleDesc.getValue());
        //
        //        final Pair<String, String> _secondTitleDesc = CriteriaReflector.getCriteriaTitleAndDesc(managedType, propertyName);
        //        final Pair<String, String> secondTitleDesc = Pair.pair(_secondTitleDesc.getKey() + sufixTo, _secondTitleDesc.getValue());

        //        return new Pair<>(firstTitleDesc, secondTitleDesc);
        if(EntityUtils.isBoolean(propertyType)){
            return generateTitleDescWithSufixes(sufixYes, sufixNo, managedType, propertyName);
        } else {
            return generateTitleDescWithSufixes(sufixFrom, sufixTo, managedType, propertyName);
        }

    }

    public static Pair<Pair<String, String>, Pair<String, String>> generateTitleDescWithSufixes(final String firstSufix, final String secondSufix, final Class<?> managedType, final String propertyName) {
        final Pair<String, String> _firstTitleDesc = CriteriaReflector.getCriteriaTitleAndDesc(managedType, propertyName);
        final Pair<String, String> firstTitleDesc = Pair.pair(_firstTitleDesc.getKey() + firstSufix, _firstTitleDesc.getValue());

        final Pair<String, String> _secondTitleDesc = CriteriaReflector.getCriteriaTitleAndDesc(managedType, propertyName);
        final Pair<String, String> secondTitleDesc = Pair.pair(_secondTitleDesc.getKey() + secondSufix, _secondTitleDesc.getValue());
        return pair(firstTitleDesc, secondTitleDesc);
    }

    public static String generateSingleName(final Class<?> root, final Class<?> managedType, final String propertyName) {
        return generateNames(root, managedType, propertyName).getKey();
    }

    public static Pair<String, String> generateSingleTitleDesc(final Class<?> root, final Class<?> managedType, final String propertyName) {
        final boolean isEntityItself = "".equals(propertyName);
        final Class<?> propertyType = isEntityItself ? managedType : PropertyTypeDeterminator.determinePropertyType(managedType, propertyName);
        final Pair<String, String> _first = generateTitleDesc(root, managedType, propertyName).getKey();
        final String title = _first.getKey();
        final int suffixLength = EntityUtils.isBoolean(propertyType) ? sufixYes.length() : sufixFrom.length();

        return pair(title.substring(0, title.length() - suffixLength), _first.getValue());
    }
}


text:
I had the idea to create a math dictionary for German <-> English.

More about this on StackExchange: [Is there an environment / document class for dictionaries?](http://tex.stackexchange.com/q/149754/5645)


text:
class QCGLWidget;

USING_NS_CC;

class QCGLView : public GLViewImpl
{
public:
    QCGLView();
    virtual ~QCGLView();

	virtual bool isOpenGLReady() override;
	virtual void end() override;
	virtual void swapBuffers() override;
	virtual void setFrameSize(float width, float height) override;
	virtual void setIMEKeyboardState(bool bOpen) override;
    virtual void setViewName(const char* pszViewName);

	void setBgColor(Color4B &color);

	static QCGLView* getInstance();

	virtual void init();

private:
    float			_screenScaleFactor;
	float			_lastWindowHeight;
	Color4F			_bgColor;
};


text:
define([
  'omega/core',
  'omega/performance',
  'omega/pulse',
  'jquery',
  'flot'
], function (o, performance, pulse) {

  'use strict';

  var secondsOfData = 10,
      updatesPerSecond = 5,
      dataLength = (1000 / pulse.getTargetFps()) * secondsOfData; // points on graph (length of each frame * duration of output)

  var debug = {
    init: function () {
      var container = o.getContainer().elem,
          fpsData = [],
          percentageEnterFrameData = [],
          percentageRenderData = [],
          entityData = [],
          next = dataLength,
          frameStart,
          enterFrames = [],
          percentageEnterFrame,
          percentageRender;

      for (var i = 0; i < dataLength; ++i) {
        fpsData[i] = [i, -1];
        percentageEnterFrameData[i] = [i, -1];
        percentageRenderData[i] = [i, -1];
        entityData[i] = [i, -1];
      }

      var $debug = $('

');
      $debug.insertAfter($(container)).width(o.getAttr().width * o.getAttr().scale);

      $debug.append('

');
      var fpsPlot = $.plot('#omega_debug .fps', [], {
        series: {shadowSize: 0, clickable: false, hoverable: false, lines: { lineWidth: 1}},
        yaxis: {min: 0, max: pulse.getTargetFps() * 1.5, labelWidth: 20, ticks: 5},
        xaxis: {show: false},
        legend: {position: 'nw'}
      });

      $debug.append('

');
      var timePlot = $.plot('#omega_debug .time', [], {
        series: {shadowSize: 0, clickable: false, hoverable: false, lines: { fill: true,  lineWidth: 1}},
        yaxis: {min: 0, max: 100, labelWidth: 20, tickSize: 25},
        xaxis: {show: false},
        legend: {position: 'nw'}
      });

      $debug.append('

');
      var entityPlot = $.plot('#omega_debug .entity', [], {
        series: {shadowSize: 0, clickable: false, hoverable: false, lines: { lineWidth: 1}},
        yaxis: {min: 0, max: 20, labelWidth: 20, ticks: 5},
        xaxis: {show: false},
        legend: {position: 'nw'}
      });

      frameStart = performance.now();
      var lastFrameDuration = 1000 / pulse.getTargetFps(),
           renderStart = performance.now() + (1000 / pulse.getTargetFps()),
           frameend = performance.now() + (1000 / pulse.getTargetFps());

      pulse.bind(function () {
        lastFrameDuration = performance.now() - frameStart;
        frameStart = performance.now();

        enterFrames[enterFrames.length] = lastFrameDuration;
        if (enterFrames.length > pulse.getTargetFps() * 2) {
          enterFrames.shift();
        }
      });

      o.bind('RenderStart', function () {
        renderStart = performance.now();
        percentageEnterFrame = (renderStart - frameStart) / lastFrameDuration * 100;
      });

      o.bind('RenderEnd', function () {
        frameend = performance.now();
        percentageRender = (frameend - renderStart) / lastFrameDuration * 100;
      });

      entityPlot.getOptions().grid.markings = [];
      o.bind('Collision', function() {
        entityPlot.getOptions().grid.markings[entityPlot.getOptions().grid.markings.length] = { color: '#ffffff', lineWidth: 1, xaxis: {from: next, to: next, lineWidth: 1}};
      });

      setInterval(function () {
        var fps,
            sum = 0;

        for (var i = 0, il = enterFrames.length; i < il; ++i) {
          sum += enterFrames[i];
        }
        fps = 1000 / (sum / enterFrames.length);

        fpsData.shift();
        fpsData[fpsData.length] = [next, fps];

        fpsPlot.setData([
          {data: [[next - dataLength + 1, pulse.getTargetFps()], [next, pulse.getTargetFps()]], label: 'Target FPS (' + pulse.getTargetFps()  + ')'},
          {data: fpsData, label: 'Actual FPS (' + (Math.round(fps*10)/10).toFixed(1) + ')'}
        ]);

        fpsPlot.setupGrid();
        fpsPlot.draw();

        // ---

        percentageEnterFrameData.shift();
        percentageEnterFrameData[percentageEnterFrameData.length] = [next, percentageEnterFrame];

        percentageRenderData.shift();
        percentageRenderData[percentageRenderData.length] = [next, percentageRender + percentageEnterFrame];

        timePlot.setData([
          {data: percentageEnterFrameData, label: 'Frame ready (' + (Math.round(percentageEnterFrame * 10)/10).toFixed(1) + '%)'},
          {data: percentageRenderData, label: 'Frame rendered (' + (Math.round((percentageRender + percentageEnterFrame)*10)/10).toFixed(1) + '%)'}
        ]);

        timePlot.setupGrid();
        timePlot.draw();

        // ---

        entityData.shift();
        entityData[entityData.length] = [next, Object.keys(o.getEntities()).length];

        if (Object.keys(o.getEntities()).length > 20) {
          entityPlot.getAxes().yaxis.options.max = null;
        }

        entityPlot.setData([
          {data: entityData, label: 'Entities (' + Object.keys(o.getEntities()).length + ')'},
        ]);

        entityPlot.setupGrid();
        entityPlot.draw();

        // ---

        ++next;
      }, 1000 / updatesPerSecond);
    }
  };

  return function (container) {
    return debug.init(container);
  };
});