text:
<?php

namespace app\modules\business\models;

use Yii;

/**
 * This is the model class for table "bur_payments".
 *
 * @property integer $id
 * @property integer $customer_id
 * @property integer $trans_id
 * @property string $date
 * @property double $amount
 * @property string $to_or_from
 */
class Payments extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'bur_payments';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['customer_id', 'trans_id', 'date', 'amount', 'to_or_from'], 'required'],
            [['customer_id', 'trans_id'], 'integer'],
            [['date'], 'safe'],
            [['amount'], 'number'],
            [['to_or_from'], 'string']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'customer_id' => 'Customer ID',
            'trans_id' => 'Trans ID',
            'date' => 'Date',
            'amount' => 'Amount',
            'to_or_from' => 'To Or From',
        ];
    }
}


text:
namespace content {

PluginInstance::PluginInstance(PluginLib* plugin, const std::string& mime_type)
    : plugin_(plugin),
      npp_(0),
      host_(PluginHost::Singleton()),
      npp_functions_(plugin->functions()),
      window_handle_(0),
      windowless_(false),
      transparent_(true),
      webplugin_(0),
      mime_type_(mime_type),
      use_mozilla_user_agent_(false),
#if defined (OS_MACOSX)
#ifdef NP_NO_QUICKDRAW
      drawing_model_(NPDrawingModelCoreGraphics),
#else
      drawing_model_(NPDrawingModelQuickDraw),
#endif
#ifdef NP_NO_CARBON
      event_model_(NPEventModelCocoa),
#else
      event_model_(NPEventModelCarbon),
#endif
      currently_handled_event_(NULL),
#endif
      task_runner_(base::ThreadTaskRunnerHandle::Get()),
      load_manually_(false),
      next_timer_id_(1) {
  npp_ = new NPP_t();
  npp_->ndata = 0;
  npp_->pdata = 0;

  if (mime_type_ == kFlashPluginSwfMimeType)
    transparent_ = false;

  memset(&zero_padding_, 0, sizeof(zero_padding_));
}

PluginInstance::~PluginInstance() {
  if (npp_ != 0) {
    delete npp_;
    npp_ = 0;
  }

  if (plugin_.get())
    plugin_->CloseInstance();
}

bool PluginInstance::Start(const GURL& url,
                           char** const param_names,
                           char** const param_values,
                           int param_count,
                           bool load_manually) {
  load_manually_ = load_manually;
  unsigned short mode = load_manually_ ? NP_FULL : NP_EMBED;
  npp_->ndata = this;

  NPError err = NPP_New(mode, param_count,
      const_cast<char **>(param_names), const_cast<char **>(param_values));
  return err == NPERR_NO_ERROR;
}

NPObject *PluginInstance::GetPluginScriptableObject() {
  NPObject *value = NULL;
  NPError error = NPP_GetValue(NPPVpluginScriptableNPObject, &value);
  if (error != NPERR_NO_ERROR || value == NULL)
    return NULL;
  return value;
}

bool PluginInstance::GetFormValue(base::string16* value) {
  // Plugins will allocate memory for the return value by using NPN_MemAlloc().
  char *plugin_value = NULL;
  NPError error = NPP_GetValue(NPPVformValue, &plugin_value);
  if (error != NPERR_NO_ERROR || !plugin_value) {
    return false;
  }
  // Assumes the result is UTF8 text, as Firefox does.
  *value = base::UTF8ToUTF16(plugin_value);
  host_->host_functions()->memfree(plugin_value);
  return true;
}

unsigned PluginInstance::GetBackingTextureId() {
  // By default the plugin instance is not backed by an OpenGL texture.
  return 0;
}

// NPAPI methods
NPError PluginInstance::NPP_New(unsigned short mode,
                                short argc,
                                char* argn[],
                                char* argv[]) {
  DCHECK(npp_functions_ != 0);
  DCHECK(npp_functions_->newp != 0);
  DCHECK(argc >= 0);

  if (npp_functions_->newp != 0) {
    return npp_functions_->newp(
        (NPMIMEType)mime_type_.c_str(), npp_, mode,  argc, argn, argv, NULL);
  }
  return NPERR_INVALID_FUNCTABLE_ERROR;
}

void PluginInstance::NPP_Destroy() {
  DCHECK(npp_functions_ != 0);
  DCHECK(npp_functions_->destroy != 0);

  if (npp_functions_->destroy != 0) {
    NPSavedData *savedData = 0;
    npp_functions_->destroy(npp_, &savedData);

    // TODO: Support savedData.  Technically, these need to be
    //       saved on a per-URL basis, and then only passed
    //       to new instances of the plugin at the same URL.
    //       Sounds like a huge security risk.  When we do support
    //       these, we should pass them back to the PluginLib
    //       to be stored there.
    DCHECK(savedData == 0);
  }

  for (unsigned int file_index = 0; file_index < files_created_.size();
       file_index++) {
    base::DeleteFile(files_created_[file_index], false);
  }

  // Ensure that no timer callbacks are invoked after NPP_Destroy.
  timers_.clear();
}

NPError PluginInstance::NPP_SetWindow(NPWindow* window) {
  DCHECK(npp_functions_ != 0);
  DCHECK(npp_functions_->setwindow != 0);

  if (npp_functions_->setwindow != 0) {
    return npp_functions_->setwindow(npp_, window);
  }
  return NPERR_INVALID_FUNCTABLE_ERROR;
}

NPError PluginInstance::NPP_NewStream(NPMIMEType type,
                                      NPStream* stream,
                                      NPBool seekable,
                                      unsigned short* stype) {
  DCHECK(npp_functions_ != 0);
  DCHECK(npp_functions_->newstream != 0);
  if (npp_functions_->newstream != 0) {
      return npp_functions_->newstream(npp_, type, stream, seekable, stype);
  }
  return NPERR_INVALID_FUNCTABLE_ERROR;
}

NPError PluginInstance::NPP_DestroyStream(NPStream* stream, NPReason reason) {
  DCHECK(npp_functions_ != 0);
  DCHECK(npp_functions_->destroystream != 0);

  if (stream == NULL || (stream->ndata == NULL))
    return NPERR_INVALID_INSTANCE_ERROR;

  if (npp_functions_->destroystream != 0) {
    NPError result = npp_functions_->destroystream(npp_, stream, reason);
    stream->ndata = NULL;
    return result;
  }
  return NPERR_INVALID_FUNCTABLE_ERROR;
}

int PluginInstance::NPP_WriteReady(NPStream* stream) {
  DCHECK(npp_functions_ != 0);
  DCHECK(npp_functions_->writeready != 0);
  if (npp_functions_->writeready != 0) {
    return npp_functions_->writeready(npp_, stream);
  }
  return 0;
}

int PluginInstance::NPP_Write(NPStream* stream,
                              int offset,
                              int len,
                              void* buffer) {
  DCHECK(npp_functions_ != 0);
  DCHECK(npp_functions_->write != 0);
  if (npp_functions_->write != 0) {
    return npp_functions_->write(npp_, stream, offset, len, buffer);
  }
  return 0;
}

void PluginInstance::NPP_StreamAsFile(NPStream* stream, const char* fname) {
  DCHECK(npp_functions_ != 0);
  DCHECK(npp_functions_->asfile != 0);
  if (npp_functions_->asfile != 0) {
    npp_functions_->asfile(npp_, stream, fname);
  }

  // Creating a temporary FilePath instance on the stack as the explicit
  // FilePath constructor with StringType as an argument causes a compiler
  // error when invoked via vector push back.
  base::FilePath file_name = base::FilePath::FromUTF8Unsafe(fname);
  files_created_.push_back(file_name);
}

NPError PluginInstance::NPP_GetValue(NPPVariable variable, void* value) {
  DCHECK(npp_functions_ != 0);
  // getvalue is NULL for Shockwave
  if (npp_functions_->getvalue != 0) {
    return npp_functions_->getvalue(npp_, variable, value);
  }
  return NPERR_INVALID_FUNCTABLE_ERROR;
}

NPError PluginInstance::NPP_SetValue(NPNVariable variable, void* value) {
  DCHECK(npp_functions_ != 0);
  if (npp_functions_->setvalue != 0) {
    return npp_functions_->setvalue(npp_, variable, value);
  }
  return NPERR_INVALID_FUNCTABLE_ERROR;
}

short PluginInstance::NPP_HandleEvent(void* event) {
  DCHECK(npp_functions_ != 0);
  DCHECK(npp_functions_->event != 0);
  if (npp_functions_->event != 0) {
    return npp_functions_->event(npp_, (void*)event);
  }
  return false;
}

bool PluginInstance::NPP_Print(NPPrint* platform_print) {
  DCHECK(npp_functions_ != 0);
  if (npp_functions_->print != 0) {
    npp_functions_->print(npp_, platform_print);
    return true;
  }
  return false;
}

void PluginInstance::PluginThreadAsyncCall(void (*func)(void*),
                                           void* user_data) {
  task_runner_->PostTask(
      FROM_HERE, base::Bind(&PluginInstance::OnPluginThreadAsyncCall, this,
                            func, user_data));
}

void PluginInstance::OnPluginThreadAsyncCall(void (*func)(void*),
                                             void* user_data) {
  // Do not invoke the callback if NPP_Destroy has already been invoked.
  if (webplugin_)
    func(user_data);
}

uint32_t PluginInstance::ScheduleTimer(uint32_t interval,
                                       NPBool repeat,
                                       void (*func)(NPP id,
                                                    uint32_t timer_id)) {
  // Use next timer id.
  uint32_t timer_id;
  timer_id = next_timer_id_;
  ++next_timer_id_;
  DCHECK(next_timer_id_ != 0);

  // Record timer interval and repeat.
  TimerInfo info;
  info.interval = interval;
  info.repeat = repeat ? true : false;
  timers_[timer_id] = info;

  // Schedule the callback.
  base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&PluginInstance::OnTimerCall, this, func, npp_, timer_id),
      base::TimeDelta::FromMilliseconds(interval));
  return timer_id;
}

void PluginInstance::UnscheduleTimer(uint32_t timer_id) {
  // Remove info about the timer.
  TimerMap::iterator it = timers_.find(timer_id);
  if (it != timers_.end())
    timers_.erase(it);
}

#if !defined(OS_MACOSX)
NPError PluginInstance::PopUpContextMenu(NPMenu* menu) {
  NOTIMPLEMENTED();
  return NPERR_GENERIC_ERROR;
}
#endif

void PluginInstance::OnTimerCall(void (*func)(NPP id, uint32_t timer_id),
                                 NPP id,
                                 uint32_t timer_id) {
  // Do not invoke callback if the timer has been unscheduled.
  TimerMap::iterator it = timers_.find(timer_id);
  if (it == timers_.end())
    return;

  // Get all information about the timer before invoking the callback. The
  // callback might unschedule the timer.
  TimerInfo info = it->second;

  func(id, timer_id);

  // If the timer was unscheduled by the callback, just free up the timer id.
  if (timers_.find(timer_id) == timers_.end())
    return;

  // Reschedule repeating timers after invoking the callback so callback is not
  // re-entered if it pumps the message loop.
  if (info.repeat) {
    base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
        FROM_HERE,
        base::Bind(&PluginInstance::OnTimerCall, this, func, npp_, timer_id),
        base::TimeDelta::FromMilliseconds(info.interval));
  } else {
    timers_.erase(it);
  }
}

void PluginInstance::PushPopupsEnabledState(bool enabled) {
  popups_enabled_stack_.push(enabled);
}

void PluginInstance::PopPopupsEnabledState() {
  popups_enabled_stack_.pop();
}

