text:
extern "C" {
#include <X11/Xlib.h>
}
#include <memory>

#include "base/command_line.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/synchronization/cancellation_flag.h"
#include "base/synchronization/lock.h"
#include "base/threading/non_thread_safe.h"
#include "base/threading/thread.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "ui/events/platform/platform_event_source.h"
#include "ui/gfx/x/x11_connection.h"
#include "ui/gfx/x/x11_types.h"
#include "ui/gl/gl_bindings.h"
#include "ui/gl/gl_implementation.h"
#include "ui/gl/gl_visual_picker_glx.h"
#include "ui/gl/sync_control_vsync_provider.h"

namespace gl {

namespace {

Display* g_display = nullptr;
bool g_glx_context_create = false;
bool g_glx_create_context_robustness_supported = false;
bool g_glx_create_context_profile_supported = false;
bool g_glx_create_context_profile_es2_supported = false;
bool g_glx_texture_from_pixmap_supported = false;
bool g_glx_oml_sync_control_supported = false;

// Track support of glXGetMscRateOML separately from GLX_OML_sync_control as a
// whole since on some platforms (e.g. crosbug.com/34585), glXGetMscRateOML
// always fails even though GLX_OML_sync_control is reported as being supported.
bool g_glx_get_msc_rate_oml_supported = false;

bool g_glx_sgi_video_sync_supported = false;

// A 24-bit RGB visual and colormap to use when creating offscreen surfaces.
Visual* g_visual = nullptr;
int g_depth = CopyFromParent;
Colormap g_colormap = CopyFromParent;

GLXFBConfig GetConfigForWindow(Display* display,
                               gfx::AcceleratedWidget window) {
  DCHECK(window != 0);

  // This code path is expensive, but we only take it when
  // attempting to use GLX_ARB_create_context_robustness, in which
  // case we need a GLXFBConfig for the window in order to create a
  // context for it.
  //
  // TODO(kbr): this is not a reliable code path. On platforms which
  // support it, we should use glXChooseFBConfig in the browser
  // process to choose the FBConfig and from there the X Visual to
  // use when creating the window in the first place. Then we can
  // pass that FBConfig down rather than attempting to reconstitute
  // it.

  XWindowAttributes attributes;
  if (!XGetWindowAttributes(display, window, &attributes)) {
    LOG(ERROR) << "XGetWindowAttributes failed for window " << window << ".";
    return nullptr;
  }

  int visual_id = XVisualIDFromVisual(attributes.visual);

  int num_elements = 0;
  gfx::XScopedPtr<GLXFBConfig> configs(
      glXGetFBConfigs(display, DefaultScreen(display), &num_elements));
  if (!configs.get()) {
    LOG(ERROR) << "glXGetFBConfigs failed.";
    return nullptr;
  }
  if (!num_elements) {
    LOG(ERROR) << "glXGetFBConfigs returned 0 elements.";
    return nullptr;
  }
  bool found = false;
  int i;
  for (i = 0; i < num_elements; ++i) {
    int value;
    if (glXGetFBConfigAttrib(display, configs.get()[i], GLX_VISUAL_ID,
                             &value)) {
      LOG(ERROR) << "glXGetFBConfigAttrib failed.";
      return nullptr;
    }
    if (value == visual_id) {
      found = true;
      break;
    }
  }
  if (found) {
    return configs.get()[i];
  }
  return nullptr;
}

bool CreateDummyWindow(Display* display) {
  DCHECK(display);
  gfx::AcceleratedWidget parent_window =
      RootWindow(display, DefaultScreen(display));
  gfx::AcceleratedWidget window =
      XCreateWindow(display, parent_window, 0, 0, 1, 1, 0, CopyFromParent,
                    InputOutput, CopyFromParent, 0, nullptr);
  if (!window) {
    LOG(ERROR) << "XCreateWindow failed";
    return false;
  }
  GLXFBConfig config = GetConfigForWindow(display, window);
  GLXWindow glx_window = glXCreateWindow(display, config, window, nullptr);
  if (!glx_window) {
    LOG(ERROR) << "glXCreateWindow failed";
    XDestroyWindow(display, window);
    return false;
  }
  glXDestroyWindow(display, glx_window);
  XDestroyWindow(display, window);
  return true;
}

class OMLSyncControlVSyncProvider : public SyncControlVSyncProvider {
 public:
  explicit OMLSyncControlVSyncProvider(GLXWindow glx_window)
      : SyncControlVSyncProvider(), glx_window_(glx_window) {}

  ~OMLSyncControlVSyncProvider() override {}

 protected:
  bool GetSyncValues(int64_t* system_time,
                     int64_t* media_stream_counter,
                     int64_t* swap_buffer_counter) override {
    return glXGetSyncValuesOML(g_display, glx_window_, system_time,
                               media_stream_counter, swap_buffer_counter);
  }

  bool GetMscRate(int32_t* numerator, int32_t* denominator) override {
    if (!g_glx_get_msc_rate_oml_supported)
      return false;

    if (!glXGetMscRateOML(g_display, glx_window_, numerator, denominator)) {
      // Once glXGetMscRateOML has been found to fail, don't try again,
      // since each failing call may spew an error message.
      g_glx_get_msc_rate_oml_supported = false;
      return false;
    }

    return true;
  }

 private:
  GLXWindow glx_window_;

  DISALLOW_COPY_AND_ASSIGN(OMLSyncControlVSyncProvider);
};

class SGIVideoSyncThread : public base::Thread,
                           public base::NonThreadSafe,
                           public base::RefCounted<SGIVideoSyncThread> {
 public:
  static scoped_refptr<SGIVideoSyncThread> Create() {
    if (!g_video_sync_thread) {
      g_video_sync_thread = new SGIVideoSyncThread();
      g_video_sync_thread->Start();
    }
    return g_video_sync_thread;
  }

 private:
  friend class base::RefCounted<SGIVideoSyncThread>;

  SGIVideoSyncThread() : base::Thread("SGI_video_sync") {
    DCHECK(CalledOnValidThread());
  }

  ~SGIVideoSyncThread() override {
    DCHECK(CalledOnValidThread());
    g_video_sync_thread = nullptr;
    Stop();
  }

  static SGIVideoSyncThread* g_video_sync_thread;

  DISALLOW_COPY_AND_ASSIGN(SGIVideoSyncThread);
};

class SGIVideoSyncProviderThreadShim {
 public:
  explicit SGIVideoSyncProviderThreadShim(gfx::AcceleratedWidget parent_window)
      : parent_window_(parent_window),
        window_(0),
        glx_window_(0),
        task_runner_(base::ThreadTaskRunnerHandle::Get()),
        cancel_vsync_flag_(),
        vsync_lock_() {
    // This ensures that creation of |parent_window_| has occured when this shim
    // is executing in the same thread as the call to create |parent_window_|.
    XSync(g_display, False);
  }

  virtual ~SGIVideoSyncProviderThreadShim() {
    if (glx_window_)
      glXDestroyWindow(display_, glx_window_);

    if (window_)
      XDestroyWindow(display_, window_);
  }

  base::CancellationFlag* cancel_vsync_flag() { return &cancel_vsync_flag_; }

  base::Lock* vsync_lock() { return &vsync_lock_; }

  void Initialize() {
    DCHECK(display_);

    window_ =
        XCreateWindow(display_, parent_window_, 0, 0, 1, 1, 0, CopyFromParent,
                      InputOutput, CopyFromParent, 0, nullptr);
    if (!window_) {
      LOG(ERROR) << "video_sync: XCreateWindow failed";
      return;
    }

    GLXFBConfig config = GetConfigForWindow(display_, window_);
    DCHECK(config);

    glx_window_ = glXCreateWindow(display_, config, window_, nullptr);
    if (!glx_window_) {
      LOG(ERROR) << "video_sync: glXCreateWindow failed";
      return;
    }

    // Create the context only once for all vsync providers.
    if (!context_) {
      context_ =
        glXCreateNewContext(display_, config, GLX_RGBA_TYPE, nullptr, True);
      if (!context_)
        LOG(ERROR) << "video_sync: glXCreateNewContext failed";
    }
  }

  void GetVSyncParameters(
      const gfx::VSyncProvider::UpdateVSyncCallback& callback) {
    base::TimeTicks now;
    {
      // Don't allow |window_| destruction while we're probing vsync.
      base::AutoLock locked(vsync_lock_);

      if (!context_ || cancel_vsync_flag_.IsSet())
        return;

      glXMakeContextCurrent(display_, glx_window_, glx_window_, context_);

      unsigned int retrace_count = 0;
      if (glXWaitVideoSyncSGI(1, 0, &retrace_count) != 0)
        return;

      TRACE_EVENT_INSTANT0("gpu", "vblank", TRACE_EVENT_SCOPE_THREAD);
      now = base::TimeTicks::Now();

      glXMakeContextCurrent(display_, 0, 0, nullptr);
    }

    const base::TimeDelta kDefaultInterval =
        base::TimeDelta::FromSeconds(1) / 60;

    task_runner_->PostTask(FROM_HERE,
                           base::Bind(callback, now, kDefaultInterval));
  }

 private:
  // For initialization of display_ in GLSurface::InitializeOneOff before
  // the sandbox goes up.
  friend class gl::GLSurfaceGLX;

  // We only need one Display and GLXContext because we only use one thread for
  // SGI_video_sync. The display is created in GLSurfaceGLX::InitializeOneOff
  // and the context is created the first time a vsync provider is initialized.
  static Display* display_;
  static GLXContext context_;

  gfx::AcceleratedWidget parent_window_;

  gfx::AcceleratedWidget window_;
  GLXWindow glx_window_;

  scoped_refptr<base::SingleThreadTaskRunner> task_runner_;

  base::CancellationFlag cancel_vsync_flag_;
  base::Lock vsync_lock_;

