text:
#include "talk/session/media/channelmanager.h"

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <algorithm>

#include "talk/base/common.h"
#include "talk/base/logging.h"
#include "talk/base/sigslotrepeater.h"
#include "talk/base/stringencode.h"
#include "talk/media/base/capturemanager.h"
#include "talk/media/base/rtpdataengine.h"
#include "talk/media/base/videocapturer.h"
#include "talk/session/media/soundclip.h"

namespace cricket {

enum {
  MSG_CREATEVOICECHANNEL = 1,
  MSG_DESTROYVOICECHANNEL = 2,
  MSG_SETAUDIOOPTIONS = 3,
  MSG_GETOUTPUTVOLUME = 4,
  MSG_SETOUTPUTVOLUME = 5,
  MSG_SETLOCALMONITOR = 6,
  MSG_SETVOICELOGGING = 7,
  MSG_CREATEVIDEOCHANNEL = 11,
  MSG_DESTROYVIDEOCHANNEL = 12,
  MSG_SETVIDEOOPTIONS = 13,
  MSG_SETLOCALRENDERER = 14,
  MSG_SETDEFAULTVIDEOENCODERCONFIG = 15,
  MSG_SETVIDEOLOGGING = 16,
  MSG_CREATESOUNDCLIP = 17,
  MSG_DESTROYSOUNDCLIP = 18,
  MSG_VIDEOCAPTURESTATE = 19,
  MSG_SETVIDEOCAPTURE = 20,
  MSG_TERMINATE = 21,
  MSG_REGISTERVIDEOPROCESSOR = 22,
  MSG_UNREGISTERVIDEOPROCESSOR = 23,
  MSG_REGISTERVOICEPROCESSOR = 24,
  MSG_UNREGISTERVOICEPROCESSOR = 25,
  MSG_SETVIDEOCAPTURER = 26,
  MSG_CREATEDATACHANNEL = 27,
  MSG_DESTROYDATACHANNEL = 28,
  // The following are done in the new "CaptureManager" style that
  // all local video capturers, processors, and managers should move
  // to.
  // TODO(pthatcher): Add more of the CaptureManager interface.
  MSG_STARTVIDEOCAPTURE = 29,
  MSG_STOPVIDEOCAPTURE = 30,
  MSG_ADDVIDEORENDERER = 31,
  MSG_REMOVEVIDEORENDERER = 32,
  MSG_GETSTARTCAPTUREFORMAT = 33,
};

static const int kNotSetOutputVolume = -1;

struct CreationParams : public talk_base::MessageData {
  CreationParams(BaseSession* session, const std::string& content_name,
                 bool rtcp, VoiceChannel* voice_channel)
      : session(session),
        content_name(content_name),
        rtcp(rtcp),
        voice_channel(voice_channel),
        video_channel(NULL),
        data_channel(NULL) {
  }
  BaseSession* session;
  std::string content_name;
  bool rtcp;
  VoiceChannel* voice_channel;
  VideoChannel* video_channel;
  DataChannel* data_channel;
};

struct AudioOptionsParams : public talk_base::MessageData {
  AudioOptionsParams(int o, const Device* in, const Device* out, int delay)
      : options(o), in_device(in), out_device(out), delay_offset(delay) {}
  int options;
  const Device* in_device;
  const Device* out_device;
  int delay_offset;
  bool result;
};

struct VolumeLevel : public talk_base::MessageData {
  VolumeLevel() : level(-1), result(false) {}
  explicit VolumeLevel(int l) : level(l), result(false) {}
  int level;
  bool result;
};

struct VideoOptions : public talk_base::MessageData {
  explicit VideoOptions(const Device* d) : cam_device(d), result(false) {}
  const Device* cam_device;
  bool result;
};

struct DefaultVideoEncoderConfig : public talk_base::MessageData {
  explicit DefaultVideoEncoderConfig(const VideoEncoderConfig& c)
      : config(c), result(false) {}
  VideoEncoderConfig config;
  bool result;
};

struct LocalMonitor : public talk_base::MessageData {
  explicit LocalMonitor(bool e) : enable(e), result(false) {}
  bool enable;
  bool result;
};

struct LocalRenderer : public talk_base::MessageData {
  explicit LocalRenderer(VideoRenderer* r) : renderer(r), result(false) {}
  VideoRenderer* renderer;
  bool result;
};

struct Capturer : public talk_base::MessageData {
  Capturer(VideoCapturer* c)
      : capturer(c),
        result(false) {}
  VideoCapturer* capturer;
  bool result;
};

struct LoggingOptions : public talk_base::MessageData {
  explicit LoggingOptions(int lev, const char* f) : level(lev), filter(f) {}
  int level;
  std::string filter;
};

struct CaptureStateParams : public talk_base::MessageData {
  CaptureStateParams(cricket::VideoCapturer* c, cricket::CaptureState s)
      : capturer(c),
        state(s) {}
  cricket::VideoCapturer* capturer;
  cricket::CaptureState state;
};

struct CaptureParams : public talk_base::MessageData {
  explicit CaptureParams(bool c) : capture(c), result(false) {}
  bool capture;
  bool result;
};

struct VideoProcessorParams : public talk_base::MessageData {
  VideoProcessorParams(VideoCapturer* c, VideoProcessor* p)
      : capturer(c), processor(p), result(false) {}
  VideoCapturer* capturer;
  VideoProcessor* processor;
  bool result;
};

struct VoiceProcessorParams : public talk_base::MessageData {
  VoiceProcessorParams(uint32 c, VoiceProcessor* p, MediaProcessorDirection d)
      : ssrc(c), direction(d), processor(p), result(false) {}
  uint32 ssrc;
  MediaProcessorDirection direction;
  VoiceProcessor* processor;
  bool result;
};

struct VideoCapturerFormatParams : public talk_base::MessageData {
  explicit VideoCapturerFormatParams(
      VideoCapturer* capturer, const VideoFormat& format)
      : capturer(capturer), format(format), result(false) {}
  VideoCapturer* capturer;
  VideoFormat format;
  bool result;
};

struct VideoCapturerRendererParams : public talk_base::MessageData {
  VideoCapturerRendererParams(VideoCapturer* capturer, VideoRenderer* renderer)
      : capturer(capturer), renderer(renderer), result(false) {}
  VideoCapturer* capturer;
  VideoRenderer* renderer;
  bool result;
};

struct StartCaptureParams  : public talk_base::MessageData {
  StartCaptureParams() : video_format() {}
  VideoFormat video_format;
};

ChannelManager::ChannelManager(talk_base::Thread* worker_thread) {
  Construct(MediaEngineFactory::Create(),
            new RtpDataEngine(),
            cricket::DeviceManagerFactory::Create(),
            new CaptureManager(),
            worker_thread);
}

ChannelManager::ChannelManager(MediaEngineInterface* me,
                               DataEngineInterface* dme,
                               DeviceManagerInterface* dm,
                               CaptureManager* cm,
                               talk_base::Thread* worker_thread) {
  Construct(me, dme, dm, cm, worker_thread);
}

ChannelManager::ChannelManager(MediaEngineInterface* me,
                               DeviceManagerInterface* dm,
                               talk_base::Thread* worker_thread) {
  Construct(me, new RtpDataEngine(), dm, new CaptureManager(), worker_thread);
}

void ChannelManager::Construct(MediaEngineInterface* me,
                               DataEngineInterface* dme,
                               DeviceManagerInterface* dm,
                               CaptureManager* cm,
                               talk_base::Thread* worker_thread) {
  media_engine_.reset(me);
  data_media_engine_.reset(dme);
  device_manager_.reset(dm);
  capture_manager_.reset(cm);
  initialized_ = false;
  main_thread_ = talk_base::Thread::Current();
  worker_thread_ = worker_thread;
  audio_in_device_ = DeviceManagerInterface::kDefaultDeviceName;
  audio_out_device_ = DeviceManagerInterface::kDefaultDeviceName;
  audio_options_ = MediaEngineInterface::DEFAULT_AUDIO_OPTIONS;
  audio_delay_offset_ = MediaEngineInterface::kDefaultAudioDelayOffset;
  audio_output_volume_ = kNotSetOutputVolume;
  local_renderer_ = NULL;
  capturing_ = false;
  monitoring_ = false;

  // Init the device manager immediately, and set up our default video device.
  SignalDevicesChange.repeat(device_manager_->SignalDevicesChange);
  device_manager_->Init();

  // Camera is started asynchronously, request callbacks when startup
  // completes to be able to forward them to the rendering manager.
  media_engine_->SignalVideoCaptureStateChange.connect(
      this, &ChannelManager::OnVideoCaptureStateChange);
  capture_manager_->SignalCapturerStateChange.connect(
      this, &ChannelManager::OnVideoCaptureStateChange);
}

ChannelManager::~ChannelManager() {
  if (initialized_)
    Terminate();
}

int ChannelManager::GetCapabilities() {
  return media_engine_->GetCapabilities() & device_manager_->GetCapabilities();
}

void ChannelManager::GetSupportedAudioCodecs(
    std::vector<AudioCodec>* codecs) const {
  codecs->clear();

  for (std::vector<AudioCodec>::const_iterator it =
           media_engine_->audio_codecs().begin();
      it != media_engine_->audio_codecs().end(); ++it) {
    codecs->push_back(*it);
  }
}

void ChannelManager::GetSupportedVideoCodecs(
    std::vector<VideoCodec>* codecs) const {
  codecs->clear();

  std::vector<VideoCodec>::const_iterator it;
  for (it = media_engine_->video_codecs().begin();
      it != media_engine_->video_codecs().end(); ++it) {
    codecs->push_back(*it);
  }
}

void ChannelManager::GetSupportedDataCodecs(
    std::vector<DataCodec>* codecs) const {
  *codecs = data_media_engine_->data_codecs();
}

bool ChannelManager::Init() {
  ASSERT(!initialized_);
  if (initialized_) {
    return false;
  }

  ASSERT(worker_thread_ != NULL);
  if (worker_thread_ && worker_thread_->started()) {
    if (media_engine_->Init()) {
      initialized_ = true;

      // Now that we're initialized, apply any stored preferences. A preferred
      // device might have been unplugged. In this case, we fallback to the
      // default device but keep the user preferences. The preferences are
      // changed only when the Javascript FE changes them.
      const std::string preferred_audio_in_device = audio_in_device_;
      const std::string preferred_audio_out_device = audio_out_device_;
      const std::string preferred_camera_device = camera_device_;
      Device device;
      if (!device_manager_->GetAudioInputDevice(audio_in_device_, &device)) {
        LOG(LS_WARNING) << "The preferred microphone '" << audio_in_device_
                        << "' is unavailable. Fall back to the default.";
        audio_in_device_ = DeviceManagerInterface::kDefaultDeviceName;
      }
      if (!device_manager_->GetAudioOutputDevice(audio_out_device_, &device)) {
        LOG(LS_WARNING) << "The preferred speaker '" << audio_out_device_
                        << "' is unavailable. Fall back to the default.";
        audio_out_device_ = DeviceManagerInterface::kDefaultDeviceName;
      }
      if (!device_manager_->GetVideoCaptureDevice(camera_device_, &device)) {
        if (!camera_device_.empty()) {
          LOG(LS_WARNING) << "The preferred camera '" << camera_device_
                          << "' is unavailable. Fall back to the default.";
        }
        camera_device_ = DeviceManagerInterface::kDefaultDeviceName;
      }

      if (!SetAudioOptions(audio_in_device_, audio_out_device_,
                           audio_options_, audio_delay_offset_)) {
        LOG(LS_WARNING) << "Failed to SetAudioOptions with"
                        << " microphone: " << audio_in_device_
                        << " speaker: " << audio_out_device_
                        << " options: " << audio_options_
                        << " delay: " << audio_delay_offset_;
      }

      // If audio_output_volume_ has been set via SetOutputVolume(), set the
      // audio output volume of the engine.
      if (kNotSetOutputVolume != audio_output_volume_ &&
          !SetOutputVolume(audio_output_volume_)) {
        LOG(LS_WARNING) << "Failed to SetOutputVolume to "
                        << audio_output_volume_;
      }
      if (!SetVideoOptions(camera_device_) && !camera_device_.empty()) {
        LOG(LS_WARNING) << "Failed to SetVideoOptions with camera: "
                        << camera_device_;
      }

      // Restore the user preferences.
      audio_in_device_ = preferred_audio_in_device;
      audio_out_device_ = preferred_audio_out_device;
      camera_device_ = preferred_camera_device;

      // Now apply the default video codec that has been set earlier.
      if (default_video_encoder_config_.max_codec.id != 0) {
        SetDefaultVideoEncoderConfig(default_video_encoder_config_);
      }
      // And the local renderer.
      if (local_renderer_) {
        SetLocalRenderer(local_renderer_);
      }
    }
  }
  return initialized_;
}

void ChannelManager::Terminate() {
  ASSERT(initialized_);
  if (!initialized_) {
    return;
  }
  Send(MSG_TERMINATE, NULL);
  media_engine_->Terminate();
  initialized_ = false;
}

void ChannelManager::Terminate_w() {
  ASSERT(worker_thread_ == talk_base::Thread::Current());
  // Need to destroy the voice/video channels
  while (!video_channels_.empty()) {
    DestroyVideoChannel_w(video_channels_.back());
  }
  while (!voice_channels_.empty()) {
    DestroyVoiceChannel_w(voice_channels_.back());
  }
  while (!soundclips_.empty()) {
    DestroySoundclip_w(soundclips_.back());
  }
  if (!SetVideoOptions_w(NULL)) {
    LOG(LS_WARNING) << "failed to delete video capturer";
  }
}

VoiceChannel* ChannelManager::CreateVoiceChannel(
    BaseSession* session, const std::string& content_name, bool rtcp) {
  CreationParams params(session, content_name, rtcp, NULL);
  return (Send(MSG_CREATEVOICECHANNEL, &params)) ? params.voice_channel : NULL;
}

VoiceChannel* ChannelManager::CreateVoiceChannel_w(
    BaseSession* session, const std::string& content_name, bool rtcp) {
  // This is ok to alloc from a thread other than the worker thread
  ASSERT(initialized_);
  VoiceMediaChannel* media_channel = media_engine_->CreateChannel();
  if (media_channel == NULL)
    return NULL;

  VoiceChannel* voice_channel = new VoiceChannel(
      worker_thread_, media_engine_.get(), media_channel,
      session, content_name, rtcp);
  if (!voice_channel->Init()) {
    delete voice_channel;
    return NULL;
  }
  voice_channels_.push_back(voice_channel);
  return voice_channel;
}

void ChannelManager::DestroyVoiceChannel(VoiceChannel* voice_channel) {
  if (voice_channel) {
    talk_base::TypedMessageData<VoiceChannel*> data(voice_channel);
    Send(MSG_DESTROYVOICECHANNEL, &data);
  }
}

void ChannelManager::DestroyVoiceChannel_w(VoiceChannel* voice_channel) {
  // Destroy voice channel.
  ASSERT(initialized_);
  VoiceChannels::iterator it = std::find(voice_channels_.begin(),
      voice_channels_.end(), voice_channel);
  ASSERT(it != voice_channels_.end());
  if (it == voice_channels_.end())
    return;

  voice_channels_.erase(it);
  delete voice_channel;
}

VideoChannel* ChannelManager::CreateVideoChannel(
    BaseSession* session, const std::string& content_name, bool rtcp,
    VoiceChannel* voice_channel) {
  CreationParams params(session, content_name, rtcp, voice_channel);
  return (Send(MSG_CREATEVIDEOCHANNEL, &params)) ? params.video_channel : NULL;
}

VideoChannel* ChannelManager::CreateVideoChannel_w(
    BaseSession* session, const std::string& content_name, bool rtcp,
    VoiceChannel* voice_channel) {
  // This is ok to alloc from a thread other than the worker thread
  ASSERT(initialized_);
  VideoMediaChannel* media_channel =
      // voice_channel can be NULL in case of NullVoiceEngine.
      media_engine_->CreateVideoChannel(voice_channel ?
          voice_channel->media_channel() : NULL);
  if (media_channel == NULL)
    return NULL;

  VideoChannel* video_channel = new VideoChannel(
      worker_thread_, media_engine_.get(), media_channel,
      session, content_name, rtcp, voice_channel);
  if (!video_channel->Init()) {
    delete video_channel;
    return NULL;
  }
  video_channels_.push_back(video_channel);
  return video_channel;
}

void ChannelManager::DestroyVideoChannel(VideoChannel* video_channel) {
  if (video_channel) {
    talk_base::TypedMessageData<VideoChannel*> data(video_channel);
    Send(MSG_DESTROYVIDEOCHANNEL, &data);
  }
}

void ChannelManager::DestroyVideoChannel_w(VideoChannel* video_channel) {
  // Destroy video channel.
  ASSERT(initialized_);
  VideoChannels::iterator it = std::find(video_channels_.begin(),
      video_channels_.end(), video_channel);
  ASSERT(it != video_channels_.end());
  if (it == video_channels_.end())
    return;

  video_channels_.erase(it);
  delete video_channel;
}

DataChannel* ChannelManager::CreateDataChannel(
    BaseSession* session, const std::string& content_name, bool rtcp) {
  CreationParams params(session, content_name, rtcp, NULL);
  return (Send(MSG_CREATEDATACHANNEL, &params)) ? params.data_channel : NULL;
}

DataChannel* ChannelManager::CreateDataChannel_w(
    BaseSession* session, const std::string& content_name, bool rtcp) {
  // This is ok to alloc from a thread other than the worker thread.
  ASSERT(initialized_);
  DataMediaChannel* media_channel = data_media_engine_->CreateChannel();
  DataChannel* data_channel = new DataChannel(
      worker_thread_, media_channel,
      session, content_name, rtcp);
  if (!data_channel->Init()) {
    LOG(LS_WARNING) << "Failed to init data channel.";
    delete data_channel;
    return NULL;
  }
  data_channels_.push_back(data_channel);
  return data_channel;
}

void ChannelManager::DestroyDataChannel(DataChannel* data_channel) {
  if (data_channel) {
    talk_base::TypedMessageData<DataChannel*> data(data_channel);
    Send(MSG_DESTROYDATACHANNEL, &data);
  }
}

void ChannelManager::DestroyDataChannel_w(DataChannel* data_channel) {
  // Destroy data channel.
  ASSERT(initialized_);
  DataChannels::iterator it = std::find(data_channels_.begin(),
      data_channels_.end(), data_channel);
  ASSERT(it != data_channels_.end());
  if (it == data_channels_.end())
    return;

  data_channels_.erase(it);
  delete data_channel;
}

Soundclip* ChannelManager::CreateSoundclip() {
  talk_base::TypedMessageData<Soundclip*> data(NULL);
  Send(MSG_CREATESOUNDCLIP, &data);
  return data.data();
}

Soundclip* ChannelManager::CreateSoundclip_w() {
  ASSERT(initialized_);
  ASSERT(worker_thread_ == talk_base::Thread::Current());

  SoundclipMedia* soundclip_media = media_engine_->CreateSoundclip();
  if (!soundclip_media) {
    return NULL;
  }

  Soundclip* soundclip = new Soundclip(worker_thread_, soundclip_media);
  soundclips_.push_back(soundclip);
  return soundclip;
}

void ChannelManager::DestroySoundclip(Soundclip* soundclip) {
  if (soundclip) {
    talk_base::TypedMessageData<Soundclip*> data(soundclip);
    Send(MSG_DESTROYSOUNDCLIP, &data);
  }
}

void ChannelManager::DestroySoundclip_w(Soundclip* soundclip) {
  // Destroy soundclip.
  ASSERT(initialized_);
  Soundclips::iterator it = std::find(soundclips_.begin(),
      soundclips_.end(), soundclip);
  ASSERT(it != soundclips_.end());
  if (it == soundclips_.end())
    return;

  soundclips_.erase(it);
  delete soundclip;
}

bool ChannelManager::GetAudioOptions(std::string* in_name,
                                     std::string* out_name, int* opts) {
  if (in_name)
    *in_name = audio_in_device_;
  if (out_name)
    *out_name = audio_out_device_;
  if (opts)
    *opts = audio_options_;
  return true;
}

bool ChannelManager::SetAudioOptions(const std::string& in_name,
                                     const std::string& out_name, int opts) {
  return SetAudioOptions(in_name, out_name, opts, audio_delay_offset_);
}

bool ChannelManager::SetAudioOptions(const std::string& in_name,
                                     const std::string& out_name, int opts,
                                     int delay_offset) {
  // Get device ids from DeviceManager.
  Device in_dev, out_dev;
  if (!device_manager_->GetAudioInputDevice(in_name, &in_dev)) {
    LOG(LS_WARNING) << "Failed to GetAudioInputDevice: " << in_name;
    return false;
  }
  if (!device_manager_->GetAudioOutputDevice(out_name, &out_dev)) {
    LOG(LS_WARNING) << "Failed to GetAudioOutputDevice: " << out_name;
    return false;
  }

  // If we're initialized, pass the settings to the media engine.
  bool ret = true;
  if (initialized_) {
    AudioOptionsParams options(opts, &in_dev, &out_dev, delay_offset);
    ret = (Send(MSG_SETAUDIOOPTIONS, &options) && options.result);
  }

  // If all worked well, save the values for use in GetAudioOptions.
  if (ret) {
    audio_options_ = opts;
    audio_in_device_ = in_name;
    audio_out_device_ = out_name;
    audio_delay_offset_ = delay_offset;
  }
  return ret;
}

bool ChannelManager::SetAudioOptions_w(int opts, int delay_offset,
    const Device* in_dev, const Device* out_dev) {
  ASSERT(worker_thread_ == talk_base::Thread::Current());
  ASSERT(initialized_);

  // Set audio options
  bool ret = media_engine_->SetAudioOptions(opts);

  if (ret) {
    ret = media_engine_->SetAudioDelayOffset(delay_offset);
  }

  // Set the audio devices
  if (ret) {
    ret = media_engine_->SetSoundDevices(in_dev, out_dev);
  }

  return ret;
}

bool ChannelManager::GetOutputVolume(int* level) {
  VolumeLevel volume;
  if (!Send(MSG_GETOUTPUTVOLUME, &volume) || !volume.result) {
    return false;
  }

  *level = volume.level;
  return true;
}

bool ChannelManager::GetOutputVolume_w(int* level) {
  ASSERT(worker_thread_ == talk_base::Thread::Current());
  ASSERT(initialized_);
  return media_engine_->GetOutputVolume(level);
}

bool ChannelManager::SetOutputVolume(int level) {
  bool ret = level >= 0 && level <= 255;
  if (initialized_) {
    VolumeLevel volume(level);
    ret &= Send(MSG_SETOUTPUTVOLUME, &volume) && volume.result;
  }

  if (ret) {
    audio_output_volume_ = level;
  }

  return ret;
}

bool ChannelManager::SetOutputVolume_w(int level) {
  ASSERT(worker_thread_ == talk_base::Thread::Current());
  ASSERT(initialized_);
  return media_engine_->SetOutputVolume(level);
}

bool ChannelManager::IsSameCapturer(const std::string& capturer_name,
                                    VideoCapturer* capturer) {
  if (capturer == NULL) {
    return false;
  }
  Device device;
  if (!device_manager_->GetVideoCaptureDevice(capturer_name, &device)) {
    return false;
  }
  return capturer->GetId() == device.id;
}

bool ChannelManager::GetVideoOptions(std::string* cam_name) {
  if (camera_device_.empty()) {
    // Initialize camera_device_ with default.
    Device device;
    if (!device_manager_->GetVideoCaptureDevice(
        DeviceManagerInterface::kDefaultDeviceName, &device)) {
      LOG(LS_WARNING) << "Device manager can't find default camera: " <<
          DeviceManagerInterface::kDefaultDeviceName;
      return false;
    }
    camera_device_ = device.name;
  }
  *cam_name = camera_device_;
  return true;
}

bool ChannelManager::SetVideoOptions(const std::string& cam_name) {
  Device device;
  bool ret = true;
  if (!device_manager_->GetVideoCaptureDevice(cam_name, &device)) {
    if (!cam_name.empty()) {
      LOG(LS_WARNING) << "Device manager can't find camera: " << cam_name;
    }
    ret = false;
  }

  // If we're running, tell the media engine about it.
  if (initialized_ && ret) {
    VideoOptions options(&device);
    ret = (Send(MSG_SETVIDEOOPTIONS, &options) && options.result);
  }

  // If everything worked, retain the name of the selected camera.
  if (ret) {
    camera_device_ = device.name;
  } else if (camera_device_.empty()) {
    // When video option setting fails, we still want camera_device_ to be in a
    // good state, so we initialize it with default if it's empty.
    Device default_device;
    if (!device_manager_->GetVideoCaptureDevice(
        DeviceManagerInterface::kDefaultDeviceName, &default_device)) {
      LOG(LS_WARNING) << "Device manager can't find default camera: " <<
          DeviceManagerInterface::kDefaultDeviceName;
    }
    camera_device_ = default_device.name;
  }

  return ret;
}

VideoCapturer* ChannelManager::CreateVideoCapturer() {
  Device device;
  if (!device_manager_->GetVideoCaptureDevice(camera_device_, &device)) {
    if (!camera_device_.empty()) {
      LOG(LS_WARNING) << "Device manager can't find camera: " << camera_device_;
    }
    return NULL;
  }
  return device_manager_->CreateVideoCapturer(device);
}

bool ChannelManager::SetVideoOptions_w(const Device* cam_device) {
  ASSERT(worker_thread_ == talk_base::Thread::Current());
  ASSERT(initialized_);

  if (!cam_device) {
    video_device_name_.clear();
    return true;
  }
  video_device_name_ = cam_device->name;
  return true;
}

bool ChannelManager::SetDefaultVideoEncoderConfig(const VideoEncoderConfig& c) {
  bool ret = true;
  if (initialized_) {
    DefaultVideoEncoderConfig config(c);
    ret = Send(MSG_SETDEFAULTVIDEOENCODERCONFIG, &config) && config.result;
  }
  if (ret) {
    default_video_encoder_config_ = c;
  }
  return ret;
}

bool ChannelManager::SetDefaultVideoEncoderConfig_w(
    const VideoEncoderConfig& c) {
  ASSERT(worker_thread_ == talk_base::Thread::Current());
  ASSERT(initialized_);
  return media_engine_->SetDefaultVideoEncoderConfig(c);
}

bool ChannelManager::SetLocalMonitor(bool enable) {
  LocalMonitor monitor(enable);
  bool ret = Send(MSG_SETLOCALMONITOR, &monitor) && monitor.result;
  if (ret) {
    monitoring_ = enable;
  }
  return ret;
}

bool ChannelManager::SetLocalMonitor_w(bool enable) {
  ASSERT(worker_thread_ == talk_base::Thread::Current());
  ASSERT(initialized_);
  return media_engine_->SetLocalMonitor(enable);
}

bool ChannelManager::SetLocalRenderer(VideoRenderer* renderer) {
  bool ret = true;
  if (initialized_) {
    LocalRenderer local(renderer);
    ret = (Send(MSG_SETLOCALRENDERER, &local) && local.result);
  }
  if (ret) {
    local_renderer_ = renderer;
  }
  return ret;
}

bool ChannelManager::SetLocalRenderer_w(VideoRenderer* renderer) {
  ASSERT(worker_thread_ == talk_base::Thread::Current());
  ASSERT(initialized_);
  return media_engine_->SetLocalRenderer(renderer);
}

bool ChannelManager::SetVideoCapturer(VideoCapturer* capturer) {
  bool ret = true;
  if (initialized_) {
    Capturer capture(capturer);
    ret = (Send(MSG_SETVIDEOCAPTURER, &capture) && capture.result);
  }
  return ret;
}

bool ChannelManager::SetVideoCapturer_w(VideoCapturer* capturer) {
  ASSERT(worker_thread_ == talk_base::Thread::Current());
  ASSERT(initialized_);
  return media_engine_->SetVideoCapturer(capturer);
}

bool ChannelManager::SetVideoCapture(bool capture) {
  bool ret;
  CaptureParams capture_params(capture);
  ret = (Send(MSG_SETVIDEOCAPTURE, &capture_params) &&
         capture_params.result);
  if (ret) {
    capturing_ = capture;
  }
  return capture_params.result;
}

bool ChannelManager::SetVideoCapture_w(bool capture) {
  ASSERT(worker_thread_ == talk_base::Thread::Current());
  ASSERT(initialized_);
  return media_engine_->SetVideoCapture(capture);
}

void ChannelManager::SetVoiceLogging(int level, const char* filter) {
  SetMediaLogging(false, level, filter);
}

void ChannelManager::SetVideoLogging(int level, const char* filter) {
  SetMediaLogging(true, level, filter);
}

void ChannelManager::SetMediaLogging(bool video, int level,
                                     const char* filter) {
  // Can be called before initialization; in this case, the worker function
  // is simply called on the main thread.
  if (initialized_) {
    LoggingOptions options(level, filter);
    Send((video) ? MSG_SETVIDEOLOGGING : MSG_SETVOICELOGGING, &options);
  } else {
    SetMediaLogging_w(video, level, filter);
  }
}

void ChannelManager::SetMediaLogging_w(bool video, int level,
                                       const char* filter) {
  // Can be called before initialization
  ASSERT(worker_thread_ == talk_base::Thread::Current() || !initialized_);
  if (video) {
    media_engine_->SetVideoLogging(level, filter);
  } else {
    media_engine_->SetVoiceLogging(level, filter);
  }
}

// TODO(janahan): For now pass this request through the mediaengine to the
// voice and video engines to do the real work. Once the capturer refactoring
// is done, we will access the capturer using the ssrc (similar to how the
// renderer is accessed today) and register with it directly.
bool ChannelManager::RegisterVideoProcessor(VideoCapturer* capturer,
                                            VideoProcessor* processor) {
  VideoProcessorParams processor_params(capturer, processor);
  return (Send(MSG_REGISTERVIDEOPROCESSOR, &processor_params) &&
      processor_params.result);
}
bool ChannelManager::RegisterVideoProcessor_w(VideoCapturer* capturer,
                                              VideoProcessor* processor) {
  media_engine_->RegisterVideoProcessor(processor);
  return capture_manager_->AddVideoProcessor(capturer, processor);
}

bool ChannelManager::UnregisterVideoProcessor(VideoCapturer* capturer,
                                              VideoProcessor* processor) {
  VideoProcessorParams processor_params(capturer, processor);
  return (Send(MSG_UNREGISTERVIDEOPROCESSOR, &processor_params) &&
      processor_params.result);
}
bool ChannelManager::UnregisterVideoProcessor_w(VideoCapturer* capturer,
                                                VideoProcessor* processor) {
  media_engine_->UnregisterVideoProcessor(processor);
  return capture_manager_->RemoveVideoProcessor(capturer, processor);
}

bool ChannelManager::RegisterVoiceProcessor(
    uint32 ssrc,
    VoiceProcessor* processor,
    MediaProcessorDirection direction) {
  VoiceProcessorParams processor_params(ssrc, processor, direction);
  return (Send(MSG_REGISTERVOICEPROCESSOR, &processor_params) &&
      processor_params.result);
}
bool ChannelManager::RegisterVoiceProcessor_w(
    uint32 ssrc,
    VoiceProcessor* processor,
    MediaProcessorDirection direction) {
  return media_engine_->RegisterVoiceProcessor(ssrc, processor, direction);
}

bool ChannelManager::UnregisterVoiceProcessor(
    uint32 ssrc,
    VoiceProcessor* processor,
    MediaProcessorDirection direction) {
  VoiceProcessorParams processor_params(ssrc, processor, direction);
  return (Send(MSG_UNREGISTERVOICEPROCESSOR, &processor_params) &&
      processor_params.result);
}
bool ChannelManager::UnregisterVoiceProcessor_w(
    uint32 ssrc,
    VoiceProcessor* processor,
    MediaProcessorDirection direction) {
  return media_engine_->UnregisterVoiceProcessor(ssrc, processor, direction);
}

// The following are done in the new "CaptureManager" style that
// all local video capturers, processors, and managers should move
// to.
// TODO(pthatcher): Add more of the CaptureManager interface.
bool ChannelManager::StartVideoCapture(
    VideoCapturer* capturer, const VideoFormat& video_format) {
  VideoCapturerFormatParams params(capturer, video_format);
  return Send(MSG_STARTVIDEOCAPTURE, &params) && params.result;
}

bool ChannelManager::StartVideoCapture_w(
    VideoCapturer* capturer, const VideoFormat& video_format) {
  return capture_manager_->StartVideoCapture(capturer, video_format);
}

bool ChannelManager::StopVideoCapture(
    VideoCapturer* capturer, const VideoFormat& video_format) {
  VideoCapturerFormatParams params(capturer, video_format);
  return (Send(MSG_STOPVIDEOCAPTURE, &params) && params.result);
}

bool ChannelManager::StopVideoCapture_w(
    VideoCapturer* capturer, const VideoFormat& video_format) {
  return capture_manager_->StopVideoCapture(capturer, video_format);
}

bool ChannelManager::AddVideoRenderer(
    VideoCapturer* capturer, VideoRenderer* renderer) {
  VideoCapturerRendererParams params(capturer, renderer);
  return (Send(MSG_ADDVIDEORENDERER, &params) && params.result);
}

bool ChannelManager::AddVideoRenderer_w(
    VideoCapturer* capturer, VideoRenderer* renderer) {
  return capture_manager_->AddVideoRenderer(capturer, renderer);
}

bool ChannelManager::RemoveVideoRenderer(
    VideoCapturer* capturer, VideoRenderer* renderer) {
  VideoCapturerRendererParams params(capturer, renderer);
  return (Send(MSG_REMOVEVIDEORENDERER, &params) && params.result);
}

bool ChannelManager::RemoveVideoRenderer_w(
    VideoCapturer* capturer, VideoRenderer* renderer) {
  return capture_manager_->RemoveVideoRenderer(capturer, renderer);
}

bool ChannelManager::Send(uint32 id, talk_base::MessageData* data) {
  if (!worker_thread_ || !initialized_) return false;
  worker_thread_->Send(this, id, data);
  return true;
}

void ChannelManager::OnVideoCaptureStateChange(VideoCapturer* capturer,
                                               CaptureState result) {
  // TODO(whyuan): Check capturer and signal failure only for camera video, not
  // screencast.
  capturing_ = result == CS_RUNNING;
  main_thread_->Post(this, MSG_VIDEOCAPTURESTATE,
                     new CaptureStateParams(capturer, result));
}

void ChannelManager::OnMessage(talk_base::Message* message) {
  talk_base::MessageData* data = message->pdata;
  switch (message->message_id) {
    case MSG_CREATEVOICECHANNEL: {
      CreationParams* p = static_cast<CreationParams*>(data);
      p->voice_channel =
          CreateVoiceChannel_w(p->session, p->content_name, p->rtcp);
      break;
    }
    case MSG_DESTROYVOICECHANNEL: {
      VoiceChannel* p = static_cast<talk_base::TypedMessageData<VoiceChannel*>*>
          (data)->data();
      DestroyVoiceChannel_w(p);
      break;
    }
    case MSG_CREATEVIDEOCHANNEL: {
      CreationParams* p = static_cast<CreationParams*>(data);
      p->video_channel = CreateVideoChannel_w(p->session, p->content_name,
                                              p->rtcp, p->voice_channel);
      break;
    }
    case MSG_DESTROYVIDEOCHANNEL: {
      VideoChannel* p = static_cast<talk_base::TypedMessageData<VideoChannel*>*>
          (data)->data();
      DestroyVideoChannel_w(p);
      break;
    }
    case MSG_CREATEDATACHANNEL: {
      CreationParams* p = static_cast<CreationParams*>(data);
      p->data_channel =
          CreateDataChannel_w(p->session, p->content_name, p->rtcp);
      break;
    }
    case MSG_DESTROYDATACHANNEL: {
      DataChannel* p = static_cast<talk_base::TypedMessageData<DataChannel*>*>
          (data)->data();
      DestroyDataChannel_w(p);
      break;
    }
    case MSG_CREATESOUNDCLIP: {
      talk_base::TypedMessageData<Soundclip*> *p =
          static_cast<talk_base::TypedMessageData<Soundclip*>*>(data);
      p->data() = CreateSoundclip_w();
      break;
    }
    case MSG_DESTROYSOUNDCLIP: {
      talk_base::TypedMessageData<Soundclip*> *p =
          static_cast<talk_base::TypedMessageData<Soundclip*>*>(data);
      DestroySoundclip_w(p->data());
      break;
    }
    case MSG_SETAUDIOOPTIONS: {
      AudioOptionsParams* p = static_cast<AudioOptionsParams*>(data);
      p->result = SetAudioOptions_w(p->options, p->delay_offset,
                                    p->in_device, p->out_device);
      break;
    }
    case MSG_GETOUTPUTVOLUME: {
      VolumeLevel* p = static_cast<VolumeLevel*>(data);
      p->result = GetOutputVolume_w(&p->level);
      break;
    }
    case MSG_SETOUTPUTVOLUME: {
      VolumeLevel* p = static_cast<VolumeLevel*>(data);
      p->result = SetOutputVolume_w(p->level);
      break;
    }
    case MSG_SETLOCALMONITOR: {
      LocalMonitor* p = static_cast<LocalMonitor*>(data);
      p->result = SetLocalMonitor_w(p->enable);
      break;
    }
    case MSG_SETVIDEOOPTIONS: {
      VideoOptions* p = static_cast<VideoOptions*>(data);
      p->result = SetVideoOptions_w(p->cam_device);
      break;
    }
    case MSG_SETDEFAULTVIDEOENCODERCONFIG: {
      DefaultVideoEncoderConfig* p =
          static_cast<DefaultVideoEncoderConfig*>(data);
      p->result = SetDefaultVideoEncoderConfig_w(p->config);
      break;
    }
    case MSG_SETLOCALRENDERER: {
      LocalRenderer* p = static_cast<LocalRenderer*>(data);
      p->result = SetLocalRenderer_w(p->renderer);
      break;
    }
    case MSG_SETVIDEOCAPTURER: {
      Capturer* p = static_cast<Capturer*>(data);
      p->result = SetVideoCapturer_w(p->capturer);
      break;
    }
    case MSG_SETVIDEOCAPTURE: {
      CaptureParams* p = static_cast<CaptureParams*>(data);
      p->result = SetVideoCapture_w(p->capture);
      break;
    }
    case MSG_SETVOICELOGGING:
    case MSG_SETVIDEOLOGGING: {
      LoggingOptions* p = static_cast<LoggingOptions*>(data);
      bool video = (message->message_id == MSG_SETVIDEOLOGGING);
      SetMediaLogging_w(video, p->level, p->filter.c_str());
      break;
    }
    case MSG_VIDEOCAPTURESTATE: {
      CaptureStateParams* data =
          static_cast<CaptureStateParams*>(message->pdata);
      SignalVideoCaptureStateChange(data->capturer, data->state);
      delete data;
      break;
    }
    case MSG_TERMINATE: {
      Terminate_w();
      break;
    }
    case MSG_REGISTERVIDEOPROCESSOR: {
      VideoProcessorParams* data =
          static_cast<VideoProcessorParams*>(message->pdata);
      data->result = RegisterVideoProcessor_w(data->capturer, data->processor);
      break;
    }
    case MSG_UNREGISTERVIDEOPROCESSOR: {
      VideoProcessorParams* data =
          static_cast<VideoProcessorParams*>(message->pdata);
      data->result = UnregisterVideoProcessor_w(data->capturer,
                                                data->processor);
      break;
    }
    case MSG_REGISTERVOICEPROCESSOR: {
      VoiceProcessorParams* data =
          static_cast<VoiceProcessorParams*>(message->pdata);
      data->result = RegisterVoiceProcessor_w(data->ssrc,
                                              data->processor,
                                              data->direction);
      break;
    }
    case MSG_UNREGISTERVOICEPROCESSOR: {
      VoiceProcessorParams* data =
          static_cast<VoiceProcessorParams*>(message->pdata);
      data->result = UnregisterVoiceProcessor_w(data->ssrc,
                                              data->processor,
                                              data->direction);
      break;
    }
    case MSG_STARTVIDEOCAPTURE: {
      VideoCapturerFormatParams* data =
          static_cast<VideoCapturerFormatParams*>(message->pdata);
      data->result = StartVideoCapture_w(data->capturer, data->format);
      break;
    }
    case MSG_STOPVIDEOCAPTURE: {
      VideoCapturerFormatParams* data =
          static_cast<VideoCapturerFormatParams*>(message->pdata);
      data->result = StopVideoCapture_w(data->capturer, data->format);
      break;
    }
    case MSG_ADDVIDEORENDERER: {
      VideoCapturerRendererParams* data =
          static_cast<VideoCapturerRendererParams*>(message->pdata);
      data->result = AddVideoRenderer_w(data->capturer, data->renderer);
      break;
    }
    case MSG_REMOVEVIDEORENDERER: {
      VideoCapturerRendererParams* data =
          static_cast<VideoCapturerRendererParams*>(message->pdata);
      data->result = RemoveVideoRenderer_w(data->capturer, data->renderer);
      break;
    }
    case MSG_GETSTARTCAPTUREFORMAT: {
      StartCaptureParams* data =
          static_cast<StartCaptureParams*>(message->pdata);
      data->video_format = GetStartCaptureFormat_w();
      break;
    }
  }
}

static void GetDeviceNames(const std::vector<Device>& devs,
                           std::vector<std::string>* names) {
  names->clear();
  for (size_t i = 0; i < devs.size(); ++i) {
    names->push_back(devs[i].name);
  }
}

bool ChannelManager::GetAudioInputDevices(std::vector<std::string>* names) {
  names->clear();
  std::vector<Device> devs;
  bool ret = device_manager_->GetAudioInputDevices(&devs);
  if (ret)
    GetDeviceNames(devs, names);

  return ret;
}

bool ChannelManager::GetAudioOutputDevices(std::vector<std::string>* names) {
  names->clear();
  std::vector<Device> devs;
  bool ret = device_manager_->GetAudioOutputDevices(&devs);
  if (ret)
    GetDeviceNames(devs, names);

  return ret;
}

bool ChannelManager::GetVideoCaptureDevices(std::vector<std::string>* names) {
  names->clear();
  std::vector<Device> devs;
  bool ret = device_manager_->GetVideoCaptureDevices(&devs);
  if (ret)
    GetDeviceNames(devs, names);

  return ret;
}

void ChannelManager::SetVideoCaptureDeviceMaxFormat(
    const std::string& uvc_id,
    const VideoFormat& max_format) {
  device_manager_->SetVideoCaptureDeviceMaxFormat(uvc_id, max_format);
}

VideoFormat ChannelManager::GetStartCaptureFormat() {
  StartCaptureParams params;
  Send(MSG_GETSTARTCAPTUREFORMAT, &params);
  return params.video_format;
}

VideoFormat ChannelManager::GetStartCaptureFormat_w() {
  return media_engine_->GetStartCaptureFormat();
}

}  // namespace cricket