bool PluginInstance::ConvertPoint(double source_x, double source_y,
                                  NPCoordinateSpace source_space,
                                  double* dest_x, double* dest_y,
                                  NPCoordinateSpace dest_space) {
#if defined(OS_MACOSX)
  CGRect main_display_bounds = CGDisplayBounds(CGMainDisplayID());

  double flipped_screen_x = source_x;
  double flipped_screen_y = source_y;
  switch(source_space) {
    case NPCoordinateSpacePlugin:
      flipped_screen_x += plugin_origin_.x();
      flipped_screen_y += plugin_origin_.y();
      break;
    case NPCoordinateSpaceWindow:
      flipped_screen_x += containing_window_frame_.x();
      flipped_screen_y = containing_window_frame_.height() - source_y +
          containing_window_frame_.y();
      break;
    case NPCoordinateSpaceFlippedWindow:
      flipped_screen_x += containing_window_frame_.x();
      flipped_screen_y += containing_window_frame_.y();
      break;
    case NPCoordinateSpaceScreen:
      flipped_screen_y = main_display_bounds.size.height - flipped_screen_y;
      break;
    case NPCoordinateSpaceFlippedScreen:
      break;
    default:
      NOTREACHED();
      return false;
  }

  double target_x = flipped_screen_x;
  double target_y = flipped_screen_y;
  switch(dest_space) {
    case NPCoordinateSpacePlugin:
      target_x -= plugin_origin_.x();
      target_y -= plugin_origin_.y();
      break;
    case NPCoordinateSpaceWindow:
      target_x -= containing_window_frame_.x();
      target_y -= containing_window_frame_.y();
      target_y = containing_window_frame_.height() - target_y;
      break;
    case NPCoordinateSpaceFlippedWindow:
      target_x -= containing_window_frame_.x();
      target_y -= containing_window_frame_.y();
      break;
    case NPCoordinateSpaceScreen:
      target_y = main_display_bounds.size.height - flipped_screen_y;
      break;
    case NPCoordinateSpaceFlippedScreen:
      break;
    default:
      NOTREACHED();
      return false;
  }

  if (dest_x)
    *dest_x = target_x;
  if (dest_y)
    *dest_y = target_y;
  return true;
#else
  NOTIMPLEMENTED();
  return false;
#endif
}

}  // namespace content

redpajama_set_name: RedPajamaGithub


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

<title>org.apache.cassandra.utils.btree Class Hierarchy (apache-cassandra API)</title>
<meta name="date" content="2015-08-28">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.apache.cassandra.utils.btree

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

org.apache.cassandra.utils.btree.BTree

org.apache.cassandra.utils.btree.BTreeSet<V> (implements java.util.NavigableSet<E>)

org.apache.cassandra.utils.btree.BTreeSet.BTreeRange<V> (implements java.util.NavigableSet<E>)

org.apache.cassandra.utils.btree.BTreeSet.BTreeDescRange<V>

org.apache.cassandra.utils.btree.Path<V>

org.apache.cassandra.utils.btree.BTreeSearchIterator<CK,K,V> (implements org.apache.cassandra.utils.SearchIterator<K,V>)

org.apache.cassandra.utils.btree.Cursor<K,V> (implements java.util.Iterator<E>)

org.apache.cassandra.utils.btree.UpdateFunction.NoOp<V> (implements org.apache.cassandra.utils.btree.UpdateFunction<V>)

Interface Hierarchy

com.google.common.base.Function<F,T>

org.apache.cassandra.utils.btree.UpdateFunction<V>

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2015 The Apache Software Foundation


text:
COPY (SELECT
id,
created,
modified,
reference,
nodes,
current_node_id,
graph_version,
state,
category_id
FROM diagnosis_diagnosistraversal
WHERE (modified >= %(from_date)s::timestamp AND modified <= %(to_date)s::timestamp)
OR (created >= %(from_date)s::timestamp AND created <= %(to_date)s::timestamp))
TO STDOUT CSV HEADER;


text:
package org.apache.jena.sparql.junit;

import java.io.PrintStream ;
import java.text.NumberFormat ;
import java.util.List ;

import org.junit.runner.Description ;
import org.junit.runner.Result ;
import org.junit.runner.notification.Failure ;
import org.junit.runner.notification.RunListener ;

class TextListenerOneLine extends RunListener
{
    // See also org.junit.internal.TextListener
    // TextListener does not provide access to the writer (!!)

    protected Description current = null ;
    protected PrintStream fWriter ;

    public TextListenerOneLine(PrintStream writer) { this.fWriter = writer ; }

    @Override
    public void testStarted(Description description) {
        current = description ;
        fWriter.println(description.getMethodName()) ;
    }

    @Override
    public void testFinished(Description description)
    {
        current = null ;
    }

    @Override
    public void testFailure(Failure failure)
    {
        if ( failure.getMessage() != null && failure.getMessage().length() > 0 )
            fWriter.println("**** Failure: "+failure.getMessage());
        else
            fWriter.println("**** Failure") ;
    }

    @Override
    public void testIgnored(Description description) {
        fWriter.println("** Ignored");
    }

    @Override
    public void testRunFinished(Result result) {
        printHeader(result.getRunTime());
        printFailures(result);
        printFooter(result);
    }
    protected void printHeader(long runTime) {
        fWriter.println();
        fWriter.println("Time: " + elapsedTimeAsString(runTime));

    }

    protected void printFailures(Result result) {
        List<Failure> failures= result.getFailures();
        if (failures.size() == 0)
            return;
        if ( result.getFailureCount() > 0 )
        {
            fWriter.println() ;
            fWriter.println("===========================================") ;
        }
        printSummary(result) ;

        int i = 1;
        for (Failure each : failures)
            printFailure(each, "" + i++);
    }

    protected void printSummary(Result result)
    {
        int badCount =  result.getFailureCount() ;
        int ignoredCount = result.getIgnoreCount() ;
        int goodCount = result.getRunCount() - badCount - ignoredCount ;

        fWriter.print("Tests = "+result.getRunCount()) ;
        fWriter.print(" : Successes = "+goodCount) ;
        if ( ignoredCount > 0 )
            fWriter.print(" : Ignored = "+ignoredCount) ;
        fWriter.print(" : Failures = "+badCount) ;
        fWriter.println() ;
        fWriter.println() ;
    }

    protected void printFailure(Failure f, String prefix) {
        System.out.print("Failure: ") ;
        System.out.print(prefix) ;
        System.out.print(" : ") ;
        //System.out.println(f.getDescription().getMethodName()) ;
        System.out.println(f.getDescription().getDisplayName()) ;
        System.out.println(f.getException()) ;
        // Truncate at : java.lang.reflect.Method.invoke
        f.getException().printStackTrace(System.out) ;
    }

    protected void printFooter(Result result)
    {
        if ( result.getFailureCount() > 0 )
            printSummary(result) ;
    }

    protected String elapsedTimeAsString(long runTime) {
        return NumberFormat.getInstance().format((double) runTime / 1000);
    }
}


text:
class CreatePostCategories < ActiveRecord::Migration
  def change
    create_table :post_categories do |t|
        t.integer :category_id
        t.integer :post_id
    end
  end
end


text:
static const int kClientEdgeThickness = 3;
static const int kTabDragWindowAlpha = 200;
// We need to offset the DWMFrame into the toolbar so that the blackness
// doesn't show up on our rounded corners.
static const int kDWMFrameTopOffset = 3;
// If not -1, windows are shown with this state.
static int explicit_show_state = -1;

using content::OpenURLParams;
using content::Referrer;
using content::WebContents;

#if !defined(USE_AURA)
extern "C" {
// Windows metro exported functions from metro_driver.
typedef void (*SetFrameWindow)(HWND window);
typedef void (*CloseFrameWindow)(HWND window);
typedef void (*FlipFrameWindows)();
typedef void (*MetroSetFullscreen)(bool fullscreen);
}
#endif  // USE_AURA

views::Button* MakeWindowSwitcherButton(views::ButtonListener* listener,
                                        bool is_off_the_record) {
  views::ImageButton* switcher_button = new views::ImageButton(listener);
  // The button in the incognito window has the hot-cold images inverted
  // with respect to the regular browser window.
  switcher_button->SetImage(
      views::ImageButton::BS_NORMAL,
      ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
          is_off_the_record ? IDR_INCOGNITO_SWITCH_ON :
                              IDR_INCOGNITO_SWITCH_OFF));
  switcher_button->SetImage(
      views::ImageButton::BS_HOT,
      ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
          is_off_the_record ? IDR_INCOGNITO_SWITCH_OFF :
                              IDR_INCOGNITO_SWITCH_ON));
  switcher_button->SetImageAlignment(views::ImageButton::ALIGN_CENTER,
                                     views::ImageButton::ALIGN_MIDDLE);
  return switcher_button;
}

static int GetMinimizeButtonOffsetForWindow(gfx::NativeView window) {
  // The WM_GETTITLEBARINFOEX message can fail if we are not active/visible.
  TITLEBARINFOEX titlebar_info = {0};
  titlebar_info.cbSize = sizeof(TITLEBARINFOEX);
  SendMessage(window, WM_GETTITLEBARINFOEX, 0,
              reinterpret_cast<WPARAM>(&titlebar_info));

  CPoint minimize_button_corner(titlebar_info.rgrect[2].left,
                                titlebar_info.rgrect[2].top);
  MapWindowPoints(HWND_DESKTOP, window, &minimize_button_corner, 1);
  return minimize_button_corner.x;
}

///////////////////////////////////////////////////////////////////////////////
// BrowserFrameWin, public:

BrowserFrameWin::BrowserFrameWin(BrowserFrame* browser_frame,
                                 BrowserView* browser_view)
    : views::NativeWidgetWin(browser_frame),
      browser_view_(browser_view),
      browser_frame_(browser_frame),
      system_menu_delegate_(new SystemMenuModelDelegate(browser_view,
          browser_view->browser())),
      cached_minimize_button_x_delta_(0) {
  if (base::win::IsMetroProcess()) {
    browser_view->SetWindowSwitcherButton(
        MakeWindowSwitcherButton(this, browser_view->IsOffTheRecord()));
  }
}

BrowserFrameWin::~BrowserFrameWin() {
}

// static
void BrowserFrameWin::SetShowState(int state) {
  explicit_show_state = state;
}

void BrowserFrameWin::AdjustFrameForImmersiveMode() {
#if defined(USE_AURA)
  return;
#endif  // USE_AURA
  HMODULE metro = base::win::GetMetroModule();
  if (!metro)
    return;
  // We are in metro mode.
  browser_frame_->set_frame_type(views::Widget::FRAME_TYPE_FORCE_CUSTOM);
  SetFrameWindow set_frame_window = reinterpret_cast<SetFrameWindow>(
      ::GetProcAddress(metro, "SetFrameWindow"));
  set_frame_window(browser_frame_->GetNativeWindow());
}

void BrowserFrameWin::CloseImmersiveFrame() {
#if defined(USE_AURA)
  return;
#endif  // USE_AURA
  HMODULE metro = base::win::GetMetroModule();
  if (!metro)
    return;
  CloseFrameWindow close_frame_window = reinterpret_cast<CloseFrameWindow>(
      ::GetProcAddress(metro, "CloseFrameWindow"));
  close_frame_window(browser_frame_->GetNativeWindow());
}

///////////////////////////////////////////////////////////////////////////////
// BrowserFrameWin, views::NativeWidgetWin overrides:

int BrowserFrameWin::GetShowState() const {
  if (explicit_show_state != -1)
    return explicit_show_state;

  STARTUPINFO si = {0};
  si.cb = sizeof(si);
  si.dwFlags = STARTF_USESHOWWINDOW;
  GetStartupInfo(&si);
  return si.wShowWindow;
}

gfx::Insets BrowserFrameWin::GetClientAreaInsets() const {
  // Use the default client insets for an opaque frame or a glass popup/app
  // frame.
  if (!GetWidget()->ShouldUseNativeFrame() ||
      !browser_view_->IsBrowserTypeNormal()) {
    return NativeWidgetWin::GetClientAreaInsets();
  }

  int border_thickness = GetSystemMetrics(SM_CXSIZEFRAME);
  // In fullscreen mode, we have no frame. In restored mode, we draw our own
  // client edge over part of the default frame.
  if (IsFullscreen())
    border_thickness = 0;
  else if (!IsMaximized())
    border_thickness -= kClientEdgeThickness;
  return gfx::Insets(0, border_thickness, border_thickness, border_thickness);
}

void BrowserFrameWin::UpdateFrameAfterFrameChange() {
  // We need to update the glass region on or off before the base class adjusts
  // the window region.
  UpdateDWMFrame();
  NativeWidgetWin::UpdateFrameAfterFrameChange();
}

void BrowserFrameWin::OnEndSession(BOOL ending, UINT logoff) {
  browser::SessionEnding();
}

void BrowserFrameWin::OnInitMenuPopup(HMENU menu, UINT position,
                                      BOOL is_system_menu) {
  system_menu_->UpdateStates();
}

void BrowserFrameWin::OnWindowPosChanged(WINDOWPOS* window_pos) {
  NativeWidgetWin::OnWindowPosChanged(window_pos);
  UpdateDWMFrame();

  // Windows lies to us about the position of the minimize button before a
  // window is visible.  We use this position to place the OTR avatar in RTL
  // mode, so when the window is shown, we need to re-layout and schedule a
  // paint for the non-client frame view so that the icon top has the correct
  // position when the window becomes visible.  This fixes bugs where the icon
  // appears to overlay the minimize button.
  // Note that we will call Layout every time SetWindowPos is called with
  // SWP_SHOWWINDOW, however callers typically are careful about not specifying
  // this flag unless necessary to avoid flicker.
  // This may be invoked during creation on XP and before the non_client_view
  // has been created.
  if (window_pos->flags & SWP_SHOWWINDOW && GetWidget()->non_client_view()) {
    GetWidget()->non_client_view()->Layout();
    GetWidget()->non_client_view()->SchedulePaint();
  }
}

void BrowserFrameWin::OnScreenReaderDetected() {
  BrowserAccessibilityState::GetInstance()->OnScreenReaderDetected();
  NativeWidgetWin::OnScreenReaderDetected();
}

bool BrowserFrameWin::ShouldUseNativeFrame() const {
  // App panel windows draw their own frame.
  if (browser_view_->IsPanel())
    return false;

  // We don't theme popup or app windows, so regardless of whether or not a
  // theme is active for normal browser windows, we don't want to use the custom
  // frame for popups/apps.
  if (!browser_view_->IsBrowserTypeNormal() &&
      NativeWidgetWin::ShouldUseNativeFrame()) {
    return true;
  }

  // Otherwise, we use the native frame when we're told we should by the theme
  // provider (e.g. no custom theme is active).
  return GetWidget()->GetThemeProvider()->ShouldUseNativeFrame();
}

void BrowserFrameWin::Show() {
  AdjustFrameForImmersiveMode();
  views::NativeWidgetWin::Show();
}

void BrowserFrameWin::ShowMaximizedWithBounds(
    const gfx::Rect& restored_bounds) {
  AdjustFrameForImmersiveMode();
  views::NativeWidgetWin::ShowMaximizedWithBounds(restored_bounds);
}

void BrowserFrameWin::ShowWithWindowState(ui::WindowShowState show_state) {
  AdjustFrameForImmersiveMode();
  views::NativeWidgetWin::ShowWithWindowState(show_state);
}

void BrowserFrameWin::Close() {
  CloseImmersiveFrame();
  views::NativeWidgetWin::Close();
}

void BrowserFrameWin::OnActivate(UINT action, BOOL minimized, HWND window) {
  if (action != WA_INACTIVE)
    CacheMinimizeButtonDelta();
  views::NativeWidgetWin::OnActivate(action, minimized, window);
}

void BrowserFrameWin::FrameTypeChanged() {
  // In Windows 8 metro mode the frame type is set to FRAME_TYPE_FORCE_CUSTOM
  // by default. We reset it back to FRAME_TYPE_DEFAULT to ensure that we
  // don't end up defaulting to BrowserNonClientFrameView in all cases.
  if (base::win::IsMetroProcess())
    browser_frame_->set_frame_type(views::Widget::FRAME_TYPE_DEFAULT);

  views::NativeWidgetWin::FrameTypeChanged();

  // In Windows 8 metro mode we call Show on the BrowserFrame instance to
  // ensure that the window can be styled appropriately, i.e. no sysmenu,
  // etc.
  if (base::win::IsMetroProcess())
    Show();
}

void BrowserFrameWin::SetFullscreen(bool fullscreen) {
  if (base::win::IsMetroProcess()) {
    HMODULE metro = base::win::GetMetroModule();
    if (metro) {
      MetroSetFullscreen set_full_screen = reinterpret_cast<MetroSetFullscreen>(
        ::GetProcAddress(metro, "SetFullscreen"));
      DCHECK(set_full_screen);
      if (set_full_screen)
        set_full_screen(fullscreen);
    } else {
      NOTREACHED() << "Failed to get metro driver module";
    }
  }
  views::NativeWidgetWin::SetFullscreen(fullscreen);
}

////////////////////////////////////////////////////////////////////////////////
// BrowserFrameWin, NativeBrowserFrame implementation:

views::NativeWidget* BrowserFrameWin::AsNativeWidget() {
  return this;
}

const views::NativeWidget* BrowserFrameWin::AsNativeWidget() const {
  return this;
}

void BrowserFrameWin::InitSystemContextMenu() {
  system_menu_contents_.reset(new SystemMenuModel(system_menu_delegate_.get()));
  // We add the menu items in reverse order so that insertion_index never needs
  // to change.
  if (browser_view_->IsBrowserTypeNormal())
    BuildSystemMenuForBrowserWindow();
  else
    BuildSystemMenuForAppOrPopupWindow();
  system_menu_.reset(
      new views::NativeMenuWin(system_menu_contents_.get(), GetNativeWindow()));
  system_menu_->Rebuild();
}

int BrowserFrameWin::GetMinimizeButtonOffset() const {
  int minimize_button_offset =
      GetMinimizeButtonOffsetForWindow(GetNativeView());

  if (minimize_button_offset > 0)
    return minimize_button_offset;

  // If we fail to get the minimize button offset via the WM_GETTITLEBARINFOEX
  // message then calculate and return this via the
  // cached_minimize_button_x_delta_ member value. Please see
  // CacheMinimizeButtonDelta() for more details.
  DCHECK(cached_minimize_button_x_delta_);

  RECT client_rect = {0};
  GetClientRect(&client_rect);

  if (base::i18n::IsRTL())
    return cached_minimize_button_x_delta_;
  else
    return client_rect.right - cached_minimize_button_x_delta_;
}

void BrowserFrameWin::TabStripDisplayModeChanged() {
  UpdateDWMFrame();
}

void BrowserFrameWin::ButtonPressed(views::Button* sender,
                                    const views::Event& event) {
  HMODULE metro = base::win::GetMetroModule();
  if (!metro)
    return;
  // Tell the metro_driver to flip our window. This causes the current
  // browser window to be hidden and the next window to be shown.
  static FlipFrameWindows flip_window_fn = reinterpret_cast<FlipFrameWindows>(
      ::GetProcAddress(metro, "FlipFrameWindows"));
  if (flip_window_fn)
    flip_window_fn();
}

LRESULT BrowserFrameWin::OnWndProc(UINT message,
                                   WPARAM w_param,
                                   LPARAM l_param) {
  static const UINT metro_navigation_search_message =
      RegisterWindowMessage(chrome::kMetroNavigationAndSearchMessage);

  static const UINT metro_get_current_tab_info_message =
      RegisterWindowMessage(chrome::kMetroGetCurrentTabInfoMessage);

  if (message == metro_navigation_search_message) {
    HandleMetroNavSearchRequest(w_param, l_param);
  } else if (message == metro_get_current_tab_info_message) {
    GetMetroCurrentTabInfo(w_param);
  } else if (message == WM_PRINT && base::win::IsMetroProcess()) {
    // This message is sent by the AnimateWindow API which is used in metro
    // mode to flip between active chrome windows.
    RECT client_rect = {0};
    ::GetClientRect(GetNativeView(), &client_rect);
    HDC dest_dc = reinterpret_cast<HDC>(w_param);
    DCHECK(dest_dc);
    HDC src_dc = ::GetDC(GetNativeView());
    ::BitBlt(dest_dc, 0, 0, client_rect.right - client_rect.left,
             client_rect.bottom - client_rect.top, src_dc, 0, 0,
             SRCCOPY);
    ::ReleaseDC(GetNativeView(), src_dc);
    return 0;
  }
  return views::NativeWidgetWin::OnWndProc(message, w_param, l_param);
}

///////////////////////////////////////////////////////////////////////////////
// BrowserFrameWin, private:

void BrowserFrameWin::UpdateDWMFrame() {
  // For "normal" windows on Aero, we always need to reset the glass area
  // correctly, even if we're not currently showing the native frame (e.g.
  // because a theme is showing), so we explicitly check for that case rather
  // than checking browser_frame_->ShouldUseNativeFrame() here.  Using that here
  // would mean we wouldn't reset the glass area to zero when moving from the
  // native frame to an opaque frame, leading to graphical glitches behind the
  // opaque frame.  Instead, we use that function below to tell us whether the
  // frame is currently native or opaque.
  if (!GetWidget()->client_view() || !browser_view_->IsBrowserTypeNormal() ||
      !NativeWidgetWin::ShouldUseNativeFrame())
    return;

  MARGINS margins = { 0 };

  // If the opaque frame is visible, we use the default (zero) margins.
  // Otherwise, we need to figure out how to extend the glass in.
  if (browser_frame_->ShouldUseNativeFrame()) {
    // In fullscreen mode, we don't extend glass into the client area at all,
    // because the GDI-drawn text in the web content composited over it will
    // become semi-transparent over any glass area.
    if (!IsMaximized() && !IsFullscreen()) {
      margins.cxLeftWidth = kClientEdgeThickness + 1;
      margins.cxRightWidth = kClientEdgeThickness + 1;
      margins.cyBottomHeight = kClientEdgeThickness + 1;
      margins.cyTopHeight = kClientEdgeThickness + 1;
    }
    // In maximized mode, we only have a titlebar strip of glass, no side/bottom
    // borders.
    if (!browser_view_->IsFullscreen()) {
      gfx::Rect tabstrip_bounds(
          browser_frame_->GetBoundsForTabStrip(browser_view_->tabstrip()));
      margins.cyTopHeight = tabstrip_bounds.bottom() + kDWMFrameTopOffset;
    }
  }

  DwmExtendFrameIntoClientArea(GetNativeView(), &margins);
}