  DISALLOW_COPY_AND_ASSIGN(SGIVideoSyncProviderThreadShim);
};

class SGIVideoSyncVSyncProvider
    : public gfx::VSyncProvider,
      public base::SupportsWeakPtr<SGIVideoSyncVSyncProvider> {
 public:
  explicit SGIVideoSyncVSyncProvider(gfx::AcceleratedWidget parent_window)
      : vsync_thread_(SGIVideoSyncThread::Create()),
        shim_(new SGIVideoSyncProviderThreadShim(parent_window)),
        cancel_vsync_flag_(shim_->cancel_vsync_flag()),
        vsync_lock_(shim_->vsync_lock()) {
    vsync_thread_->task_runner()->PostTask(
        FROM_HERE, base::Bind(&SGIVideoSyncProviderThreadShim::Initialize,
                              base::Unretained(shim_.get())));
  }

  ~SGIVideoSyncVSyncProvider() override {
    {
      base::AutoLock locked(*vsync_lock_);
      cancel_vsync_flag_->Set();
    }

    // Hand-off |shim_| to be deleted on the |vsync_thread_|.
    vsync_thread_->task_runner()->DeleteSoon(FROM_HERE, shim_.release());
  }

  void GetVSyncParameters(
      const gfx::VSyncProvider::UpdateVSyncCallback& callback) override {
    // Only one outstanding request per surface.
    if (!pending_callback_) {
      pending_callback_.reset(
          new gfx::VSyncProvider::UpdateVSyncCallback(callback));
      vsync_thread_->task_runner()->PostTask(
          FROM_HERE,
          base::Bind(
              &SGIVideoSyncProviderThreadShim::GetVSyncParameters,
              base::Unretained(shim_.get()),
              base::Bind(&SGIVideoSyncVSyncProvider::PendingCallbackRunner,
                         AsWeakPtr())));
    }
  }

 private:
  void PendingCallbackRunner(const base::TimeTicks timebase,
                             const base::TimeDelta interval) {
    DCHECK(pending_callback_);
    pending_callback_->Run(timebase, interval);
    pending_callback_.reset();
  }

  scoped_refptr<SGIVideoSyncThread> vsync_thread_;

  // Thread shim through which the sync provider is accessed on |vsync_thread_|.
  std::unique_ptr<SGIVideoSyncProviderThreadShim> shim_;

  std::unique_ptr<gfx::VSyncProvider::UpdateVSyncCallback> pending_callback_;

  // Raw pointers to sync primitives owned by the shim_.
  // These will only be referenced before we post a task to destroy
  // the shim_, so they are safe to access.
  base::CancellationFlag* cancel_vsync_flag_;
  base::Lock* vsync_lock_;

  DISALLOW_COPY_AND_ASSIGN(SGIVideoSyncVSyncProvider);
};

SGIVideoSyncThread* SGIVideoSyncThread::g_video_sync_thread = nullptr;

// In order to take advantage of GLX_SGI_video_sync, we need a display
// for use on a separate thread. We must allocate this before the sandbox
// goes up (rather than on-demand when we start the thread).
Display* SGIVideoSyncProviderThreadShim::display_ = nullptr;
GLXContext SGIVideoSyncProviderThreadShim::context_ = 0;

}  // namespace

GLSurfaceGLX::GLSurfaceGLX() {}

bool GLSurfaceGLX::InitializeOneOff() {
  static bool initialized = false;
  if (initialized)
    return true;

  // http://crbug.com/245466
  setenv("force_s3tc_enable", "true", 1);

  // SGIVideoSyncProviderShim (if instantiated) will issue X commands on
  // it's own thread.
  gfx::InitializeThreadedX11();
  g_display = gfx::GetXDisplay();

  if (!g_display) {
    LOG(ERROR) << "XOpenDisplay failed.";
    return false;
  }

  int major, minor;
  if (!glXQueryVersion(g_display, &major, &minor)) {
    LOG(ERROR) << "glxQueryVersion failed";
    return false;
  }

  if (major == 1 && minor < 3) {
    LOG(ERROR) << "GLX 1.3 or later is required.";
    return false;
  }

  g_glx_context_create = HasGLXExtension("GLX_ARB_create_context");
  g_glx_create_context_robustness_supported =
      HasGLXExtension("GLX_ARB_create_context_robustness");
  g_glx_create_context_profile_supported =
      HasGLXExtension("GLX_ARB_create_context_profile");
  g_glx_create_context_profile_es2_supported =
      HasGLXExtension("GLX_ARB_create_context_es2_profile");
  g_glx_texture_from_pixmap_supported =
      HasGLXExtension("GLX_EXT_texture_from_pixmap");
  g_glx_oml_sync_control_supported = HasGLXExtension("GLX_OML_sync_control");
  g_glx_get_msc_rate_oml_supported = g_glx_oml_sync_control_supported;
  g_glx_sgi_video_sync_supported = HasGLXExtension("GLX_SGI_video_sync");

  const XVisualInfo& visual_info =
      gl::GLVisualPickerGLX::GetInstance()->system_visual();
  g_visual = visual_info.visual;
  g_depth = visual_info.depth;
  g_colormap = XCreateColormap(g_display, DefaultRootWindow(g_display),
                               visual_info.visual, AllocNone);

  // We create a dummy unmapped window for both the main Display and the video
  // sync Display so that the Nvidia driver can initialize itself before the
  // sandbox is set up.
  // Unfortunately some fds e.g. /dev/nvidia0 are cached per thread and because
  // we can't start threads before the sandbox is set up, these are accessed
  // through the broker process. See GpuProcessPolicy::InitGpuBrokerProcess.
  if (!CreateDummyWindow(g_display)) {
    LOG(ERROR) << "CreateDummyWindow(g_display) failed";
    return false;
  }

  if (!g_glx_get_msc_rate_oml_supported && g_glx_sgi_video_sync_supported) {
    Display* video_sync_display = gfx::OpenNewXDisplay();
    if (!CreateDummyWindow(video_sync_display)) {
      LOG(ERROR) << "CreateDummyWindow(video_sync_display) failed";
      return false;
    }
    SGIVideoSyncProviderThreadShim::display_ = video_sync_display;
  }

  initialized = true;
  return true;
}

// static
const char* GLSurfaceGLX::GetGLXExtensions() {
  return glXQueryExtensionsString(g_display, 0);
}

// static
bool GLSurfaceGLX::HasGLXExtension(const char* name) {
  return ExtensionsContain(GetGLXExtensions(), name);
}

// static
bool GLSurfaceGLX::IsCreateContextSupported() {
  return g_glx_context_create;
}

// static
bool GLSurfaceGLX::IsCreateContextRobustnessSupported() {
  return g_glx_create_context_robustness_supported;
}

// static
bool GLSurfaceGLX::IsCreateContextProfileSupported() {
  return g_glx_create_context_profile_supported;
}

// static
bool GLSurfaceGLX::IsCreateContextES2ProfileSupported() {
  return g_glx_create_context_profile_es2_supported;
}

// static
bool GLSurfaceGLX::IsTextureFromPixmapSupported() {
  return g_glx_texture_from_pixmap_supported;
}

// static
bool GLSurfaceGLX::IsOMLSyncControlSupported() {
  return g_glx_oml_sync_control_supported;
}

void* GLSurfaceGLX::GetDisplay() {
  return g_display;
}

GLSurfaceGLX::~GLSurfaceGLX() {}

NativeViewGLSurfaceGLX::NativeViewGLSurfaceGLX(gfx::AcceleratedWidget window)
    : parent_window_(window),
      window_(0),
      glx_window_(0),
      config_(nullptr),
      visual_id_(CopyFromParent) {}

GLXDrawable NativeViewGLSurfaceGLX::GetDrawableHandle() const {
  return glx_window_;
}

bool NativeViewGLSurfaceGLX::Initialize(GLSurfaceFormat format) {
  XWindowAttributes attributes;
  if (!XGetWindowAttributes(g_display, parent_window_, &attributes)) {
    LOG(ERROR) << "XGetWindowAttributes failed for window " << parent_window_
               << ".";
    return false;
  }
  size_ = gfx::Size(attributes.width, attributes.height);
  visual_id_ = XVisualIDFromVisual(attributes.visual);
  // Create a child window, with a CopyFromParent visual (to avoid inducing
  // extra blits in the driver), that we can resize exactly in Resize(),
  // correctly ordered with GL, so that we don't have invalid transient states.
  // See https://crbug.com/326995.
  XSetWindowAttributes swa;
  memset(&swa, 0, sizeof(swa));
  swa.background_pixmap = 0;
  swa.bit_gravity = NorthWestGravity;
  window_ = XCreateWindow(g_display, parent_window_, 0, 0, size_.width(),
                          size_.height(), 0, CopyFromParent, InputOutput,
                          CopyFromParent, CWBackPixmap | CWBitGravity, &swa);
  XMapWindow(g_display, window_);

  RegisterEvents();
  XFlush(g_display);

  GetConfig();
  DCHECK(config_);
  glx_window_ = glXCreateWindow(g_display, config_, window_, NULL);

  if (g_glx_oml_sync_control_supported) {
    vsync_provider_.reset(new OMLSyncControlVSyncProvider(glx_window_));
  } else if (g_glx_sgi_video_sync_supported) {
    vsync_provider_.reset(new SGIVideoSyncVSyncProvider(parent_window_));
  } else {
    // Assume a refresh rate of 59.9 Hz, which will cause us to skip
    // 1 frame every 10 seconds on a 60Hz monitor, but will prevent us
    // from blocking the GPU service due to back pressure. This would still
    // encounter backpressure on a <60Hz monitor, but hopefully that is
    // not common.
    const base::TimeTicks kDefaultTimebase;
    const base::TimeDelta kDefaultInterval =
        base::TimeDelta::FromSeconds(1) / 59.9;
    vsync_provider_.reset(
        new gfx::FixedVSyncProvider(kDefaultTimebase, kDefaultInterval));
  }

  return true;
}

void NativeViewGLSurfaceGLX::Destroy() {
  vsync_provider_.reset();
  if (glx_window_) {
    glXDestroyWindow(g_display, glx_window_);
    glx_window_ = 0;
  }
  if (window_) {
    UnregisterEvents();
    XDestroyWindow(g_display, window_);
    window_ = 0;
    XFlush(g_display);
  }
}

bool NativeViewGLSurfaceGLX::Resize(const gfx::Size& size,
                                    float scale_factor,
                                    bool has_alpha) {
  size_ = size;
  glXWaitGL();
  XResizeWindow(g_display, window_, size.width(), size.height());
  glXWaitX();
  return true;
}

bool NativeViewGLSurfaceGLX::IsOffscreen() {
  return false;
}

gfx::SwapResult NativeViewGLSurfaceGLX::SwapBuffers() {
  TRACE_EVENT2("gpu", "NativeViewGLSurfaceGLX:RealSwapBuffers", "width",
               GetSize().width(), "height", GetSize().height());

  glXSwapBuffers(g_display, GetDrawableHandle());
  return gfx::SwapResult::SWAP_ACK;
}

gfx::Size NativeViewGLSurfaceGLX::GetSize() {
  return size_;
}

void* NativeViewGLSurfaceGLX::GetHandle() {
  return reinterpret_cast<void*>(GetDrawableHandle());
}

bool NativeViewGLSurfaceGLX::SupportsPostSubBuffer() {
  return g_driver_glx.ext.b_GLX_MESA_copy_sub_buffer;
}

void* NativeViewGLSurfaceGLX::GetConfig() {
  if (!config_)
    config_ = GetConfigForWindow(g_display, window_);
  return config_;
}

unsigned long NativeViewGLSurfaceGLX::GetCompatibilityKey() {
  return visual_id_;
}

gfx::SwapResult NativeViewGLSurfaceGLX::PostSubBuffer(int x,
                                                      int y,
                                                      int width,
                                                      int height) {
  DCHECK(g_driver_glx.ext.b_GLX_MESA_copy_sub_buffer);
  glXCopySubBufferMESA(g_display, GetDrawableHandle(), x, y, width, height);
  return gfx::SwapResult::SWAP_ACK;
}

gfx::VSyncProvider* NativeViewGLSurfaceGLX::GetVSyncProvider() {
  return vsync_provider_.get();
}

NativeViewGLSurfaceGLX::~NativeViewGLSurfaceGLX() {
  Destroy();
}

void NativeViewGLSurfaceGLX::ForwardExposeEvent(XEvent* event) {
  XEvent forwarded_event = *event;
  forwarded_event.xexpose.window = parent_window_;
  XSendEvent(g_display, parent_window_, False, ExposureMask, &forwarded_event);
  XFlush(g_display);
}

bool NativeViewGLSurfaceGLX::CanHandleEvent(XEvent* event) {
  return event->type == Expose &&
         event->xexpose.window == static_cast<Window>(window_);
}

UnmappedNativeViewGLSurfaceGLX::UnmappedNativeViewGLSurfaceGLX(
    const gfx::Size& size)
    : size_(size), config_(nullptr), window_(0), glx_window_(0) {
  // Ensure that we don't create a window with zero size.
  if (size_.GetArea() == 0)
    size_.SetSize(1, 1);
}

bool UnmappedNativeViewGLSurfaceGLX::Initialize(GLSurfaceFormat format) {
  DCHECK(!window_);

  gfx::AcceleratedWidget parent_window = DefaultRootWindow(g_display);

  XSetWindowAttributes attrs;
  attrs.border_pixel = 0;
  attrs.colormap = g_colormap;
  window_ = XCreateWindow(g_display, parent_window, 0, 0, size_.width(),
                          size_.height(), 0, g_depth, InputOutput, g_visual,
                          CWBorderPixel | CWColormap, &attrs);
  GetConfig();
  DCHECK(config_);
  glx_window_ = glXCreateWindow(g_display, config_, window_, NULL);
  return window_ != 0;
}

void UnmappedNativeViewGLSurfaceGLX::Destroy() {
  config_ = nullptr;
  if (glx_window_) {
    glXDestroyWindow(g_display, glx_window_);
    glx_window_ = 0;
  }
  if (window_) {
    XDestroyWindow(g_display, window_);
    window_ = 0;
  }
}

bool UnmappedNativeViewGLSurfaceGLX::IsOffscreen() {
  return true;
}

gfx::SwapResult UnmappedNativeViewGLSurfaceGLX::SwapBuffers() {
  NOTREACHED() << "Attempted to call SwapBuffers on an unmapped window.";
  return gfx::SwapResult::SWAP_FAILED;
}

gfx::Size UnmappedNativeViewGLSurfaceGLX::GetSize() {
  return size_;
}

void* UnmappedNativeViewGLSurfaceGLX::GetHandle() {
  return reinterpret_cast<void*>(glx_window_);
}

void* UnmappedNativeViewGLSurfaceGLX::GetConfig() {
  if (!config_)
    config_ = GetConfigForWindow(g_display, window_);
  return config_;
}

unsigned long UnmappedNativeViewGLSurfaceGLX::GetCompatibilityKey() {
  return XVisualIDFromVisual(g_visual);
}

UnmappedNativeViewGLSurfaceGLX::~UnmappedNativeViewGLSurfaceGLX() {
  Destroy();
}

}  // namespace gl


