text:
(function(){

/**
 * @requires jQuery
 */
if (!window.jQuery) {
  var jq = document.createElement('script');
  jq.type = 'text/javascript';
  jq.src = 'easy-writer/assets/jquery-2.1.4.min.js';
  document.getElementsByTagName('head')[0].appendChild(jq);
}

/** Initialize after page is loaded. */
window.onload = function(){
  ezw.editing.off();
  ezw.load();
};

/**
 * @namespace
 */
var ezw = ezw || {};

ezw.load = function(){
  /*
  ezw.self.file = $('meta[name="self"]')[0].content;
  if (ezw.self.file.match(/\.\w+$/)) {
    ezw.self.base = ezw.self.file.replace(/\.\w+$/, "");
  } else {
    ezw.self.base = ezw.self.file;
  }
  */
  //console.log(ezw.self);
  $('head').append('<link rel="stylesheet" type="text/css" href="/easy-writer/style.css">');
  $.get("easy-writer/menu.php")
  .done(function(response){
    $('body').append(response);
    ezw.initialize();
  });
}

/**
 * @namespace
 * @property {string} file - The full file name of the page to be edited.
 * @property {string} base - The file name without it's type extension.
 */
/*
ezw.self = {
  file: null,
  base: null
}*/

/**
 * Initialize.
 * @function
 */
ezw.initialize = function(){
  ezw.bindControls();
  ezw.menu.show('off');
};

/**
 * Bind appropriate actions to keypress and mouseclick events.
 * @function
 */
ezw.bindControls = function(){
  $('body').keydown(ezw.keyboard);
  //$('.ez-writable').on('focus', function(e){
  //  console.log(e);
  //});
  $('[data-ezw-action="menu-idle"]').on('click', function(){ezw.menu.show("idle")});
  $('[data-ezw-action="menu-start"]').on('click', function(){if(ezw.editing.state){ezw.menu.show("start")}else{ezw.editing.on()}});
  $('[data-ezw-action="menu-file"]').on('click', function(){ezw.menu.show("file")});
  $('[data-ezw-action="menu-add"]').on('click', function(){ezw.menu.show("add")});
  $('[data-ezw-action="menu-h"]').on('click', function(){ezw.menu.show("h")});

  $('[data-ezw-action="edit-on"]').on('click', function(){ezw.editing.on();ezw.menu.show('idle');});
  $('[data-ezw-action="edit-off"]').on('click', function(){ezw.editing.off();ezw.menu.show('off');});

  $('[data-ezw-action="file-save"]').on('click', function(){ezw.file.save();ezw.menu.show('idle');});

  $('[data-ezw-action="add-p"]').on('click', function(){ezw.addSection('p');ezw.menu.show('idle');});
  $('[data-ezw-action="add-h1"]').on('click', function(){ezw.addSection('h1');ezw.menu.show('idle');});
  $('[data-ezw-action="add-h2"]').on('click', function(){ezw.addSection('h2');ezw.menu.show('idle');});
  $('[data-ezw-action="add-h3"]').on('click', function(){ezw.addSection('h3');ezw.menu.show('idle');});
  $('[data-ezw-action="add-h4"]').on('click', function(){ezw.addSection('h4');ezw.menu.show('idle');});
  $('[data-ezw-action="add-h5"]').on('click', function(){ezw.addSection('h5');ezw.menu.show('idle');});
  $('[data-ezw-action="add-h6"]').on('click', function(){ezw.addSection('h6');ezw.menu.show('idle');});
}

ezw.keyboard = function(e){
  //console.log(e.keyCode);

  // Escape Key //
  if (e.keyCode == 27) {
    if (ezw.menu.active) {
      ezw.menu.active = false;
      ezw.menu.activate('idle');
    } else {
      ezw.menu.active = true;
      ezw.menu.activate('start');
    }

  // Return Key //
  } else if (e.keyCode == 13) {
    e.preventDefault();
    var ne = ezw.addSection({
      tag: 'p',
      insert: 'after',
      element: $(':focus')[0]
    });

  // Alpha Keys when Menu Active //
  } else if ( ezw.menu.active && ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 65 && e.keyCode <= 90)) && !(e.altKey || e.ctrlKey || e.metaKey) ) {
    e.preventDefault();
    ezw.menu.key( String.fromCharCode( e.keyCode ) );
  }
};

/**
 * Quickly navigate the menu with the keyboard.
 * @function
 */
ezw.menu = {
  active: false,
  show: function( menu ){
    $('.ezw-menu').hide();
    $('#ezw-menu-' + menu).show();
  }
}

/**
 * Add a new section to the end of the document.
 * @function
 */
ezw.addSection = function( opts ){
  console.log( opts );
  if (typeof opts === 'string') {
    opts = {tag: opts};
  }
  if (!opts.element) opts.element = '.easy-writer:last';
  if (!opts.insert) opts.insert = 'append';
  console.log( opts );
  var newElement = $('<' + opts.tag + ' contenteditable="true">' + opts.tag + '</' + opts.tag + '>');
  console.log( newElement );
  $(opts.element)[opts.insert](newElement);
  newElement.focus();
  ezw.menu.reset();
  return newElement;
}

/**
 * Activate all elements with the class "ez-writable" as "contentEditable".
 * @function
 */
ezw.editing = {
  state: false,
  on: function(){
    $('.easy-writer *')
    .attr("contentEditable", true)
    .on('focus', function(){
      console.log("Editing:");
      console.log(this);
      var $this = $(this);
      var geometry = $this.offset();
      geometry.width = $this.outerWidth();
      geometry.height = $this.outerHeight();
      console.log(geometry);
    });
    this.state = true;
  },
  off: function(){
    $('.easy-writer *')
    .attr("contentEditable", false)
    .off('click');
    this.state = false;
  }
}

ezw.file = {
  save: function(){
    var data = {containers: []};
    console.log("Saving...");
    $('.easy-writer').each(function(){
      $this = $(this);
      console.log( $this );
      console.log( $this.data('ezw-file') );
      data.containers.push({
        file: $this.data('ezw-file'),
        content: $this.html()
      });
    });
    console.log( data );
    $.post("easy-writer/save.php", data)
    .done(function(response){
      console.log( response );
    });
  }
};

})();


text:
package cloudtags

import (
	"context"
)

type Interface interface {
	// Get Labels from cluster API object
	GetTagsByCluster(ctx context.Context, clusterID string) (map[string]string, error)
}

redpajama_set_name: RedPajamaGithub


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

<title>Main</title>
<meta name="date" content="2015-06-04">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

main

Class Main

java.lang.Object

org.newdawn.slick.state.StateBasedGame

main.Main

All Implemented Interfaces:

org.newdawn.slick.ControlledInputReciever, org.newdawn.slick.ControllerListener, org.newdawn.slick.Game, org.newdawn.slick.InputListener, org.newdawn.slick.KeyListener, org.newdawn.slick.MouseListener

public class Main
extends org.newdawn.slick.state.StateBasedGame

Main method

Author:

Bradley

Field Summary

Fields

Modifier and Type
Field and Description

static int
end

static int
FPS

static java.lang.String
gamename

static int
menu

static int
reader

Constructor Summary

Constructors

Constructor and Description

Main(java.lang.String gamename)

Will add 3 states, the menu, the book, and the end

Method Summary

All Methods Static Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
initStatesList(org.newdawn.slick.GameContainer gc)

Starts up the listed states init method

static void
main(java.lang.String[] args)

Creates and App Game Container which creates the window and set the first state

Methods inherited from class org.newdawn.slick.state.StateBasedGame

addState, closeRequested, controllerButtonPressed, controllerButtonReleased, controllerDownPressed, controllerDownReleased, controllerLeftPressed, controllerLeftReleased, controllerRightPressed, controllerRightReleased, controllerUpPressed, controllerUpReleased, enterState, enterState, getContainer, getCurrentState, getCurrentStateID, getState, getStateCount, getTitle, init, inputEnded, inputStarted, isAcceptingInput, keyPressed, keyReleased, mouseClicked, mouseDragged, mouseMoved, mousePressed, mouseReleased, mouseWheelMoved, render, setInput, update

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

gamename

public static final java.lang.String gamename

See Also:

Constant Field Values

menu

public static final int menu

See Also:

Constant Field Values

reader

public static final int reader

See Also:

Constant Field Values

end

public static final int end

See Also:

Constant Field Values

FPS

public static final int FPS

See Also:

Constant Field Values

Constructor Detail

Main

public Main(java.lang.String gamename)

Will add 3 states, the menu, the book, and the end

Parameters:

gamename - - Name of window

Method Detail

initStatesList

public void initStatesList(org.newdawn.slick.GameContainer gc)
                    throws org.newdawn.slick.SlickException

Starts up the listed states init method

Specified by:

initStatesList in class org.newdawn.slick.state.StateBasedGame

Throws:

org.newdawn.slick.SlickException

main

public static void main(java.lang.String[] args)

Creates and App Game Container which creates the window and set the first state

Parameters:

args - - Command line arguments

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
"""
A new reader class is created by creating a new-style class that has
the following methods:

  def get_intervals(self) -> returns: IntervalSet
  def fetch(self, startTime, endTime) -> returns: list of results

"""

import os
import time
from graphite.node import LeafNode, BranchNode
from graphite.intervals import Interval, IntervalSet
from graphite.carbonlink import CarbonLink
from graphite.logger import log
from django.conf import settings

try:
  import whisper
except ImportError:
  whisper = False

try:
  import rrdtool
except ImportError:
  rrdtool = False

try:
  import gzip
except ImportError:
  gzip = False

try:
  import pyKairosDB
  from pyKairosDB import graphite as pyk_graphite
  kairos=True
except ImportError:
  kairos = False

class FetchInProgress(object):
  def __init__(self, wait_callback):
    self.wait_callback = wait_callback

  def waitForResults(self):
    return self.wait_callback()

class MultiReader(object):
  __slots__ = ('nodes',)

  def __init__(self, nodes):
    self.nodes = nodes

  def get_intervals(self):
    interval_sets = []
    for node in self.nodes:
      interval_sets.extend( node.intervals.intervals )
    return IntervalSet( sorted(interval_sets) )

  def fetch(self, startTime, endTime):
    # Start the fetch on each node
    results = [ n.fetch(startTime, endTime) for n in self.nodes ]

    # Wait for any asynchronous operations to complete
    for i, result in enumerate(results):
      if isinstance(result, FetchInProgress):
        try:
          results[i] = result.waitForResults()
        except:
          log.exception("Failed to complete subfetch")
          results[i] = None

    results = [r for r in results if r is not None]
    if not results:
      raise Exception("All sub-fetches failed")

    return reduce(self.merge, results)

  def merge(self, results1, results2):
    # Ensure results1 is finer than results2
    if results1[0][2] > results2[0][2]:
      results1, results2 = results2, results1

    time_info1, values1 = results1
    time_info2, values2 = results2
    start1, end1, step1 = time_info1
    start2, end2, step2 = time_info2

    step   = step1                # finest step
    start  = min(start1, start2)  # earliest start
    end    = max(end1, end2)      # latest end
    time_info = (start, end, step)
    values = []

    t = start
    while t < end:
      # Look for the finer precision value first if available
      i1 = (t - start1) / step1

      if len(values1) > i1:
        v1 = values1[i1]
      else:
        v1 = None

      if v1 is None:
        i2 = (t - start2) / step2

        if len(values2) > i2:
          v2 = values2[i2]
        else:
          v2 = None

        values.append(v2)
      else:
        values.append(v1)

      t += step

    return (time_info, values)