void BrowserFrameWin::BuildSystemMenuForBrowserWindow() {
  system_menu_contents_->AddSeparator();

  if (chrome::CanOpenTaskManager()) {
    system_menu_contents_->AddItemWithStringId(IDC_TASK_MANAGER,
                                               IDS_TASK_MANAGER);
  }
  system_menu_contents_->AddSeparator();
  system_menu_contents_->AddItemWithStringId(IDC_RESTORE_TAB, IDS_RESTORE_TAB);
  system_menu_contents_->AddItemWithStringId(IDC_NEW_TAB, IDS_NEW_TAB);
  AddFrameToggleItems();
  // If it's a regular browser window with tabs, we don't add any more items,
  // since it already has menus (Page, Chrome).
}

void BrowserFrameWin::BuildSystemMenuForAppOrPopupWindow() {
  Browser* browser = browser_view()->browser();
  if (browser->is_app() && chrome::CanOpenTaskManager()) {
    system_menu_contents_->AddSeparator();
    system_menu_contents_->AddItemWithStringId(IDC_TASK_MANAGER,
                                               IDS_TASK_MANAGER);
  }
  system_menu_contents_->AddSeparator();
  encoding_menu_contents_.reset(new EncodingMenuModel(browser));
  system_menu_contents_->AddSubMenuWithStringId(IDC_ENCODING_MENU,
                                                IDS_ENCODING_MENU,
                                                encoding_menu_contents_.get());
  zoom_menu_contents_.reset(new ZoomMenuModel(system_menu_delegate_.get()));
  system_menu_contents_->AddSubMenuWithStringId(IDC_ZOOM_MENU, IDS_ZOOM_MENU,
                                                zoom_menu_contents_.get());
  system_menu_contents_->AddItemWithStringId(IDC_PRINT, IDS_PRINT);
  system_menu_contents_->AddItemWithStringId(IDC_FIND, IDS_FIND);
  system_menu_contents_->AddSeparator();
  system_menu_contents_->AddItemWithStringId(IDC_PASTE, IDS_PASTE);
  system_menu_contents_->AddItemWithStringId(IDC_COPY, IDS_COPY);
  system_menu_contents_->AddItemWithStringId(IDC_CUT, IDS_CUT);
  system_menu_contents_->AddSeparator();
  if (browser->is_app()) {
    system_menu_contents_->AddItemWithStringId(IDC_NEW_TAB,
                                               IDS_APP_MENU_NEW_WEB_PAGE);
  } else {
    system_menu_contents_->AddItemWithStringId(IDC_SHOW_AS_TAB,
                                               IDS_SHOW_AS_TAB);
  }
  system_menu_contents_->AddSeparator();
  system_menu_contents_->AddItemWithStringId(IDC_RELOAD, IDS_APP_MENU_RELOAD);
  system_menu_contents_->AddItemWithStringId(IDC_FORWARD,
                                             IDS_CONTENT_CONTEXT_FORWARD);
  system_menu_contents_->AddItemWithStringId(IDC_BACK,
                                             IDS_CONTENT_CONTEXT_BACK);
  AddFrameToggleItems();
}

void BrowserFrameWin::AddFrameToggleItems() {
  if (CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kDebugEnableFrameToggle)) {
    system_menu_contents_->AddSeparator();
    system_menu_contents_->AddItem(IDC_DEBUG_FRAME_TOGGLE,
                                   L"Toggle Frame Type");
  }
}

void BrowserFrameWin::HandleMetroNavSearchRequest(WPARAM w_param,
                                                  LPARAM l_param) {
  if (!base::win::IsMetroProcess()) {
    NOTREACHED() << "Received unexpected metro navigation request";
    return;
  }

  if (!w_param && !l_param) {
    NOTREACHED() << "Invalid metro request parameters";
    return;
  }

  Browser* browser = browser_view()->browser();
  DCHECK(browser);

  GURL request_url;

  if (w_param) {
    const wchar_t* url = reinterpret_cast<const wchar_t*>(w_param);
    request_url = GURL(url);
  } else if (l_param) {
    const wchar_t* search_string =
        reinterpret_cast<const wchar_t*>(l_param);
    const TemplateURL* default_provider =
        TemplateURLServiceFactory::GetForProfile(browser->profile())->
        GetDefaultSearchProvider();
    if (default_provider) {
      const TemplateURLRef& search_url = default_provider->url_ref();
      DCHECK(search_url.SupportsReplacement());
      request_url = GURL(search_url.ReplaceSearchTerms(
          TemplateURLRef::SearchTermsArgs(search_string)));
    }
  }
  if (request_url.is_valid()) {
    browser->OpenURL(OpenURLParams(request_url, Referrer(), NEW_FOREGROUND_TAB,
                                   content::PAGE_TRANSITION_TYPED, false));
  }
}

void BrowserFrameWin::GetMetroCurrentTabInfo(WPARAM w_param) {
  if (!base::win::IsMetroProcess()) {
    NOTREACHED() << "Received unexpected metro request";
    return;
  }

  if (!w_param) {
    NOTREACHED() << "Invalid metro request parameter";
    return;
  }

  base::win::CurrentTabInfo* current_tab_info =
      reinterpret_cast<base::win::CurrentTabInfo*>(w_param);

  Browser* browser = browser_view()->browser();
  DCHECK(browser);

  // We allocate memory for the title and url via LocalAlloc. The caller has to
  // free the memory via LocalFree.
  current_tab_info->title = base::win::LocalAllocAndCopyString(
      browser->GetWindowTitleForCurrentTab());

  WebContents* current_tab = chrome::GetActiveWebContents(browser);
  DCHECK(current_tab);

  current_tab_info->url = base::win::LocalAllocAndCopyString(
      UTF8ToWide(current_tab->GetURL().spec()));
}

void BrowserFrameWin::CacheMinimizeButtonDelta() {
  int minimize_offset = GetMinimizeButtonOffsetForWindow(GetNativeView());
  if (!minimize_offset)
    return;

  RECT rect = {0};
  GetClientRect(&rect);
  // Calculate and cache the value of the minimize button delta, i.e. the
  // offset to be applied to the left or right edge of the client rect
  // depending on whether the language is RTL or not.
  // This cached value is only used if the WM_GETTITLEBARINFOEX message fails
  // to get the offset of the minimize button.
  if (base::i18n::IsRTL())
    cached_minimize_button_x_delta_ = minimize_offset;
  else
    cached_minimize_button_x_delta_ = rect.right - minimize_offset;
}

////////////////////////////////////////////////////////////////////////////////
// BrowserFrame, public:

// static
const gfx::Font& BrowserFrame::GetTitleFont() {
  static gfx::Font* title_font =
      new gfx::Font(views::NativeWidgetWin::GetWindowTitleFont());
  return *title_font;
}

////////////////////////////////////////////////////////////////////////////////
// NativeBrowserFrame, public:

// static
NativeBrowserFrame* NativeBrowserFrame::CreateNativeBrowserFrame(
    BrowserFrame* browser_frame,
    BrowserView* browser_view) {
  return new BrowserFrameWin(browser_frame, browser_view);
}


text:
#include "timer.h"

#include <stdio.h>

// pulled from the defaults in memcached
#define FB_TIMER_DEFAULT_LATENCY_COUNTDOWN 100
#define FB_TIMER_DEFAULT_LATENCY_AVG_POWER 6

static fb_timer_list_t all_timers;
static int num_timers = 0;
fb_cycle_timer_func_t* cycle_timer_func = &cycle_timer;
static double cpu_frequency_MHz;

static nstring_t timer_output_names[] = {
  NSTRING_LIT(".total_time_us"),
  NSTRING_LIT(".recent_peak_us"),
  NSTRING_LIT(".avg_peak_us"),
  NSTRING_LIT(".recent_min_us"),
  NSTRING_LIT(".avg_min_us"),
  NSTRING_LIT(".abs_min_us"),
};

static void fb_timer_init() {
  static int fb_timer_initialized = 0;
  if (fb_timer_initialized == 0) {
    TAILQ_INIT(&all_timers);
    num_timers = 0;
    cpu_frequency_MHz = get_cpu_frequency();
    fb_timer_initialized = 1;
  }

}

void fb_timer_set_cycle_timer_func(fb_cycle_timer_func_t func,
                                   double cycles_per_usec) {
  fb_timer_init();

  cycle_timer_func = func;
  cpu_frequency_MHz = cycles_per_usec;
}

fb_timer_t* fb_timer_alloc(nstring_t name, int window_size,
                           int decay_power) {
  fb_timer_t *ret;
  int i;

  fb_timer_init();
  ret = calloc(1, sizeof(fb_timer_t));
  if (!ret) {
    return NULL;
  }

  ret->names = malloc(sizeof(nstring_t)*NUM_TIMER_OUTPUT_TYPES);
  for (i = 0; i < NUM_TIMER_OUTPUT_TYPES; i++) {
    ret->names[i].len = name.len + timer_output_names[i].len;
    ret->names[i].str = malloc(ret->names[i].len + 1);
    memcpy(ret->names[i].str, name.str, name.len);
    memcpy(ret->names[i].str + name.len,
           timer_output_names[i].str,
           timer_output_names[i].len);
    ret->names[i].str[ret->names[i].len] = '\0';
  }

  ret->latency_countdown = (window_size == 0 ?
                            FB_TIMER_DEFAULT_LATENCY_COUNTDOWN :
                            window_size);

  ret->latency_avg_power = (decay_power == 0 ?
                            FB_TIMER_DEFAULT_LATENCY_AVG_POWER :
                            decay_power);

  ret->idx = ret->latency_countdown;

  ret->abs_min = 0;
  ret->min = 0;

  ret->status = TIMER_STOPPED;
  return ret;
}

void fb_timer_register(fb_timer_t* timer) {
  if (!timer) {
    return;
  }
  if (!timer->registered) {
    TAILQ_INSERT_TAIL(&all_timers, timer, entry);
    timer->registered = 1;
    num_timers++;
  }
}

fb_timer_list_t fb_timer_get_all_timers() {
  return all_timers;
}

int fb_timer_get_num_timers() {
  return num_timers;
}

void fb_timer_free(fb_timer_t* timer) {
  fb_timer_t *curr_temp, *curr;
  int i;
  TAILQ_FOREACH_SAFE(curr, &all_timers, entry, curr_temp) {
    if (curr == timer) {
      TAILQ_REMOVE(&all_timers, curr, entry);
      timer->registered = 0;
      break;
    }
  }
  for (i = 0; i < NUM_TIMER_OUTPUT_TYPES; i ++) {
    free(timer->names[i].str);
  }
  free(timer->names);
  free(timer);
}

double fb_timer_get_total_time(fb_timer_t* timer) {
  return ((double) timer->total_time) / cpu_frequency_MHz;
}

double fb_timer_get_recent_peak(fb_timer_t* timer) {
  return ((double) timer->peak) / cpu_frequency_MHz;
}

double fb_timer_get_avg_peak(fb_timer_t* timer) {
  return ((double) timer->avg_peak) / cpu_frequency_MHz;
}

double fb_timer_get_avg(fb_timer_t* timer) {
  return ((double) timer->avg) / cpu_frequency_MHz;
}

double fb_timer_get_recent_min(fb_timer_t *timer){
  return ((double) timer->min) / cpu_frequency_MHz;
}

double fb_timer_get_avg_min(fb_timer_t* timer){
  return ((double) timer->avg_min) / cpu_frequency_MHz;
}

double fb_timer_get_abs_min(fb_timer_t *timer){
  return ((double) timer->abs_min) / cpu_frequency_MHz;
}

static inline void fb_timer_to_nstring_helper(nstring_t* nstr, double value) {
  char temp[100];
  int len;
  len = snprintf(temp, 100, "%g", value);
  // the string was truncated so we only care about the truncated length
  if (len > 100) {
    len = 100;
  }

  nstr->str = malloc(len + 1);
  nstr->len = len;
  memcpy(nstr->str, temp, nstr->len);
  nstr->str[len] = '\0';
}