text:
killall feh
killall unclutter

redpajama_set_name: RedPajamaGithub


text:
"""Support for MyQ-Enabled Garage Doors."""
from typing import Any

from pymyq.const import DEVICE_TYPE_GATE as MYQ_DEVICE_TYPE_GATE
from pymyq.errors import MyQError

from homeassistant.components.cover import (
    CoverDeviceClass,
    CoverEntity,
    CoverEntityFeature,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import STATE_CLOSED, STATE_CLOSING, STATE_OPEN, STATE_OPENING
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from . import MyQEntity
from .const import DOMAIN, MYQ_COORDINATOR, MYQ_GATEWAY, MYQ_TO_HASS

async def async_setup_entry(
    hass: HomeAssistant,
    config_entry: ConfigEntry,
    async_add_entities: AddEntitiesCallback,
) -> None:
    """Set up mysq covers."""
    data = hass.data[DOMAIN][config_entry.entry_id]
    myq = data[MYQ_GATEWAY]
    coordinator = data[MYQ_COORDINATOR]

    async_add_entities(
        [MyQCover(coordinator, device) for device in myq.covers.values()]
    )

class MyQCover(MyQEntity, CoverEntity):
    """Representation of a MyQ cover."""

    _attr_supported_features = CoverEntityFeature.OPEN | CoverEntityFeature.CLOSE

    def __init__(self, coordinator, device):
        """Initialize with API object, device id."""
        super().__init__(coordinator, device)
        self._device = device
        if device.device_type == MYQ_DEVICE_TYPE_GATE:
            self._attr_device_class = CoverDeviceClass.GATE
        else:
            self._attr_device_class = CoverDeviceClass.GARAGE
        self._attr_unique_id = device.device_id

    @property
    def is_closed(self) -> bool:
        """Return true if cover is closed, else False."""
        return MYQ_TO_HASS.get(self._device.state) == STATE_CLOSED

    @property
    def is_closing(self) -> bool:
        """Return if the cover is closing or not."""
        return MYQ_TO_HASS.get(self._device.state) == STATE_CLOSING

    @property
    def is_open(self) -> bool:
        """Return if the cover is opening or not."""
        return MYQ_TO_HASS.get(self._device.state) == STATE_OPEN

    @property
    def is_opening(self) -> bool:
        """Return if the cover is opening or not."""
        return MYQ_TO_HASS.get(self._device.state) == STATE_OPENING

    async def async_close_cover(self, **kwargs: Any) -> None:
        """Issue close command to cover."""
        if self.is_closing or self.is_closed:
            return

        try:
            wait_task = await self._device.close(wait_for_state=False)
        except MyQError as err:
            raise HomeAssistantError(
                f"Closing of cover {self._device.name} failed with error: {err}"
            ) from err

        # Write closing state to HASS
        self.async_write_ha_state()

        result = wait_task if isinstance(wait_task, bool) else await wait_task

        # Write final state to HASS
        self.async_write_ha_state()

        if not result:
            raise HomeAssistantError(f"Closing of cover {self._device.name} failed")

    async def async_open_cover(self, **kwargs: Any) -> None:
        """Issue open command to cover."""
        if self.is_opening or self.is_open:
            return

        try:
            wait_task = await self._device.open(wait_for_state=False)
        except MyQError as err:
            raise HomeAssistantError(
                f"Opening of cover {self._device.name} failed with error: {err}"
            ) from err

        # Write opening state to HASS
        self.async_write_ha_state()

        result = wait_task if isinstance(wait_task, bool) else await wait_task

        # Write final state to HASS
        self.async_write_ha_state()

        if not result:
            raise HomeAssistantError(f"Opening of cover {self._device.name} failed")


text:
class CharDevice : public Device
{
  private:
  public:
  virtual void read(char* readTo) =0 ;
  virtual char read()=0;
};

#endif


text:
package com.lbconsulting.a1list.domain.interactors.listTitle.impl;

import android.content.ContentResolver;
import android.net.Uri;

import com.backendless.Backendless;
import com.backendless.exceptions.BackendlessException;
import com.lbconsulting.a1list.AndroidApplication;
import com.lbconsulting.a1list.domain.executor.Executor;
import com.lbconsulting.a1list.domain.executor.MainThread;
import com.lbconsulting.a1list.domain.interactors.base.AbstractInteractor;
import com.lbconsulting.a1list.domain.interactors.listTitle.interactors.DeleteListTitlesFromCloud;
import com.lbconsulting.a1list.domain.model.ListTitle;
import com.lbconsulting.a1list.domain.storage.ListTitlesSqlTable;
import com.lbconsulting.a1list.utils.CommonMethods;

import java.util.Date;
import java.util.List;

/**
 * An interactor that saves the provided ListTitles to Backendless.
 */
public class DeleteListTitlesFromCloud_InBackground extends AbstractInteractor implements DeleteListTitlesFromCloud {
    private final Callback mCallback;
    private final List<ListTitle> mListTitles;

    public DeleteListTitlesFromCloud_InBackground(Executor threadExecutor, MainThread mainThread,
                                                  Callback callback, List<ListTitle> listTitles) {
        super(threadExecutor, mainThread);
        mListTitles = listTitles;
        mCallback = callback;
    }

    @Override
    public void run() {

        if (!CommonMethods.isNetworkAvailable()) {
            return;
        }

        for (ListTitle listTile : mListTitles) {
            try {
                // Delete ListTitle from Backendless.
                long timestamp = Backendless.Data.of(ListTitle.class).remove(listTile);

                try {
                    // Delete ListTitle from the SQLite Db
                    int numberOfDeletedListTitles = 0;

                    Uri uri = ListTitlesSqlTable.CONTENT_URI;
                    String selection = ListTitlesSqlTable.COL_UUID + " = ?";
                    String[] selectionArgs = new String[]{listTile.getUuid()};
                    ContentResolver cr = AndroidApplication.getContext().getContentResolver();
                    numberOfDeletedListTitles = cr.delete(uri, selection, selectionArgs);

                    if (numberOfDeletedListTitles == 1) {
                        String successMessage = "\"" + listTile.getName() + "\" successfully deleted from SQLiteDb and removed from Backendless at " + new Date(timestamp).toString();
                        postListTitlesDeletedFromBackendless(successMessage);
                    } else {
                        String errorMessage = "\"" + listTile.getName() + "\" NOT DELETED from SQLiteDb but removed from Backendless at " + new Date(timestamp).toString();
                        postListTitlesDeletionFromBackendlessFailed(errorMessage);
                    }

                } catch (Exception e) {
                    String errorMessage = "\"" + listTile.getName() + "\" DELETION EXCEPTION: " + e.getMessage();
                    postListTitlesDeletionFromBackendlessFailed(errorMessage);
                }

            } catch (BackendlessException e) {
                String errorMessage = "\"" + listTile.getName() + "\" FAILED TO BE REMOVED from Backendless. " + e.getMessage();
                postListTitlesDeletionFromBackendlessFailed(errorMessage);
            }
        }
    }

    private void postListTitlesDeletedFromBackendless(final String successMessage) {
        mMainThread.post(new Runnable() {
            @Override
            public void run() {
                mCallback.onListTitlesDeletedFromBackendless(successMessage);
            }
        });
    }

    private void postListTitlesDeletionFromBackendlessFailed(final String errorMessage) {
        mMainThread.post(new Runnable() {
            @Override
            public void run() {
                mCallback.onListTitlesDeleteFromBackendlessFailed(errorMessage);
            }
        });
    }

}


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

package com.twitter.heron.healthmgr.sensors;

import java.time.Duration;

import com.microsoft.dhalion.api.ISensor;

import com.twitter.heron.healthmgr.HealthPolicyConfig;
import com.twitter.heron.healthmgr.HealthPolicyConfigReader.PolicyConfigKey;

public abstract class BaseSensor implements ISensor {
  static final Duration DEFAULT_METRIC_DURATION = Duration.ofSeconds(300);
  static final String COMPONENT_STMGR = "__stmgr__";

  public enum MetricName {
    METRIC_EXE_COUNT("__execute-count/default"),
    METRIC_BACK_PRESSURE("__time_spent_back_pressure_by_compid/"),
    METRIC_BUFFER_SIZE("__connection_buffer_by_instanceid/"),
    METRIC_BUFFER_SIZE_SUFFIX("/bytes"),
    METRIC_WAIT_Q_GROWTH_RATE("METRIC_WAIT_Q_GROWTH_RATE");

    private String text;

    MetricName(String name) {
      this.text = name;
    }

    public String text() {
      return text;
    }

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

  private Duration duration;
  private final HealthPolicyConfig config;
  private final String metricName;

  BaseSensor(HealthPolicyConfig config, String metricName, String confPrefix) {
    this.config = config;
    this.metricName = metricName;
    duration = getDurationFromConfig(confPrefix);
  }

  /**
   * Returns the duration for which the metrics need to be collected
   *
   * @return duration in seconds
   */
  protected synchronized Duration getDuration() {
    return duration;
  }

  private Duration getDurationFromConfig(String prefix) {
    Duration value = DEFAULT_METRIC_DURATION;

    String configName = prefix + PolicyConfigKey.CONF_SENSOR_DURATION_SUFFIX;
    if (config != null && config.getConfig(configName) != null) {
      value = Duration.ofSeconds((int) config.getConfig(configName));
    }

    return value;
  }

  public String getMetricName() {
    return metricName;
  }

  public HealthPolicyConfig getConfig() {
    return config;
  }
}


text:
package core.stringbuilder;

import org.junit.Test;

import static org.junit.Assert.assertTrue;

public class CharAtTest {

	@Test
	public void charAtIndex() {
		StringBuilder sb = new StringBuilder("123");
		assertTrue(sb.charAt(0) == '1');
		assertTrue(sb.charAt(1) == '2');
		assertTrue(sb.charAt(2) == '3');
	}

	@Test(expected = IndexOutOfBoundsException.class)
	public void charAtExceedingIndex() {
		new StringBuilder("1").charAt(1);
	}

	@Test(expected = IndexOutOfBoundsException.class)
	public void chartAtNegativeIndex() {
		new StringBuilder("1").charAt(-1);
	}
}


text:
<?xml version='1.0' encoding='utf-8'?>
<hibernate-mapping
	 xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
	 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns='urn:nhibernate-mapping-2.0'>
  <class
		 name='NShop.Order, NShop'
		 table='Orders'>
    <id
			 name='Id'>
      <generator
				 class='guid' />
    </id>
    <property
			 name='BillingAddress' />
    <property
			 name='ShippingMethod' />
    <property
			 name='ShippingAddress' />
    <set
       lazy='true'
			 name='OrderLines'
			 access='NHibernate.Generics.GenericAccessor+CamelCase, NHibernate.Generics'>
      <key
				 column='OrderId' />
      <one-to-many
				 class='NShop.OrderLine, NShop' />
    </set>
    <many-to-one
      name='Customer'
      column='CustomerId'
      class='NShop.Customer, NShop'
      access='NHibernate.Generics.GenericAccessor+CamelCase, NHibernate.Generics'/>
  </class>
</hibernate-mapping>


text:
package jdepend.knowledge.domainanalysis;

import jdepend.framework.domain.PersistentBean;
import jdepend.model.result.AnalysisResult;

public abstract class AbstractDomainAnalysis extends PersistentBean implements DomainAnalysis {

	private boolean enable = true;

	public AdviseInfo advise(String name, AnalysisResult data) throws ExpertException {
		if (!enable) {
			return null;
		} else {
			return doAdvise(name, data);
		}
	}

	protected abstract AdviseInfo doAdvise(String name, AnalysisResult data) throws ExpertException;

	public AbstractDomainAnalysis() {
		super();
	}

	public AbstractDomainAnalysis(String name, String tip) {
		super(name, tip, "domainanalysis");
	}

	public boolean isEnable() {
		return enable;
	}

	public void setEnable(boolean enable) {
		this.enable = enable;
	}

}


text:
ottobot
=======

Turntable API Bot (Module Driven)

To Run:
=======
Install turntable api in node...
``npm install ttapi``

Install require.js in node...
``npm install requirejs``

Run the bot app using the auth/user/room of your bot (see links section for more detail)...
``node app.js [auth] [userid] [roomid]``

Structure
=========
app.js --> assembles/configures bot application using modules and ttapi.

Known Issues
============
This is sort of in beta... the autoreconnect feature isn't re-connecting.
Queueing is very basic.

License
=======
[MIT License](https://github.com/mkelandis/ottobot/blob/master/LICENSE-MIT)

Links
=====
https://github.com/alaingilbert/Turntable-API
http://zachlatta.com/blog/2013/05/18/creating-our-first-turntable-bot/


text:
<action>
    <field name="name">email_account</field>
    <field name="string">Email Accounts</field>
    <field name="view">multi_view</field>
    <field name="model">email.account</field>
    <field name="menu">msg_menu</field>
</action>


text:
var restify = require('restify')
var addRoutes = require('./lib/routes')

function MockAPI(expiration, options, toggle) {
  var apicache = require('../../src/apicache').newInstance(options)
  var app = restify.createServer()

  // ENABLE COMPRESSION
  var whichGzip = restify.gzipResponse && restify.gzipResponse() || restify.plugins.gzipResponse()
  app.use(whichGzip)

  // EMBED UPSTREAM RESPONSE PARAM
  app.use(function(req, res, next) {
    res.id = 123
    next()
  })

  // ENABLE APICACHE
  app.use(apicache.middleware(expiration, toggle))
  app.apicache = apicache

  app.use(function(req, res, next) {
    res.charSet('utf-8')
    next()
  })

  app.use(require('restify-etag-cache')())

  // ADD API ROUTES
  app = addRoutes(app)

  return app
}

module.exports = {
  create: function(expiration, config, toggle) { return new MockAPI(expiration, config, toggle) }
}


text:
using System;
using System.IO;
using AutoMapper;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using NetCoreToDo.Services;

namespace NetCoreToDo {
  public class Startup {
    public IConfigurationRoot Configuration { get; }

    public Startup(IHostingEnvironment env) {
      var builder = new ConfigurationBuilder()
        .SetBasePath($"{env.ContentRootPath}\\src")
        .AddJsonFile("appsettings.json",
          optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json",
          optional: true)
        .AddEnvironmentVariables();
      this.Configuration = builder.Build();
    }

    public void ConfigureServices(IServiceCollection services) {
      services.AddDbContext<Context>(o => o.UseSqlServer(
        this.Configuration.GetConnectionString("SqlExpress")));
      services.AddAutoMapper(typeof(Startup));

      services.AddCors();
      services.AddMvc();

      services.AddScoped<IItemsService, ItemsService>();
      services.AddScoped<IListsService, ListsService>();
      services.AddScoped<IUsersService, UsersService>();
    }

    public void Configure(
        IApplicationBuilder app, IHostingEnvironment env,
        ILoggerFactory loggerFactory, Context context) {
      loggerFactory.AddConsole(Configuration.GetSection("Logging"));
      loggerFactory.AddDebug();

      app.UseCors(this.ConfigureCors);
      app.UseCookieAuthentication(this.GetAuthConfig());
      app.UseMvc();

      context.Database.EnsureCreated();
    }

    private void ConfigureCors(CorsPolicyBuilder builder) {
      builder.AllowAnyOrigin();
      builder.AllowAnyMethod();
      builder.AllowAnyHeader();
      builder.AllowCredentials();
    }

    private CookieAuthenticationOptions GetAuthConfig() {
      return new CookieAuthenticationOptions {
        AuthenticationScheme = "CookieScheme",
        CookieName = "NetCoreToDoAuthCookie",
        AutomaticAuthenticate = true,
        AutomaticChallenge = false,
        SlidingExpiration = true
      };
    }
  }
}


text:
package com.callfire.api.client.api.callstexts;

import static com.callfire.api.client.ClientConstants.PLACEHOLDER;
import static com.callfire.api.client.ClientUtils.addQueryParamIfSet;
import static com.callfire.api.client.ModelType.of;
import static com.callfire.api.client.ModelType.pageOf;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.Validate;
import org.apache.http.NameValuePair;

import com.callfire.api.client.AccessForbiddenException;
import com.callfire.api.client.BadRequestException;
import com.callfire.api.client.CallfireApiException;
import com.callfire.api.client.CallfireClientException;
import com.callfire.api.client.InternalServerErrorException;
import com.callfire.api.client.ResourceNotFoundException;
import com.callfire.api.client.RestApiClient;
import com.callfire.api.client.UnauthorizedException;
import com.callfire.api.client.api.callstexts.model.Media;
import com.callfire.api.client.api.callstexts.model.MediaType;
import com.callfire.api.client.api.callstexts.model.request.FindMediaRequest;
import com.callfire.api.client.api.common.model.Page;
import com.callfire.api.client.api.common.model.ResourceId;

/**
 * Represents rest endpoint /media
 * Use the /media API to upload and download different types of media files: images, videos, music, etc.
 *

 *
 * @since 1.7
 */
public class MediaApi {
    private static final String MEDIA_PATH = "/media";
    private static final String MEDIA_FILE_PATH = "/media/{}/file";
    private static final String MEDIA_ITEM_PATH = "/media/{}";
    private static final String MEDIA_ITEM_ID_PATH = "/media/{}.{}";
    private static final String MEDIA_ITEM_KEY_PATH = "/media/public/{}.{}";

    private RestApiClient client;

    public MediaApi(RestApiClient client) {
        this.client = client;
    }

    /**
     * Finds all media files which was uploaded by the user, filtered by file name.
     *
     * @param request request object with different fields to filter
     * @return Page with @{Media} objects
     * @throws BadRequestException          in case HTTP response code is 400 - Bad request, the request was formatted improperly.
     * @throws UnauthorizedException        in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
     * @throws AccessForbiddenException     in case HTTP response code is 403 - Forbidden, insufficient permissions.
     * @throws ResourceNotFoundException    in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
     * @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
     * @throws CallfireApiException         in case HTTP response code is something different from codes listed above.
     * @throws CallfireClientException      in case error has occurred in client.
     * @see call states and results
     */
    public Page<Media> find(FindMediaRequest request) {
        return client.get(MEDIA_PATH, pageOf(Media.class), request);
    }

    /**
     * Upload media file into account
     *
     * @param file file to upload
     * @return ResourceId object with sound id
     * @throws BadRequestException          in case HTTP response code is 400 - Bad request, the request was formatted improperly.
     * @throws UnauthorizedException        in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
     * @throws AccessForbiddenException     in case HTTP response code is 403 - Forbidden, insufficient permissions.
     * @throws ResourceNotFoundException    in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
     * @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
     * @throws CallfireApiException         in case HTTP response code is something different from codes listed above.
     * @throws CallfireClientException      in case error has occurred in client.
     */
    public ResourceId upload(File file) {
        return upload(file, null);
    }

    /**
     * Upload media file into account
     *
     * @param file file to upload
     * @param name name for file uploaded
     * @return ResourceId object with sound id
     * @throws BadRequestException          in case HTTP response code is 400 - Bad request, the request was formatted improperly.
     * @throws UnauthorizedException        in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
     * @throws AccessForbiddenException     in case HTTP response code is 403 - Forbidden, insufficient permissions.
     * @throws ResourceNotFoundException    in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
     * @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
     * @throws CallfireApiException         in case HTTP response code is something different from codes listed above.
     * @throws CallfireClientException      in case error has occurred in client.
     */
    public ResourceId upload(File file, String name) {
        Map<String, Object> params = new HashMap<>(2);
        params.put("file", file);
        params.put("name", name);
        return client.postFile(MEDIA_PATH, of(ResourceId.class), params);
    }

    /**
     * Returns a single Media instance for a given media file id. This is the metadata
     * for the media only. No content data is returned from this API.
     *
     * @param id id of media file
     * @return Media meta object
     * @throws BadRequestException          in case HTTP response code is 400 - Bad request, the request was formatted improperly.
     * @throws UnauthorizedException        in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
     * @throws AccessForbiddenException     in case HTTP response code is 403 - Forbidden, insufficient permissions.
     * @throws ResourceNotFoundException    in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
     * @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
     * @throws CallfireApiException         in case HTTP response code is something different from codes listed above.
     * @throws CallfireClientException      in case error has occurred in client.
     */
    public Media get(Long id) {
        return get(id, null);
    }

    /**
     * Returns a single Media instance for a given media file id. This is the metadata
     * for the media only. No content data is returned from this API.
     *
     * @param id     id of media file
     * @param fields Limit text fields returned. Example fields=limit,offset,items(id,message)
     * @return Media meta object
     * @throws BadRequestException          in case HTTP response code is 400 - Bad request, the request was formatted improperly.
     * @throws UnauthorizedException        in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
     * @throws AccessForbiddenException     in case HTTP response code is 403 - Forbidden, insufficient permissions.
     * @throws ResourceNotFoundException    in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
     * @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
     * @throws CallfireApiException         in case HTTP response code is something different from codes listed above.
     * @throws CallfireClientException      in case error has occurred in client.
     */
    public Media get(Long id, String fields) {
        Validate.notNull(id, "id cannot be null");
        List<NameValuePair> queryParams = new ArrayList<>(1);
        addQueryParamIfSet("fields", fields, queryParams);
        String path = MEDIA_ITEM_PATH.replaceFirst(PLACEHOLDER, id.toString());
        return client.get(path, of(Media.class), queryParams);
    }

    /**
     * Returns media file's data as stream, in case there is no appropriate MediaType for your media file pass
     * MediaType.UNKNOWN
     *
     * @param id   id of media file
     * @param type media type: jpeg, png, gif, mp3, mp4, wav
     * @return file data as binary stream
     * @throws BadRequestException          in case HTTP response code is 400 - Bad request, the request was formatted improperly.
     * @throws UnauthorizedException        in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
     * @throws AccessForbiddenException     in case HTTP response code is 403 - Forbidden, insufficient permissions.
     * @throws ResourceNotFoundException    in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
     * @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
     * @throws CallfireApiException         in case HTTP response code is something different from codes listed above.
     * @throws CallfireClientException      in case error has occurred in client.
     */
    public InputStream getData(Long id, MediaType type) {
        Validate.notNull(id, "id cannot be null");
        Validate.notNull(type, "type cannot be null");
        String path = type == MediaType.UNKNOWN ? MEDIA_FILE_PATH.replaceFirst(PLACEHOLDER, id.toString())
            : MEDIA_ITEM_ID_PATH.replaceFirst(PLACEHOLDER, id.toString()).replaceFirst(PLACEHOLDER, type.getType());
        return client.get(path, of(InputStream.class));
    }

    /**
     * Returns media file's data as stream
     *
     * @param key  key of media file
     * @param type media type: jpeg, png, gif, mp3, mp4, wav
     * @return file data as binary stream
     * @throws BadRequestException          in case HTTP response code is 400 - Bad request, the request was formatted improperly.
     * @throws UnauthorizedException        in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
     * @throws AccessForbiddenException     in case HTTP response code is 403 - Forbidden, insufficient permissions.
     * @throws ResourceNotFoundException    in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
     * @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
     * @throws CallfireApiException         in case HTTP response code is something different from codes listed above.
     * @throws CallfireClientException      in case error has occurred in client.
     */
    public InputStream getData(String key, MediaType type) {
        Validate.notBlank(key, "key cannot be blank");
        Validate.notNull(type, "type cannot be null");
        String path = MEDIA_ITEM_KEY_PATH.replaceFirst(PLACEHOLDER, key).replaceFirst(PLACEHOLDER, type.getType());
        return client.get(path, of(InputStream.class));
    }
}


text:
using XSharp.Assembler;
using XSharp;

namespace Cosmos.CPU_Asm {
    public class CPUDisableINTsAsm : AssemblerMethod
    {
        public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
        {
            XS.ClearInterruptFlag();
        }
    }
}


text:
demoGIT
=======

Remote repository used to demo GIT functionality
with MDH team #3571

Initial code is the FRC java EnhancedIOSample


text:
<?php

namespace App\Helpers;

use App\Model\Entity\LocalizedEntity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Nette\StaticClass;

class Localizations
{
    use StaticClass;

    public const PRIMARY_LOCALE = "cs";

    /**
     * Update a collection of localized entities with new versions if necessary
     * (i.e. only replace original entities with new ones if they are not considered equal).
     * For the new entities, the parent association (createdFrom) is set automatically.
     * If an entity in the collection has no counterpart among the updated entities, it is removed.
     * @param Collection $collection the collection to be updated
     * @param array $updatedLocalizations the updated entities
     */
    public static function updateCollection(Collection $collection, $updatedLocalizations)
    {
        $updatedLocalizations = new ArrayCollection($updatedLocalizations);

        /** @var LocalizedEntity $localization */
        foreach ($updatedLocalizations as $localization) {
            $original = $collection->filter(
                function (LocalizedEntity $candidate) use ($localization) {
                    return $localization->getLocale() === $candidate->getLocale();
                }
            )->first();

            if (!$original || !$localization->equals($original)) {
                $collection->add($localization);

                if ($original) {
                    $collection->removeElement($original);
                    $localization->setCreatedFrom($original);
                }
            }
        }

        $toRemove = [];

        foreach ($collection as $localization) {
            if (
                !$updatedLocalizations->exists(
                    function ($key, LocalizedEntity $entity) use ($localization) {
                        return $entity->getLocale() === $localization->getLocale();
                    }
                )
            ) {
                $toRemove[] = $localization;
            }
        }

        foreach ($toRemove as $entity) {
            $collection->removeElement($entity);
        }
    }

    public static function getPrimaryLocalization(Collection $collection): ?LocalizedEntity
    {
        /** @var LocalizedEntity $text */
        foreach ($collection as $text) {
            if ($text->getLocale() === self::PRIMARY_LOCALE) {
                return $text;
            }
        }

        return !$collection->isEmpty() ? $collection->first() : null;
    }
}


text:
import React from 'react'
import mapProps from 'recompose/mapProps'
import { bulmaComponent } from './internal'

// http://bulma.io/documentation/components/card/
export const Card = bulmaComponent('div', 'card')
export const CardHeaderTitle = bulmaComponent('p', 'card-header-title')
export const CardHeaderIcon = bulmaComponent('a', 'card-header-icon')
export const CardHeader = bulmaComponent('header', 'card-header',
  // Add `title` and `icon` shortcut props.
  mapProps(({ title, icon, ...props }) => ({
    ...props,
    children: [
      title && <CardHeaderTitle>{title}</CardHeaderTitle>,
      icon && <CardHeaderIcon>{icon}</CardHeaderIcon>
    ].concat(props.children).filter(Boolean)
  }))
)
export const CardImage = bulmaComponent('div', 'card-image')
export const CardContent = bulmaComponent('div', 'card-content')
export const CardFooter = bulmaComponent('footer', 'card-footer')
export const CardFooterItem = bulmaComponent('span', 'card-footer-item')
export const CardFooterLink = bulmaComponent('a', 'card-footer-item')


text:
package com.codahale.shamir.tests;

import static com.codahale.shamir.Generators.byteArrays;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import com.codahale.shamir.Scheme;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.quicktheories.WithQuickTheories;

class SchemeTest implements WithQuickTheories {

  @Test
  void hasProperties() {
    final Scheme scheme = new Scheme(new SecureRandom(), 5, 3);

    assertThat(scheme.n()).isEqualTo(5);
    assertThat(scheme.k()).isEqualTo(3);
  }

  @Test
  void tooManyShares() {
    assertThatThrownBy(() -> new Scheme(new SecureRandom(), 2_000, 3))
        .isInstanceOf(IllegalArgumentException.class);
  }

  @Test
  void thresholdTooLow() {
    assertThatThrownBy(() -> new Scheme(new SecureRandom(), 1, 1))
        .isInstanceOf(IllegalArgumentException.class);
  }

  @Test
  void thresholdTooHigh() {
    assertThatThrownBy(() -> new Scheme(new SecureRandom(), 1, 2))
        .isInstanceOf(IllegalArgumentException.class);
  }

  @Test
  void joinEmptyParts() {
    assertThatThrownBy(() -> new Scheme(new SecureRandom(), 3, 2).join(Collections.emptyMap()))
        .isInstanceOf(IllegalArgumentException.class);
  }

  @Test
  void joinIrregularParts() {
    final byte[] one = new byte[] {1};
    final byte[] two = new byte[] {1, 2};

    assertThatThrownBy(
            () -> new Scheme(new SecureRandom(), 3, 2).join(ImmutableMap.of(1, one, 2, two)))
        .isInstanceOf(IllegalArgumentException.class);
  }

  @Test
  void splitAndJoinSingleByteSecret() {
    final Scheme scheme = new Scheme(new SecureRandom(), 8, 3);
    final byte[] secret = "x".getBytes(StandardCharsets.UTF_8);

    assertThat(scheme.join(scheme.split(secret))).containsExactly(secret);
  }

  @Test
  void splitAndJoinMoreThanByteMaxValueParts() {
    final Scheme scheme = new Scheme(new SecureRandom(), 200, 3);
    final byte[] secret = "x".getBytes(StandardCharsets.UTF_8);

    assertThat(scheme.join(scheme.split(secret))).containsExactly(secret);
  }

  @Test
  void splitAndJoinQuorate() {
    // All distinct subsets of parts of cardinality greater than or equal to the threshold should
    // join to recover the original secret.
    qt().forAll(integers().between(2, 5), integers().between(1, 5), byteArrays(1, 300))
        .asWithPrecursor((k, extra, secret) -> new Scheme(new SecureRandom(), k + extra, k))
        .check(
            (k, e, secret, scheme) -> {
              final Map<Integer, byte[]> parts = scheme.split(secret);
              return Sets.powerSet(parts.entrySet()).stream()
                  .parallel()
                  .filter(s -> s.size() >= k)
                  .map(entries -> join(scheme, entries))
                  .allMatch(s -> Arrays.equals(s, secret));
            });
  }

  @Test
  void splitAndJoinInquorate() {
    // All distinct subsets of parts of cardinality less than the threshold should never join to
    // recover the original secret. Only check larger secrets to avoid false positives.
    qt().forAll(integers().between(2, 5), integers().between(1, 5), byteArrays(3, 300))
        .asWithPrecursor((k, extra, secret) -> new Scheme(new SecureRandom(), k + extra, k))
        .check(
            (k, e, secret, scheme) -> {
              final Map<Integer, byte[]> parts = scheme.split(secret);
              return Sets.powerSet(parts.entrySet()).stream()
                  .parallel()
                  .filter(s -> s.size() < k && !s.isEmpty())
                  .map(entries -> join(scheme, entries))
                  .noneMatch(s -> Arrays.equals(s, secret));
            });
  }

  private byte[] join(Scheme scheme, Set<Map.Entry<Integer, byte[]>> entries) {
    final Map<Integer, byte[]> m = new HashMap<>();
    entries.forEach(v -> m.put(v.getKey(), v.getValue()));
    return scheme.join(m);
  }
}


text:
navigator.webkitGetUserMedia({ video: true }, function(stream) {
  document.querySelector('video').src = URL.createObjectURL(stream);
}, function(error) { console.log(error) });


text:
Generates sentence based passwords using a dictionary file

## What is this?
This is a very simple utility to quickly create
sentence based passwords by pulling words
out of a dictionary file.

## Usage
```sh
passgen "path/to/dictfile" "# of words to print"
```

## Compiling
Just type ```make && sudo make install ``` in the source direcrtory.
If you want to uninstall it, simply type ```sudo make remove``` inside the source
directory.

## Extra
``` get_dict.sh ``` will download an English dictionary file if one is not present in the ```/usr/share/dict``` directory already, you can run it by typing ```sudo ./get_dict```.


text:
YUI.add('selector-native', function(Y) {

Y.namespace('Selector'); // allow native module to standalone

var PARENT_NODE = 'parentNode',
    LENGTH = 'length',

NativeSelector = {
    _reLead: /^\s*([>+~]|:self)/,
    _reUnSupported: /!./,

    _foundCache: [],

    _supportsNative: function() {
        // whitelist and feature detection to manage
        // future implementations manually
        return ( (Y.UA.ie >= 8 || Y.UA.webkit > 525) &&
            document.querySelectorAll);
    },

    _toArray: function(nodes) { // TODO: move to Y.Array
        var ret = nodes;
        if (!nodes.slice) {
            try {
                ret = Array.prototype.slice.call(nodes);
            } catch(e) { // IE: requires manual copy
                ret = [];
                for (var i = 0, len = nodes[LENGTH]; i < len; ++i) {
                    ret[i] = nodes[i];
                }
            }
        }
        return ret;
    },

    _clearFoundCache: function() {
        var foundCache = NativeSelector._foundCache;
        for (var i = 0, len = foundCache[LENGTH]; i < len; ++i) {
            try { // IE no like delete
                delete foundCache[i]._found;
            } catch(e) {
                foundCache[i].removeAttribute('_found');
            }
        }
        foundCache = [];
    },

    _sort: function(nodes) {
        if (nodes) {
            nodes = NativeSelector._toArray(nodes);
            if (nodes.sort) {
                nodes.sort(function(a, b) {
                    return Y.DOM.srcIndex(a) - Y.DOM.srcIndex(b);
                });
            }
        }

        return nodes;
    },

    _deDupe: function(nodes) {
        var ret = [],
            cache = NativeSelector._foundCache;

        for (var i = 0, node; node = nodes[i++];) {
            if (!node._found) {
                ret[ret[LENGTH]] = cache[cache[LENGTH]] = node;
                node._found = true;
            }
        }
        NativeSelector._clearFoundCache();
        return ret;
    },

    // allows element scoped queries to begin with combinator
    // e.g. query('> p', document.body) === query('body > p')
    _prepQuery: function(root, selector) {
        var groups = selector.split(','),
            queries = [],
            isDocRoot = (root && root.nodeType === 9);

        if (root) {
            if (!isDocRoot) {
                root.id = root.id || Y.guid();
                // break into separate queries for element scoping
                for (var i = 0, len = groups[LENGTH]; i < len; ++i) {
                    selector = '#' + root.id + ' ' + groups[i]; // prepend with root ID
                    queries.push({root: root.ownerDocument, selector: selector});
                }
            } else {
                queries.push({root: root, selector: selector});
            }
        }

        return queries;
    },

    _query: function(selector, root, firstOnly) {
        if (NativeSelector._reUnSupported.test(selector)) {
            return Y.Selector._brute.query(selector, root, firstOnly);
        }

        var ret = firstOnly ? null : [],
            queryName = firstOnly ? 'querySelector' : 'querySelectorAll',
            result,
            queries;

        root = root || Y.config.doc;

        if (selector) {
            queries = NativeSelector._prepQuery(root, selector);
            ret = [];

            for (var i = 0, query; query = queries[i++];) {
                try {
                    result = query.root[queryName](query.selector);
                    if (queryName === 'querySelectorAll') { // convert NodeList to Array
                        result = NativeSelector._toArray(result);
                    }
                    ret = ret.concat(result);
                } catch(e) {
                }
            }

            if (queries[LENGTH] > 1) { // remove dupes and sort by doc order
                ret = NativeSelector._sort(NativeSelector._deDupe(ret));
            }
            ret = (!firstOnly) ? ret : ret[0] || null;
        }
        return ret;
    },

    _filter: function(nodes, selector) {
        var ret = [];

        if (nodes && selector) {
            for (var i = 0, node; (node = nodes[i++]);) {
                if (Y.Selector._test(node, selector)) {
                    ret[ret[LENGTH]] = node;
                }
            }
        } else {
        }

        return ret;
    },

    _test: function(node, selector) {
        var ret = false,
            groups = selector.split(','),
            item;

        if (node && node[PARENT_NODE]) {
            node.id = node.id || Y.guid();
            node[PARENT_NODE].id = node[PARENT_NODE].id || Y.guid();
            for (var i = 0, group; group = groups[i++];) {
                group += '#' + node.id; // add ID for uniqueness
                //group = '#' + node[PARENT_NODE].id + ' ' + group; // document scope parent test
                item = Y.Selector.query(group, null, true);
                ret = (item === node);
                if (ret) {
                    break;
                }
            }
        }

        return ret;
    }
};

if (Y.UA.ie && Y.UA.ie <= 8) {
    NativeSelector._reUnSupported = /:(?:nth|not|root|only|checked|first|last|empty)/;
}

Y.mix(Y.Selector, NativeSelector, true);

// allow standalone selector-native module
if (NativeSelector._supportsNative()) {
    Y.Selector.query = NativeSelector._query;
    //Y.Selector.filter = NativeSelector._filter;
    //Y.Selector.test = NativeSelector._test;
}
Y.Selector.test = NativeSelector._test;
Y.Selector.filter = NativeSelector._filter;

}, '@VERSION@' ,{requires:['dom-base'], skinnable:false});


text:
package options

import (
	"io/ioutil"
	"os"
	"reflect"
	"testing"

	"github.com/spf13/pflag"
	utilfeature "k8s.io/apiserver/pkg/util/feature"
	featuregatetesting "k8s.io/component-base/featuregate/testing"
	"k8s.io/controller-manager/config"
	"k8s.io/controller-manager/pkg/features"
	migrationconfig "k8s.io/controller-manager/pkg/leadermigration/config"
)

func TestLeaderMigrationOptions(t *testing.T) {
	testCases := []struct {
		name              string
		flags             []string
		configContent     string
		expectEnabled     bool
		expectErr         bool
		enableFeatureGate bool
		expectConfig      *config.LeaderMigrationConfiguration
	}{
		{
			name:              "default (disabled), with feature gate disabled",
			flags:             []string{},
			enableFeatureGate: false,
			expectEnabled:     false,
			expectErr:         false,
		},
		{
			name:              "enabled, with feature gate disabled",
			flags:             []string{"--enable-leader-migration"},
			enableFeatureGate: false,
			expectErr:         true,
		},
		{
			name:              "enabled, with default configuration",
			flags:             []string{"--enable-leader-migration"},
			enableFeatureGate: true,
			expectEnabled:     true,
			expectErr:         false,
			expectConfig:      migrationconfig.DefaultLeaderMigrationConfiguration(),
		},
		{
			name:              "enabled, with custom configuration file",
			flags:             []string{"--enable-leader-migration"},
			enableFeatureGate: true,
			expectEnabled:     true,
			configContent: `
apiVersion: controllermanager.config.k8s.io/v1alpha1
kind: LeaderMigrationConfiguration
leaderName: test-leader-migration
resourceLock: leases
controllerLeaders: []
`,
			expectErr: false,
			expectConfig: &config.LeaderMigrationConfiguration{
				LeaderName:        "test-leader-migration",
				ResourceLock:      "leases",
				ControllerLeaders: []config.ControllerLeaderConfiguration{},
			},
		},
		{
			name:              "enabled, with custom configuration file (version v1beta1)",
			flags:             []string{"--enable-leader-migration"},
			enableFeatureGate: true,
			expectEnabled:     true,
			configContent: `
apiVersion: controllermanager.config.k8s.io/v1beta1
kind: LeaderMigrationConfiguration
leaderName: test-leader-migration
resourceLock: leases
controllerLeaders: []
`,
			expectErr: false,
			expectConfig: &config.LeaderMigrationConfiguration{
				LeaderName:        "test-leader-migration",
				ResourceLock:      "leases",
				ControllerLeaders: []config.ControllerLeaderConfiguration{},
			},
		},
	}
	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.ControllerManagerLeaderMigration, tc.enableFeatureGate)()
			flags := tc.flags
			if tc.configContent != "" {
				configFile, err := ioutil.TempFile("", tc.name)
				if err != nil {
					t.Fatal(err)
				}
				defer os.Remove(configFile.Name())
				err = ioutil.WriteFile(configFile.Name(), []byte(tc.configContent), os.FileMode(0755))
				if err != nil {
					t.Fatal(err)
				}
				flags = append(flags, "--leader-migration-config="+configFile.Name())
			}
			genericConfig := new(config.GenericControllerManagerConfiguration)
			options := new(LeaderMigrationOptions)
			fs := pflag.NewFlagSet("addflagstest", pflag.ContinueOnError)
			options.AddFlags(fs)
			err := fs.Parse(flags)
			if err != nil {
				t.Errorf("cannot parse leader-migration-config: %v", err)
				return
			}
			err = options.ApplyTo(genericConfig)
			if err != nil {
				if !tc.expectErr {
					t.Errorf("unexpected error: %v", err)
					return
				}
				// expect err and got err, finish the test case.
				return
			}
			if err == nil && tc.expectErr {
				t.Errorf("expected error but got nil")
				return
			}
			if genericConfig.LeaderMigrationEnabled != tc.expectEnabled {
				t.Errorf("expected Enabled=%v, got %v", tc.expectEnabled, options.Enabled)
				return
			}
			if tc.expectEnabled && !reflect.DeepEqual(tc.expectConfig, &genericConfig.LeaderMigration) {
				t.Errorf("expected config %#v but got %#v", tc.expectConfig, genericConfig.LeaderMigration)
			}
		})
	}

}