text:
<?php

/**
 * SlugStrategy.php
 *
 * @since 18/11/15
 * @author gseidel
 */

namespace Enhavo\Bundle\AppBundle\Preview\Strategy;

use Enhavo\Bundle\AppBundle\Exception\PreviewException;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Enhavo\Bundle\AppBundle\Preview\StrategyInterface;

class DynamicStrategy implements StrategyInterface
{
    use ContainerAwareTrait;

    /**
     * {@inheritdoc}
     */
    public function getPreviewResponse($resource, $options = array())
    {
        $map = $this->container->getParameter('cmf_routing.controllers_by_class');
        $controllerDefinition = null;
        foreach ($map as $class => $value) {
            if ($resource instanceof $class) {
                $controllerDefinition = $value;
                break;
            }
        }

        if($controllerDefinition === null) {
            throw new PreviewException(
                sprintf(
                    'No controller found for resource, did you add "%s" to cmf_routing.dynamic.controller_by_class in your configuration?',
                    get_class($resource)
                )
            );
        }

        try {
            $request = new Request(array(), array(), array('_controller' => $controllerDefinition));
            $controller = $this->container->get('debug.controller_resolver')->getController($request);
            $response = call_user_func_array($controller, array($resource));
        } catch(\Exception $e) {
            throw new PreviewException(
                sprintf(
                    'Something went wrong while trying to invoke the controller "%s", this "%s" was thrown before with message: %s',
                    $controllerDefinition,
                    get_class($e),
                    $e->getMessage()
                )
            );
        }

        return $response;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.wicket.markup.html.header.testing3;

import org.apache.wicket.markup.html.panel.Panel;

/**
 *
 * @author Juergen Donnerstag
 */
public class Panel1 extends Panel
{
	private static final long serialVersionUID = 1L;

	/**
	 * Construct.
	 *
	 * @param id
	 */
	public Panel1(final String id)
	{
		super(id);
	}
}


text:
'use strict';

// Contactnotes controller
angular.module('contactnotes').controller('ContactnotesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Contactnotes',
	function($scope, $stateParams, $location, Authentication, Contactnotes) {
		$scope.authentication = Authentication;

		// Create new Contactnote
		$scope.create = function() {
			// Create new Contactnote object
			var contactnote = new Contactnotes ({
				name: this.name
			});

			// Redirect after save
			contactnote.$save(function(response) {
				$location.path('contactnotes/' + response._id);

				// Clear form fields
				$scope.name = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Contactnote
		$scope.remove = function(contactnote) {
			if ( contactnote ) {
				contactnote.$remove();

				for (var i in $scope.contactnotes) {
					if ($scope.contactnotes [i] === contactnote) {
						$scope.contactnotes.splice(i, 1);
					}
				}
			} else {
				$scope.contactnote.$remove(function() {
					$location.path('contactnotes');
				});
			}
		};

		// Update existing Contactnote
		$scope.update = function() {
			var contactnote = $scope.contactnote;

			contactnote.$update(function() {
				$location.path('contactnotes/' + contactnote._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Contactnotes
		$scope.find = function() {
			$scope.contactnotes = Contactnotes.query();
		};

		// Find existing Contactnote
		$scope.findOne = function() {
			$scope.contactnote = Contactnotes.get({
				contactnoteId: $stateParams.contactnoteId
			});
		};
	}
]);


text:
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Windows.Forms;

using ADODB;

using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using Miner.Framework;

namespace Miner.Interop
{
    /// <summary>
    ///     An abstract class that can be used to customize the user interface of the ArcFM Login
    /// </summary>
    /// <remarks>
    ///     It uses the <see cref="Miner.Interop.MMFrameworkLoginObjectClass" />
    ///     to handling logging into the ArcFM Framework.
    /// </remarks>
    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.None)]
    public abstract class BaseLogin : BaseLogin<Form>
    {
        #region Constructors

        /// <summary>
        ///     Initializes a new instance of the <see cref="BaseLogin" /> class.
        /// </summary>
        /// <param name="window">The window.</param>
        protected BaseLogin(Form window)
            : base(window)
        {
        }

        #endregion
    }

    /// <summary>
    ///     An abstract class that can be used to customize the user interface of the ArcFM Login
    /// </summary>
    /// <typeparam name="TWindow">The type of the window.</typeparam>
    /// <remarks>
    ///     It uses the <see cref="Miner.Interop.MMFrameworkLoginObjectClass" />
    ///     to handling logging into the ArcFM Framework.
    /// </remarks>
    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.None)]
    public abstract class BaseLogin<TWindow> : IMMLoginObject, IMMChangeDefaultVersion, IMMAdoConnection
        where TWindow : Form
    {
        #region Constants

        /// <summary>
        ///     The property set name that the internal product uses to locate the process framework connection string.
        /// </summary>
        private const string PxConnectionString = "PXCONNECTIONSTRING";

        #endregion

        #region Fields

        private readonly MMFrameworkLoginObjectClass _LoginObject;

        #endregion

        #region Constructors

        /// <summary>
        ///     Initializes a new instance of the <see cref="BaseLogin{TWindow}" /> class.
        /// </summary>
        /// <param name="window">The window.</param>
        protected BaseLogin(TWindow window)
        {
            _LoginObject = new MMFrameworkLoginObjectClass();
            Window = window;
        }

        #endregion

        #region Public Properties

        /// <summary>
        ///     Gets the connection.
        /// </summary>
        /// <value>
        ///     The connection.
        /// </value>
        public virtual Connection Connection
        {
            get { return _LoginObject.Connection; }
        }

        /// <summary>
        ///     Gets a value indicating whether this instance is valid login.
        /// </summary>
        /// <value>
        ///     <c>true</c> if this instance is valid login; otherwise, <c>false</c>.
        /// </value>
        public virtual bool IsValidLogin
        {
            get { return _LoginObject.IsValidLogin; }
        }

        /// <summary>
        ///     Gets the login workspace.
        /// </summary>
        /// <value>
        ///     The login workspace.
        /// </value>
        public virtual IWorkspace LoginWorkspace
        {
            get { return _LoginObject.LoginWorkspace; }
        }

        /// <summary>
        ///     Gets the name of the user.
        /// </summary>
        /// <value>
        ///     The name of the user.
        /// </value>
        public virtual string UserName
        {
            get { return _LoginObject.UserName; }
        }

        #endregion

        #region Protected Properties

        /// <summary>
        ///     Gets the connection properties for the user selected default connection.
        /// </summary>
        /// <returns>A property set of the connection properties for the default connection.</returns>
        protected abstract IPropertySet ConnectionProperties { get; }

        /// <summary>
        ///     Gets the window.
        /// </summary>
        /// <value>
        ///     The window.
        /// </value>
        protected TWindow Window { get; }

        #endregion

        #region Public Methods

        /// <summary>
        ///     Changes the default version.
        /// </summary>
        /// <param name="pVersion">The version.</param>
        public virtual void ChangeDefaultVersion(IVersion pVersion)
        {
            _LoginObject.ChangeDefaultVersion(pVersion);
        }

        /// <summary>
        ///     Gets the full name of the table.
        /// </summary>
        /// <param name="bstrBaseTableName">Name of the BSTR base table.</param>
        /// <returns>
        ///     The full name of the table name.
        /// </returns>
        public virtual string GetFullTableName(string bstrBaseTableName)
        {
            return _LoginObject.GetFullTableName(bstrBaseTableName);
        }

        /// <summary>
        ///     Attempts the log into the ArcMap session. This method is called within exception handling.
        /// </summary>
        /// <param name="vbInitialLogin">if set to <c>true</c> this is the initial login.</param>
        /// <returns>
        ///     <c>true</c> if the login is successful otherwise <c>false</c>
        /// </returns>
        /// <remarks>
        ///     The DialogResult will be used to determine the execution path.
        ///     OK - Attempt to log into the geodatabase and process framework.
        ///     Retry - Display the login form again.
        ///     Cancel - Closes the login form and terminates the ArcMap session.
        ///     All Others - Shows the default OOTB login.
        /// </remarks>
        public virtual bool Login(bool vbInitialLogin)
        {
            switch (Window.ShowDialog(Document.ParentWindow))
            {
                case DialogResult.OK:

                    // Set the database connection information
                    _LoginObject.SetConnectionProperties(this.ConnectionProperties);
                    _LoginObject.ShowDialog = false;

                    if (!_LoginObject.Login(vbInitialLogin))
                        return this.Login(vbInitialLogin);

                    // Validate the system tables are present.
                    if (!((IMMDefaultLoginObject2) _LoginObject).ValidateSystemTables(this.LoginWorkspace, Window.Text))
                        return this.Login(vbInitialLogin);

                    return true;

                case DialogResult.Retry:
                    return this.Login(vbInitialLogin);

                case DialogResult.Cancel:
                    return true;

                default:
                    _LoginObject.ShowDialog = true;
                    return _LoginObject.Login(vbInitialLogin);
            }
        }

        #endregion

        #region Protected Methods

        /// <summary>
        ///     Updates the connection string and sets the value in the PXCONNECTIONSTRING property.
        /// </summary>
        /// <param name="propertySet">The property set.</param>
        /// <param name="userName">Name of the user.</param>
        /// <param name="password">The password.</param>
        /// <returns>
        ///     The updated property set.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">propertySet</exception>
        protected IPropertySet AddPxConnection(IPropertySet propertySet, string userName, string password)
        {
            if (propertySet == null) throw new ArgumentNullException("propertySet");

            string connectionString = propertySet.GetProperty(PxConnectionString, string.Empty);
            if (!string.IsNullOrEmpty(connectionString))
            {
                if (propertySet.GetProperty("AUTHENTICATION_MODE", "DBMS") == "OSA")
                    connectionString = string.Format(CultureInfo.InvariantCulture, "{0}User Id={1};Password={2}", connectionString, userName, password);
                else
                    connectionString = string.Format(CultureInfo.InvariantCulture, "{0}User Id={1};", connectionString, userName);

                propertySet.SetProperty(PxConnectionString, connectionString);
            }

            return propertySet;
        }

        #endregion
    }
}


text:
@interface PodsDummy_Pods_IMWozhua : NSObject
@end
@implementation PodsDummy_Pods_IMWozhua
@end


text:
$('.navbar-header .nav a h4').html('Group');
$('[href="/admin/groups"]').parent().addClass('active');

$g.getData('/api/'+route+'s/'+resource_id+'/summary', group => {
        group.mypages = group.pages; // TJC -- For some reason, can't reference pages in the mustache template.
		$('#table').html(templates.group_summary.render({...group, group_slug: group.slug}, templates));
	}
);


text:
module MotionMastr
  class MastrBuilder

    include Attributes

    attr_reader :default_styles, :pieces

    ATTRIBUTES = {
      font_attribute:                NSFontAttributeName,
      foreground_color_attribute:    NSForegroundColorAttributeName,
      background_color_attribute:    NSBackgroundColorAttributeName,
      stroke_color_attribute:        NSStrokeColorAttributeName,
      strikethrough_color_attribute: NSStrikethroughColorAttributeName,
      underline_color_attribute:     NSUnderlineColorAttributeName,
      ligature_attribute:            NSLigatureAttributeName,
      kern_attribute:                NSKernAttributeName,
      paragraph_style_attribute:     NSParagraphStyleAttributeName,
      strikethrough_style_attribute: NSStrikethroughStyleAttributeName,
      underline_style_attribute:     NSUnderlineStyleAttributeName,
      stroke_width_attribute:        NSStrokeWidthAttributeName,
      shadow_attribute:              NSShadowAttributeName,
      text_effect_attribute:         NSTextEffectAttributeName,
      attachment_attribute:          NSAttachmentAttributeName,
      link_attribute:                NSLinkAttributeName,
      baseline_offset_attribute:     NSBaselineOffsetAttributeName,
      obliqueness_attribute:         NSObliquenessAttributeName,
      expansion_attribute:           NSExpansionAttributeName,
    }

    def initialize(default_styles={})
      @default_styles = default_styles || {}
      @pieces = []
    end

    # write to default styles
    def []=(key, value)
      @default_styles[key] = value
    end

    # read from default styles
    def [](key)
      @default_styles[key]
    end

    # add a piece of text and optional styles
    def add(text, styles={})
      @pieces << {text: text, styles: styles} unless text.nil?
      self
    end

    def build
      # weld up the text pieces
      text = @pieces.map { |p| p[:text] }.join

      # compose a attribute string
      result = NSMutableAttributedString.alloc.initWithString(text)

      # style it with the default styles
      apply_attributes result, 0, text.length, @default_styles

      # apply the styles from the pieces
      idx = 0
      @pieces.each do |piece|
        apply_attributes result, idx, piece[:text].length, piece[:styles]
        idx += piece[:text].length
      end

      result
    end

    # applies styles in a range to the attributed string
    def apply_attributes(attributed_string, start, length, styles)
      return unless attributed_string && start && length && styles # sanity
      return unless start >= 0 && length > 0 && styles.length > 0  # minimums
      return unless start + length <= attributed_string.length     # maximums

      range = [start, length]

      ATTRIBUTES.each_pair do |method_name, attribute_name|
        value = send method_name, styles
        attributed_string.addAttribute(attribute_name, value: value, range: range) if value
      end
    end

  end
end


text:
package com.bagri.server.hazelcast.task.auth;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.bagri.core.api.SchemaRepository;
import com.bagri.server.hazelcast.impl.ClientManagementImpl;
import com.bagri.server.hazelcast.impl.SchemaRepositoryImpl;
import com.hazelcast.spring.context.SpringAware;

@SpringAware
public class ChildIdsRegistrator extends com.bagri.client.hazelcast.task.auth.ChildIdsRegistrator {

	private static final transient Logger logger = LoggerFactory.getLogger(ChildIdsRegistrator.class);

	@Autowired
    @Override
	public void setRepository(SchemaRepository repo) {
		this.repo = repo;
	}

    @Override
	public Void call() throws Exception {
    	SchemaRepositoryImpl xRepo = (SchemaRepositoryImpl) repo;
    	ClientManagementImpl cmi = (ClientManagementImpl) xRepo.getClientManagement();
    	String userName = cmi.getClientUser(clientId);
    	logger.trace("registering client: {}", clientId);
    	for (String childId: childIds) {
        	logger.trace("registering child: {}", childId);
    		cmi.addClient(childId, userName);
    		xRepo.getXQProcessor(childId);
    	}
    	xRepo.setClientId(clientId);
    	return null;
    }

}


text:
layout: essay
type: essay
title: The Ultimate Landing Package
date: 2017-03-23
labels:
  - Meteor
  - Web - Application
---

## Meteor came along saving us all from archiac monstronsities of earlier millennium web designs

<img class="ui floated medium left image" src="/images/degree_difficulty.jpg">

Meteor was first released back in 2011, and since then it's been one of the most powerful platforms for web developers. One of the more powerful ones is where the client, server and the database can share code, almost the same API and code snippets, which really accelerated the development process. This built application can be easily consumed by a wide variety other tools that work with Node and Javascript apps. It is a module-bundler which will take a bunch of Meteor packages and bundle them into a single script, based on a specified configuration. Applications which are not based on Meteor can use the DDP client to fetch data from a Meteor-service.
 - We can gradually migrate outdated front-end applications into Meteor
 - We can use other CLI tools besides Meteor's like WebPack, Angular and Ionic CLIs and more and not be locked in on a single CLI
 - Use Meteor when and where it excels and where it fits your needs.

I'm interested in streamlining my ability to get things done by focusing on learning Meteor.
My main focus is time to production. That web is currently morphing into something better, something more modern that fits current design protocols of accessibility and browser standards. If I can skip the learning curve of Node for a small performance decrease, that's an easy decision for me.  Part of the development process is to pick the right tool for the project. Meteor can do all of the things you want in some way or another (it is just a Node application after all and can therefore use other Node packages) but it's not a good pick for any of them and it might even end up increasing development time because you'll have to figure out how to do things properly in Meteor. Edit to clarify: If there's a thing Meteor normally doesn't support out of the box you'll have to figure out how to coax Meteor into doing it anyway without breaking things.

If you want to build an app while using the Meteor platform for all your stack, or you want to interact with a Meteor server and use any other front-end library or setup, and will get you on the right track.


text:
package com.googlecode.jmapper.integrationtest.configurations.bean;

public class JGlobalMapS {
	private String field;
	private String field2;
	private String field3;

	public JGlobalMapS() {}

	public JGlobalMapS(String field, String field2, String field3) {
		super();
		this.field = field;
		this.field2 = field2;
		this.field3 = field3;
	}

	public String getField() {
		return field;
	}
	public void setField(String field) {
		this.field = field;
	}
	public String getField2() {
		return field2;
	}
	public void setField2(String field2) {
		this.field2 = field2;
	}
	public String getField3() {
		return field3;
	}
	public void setField3(String field3) {
		this.field3 = field3;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((field == null) ? 0 : field.hashCode());
		result = prime * result + ((field2 == null) ? 0 : field2.hashCode());
		result = prime * result + ((field3 == null) ? 0 : field3.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		JGlobalMapS other = (JGlobalMapS) obj;
		if (field == null) {
			if (other.field != null)
				return false;
		} else if (!field.equals(other.field))
			return false;
		if (field2 == null) {
			if (other.field2 != null)
				return false;
		} else if (!field2.equals(other.field2))
			return false;
		if (field3 == null) {
			if (other.field3 != null)
				return false;
		} else if (!field3.equals(other.field3))
			return false;
		return true;
	}
}


text: **bold** text **bold** text


text:
package androidx.core.os;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import static java.util.Arrays.asList;
import static java.util.concurrent.TimeUnit.SECONDS;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;

import androidx.test.filters.MediumTest;
import androidx.test.filters.SdkSuppress;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

@MediumTest
public final class HandlerCompatTest {
    private final HandlerThread mThread = new HandlerThread("handler-compat-test");

    @Before
    public void before() {
        mThread.start();
    }

    @After
    public void after() {
        assertTrue(mThread.quit());
    }

    @Test
    public void postDelayedWithToken() throws InterruptedException {
        final Handler handler = new Handler(mThread.getLooper());

        // Schedule a latch at 300ms to block the test thread.
        final CountDownLatch latch = new CountDownLatch(1);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                latch.countDown();
            }
        }, 300);

        final List<String> events = new ArrayList<>();
        final Object token = new Object();

        // Schedule an event at 200ms with the token.
        HandlerCompat.postDelayed(handler, new Runnable() {
            @Override
            public void run() {
                events.add("200");
            }
        }, token, 200);

        // Schedule an event at 100ms which removes future messages with the token.
        HandlerCompat.postDelayed(handler, new Runnable() {
            @Override
            public void run() {
                events.add("100");
                handler.removeCallbacksAndMessages(token);
            }
        }, token, 100);

        // Schedule an event immediately to ensure the delays are being honored.
        handler.post(new Runnable() {
            @Override
            public void run() {
                events.add("0");
            }
        });

        assertTrue(latch.await(1, SECONDS));
        assertEquals(asList("0", "100"), events);
    }

    @Test
    public void createAsyncAllApiLevels() throws InterruptedException {
        Handler handler = HandlerCompat.createAsync(mThread.getLooper());

        final CountDownLatch latch = new CountDownLatch(1);
        Message message = Message.obtain(handler, new Runnable() {
            @Override
            public void run() {
                latch.countDown();
            }
        });

        handler.sendMessage(message);

        assertTrue(latch.await(1, SECONDS));
    }

    @SdkSuppress(minSdkVersion = 17)
    @Test
    public void createAsyncWhenAsyncAvailable() throws InterruptedException {
        Handler handler = HandlerCompat.createAsync(mThread.getLooper());

        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicReference<Boolean> isAsync = new AtomicReference<>();
        final AtomicReference<Message> self = new AtomicReference<>();
        Message message = Message.obtain(handler, new Runnable() {
            @Override
            public void run() {
                isAsync.set(MessageCompat.isAsynchronous(self.get()));
                latch.countDown();
            }
        });
        self.set(message);

        handler.sendMessage(message);

        assertTrue(latch.await(1, SECONDS));
        assertTrue(isAsync.get());
    }

    @Test
    public void createAsyncWithCallbackAllApiLevels() throws InterruptedException {
        final CountDownLatch latch = new CountDownLatch(1);
        Handler handler = HandlerCompat.createAsync(mThread.getLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                latch.countDown();
                return true;
            }
        });

        handler.sendEmptyMessage(0);
        assertTrue(latch.await(1, SECONDS));
    }