void fb_timer_to_nstring(fb_timer_t* timer, nstring_t* vals) {
  fb_timer_to_nstring_helper(&vals[TIMER_TOTAL],
                             fb_timer_get_total_time(timer));
  fb_timer_to_nstring_helper(&vals[TIMER_RECENT_PEAK],
                             fb_timer_get_recent_peak(timer));
  fb_timer_to_nstring_helper(&vals[TIMER_AVG_PEAK],
                             fb_timer_get_avg_peak(timer));
  fb_timer_to_nstring_helper(&vals[TIMER_RECENT_MIN],
                             fb_timer_get_recent_min(timer));
  fb_timer_to_nstring_helper(&vals[TIMER_AVG_MIN],
                             fb_timer_get_avg_min(timer));
  fb_timer_to_nstring_helper(&vals[TIMER_ABS_MIN],
                             fb_timer_get_abs_min(timer));
}


text:
//
// Generated by JTB 1.3.2
//

package com.mhs.qsol.syntaxtree;

/**
 * The interface which NodeList, NodeListOptional, and NodeSequence implement.
 */
public interface NodeListInterface extends Node {
  public void addNode(Node n);

  public Node elementAt(int i);

  public java.util.Enumeration<Node> elements();

  public int size();

  public void accept(com.mhs.qsol.visitor.Visitor v);

  public <R, A> R accept(com.mhs.qsol.visitor.GJVisitor<R, A> v, A argu);

  public <R> R accept(com.mhs.qsol.visitor.GJNoArguVisitor<R> v);

  public <A> void accept(com.mhs.qsol.visitor.GJVoidVisitor<A> v, A argu);
}


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.ec.fragment.Fragment4">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment" />

</FrameLayout>


text:
# TheComments