text:
package com.asakusafw.directio.hive.serde;

import org.apache.hadoop.hive.serde2.io.TimestampWritable;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.TimestampObjectInspector;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;

import com.asakusafw.runtime.value.DateTime;
import com.asakusafw.runtime.value.DateTimeOption;
import com.asakusafw.runtime.value.ValueOption;

/**
 * Inspects {@link DateTimeOption} object.
 * @since 0.7.0
 */
public class DateTimeOptionInspector extends AbstractValueInspector implements TimestampObjectInspector {

    /**
     * Creates a new instance.
     */
    public DateTimeOptionInspector() {
        super(TypeInfoFactory.timestampTypeInfo);
    }

    @Override
    protected ValueOption<?> newObject() {
        return new DateTimeOption();
    }

    @Override
    public java.sql.Timestamp getPrimitiveJavaObject(Object o) {
        DateTimeOption object = (DateTimeOption) o;
        if (object == null || object.isNull()) {
            return null;
        }
        DateTime value = object.get();

        // FIXME for optimization
        @SuppressWarnings("deprecation")
        java.sql.Timestamp result = new java.sql.Timestamp(
                value.getYear() - 1900, value.getMonth() - 1, value.getDay(),
                value.getHour(), value.getMinute(), value.getSecond(), 0);
        return result;
    }