    @SdkSuppress(minSdkVersion = 17)
    @Test
    public void createAsyncWithCallbackWhenAsyncAvailable() throws InterruptedException {
        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicReference<Boolean> isAsync = new AtomicReference<>();
        Handler handler = HandlerCompat.createAsync(mThread.getLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                isAsync.set(MessageCompat.isAsynchronous(msg));
                latch.countDown();
                return true;
            }
        });

        handler.sendEmptyMessage(0);
        assertTrue(latch.await(1, SECONDS));
        assertTrue(isAsync.get());
    }

    @SdkSuppress(minSdkVersion = 16)
    @Test
    public void testHasCallbacks() {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                // Meh?
            }
        };

        PausedLooper looperThread = new PausedLooper();
        looperThread.start();

        Handler handler = looperThread.getHandler(1000);
        handler.post(r);

        assertTrue("Handler has callback for r", HandlerCompat.hasCallbacks(handler, r));
    }

    private static class PausedLooper extends Thread {
        private final Semaphore mHandlerLock = new Semaphore(0);
        private Handler mHandler;

        @Override
        public void run() {
            Looper.prepare();
            mHandler = new Handler(Looper.myLooper());
            mHandlerLock.release();
        }

        public Handler getHandler(long timeout) {
            try {
                mHandlerLock.tryAcquire(1, timeout, TimeUnit.MILLISECONDS);
            } catch (InterruptedException ignored) {
            }
            return mHandler;
        }
    }
}