class CeresReader(object):
  __slots__ = ('ceres_node', 'real_metric_path')
  supported = True

  def __init__(self, ceres_node, real_metric_path):
    self.ceres_node = ceres_node
    self.real_metric_path = real_metric_path

  def get_intervals(self):
    intervals = []
    for info in self.ceres_node.slice_info:
      (start, end, step) = info
      intervals.append( Interval(start, end) )

    return IntervalSet(intervals)

  def fetch(self, startTime, endTime):
    data = self.ceres_node.read(startTime, endTime)
    time_info = (data.startTime, data.endTime, data.timeStep)
    values = list(data.values)

    # Merge in data from carbon's cache
    try:
      cached_datapoints = CarbonLink.query(self.real_metric_path)
    except:
      log.exception("Failed CarbonLink query '%s'" % self.real_metric_path)
      cached_datapoints = []

    for (timestamp, value) in cached_datapoints:
      interval = timestamp - (timestamp % data.timeStep)

      try:
        i = int(interval - data.startTime) / data.timeStep
        values[i] = value
      except:
        pass

    return (time_info, values)

class KairosDBReader(object):
  __slots__ = ('server', 'port', 'conn', 'metric_path')
  supported = bool(kairos)

  def __init__(self, kairosdb_connection, metric_path):
    """
    :type kairosdb_connection: pyKairosDB.connection
    :param kairosdb_connection: This is a connection to the KairosDB serer

    :type metric_path: str
    :param metric_path: A string describing the metric name whose values are being sought
    """
    self.conn        = kairosdb_connection
    self.metric_path = metric_path

  def get_intervals(self):
    """What are intervals, exactly?

    What I currently understand [that is, me, pcn] is that
    get_intervals returns a set (or rather, an IntervalSet) that
    contains Interval objects.  Each Interval is a start and end time.
    When a request is finally made, it should be done by combining any
    overlapping time ranges (intervals), and then issuing a request
    for each range of times and those will be the stats.  I don't get
    whether they're important here, though.

    The start and end time appears to be normally generated by
    querying metadata about the metric(s) in question.  For instance,
    the whisper and rrd readers seem to be directly accessing
    properties of the respective databases files (st_mtime) to construct a period that
    runs from now, to the oldest possible retained value in the file
    store for this particular metric.

    It seems, then, that it's acceptable to wait a moment here while we
    go off to the server and get the oldest datapoint for a particular
    metric, so I have to figure out what query options I have to
    satisfy this.

    """
    intervals = []

    # Interval finding is waiting on https://code.google.com/p/kairosdb/issues/detail?id=12
    # For now, use a bogus interval - it doesn't seem to be that important as long as there is one?
    # That's right, this is an internal detail to ceres, and outside of ceres nothing else should
    # care about it.
    intervals.append(Interval(time.time()-3600, time.time()))
    return IntervalSet(intervals)

  def fetch(self, startTime, endTime):
    """
    :type startTime: float
    :param startTime: The time in seconds since the unix epoch that we want to start fetching metrics

    :type endTime: float
    :param endTime: The time in seconds since the unix epoch that we want bound our fetch at

    :rtype: tuple
    :return: A tuple of (time_info, values).  Time_info is a tuple of (start, end, interval)
             where interval is seconds between metrics.  Values is a list of floats which are
             the values to be graphed.

    This will get called for each range.  This seems sub-optimal
    since KariosDB can satisfy multiple query ranges in one
    request, but that can come later.

    This is called from datalib.fetchData() via LeafNode
    """
    return pyk_graphite.read_absolute(self.conn, self.metric_path, startTime, endTime)

class WhisperReader(object):
  __slots__ = ('fs_path', 'real_metric_path')
  supported = bool(whisper)

  def __init__(self, fs_path, real_metric_path):
    self.fs_path = fs_path
    self.real_metric_path = real_metric_path

  def get_intervals(self):
    start = time.time() - whisper.info(self.fs_path)['maxRetention']
    end = max( os.stat(self.fs_path).st_mtime, start )
    return IntervalSet( [Interval(start, end)] )

  def fetch(self, startTime, endTime):
    data = whisper.fetch(self.fs_path, startTime, endTime)
    if not data:
      return None

    time_info, values = data
    (start,end,step) = time_info

    # Merge in data from carbon's cache
    try:
      cached_datapoints = CarbonLink.query(self.real_metric_path)
    except:
      log.exception("Failed CarbonLink query '%s'" % self.real_metric_path)
      cached_datapoints = []

    for (timestamp, value) in cached_datapoints:
      interval = timestamp - (timestamp % step)

      try:
        i = int(interval - start) / step
        values[i] = value
      except:
        pass

    return (time_info, values)

class GzippedWhisperReader(WhisperReader):
  supported = bool(whisper and gzip)

  def get_intervals(self):
    fh = gzip.GzipFile(self.fs_path, 'rb')
    try:
      info = whisper.__readHeader(fh) # evil, but necessary.
    finally:
      fh.close()

    start = time.time() - info['maxRetention']
    end = max( os.stat(self.fs_path).st_mtime, start )
    return IntervalSet( [Interval(start, end)] )

  def fetch(self, startTime, endTime):
    fh = gzip.GzipFile(self.fs_path, 'rb')
    try:
      return whisper.file_fetch(fh, startTime, endTime)
    finally:
      fh.close()

class RRDReader:
  supported = bool(rrdtool)

  def __init__(self, fs_path, datasource_name):
    self.fs_path = fs_path
    self.datasource_name = datasource_name

  def get_intervals(self):
    start = time.time() - self.get_retention(self.fs_path)
    end = max( os.stat(self.fs_path).st_mtime, start )
    return IntervalSet( [Interval(start, end)] )

  def fetch(self, startTime, endTime):
    startString = time.strftime("%H:%M_%Y%m%d+%Ss", time.localtime(startTime))
    endString = time.strftime("%H:%M_%Y%m%d+%Ss", time.localtime(endTime))

    if settings.FLUSHRRDCACHED:
      rrdtool.flushcached(self.fs_path, '--daemon', settings.FLUSHRRDCACHED)

    (timeInfo, columns, rows) = rrdtool.fetch(self.fs_path,'AVERAGE','-s' + startString,'-e' + endString)
    colIndex = list(columns).index(self.datasource_name)
    rows.pop() #chop off the latest value because RRD returns crazy last values sometimes
    values = (row[colIndex] for row in rows)

    return (timeInfo, values)

  @staticmethod
  def get_datasources(fs_path):
    info = rrdtool.info(fs_path)

    if 'ds' in info:
      return [datasource_name for datasource_name in info['ds']]
    else:
      ds_keys = [ key for key in info if key.startswith('ds[') ]
      datasources = set( key[3:].split(']')[0] for key in ds_keys )
      return list(datasources)

  @staticmethod
  def get_retention(fs_path):
    info = rrdtool.info(fs_path)
    if 'rra' in info:
      rras = info['rra']
    else:
      # Ugh, I like the old python-rrdtool api better..
      rra_count = max([ int(key[4]) for key in info if key.startswith('rra[') ]) + 1
      rras = [{}] * rra_count
      for i in range(rra_count):
        rras[i]['pdp_per_row'] = info['rra[%d].pdp_per_row' % i]
        rras[i]['rows'] = info['rra[%d].rows' % i]

    retention_points = 0
    for rra in rras:
      points = rra['pdp_per_row'] * rra['rows']
      if points > retention_points:
        retention_points = points

    return  retention_points * info['step']


text:
  Vinkel Demo App

        Home
        Notification
        Progress Bar
        Drop Zone

      <router-outlet></router-outlet>


text:
var timeout;

Template.idea.rendered = function () {
	var self = this;
	var $idea = this.$(self.firstNode);
	var index = $idea.index();
	Meteor.setTimeout(function () {
		$idea.addClass("rendered");
	}, 15 + (10 * index));
};

Template.idea.events({
	"click .check": function (evt, template) {
		var self = this;
		var $check = template.$("[name='check']");
		var checked = !template.data.checked;

		Ideas.update({_id: template.data._id}, {$set: {checked: checked}});

		Meteor.clearTimeout(self.tooltipTimeout);

		if (checked) {
			$check.tooltip("show");
			self.tooltipTimeout = Meteor.setTimeout(function () {
				$check.tooltip("hide");
			}, 3000);
		} else {
			$check.tooltip("hide");
		}
	},
	"keyup [name='text']": function (evt, template) {
		var $text = template.$(evt.target);
		var value = $text.val();
		var checked = template.data.checked;
		var delay = 0;

		if (value === template.data.text) return;

		if (evt.keyCode === 13) delay = 500;
		if (checked) delay = 750;

		var func = function () {
			Ideas.update({_id: template.data._id}, {$set: {text: value}});
		};

		Meteor.clearTimeout(timeout);
		timeout = Meteor.setTimeout(function () {
			if (checked) {
				confirm("Someone has expressed interest in getting this. Are you sure you want to change the text?", function (result) {
					if (result) return func();
					$text.val(template.data.text);
				});
			} else {
				func();
			}
		}, delay);
	},
	"click [name='del']": function (evt, template) {
		var func = function () {
			var $check = template.$("[name='check']");
			$check.tooltip("hide");

			Ideas.remove({_id: template.data._id});
		};

		if (template.data.checked) {
			confirm("Are you sure you want to remove this gift idea? Someone has expressed interest in getting it.", function (result) {
				result && func();
			});
		} else {
			func();
		}
	}
});


text:
using content::BrowserThread;

namespace chromeos {

namespace {

// Default volume as a percentage in the range [0.0, 100.0].
const double kDefaultVolumePercent = 75.0;

// Number of seconds that we'll sleep between each connection attempt.
const int kConnectionRetrySleepSec = 1;

}  // namespace

AudioMixerCras::AudioMixerCras()
    : client_(NULL),
      client_connected_(false),
      volume_percent_(kDefaultVolumePercent),
      is_muted_(false),
      is_mute_locked_(false),
      is_capture_muted_(false),
      is_capture_mute_locked_(false),
      apply_is_pending_(true) {
}

AudioMixerCras::~AudioMixerCras() {
  if (!thread_.get())
    return;
  DCHECK(MessageLoop::current() != thread_->message_loop());

  base::ThreadRestrictions::ScopedAllowIO allow_io_for_thread_join;
  thread_->Stop();
  thread_.reset();

  cras_client_destroy(client_);
}

void AudioMixerCras::Init() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!thread_.get()) << "Init() called twice";

  thread_.reset(new base::Thread("AudioMixerCras"));
  CHECK(thread_->Start());
  thread_->message_loop()->PostTask(
      FROM_HERE, base::Bind(&AudioMixerCras::Connect, base::Unretained(this)));
}

double AudioMixerCras::GetVolumePercent() {
  base::AutoLock lock(lock_);
  return volume_percent_;
}

void AudioMixerCras::SetVolumePercent(double percent) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (isnan(percent))
    percent = 0.0;
  percent = std::max(std::min(percent, 100.0), 0.0);

  base::AutoLock lock(lock_);
  volume_percent_ = percent;
  if (client_connected_ && !apply_is_pending_)
    thread_->message_loop()->PostTask(FROM_HERE,
        base::Bind(&AudioMixerCras::ApplyState, base::Unretained(this)));
}

bool AudioMixerCras::IsMuted() {
  base::AutoLock lock(lock_);
  return is_muted_;
}

void AudioMixerCras::SetMuted(bool mute) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  base::AutoLock lock(lock_);
  if (is_mute_locked_) {
    NOTREACHED() << "Mute has been locked!";
    return;
  }
  is_muted_ = mute;
  ApplyStateIfNeeded();
}

bool AudioMixerCras::IsMuteLocked() {
  base::AutoLock lock(lock_);
  return is_mute_locked_;
}

void AudioMixerCras::SetMuteLocked(bool locked) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  base::AutoLock lock(lock_);
  is_mute_locked_ = locked;
  ApplyStateIfNeeded();
}