    @Override
    public TimestampWritable getPrimitiveWritableObject(Object o) {
        java.sql.Timestamp value = getPrimitiveJavaObject(o);
        if (value == null) {
            return null;
        }
        return new TimestampWritable(value);
    }
}


text:
package com.codepath.apps.restclienttemplate;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;

import com.codepath.apps.restclienttemplate.models.SampleModel;
import com.codepath.apps.restclienttemplate.models.SampleModelDao;
import com.codepath.oauth.OAuthLoginActionBarActivity;

public class LoginActivity extends OAuthLoginActionBarActivity<RestClient> {

	SampleModelDao sampleModelDao;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		final SampleModel sampleModel = new SampleModel();
		sampleModel.setName("CodePath");

		sampleModelDao = ((RestApplication) getApplicationContext()).getMyDatabase().sampleModelDao();

		AsyncTask.execute(new Runnable() {
			@Override
			public void run() {
				sampleModelDao.insertModel(sampleModel);
			}
		});
	}

	// Inflate the menu; this adds items to the action bar if it is present.
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	// OAuth authenticated successfully, launch primary authenticated activity
	// i.e Display application "homepage"
	@Override
	public void onLoginSuccess() {
		// Intent i = new Intent(this, PhotosActivity.class);
		// startActivity(i);
	}

	// OAuth authentication flow failed, handle the error
	// i.e Display an error dialog or toast
	@Override
	public void onLoginFailure(Exception e) {
		e.printStackTrace();
	}

	// Click handler method for the button used to start OAuth flow
	// Uses the client to initiate OAuth authorization
	// This should be tied to a button used to login
	public void loginToRest(View view) {
		getClient().connect();
	}

}


text:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using Gigya.Microdot.Interfaces.Configuration;
using Gigya.Microdot.SharedLogic.HttpService;
using Newtonsoft.Json;

namespace Gigya.Microdot.ServiceDiscovery.Config
{
    /// <summary>
    /// Config object read from <configuration.Discovery/> XML entry. Will be recreated when config changes.
    /// </summary>
    [Serializable]
    [ConfigurationRoot("Discovery", RootStrategy.ReplaceClassNameWithPath)]
    public class DiscoveryConfig : IConfigObject
    {
        internal ServiceDiscoveryConfig DefaultItem { get; private set; }

        /// <summary>
        /// Scope where this service is installed.
        /// Some services are installed for current environment only (itg1, prod, etc.)
        /// Other services are installed for entire data-center (e.g. Kafka, Flume, etc.)
        /// </summary>
        public ServiceScope Scope { get; set; } = ServiceScope.Environment;

        /// <summary>
        /// The time-out trying to send requests to the service.
        /// </summary>
        public TimeSpan? RequestTimeout { get; set; }

        /// <summary>
        /// Time period to keep monitoring a deployed service after it was no longer requested
        /// </summary>
        public TimeSpan MonitoringLifetime { get; set; } = TimeSpan.FromMinutes(5);

        /// <summary>
        /// When we lose connection to some endpoint, we wait this delay till we start trying to reconnect.
        /// </summary>
        [Obsolete("To be deleted after discovery refactoring")]
        public double FirstAttemptDelaySeconds { get; set; } = 0.001;