text: puppet agent -t


text:
.PHONY: clean-pyc clean-build clean

help:
	@echo "clean - remove all build, test, coverage and Python artifacts"
	@echo "clean-build - remove build artifacts"
	@echo "clean-pyc - remove Python file artifacts"
	@echo "release - package and upload a release"
	@echo "dist - package"
	@echo "install - install the package to the active Python's site-packages"
	@echo "authors - update list of authors"
	@echo "test - run tests for current version of python"
	@echo "run_example - istall and run example"

clean: clean-build clean-pyc

clean-build:
	rm -fr build/
	rm -fr dist/
	rm -fr .eggs/
	rm -fr venv_temp/
	find . -name '*.egg-info' -not -path '*venv_18*' -exec rm -fr {} +
	find . -name '*.egg' -not -path '*venv_18*' -exec rm -f {} +

clean-pyc:
	find . -name '*.pyc' -exec rm -f {} +
	find . -name '*.pyo' -exec rm -f {} +
	find . -name '*~' -exec rm -f {} +
	find . -name '__pycache__' -exec rm -fr {} +

release: clean
	python setup.py sdist upload

dist: clean
	python setup.py sdist
	ls -l dist

install: clean
	python setup.py install

authors:
	git log --format='%aN <%aE>' | sort -u | cat > AUTHORS.rst