bool AudioMixerCras::IsCaptureMuted() {
  base::AutoLock lock(lock_);
  return is_capture_muted_;
}

void AudioMixerCras::SetCaptureMuted(bool mute) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  base::AutoLock lock(lock_);
  if (is_capture_mute_locked_) {
    NOTREACHED() << "Capture mute has been locked!";
    return;
  }
  is_capture_muted_ = mute;
  ApplyStateIfNeeded();
}

bool AudioMixerCras::IsCaptureMuteLocked() {
  base::AutoLock lock(lock_);
  return is_capture_mute_locked_;
}

void AudioMixerCras::SetCaptureMuteLocked(bool locked) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  base::AutoLock lock(lock_);
  is_capture_mute_locked_ = locked;
  ApplyStateIfNeeded();
}

void AudioMixerCras::Connect() {
  DCHECK(MessageLoop::current() == thread_->message_loop());

  // Create the client structure.
  if (client_ == NULL && cras_client_create(&client_) < 0) {
    LOG(DFATAL) << "cras_client_create() failed";
    return; // TODO(dgreid) change interface so this can return an error.
  }

  if (cras_client_connect(client_) != 0) {
    thread_->message_loop()->PostDelayedTask(FROM_HERE,
        base::Bind(&AudioMixerCras::Connect, base::Unretained(this)),
        base::TimeDelta::FromSeconds(kConnectionRetrySleepSec));
    return;
  }
  client_connected_ = true;

  // The speech synthesis service shouldn't be initialized until after
  // we get to this point, so we call this function to tell it that it's
  // safe to do TTS now.  NotificationService would be cleaner,
  // but it's not available at this point.
  EnableChromeOsTts();

  ApplyState();
}

void AudioMixerCras::ApplyState() {
  DCHECK(MessageLoop::current() == thread_->message_loop());
  if (!client_connected_)
    return;

  bool should_mute = false;
  bool should_lock_mute = false;
  bool should_mute_capture = false;
  bool should_lock_capture_mute = false;
  size_t new_volume = 0;
  {
    base::AutoLock lock(lock_);
    should_mute = is_muted_;
    should_lock_mute = is_mute_locked_;
    should_mute_capture = is_capture_muted_;
    should_lock_capture_mute = is_capture_mute_locked_;
    new_volume = floor(volume_percent_ + 0.5);
    apply_is_pending_ = false;
  }

  // If muting mute before setting volume, if un-muting set volume first.
  if (should_mute) {
    cras_client_set_system_mute(client_, should_mute);
    cras_client_set_system_volume(client_, new_volume);
  } else {
    cras_client_set_system_volume(client_, new_volume);
    cras_client_set_system_mute(client_, should_mute);
  }
  cras_client_set_system_mute_locked(client_, should_lock_mute);
  cras_client_set_system_capture_mute(client_, should_mute_capture);
  cras_client_set_system_capture_mute_locked(client_, should_lock_capture_mute);
}

void AudioMixerCras::ApplyStateIfNeeded() {
  lock_.AssertAcquired();
  if (client_connected_ && !apply_is_pending_) {
    thread_->message_loop()->PostTask(
        FROM_HERE,
        base::Bind(&AudioMixerCras::ApplyState, base::Unretained(this)));
  }
}

}  // namespace chromeos


text:
Homebrew, like Git, supports *external commands*. This lets you create new commands that can be run like:

```shell
$ brew mycommand --option1 --option3 formula
```

without modifying Homebrew's internals.

## COMMAND TYPES
External commands come in two flavors: Ruby commands and shell scripts.

In both cases, the command file should be executable (`chmod +x`) and live somewhere in `$PATH`.

### RUBY COMMANDS
An external command `extcmd` implemented as a Ruby command should be named `brew-extcmd.rb`. The command is executed by doing a `require` on the full pathname. As the command is `require`d, it has full access to the Homebrew "environment", i.e. all global variables and modules that any internal command has access to.

The command may `Kernel.exit` with a status code if it needs to; if it doesn't explicitly exit then Homebrew will return 0.