        /// <summary>
        /// When retrying to reconnect to an endpoint, we use exponential backoff (e.g. 1,2,4,8ms, etc). Once that
        /// backoff reaches this value, it won't increase any more.
        /// </summary>
        [Obsolete("To be deleted after discovery refactoring")]
        public double MaxAttemptDelaySeconds { get; set; } = 10;

        /// <summary>
        /// The factor of the exponential backoff when retrying connections to endpoints.
        /// </summary>
        [Obsolete("To be deleted after discovery refactoring")]
        public double DelayMultiplier { get; set; } = 2;

        /// <summary>
        /// Indicate wheather clients should use secure channel to communicate with target service
        /// </summary>
        public bool UseHttpsOverride { get; set; } = false;

        /// <summary>
        /// Indicates whether the service should listen for HTTPs traffic
        /// </summary>
        public bool ServiceHttpsOverride { get; set; } = false;

        /// <summary>
        /// Indicates whether the client should try and elevate to HTTPs traffic even if not explicitly configured to
        /// </summary>
        public bool TryHttps { get; set; }

        /// <summary>
        /// The frequency in which the service proxy will try to send an HTTPS request in minutes
        /// </summary>
        public int TryHttpsIntervalInMinutes { get; set; } = 1;

        /// <summary>
        /// Indicates whether the proxy provider send connections metrics to metrics.net and flume
        /// </summary>
        public bool PublishConnectionsMetrics { get; set; } = true;

        /// <summary>
        /// Controls the client verification logic for the server certificate.
        /// Default behavior is to validate that the server domain matches the certificate domain.
        /// </summary>
        public ServerCertificateVerificationMode ServerCertificateVerification { get; set; } = ServerCertificateVerificationMode.VerifyDomain;

        /// <summary>
        /// Controls the verification logic of the client certificate.
        /// Default behavior is that no verification is been made.
        /// </summary>
        public ClientCertificateVerificationMode ClientCertificateVerification { get; set; } = ClientCertificateVerificationMode.Disable;

        /// <summary>
        /// The discovery mode to use, e.g. whether to use DNS resolving, Consul, etc.
        /// </summary>
        public string Source { get; set; } = ConsulDiscoverySource.Name;

        /// <summary>
        /// The discovery configuration for the various services.
        /// </summary>
        public IImmutableDictionary<string, ServiceDiscoveryConfig> Services { get; set; }  // <service name, discovery params>

        [Required]
        public PortAllocationConfig PortAllocation { get; set; } = new PortAllocationConfig();

        public bool EnvironmentFallbackEnabled { get; set; } = false;

        public string EnvironmentFallbackTarget { get; set; }

        public List<string> CertificateErrorMessageSubstrings { get; set; } = new List<string>()
        {
            "Element not found"
        };

        [OnDeserialized]
        private void OnDeserialized(StreamingContext context)
        {
            DefaultItem = new ServiceDiscoveryConfig
            {
                DelayMultiplier = DelayMultiplier,
                FirstAttemptDelaySeconds = FirstAttemptDelaySeconds,
                MaxAttemptDelaySeconds = MaxAttemptDelaySeconds,
                RequestTimeout = RequestTimeout,
                Scope = Scope,
                Source = Source
            };

            var services = (IDictionary<string, ServiceDiscoveryConfig>)Services ?? new Dictionary<string, ServiceDiscoveryConfig>();

            Services = new ServiceDiscoveryCollection(services, DefaultItem, PortAllocation);
        }
    }
}


text:
if [ ! -d .venv ]; then
    virtualenv --distribute --python /usr/local/bin/python3.6 .venv
    . .venv/bin/activate
    pip install -r requirements.txt
fi


text:
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';

//import './main.html';
import './index.html';


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>ComposeTweetController | angular-typescript-webpack</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					angular-typescript-webpack

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-externals" checked />
							Externals
							<input type="checkbox" id="tsd-filter-only-exported" />
							Only exported

					Menu

					Globals

					"ui/modules/composeTweet/ComposeTweetComponentController"

					ComposeTweetController

Class ComposeTweetController

The ComposeTweetController is the controller for the compose twee section.

Hierarchy

						ComposeTweetController

Index

Constructors

constructor

Properties

account

message

tweet<wbr>Service

user<wbr>Account<wbr>Model

$inject

Methods

clear<wbr>Message<wbr>Inputs

handle<wbr>Post<wbr>Button<wbr>Clicked

Constructors

constructor

new <wbr>Compose<wbr>Tweet<wbr>Controller(tweetService: TweetService, userAccountModel: UserAccountModel): ComposeTweetController

Defined in ui/modules/composeTweet/ComposeTweetComponentController.ts:11

Parameters

tweetService: TweetService

The service that mediates the calls to the TweetAPIService or TweetAPIFakeService.

userAccountModel: UserAccountModel

The account model for the current user.

Returns ComposeTweetController

Properties

account

account: string = ""

Defined in ui/modules/composeTweet/ComposeTweetComponentController.ts:10

message

message: string = ""

Defined in ui/modules/composeTweet/ComposeTweetComponentController.ts:11

Private tweet<wbr>Service

tweet<wbr>Service: TweetService

Defined in ui/modules/composeTweet/ComposeTweetComponentController.ts:17

The service that mediates the calls to the TweetAPIService or TweetAPIFakeService.

Private user<wbr>Account<wbr>Model

user<wbr>Account<wbr>Model: UserAccountModel

Defined in ui/modules/composeTweet/ComposeTweetComponentController.ts:17

The account model for the current user.

Static $inject

$inject: Array<string> = ['TweetService', 'UserAccountModel']

Defined in ui/modules/composeTweet/ComposeTweetComponentController.ts:8

Methods

Private clear<wbr>Message<wbr>Inputs

clear<wbr>Message<wbr>Inputs(): void

Defined in ui/modules/composeTweet/ComposeTweetComponentController.ts:42

Clear the message form inputs.

Returns void

handle<wbr>Post<wbr>Button<wbr>Clicked

handle<wbr>Post<wbr>Button<wbr>Clicked(form: ng.IFormController): void

Defined in ui/modules/composeTweet/ComposeTweetComponentController.ts:24

This method handles the event when the post Tweet button is pressed.

Parameters

form: ng.IFormController

The form that is to be set untouched and inputs to be reset.

Returns void

						Globals

						"configs/config<wbr>Material"

						"configs/routes"

						"index"

						"models/<wbr>Tweets<wbr>Model"

						"models/<wbr>User<wbr>Account<wbr>Model"

						"services/<wbr>Data<wbr>Factory"

						"services/<wbr>Tweet"

						"services/<wbr>TweetAPIFake<wbr>Service"

						"services/<wbr>TweetAPIService"

						"services/<wbr>Tweet<wbr>Service"

						"test"

						"ui/<wbr>Application<wbr>Component"

						"ui/<wbr>Application<wbr>Component<wbr>Controller"

						"ui/index"

						"ui/modules/compose<wbr>Tweet/<wbr>Compose<wbr>Tweet<wbr>Component"

						"ui/modules/compose<wbr>Tweet/<wbr>Compose<wbr>Tweet<wbr>Component<wbr>Controller"

						"ui/modules/timeline/<wbr>Timeline<wbr>Component"

						"ui/modules/timeline/<wbr>Timeline<wbr>Component<wbr>Controller"

						"ui/modules/user<wbr>Account/<wbr>User<wbr>Account<wbr>Component"

						"ui/modules/user<wbr>Account/<wbr>User<wbr>Account<wbr>Component<wbr>Controller"

						Compose<wbr>Tweet<wbr>Controller

								constructor

								account

								message

								tweet<wbr>Service

								user<wbr>Account<wbr>Model

								$inject

								clear<wbr>Message<wbr>Inputs

								handle<wbr>Post<wbr>Button<wbr>Clicked

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

Generated using TypeDoc


text:
Dependency_Validator: Extension dependency, recommended failure --nodeps
--FILE--
<?php
require __DIR__ . '/../setup.php.inc';

\Pyrus\Main::$options['nodeps'] = true;
$fake = new \Pyrus\PackageFile\v2;
$foo = $fake->dependencies['required']->extension['foo']->recommended('2.1.0');
$validator->extensions['foo'] = true;
$validator->versions['foo'] = '2.0.0';

$test->assertEquals(true, $validator->validateExtensionDependency($foo), 'basic fail');
$test->assertEquals(1, count($errs->E_WARNING), 'basic fail count');
$test->assertEquals(1, count($errs), 'basic fail count 2');
foreach ($errs->E_WARNING as $error) {
    $test->assertEquals('warning: channel://pear2.php.net/test dependency: PHP extension foo version "2.0.0" is not the recommended version "2.1.0"', $error->getMessage(),
                        'basic fail message');
}
?>
===DONE===
--EXPECT--
===DONE===


text:
import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';

import { User } from '../../models/user';
import { CheckResetPwTokenAction, ResetMessageAction, ResetPasswordAction } from '../../actions/user';
import * as fromRoot from '../../reducers'
import { Observable } from 'rxjs/Observable';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { STATUS } from '../../../../app.config';

@Component({
  selector: 'bc-reset-password-page',
  template: `
      <bc-reset-password (resetPassword)="resetPassword($event)"
                         (resetUserMessage)="resetUserMessage($event)"
                         [userMessage]="userMessage$"
                         [isLoading]="isLoading$ | async"
                         [validToken]="validToken$ | async"></bc-reset-password>
  `
})
export class ResetPasswordPageComponent implements OnInit {
  userMessage$: Observable<string>;
  isLoading$: Observable<boolean>;
  resetPasswordToken: string;
  validToken$: Observable<boolean>;