test:
	python runtests.py

run_example:
	pip install Flask
	python setup.py develop
	python example/main.py


text:
package at.vizu.s2n.generator

/**
  * Phil on 02.12.15.
  */
object CodePrettifier {

  def prettify(content: String): String = {
    var intendLevel = 0
    content.split("\n").foldLeft("")((tmp, line) => {
      val trimmedLine = line.trim
      val (tmpIntendLevel, newLineCount) = if (trimmedLine.endsWith("{") && trimmedLine.startsWith("}")) {
        (intendLevel - 1, 1)
      } else if (trimmedLine.endsWith("{")) {
        intendLevel += 1
        (intendLevel - 1, 1)
      } else if (trimmedLine.startsWith("}")) {
        intendLevel -= 1
        (intendLevel, if (intendLevel == 0) 1 else 1)
      } else {
        (intendLevel, 1)
      }

      tmp + "  " * tmpIntendLevel + trimmedLine + "\n" * newLineCount
    })
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  #%L
  SparkCommerce CMS Module
  %%
  Copyright (C) 2009 - 2013 Spark Commerce
  %%
  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.
  #L%
  -->

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

    <!-- Entity mappings - override for extensibility -->
    <bean id="org.sparkcommerce.cms.page.domain.Page" class="org.sparkcommerce.cms.page.domain.PageImpl" scope="prototype"/>
    <bean id="org.sparkcommerce.cms.page.domain.PageRule" class="org.sparkcommerce.cms.page.domain.PageRuleImpl" scope="prototype"/>

    <bean id="org.sparkcommerce.cms.page.domain.PageTemplate" class="org.sparkcommerce.cms.page.domain.PageTemplateImpl" scope="prototype"/>
    <bean id="org.sparkcommerce.cms.file.domain.StaticAssetStorage" class="org.sparkcommerce.cms.file.domain.StaticAssetStorageImpl" scope="prototype"/>
    <bean id="org.sparkcommerce.cms.file.domain.StaticAsset" class="org.sparkcommerce.cms.file.domain.StaticAssetImpl" scope="prototype"/>
    <bean id="org.sparkcommerce.cms.structure.domain.StructuredContent" class="org.sparkcommerce.cms.structure.domain.StructuredContentImpl" scope="prototype"/>
    <bean id="org.sparkcommerce.cms.structure.domain.StructuredContentType" class="org.sparkcommerce.cms.structure.domain.StructuredContentTypeImpl" scope="prototype"/>
    <bean id="org.sparkcommerce.cms.structure.domain.StructuredContentFieldTemplate" class="org.sparkcommerce.cms.structure.domain.StructuredContentFieldTemplateImpl" scope="prototype"/>
    <bean id="org.sparkcommerce.cms.structure.domain.StructuredContentRule" class="org.sparkcommerce.cms.structure.domain.StructuredContentRuleImpl" scope="prototype"/>
    <bean id="org.sparkcommerce.cms.url.domain.URLHandler" class="org.sparkcommerce.cms.url.domain.URLHandlerImpl" scope="prototype"/>

</beans>


text:
// Copyright (c) 2011 Hewlett-Packard Development Company, L.P. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef WEBVFX_LOGGER_H_
#define WEBVFX_LOGGER_H_

class QString;

namespace WebVfx {

/*!
 * @brief Callback interface to expose logging.
 *
 * An instance of this class should be passed to WebVfx::setLogger().
 * WebVfx will then log all messages using that instance.
 */
class Logger
{
public:
    virtual ~Logger() = 0;

    /*!
     * @brief Called whenever WebVfx needs to log a message.
     *
     * @param msg Message to be logged.
     */
    //XXX should add log level enum
    virtual void log(const QString& msg) = 0;
};

}

#endif


text:
package org.kie.workbench.common.screens.library.api.index;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.junit.Test;

import static org.junit.Assert.*;

public class LibraryValueFileExtensionIndexTermTest {

    @Test(expected = IllegalArgumentException.class)
    public void testZeroExtension() {
        List<String> extensions = Collections.emptyList();
        LibraryValueFileExtensionIndexTerm term = new LibraryValueFileExtensionIndexTerm(extensions);
    }

    @Test
    public void testOneExtension() {
        List<String> extensions = Arrays.asList("xml");
        LibraryValueFileExtensionIndexTerm term = new LibraryValueFileExtensionIndexTerm(extensions);
        assertEquals(".*(xml)",
                     term.getValue());
    }

    @Test
    public void testSeveralExtensions() {
        List<String> extensions = Arrays.asList("xml",
                                                "java",
                                                "drl");
        LibraryValueFileExtensionIndexTerm term = new LibraryValueFileExtensionIndexTerm(extensions);
        assertEquals(".*(xml|java|drl)",
                     term.getValue());
    }
}


text:
#include <stdint.h>

#include "hecmw_fstr_endian.h"

/**
 * @fn void HECMW_is_big_endian(void)
 * @brief function for investigating endian of running CPU
 * @param[in] void
 * @return bool if running CPU is big endian, return true,
 * @details if running CPU is big endian, return true.
 *          if it is little endian, return false.
 */
bool HECMW_is_big_endian(void) {
  union {
    uint32_t i;
    char c[4];
  } endian = {0x01020304};

  return endian.c[0] == true;
}

/**
 * @fn void HECMW_endian_str(void)
 * @brief function for investigating endian of running CPU
 * @param[in] void
 * @return const char* if running CPU is big endian, return "BigEndian",
 * @details if running CPU is big endian, return "BigEndian" as const char*.
 *          if it is little endian, return "LittleEndian" as const char*.
 */
const char* HECMW_endian_str(void) {
  if (HECMW_is_big_endian() == true) {
    return "BigEndian";
  } else {
    return "LittleEndian";
  }
}


text:
lang:   PT-BR
title:  Um Cálculo
answer: \w+
ok:     Yodelay!
error:
---

Uma das coisas incríveis que nós acabamos de usar é o __bloco__. Nós vamos explorar mais isso
nesta e na próxima lição. Mas, basicamente, um bloco é um pedaço de código Ruby cercado por chaves {}.

Vamos tentar outro bloco:

    5.times { print "Odelay! " }

Blocos são sempre associados a métodos. Como o método __times__, que pega o bloco e roda o código
dele várias e várias vezes. (No nosso exemplo: cinco vezes).


text:
function(managed_package_source source_name directory)
  path_qualify(directory)
  obj("{
    source_name:$source_name,
    directory:$directory,
    pull:'package_source_pull_managed',
    push:'package_source_push_managed',
    query:'package_source_query_managed',
    resolve:'package_source_resolve_managed',
    delete:'package_source_delete_managed'
  }")
  return_ans()
endfunction()


text:
package archive

import (
	"context"

	"go-common/app/job/main/videoup/model/archive"
	xsql "go-common/library/database/sql"
	"go-common/library/log"
)

const (
	_arcPOISQL  = "SELECT data from archive_biz   WHERE aid=? AND type= ?"
	_arcVoteSQL = "SELECT data from archive_biz   WHERE aid=? AND type=2"
)

// POI get a archive POI by avid.
func (d *Dao) POI(c context.Context, aid int64) (data []byte, err error) {
	var (
		row = d.db.QueryRow(c, _arcPOISQL, aid, archive.BIZPOI)
	)
	if err = row.Scan(&data); err != nil {
		if err == xsql.ErrNoRows {
			err = nil
		} else {
			log.Error("row.Scan error(%v)", err)
		}
		return
	}
	return
}

// Vote get a archive Vote by avid.
func (d *Dao) Vote(c context.Context, aid int64) (data []byte, err error) {
	var (
		row = d.db.QueryRow(c, _arcVoteSQL, aid)
	)
	if err = row.Scan(&data); err != nil {
		if err == xsql.ErrNoRows {
			err = nil
		} else {
			log.Error("row.Scan error(%v)", err)
		}
		return
	}
	return
}


text:
{-# LANGUAGE ViewPatterns, TupleSections, RecordWildCards, ScopedTypeVariables, PatternGuards, DeriveDataTypeable #-}

module Output.Items(writeItems, lookupItem) where

import Language.Haskell.Exts
import System.IO.Extra
import Data.List.Extra
import System.FilePath
import Control.Monad.Extra
import Data.Maybe
import Data.IORef
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy.Char8 as LBS
import qualified Data.ByteString.Lazy.UTF8 as UTF8

import Input.Type
import General.Util
import General.Store

outputItem :: (Id, ItemEx) -> [String]
outputItem (i, ItemEx{..}) =
    [show i ++ " " ++ showItem itemItem
    ,if null itemURL then "." else itemURL
    ,maybe "." (joinPair " ") itemPackage
    ,maybe "." (joinPair " ") itemModule] ++
    replace [""] ["."] (lines itemDocs)

inputItem :: [String] -> (Id, ItemEx)
inputItem ((word1 -> (i,name)):url:pkg:modu:docs) = (,) (read i) $ ItemEx
    (fromMaybe (error $ "Failed to reparse: " ++ name) $ readItem name)
    (if url == "." then "" else url)
    (f pkg) (f modu) (unlines docs)
    where
        f "." = Nothing
        f x = Just (word1 x)

data Items = Items deriving Typeable

-- write all the URLs, docs and enough info to pretty print it to a result
-- and replace each with an identifier (index in the space) - big reduction in memory
writeItems :: StoreOut -> FilePath -> [Either String ItemEx] -> IO [(Maybe Id, Item)]
writeItems store file xs = do
    warns <- newIORef 0
    pos <- newIORef 0
    res <- writeStoreType store Items $ writeStoreParts store $ do
        withBinaryFile (file <.> "warn") WriteMode $ \herr -> do
            hSetEncoding herr utf8
            flip mapMaybeM xs $ \x -> case x of
                Right item@ItemEx{..} | f itemItem -> do
                    i <- readIORef pos
                    let bs = BS.concat $ LBS.toChunks $ UTF8.fromString $ unlines $ outputItem (Id i, item)
                    writeStoreBS store $ intToBS $ BS.length bs
                    writeStoreBS store bs
                    writeIORef pos $ i + fromIntegral (intSize + BS.length bs)
                    return $ Just (Just $ Id i, itemItem)
                Right ItemEx{..} -> return $ Just (Nothing, itemItem)
                Left err -> do modifyIORef warns (+1); hPutStrLn herr err; return Nothing
    warns <- readIORef warns
    unless (warns == 0) $
        putStrLn $ "Failed to parse " ++ show warns ++ " definitions, see " ++ file <.> "warn"
    return res
    where
        f :: Item -> Bool
        f (IDecl i@InstDecl{}) = False
        f x = True

lookupItem :: StoreIn -> IO (Id -> IO ItemEx)
lookupItem store = do
    let x = readStoreBS $ readStoreType Items store
    return $ \(Id i) -> do
        let i2 = fromIntegral i
        let n = intFromBS $ BS.take intSize $ BS.drop i2 x
        return $ snd $ inputItem $ lines $ UTF8.toString $ LBS.fromChunks $ return $ BS.take n $ BS.drop (i2 + intSize) x


text:
<?php

namespace Jdomenechb\XSLT2Processor\XPath\FunctionImplementation\Fn;

use Jdomenechb\XSLT2Processor\XML\DOMNodeList;
use Jdomenechb\XSLT2Processor\XML\DOMResultTree;
use Jdomenechb\XSLT2Processor\XML\NotANumber;
use Jdomenechb\XSLT2Processor\XPath\FunctionImplementation\AbstractFunctionImplementation;
use Jdomenechb\XSLT2Processor\XPath\XPathFunction;

/**
 * Function number() from XSLT standard library.
 */
class Number extends AbstractFunctionImplementation
{
    /**
     * {@inheritdoc}
     *
     * @param XPathFunction $func
     * @param $context
     *
     * @return string
     */
    public function evaluate(XPathFunction $func, $context)
    {
        if (count($func->getParameters()) === 0) {
            $toEvaluate = $context;
        } else {
            $toEvaluate = $func->getParameters()[0]->evaluate($context);
        }

        if ($toEvaluate instanceof DOMNodeList) {
            if (!$toEvaluate->count()) {
                return new NotANumber();
            }

            $toEvaluate = $toEvaluate->item(0);
        }

        if ($toEvaluate instanceof \DOMNode) {
            $toEvaluate = $toEvaluate->nodeValue;
        }

        if ($toEvaluate instanceof DOMResultTree) {
            $toEvaluate = $toEvaluate->evaluate();
        }

        if (!is_string($toEvaluate) || $toEvaluate !== '' || is_numeric($toEvaluate)) {
            return (float) $toEvaluate;
        }

        return new NotANumber();
    }
}


text:
namespace ast {
class Variable : public Expression {
 public:
  Variable(lexer::Position position, const std::string& name)
      : Expression(position), name_(name), v_(nullptr) {
    DebugLog(position, "Variable: ", name_);
  }
  llvm::Value* Codegen() const override;
  llvm::Type* Type() const override;

  const std::string& name() const { return name_; }

 private:
  std::string name_;

  mutable llvm::Value* v_;
};
}  // end namespace ast

#endif


text:
title: "Furry hat snuggling a Siamese cat"
excerpt: "PaperFaces portrait of @ihatealexwright drawn with Paper for iOS on an iPad."
image:
  path: &image /assets/images/paperfaces-ihatealexwright-twitter.jpg
  feature: *image
  thumbnail: /assets/images/paperfaces-ihatealexwright-twitter-150.jpg
categories: [paperfaces]
tags: [portrait, illustration, Paper for iOS]
---

PaperFaces portrait of [@ihatealexwright](https://twitter.com/ihatealexwright).

{% include_cached boilerplate/paperfaces.md %}


text:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser';

import { Vacancy } from '@services/classes/vacancy';
import { VacanciesService } from '@services/vacancies.service';

@Component({
  selector: 'vacancy',
  templateUrl: './vacancy.html'
})
export class VacancyComponent implements OnInit {
  public pageName: string;
  public vacancy: Vacancy;
  public vacancyId: number;

  constructor(private vacanciesService: VacanciesService, private route: ActivatedRoute, private _titleService: Title) {
  }

  private static incScrollTo(step: number): void {
    document.body.scrollTop += step;
  }

  private static goToScroll(step: number, duration: number, inc: number): any {
    return () => {
      const currentDuration = duration - inc;
      VacancyComponent.incScrollTo(step);

      if (currentDuration < inc) {
        return;
      }

      window.requestAnimationFrame(this.goToScroll(step, currentDuration, inc));
    };
  }

  public ngOnInit(): void {
    this.pageName = 'Vacancy page';
    this.route.params.subscribe((params: any) => {
      /* tslint:disable */
      this.vacancyId = params['vacancyId'];
      /* tslint:enable */

      this.vacancy = this.vacanciesService.getById(this.vacancyId);

      // setting up <title> and tab name
      this._titleService.setTitle(`Vacancy: ${this.vacancy.name}`);
    });
  }
}


text:
/**
 *
 */

package org.opensaml.saml2.core.impl;

import org.opensaml.common.impl.AbstractSAMLObjectMarshaller;

/**
 * A thread-safe Marshaller for {@link org.opensaml.saml2.core.Subject} objects.
 */
public class SubjectMarshaller extends AbstractSAMLObjectMarshaller {

}


text:
Run `dotnet build /t:GenerateCode` to generate code.

``` yaml

azure-arm: true
csharp: true
library-name: HDInsight
namespace: Azure.ResourceManager.HDInsight
require: https://github.com/Azure/azure-rest-api-specs/blob/bab2f4389eb5ca73cdf366ec0a4af3f3eb6e1f6d/specification/hdinsight/resource-manager/readme.md
output-folder: $(this-folder)/Generated
clear-output-folder: true
skip-csproj: true
modelerfour:
  flatten-payloads: false

format-by-name-rules:
  'tenantId': 'uuid'
  'ETag': 'etag'
  'location': 'azure-location'
  '*Uri': 'Uri'
  '*Uris': 'Uri'
  'privateIPAddress': 'ip-address'

rename-rules:
  CPU: Cpu
  CPUs: Cpus
  Os: OS
  Ip: IP
  Ips: IPs|ips
  ID: Id
  IDs: Ids
  VM: Vm
  VMs: Vms
  Vmos: VmOS
  VMScaleSet: VmScaleSet
  DNS: Dns
  VPN: Vpn
  NAT: Nat
  WAN: Wan
  Ipv4: IPv4|ipv4
  Ipv6: IPv6|ipv6
  Ipsec: IPsec|ipsec
  SSO: Sso
  URI: Uri
  Etag: ETag|etag
  RSA: Rsa
  RSA15: Rsa15
  Autoscale: AutoScale
  Mb: MB

override-operation-name:
  Locations_CheckNameAvailability: CheckHDInsightNameAvailability
  Locations_ListBillingSpecs: GetHDInsightBillingSpecs
  Locations_GetCapabilities: GetHDInsightCapabilities
  Locations_ListUsages: GetHDInsightUsages
  Locations_ValidateClusterCreateRequest: ValidateHDInsightClusterCreation
  Clusters_GetAzureAsyncOperationStatus: GetAsyncOperationStatus
  Extensions_GetAzureAsyncOperationStatus: GetExtensionAsyncOperationStatus
  Extensions_EnableMonitoring: EnableClusterMonitoringExtension
  Extensions_GetMonitoringStatus: GetClusterMonitoringExtensionStatus
  Extensions_DisableMonitoring: DisableClusterMonitoringExtension
  Extensions_EnableAzureMonitor: EnableAzureMonitorExtension
  Extensions_GetAzureMonitorStatus: GetAzureMonitorExtensionStatus
  Extensions_DisableAzureMonitor: DisableAzureMonitorExtension
  ScriptActions_GetExecutionDetail: GetScriptActionExecutionDetail
  ScriptActions_GetExecutionAsyncOperationStatus: GetScriptActionExecutionAsyncOperationStatus
  VirtualMachines_ListHosts: GetVirtualMachineHosts
  VirtualMachines_RestartHosts: RestartVirtualMachineHosts
  VirtualMachines_GetAsyncOperationStatus: GetVirtualMachineAsyncOperationStatus

rename-mapping:
  StorageAccount.saskey: SasKey
  Application: HDInsightApplication
  Cluster: HDInsightCluster
  NameAvailabilityCheckRequestParameters: HDInsightNameAvailabilityContent
  NameAvailabilityCheckResult: HDInsightNameAvailabilityResult
  ClusterCreateValidationResult: HDInsightClusterCreationValidateResult
  ClusterCreateRequestValidationParameters: HDInsightClusterCreationValidateContent
  AaddsResourceDetails: HDInsightClusterAaddsDetail
  ValidationErrorInfo: HDInsightClusterValidationErrorInfo
  AaddsResourceDetails.initialSyncComplete: IsInitialSyncComplete
  AaddsResourceDetails.ldapsEnabled: IsLdapsEnabled
  AaddsResourceDetails.resourceId: -|arm-id
  AaddsResourceDetails.subnetId: -|arm-id
  AsyncOperationResult: HDInsightAsyncOperationResult
  AsyncOperationState: HDInsightAsyncOperationState
  ApplicationProperties: HDInsightApplicationProperties
  ApplicationGetEndpoint: HDInsightApplicationEndpoint
  ApplicationGetHttpsEndpoint: HDInsightApplicationHttpsEndpoint
  Role: HDInsightClusterRole
  Autoscale: HDInsightAutoscaleConfiguration
  AutoscaleCapacity: HDInsightAutoscaleCapacity
  AutoscaleRecurrence: HDInsightAutoscaleRecurrence
  AutoscaleSchedule: HDInsightAutoscaleSchedule
  AutoscaleTimeAndCapacity: HDInsightAutoscaleTimeAndCapacity
  AutoscaleConfigurationUpdateParameter: HDInsightAutoscaleConfigurationUpdateContent
  BillingResponseListResult: HDInsightBillingSpecsListResult
  CapabilitiesResult: HDInsightCapabilitiesResult
  BillingMeters: HDInsightBillingMeters
  BillingResources: HDInsightBillingResources
  BillingResources.region: -|azure-location
  ClusterConfigurations: HDInsightClusterConfigurations
  ClusterCreateProperties: HDInsightClusterCreateOrUpdateProperties
  ClusterGetProperties: HDInsightClusterProperties
  ClusterDefinition: HDInsightClusterDefinition
  ClusterDiskEncryptionParameters: HDInsightClusterDiskEncryptionContent
  ClusterResizeParameters: HDInsightClusterResizeContent
  DataDisksGroups: HDInsightClusterDataDiskGroup
  DataDisksGroups.diskSizeGB: DiskSizeInGB
  DiskBillingMeters: HDInsightDiskBillingMeters
  Tier: HDInsightTier
  AzureMonitorRequest: HDInsightAzureMonitorExtensionEnableContent
  AzureMonitorResponse: HDInsightAzureMonitorExtensionStatus
  AzureMonitorResponse.clusterMonitoringEnabled: IsClusterMonitoringEnabled
  ClusterMonitoringRequest: HDInsightClusterEnableClusterMonitoringContent
  ClusterMonitoringResponse: HDInsightClusterExtensionStatus
  ClusterMonitoringResponse.clusterMonitoringEnabled: IsClusterMonitoringEnabled
  Extension: HDInsightClusterCreateExtensionContent
  AzureMonitorSelectedConfigurations: HDInsightAzureMonitorSelectedConfigurations
  AzureMonitorTableConfiguration: HDInsightAzureMonitorTableConfiguration
  SecurityProfile.msiResourceId: -|arm-id
  StorageAccount: HDInsightStorageAccountInfo
  StorageProfile.storageaccounts: StorageAccounts
  StorageAccount.resourceId: -|arm-id
  StorageAccount.msiResourceId: -|arm-id
  ComputeIsolationProperties: HDInsightComputeIsolationProperties
  DiskEncryptionProperties: HDInsightDiskEncryptionProperties
  DiskEncryptionProperties.msiResourceId: -|arm-id
  VirtualNetworkProfile: HDInsightVirtualNetworkProfile
  VirtualNetworkProfile.id: -|arm-id
  UpdateGatewaySettingsParameters: HDInsightClusterUpdateGatewaySettingsContent
  UpdateClusterIdentityCertificateParameters: HDInsightClusterUpdateIdentityCertificateContent
  PrivateLink: HDInsightPrivateLinkState
  NetworkProperties: HDInsightClusterNetworkProperties
  LinuxOperatingSystemProfile: HDInsightLinuxOSProfile
  OsProfile.linuxOperatingSystemProfile: LinuxProfile
  HostInfo: HDInsightClusterHostInfo
  GatewaySettings: HDInsightClusterGatewaySettings
  IPConfiguration.id: -|arm-id
  IPConfiguration.type: -|resource-type
  IPConfiguration.properties.primary: IsPrimary
  NameAvailabilityCheckRequestParameters.type: -|resource-type
  NameAvailabilityCheckResult.nameAvailable: IsNameAvailable
  RuntimeScriptActionDetail.startTime: -|date-time
  RuntimeScriptActionDetail.endTime: -|date-time
  DaysOfWeek: HDInsightDayOfWeek
  DiskEncryptionProperties.encryptionAtHost: IsEncryptionAtHostEnabled
  DirectoryType: AuthenticationDirectoryType
  ConnectivityEndpoint.location: EndpointLocation
  ApplicationGetEndpoint.location: EndpointLocation
  ApplicationGetHttpsEndpoint.location: EndpointLocation
  SecurityProfile.aaddsResourceId: -|arm-id
  PrivateLinkConfiguration.type: ResourceType|resource-type
  RegionalQuotaCapability.regionName: region|azure-location
  VmSizeProperty.supportedByVirtualMachines: IsSupportedByVirtualMachines
  VmSizeProperty.supportedByWebWorkerRoles: IsSupportedByWebWorkerRoles
  VmSizeCompatibilityFilterV2.computeIsolationSupported: IsComputeIsolationSupported
  SecurityProfile.ldapsUrls: LdapUris|uri
  ApplicationProperties.createdDate: CreatedOn|date-time
  ClusterGetProperties.createdDate: CreatedOn|date-time

prepend-rp-prefix:
- VmSizeCompatibilityFilterV2
- VmSizeProperty
- FilterMode
- OSType
- SshPublicKey
- SecurityProfile
- VersionSpec
- VersionsCapability
- RoleName
- PrivateLinkConfiguration
- PrivateLinkConfigurationProvisioningState
- PrivateLinkServiceConnectionStatus
- PrivateIPAllocationMethod
- LocalizedName
- ResourceProviderConnection
- IPConfiguration

directive:
  - remove-operation: Locations_GetAzureAsyncOperationStatus # this operation is an LRO polling operation. Remove it here since our SDK provided LRO polling in a native way
  - from: cluster.json
    where: $.definitions
    transform: >
      $.Resource['x-ms-client-name'] = 'HDInsightClusterResponseData';
      $.GatewaySettings.properties['restAuthCredential.isEnabled']['type'] = 'boolean';
# this model has an extra property which prevents the generator to replace it with the type provided by resourcemanager
  - from: swagger-document
    where: $.definitions.UserAssignedIdentity.properties
    transform: $['tenantId'] = undefined
# mark it as input so that the getter of its properties will still preseve the setter
  - from: swagger-document
    where: $.definitions.Cluster
    transform: $['x-csharp-usage'] = 'model,input,output'
# fix some attributes in Errors so that it could be replaced by Azure.ResponseError
  - from: swagger-document
    where: $.definitions.Errors.properties
    transform: >
      return {
        'code': {
          'readOnly': true,
          'type': 'string',
          'description': 'The error code.'
        },
        'message': {
          'readOnly': true,
          'type': 'string',
          'description': 'The error message.'
        },
        'target': {
          'readOnly': true,
          'type': 'string',
          'description': 'The error target.'
        },
        'details': {
          'readOnly': true,
          'type': 'array',
          'items': {
            '$ref': '#/definitions/Errors'
          },
          'x-ms-identifiers': [
            'message',
            'target'
          ],
          'description': 'The error details.'
        }
      };
# nullable
  - from: cluster.json
    where: $.definitions
    transform: >
      $.StorageAccount.properties.msiResourceId['x-nullable'] = true;
      $.StorageAccount.properties.resourceId['x-nullable'] = true;
      $.DiskEncryptionProperties.properties.encryptionAlgorithm['x-nullable'] = true;
      $.DiskEncryptionProperties.properties.msiResourceId['x-nullable'] = true;

```