### SHELL SCRIPTS
A shell script for an command named `extcmd` should be named `brew-extcmd`. This file will be run via `exec` with some Homebrew variables set as environmental variables, and passed any additional command-line arguments.

    Variable
    Description

    HOMEBREW_CACHE
		Where Homebrew caches downloaded tarballs to, typically /Library/Caches/Homebrew.

    HOMEBREW_CELLAR
		The location of the Homebrew Cellar, where software is staged. This will be $HOMEBREW_PREFIX/Cellar if that directory exists, or $HOMEBREW_REPOSITORY/Cellar otherwise.

    HOMEBREW_LIBRARY_PATH
		The directory containing Homebrew's own application code.

    HOMEBREW_PREFIX
		Where Homebrew installs software. This is always the grandparent directory of the `brew` executable, /usr/local by default.

    HOMEBREW_REPOSITORY
		If installed from a Git clone, the repo directory (i.e., where Homebrew's .git directory lives).

Note that the script itself can use any suitable shebang (`#!`) line, so an external "shell script" can be written for sh, bash, Ruby, or anything else.

## USER-SUBMITTED COMMANDS
These commands have been contributed by Homebrew users but are not included in the main Homebrew repository, nor are they installed by the installer script. You can install them manually, as outlined above.

>*NOTE:* They are largely untested, and as always, be careful about running untested code on your machine.

### brew-livecheck
> Check if there is a new upstream version of a formula.
>
> See the [`README`](https://github.com/youtux/homebrew-livecheck/blob/master/README.md) for more info and usage.
>
> Install using:
> ```
> $ brew tap youtux/livecheck
> ```

### brew-cask

>Install .app and other "Drag to install" packages from Homebrew.
>
> https://github.com/caskroom/homebrew-cask
>
> Install using:
> ```
  $ brew tap caskroom/cask
> ```

### brew-gem
>Install any gem package into a self-contained Homebrew cellar location: <https://github.com/sportngin/brew-gem>
>
>*Note:* This can also be installed with `brew install brew-gem`.

### brew-growl
>Get Growl notifications for Homebrew https://github.com/secondplanet/brew-growl

### brew-more
>Scrapes a formula's homepage to get more information: [https://gist.github.com/475200](https://gist.github.com/475200)

### brew-services
>Simple support to start formulae using launchctl, has out of the box support for any formula which defines `startup_plist` (e.g. mysql, postgres, redis u.v.m.): [https://github.com/gapple/homebrew-services](https://github.com/gapple/homebrew-services)

> Install using:
> ```
  $ brew tap gapple/services
> ```

## SEE ALSO
Homebrew Docs: <https://github.com/Homebrew/brew/tree/master/share/doc/homebrew>


text:
package org.apache.asterix.common.ioopcallbacks;

import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.storage.am.btree.impls.BTree;
import org.apache.hyracks.storage.am.common.api.IMetadataPageManager;
import org.apache.hyracks.storage.am.lsm.btree.impls.LSMBTreeFileManager;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMComponentIdGenerator;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMDiskComponent;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIndex;

public class LSMBTreeIOOperationCallback extends AbstractLSMIOOperationCallback {

    public LSMBTreeIOOperationCallback(ILSMIndex index, ILSMComponentIdGenerator idGenerator) {
        super(index, idGenerator);
    }

    @Override
    public long getComponentFileLSNOffset(ILSMDiskComponent diskComponent, String diskComponentFilePath)
            throws HyracksDataException {
        if (diskComponentFilePath.endsWith(LSMBTreeFileManager.BTREE_SUFFIX)) {
            IMetadataPageManager metadataPageManager =
                    (IMetadataPageManager) ((BTree) diskComponent.getIndex()).getPageManager();
            return metadataPageManager.getFileOffset(metadataPageManager.createMetadataFrame(), LSN_KEY);
        }
        return INVALID;
    }
}


text:
package com.trickl.crawler.parser.html;

import java.io.InputStream;
import org.apache.droids.exception.DroidsException;
import org.w3c.dom.Document;

public interface DocumentBuilder {
    Document build(InputStream stream) throws DroidsException;
}


text:
@interface OLPresenter()<OLMVPViewDelegate>
{

}
@end

@implementation OLPresenter
- (void)printJobStart {
    [self.mvpView printOnView:self.mvpModel.content];
}

- (void)printButtonClick {
    NSInteger lineNumber = arc4random()%10+1;
    self.mvpModel.content = [NSString stringWithFormat:@"line %ld", lineNumber];
    [self.mvpView printOnView:self.mvpModel.content];
}

@end


text:
package org.springframework.boot.autoconfigure.security;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.List;

import javax.servlet.Filter;

import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration;
import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration;
import org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration;
import org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration;
import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration;
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.WebApplicationContext;

import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;

/**
 * Tests for {@link SpringBootWebSecurityConfiguration}.
 *
 * @author Dave Syer
 * @author Rob Winch
 * @author Andy Wilkinson
 */
public class SpringBootWebSecurityConfigurationTests {

	private ConfigurableApplicationContext context;

	@After
	public void close() {
		if (this.context != null) {
			this.context.close();
		}
	}

	@Test
	public void testDefaultIgnores() {
		List<String> ignored = SpringBootWebSecurityConfiguration
				.getIgnored(new SecurityProperties());
		assertThat(ignored).contains("/css/**");
	}

	@Test
	public void testWebConfigurationOverrideGlobalAuthentication() throws Exception {
		this.context = SpringApplication.run(TestWebConfiguration.class,
				"--server.port=0");
		assertThat(this.context.getBean(AuthenticationManagerBuilder.class)).isNotNull();
		assertThat(this.context.getBean(AuthenticationManager.class)
				.authenticate(new UsernamePasswordAuthenticationToken("dave", "secret")))
						.isNotNull();
	}

	@Test
	public void testWebConfigurationFilterChainUnauthenticated() throws Exception {
		this.context = SpringApplication.run(VanillaWebConfiguration.class,
				"--server.port=0");
		MockMvc mockMvc = MockMvcBuilders
				.webAppContextSetup((WebApplicationContext) this.context)
				.addFilters(
						this.context.getBean("springSecurityFilterChain", Filter.class))
				.build();
		mockMvc.perform(MockMvcRequestBuilders.get("/"))
				.andExpect(MockMvcResultMatchers.status().isUnauthorized())
				.andExpect(MockMvcResultMatchers.header().string("www-authenticate",
						Matchers.containsString("realm=\"Spring\"")));
	}

	@Test
	public void testWebConfigurationFilterChainUnauthenticatedWithAuthorizeModeNone()
			throws Exception {
		this.context = SpringApplication.run(VanillaWebConfiguration.class,
				"--server.port=0", "--security.basic.authorize-mode=none");
		MockMvc mockMvc = MockMvcBuilders
				.webAppContextSetup((WebApplicationContext) this.context)
				.addFilters(
						this.context.getBean("springSecurityFilterChain", Filter.class))
				.build();
		mockMvc.perform(MockMvcRequestBuilders.get("/"))
				.andExpect(MockMvcResultMatchers.status().isNotFound());
	}

	@Test
	public void testWebConfigurationFilterChainUnauthenticatedWithAuthorizeModeAuthenticated()
			throws Exception {
		this.context = SpringApplication.run(VanillaWebConfiguration.class,
				"--server.port=0", "--security.basic.authorize-mode=authenticated");
		MockMvc mockMvc = MockMvcBuilders
				.webAppContextSetup((WebApplicationContext) this.context)
				.addFilters(
						this.context.getBean("springSecurityFilterChain", Filter.class))
				.build();
		mockMvc.perform(MockMvcRequestBuilders.get("/"))
				.andExpect(MockMvcResultMatchers.status().isUnauthorized())
				.andExpect(MockMvcResultMatchers.header().string("www-authenticate",
						Matchers.containsString("realm=\"Spring\"")));
	}

	@Test
	public void testWebConfigurationFilterChainBadCredentials() throws Exception {
		this.context = SpringApplication.run(VanillaWebConfiguration.class,
				"--server.port=0");
		MockMvc mockMvc = MockMvcBuilders
				.webAppContextSetup((WebApplicationContext) this.context)
				.addFilters(
						this.context.getBean("springSecurityFilterChain", Filter.class))
				.build();
		mockMvc.perform(
				MockMvcRequestBuilders.get("/").header("authorization", "Basic xxx"))
				.andExpect(MockMvcResultMatchers.status().isUnauthorized())
				.andExpect(MockMvcResultMatchers.header().string("www-authenticate",
						Matchers.containsString("realm=\"Spring\"")));
	}

	@Test
	public void testWebConfigurationInjectGlobalAuthentication() throws Exception {
		this.context = SpringApplication.run(TestInjectWebConfiguration.class,
				"--server.port=0");
		assertThat(this.context.getBean(AuthenticationManagerBuilder.class)).isNotNull();
		assertThat(this.context.getBean(AuthenticationManager.class)
				.authenticate(new UsernamePasswordAuthenticationToken("dave", "secret")))
						.isNotNull();
	}

	// gh-3447
	@Test
	public void testHiddenHttpMethodFilterOrderedFirst() throws Exception {
		this.context = SpringApplication.run(DenyPostRequestConfig.class,
				"--server.port=0");
		int port = Integer
				.parseInt(this.context.getEnvironment().getProperty("local.server.port"));
		TestRestTemplate rest = new TestRestTemplate();

		// not overriding causes forbidden
		MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();

		ResponseEntity<Object> result = rest
				.postForEntity("http://localhost:" + port + "/", form, Object.class);
		assertThat(result.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);

		// override method with GET
		form = new LinkedMultiValueMap<String, String>();
		form.add("_method", "GET");

		result = rest.postForEntity("http://localhost:" + port + "/", form, Object.class);
		assertThat(result.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
	}

	@Test
	public void defaultHeaderConfiguration() throws Exception {
		this.context = SpringApplication.run(VanillaWebConfiguration.class,
				"--server.port=0");
		MockMvc mockMvc = MockMvcBuilders
				.webAppContextSetup((WebApplicationContext) this.context)
				.addFilters((FilterChainProxy) this.context
						.getBean("springSecurityFilterChain", Filter.class))
				.build();
		mockMvc.perform(MockMvcRequestBuilders.get("/"))
				.andExpect(MockMvcResultMatchers.header().string("X-Content-Type-Options",
						is(notNullValue())))
				.andExpect(MockMvcResultMatchers.header().string("X-XSS-Protection",
						is(notNullValue())))
				.andExpect(MockMvcResultMatchers.header().string("Cache-Control",
						is(notNullValue())))
				.andExpect(MockMvcResultMatchers.header().string("X-Frame-Options",
						is(notNullValue())))
				.andExpect(MockMvcResultMatchers.header()
						.doesNotExist("Content-Security-Policy"));
	}

	@Test
	public void securityHeadersCanBeDisabled() throws Exception {
		this.context = SpringApplication.run(VanillaWebConfiguration.class,
				"--server.port=0", "--security.headers.content-type=false",
				"--security.headers.xss=false", "--security.headers.cache=false",
				"--security.headers.frame=false");

		MockMvc mockMvc = MockMvcBuilders
				.webAppContextSetup((WebApplicationContext) this.context)
				.addFilters(
						this.context.getBean("springSecurityFilterChain", Filter.class))
				.build();
		mockMvc.perform(MockMvcRequestBuilders.get("/"))
				.andExpect(MockMvcResultMatchers.status().isUnauthorized())
				.andExpect(MockMvcResultMatchers.header()
						.doesNotExist("X-Content-Type-Options"))
				.andExpect(
						MockMvcResultMatchers.header().doesNotExist("X-XSS-Protection"))
				.andExpect(MockMvcResultMatchers.header().doesNotExist("Cache-Control"))
				.andExpect(
						MockMvcResultMatchers.header().doesNotExist("X-Frame-Options"));
	}

	@Test
	public void contentSecurityPolicyConfiguration() throws Exception {
		this.context = SpringApplication.run(VanillaWebConfiguration.class,
				"--security.headers.content-security-policy=default-src 'self';");
		MockMvc mockMvc = MockMvcBuilders
				.webAppContextSetup((WebApplicationContext) this.context)
				.addFilters((FilterChainProxy) this.context
						.getBean("springSecurityFilterChain", Filter.class))
				.build();
		mockMvc.perform(MockMvcRequestBuilders.get("/"))
				.andExpect(MockMvcResultMatchers.header()
						.string("Content-Security-Policy", is("default-src 'self';")))
				.andExpect(MockMvcResultMatchers.header()
						.doesNotExist("Content-Security-Policy-Report-Only"));
	}

	@Test
	public void contentSecurityPolicyReportOnlyConfiguration() throws Exception {
		this.context = SpringApplication.run(VanillaWebConfiguration.class,
				"--security.headers.content-security-policy=default-src 'self';",
				"--security.headers.content-security-policy-mode=report-only");
		MockMvc mockMvc = MockMvcBuilders
				.webAppContextSetup((WebApplicationContext) this.context)
				.addFilters((FilterChainProxy) this.context
						.getBean("springSecurityFilterChain", Filter.class))
				.build();
		mockMvc.perform(MockMvcRequestBuilders.get("/"))
				.andExpect(MockMvcResultMatchers.header().string(
						"Content-Security-Policy-Report-Only", is("default-src 'self';")))
				.andExpect(MockMvcResultMatchers.header()
						.doesNotExist("Content-Security-Policy"));
	}

	@Configuration
	@Import(TestWebConfiguration.class)
	@Order(Ordered.LOWEST_PRECEDENCE)
	protected static class TestInjectWebConfiguration
			extends WebSecurityConfigurerAdapter {

		private final AuthenticationManagerBuilder auth;

		// It's a bad idea to inject an AuthenticationManager into a
		// WebSecurityConfigurerAdapter because it can cascade early instantiation,
		// unless you explicitly want the Boot default AuthenticationManager. It's
		// better to inject the builder, if you want the global AuthenticationManager. It
		// might even be necessary to wrap the builder in a lazy AuthenticationManager
		// (that calls getOrBuild() only when the AuthenticationManager is actually
		// called).
		protected TestInjectWebConfiguration(AuthenticationManagerBuilder auth) {
			this.auth = auth;
		}

		@Override
		public void init(WebSecurity web) throws Exception {
			this.auth.getOrBuild();
		}

	}

	@MinimalWebConfiguration
	@Import(SecurityAutoConfiguration.class)
	protected static class VanillaWebConfiguration {
	}

	@MinimalWebConfiguration
	@Import(SecurityAutoConfiguration.class)
	@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
	protected static class TestWebConfiguration extends WebSecurityConfigurerAdapter {

		@Autowired
		public void init(AuthenticationManagerBuilder auth) throws Exception {
			auth.inMemoryAuthentication().withUser("dave").password("secret")
					.roles("USER");
		}

		@Override
		protected void configure(HttpSecurity http) throws Exception {
			http.authorizeRequests().anyRequest().denyAll();
		}

	}

	@Configuration
	@Target(ElementType.TYPE)
	@Retention(RetentionPolicy.RUNTIME)
	@Documented
	@Import({ EmbeddedServletContainerAutoConfiguration.class,
			ServerPropertiesAutoConfiguration.class,
			DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class,
			HttpMessageConvertersAutoConfiguration.class, ErrorMvcAutoConfiguration.class,
			PropertyPlaceholderAutoConfiguration.class })
	protected @interface MinimalWebConfiguration {

	}

	@MinimalWebConfiguration
	@Import(SecurityAutoConfiguration.class)
	protected static class DenyPostRequestConfig extends WebSecurityConfigurerAdapter {

		@Override
		protected void configure(HttpSecurity http) throws Exception {
			http.authorizeRequests().antMatchers(HttpMethod.POST, "/**").denyAll();
		}

	}

}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using FluentAssertions;
using NUnit.Framework;

namespace Shapeshifter.Tests.Unit.RoundtripTests
{
    [TestFixture]
    public class EnumConverterTests
    {
        [Test]
        public void TestEnumConverter()
        {
            var serializer = new ShapeshifterSerializer<MyClassWithEnum>(); //EnumConverter is set implicitly
            var input = new MyClassWithEnum()
            {
                EnumVal = MyEnum.Second
            };

            var wireFormat = serializer.Serialize(input);
            var result = serializer.Deserialize(wireFormat);

            result.EnumVal.Should().Be(MyEnum.Second);
        }

        [Test]
        public void TestEnumConverterIfEnumHasDataContractAttribute()
        {
            var serializer = new ShapeshifterSerializer<MyClassWithEnumAttributed>(); //EnumConverter is set implicitly
            var input = new MyClassWithEnumAttributed()
            {
                EnumVal = MyEnumAttributed.Second
            };

            var wireFormat = serializer.Serialize(input);
            var result = serializer.Deserialize(wireFormat);

            result.EnumVal.Should().Be(MyEnumAttributed.Second);
        }

        [DataContract]
        [ShapeshifterRoot]
        private class MyClassWithEnum
        {
            [DataMember]
            public MyEnum EnumVal { get; set; }
        }

        private enum MyEnum
        {
            First,
            Second
        }

        [DataContract]
        [ShapeshifterRoot]
        private class MyClassWithEnumAttributed
        {
            [DataMember]
            public MyEnumAttributed EnumVal { get; set; }
        }

        [DataContract]
        private enum MyEnumAttributed
        {
            First,
            Second
        }
    }
}


text:
// .NAME vtkXRenderWindowInteractor - an X event driven interface for a RenderWindow
// .SECTION Description
// vtkXRenderWindowInteractor is a convenience object that provides event
// bindings to common graphics functions. For example, camera and actor
// functions such as zoom-in/zoom-out, azimuth, roll, and pan. IT is one of
// the window system specific subclasses of vtkRenderWindowInteractor. Please
// see vtkRenderWindowInteractor documentation for event bindings.
//
// .SECTION see also
// vtkRenderWindowInteractor vtkXRenderWindow

// I've been though this and deleted all I think should go, tried to create
// the basic structure and if you're lucky it might even work!
// but frankly I doubt it

#ifndef vtkXRenderWindowInteractor_h
#define vtkXRenderWindowInteractor_h

//===========================================================
// now we define the C++ class

#include "vtkRenderingOpenGLModule.h" // For export macro
#include "vtkRenderWindowInteractor.h"
#include <X11/StringDefs.h> // Needed for X types in the public interface
#include <X11/Intrinsic.h> // Needed for X types in the public interface

class vtkCallbackCommand;
class vtkXRenderWindowInteractorInternals;

//BTX
// Forward declare internal friend functions.
void VTKRENDERINGOPENGL_EXPORT vtkXRenderWindowInteractorCallback(Widget,XtPointer, XEvent *,Boolean *);
void VTKRENDERINGOPENGL_EXPORT vtkXRenderWindowInteractorTimer(XtPointer,XtIntervalId *);
//ETX

class VTKRENDERINGOPENGL_EXPORT vtkXRenderWindowInteractor : public vtkRenderWindowInteractor
{
public:
  static vtkXRenderWindowInteractor *New();
  vtkTypeMacro(vtkXRenderWindowInteractor,vtkRenderWindowInteractor);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Description:
  // Initializes the event handlers without an XtAppContext.  This is
  // good for when you don't have a user interface, but you still
  // want to have mouse interaction.
  virtual void Initialize();

  // Description:
  // Break the event loop on 'q','e' keypress. Want more ???
  void TerminateApp();

  // Description:
  // The BreakLoopFlag is checked in the Start() method.
  // Setting it to anything other than zero will cause
  // the interactor loop to terminate and return to the
  // calling function.
  vtkGetMacro(BreakLoopFlag, int);
  void SetBreakLoopFlag(int);
  void BreakLoopFlagOff();
  void BreakLoopFlagOn();

  // Description:
  // Initializes the event handlers using an XtAppContext that you have
  // provided.  This assumes that you want to own the event loop.
  virtual void Initialize(XtAppContext app);
  vtkGetMacro( App, XtAppContext );

  // Description:
  // Enable/Disable interactions.  By default interactors are enabled when
  // initialized.  Initialize() must be called prior to enabling/disabling
  // interaction. These methods are used when a window/widget is being
  // shared by multiple renderers and interactors.  This allows a "modal"
  // display where one interactor is active when its data is to be displayed
  // and all other interactors associated with the widget are disabled
  // when their data is not displayed.
  virtual void Enable();
  virtual void Disable();

  // Description:
  // Update the Size data member and set the associated RenderWindow's
  // size.
  virtual void UpdateSize(int,int);

  // Description:
  // Specify the Xt widget to use for interaction. This method is
  // one of a couple steps that are required for setting up a
  // vtkRenderWindowInteractor as a widget inside of another user
  // interface. You do not need to use this method if the render window
  // will be a stand-alone window. This is only used when you want the
  // render window to be a subwindow within a larger user interface.
  // In that case, you must tell the render window what X display id
  // to use, and then ask the render window what depth, visual and
  // colormap it wants. Then, you must create an Xt TopLevelShell with
  // those settings. Then you can create the rest of your user interface
  // as a child of the TopLevelShell you created. Eventually, you will
  // create a drawing area or some other widget to serve as the rendering
  // window. You must use the SetWidget method to tell this Interactor
  // about that widget. It's X and it's not terribly easy, but it looks cool.
  virtual void SetWidget(Widget);
  Widget GetWidget() {return this->Top;};

  // Description
  // This method will store the top level shell widget for the interactor.
  // This method and the method invocation sequence applies for:
  //     1 vtkRenderWindow-Interactor pair in a nested widget hierarchy
  //     multiple vtkRenderWindow-Interactor pairs in the same top level shell
  // It is not needed for
  //     1 vtkRenderWindow-Interactor pair as the direct child of a top level shell
  //     multiple vtkRenderWindow-Interactor pairs, each in its own top level shell
  //
  // The method, along with EnterNotify event, changes the keyboard focus among
  // the widgets/vtkRenderWindow(s) so the Interactor(s) can receive the proper
  // keyboard events. The following calls need to be made:
  //     vtkRenderWindow's display ID need to be set to the top level shell's
  //           display ID.
  //     vtkXRenderWindowInteractor's Widget has to be set to the vtkRenderWindow's
  //           container widget
  //     vtkXRenderWindowInteractor's TopLevel has to be set to the top level
  //           shell widget
  // note that the procedure for setting up render window in a widget needs to
  // be followed.  See vtkRenderWindowInteractor's SetWidget method.
  //
  // If multiple vtkRenderWindow-Interactor pairs in SEPARATE windows are desired,
  // do not set the display ID (Interactor will create them as needed.  Alternatively,
  // create and set distinct DisplayID for each vtkRenderWindow. Using the same
  // display ID without setting the parent widgets will cause the display to be
  // reinitialized every time an interactor is initialized), do not set the
  // widgets (so the render windows would be in their own windows), and do
  // not set TopLevelShell (each has its own top level shell already)
  virtual void SetTopLevelShell(Widget);
  Widget GetTopLevelShell() {return this->TopLevelShell;};

  // Description:
  // Re-defines virtual function to get mouse position by querying X-server.
  virtual void GetMousePosition(int *x, int *y);

  // Description:
  // Functions that are used internally.
  friend void vtkXRenderWindowInteractorCallback(Widget,XtPointer,
                                                 XEvent *,Boolean *);
  friend void vtkXRenderWindowInteractorTimer(XtPointer,XtIntervalId *);

protected:
  vtkXRenderWindowInteractor();
  ~vtkXRenderWindowInteractor();

  //Using static here to avoid detroying context when many apps are open:
  static XtAppContext App;
  static int NumAppInitialized;

  Display *DisplayId;
  Window WindowId;
  Atom KillAtom;
  Widget Top;
  int OwnTop;
  int OwnApp;
  int PositionBeforeStereo[2];
  Widget TopLevelShell;
  int TimerId;
  vtkXRenderWindowInteractorInternals* Internal;

  // Description:
  // This will start up the X event loop and never return. If you
  // call this method it will loop processing X events until the
  // application is exited.
  virtual void StartEventLoop();

  // Description:
  // X-specific internal timer methods. See the superclass for detailed
  // documentation.
  virtual int InternalCreateTimer(int timerId, int timerType, unsigned long duration);
  virtual int InternalDestroyTimer(int platformTimerId);

  XtIntervalId AddTimeOut(XtAppContext app_context, unsigned long interval,
                          XtTimerCallbackProc proc, XtPointer client_data) ;
  void Timer(XtPointer client_data, XtIntervalId *id);
  void Callback(Widget w, XtPointer client_data, XEvent *event, Boolean *ctd);

  static int BreakLoopFlag;

private:
  vtkXRenderWindowInteractor(const vtkXRenderWindowInteractor&);  // Not implemented.
  void operator=(const vtkXRenderWindowInteractor&);  // Not implemented.
};

#endif


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

import com.google.devtools.build.lib.vfs.DigestHashFunction.DefaultHashFunctionNotSetException;
import java.io.IOException;

/**
 * An {@link AbstractFileSystem} that provides default implementations of {@link FileSystem#isFile}
 * et al. in terms of {@link FileSystem#stat} (rather than the other way around, which is what
 * {@link FileSystem} does).
 */
public abstract class AbstractFileSystemWithCustomStat extends AbstractFileSystem {

  public AbstractFileSystemWithCustomStat() throws DefaultHashFunctionNotSetException {}

  public AbstractFileSystemWithCustomStat(DigestHashFunction hashFunction) {
    super(hashFunction);
  }

  @Override
  protected boolean isFile(Path path, boolean followSymlinks) {
    FileStatus stat = statNullable(path, followSymlinks);
    return stat != null ? stat.isFile() : false;
  }

  @Override
  protected boolean isSpecialFile(Path path, boolean followSymlinks) {
    FileStatus stat = statNullable(path, followSymlinks);
    return stat != null ? stat.isSpecialFile() : false;
  }

  @Override
  protected boolean isSymbolicLink(Path path) {
    FileStatus stat = statNullable(path, false);
    return stat != null ? stat.isSymbolicLink() : false;
  }

  @Override
  protected boolean isDirectory(Path path, boolean followSymlinks) {
    FileStatus stat = statNullable(path, followSymlinks);
    return stat != null ? stat.isDirectory() : false;
  }

  @Override
  protected abstract FileStatus stat(Path path, boolean followSymlinks) throws IOException;
}


text:
class PrefRegistrySimple;
class PrefService;

namespace device {
class BluetoothAdapter;
}  // namespace device

namespace ash {
namespace quick_pair {

// Saves the Fast Pair account key to disk for peripherals that have been
// paired with this device for the active user, using the bluetooth MAC address
// as a lookup key, and user prefs for storage.
class SavedDeviceRegistry {
 public:
  explicit SavedDeviceRegistry(scoped_refptr<device::BluetoothAdapter> adapter);
  SavedDeviceRegistry(const SavedDeviceRegistry&) = delete;
  SavedDeviceRegistry& operator=(const SavedDeviceRegistry&) = delete;
  ~SavedDeviceRegistry();

  // Registers preferences used by this class in the provided |registry|.
  static void RegisterProfilePrefs(PrefRegistrySimple* registry);

  // Saves an account key to disk.
  void SaveAccountKey(const std::string& mac_address,
                      const std::vector<uint8_t>& account_key);

  // Deletes the |mac_address| -> account key record from prefs based on
  // |mac address|. Returns true on success, false on failure.
  bool DeleteAccountKey(const std::string& mac_address);

  // Deletes the mac address -> |account_key| record from prefs based on
  // |account_key|. Returns true on success, false on failure.
  bool DeleteAccountKey(const std::vector<uint8_t>& account_key);

  // Retrieves an account key from disk if available, otherwise returns an
  // empty vector.
  absl::optional<const std::vector<uint8_t>> GetAccountKey(
      const std::string& mac_address);

  // Checks if the account key is in the registry.
  bool IsAccountKeySavedToRegistry(const std::vector<uint8_t>& account_key);

 private:
  // Cross check the list of devices in the registry with the devices paired
  // to the BluetoothAdapter to see if any devices need to be removed from the
  // registry if they are no longer paired to the adapter. This can happen if
  // a primary user pairs and saves a device to their account, logs out, then a
  // secondary user logs in, forgets the device from the Bluetooth pairing
  // menu. When the primary user logs back in, we need to reflect the device is
  // no longer paired locally in the registry.
  void RemoveDevicesIfRemovedFromDifferentUser(PrefService* pref_service);

  // Flags cross checking the registry with the devices paired to the adapter
  // to see if any devices need to be removed from the registry (see
  // |RemoveDevicesIfRemovedFromDifferentUser|). This only needs to happen once
  // per session, which is why it is flagged. Everything else following during
  // the user session will be immediately reflected here.
  bool has_updated_saved_devices_registry_ = false;

  scoped_refptr<device::BluetoothAdapter> adapter_;
};

}  // namespace quick_pair
}  // namespace ash

#endif  // ASH_QUICK_PAIR_REPOSITORY_FAST_PAIR_SAVED_DEVICE_REGISTRY_H_


text:
<?php require 'config.php' ?>
<?php require 'authen.php' ?>
<?php require 'function.php' ?>
<?php
	$url = $_GET['url'];
	$video_type = $_GET['video_type'];
	$title = $_GET['title'];

	header("Content-type: video/mvrl");
	header("Content-Disposition: attachment; filename=$title.mvrl");

	echo $url . "\r\n";
	echo $video_type;
 ?>


text:
package com.telefonica.euro_iaas.paasmanager.rest.resources;

import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

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

import junit.framework.TestCase;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import com.telefonica.fiware.commons.dao.AlreadyExistsEntityException;
import com.telefonica.fiware.commons.dao.EntityNotFoundException;
import com.telefonica.fiware.commons.dao.InvalidEntityException;
import com.telefonica.euro_iaas.paasmanager.dao.ProductReleaseDao;
import com.telefonica.euro_iaas.paasmanager.exception.InfrastructureException;
import com.telefonica.euro_iaas.paasmanager.exception.InvalidSecurityGroupRequestException;
import com.telefonica.euro_iaas.paasmanager.manager.EnvironmentManager;
import com.telefonica.euro_iaas.paasmanager.manager.TierManager;
import com.telefonica.euro_iaas.paasmanager.model.ClaudiaData;
import com.telefonica.euro_iaas.paasmanager.model.Environment;
import com.telefonica.euro_iaas.paasmanager.model.ProductRelease;
import com.telefonica.euro_iaas.paasmanager.model.Tier;
import com.telefonica.euro_iaas.paasmanager.model.dto.NetworkDto;
import com.telefonica.euro_iaas.paasmanager.model.dto.ProductReleaseDto;
import com.telefonica.euro_iaas.paasmanager.model.dto.TierDto;
import com.telefonica.euro_iaas.paasmanager.rest.exception.APIException;
import com.telefonica.euro_iaas.paasmanager.rest.validation.TierResourceValidator;
import com.telefonica.euro_iaas.paasmanager.util.SystemPropertiesProvider;

/**
 * Test the TierResource class.
 */
public class TierResourceTest extends TestCase {

    private TierResourceImpl tierResource;
    private TierManager tierManager;
    private SystemPropertiesProvider systemPropertiesProvider;
    private EnvironmentManager environmentManager;
    private TierResourceValidator tierResourceValidator;
    private static String vdc = "VDC";
    private static String org = "ORG";
    private static String env = "env";

    /**
     * Initialize the Unit Test.
     * @throws Exception
     */
    @Before
    public void setUp() throws Exception {
        tierResource = new TierResourceImpl();
        tierManager = mock(TierManager.class);
        systemPropertiesProvider = mock(SystemPropertiesProvider.class);
        environmentManager = mock(EnvironmentManager.class);
        tierResourceValidator = mock(TierResourceValidator.class);
        ProductReleaseDao productReleaseDao = mock(ProductReleaseDao.class);
        tierResource.setTierManager(tierManager);
        tierResource.setSystemPropertiesProvider(systemPropertiesProvider);
        tierResource.setEnvironmentManager(environmentManager);

        tierResource.setProductReleaseDao(productReleaseDao);
        when(systemPropertiesProvider.getProperty(any(String.class))).thenReturn("FsIWARE");

        Mockito.doNothing().when(tierResourceValidator).validateCreate(any(ClaudiaData.class), any(TierDto.class),
                any(String.class), any(String.class));

        Mockito.doNothing().when(tierResourceValidator).validateDelete(any(String.class), any(String.class),
                any(String.class));

        Mockito.doNothing().when(tierResourceValidator).validateUpdate(any(String.class), any(String.class),
                any(String.class), any(TierDto.class));

        tierResource.setTierResourceValidator(tierResourceValidator);

        List<ProductRelease> productReleases = new ArrayList<ProductRelease>();
        productReleases.add(new ProductRelease("test", "0.1"));
        Tier tier = new Tier("tiername", new Integer(1), new Integer(1), new Integer(1), productReleases);
        tier.setImage("image");
        tier.setIcono("icono");
        tier.setFlavour("flavour");
        tier.setFloatingip("floatingip");
        tier.setKeypair("keypair");

        Environment environment = new Environment("name", "description", null);
        environment.addTier(tier);

        ProductRelease productRelease = new ProductRelease("test", "0.1");
        when(productReleaseDao.load(any(String.class))).thenReturn(productRelease);

        when(environmentManager.load(any(String.class), any(String.class))).thenReturn(environment);

    }

    /**
     * Test the operation to insert a new tier.
     * @throws APIException
     * @throws InvalidEntityException
     * @throws InvalidSecurityGroupRequestException
     * @throws InfrastructureException
     * @throws EntityNotFoundException
     * @throws AlreadyExistsEntityException
     */
    @Test
    public void testInsertTier()
            throws APIException, InvalidEntityException, InvalidSecurityGroupRequestException, InfrastructureException,
            EntityNotFoundException, AlreadyExistsEntityException {

        List<ProductReleaseDto> productReleaseDto = new ArrayList<ProductReleaseDto>();
        productReleaseDto.add(new ProductReleaseDto("test", "0.1"));
        TierDto tierDto = new TierDto("tiername", new Integer(1), new Integer(1), new Integer(1), productReleaseDto);
        tierDto.setImage("image");
        tierDto.setIcono("icono");
        tierDto.setFlavour("flavour");
        tierDto.setFloatingip("floatingip");
        tierDto.setKeypair("keypair");

        List<TierDto> tiers = new ArrayList<TierDto>();
        tiers.add(tierDto);

        when(tierManager.create(any(ClaudiaData.class), any(String.class), any(Tier.class)))
                .thenReturn(tierDto.fromDto(vdc, "env"));

        tierResource.insert(org, vdc, env, tierDto);

    }

    /**
     * Test the operation to insert a new tier with network details.
     * @throws APIException
     * @throws InvalidEntityException
     * @throws InvalidSecurityGroupRequestException
     * @throws InfrastructureException
     * @throws EntityNotFoundException
     * @throws AlreadyExistsEntityException
     */
    @Test
    public void testInsertTierWithNetwork()
            throws APIException, InvalidEntityException, InvalidSecurityGroupRequestException, InfrastructureException,
            EntityNotFoundException, AlreadyExistsEntityException {

        List<ProductReleaseDto> productReleaseDto = new ArrayList<ProductReleaseDto>();
        productReleaseDto.add(new ProductReleaseDto("test", "0.1"));
        NetworkDto net = new NetworkDto("net");
        TierDto tierDto = new TierDto("tiername", new Integer(1), new Integer(1), new Integer(1), productReleaseDto);
        tierDto.setImage("image");
        tierDto.setIcono("icono");
        tierDto.setFlavour("flavour");
        tierDto.setFloatingip("floatingip");
        tierDto.setKeypair("keypair");
        tierDto.addNetworkDto(net);

        List<TierDto> tiers = new ArrayList<TierDto>();
        tiers.add(tierDto);

        when(tierManager.create(any(ClaudiaData.class), any(String.class), any(Tier.class)))
                .thenReturn(tierDto.fromDto(vdc, "env"));

        tierResource.insert(org, vdc, env, tierDto);

    }

    /**
     * Test the insertion of a new Tier with no products information.
     * @throws Exception
     */
    @Test
    public void testTierNoProducts() throws Exception {

        TierDto tierDto = new TierDto("tiername", new Integer(1), new Integer(1), new Integer(1), null);
        tierDto.setImage("image");
        tierDto.setIcono("icono");
        tierDto.setFlavour("flavour");
        tierDto.setFloatingip("floatingip");
        tierDto.setKeypair("keypair");

        List<TierDto> tiers = new ArrayList<TierDto>();
        tiers.add(tierDto);
        when(tierManager.create(any(ClaudiaData.class), any(String.class), any(Tier.class)))
                .thenReturn(tierDto.fromDto(vdc, "env"));

        tierResource.insert(org, vdc, env, tierDto);

    }

    /**
     * Test the launch of a exception.
     * @throws APIException
     * @throws InvalidEntityException
     * @throws InvalidSecurityGroupRequestException
     * @throws InfrastructureException
     * @throws EntityNotFoundException
     * @throws AlreadyExistsEntityException
     */
    @Test(expected = APIException.class)
    public void testTierException()
            throws APIException, InvalidEntityException, InvalidSecurityGroupRequestException, InfrastructureException,
            EntityNotFoundException, AlreadyExistsEntityException {

        TierDto tierDto = new TierDto("", new Integer(1), new Integer(1), new Integer(1), null);
        tierDto.setImage("image");
        tierDto.setIcono("icono");
        tierDto.setFlavour("flavour");
        tierDto.setFloatingip("floatingip");
        tierDto.setKeypair("keypair");
        when(tierManager.create(any(ClaudiaData.class), any(String.class), any(Tier.class)))
                .thenReturn(tierDto.fromDto(vdc, "env"));

        tierResource.insert(org, vdc, env, tierDto);
    }

    /**
     * Test the operation to delete a Tier.
     * @throws APIException
     * @throws InvalidEntityException
     * @throws InvalidSecurityGroupRequestException
     * @throws InfrastructureException
     * @throws EntityNotFoundException
     * @throws AlreadyExistsEntityException
     */
    @Test
    public void testDeleteTier()
            throws APIException, InvalidEntityException, InvalidSecurityGroupRequestException, InfrastructureException,
            EntityNotFoundException, AlreadyExistsEntityException {

        List<ProductReleaseDto> productReleaseDto = new ArrayList<ProductReleaseDto>();
        productReleaseDto.add(new ProductReleaseDto("test", "0.1"));
        TierDto tierDto = new TierDto("tiername22", new Integer(1), new Integer(1), new Integer(1), productReleaseDto);
        tierDto.setImage("image");
        tierDto.setIcono("icono");
        tierDto.setFlavour("flavour");
        tierDto.setFloatingip("floatingip");
        tierDto.setKeypair("keypair");
        when(tierManager.load(any(String.class), any(String.class), any(String.class)))
                .thenReturn(tierDto.fromDto(vdc, "env"));

        tierResource.delete(org, vdc, env, tierDto.getName());
    }

    /**
     * Test the operation to delete a Tier with network details.
     * @throws APIException
     * @throws InvalidEntityException
     * @throws InvalidSecurityGroupRequestException
     * @throws InfrastructureException
     * @throws EntityNotFoundException
     * @throws AlreadyExistsEntityException
     */
    @Test
    public void testDeleteTierWithNetwork()
            throws APIException, InvalidEntityException, InvalidSecurityGroupRequestException, InfrastructureException,
            EntityNotFoundException, AlreadyExistsEntityException {

        List<ProductReleaseDto> productReleaseDto = new ArrayList<ProductReleaseDto>();
        productReleaseDto.add(new ProductReleaseDto("test", "0.1"));
        NetworkDto net = new NetworkDto("net");
        TierDto tierDto = new TierDto("tiername22", new Integer(1), new Integer(1), new Integer(1), productReleaseDto);
        tierDto.setImage("image");
        tierDto.setIcono("icono");
        tierDto.setFlavour("flavour");
        tierDto.setFloatingip("floatingip");
        tierDto.setKeypair("keypair");
        tierDto.addNetworkDto(net);
        when(tierManager.load(any(String.class), any(String.class), any(String.class)))
                .thenReturn(tierDto.fromDto(vdc, "env"));

        tierResource.delete(org, vdc, env, tierDto.getName());
    }

    /**
     * Test the operation to update a tier.
     * @throws APIException
     * @throws InvalidEntityException
     * @throws InvalidSecurityGroupRequestException
     * @throws InfrastructureException
     * @throws EntityNotFoundException
     * @throws AlreadyExistsEntityException
     */
    @Test
    public void testUpdateTier()
            throws APIException, InvalidEntityException, InvalidSecurityGroupRequestException, InfrastructureException,
            EntityNotFoundException, AlreadyExistsEntityException {

        List<ProductReleaseDto> productReleaseDto = new ArrayList<ProductReleaseDto>();
        productReleaseDto.add(new ProductReleaseDto("test", "0.1"));
        TierDto tierDto = new TierDto("tiername22", new Integer(1), new Integer(1), new Integer(1), productReleaseDto);
        tierDto.setImage("image");
        tierDto.setIcono("icono");
        tierDto.setFlavour("flavour");
        tierDto.setFloatingip("floatingip");
        tierDto.setKeypair("keypair");
        tierDto.setRegion("region1");
        when(tierManager.create(any(ClaudiaData.class), any(String.class), any(Tier.class)))
                .thenReturn(tierDto.fromDto(vdc, "env"));

        when(tierManager.load(any(String.class), any(String.class), any(String.class)))
                .thenReturn(tierDto.fromDto(vdc, "env"));

        tierResource.insert(org, vdc, env, tierDto);

        TierDto tierDto2 = new TierDto("tiername22", new Integer(1), new Integer(1), new Integer(1), productReleaseDto);
        tierDto2.setImage("image2");
        tierDto2.setIcono("icono");
        tierDto2.setFlavour("flavour");
        tierDto2.setFloatingip("floatingip");
        tierDto2.setKeypair("keypair");
        tierDto.setRegion("region2");
        Mockito.doNothing().when(tierManager).updateTier(any(ClaudiaData.class), any(Tier.class), any(Tier.class));
        tierResource.update(org, vdc, env, tierDto.getName(), tierDto2);
    }

    /**
     * Test the operation to update a Tier with different information.
     * @throws APIException
     * @throws EntityNotFoundException
     */
    @Test(expected = APIException.class)
    public void testUpdateTierDifferent() throws APIException, EntityNotFoundException {

        List<ProductReleaseDto> productReleaseDto = new ArrayList<ProductReleaseDto>();
        productReleaseDto.add(new ProductReleaseDto("test", "0.1"));
        TierDto tierDto = new TierDto("tiername3", new Integer(1), new Integer(1), new Integer(1), productReleaseDto);
        tierDto.setImage("image");
        tierDto.setIcono("icono");
        tierDto.setFlavour("flavour");
        tierDto.setFloatingip("floatingip");
        tierDto.setKeypair("keypair");

        when(tierManager.load(any(String.class), any(String.class), any(String.class)))
                .thenReturn(tierDto.fromDto(vdc, "env"));

        TierDto tierDto2 = new TierDto("tiername4", new Integer(1), new Integer(1), new Integer(1), productReleaseDto);
        tierResource.update(org, vdc, env, tierDto.getName(), tierDto2);

    }

}


text:
import mock
from oslo_concurrency import processutils as putils

from cinder import context
from cinder import exception
from cinder.tests.unit.targets import targets_fixture as tf
from cinder import utils
from cinder.volume.targets import lio

class TestLioAdmDriver(tf.TargetDriverFixture):

    def setUp(self):
        super(TestLioAdmDriver, self).setUp()

        with mock.patch.object(lio.LioAdm, '_verify_rtstool'):
            self.target = lio.LioAdm(root_helper=utils.get_root_helper(),
                                     configuration=self.configuration)

    @mock.patch.object(lio.LioAdm, '_execute', side_effect=lio.LioAdm._execute)
    @mock.patch.object(lio.LioAdm, '_persist_configuration')
    @mock.patch('cinder.utils.execute')
    def test_get_target(self, mexecute, mpersist_cfg, mlock_exec):
        mexecute.return_value = (self.test_vol, None)
        self.assertEqual(self.test_vol, self.target._get_target(self.test_vol))
        self.assertFalse(mpersist_cfg.called)
        expected_args = ('cinder-rtstool', 'get-targets')
        mlock_exec.assert_called_once_with(*expected_args, run_as_root=True)
        mexecute.assert_called_once_with(*expected_args, run_as_root=True)

    def test_get_iscsi_target(self):
        ctxt = context.get_admin_context()
        expected = 0
        self.assertEqual(expected,
                         self.target._get_iscsi_target(ctxt,
                                                       self.testvol['id']))

    def test_get_target_and_lun(self):
        lun = 0
        iscsi_target = 0
        ctxt = context.get_admin_context()
        expected = (iscsi_target, lun)
        self.assertEqual(expected,
                         self.target._get_target_and_lun(ctxt, self.testvol))

    @mock.patch.object(lio.LioAdm, '_execute', side_effect=lio.LioAdm._execute)
    @mock.patch.object(lio.LioAdm, '_persist_configuration')
    @mock.patch('cinder.utils.execute')
    @mock.patch.object(lio.LioAdm, '_get_target')
    def test_create_iscsi_target(self, mget_target, mexecute, mpersist_cfg,
                                 mlock_exec):

        mget_target.return_value = 1
        # create_iscsi_target sends volume_name instead of volume_id on error
        self.assertEqual(
            1,
            self.target.create_iscsi_target(
                self.test_vol,
                1,
                0,
                self.fake_volumes_dir))
        mpersist_cfg.assert_called_once_with(self.VOLUME_NAME)
        mexecute.assert_called_once_with(
            'cinder-rtstool',
            'create',
            self.fake_volumes_dir,
            self.test_vol,
            '',
            '',
            self.target.iscsi_protocol == 'iser',
            run_as_root=True)

    @mock.patch.object(lio.LioAdm, '_execute', side_effect=lio.LioAdm._execute)
    @mock.patch.object(lio.LioAdm, '_persist_configuration')
    @mock.patch.object(utils, 'execute')
    @mock.patch.object(lio.LioAdm, '_get_target', return_value=1)
    def test_create_iscsi_target_port_ip(self, mget_target, mexecute,
                                         mpersist_cfg, mlock_exec):
        ip = '10.0.0.15'
        port = 3261

        self.assertEqual(
            1,
            self.target.create_iscsi_target(
                name=self.test_vol,
                tid=1,
                lun=0,
                path=self.fake_volumes_dir,
                **{'portals_port': port, 'portals_ips': [ip]}))

        expected_args = (
            'cinder-rtstool',
            'create',
            self.fake_volumes_dir,
            self.test_vol,
            '',
            '',
            self.target.iscsi_protocol == 'iser',
            '-p%s' % port,
            '-a' + ip)

        mlock_exec.assert_any_call(*expected_args, run_as_root=True)
        mexecute.assert_any_call(*expected_args, run_as_root=True)
        mpersist_cfg.assert_called_once_with(self.VOLUME_NAME)

    @mock.patch.object(lio.LioAdm, '_execute', side_effect=lio.LioAdm._execute)
    @mock.patch.object(lio.LioAdm, '_persist_configuration')
    @mock.patch.object(utils, 'execute')
    @mock.patch.object(lio.LioAdm, '_get_target', return_value=1)
    def test_create_iscsi_target_port_ips(self, mget_target, mexecute,
                                          mpersist_cfg, mlock_exec):
        test_vol = 'iqn.2010-10.org.openstack:' + self.VOLUME_NAME
        ips = ['10.0.0.15', '127.0.0.1']
        port = 3261

        self.assertEqual(
            1,
            self.target.create_iscsi_target(
                name=test_vol,
                tid=1,
                lun=0,
                path=self.fake_volumes_dir,
                **{'portals_port': port, 'portals_ips': ips}))

        expected_args = (
            'cinder-rtstool',
            'create',
            self.fake_volumes_dir,
            test_vol,
            '',
            '',
            self.target.iscsi_protocol == 'iser',
            '-p%s' % port,
            '-a' + ','.join(ips))

        mlock_exec.assert_any_call(*expected_args, run_as_root=True)
        mexecute.assert_any_call(*expected_args, run_as_root=True)
        mpersist_cfg.assert_called_once_with(self.VOLUME_NAME)

    @mock.patch.object(lio.LioAdm, '_execute', side_effect=lio.LioAdm._execute)
    @mock.patch.object(lio.LioAdm, '_persist_configuration')
    @mock.patch('cinder.utils.execute',
                side_effect=putils.ProcessExecutionError)
    @mock.patch.object(lio.LioAdm, '_get_target')
    def test_create_iscsi_target_already_exists(self, mget_target, mexecute,
                                                mpersist_cfg, mlock_exec):
        chap_auth = ('foo', 'bar')
        self.assertRaises(exception.ISCSITargetCreateFailed,
                          self.target.create_iscsi_target,
                          self.test_vol,
                          1,
                          0,
                          self.fake_volumes_dir,
                          chap_auth)
        self.assertFalse(mpersist_cfg.called)
        expected_args = ('cinder-rtstool', 'create', self.fake_volumes_dir,
                         self.test_vol, chap_auth[0], chap_auth[1], False)
        mlock_exec.assert_called_once_with(*expected_args, run_as_root=True)
        mexecute.assert_called_once_with(*expected_args, run_as_root=True)

    @mock.patch.object(lio.LioAdm, '_execute', side_effect=lio.LioAdm._execute)
    @mock.patch.object(lio.LioAdm, '_persist_configuration')
    @mock.patch('cinder.utils.execute')
    def test_remove_iscsi_target(self, mexecute, mpersist_cfg, mlock_exec):
        # Test the normal case
        self.target.remove_iscsi_target(0,
                                        0,
                                        self.testvol['id'],
                                        self.testvol['name'])
        expected_args = ('cinder-rtstool', 'delete',
                         self.iscsi_target_prefix + self.testvol['name'])

        mlock_exec.assert_called_once_with(*expected_args, run_as_root=True)
        mexecute.assert_called_once_with(*expected_args, run_as_root=True)
        mpersist_cfg.assert_called_once_with(self.fake_volume_id)

        # Test the failure case: putils.ProcessExecutionError
        mlock_exec.reset_mock()
        mpersist_cfg.reset_mock()
        mexecute.side_effect = putils.ProcessExecutionError
        self.assertRaises(exception.ISCSITargetRemoveFailed,
                          self.target.remove_iscsi_target,
                          0,
                          0,
                          self.testvol['id'],
                          self.testvol['name'])
        mlock_exec.assert_called_once_with(*expected_args, run_as_root=True)

        # Ensure there have been no calls to persist configuration
        self.assertFalse(mpersist_cfg.called)

    @mock.patch.object(lio.LioAdm, '_get_targets')
    @mock.patch.object(lio.LioAdm, '_execute', side_effect=lio.LioAdm._execute)
    @mock.patch('cinder.utils.execute')
    def test_ensure_export(self, mock_exec, mock_execute, mock_get_targets):

        ctxt = context.get_admin_context()
        mock_get_targets.return_value = None
        self.target.ensure_export(ctxt,
                                  self.testvol,
                                  self.fake_volumes_dir)

        expected_args = ('cinder-rtstool', 'restore')
        mock_exec.assert_called_once_with(*expected_args, run_as_root=True)

    @mock.patch.object(lio.LioAdm, '_get_targets')
    @mock.patch.object(lio.LioAdm, '_restore_configuration')
    def test_ensure_export_target_exist(self, mock_restore, mock_get_targets):

        ctxt = context.get_admin_context()
        mock_get_targets.return_value = 'target'
        self.target.ensure_export(ctxt,
                                  self.testvol,
                                  self.fake_volumes_dir)
        self.assertFalse(mock_restore.called)

    @mock.patch.object(lio.LioAdm, '_execute', side_effect=lio.LioAdm._execute)
    @mock.patch.object(lio.LioAdm, '_persist_configuration')
    @mock.patch('cinder.utils.execute')
    @mock.patch.object(lio.LioAdm, '_get_iscsi_properties')
    def test_initialize_connection(self, mock_get_iscsi, mock_execute,
                                   mpersist_cfg, mlock_exec):
        target_id = self.iscsi_target_prefix + 'volume-' + self.fake_volume_id
        connector = {'initiator': 'fake_init'}

        # Test the normal case
        mock_get_iscsi.return_value = 'foo bar'
        expected_return = {'driver_volume_type': 'iscsi',
                           'data': 'foo bar'}
        self.assertEqual(expected_return,
                         self.target.initialize_connection(self.testvol,
                                                           connector))

        expected_args = ('cinder-rtstool', 'add-initiator', target_id,
                         self.expected_iscsi_properties['auth_username'],
                         '2FE0CQ8J196R', connector['initiator'])

        mlock_exec.assert_called_once_with(*expected_args, run_as_root=True)
        mock_execute.assert_called_once_with(*expected_args, run_as_root=True)
        mpersist_cfg.assert_called_once_with(self.fake_volume_id)

        # Test the failure case: putils.ProcessExecutionError
        mlock_exec.reset_mock()
        mpersist_cfg.reset_mock()
        mock_execute.side_effect = putils.ProcessExecutionError
        self.assertRaises(exception.ISCSITargetAttachFailed,
                          self.target.initialize_connection,
                          self.testvol,
                          connector)

        mlock_exec.assert_called_once_with(*expected_args, run_as_root=True)

        # Ensure there have been no calls to persist configuration
        self.assertFalse(mpersist_cfg.called)

    @mock.patch.object(lio.LioAdm, '_execute', side_effect=lio.LioAdm._execute)
    @mock.patch.object(lio.LioAdm, '_persist_configuration')
    @mock.patch('cinder.utils.execute')
    def test_terminate_connection(self, mock_execute, mpersist_cfg,
                                  mlock_exec):

        target_id = self.iscsi_target_prefix + 'volume-' + self.fake_volume_id

        connector = {'initiator': 'fake_init'}
        self.target.terminate_connection(self.testvol,
                                         connector)
        expected_args = ('cinder-rtstool', 'delete-initiator', target_id,
                         connector['initiator'])

        mlock_exec.assert_called_once_with(*expected_args, run_as_root=True)
        mock_execute.assert_called_once_with(*expected_args, run_as_root=True)
        mpersist_cfg.assert_called_once_with(self.fake_volume_id)

    @mock.patch.object(lio.LioAdm, '_execute', side_effect=lio.LioAdm._execute)
    @mock.patch.object(lio.LioAdm, '_persist_configuration')
    @mock.patch('cinder.utils.execute')
    def test_terminate_connection_no_prov_loc(self,
                                              mock_execute,
                                              mpersist_cfg,
                                              mlock_exec):
        """terminate_connection does nothing if provider_location is None"""

        connector = {'initiator': 'fake_init'}
        self.target.terminate_connection(self.testvol_no_prov_loc,
                                         connector)

        mlock_exec.assert_not_called()
        mock_execute.assert_not_called()
        mpersist_cfg.assert_not_called()

    @mock.patch.object(lio.LioAdm, '_execute', side_effect=lio.LioAdm._execute)
    @mock.patch.object(lio.LioAdm, '_persist_configuration')
    @mock.patch('cinder.utils.execute')
    def test_terminate_connection_fail(self, mock_execute, mpersist_cfg,
                                       mlock_exec):

        target_id = self.iscsi_target_prefix + 'volume-' + self.fake_volume_id
        mock_execute.side_effect = putils.ProcessExecutionError
        connector = {'initiator': 'fake_init'}
        self.assertRaises(exception.ISCSITargetDetachFailed,
                          self.target.terminate_connection,
                          self.testvol,
                          connector)
        mlock_exec.assert_called_once_with('cinder-rtstool',
                                           'delete-initiator', target_id,
                                           connector['initiator'],
                                           run_as_root=True)
        self.assertFalse(mpersist_cfg.called)

    def test_iscsi_protocol(self):
        self.assertEqual('iscsi', self.target.iscsi_protocol)

    @mock.patch.object(lio.LioAdm, '_get_target_and_lun', return_value=(1, 2))
    @mock.patch.object(lio.LioAdm, 'create_iscsi_target', return_value=3)
    @mock.patch.object(lio.LioAdm, '_get_target_chap_auth',
                       return_value=(mock.sentinel.user, mock.sentinel.pwd))
    def test_create_export(self, mock_chap, mock_create, mock_get_target):
        ctxt = context.get_admin_context()
        result = self.target.create_export(ctxt, self.testvol_2,
                                           self.fake_volumes_dir)

        loc = (u'%(ip)s:%(port)d,3 %(prefix)s%(name)s 2' %
               {'ip': self.configuration.iscsi_ip_address,
                'port': self.configuration.iscsi_port,
                'prefix': self.iscsi_target_prefix,
                'name': self.testvol_2['name']})

        expected_result = {
            'location': loc,
            'auth': 'CHAP %s %s' % (mock.sentinel.user, mock.sentinel.pwd),
        }

        self.assertEqual(expected_result, result)

        mock_create.assert_called_once_with(
            self.iscsi_target_prefix + self.testvol_2['name'],
            1,
            2,
            self.fake_volumes_dir,
            (mock.sentinel.user, mock.sentinel.pwd),
            portals_ips=[self.configuration.iscsi_ip_address],
            portals_port=self.configuration.iscsi_port)


text:
package odin.domain;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Burndown {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;

    public Long getSprintId() {
		return sprintId;
	}

	public void setSprintId(Long sprintId) {
		this.sprintId = sprintId;
	}

	public Date getSnapshotDate() {
		return snapshotDate;
	}

	public void setSnapshotDate(Date snapshotDate) {
		this.snapshotDate = snapshotDate;
	}

	public Integer getSumEstimated() {
		return sumEstimated;
	}

	public void setSumEstimated(Integer sumEstimated) {
		this.sumEstimated = sumEstimated;
	}

	public Integer getSumLogged() {
		return sumLogged;
	}

	public void setSumLogged(Integer sumLogged) {
		this.sumLogged = sumLogged;
	}

	public Integer getSumRemaining() {
		return sumRemaining;
	}

	public void setSumRemaining(Integer sumRemaining) {
		this.sumRemaining = sumRemaining;
	}

	public Integer getSumIdealRemaining() {
		return sumIdealRemaining;
	}

	public void setSumIdealRemaining(Integer sumIdealRemaining) {
		this.sumIdealRemaining = sumIdealRemaining;
	}

	public Integer getSumTickets() {
		return sumTickets;
	}

	public void setSumTickets(Integer sumTickets) {
		this.sumTickets = sumTickets;
	}

	public Integer getSumStatusNew() {
		return sumStatusNew;
	}

	public void setSumStatusNew(Integer sumStatusNew) {
		this.sumStatusNew = sumStatusNew;
	}

	public Integer getSumStatusInProgress() {
		return sumStatusInProgress;
	}

	public void setSumStatusInProgress(Integer sumStatusInProgress) {
		this.sumStatusInProgress = sumStatusInProgress;
	}

	public Integer getSumStatusDone() {
		return sumStatusDone;
	}

	public void setSumStatusDone(Integer sumStatusDone) {
		this.sumStatusDone = sumStatusDone;
	}

	private Long sprintId;

    private Date snapshotDate;

    private Integer sumEstimated;

    private Integer sumLogged;

    private Integer sumRemaining;

    private Integer sumIdealRemaining;

    private Integer sumTickets;

    private Integer sumStatusNew;

    private Integer sumStatusInProgress;

    private Integer sumStatusDone;
}


text:
/*
 * print.css
 *
 * print styles
 */
* { background: transparent !important; color: #444 !important; text-shadow: none; }

a, a:visited { color: #444 !important; text-decoration: underline; }

a:after { content: " (" attr(href) ")"; }

abbr:after { content: " (" attr(title) ")"; }

.ir a:after { content: ""; }  /* Don't show links for images */

pre, blockquote { border: 1px solid #999; page-break-inside: avoid; }

img { page-break-inside: avoid; }

@page { margin: 0.5cm; }

p, h2, h3 { orphans: 3; widows: 3; }

h2, h3{ page-break-after: avoid; }

#no-js-warning-wrapper{ display: none; visibility: hidden; }


text:
typedef NS_ENUM(NSUInteger, RCKAudioDownloadOptions)
{
    RCKAudioDownloadAsk = 0,
    RCKAudioDownloadAlwaysDownload,
    RCKAudioDownloadDontDownload
};

typedef NS_ENUM(NSUInteger, RCKAudioAlbumShowOptions)
{
    RCKAudioAlbumShowMyAudio = 0,
    RCKAudioAlbumShowOnlyDownload
};

@interface RCKSettings : NSObject

@property (nonatomic) RCKAudioDownloadOptions audioDownloadOptions;
@property (nonatomic) RCKAudioAlbumShowOptions audioAlbumShowOptions;

+ (instancetype)sharedInstance;

@end


text:
<?php

/**
 * Short description for class.
 *
 * @package       Cake.Test.Fixture
 */
class GuildFixture extends CakeTestFixture {

/**
 * name property
 *
 * @var string 'Guild'
 */
	public $name = 'Guild';

/**
 * fields property
 *
 * @var array
 */
	public $fields = array(
		'id' => array('type' => 'integer', 'key' => 'primary'),
		'name' => array('type' => 'string', 'null' => false),
	);

/**
 * records property
 *
 * @var array
 */
	public $records = array(
		array('name' => 'Warriors'),
		array('name' => 'Rangers'),
		array('name' => 'Wizards'),
	);
}


text:
$(function () {
    'use strict';

    var sut;
    var sutChaining;

    var build;

    var $fixture;

    var $main;
    var $panel;
    var $clip;
    var $header;
    var $body;

    QUnit.testStart(function () {
        $fixture = $('#qunit-fixture');
        $fixture.append($('

'));

        $main = $('#main');

        build = new Build();

        sut = new LyricContainer($main, build);

        $panel = $main.find('#lyrics-panel');
        $clip = $main.find('#lyrics-panel #lyrics-clip');
        $header = $main.find('#lyrics-panel #lyrics-header');
        $body = $main.find('#lyrics-panel #lyrics-body');
    });

    QUnit.test('Lyric container init throws exception when no parent defined', 1, function () {
        throws(function () {
            new LyricContainer(undefined, build);
        }, 'Please define a selector', 'Throws a exception when parent is not defined.');
    });

    QUnit.test('Lyric container init throws exception when no build defined', 1, function () {
        throws(function () {
            new LyricContainer($main, undefined);
        }, 'Build object undefined', 'Throws a exception when build is not defined.');
    });

    QUnit.test('Lyric container ', 12, function () {
        equal($panel.hasClass('lyrics-panel'), true, 'Panel has class lyrics-panel');
        equal($panel.hasClass('un-clicked'), true, 'Panel is un-clicked');
        equal($panel.attr('id'), 'lyrics-panel', 'Panel has id lyrics-panel');

        equal($clip.hasClass('lyrics-clip'), true, 'Clip has class lyrics-clip');
        equal($clip.text(), 'Lyric', 'Clip has text: Lyric');
        equal($clip.attr('id'), 'lyrics-clip', 'Clip has id lyrics-clip');

        equal($header.hasClass('lyrics-header'), true, 'Header has class lyrics-header');
        equal($header.attr('id'), 'lyrics-header', 'Header has id lyrics-header');
        equal($header.text(), 'Lyrics Panel', 'Header has text: Lyric Panel');

        equal($body.hasClass('lyrics-body'), true, 'Body has class lyrics-body');
        equal($body.attr('id'), 'lyrics-body', 'Body has id lyrics-body');
        equal($body.text(), 'I can not hear a sound. Play something loud!', 'Header has text: I can not hear a sound. Play something loud!');
    });

    QUnit.test('Lyric container register toggler', 3, function () {
        sutChaining = sut.registerToggler();

        strictEqual(sut, sutChaining, 'Chaining is correct.');

        equal($panel.hasClass('un-clicked'), true, 'Panel has not been clicked');

        $clip.click();

        equal($panel.hasClass('clicked'), true, 'Panel has been clicked');
    });

    QUnit.test('Lyric container register event loading overlay', 2, function () {
        sut.registerEvents();

        $panel.trigger('add-loading-overlay');

        var $loadingOverlay = $('#lyrics-body').find('#loading-overlay');

        equal($loadingOverlay.attr('id'), 'loading-overlay', 'Loading-overlay has been added with id');
        equal($loadingOverlay.attr('data-type'), 'regular-loading-overlay', 'Loading-overlay has been added with data-type');
    });

    QUnit.test('Lyric container register event update and trigger with headline change', 2, function () {
        sut.registerEvents();

        $panel.trigger('update', {artist: 'artist', title: 'title'});

        equal($header.html(), 'artist - title', 'Container update has correct header information');
        equal($body.html(), 'I can not hear a sound. Play something loud!', 'Default body text set');
    });

    QUnit.test('Lyric container no scrolling on headline change', 1, function () {
        sut.registerEvents();
        $body.css({height: '10px', overflowY: 'scroll'}).scrollTop(5);

        $panel.trigger('update', {artist: 'artist', title: 'title'});

        equal($body.scrollTop(), '5', 'Container update without lyric that does not reset the scrolling');
    });

    QUnit.test('Lyric container register event update and trigger with lyric change', 3, function () {
        sut.registerEvents();

        $panel.trigger('update', {lyric: 'lyric'});

        equal($header.html(), 'Lyrics Panel', 'Default headline is set');
        equal($body.html(), 'lyric', 'Container update has correct body information');
        equal($body.scrollTop(), '0', 'Container update reset the scrolling');
    });

    QUnit.test('Lyric container register event chaining', 1, function () {
        sutChaining = sut.registerEvents();
        strictEqual(sut, sutChaining, 'Chaining is correct.');
    });
});