  constructor(
    private store: Store<fromRoot.State>,
    private route: ActivatedRoute,
    private router: Router
  ) {
    this.userMessage$ = store.select<string>(fromRoot.getUserMessage);
    this.isLoading$ = store.select<boolean>(fromRoot.isLoading);
    this.validToken$ = store.select<boolean>(fromRoot.getResetPwToken);

    this.userMessage$
      .delay(5000)          // TODO don't work or not. Need to retest it after SendGrid is activated.
      .subscribe( message => {
      if ( message === STATUS.RESET_PASSWORD_OK )
        this.router.navigate(['./login']);
    });
  }

  ngOnInit() {
    this.route.params
      .map((params: Params) => params['token'])
      .subscribe(token => {
        this.resetPasswordToken = token;
      });
    this.store.dispatch(new CheckResetPwTokenAction(this.resetPasswordToken));
  }

  resetUserMessage( reset: boolean ) {
    this.store.dispatch(new ResetMessageAction(reset));
  }

  resetPassword( user: User ) {
    this.store.dispatch(new ResetPasswordAction({
      user: user,
      resetPasswordToken: this.resetPasswordToken
    }));
  }

}


text:
#ifndef __GETGATEWAY_H__
#define __GETGATEWAY_H__

/* getdefaultgateway() :
 * return value :
 *    0 : success
 *   -1 : failure    */
int getdefaultgateway(in_addr_t * addr);

#endif


text:
package org.commonmark.internal.renderer.text;

import org.commonmark.node.BulletList;

public class BulletListHolder extends ListHolder {
    private final char marker;

    public BulletListHolder(ListHolder parent, BulletList list) {
        super(parent);
        marker = list.getBulletMarker();
    }

    public char getMarker() {
        return marker;
    }
}


text:
package socks

var (
	ErrNoProperRespone              = NewSocksError("Server does not respond properly.")
	ErrNoSocks5Support              = NewSocksError("Server does not support Socks 5.")
	ErrMethodNegotiationFailed      = NewSocksError("socks method negotiation failed.")
	ErrCantCompleteSocks5Connection = NewSocksError("Can't complete SOCKS5 connection.")
	ErrSocksRequestRejectedOrFailed = NewSocksError("Socks connection request rejected or failed.")
	ErrCannotConnectToIdentd        = NewSocksError("Socks connection request rejected becasue SOCKS server cannot connect to identd on the client.")
	ErrClientServerDifferentUserIds = NewSocksError("Socks connection request rejected because the client program and identd report different user-ids.")
	ErrUnknown                      = NewSocksError("Socks connection request failed, unknown error.")
	ErrIpv6NotSupported             = NewSocksError("IPv6 is not supported by SOCKS4.")
)

type (
	SocksError struct {
		Message string
	}
)

func (s *SocksError) Error() string {
	return s.Message
}

func NewSocksError(message string) *SocksError {
	return &SocksError{
		Message: message,
	}
}


text:
package io.qameta.allure.grpc;

import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.util.JsonFormat;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.ForwardingClientCall;
import io.grpc.ForwardingClientCallListener;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.qameta.allure.Allure;
import io.qameta.allure.attachment.AttachmentData;
import io.qameta.allure.attachment.AttachmentProcessor;
import io.qameta.allure.attachment.DefaultAttachmentProcessor;
import io.qameta.allure.attachment.FreemarkerAttachmentRenderer;
import io.qameta.allure.model.Status;
import io.qameta.allure.model.StepResult;
import io.qameta.allure.util.ResultsUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static java.util.Objects.requireNonNull;

/**
 * Allure interceptor logger for gRPC.
 *
 * @author dtuchs (Dmitry Tuchs).
 */
@SuppressWarnings({
        "PMD.AvoidFieldNameMatchingMethodName",
        "checkstyle:ClassFanOutComplexity",
        "checkstyle:AnonInnerLength",
        "checkstyle:JavaNCSS"
})
public class AllureGrpc implements ClientInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(AllureGrpc.class);
    private static final JsonFormat.Printer JSON_PRINTER = JsonFormat.printer();

    private String requestTemplatePath = "grpc-request.ftl";
    private String responseTemplatePath = "grpc-response.ftl";

    private boolean markStepFailedOnNonZeroCode = true;
    private boolean interceptResponseMetadata;

    public AllureGrpc setRequestTemplate(final String templatePath) {
        this.requestTemplatePath = templatePath;
        return this;
    }

    public AllureGrpc setResponseTemplate(final String templatePath) {
        this.responseTemplatePath = templatePath;
        return this;
    }

    public AllureGrpc markStepFailedOnNonZeroCode(final boolean value) {
        this.markStepFailedOnNonZeroCode = value;
        return this;
    }

    public AllureGrpc interceptResponseMetadata(final boolean value) {
        this.interceptResponseMetadata = value;
        return this;
    }

    @SuppressWarnings({"PMD.MethodArgumentCouldBeFinal", "PMD.NPathComplexity"})
    @Override
    public <T, A> ClientCall<T, A> interceptCall(MethodDescriptor<T, A> method,
                                                 CallOptions callOptions,
                                                 Channel next) {
        final AttachmentProcessor<AttachmentData> processor = new DefaultAttachmentProcessor();

        return new ForwardingClientCall.SimpleForwardingClientCall<T, A>(
                next.newCall(method, callOptions.withoutWaitForReady())) {

            private String stepUuid;
            private List<String> parsedResponses = new ArrayList<>();

            @SuppressWarnings("PMD.MethodArgumentCouldBeFinal")
            @Override
            public void sendMessage(T message) {
                stepUuid = UUID.randomUUID().toString();
                Allure.getLifecycle().startStep(stepUuid, (new StepResult()).setName(
                        "Send gRPC request to "
                                + next.authority()
                                + trimGrpcMethodName(method.getFullMethodName())
                ));
                try {
                    final GrpcRequestAttachment rpcRequestAttach = GrpcRequestAttachment.Builder
                            .create("gRPC request", method.getFullMethodName())
                            .setBody(JSON_PRINTER.print((MessageOrBuilder) message))
                            .build();
                    processor.addAttachment(rpcRequestAttach, new FreemarkerAttachmentRenderer(requestTemplatePath));
                    super.sendMessage(message);
                } catch (InvalidProtocolBufferException e) {
                    LOGGER.warn("Can`t parse gRPC request", e);
                } catch (Throwable e) {
                    Allure.getLifecycle().updateStep(stepResult ->
                            stepResult.setStatus(ResultsUtils.getStatus(e).orElse(Status.BROKEN))
                                    .setStatusDetails(ResultsUtils.getStatusDetails(e).orElse(null))
                    );
                    Allure.getLifecycle().stopStep(stepUuid);
                    stepUuid = null;
                }
            }

            @SuppressWarnings("PMD.MethodArgumentCouldBeFinal")
            @Override
            public void start(Listener<A> responseListener, Metadata headers) {
                final ClientCall.Listener<A> listener = new ForwardingClientCallListener<A>() {
                    @Override
                    protected Listener<A> delegate() {
                        return responseListener;
                    }

                    @SuppressWarnings({"PMD.MethodArgumentCouldBeFinal", "PMD.AvoidLiteralsInIfCondition"})
                    @Override
                    public void onClose(io.grpc.Status status, Metadata trailers) {
                        GrpcResponseAttachment.Builder responseAttachmentBuilder = null;

                        if (parsedResponses.size() == 1) {
                            responseAttachmentBuilder = GrpcResponseAttachment.Builder
                                    .create("gRPC response")
                                    .setBody(parsedResponses.iterator().next());
                        } else if (parsedResponses.size() > 1) {
                            responseAttachmentBuilder = GrpcResponseAttachment.Builder
                                    .create("gRPC response (collection of elements from Server stream)")
                                    .setBody("[" + String.join(",\n", parsedResponses) + "]");
                        }
                        if (!status.isOk()) {
                            String description = status.getDescription();
                            if (description == null) {
                                description = "No description provided";
                            }
                            responseAttachmentBuilder = GrpcResponseAttachment.Builder
                                    .create(status.getCode().name())
                                    .setStatus(description);
                        }

                        requireNonNull(responseAttachmentBuilder).setStatus(status.toString());
                        if (interceptResponseMetadata) {
                            for (String key : headers.keys()) {
                                requireNonNull(responseAttachmentBuilder).setMetadata(
                                        key,
                                        headers.get(Metadata.Key.of(key, Metadata.ASCII_STRING_MARSHALLER))
                                );
                            }
                        }
                        processor.addAttachment(
                                requireNonNull(responseAttachmentBuilder).build(),
                                new FreemarkerAttachmentRenderer(responseTemplatePath)
                        );

                        if (status.isOk() || !markStepFailedOnNonZeroCode) {
                            Allure.getLifecycle().updateStep(stepUuid, step -> step.setStatus(Status.PASSED));
                        } else {
                            Allure.getLifecycle().updateStep(stepUuid, step -> step.setStatus(Status.FAILED));
                        }
                        Allure.getLifecycle().stopStep(stepUuid);
                        stepUuid = null;
                        super.onClose(status, trailers);
                    }

                    @SuppressWarnings("PMD.MethodArgumentCouldBeFinal")
                    @Override
                    public void onMessage(A message) {
                        try {
                            parsedResponses.add(JSON_PRINTER.print((MessageOrBuilder) message));
                            super.onMessage(message);
                        } catch (InvalidProtocolBufferException e) {
                            LOGGER.warn("Can`t parse gRPC response", e);
                        } catch (Throwable e) {
                            Allure.getLifecycle().updateStep(step ->
                                    step.setStatus(ResultsUtils.getStatus(e).orElse(Status.BROKEN))
                                            .setStatusDetails(ResultsUtils.getStatusDetails(e).orElse(null))
                            );
                            Allure.getLifecycle().stopStep(stepUuid);
                            stepUuid = null;
                        }
                    }
                };
                super.start(listener, headers);
            }

            private String trimGrpcMethodName(final String source) {
                return source.substring(source.lastIndexOf('/'));
            }
        };
    }
}


text:
module Dynamoid #:nodoc:

  module Associations
    module SingleAssociation
      include Association

      delegate :class, :to => :target

      def setter(object)
        delete unless source.send(source_attribute).nil?
        if object
          raise Dynamoid::Errors::Error.new("Cannot reference object #{object.inspect} without ID.") if object.id.nil?
          raise Dynamoid::Errors::Error.new("Cannot create inverse association on object #{self.inspect} without ID.") if target_association && source.id.nil?
          set(object)
          source.update_attribute(source_attribute, object.id)
          self.send(:associate_target, object) if target_association
        end
        object
      end

      def delete
        self.send(:disassociate_target, target) if target && target_association
        reset
        source.update_attribute(source_attribute, nil)
        target
      end

      def create!(attributes = {})
        setter(target_class.create!(attributes))
      end

      def create(attributes = {})
        setter(target_class.create!(attributes))
      end

      # Is this object equal to the association's target?
      #
      # @return [Boolean] true/false
      #
      # @since 0.2.0
      def ==(other)
        target == other
      end

      # Delegate methods we don't find directly to the target.
      #
      # @since 0.2.0
      def method_missing(method, *args)
        if target.respond_to?(method)
          target.send(method, *args)
        else
          super
        end
      end

      def nil?
        target.nil?
      end

      private

      # Find the target of the has_one association.
      #
      # @return [Dynamoid::Document] the found target (or nil if nothing)
      #
      # @since 0.2.0
      def find_target
        return if source_ids.empty?
        target_class.find(source_ids.first)
      end

      # The ids in the source association.
      #
      # @since 0.2.0
      def source_ids
        id = source.send(source_attribute)
        (id && Set[id]) || Set.new
      end
    end
  end
end