[![Gem Version](https://badge.fury.io/rb/the_comments.png)](http://badge.fury.io/rb/the_comments) | [![Build Status](https://travis-ci.org/the-teacher/the_comments.png?branch=master)](https://travis-ci.org/the-teacher/the_comments) | [![Code Climate](https://codeclimate.com/github/the-teacher/the_comments.png)](https://codeclimate.com/github/the-teacher/the_comments) | [(rubygems)](http://rubygems.org/gems/the_comments)

TheComments - The best Rails gem for blog-style comments

:question:   [Why is TheComments better than other gems?](docs/whats_wrong_with_other_gems.md#why-thecomments-is-better-than-others-gems)

### Features

* Threaded comments
* Useful cache counters
* Admin UI for moderation
* Mountable Engine.routes
* Online Support via skype: **ilya.killich**
* [Denormalization](docs/denormalization_and_recent_comments.md) for recent comments
* Production-ready commenting system for Rails 4+
* Designed for preprocessors such as Sanitize, Textile, Markdawn etc.

### :books:   [Documentation](docs/documentation.md)

## If you have any questions

Please try playing around with the **[Dummy App](spec/dummy_app)** in the `spec` folder first. An example integration is often better than any documentation! Thanks.

## How to start the dummy app (screencast)

[![Foo](https://raw.github.com/the-teacher/the_comments/master/docs/screencast.jpg)](http://vk.com/video_ext.php?oid=49225742&id=166578209&hash=10be1dba625149bb&hd=3)

## Quick Start Installation

**NB: In the following examples, `Posts` is the model to which comments are being added. For your app, the model might be `Articles` or similar instead.**

### 1. Install Gems

**Gemfile**

```ruby
gem "the_comments", "~> 2.2.1"

gem 'haml'                # or gem 'slim'
gem 'awesome_nested_set'  # or same gem
```

**Bundle**

```
bundle
```

Don't forget to restart your server!

### 2. Add migrations

```
rake the_comments_engine:install:migrations
```

Will create:

* xxxxx_change_user.rb
* xxxxx_create_comments.rb
* xxxxx_change_commentable.rb

:warning:   **Open and change xxxxx_change_commentable.rb migration**

```ruby
class ChangeCommentable < ActiveRecord::Migration
  def change
    # Additional fields to Commentable Models
    # [:posts, :articles, ... ]

    # There is only Post model is commentable
    [:posts].each do |table_name|
      change_table table_name do |t|
        t.integer :draft_comments_count,     default: 0
        t.integer :published_comments_count, default: 0
        t.integer :deleted_comments_count,   default: 0
      end
    end
  end
end
```

**Invoke migrations**

```
rake db:migrate
```

### 3. Code installation

```ruby
rails g the_comments install
```

Will create:

* config/initializers/the_comments.rb
* app/controllers/comments_controller.rb
* app/models/comment.rb

:warning:   **Open each file and follow the instructions**

### 4. Models modifictions

**app/models/user.rb**

```ruby
class User < ActiveRecord::Base
  include TheComments::User

  has_many :posts

  # IT'S JUST AN EXAMPLE OF ANY ROLE SYSTEM
  def admin?
    self == User.first
  end

  # YOU HAVE TO IMPLEMENT YOUR ROLE POLICY FOR COMMENTS HERE
  def comments_admin?
    admin?
  end

  def comments_moderator? comment
    id == comment.holder_id
  end
end
```

**app/models/post.rb**

```ruby
class Post < ActiveRecord::Base
  include TheComments::Commentable

  belongs_to :user

  # Denormalization methods
  # Check the documentation for information on advanced usage
  def commentable_title
    "Undefined Post Title"
  end

  def commentable_url
    "#"
  end

  def commentable_state
    "published"
  end
end
```

### 5. Add routes

**config/routes.rb**

```ruby
MyApp::Application.routes.draw do
  root 'posts#index'
  resources :posts

  # ...

  # TheComments routes
  concern   :user_comments,  TheComments::UserRoutes.new
  concern   :admin_comments, TheComments::AdminRoutes.new
  resources :comments, concerns:  [:user_comments, :admin_comments]
end
```

Refer to the [documentation](docs/documentation.md) for more information

### 6. Add to Application Controller

**app/controllers/application_controller.rb**

```ruby
class ApplicationController < ActionController::Base
  include TheComments::ViewToken

  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
end
```

### 7. Install assets

**app/assets/stylesheets/application.css**

```css
/*
 *= require the_comments
*/
```

**app/assets/javascripts/application.js**

```js
//= require the_comments
```

### 8. Example controller code

**app/controllers/posts_controller.rb**

```ruby
def show
  @post     = Post.find params[:id]
  @comments = @post.comments.with_state([:draft, :published])
end
```

### 9. Example view code

**app/views/posts/show.html.haml**

```haml
= render partial: 'the_comments/tree', locals: { commentable: @post, comments_tree: @comments }
```

### Common problems

For error with `unpermitted parameters` in webserver output.

Example:

    Unpermitted parameters: commentable_type, commentable_id

    User Load (0.3ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 1  ORDER BY "users"."id" ASC LIMIT 1

    Completed 500 Internal Server Error in 8ms

Add the following to your Comments Controller.

    def comment_params
      params
      .require(:comment)
      .permit(:title, :contacts, :raw_content, :parent_id, :commentable_type, :commentable_id)
      .merge(denormalized_fields)
      .merge(request_data_for_comment)
      .merge(tolerance_time: params[:tolerance_time].to_i)
      .merge(user: current_user, view_token: comments_view_token)
    end

See [here](https://github.com/the-teacher/the_comments/issues/34).

For errors with `around_validation`.

Example:

    NoMethodError - protected method `around_validation' called for #<StateMachine::Machine:0x007f84148c3c60>:

Create a new file `config/state_machine.rb`.

    # Rails 4.1.0.rc1 and StateMachine don't play nice
    # https://github.com/pluginaweek/state_machine/issues/295

    require 'state_machine/version'

    unless StateMachine::VERSION == '1.2.0'
      # If you see this message, please test removing this file
      # If it's still required, please bump up the version above
      Rails.logger.warn "Please remove me, StateMachine version has changed"
    end

    module StateMachine::Integrations::ActiveModel
      public :around_validation
    end

See [here](https://github.com/pluginaweek/state_machine/issues/295).

### Feedback

:speech_balloon:   My twitter: [@iam_teacher](https://twitter.com/iam_teacher)       hashtag: **#the_comments**

### Acknowledgments

* Anna Nechaeva (my wife) - for love and my happy life
* @tanraya (Andrew Kozlov) - for code review
* @solenko (Anton Petrunich) - for mountable routes
* @pyromaniac (Arkadiy Zabazhanov) - for consulting

### MIT License

Copyright (c) 2013 Ilya N. Zykin

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
<?php

namespace Modules\Mysql\Config;

if ( ! defined ( 'ENGINE' ) ) {
	die ( 'Get out of here!' );

}

class ConfigDb {
    const DBHOST = 'localhost';
    const DBNAME = 'cmsproject';
    const DBUSER = 'cmsproject';
    const DBPASS = 'cmsproject';
    /*
    const DBUSER = 'root';
    const DBPASS = 'mR7clzJsqXzVD7k6';
    */
    const COLLATE = 'utf8';
    const SECURE_AUTH_KEY = '[xF}Fsr;iXs 9jMP~YGYa8=0?cY0h*%?x~.loiu7+d@^(h|dHZ6^=)BBL/Pr}6iV';

    /**
     * @return string
     */
    public function getDbHost() {
        return ConfigDb::DBHOST;
    }

    /**
     * @return string
     */
    public function getDbName() {
        return ConfigDb::DBNAME;
    }

    /**
     * @return string
     */
    public function getDbUser() {
        return ConfigDb::DBUSER;
    }

    /**
     * @return string
     */
    public function getDbPass() {
        return ConfigDb::DBPASS;
    }

	/**
	 * @return string
	 */
	public function getCollate() {
		return ConfigDb::COLLATE;
	}

	/**
	 * @return string
	 */
	public function getSecureAuthKey() {
		return ConfigDb::SECURE_AUTH_KEY;

	}

}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Ceská Mykol. 43(4): 222 (1989)

#### Original name
null

### Remarks
null


text:
if [ "$1" ]; then
    echo "parameter: $1" >> quotes.txt
    # do something, e.g. adding your quote
else
    echo "Error: Missing parameter" 1>&2
    exit 1
fi


text:
=============
Configuration
=============

DevStack has always tried to be mostly-functional with a minimal amount
of configuration. The number of options has ballooned as projects add
features, new projects added and more combinations need to be tested.
Historically DevStack obtained all local configuration and
customizations from a ``localrc`` file. The number of configuration
variables that are simply passed-through to the individual project
configuration files is also increasing. The old mechanism for this
(``EXTRAS_OPTS`` and friends) required specific code for each file and
did not scale well.

In Oct 2013 a new configuration method was introduced (in `review
46768 <https://review.openstack.org/#/c/46768/>`__) to hopefully
simplify this process and meet the following goals:

-  contain all non-default local configuration in a single file
-  be backward-compatible with ``localrc`` to smooth the transition
   process
-  allow settings in arbitrary configuration files to be changed

local.conf
==========

The new configuration file is ``local.conf`` and resides in the root
DevStack directory like the old ``localrc`` file. It is a modified INI
format file that introduces a meta-section header to carry additional
information regarding the configuration files to be changed.

The new header is similar to a normal INI section header but with double
brackets (``[[ ... ]]``) and two internal fields separated by a pipe
(``|``):

::

    [[ <phase> | <config-file-name> ]]

where ``<phase>`` is one of a set of phase names defined by ``stack.sh``
and ``<config-file-name>`` is the configuration filename. The filename
is eval'ed in the ``stack.sh`` context so all environment variables are
available and may be used. Using the project config file variables in
the header is strongly suggested (see the ``NOVA_CONF`` example below).
If the path of the config file does not exist it is skipped.

The defined phases are:

-  **local** - extracts ``localrc`` from ``local.conf`` before
   ``stackrc`` is sourced
-  **pre-install** - runs after the system packages are installed but
   before any of the source repositories are installed
-  **install** - runs immediately after the repo installations are
   complete
-  **post-config** - runs after the layer 2 services are configured and
   before they are started
-  **extra** - runs after services are started and before any files in
   ``extra.d`` are executed

The file is processed strictly in sequence; meta-sections may be
specified more than once but if any settings are duplicated the last to
appear in the file will be used.

::

    [[post-config|$NOVA_CONF]]
    [DEFAULT]
    use_syslog = True

    [osapi_v3]
    enabled = False

A specific meta-section ``local|localrc`` is used to provide a default
``localrc`` file (actually ``.localrc.auto``). This allows all custom
settings for DevStack to be contained in a single file. If ``localrc``
exists it will be used instead to preserve backward-compatibility. More
details on the :doc:`contents of local.conf <local.conf>` are available.

::

    [[local|localrc]]
    FIXED_RANGE=10.254.1.0/24
    ADMIN_PASSWORD=speciale
    LOGFILE=$DEST/logs/stack.sh.log

Note that ``Q_PLUGIN_CONF_FILE`` is unique in that it is assumed to
*NOT* start with a ``/`` (slash) character. A slash will need to be
added:

::

    [[post-config|/$Q_PLUGIN_CONF_FILE]]

Also note that the ``localrc`` section is sourced as a shell script
fragment and MUST conform to the shell requirements, specifically no
whitespace around ``=`` (equals).

Minimal Configuration
=====================

While ``stack.sh`` is happy to run without a ``localrc`` section in
``local.conf``, devlife is better when there are a few minimal variables
set. This is an example of a minimal configuration that touches the
values that most often need to be set.

-  no logging
-  pre-set the passwords to prevent interactive prompts
-  move network ranges away from the local network (``FIXED_RANGE`` and
   ``FLOATING_RANGE``, commented out below)
-  set the host IP if detection is unreliable (``HOST_IP``, commented
   out below)

::

    [[local|localrc]]
    ADMIN_PASSWORD=secrete
    DATABASE_PASSWORD=$ADMIN_PASSWORD
    RABBIT_PASSWORD=$ADMIN_PASSWORD
    SERVICE_PASSWORD=$ADMIN_PASSWORD
    SERVICE_TOKEN=a682f596-76f3-11e3-b3b2-e716f9080d50
    #FIXED_RANGE=172.31.1.0/24
    #FLOATING_RANGE=192.168.20.0/25
    #HOST_IP=10.3.4.5

If the ``*_PASSWORD`` variables are not set here you will be prompted to
enter values for them by ``stack.sh``.

The network ranges must not overlap with any networks in use on the
host. Overlap is not uncommon as RFC-1918 'private' ranges are commonly
used for both the local networking and Nova's fixed and floating ranges.

``HOST_IP`` is normally detected on the first run of ``stack.sh`` but
often is indeterminate on later runs due to the IP being moved from an
Ethernet interface to a bridge on the host. Setting it here also makes it
available for ``openrc`` to set ``OS_AUTH_URL``. ``HOST_IP`` is not set
by default.

Common Configuration Variables
==============================

Installation Directory
----------------------

    | *Default: ``DEST=/opt/stack``*
    |  The DevStack install directory is set by the ``DEST`` variable.
    |  By setting it early in the ``localrc`` section you can reference it
       in later variables. It can be useful to set it even though it is not
       changed from the default value.
    |

    ::

        DEST=/opt/stack

Libraries from Git
------------------

   | *Default: ``LIBS_FROM_GIT=""``*

   | By default devstack installs OpenStack server components from
     git, however it installs client libraries from released versions
     on pypi. This is appropriate if you are working on server
     development, but if you want to see how an unreleased version of
     the client affects the system you can have devstack install it
     from upstream, or from local git trees.
   | Multiple libraries can be specified as a comma separated list.
   |

   ::

      LIBS_FROM_GIT=python-keystoneclient,oslo.config

Virtual Environments
--------------------

  | *Default: ``USE_VENV=False``*
  |   Enable the use of Python virtual environments by setting ``USE_VENV``
      to ``True``.  This will enable the creation of venvs for each project
      that is defined in the ``PROJECT_VENV`` array.

  | *Default: ``PROJECT_VENV['<project>']='<project-dir>.venv'*
  |   Each entry in the ``PROJECT_VENV`` array contains the directory name
      of a venv to be used for the project.  The array index is the project
      name.  Multiple projects can use the same venv if desired.

  ::

    PROJECT_VENV["glance"]=${GLANCE_DIR}.venv

  | *Default: ``ADDITIONAL_VENV_PACKAGES=""``*
  |   A comma-separated list of additional packages to be installed into each
      venv.  Often projects will not have certain packages listed in its
      ``requirements.txt`` file because they are 'optional' requirements,
      i.e. only needed for certain configurations.  By default, the enabled
      databases will have their Python bindings added when they are enabled.

Enable Logging
--------------

    | *Defaults: ``LOGFILE="" LOGDAYS=7 LOG_COLOR=True``*
    |  By default ``stack.sh`` output is only written to the console
       where is runs. It can be sent to a file in addition to the console
       by setting ``LOGFILE`` to the fully-qualified name of the
       destination log file. A timestamp will be appended to the given
       filename for each run of ``stack.sh``.
    |

    ::

        LOGFILE=$DEST/logs/stack.sh.log

    Old log files are cleaned automatically if ``LOGDAYS`` is set to the
    number of days of old log files to keep.

    ::

        LOGDAYS=1

    The some of the project logs (Nova, Cinder, etc) will be colorized
    by default (if ``SYSLOG`` is not set below); this can be turned off
    by setting ``LOG_COLOR`` False.

    ::

        LOG_COLOR=False

Logging the Service Output
--------------------------

    | *Default: ``LOGDIR=""``*
    |  DevStack will log the stdout output of the services it starts.
       When using ``screen`` this logs the output in the screen windows
       to a file.  Without ``screen`` this simply redirects stdout of
       the service process to a file in ``LOGDIR``.
    |

    ::

        LOGDIR=$DEST/logs

    *Note the use of ``DEST`` to locate the main install directory; this
    is why we suggest setting it in ``local.conf``.*

Enabling Syslog
---------------

    | *Default: ``SYSLOG=False SYSLOG_HOST=$HOST_IP SYSLOG_PORT=516``*
    |  Logging all services to a single syslog can be convenient. Enable
       syslogging by setting ``SYSLOG`` to ``True``. If the destination log
       host is not localhost ``SYSLOG_HOST`` and ``SYSLOG_PORT`` can be
       used to direct the message stream to the log host.
    |

    ::

        SYSLOG=True
        SYSLOG_HOST=$HOST_IP
        SYSLOG_PORT=516

A clean install every time
--------------------------

    | *Default: ``RECLONE=""``*
    |  By default ``stack.sh`` only clones the project repos if they do
       not exist in ``$DEST``. ``stack.sh`` will freshen each repo on each
       run if ``RECLONE`` is set to ``yes``. This avoids having to manually
       remove repos in order to get the current branch from ``$GIT_BASE``.
    |

    ::

        RECLONE=yes

Upgrade packages installed by pip
---------------------------------

    | *Default: ``PIP_UPGRADE=""``*
    |  By default ``stack.sh`` only installs Python packages if no version
       is currently installed or the current version does not match a specified
       requirement. If ``PIP_UPGRADE`` is set to ``True`` then existing required
       Python packages will be upgraded to the most recent version that
       matches requirements.
    |

    ::

        PIP_UPGRADE=True

Swift
-----

    | Default: SWIFT_HASH=""
    | SWIFT_REPLICAS=1
    | SWIFT_DATA_DIR=$DEST/data/swift

    | Swift is now used as the back-end for the S3-like object store.
      When enabled Nova's objectstore (n-obj in ENABLED_SERVICES) is
      automatically disabled. Enable Swift by adding it services to
      ENABLED_SERVICES: enable_service s-proxy s-object s-container
      s-account

    Setting Swift's hash value is required and you will be prompted for
    it if Swift is enabled so just set it to something already:

    ::

        SWIFT_HASH=66a3d6b56c1f479c8b4e70ab5c2000f5

    For development purposes the default number of replicas is set to
    ``1`` to reduce the overhead required. To better simulate a
    production deployment set this to ``3`` or more.

    ::

        SWIFT_REPLICAS=3

    The data for Swift is stored in the source tree by default (in
    ``$DEST/swift/data``) and can be moved by setting
    ``SWIFT_DATA_DIR``. The specified directory will be created if it
    does not exist.

    ::

        SWIFT_DATA_DIR=$DEST/data/swift

    *Note: Previously just enabling ``swift`` was sufficient to start
    the Swift services. That does not provide proper service
    granularity, particularly in multi-host configurations, and is
    considered deprecated. Some service combination tests now check for
    specific Swift services and the old blanket acceptance will longer
    work correctly.*

Service Catalog Backend
-----------------------

    | *Default: ``KEYSTONE_CATALOG_BACKEND=sql``*
    |  DevStack uses Keystone's ``sql`` service catalog backend. An
       alternate ``template`` backend is also available. However, it does
       not support the ``service-*`` and ``endpoint-*`` commands of the
       ``keystone`` CLI. To do so requires the ``sql`` backend be enabled:
    |

    ::

        KEYSTONE_CATALOG_BACKEND=template

    DevStack's default configuration in ``sql`` mode is set in
    ``files/keystone_data.sh``

Cinder
------

    | Default:
    | VOLUME_GROUP="stack-volumes" VOLUME_NAME_PREFIX="volume-" VOLUME_BACKING_FILE_SIZE=10250M
    |  The logical volume group used to hold the Cinder-managed volumes
       is set by ``VOLUME_GROUP``, the logical volume name prefix is set
       with ``VOLUME_NAME_PREFIX`` and the size of the volume backing file
       is set with ``VOLUME_BACKING_FILE_SIZE``.
    |

    ::

        VOLUME_GROUP="stack-volumes"
        VOLUME_NAME_PREFIX="volume-"
        VOLUME_BACKING_FILE_SIZE=10250M

Multi-host DevStack
-------------------

    | *Default: ``MULTI_HOST=False``*
    |  Running DevStack with multiple hosts requires a custom
       ``local.conf`` section for each host. The master is the same as a
       single host installation with ``MULTI_HOST=True``. The slaves have
       fewer services enabled and a couple of host variables pointing to
       the master.
    |  **Master**

    ::

        MULTI_HOST=True

    **Slave**

    ::

        MYSQL_HOST=w.x.y.z
        RABBIT_HOST=w.x.y.z
        GLANCE_HOSTPORT=w.x.y.z:9292
        ENABLED_SERVICES=n-vol,n-cpu,n-net,n-api

IP Version
    | Default: ``IP_VERSION=4``
    | This setting can be used to configure DevStack to create either an IPv4,
      IPv6, or dual stack tenant data network by setting ``IP_VERSION`` to
      either ``IP_VERSION=4``, ``IP_VERSION=6``, or ``IP_VERSION=4+6``
      respectively. This functionality requires that the Neutron networking
      service is enabled by setting the following options:
    |

    ::

        disable_service n-net
        enable_service q-svc q-agt q-dhcp q-l3

    | The following optional variables can be used to alter the default IPv6
      behavior:
    |

    ::

        IPV6_RA_MODE=slaac
        IPV6_ADDRESS_MODE=slaac
        FIXED_RANGE_V6=fd$IPV6_GLOBAL_ID::/64
        IPV6_PRIVATE_NETWORK_GATEWAY=fd$IPV6_GLOBAL_ID::1

    | *Note: ``FIXED_RANGE_V6`` and ``IPV6_PRIVATE_NETWORK_GATEWAY``
      can be configured with any valid IPv6 prefix. The default values make
      use of an auto-generated ``IPV6_GLOBAL_ID`` to comply with RFC 4193.*

Examples
========

-  Eliminate a Cinder pass-through (``CINDER_PERIODIC_INTERVAL``):

   ::

       [[post-config|$CINDER_CONF]]
       [DEFAULT]
       periodic_interval = 60

-  Sample ``local.conf`` with screen logging enabled:

   ::

       [[local|localrc]]
       FIXED_RANGE=10.254.1.0/24
       NETWORK_GATEWAY=10.254.1.1
       LOGDAYS=1
       LOGDIR=$DEST/logs
       LOGFILE=$LOGDIR/stack.sh.log
       ADMIN_PASSWORD=quiet
       DATABASE_PASSWORD=$ADMIN_PASSWORD
       RABBIT_PASSWORD=$ADMIN_PASSWORD
       SERVICE_PASSWORD=$ADMIN_PASSWORD
       SERVICE_TOKEN=a682f596-76f3-11e3-b3b2-e716f9080d50


text:
.histogram-bar rect {
  fill: steelblue;
  shape-rendering: crispEdges;
}

.histogram-bar rect:hover{
  opacity: 0.9;
}

.histogram-bar text {
  fill: #fff;
}

.histogram-axis path, .histogram-axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}


text:
package io.opentelemetry.sdk.autoconfigure;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import com.google.common.collect.ImmutableMap;
import io.opentelemetry.api.metrics.MeterProvider;
import io.opentelemetry.exporter.jaeger.JaegerGrpcSpanExporter;
import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter;
import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException;
import io.opentelemetry.sdk.trace.export.SpanExporter;
import java.util.Collections;
import org.junit.jupiter.api.Test;

class SpanExporterConfigurationTest {

  @Test
  void configureOtlpSpansUnsupportedProtocol() {
    assertThatThrownBy(
            () ->
                SpanExporterConfiguration.configureOtlp(
                    DefaultConfigProperties.createForTest(
                        ImmutableMap.of("otel.exporter.otlp.protocol", "foo")),
                    MeterProvider.noop()))
        .isInstanceOf(ConfigurationException.class)
        .hasMessageContaining("Unsupported OTLP traces protocol: foo");
  }

  // Timeout difficult to test using real exports so just check implementation detail here.
  @Test
  void configureOtlpTimeout() {
    SpanExporter exporter =
        SpanExporterConfiguration.configureExporter(
            "otlp",
            DefaultConfigProperties.createForTest(
                Collections.singletonMap("otel.exporter.otlp.timeout", "10")),
            NamedSpiManager.createEmpty(),
            MeterProvider.noop());
    try {
      assertThat(exporter)
          .isInstanceOfSatisfying(
              OtlpGrpcSpanExporter.class,
              otlp ->
                  assertThat(otlp).extracting("delegate.client.callTimeoutMillis").isEqualTo(10));
    } finally {
      exporter.shutdown();
    }
  }

  // Timeout difficult to test using real exports so just check implementation detail here.
  @Test
  void configureJaegerTimeout() {
    SpanExporter exporter =
        SpanExporterConfiguration.configureExporter(
            "jaeger",
            DefaultConfigProperties.createForTest(
                Collections.singletonMap("otel.exporter.jaeger.timeout", "10")),
            NamedSpiManager.createEmpty(),
            MeterProvider.noop());
    try {
      assertThat(exporter)
          .isInstanceOfSatisfying(
              JaegerGrpcSpanExporter.class,
              jaeger ->
                  assertThat(jaeger).extracting("delegate.client.callTimeoutMillis").isEqualTo(10));
    } finally {
      exporter.shutdown();
    }
  }

  // Timeout difficult to test using real exports so just check that things don't blow up.
  @Test
  void configureZipkinTimeout() {
    SpanExporter exporter =
        SpanExporterConfiguration.configureExporter(
            "zipkin",
            DefaultConfigProperties.createForTest(
                Collections.singletonMap("otel.exporter.zipkin.timeout", "5s")),
            NamedSpiManager.createEmpty(),
            MeterProvider.noop());
    try {
      assertThat(exporter).isNotNull();
    } finally {
      exporter.shutdown();
    }
  }
}


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------

namespace Microsoft.WindowsAzure.Management.Utilities.Store
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Security.Cryptography;
    using System.Security.Cryptography.X509Certificates;
    using System.Text;
    using System.Threading;
    using Microsoft.WindowsAzure.Management.Utilities.Common;
    using Microsoft.WindowsAzure.Management.Utilities.MarketplaceServiceReference;
    using Microsoft.WindowsAzure.Management.Utilities.Properties;
    using Microsoft.WindowsAzure.Management.Utilities.Store.Contract;
    using Microsoft.WindowsAzure.Management.Utilities.Store.ResourceModel;
    using Microsoft.WindowsAzure.ServiceManagement;
    using ServiceManagementConstants = Microsoft.WindowsAzure.ServiceManagement.Constants;

    public class StoreClient
    {
        private const int SleepDuration = 1000;

        private const string DataMarketResourceProviderNamespace = "DataMarket";

        private const string AppService = "AzureDevService";

        private const string StoreServicePrefix = "Azure-Stores";

        private const string IfMatchHeader = "If-Match";

        private IStoreManagement storeChannel;

        private IServiceManagement serviceManagementChannel;

        private string subscriptionId;

        private HeadersInspector headersInspector;

        private List<CloudService> GetStoreCloudServices()
        {
            CloudServiceList cloudServices = storeChannel.ListCloudServices(subscriptionId);
            List<CloudService> storeServices = cloudServices.FindAll(
                c => CultureInfo.CurrentCulture.CompareInfo.IsPrefix(c.Name, StoreServicePrefix));
            return storeServices;
        }

        private string GetCloudServiceName(string subscriptionId, string region)
        {
            string hashedSubId = String.Empty;
            using (SHA256 sha256 = SHA256Managed.Create())
            {
                hashedSubId = Base32NoPaddingEncode(sha256.ComputeHash(UTF8Encoding.UTF8.GetBytes(subscriptionId)));
            }

            return string.Format(CultureInfo.InvariantCulture, "{0}-{1}-{2}", StoreServicePrefix, hashedSubId, region.Replace(' ', '-'));
        }

        private string Base32NoPaddingEncode(byte[] data)
        {
            const string base32StandardAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";

            StringBuilder result = new StringBuilder(Math.Max((int)Math.Ceiling(data.Length * 8 / 5.0), 1));

            byte[] emptyBuffer = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
            byte[] workingBuffer = new byte[8];

            // Process input 5 bytes at a time
            for (int i = 0; i < data.Length; i += 5)
            {
                int bytes = Math.Min(data.Length - i, 5);
                Array.Copy(emptyBuffer, workingBuffer, emptyBuffer.Length);
                Array.Copy(data, i, workingBuffer, workingBuffer.Length - (bytes + 1), bytes);
                Array.Reverse(workingBuffer);
                ulong val = BitConverter.ToUInt64(workingBuffer, 0);

                for (int bitOffset = ((bytes + 1) * 8) - 5; bitOffset > 3; bitOffset -= 5)
                {
                    result.Append(base32StandardAlphabet[(int)((val >> bitOffset) & 0x1f)]);
                }
            }

            return result.ToString();
        }

        private string CreateCloudServiceIfNotExists(string location)
        {
            string cloudServiceName = GetCloudServiceName(subscriptionId, location);
            CloudService cloudService = new CloudService()
            {
                Name = cloudServiceName,
                Label = cloudServiceName,
                Description = string.Format(Resources.CloudServiceDescription, location),
                GeoRegion = location
            };
            try
            {
                storeChannel.CreateCloudService(subscriptionId, cloudServiceName, cloudService);
                WaitForOperation(headersInspector.ResponseHeaders[ServiceManagementConstants.OperationTrackingIdHeader]);
            }
            catch (Exception)
            {
                // The CloudService is already created, ignore exception.
            }

            return cloudServiceName;
        }

        private void WaitForOperation(string operationId)
        {
            Operation operation = new Operation();
            do
            {
                operation = serviceManagementChannel.GetOperationStatus(subscriptionId, operationId);
                Thread.Sleep(SleepDuration);
            }
            while (operation.Status == OperationState.InProgress);

            if (operation.Status == OperationState.Failed)
            {
                throw new Exception(string.Format(
                    Resources.OperationFailedMessage,
                    operation.Error.Message,
                    operation.Error.Code));
            }
        }

        private bool IsDataService(string type)
        {
            return type.Equals(WindowsAzureAddOn.DataType, StringComparison.OrdinalIgnoreCase);
        }

        public MarketplaceClient MarketplaceClient { get; set; }

        /// <summary>
        /// Parameterless constructor added for mocking framework.
        /// </summary>
        public StoreClient()
        {

        }

        /// <summary>
        /// Creates new instance from the store client.
        /// </summary>
        /// <param name="subscriptionId">The Windows Azure subscription id</param>
        /// <param name="storeEndpointUri">The service management endpoint uri</param>
        /// <param name="cert">The authentication certificate</param>
        /// <param name="logger">The logger for http request/response</param>
        /// <param name="serviceManagementChannel">The service management channel</param>
        public StoreClient(
            string subscriptionId,
            string storeEndpointUri,
            X509Certificate2 cert,
            Action<string> logger,
            IServiceManagement serviceManagementChannel)
        {
            Validate.ValidateStringIsNullOrEmpty(storeEndpointUri, null, true);
            Validate.ValidateStringIsNullOrEmpty(subscriptionId, null, true);
            Validate.ValidateNullArgument(cert, Resources.NullCertificateMessage);

            this.subscriptionId = subscriptionId;
            headersInspector = new HeadersInspector();
            storeChannel = ServiceManagementHelper.CreateServiceManagementChannel<IStoreManagement>(
                ConfigurationConstants.WebHttpBinding(0),
                new Uri(storeEndpointUri),
                cert,
                new HttpRestMessageInspector(logger),
                headersInspector);
            this.serviceManagementChannel = serviceManagementChannel;
            MarketplaceClient = new MarketplaceClient();
        }

        /// <summary>
        /// Gets add ons based on the passed filter.
        /// </summary>
        /// <param name="searchOptions">The add on search options</param>
        /// <returns>The list of filtered add ons</returns>
        public virtual List<WindowsAzureAddOn> GetAddOn(AddOnSearchOptions searchOptions = null)
        {
            List<WindowsAzureAddOn> addOns = new List<WindowsAzureAddOn>();
            List<CloudService> storeServices = GetStoreCloudServices();

            foreach (CloudService storeService in storeServices)
            {
                if (General.TryEquals(searchOptions.GeoRegion, storeService.GeoRegion))
                {
                    foreach (Resource resource in storeService.Resources)
                    {
                        if (General.TryEquals(searchOptions.Name, resource.Name) &&
                            General.TryEquals(searchOptions.Provider, resource.ResourceProviderNamespace))
                        {
                            addOns.Add(new WindowsAzureAddOn(resource, storeService.GeoRegion, storeService.Name));
                        }
                    }
                }
            }

            return addOns;
        }

        /// <summary>
        /// Removes given Add-On
        /// </summary>
        /// <param name="name">The add-on name</param>
        public virtual void RemoveAddOn(string name)
        {
            List<WindowsAzureAddOn> addOns = GetAddOn(new AddOnSearchOptions(name, null, null));

            if (addOns.Count != 1)
            {
                throw new Exception(string.Format(Resources.AddOnNotFound, name));
            }

            WindowsAzureAddOn addon = addOns[0];
            string type;
            string cloudService;
            string addonId;
            addonId = GetResourceInformation(addon.AddOn, addon.Location, out type, out cloudService);

            storeChannel.DeleteResource(
                subscriptionId,
                cloudService,
                type,
                addonId,
                name
            );

            WaitForOperation(headersInspector.ResponseHeaders[ServiceManagementConstants.OperationTrackingIdHeader]);
        }

        public virtual void NewAddOn(
            string name,
            string addon,
            string plan,
            string location,
            string promotionCode)
        {
            string type;
            string cloudService;
            addon = GetResourceInformation(addon, location, out type, out cloudService);

            Resource resource = new Resource()
            {
                Plan = plan,
                Type = type,
                PromotionCode = promotionCode
            };

            try
            {
                storeChannel.CreateResource(subscriptionId, cloudService, type, addon, name, resource);
            }
            catch (Exception ex)
            {
                if (ex.Message.Equals(Resources.FirstPurchaseErrorMessage, StringComparison.OrdinalIgnoreCase))
                {
                    throw new Exception(Resources.FirstPurchaseMessage);
                }
            }

            WaitForOperation(headersInspector.ResponseHeaders[ServiceManagementConstants.OperationTrackingIdHeader]);
        }

        private string GetResourceInformation(string addon, string location, out string type, out string cloudService)
        {
            Offer offer = MarketplaceClient.GetOffer(addon);
            type = offer.OfferType;
            string provider = offer.ProviderIdentifier;
            cloudService = CreateCloudServiceIfNotExists(location);
            type = IsDataService(type) ? DataMarketResourceProviderNamespace : provider;

            if (type.Equals(DataMarketResourceProviderNamespace, StringComparison.OrdinalIgnoreCase))
            {
                addon = string.Format("{0}-{1}", provider, addon);
            }
            return addon;
        }

        /// <summary>
        /// Gets confirmation message for the given operation.
        /// </summary>
        /// <param name="operation">The operation type</param>
        /// <param name="addon">The add-on id</param>
        /// <param name="plan">The plan id</param>
        /// <returns>The confirmation message</returns>
        public virtual string GetConfirmationMessage(OperationType operation, string addon = null, string plan = null)
        {
            Offer offer = null;
            bool microsoftOffer = false;
            string addOnUrl = null;
            string message = null;

            if (!string.IsNullOrEmpty(plan))
            {
                offer = MarketplaceClient.GetOffer(addon);

                if (offer == null)
                {
                    throw new Exception(string.Format(Resources.AddOnNotFound, addon));
                }

                if (!MarketplaceClient.IsKnownProvider(offer.ProviderId))
                {
                    throw new Exception(string.Format(Resources.UnknownProviderMessage, offer.ProviderId));
                }

                microsoftOffer = MarketplaceClient.IsMicrosoftOffer(offer);
                addOnUrl = string.Format(Resources.AddOnUrl, offer.Id);
            }

            switch (operation)
            {
                case OperationType.New:
                    message = microsoftOffer ? Resources.NewMicrosoftAddOnMessage :
                        Resources.NewNonMicrosoftAddOnMessage;
                    break;
                case OperationType.Set:
                    message = microsoftOffer ? Resources.SetMicrosoftAddOnMessage :
                        Resources.SetNonMicrosoftAddOnMessage;
                    break;
                case OperationType.Remove:
                    message = Resources.RemoveAddOnMessage;
                    break;
                default:
                    throw new Exception();
            }

            if (!string.IsNullOrEmpty(addOnUrl) && !string.IsNullOrEmpty(plan) && offer != null)
            {
                return string.Format(message, addOnUrl, plan, offer.ProviderIdentifier);
            }

            return message;
        }

        /// <summary>
        /// Tries to get an add-on using it's name.
        /// </summary>
        /// <param name="name">The add-on name</param>
        /// <param name="addon">The add-on instance. Will be null if not found</param>
        /// <returns>Boolean if the add-on is found, false otherwise</returns>
        public virtual bool TryGetAddOn(string name, out WindowsAzureAddOn addon)
        {
            List<WindowsAzureAddOn> addons = GetAddOn(new AddOnSearchOptions(name, null, null));

            if (addons.Count == 1)
            {
                addon = addons[0];
                return true;
            }

            addon = null;
            return false;
        }

        /// <summary>
        /// Updates an add-on plan.
        /// </summary>
        /// <param name="name">The add-on name</param>
        /// <param name="plan">The add-on new plan id</param>
        /// <param name="promotionCode">The plan promotion code</param>
        public virtual void UpdateAddOn(string name, string plan, string promotionCode)
        {
            List<WindowsAzureAddOn> addons = GetAddOn(new AddOnSearchOptions(name));
            if (addons.Count != 1)
            {
                throw new Exception(string.Format(Resources.AddOnNotFound, name));
            }

            WindowsAzureAddOn addon = addons[0];

            if (!string.IsNullOrEmpty(promotionCode) && addon.Plan.Equals(plan, StringComparison.OrdinalIgnoreCase))
            {
                throw new Exception(Resources.PromotionCodeWithCurrentPlanMessage);
            }

            headersInspector.RequestHeaders.Add(IfMatchHeader, addon.ETag);

            NewAddOn(name, addon.AddOn, plan, addon.Location, promotionCode);
        }
    }

    public enum OperationType
    {
        New,
        Set,
        Remove
    }
}


text:
""""
Django REST Framework client
https://github.com/qvantel/django-rest-framework-client
Copyright (c) 2017, Qvantel
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the Qvantel nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL QVANTEL BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import pydoc
import logging
import collections
import threading
import itertools
import urllib
import urlparse

ObjRef = collections.namedtuple('ObjRef', ['name', 'module'])

def qualname(cls):
    """
    Similar to the Python 3.3+ __qualname__ attribute.
    >>> qualname(C)
    'C'
    >>> qualname(C.f)
    'C.f'
    >>> qualname(C.D)
    'C.D'
    >>> qualname(C.D.g)
    'C.D.g'
    """
    return '%s.%s' % (cls.__module__, cls.__name__)

def lookup_by_name(class_name):
    """
    Imports an object by name or dotted path.
    """
    obj = pydoc.locate(class_name)
    if obj is None:
        raise ImportError('Unable to import "%s"' % (class_name))
    return obj

def lookup_by_objref(objref):
    """
    Imports an object by an ObjRef object.

    If ObjRef object also contains module attribute, it will also attempt to relative import from it
    when absolute import was not successful.
    """
    obj = pydoc.locate(objref.name)
    if obj is None:
        if objref.module is None:
            raise ImportError('Unable to import "%s"' % (objref.name))
        path = '.'.join([objref.module, objref.name])
        obj = pydoc.locate(path)
        if obj is None:
            raise ImportError('Unable to import "%s" nor "%s"' % (objref.name, path))
    return obj

class Indexable(object):
    """
    Indexable generator wrapper.

    Allows accessing individual items from a generator via indexes and slices.
    Computed items are cached so they can be accessed multiple times.

    Negative indexes are not supported.

    Example:
    >>> def generator():
    ...     i = 0
    ...     while True:
    ...         yield i
    ...         i += 1
    ...
    >>> generator()[0]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'generator' object has no attribute '__getitem__'
    >>> Indexable(generator())[0]
    0
    >>> Indexable(generator())[10:20:2]
    [10, 12, 14, 16, 18]
    >>> Indexable(generator())
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, '...(remaining elements truncated)...']

    See http://stackoverflow.com/a/2322711/682025
    """
    def __init__(self, it):
        self.it = iter(it)
        self.already_computed = []

    def __iter__(self):
        already_computed_it = iter(self.already_computed)
        try:
            while True:
                if already_computed_it.__length_hint__() == 0:
                    item = next(self.it)
                    self.already_computed.append(item)
                yield next(already_computed_it)
        except StopIteration:
            pass

    def __getitem__(self, index):
        try:
            max_idx = index.stop - 1
        except AttributeError:
            max_idx = index
        n = max_idx - len(self.already_computed) + 1
        if n > 0:
            self.already_computed.extend(itertools.islice(self.it, n))
        return self.already_computed[index]

    def __nonzero__(self):
        try:
            return self[0] is not None
        except IndexError:
            return False

    def __repr__(self):
        num_to_show = 10
        beginning = list(self[:num_to_show + 1])
        if len(beginning) == num_to_show + 1:
            beginning[num_to_show] = '...(remaining elements truncated)...'
        return beginning.__repr__()

_pending_setattrs = []
_pending_setattrs_lock = threading.Lock()

def setattr_lazy(get_obj, name, value):
    """
    Like setattr(obj, name, value) but for cases when obj is not yet known or importable.

    The actual setattr calls will be executed when calling setattr_lazy_finish() later.
    """
    with _pending_setattrs_lock:
        _pending_setattrs.append((get_obj, name, value))

def setattr_lazy_finish():
    """
    Sets the attributes marked to be set in calls to setattr_lazy
    """
    if not _pending_setattrs:
        return

    with _pending_setattrs_lock:
        while _pending_setattrs:
            get_obj, name, value = _pending_setattrs.pop()
            try:
                obj = get_obj()
            except ImportError as e:
                logging.error(e)
                raise
            setattr(obj, name, value)
            if hasattr(value, 'contribute_to_class'):
                value.contribute_to_class(obj, name)

def extend_url_query_string(url, params):
    """
    Extend the querystring of the url by the params dict and return the new URL
    """
    url_parsed = urlparse.urlparse(url)

    def no_nones(value):
        """
        Removes None values from a list or a tuple.
        Ignore any other value types.
        """
        if isinstance(value, (list, tuple)):
            return [x for x in value if x is not None]
        return value

    # Like the requests library, ignore any None values in params
    params = {k: no_nones(v)
              for k, v in params.iteritems()
              if v is not None}

    url_params = urlparse.parse_qs(url_parsed.query)
    url_params.update(params)
    query_string = urllib.urlencode(url_params, doseq=True)

    url_parts = list(url_parsed)
    url_parts[4] = query_string
    url = urlparse.urlunparse(url_parts)
    return url

def min_ignoring_nones(a, b):
    if a is None:
        return b
    if b is None:
        return a
    return min(a, b)


text:
class Solution {
private:
    vector<vector<int>> ans;
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        vector<int> myans;
        sort(candidates.begin(), candidates.end());
        makeSum(candidates, target, 0, myans);
        return ans;
    }
    void makeSum(vector<int>& candidates, int target, int index, vector<int>& myans) {
        if (target == 0) {
            ans.push_back(myans);
            return;
        }
        if (index >= candidates.size()) return;
        int nextIndex = index + 1;
        while (candidates[nextIndex] == candidates[nextIndex - 1]) nextIndex++;
        if (nextIndex > candidates.size()) nextIndex = candidates.size();
        makeSum(candidates, target, nextIndex, myans);
        int count = 0;
        for (int i = index; i < nextIndex && target - candidates[index] >= 0; i++) {
            count++;
            target -= candidates[index];
            myans.push_back(candidates[index]);
            makeSum(candidates, target, nextIndex, myans);
        }
        for (int i = 0; i < count; i++) {
            myans.pop_back();
        }
    }
};