text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<TITLE>Q Light Controller Plus - Questions & Answers</TITLE>

<link href="style.css" rel="stylesheet" type="text/css" />

Questions & Answers

In this page you will find the common questions that may come to mind when starting with QLC+.

Here you can either find the answer directly or find help to point you in the right direction.

  1
  Q:
  QLC+ cannot detect my USB device

  A:
  QLC+ supports a wide variety of USB devices. First of all you should check if the physical connection
      is OK. Usually a LED on your device should indicate if it is powered up and working correctly.

      If you are using Windows and your device is manufactured by Peperoni or Velleman, please read the information on how to get
      them working on these help pages. For licensing issues they both need an extra DLL file to work.
      Please check Peperoni output plugin or Velleman output plugin

      If you're using Linux, please check if your distribution detected the device when plugged in. Basically, the
      "dmesg" command should tell you something.

  2
  Q:
  I've got several buttons in my Virtual Console. I need a way to disable the currently
      active button when I enable another one. How do I do that ?

  A:
  Simply place your buttons inside a Solo Frame. It does exactly that.

  3
  Q:
  When I start an EFX function, all my fixtures go to full intensity and I can't make them dimmer.

  A:
  Please, read this note.

  4
  Q:
  I just upgraded my Mac to Mavericks (or later) and my USB DMX adapter doesn't transmit any data.

  A:
  The problem is in an Apple driver called AppleUSBFTDI, which takes control of every FTDI based device detected in the system.

      There are a few ways to solve the problem, but basically the result is the same: the Apple driver must be disabled.

      Please check the dedicated page to understand how to disable the Apple FTDI driver

      Otherwise, you can download the ENTTEC FTDI Driver Control tool
      and try to enable/disable the Apple driver with it.

      Note 1: this can compromise the behaviour of other USB devices, so do it only
      if you know what you're doing!

      Note 2: every time Mac OS receives an update, you need to perform this procedure again !

      Note 3: Most likely, when you disable/enable the Apple driver, you need to reboot your Mac

  5
  Q:
  Where is the QLC+ user folder located in my system ?

  A:
  The user folder is where user fixtures, input profiles, RGB scripts and MIDI templates go.

      It changes depending on your operating system:

      Linux: it is a hidden folder in your user home directory: $HOME/.qlcplus

      Windows: it is a folder in your user (e.g. MyUser) directory: C:\Users\MyUser\QLC+

      Mac OS: it is located in your user "Library" directory: $HOME/Library/Application\ Support/QLC+

      You can reach any of these folders from a terminal with the 'cd' command. For example:

cd $HOME/Library/Application\ Support/QLC+

      Please keep in mind that fixures and input profiles found in the user folder will have precedence
      over the same files in the QLC+ system folder.

  6
  Q:
  Where is the QLC+ system folder located in my system ?

  A:
  The system folder is where QLC+ resources (fixtures, input profiles, RGB scripts, etc) are installed
      and it changes depending on your operating system:

      Linux: it's a fixed folder named /usr/share/qlcplus

      Windows: it is the folder where you actually installed QLC+. By default: C:\QLC+

      Mac OS: it is a folder inside the QLC+ bundle (.app file). It is possible to browse the QLC+.app bundle contents simply with Finder.
      Just right click on the file and select "Show Package Contents".

      Otherwise, the system folder can be reached with a terminal but it depends on where you installed QLC+.

      For example if you dragged QLC+ into Applications it will be: /Applications/QLC+.app/Contents/Resources

  7
  Q:
  QLC+ cannot play some videos on Windows

  A:
  QLC+ relies on the Qt libraries which relies on the DirectShow filters installed in the system.

      Unfortunately the basic codecs supported by Windows are quite poor, so you need to install some extra
      codecs package like K-Lite, available here.

  8
  Q:
  I have a 4k display and everything in the QLC+ interface is extremely small

  A:
  You need to add an option to the QLC+ command line to tell the Qt libraries to autoscale
      the interface on a High DPI display. Examples:

Linux (from terminal): QT_AUTO_SCREEN_SCALE_FACTOR=1 qlcplus

Windows shortcut: C:\Windows\System32\cmd.exe /c "SET QT_AUTO_SCREEN_SCALE_FACTOR=1 && START /D ^"C:\QLC+^" qlcplus.exe"

Mac OS (from terminal): QT_AUTO_SCREEN_SCALE_FACTOR=1 QLC+.app\Contents\MacOS\qlcplus

      In case, see the command line parameters page for further information.


text:
var gulp = require('gulp');
var path = require('path');
var replace = require('gulp-replace');
var child_process = require('child_process');
var fs = require('fs');
var shell = require('gulp-shell');
var jshint = require('gulp-jshint');
var jshStylish = require('jshint-stylish');
var exec = require('child_process').exec;
var runSequence = require('run-sequence');
var prompt = require('gulp-prompt');
var version;

gulp.task('default', [], function( next ){
  console.log('You must explicitly call `gulp publish` to publish the extension');
  next();
});

gulp.task('publish', [], function( next ){
  runSequence('confver', 'lint', 'pkgver', 'push', 'tag', 'npm', next);
});

gulp.task('confver', ['version'], function(){
  return gulp.src('.')
    .pipe( prompt.confirm({ message: 'Are you sure version `' + version + '` is OK to publish?' }) )
  ;
});

gulp.task('version', function( next ){
  var now = new Date();
  version = process.env['VERSION'];

  if( version ){
    done();
  } else {
    exec('git rev-parse HEAD', function( error, stdout, stderr ){
      var sha = stdout.substring(0, 10); // shorten so not huge filename

      version = [ 'snapshot', sha, +now ].join('-');
      done();
    });
  }

  function done(){
    console.log('Using version number `%s` for building', version);
    next();
  }

});

gulp.task('pkgver', ['version'], function(){
  return gulp.src([
    'package.json',
    'bower.json'
  ])
    .pipe( replace(/\"version\"\:\s*\".*?\"/, '"version": "' + version + '"') )

    .pipe( gulp.dest('./') )
  ;
});

gulp.task('push', shell.task([
  'git add -A',
  'git commit -m "pushing changes for v$VERSION release" || echo Nothing to commit',
  'git push || echo Nothing to push'
]));

gulp.task('tag', shell.task([
  'git tag -a $VERSION -m "tagging v$VERSION"',
  'git push origin $VERSION'
]));

gulp.task('npm', shell.task([
  'npm publish .'
]));

// http://www.jshint.com/docs/options/
gulp.task('lint', function(){
  return gulp.src( 'cytoscape-*.js' )
    .pipe( jshint({
      funcscope: true,
      laxbreak: true,
      loopfunc: true,
      strict: true,
      unused: 'vars',
      eqnull: true,
      sub: true,
      shadow: true,
      laxcomma: true
    }) )

    .pipe( jshint.reporter(jshStylish) )

    .pipe( jshint.reporter('fail') )
  ;
});

redpajama_set_name: RedPajamaGithub


text:
$('#font-bomb').on('click', function(event) {
  var Bomb, Explosion, Particle, targetTime, vendor, w, _i, _len, _ref,
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  w = window;

  _ref = ['ms', 'moz', 'webkit', 'o'];
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
    vendor = _ref[_i];
    if (w.requestAnimationFrame) break;
    w.requestAnimationFrame = w["#vendorRequestAnimationFrame"];
    w.cancelAnimationFrame = w["#vendorCancelAnimationFrame"] || w["#vendorCancelRequestAnimationFrame"];
  }

  targetTime = 0;

  w.requestAnimationFrame || (w.requestAnimationFrame = function(callback) {
    var currentTime;
    targetTime = Math.max(targetTime + 16, currentTime = +(new Date));
    return w.setTimeout((function() {
      return callback(+(new Date));
    }), targetTime - currentTime);
  });

  w.cancelAnimationFrame || (w.cancelAnimationFrame = function(id) {
    return clearTimeout(id);
  });

  w.findClickPos = function(e) {
    var posx, posy;
    posx = 0;
    posy = 0;
    if (!e) e = window.event;
    if (e.pageX || e.pageY) {
      posx = e.pageX;
      posy = e.pageY;
    } else if (e.clientX || e.clientY) {
      posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
      posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }
    return {
      x: posx,
      y: posy
    };
  };

  w.getOffset = function(el) {
    var body, _x, _y;
    body = document.getElementsByTagName("body")[0];
    _x = 0;
    _y = 0;
    while (el && !isNaN(el.offsetLeft) && !isNaN(el.offsetTop)) {
      _x += el.offsetLeft - el.scrollLeft;
      _y += el.offsetTop - el.scrollTop;
      el = el.offsetParent;
    }
    return {
      top: _y + body.scrollTop,
      left: _x + body.scrollLeft
    };
  };

  Particle = (function() {

    function Particle(elem) {
      this.elem = elem;
      this.style = elem.style;
      this.elem.style['zIndex'] = 9999;
      this.transformX = 0;
      this.transformY = 0;
      this.transformRotation = 0;
      this.offsetTop = window.getOffset(this.elem).top;
      this.offsetLeft = window.getOffset(this.elem).left;
      this.velocityX = 0;
      this.velocityY = 0;
    }

    Particle.prototype.tick = function(blast) {
      var distX, distXS, distY, distYS, distanceWithBlast, force, forceX, forceY, previousRotation, previousStateX, previousStateY, rad, transform;
      previousStateX = this.transformX;
      previousStateY = this.transformY;
      previousRotation = this.transformRotation;
      if (this.velocityX > 1.5) {
        this.velocityX -= 1.5;
      } else if (this.velocityX < -1.5) {
        this.velocityX += 1.5;
      } else {
        this.velocityX = 0;
      }
      if (this.velocityY > 1.5) {
        this.velocityY -= 1.5;
      } else if (this.velocityY < -1.5) {
        this.velocityY += 1.5;
      } else {
        this.velocityY = 0;
      }
      if (blast != null) {
        distX = this.offsetLeft + this.transformX - blast.x;
        distY = this.offsetTop + this.transformY - blast.y;
        distXS = distX * distX;
        distYS = distY * distY;
        distanceWithBlast = distXS + distYS;
        force = 100000 / distanceWithBlast;
        if (force > 50) force = 50;
        rad = Math.asin(distYS / distanceWithBlast);
        forceY = Math.sin(rad) * force * (distY < 0 ? -1 : 1);
        forceX = Math.cos(rad) * force * (distX < 0 ? -1 : 1);
        this.velocityX = +forceX;
        this.velocityY = +forceY;
      }
      this.transformX = this.transformX + this.velocityX;
      this.transformY = this.transformY + this.velocityY;
      this.transformRotation = this.transformX * -1;
      if ((Math.abs(previousStateX - this.transformX) > 1 || Math.abs(previousStateY - this.transformY) > 1 || Math.abs(previousRotation - this.transformRotation) > 1) && ((this.transformX > 1 || this.transformX < -1) || (this.transformY > 1 || this.transformY < -1))) {
        transform = "translate(" + this.transformX + "px, " + this.transformY + "px) rotate(" + this.transformRotation + "deg)";
        this.style['MozTransform'] = transform;
        this.style['OTransform'] = transform;
        this.style['WebkitTransform'] = transform;
        this.style['msTransform'] = transform;
        return this.style['transform'] = transform;
      }
    };

    return Particle;

  })();

  this.Particle = Particle;

  Bomb = (function() {

    Bomb.SIZE = 50;

    function Bomb(x, y) {
      this.countDown = __bind(this.countDown, this);
      this.drop = __bind(this.drop, this);      this.pos = {
        x: x,
        y: y
      };
      this.body = document.getElementsByTagName("body")[0];
      this.state = 'planted';
      this.count = 3;
      this.drop();
    }

    Bomb.prototype.drop = function() {
      this.bomb = document.createElement("div");
      this.bomb.innerHTML = this.count;
      this.body.appendChild(this.bomb);
      this.bomb.style['zIndex'] = "9999";
      this.bomb.style['fontFamily'] = "verdana";
      this.bomb.style['width'] = "" + Bomb.SIZE + "px";
      this.bomb.style['height'] = "" + Bomb.SIZE + "px";
      this.bomb.style['display'] = 'block';
      this.bomb.style['borderRadius'] = "" + Bomb.SIZE + "px";
      this.bomb.style['WebkitBorderRadius'] = "" + Bomb.SIZE + "px";
      this.bomb.style['MozBorderRadius'] = "" + Bomb.SIZE + "px";
      this.bomb.style['fontSize'] = '18px';
      this.bomb.style['color'] = '#fff';
      this.bomb.style['lineHeight'] = "" + Bomb.SIZE + "px";
      this.bomb.style['background'] = '#000';
      this.bomb.style['position'] = 'absolute';
      this.bomb.style['top'] = "" + (this.pos.y - Bomb.SIZE / 2) + "px";
      this.bomb.style['left'] = "" + (this.pos.x - Bomb.SIZE / 2) + "px";
      this.bomb.style['textAlign'] = "center";
      this.bomb.style['WebkitUserSelect'] = 'none';
      this.bomb.style['font-weight'] = 700;
      return setTimeout(this.countDown, 1000);
    };

    Bomb.prototype.countDown = function() {
      this.state = 'ticking';
      this.count--;
      this.bomb.innerHTML = this.count;
      if (this.count > 0) {
        return setTimeout(this.countDown, 1000);
      } else {
        return this.explose();
      }
    };

    Bomb.prototype.explose = function() {
      this.bomb.innerHTML = '';
      return this.state = 'explose';
    };

    Bomb.prototype.exploded = function() {
      this.state = 'exploded';
      this.bomb.innerHTML = '';
      this.bomb.style['fontSize'] = '12px';
      return this.bomb.style['opacity'] = 0.05;
    };

    return Bomb;

  })();

  this.Bomb = Bomb;

  Explosion = (function() {

    function Explosion() {
      this.tick = __bind(this.tick, this);
      this.dropBomb = __bind(this.dropBomb, this);
      var char, confirmation, style, _ref2,
        _this = this;
      if (window.FONTBOMB_LOADED) return;
      window.FONTBOMB_LOADED = true;
      if (!window.FONTBOMB_HIDE_CONFIRMATION) confirmation = true;
      this.bombs = [];
      this.body = document.getElementsByTagName("body")[0];
      if ((_ref2 = this.body) != null) {
        _ref2.onclick = function(event) {
          return _this.dropBomb(event);
        };
      }
      this.body.addEventListener("touchstart", function(event) {
        return _this.touchEvent = event;
      });
      this.body.addEventListener("touchmove", function(event) {
        _this.touchMoveCount || (_this.touchMoveCount = 0);
        return _this.touchMoveCount++;
      });
      this.body.addEventListener("touchend", function(event) {
        if (_this.touchMoveCount < 2) _this.dropBomb(_this.touchEvent);
        return _this.touchMoveCount = 0;
      });
      this.explosifyNodes(this.body.childNodes);
      this.chars = (function() {
        var _j, _len2, _ref3, _results;
        _ref3 = document.getElementsByTagName('particle');
        _results = [];
        for (_j = 0, _len2 = _ref3.length; _j < _len2; _j++) {
          char = _ref3[_j];
          _results.push(new Particle(char, this.body));
        }
        return _results;
      }).call(this);
      this.tick();
      if (confirmation != null) {
        style = document.createElement('style');
        style.innerHTML = "div#fontBombConfirmation {\n  position: absolute;\n  top: -200px;\n  left: 0px;\n  right: 0px;\n  bottom: none;\n  width: 100%;\n  padding: 18px;\n  margin: 0px;\n  background: #e8e8e8;\n  text-align: center;\n  font-size: 14px;\n  line-height: 14px;\n  font-family: verdana, sans-serif;\n  color: #000;\n  -webkit-transition: all 1s ease-in-out;\n  -moz-transition: all 1s ease-in-out;\n  -o-transition: all 1s ease-in-out;\n  -ms-transition: all 1s ease-in-out;\n  transition: all 1s ease-in-out;\n  -webkit-box-shadow: 0px 3px 3px rgba(0,0,0,0.20);\n  -moz-box-shadow: 0px 3px 3px rgba(0,0,0,0.20);\n  box-shadow: 0px 3px 3px rgba(0,0,0,0.20);\n  z-index: 100000002;\n}\ndiv#fontBombConfirmation span,div#fontBombConfirmation a {\n  color: #fe3a1a;\n}\ndiv#fontBombConfirmation.show {\n  top:0px;\n  display:block;\n}";
        document.head.appendChild(style);
        this.confirmation = document.createElement("div");
        this.confirmation.id = 'fontBombConfirmation';
        this.confirmation.innerHTML = "fontBomb loaded! Click anywhere to destroy " + (document.title.substring(0, 50));
        this.body.appendChild(this.confirmation);
        setTimeout(function() {
          return _this.confirmation.className = 'show';
        }, 10);
        setTimeout(function() {
          _this.confirmation.className = '';
          return setTimeout(function() {
            _this.confirmation.innerHTML = "If you think fontBomb is a blast, follow me on twitter @plehoux for my next experiment!";
            _this.confirmation.className = 'show';
            return setTimeout(function() {
              return _this.confirmation.className = '';
            }, 20000);
          }, 5000);
        }, 5000);
      }
    }

    Explosion.prototype.explosifyNodes = function(nodes) {
      var node, _j, _len2, _results;
      _results = [];
      for (_j = 0, _len2 = nodes.length; _j < _len2; _j++) {
        node = nodes[_j];
        _results.push(this.explosifyNode(node));
      }
      return _results;
    };

    Explosion.prototype.explosifyNode = function(node) {
      var name, newNode, _j, _len2, _ref2;
      _ref2 = ['script', 'style', 'iframe', 'canvas', 'video', 'audio', 'textarea', 'embed', 'object', 'select', 'area', 'map', 'input'];
      for (_j = 0, _len2 = _ref2.length; _j < _len2; _j++) {
        name = _ref2[_j];
        if (node.nodeName.toLowerCase() === name) return;
      }
      switch (node.nodeType) {
        case 1:
          return this.explosifyNodes(node.childNodes);
        case 3:
          if (!/^\s*$/.test(node.nodeValue)) {
            if (node.parentNode.childNodes.length === 1) {
              return node.parentNode.innerHTML = this.explosifyText(node.nodeValue);
            } else {
              newNode = document.createElement("particles");
              newNode.innerHTML = this.explosifyText(node.nodeValue);
              return node.parentNode.replaceChild(newNode, node);
            }
          }
      }
    };

    Explosion.prototype.explosifyText = function(string) {
      var char, chars, index;
      chars = (function() {
        var _len2, _ref2, _results;
        _ref2 = string.split('');
        _results = [];
        for (index = 0, _len2 = _ref2.length; index < _len2; index++) {
          char = _ref2[index];
          if (!/^\s*$/.test(char)) {
            _results.push("<particle style='display:inline-block;'>" + char + "</particle>");
          } else {
            _results.push(' ');
          }
        }
        return _results;
      })();
      chars = chars.join('');
      chars = (function() {
        var _len2, _ref2, _results;
        _ref2 = chars.split(' ');
        _results = [];
        for (index = 0, _len2 = _ref2.length; index < _len2; index++) {
          char = _ref2[index];
          if (!/^\s*$/.test(char)) {
            _results.push("<word style='white-space:nowrap'>" + char + "</word>");
          } else {
            _results.push(char);
          }
        }
        return _results;
      })();
      return chars.join(' ');
    };

    Explosion.prototype.dropBomb = function(event) {
      var pos;
      pos = window.findClickPos(event);
      this.bombs.push(new Bomb(pos.x, pos.y));
      if (window.FONTBOMB_PREVENT_DEFAULT) return event.preventDefault();
    };

    Explosion.prototype.tick = function() {
      var bomb, char, _j, _k, _l, _len2, _len3, _len4, _ref2, _ref3, _ref4;
      _ref2 = this.bombs;
      for (_j = 0, _len2 = _ref2.length; _j < _len2; _j++) {
        bomb = _ref2[_j];
        if (bomb.state === 'explose') {
          bomb.exploded();
          this.blast = bomb.pos;
        }
      }
      if (this.blast != null) {
        _ref3 = this.chars;
        for (_k = 0, _len3 = _ref3.length; _k < _len3; _k++) {
          char = _ref3[_k];
          char.tick(this.blast);
        }
        this.blast = null;
      } else {
        _ref4 = this.chars;
        for (_l = 0, _len4 = _ref4.length; _l < _len4; _l++) {
          char = _ref4[_l];
          char.tick();
        }
      }
      return requestAnimationFrame(this.tick);
    };

    return Explosion;

  })();

  new Explosion();

});


text:
module Main.Setting where

import Foreign.C.Types

xSize :: Int
xSize = 100

ySize :: Int
ySize = 100

wSize :: CInt
wSize = 600


text:
require 'test_helper'
class TestCSV2Strings < Test::Unit::TestCase

  def test_converting_csv_to_dotstrings
    csv_file = "test/data/test_data.csv"
    converter = Babelish::CSV2Strings.new(csv_file, 'English' => [:en])
    converter.convert
    assert File.exist?("en.lproj/Localizable.strings"), "the ouptut file does not exist"
    system("rm -rf en.lproj/")
  end

  def test_converting_csv_to_dotstrings_one_output_option
    csv_file = "test/data/test_data.csv"
    single_file = 'myApp.strings'
    converter = Babelish::CSV2Strings.new(csv_file,
    {'English' => [:en]},
    :output_basename => 'myApp',
    :ignore_lang_path => true)
    converter.convert
    assert File.exist?(single_file), "the ouptut file does not exist"
    system("rm -f #{single_file}")
  end

  def test_converting_csv_to_dotstrings_default_lang
    expected_output = String.new(<<-EOS)
"GREETINGS"      = "Buenos dias";
"ANOTHER_STRING" = "testEN";
    EOS
    csv_file = "test/data/test_data_multiple_langs.csv"
    spanish_file = "es.lproj/Localizable.strings"
    converter = Babelish::CSV2Strings.new(csv_file,
    {'English' => [:en], "French" => "fr", "German" => "de", "Spanish" => "es"},
    :default_lang => "English")
    converter.convert
    assert File.exist?(spanish_file), "the ouptut file does not exist"
    result = File.read(spanish_file)
    assert_equal expected_output, result
    system("rm -rf *.lproj")
  end

  def test_converting_csv_to_dotstrings_with_no_default_lang_is_empty
    expected_output = String.new(<<-EOS)
"GREETINGS"      = "Buenos dias";
"ANOTHER_STRING" = "";
    EOS
    csv_file = "test/data/test_data_multiple_langs.csv"
    spanish_file = "es.lproj/Localizable.strings"
    converter = Babelish::CSV2Strings.new(csv_file,
    {'English' => [:en], "French" => "fr", "German" => "de", "Spanish" => "es"})
    converter.convert
    assert File.exist?(spanish_file), "the ouptut file does not exist"
    result = File.read(spanish_file)
    assert_equal expected_output, result
    system("rm -rf *.lproj")
  end

  def test_converting_csv_to_dotstrings_default_lang_to_key
    expected_output = String.new(<<-EOS)
"GREETINGS"      = "Buenos dias";
"ANOTHER_STRING" = "ANOTHER_STRING";
    EOS
    csv_file = "test/data/test_data_multiple_langs.csv"
    spanish_file = "es.lproj/Localizable.strings"
    converter = Babelish::CSV2Strings.new(csv_file,
    {'English' => [:en], "French" => "fr", "German" => "de", "Spanish" => "es"},
    :default_lang => "variables")
    converter.convert
    assert File.exist?(spanish_file), "the ouptut file does not exist"
    result = File.read(spanish_file)
    assert_equal expected_output, result
    system("rm -rf *.lproj")
  end

  def test_converting_csv_to_dotstrings_keys
    expected_output = String.new(<<-EOS)
"GREETINGS"      = "Buenos dias";
"ANOTHER_STRING" = "ANOTHER_STRING";
    EOS
    csv_file = "test/data/test_data_multiple_langs.csv"
    converter = Babelish::CSV2Strings.new(csv_file,
    {'English' => [:en], "French" => "fr", "German" => "de", "Spanish" => "es"},
    :default_lang => "variables")
    converter.convert
    assert !converter.keys.empty?
    system("rm -rf *.lproj")
  end

  def test_converting_csv_to_dotstrings_with_percent
    expected_output = String.new(<<-EOS)
"GREETINGS"      = "hello_%@";
"ANOTHER_STRING" = "hello";
    EOS
    csv_file = "test/data/test_data_with_percent.csv"
    converter = Babelish::CSV2Strings.new(csv_file, "English" => [:en])
    converter.convert
    result = File.read("en.lproj/Localizable.strings")
    assert_equal expected_output, result
    system("rm -rf *.lproj")
  end

  def test_converting_csv_to_dotstrings_with_spaces
    expected_output = String.new(<<-EOS)
"GREETINGS "     = "hello ";
"ANOTHER_STRING" = " my other string with space at begin";
    EOS
    csv_file = "test/data/test_data_with_spaces.csv"
    converter = Babelish::CSV2Strings.new(csv_file, "English" => [:en])
    converter.convert
    result = File.read("en.lproj/Localizable.strings")
    assert_equal expected_output, result
    system("rm -rf *.lproj")
  end

  def test_converting_csv_to_dotstrings_with_percent_space
    expected_output = String.new(<<-EOS)
"GREETINGS"       = "you have %d points";
"ANOTHER_STRING"  = "this is a string with 10% of juice";
"ANOTHER_EXAMPLE" = "tu as fait 10% d'efforts";
    EOS
    csv_file = "test/data/test_data_with_percent_space.csv"
    converter = Babelish::CSV2Strings.new(csv_file, "English" => [:en])
    converter.convert
    result = File.read("en.lproj/Localizable.strings")
    assert_equal expected_output, result
    system("rm -rf *.lproj")
  end

  def test_converting_csv_to_dotstrings_with_stripping_option
    expected_output = String.new(<<-EOS)
"GREETINGS"      = "hello";
"ANOTHER_STRING" = "my other string with space at begin";
    EOS
    csv_file = "test/data/test_data_with_spaces.csv"
    converter = Babelish::CSV2Strings.new(csv_file, {"English" => [:en]}, :stripping => true)
    converter.convert
    result = File.read("en.lproj/Localizable.strings")
    assert_equal expected_output, result
    system("rm -rf *.lproj")
  end

  def test_converting_with_comments
    csv_file = "test/data/test_data_with_comments.csv"
    spanish_file = "fr.lproj/Localizable.strings"
    expected_output = File.read("test/data/test_data_fr_with_comments.strings")
    converter = Babelish::CSV2Strings.new(csv_file,
    {"French" => "fr"},
    :default_lang => "English", :comments_column => 5)
    converter.convert
    assert File.exist?(spanish_file), "the ouptut file does not exist"
    result = File.read(spanish_file)
    assert_equal expected_output, result
    system("rm -rf *.lproj")
  end
end


text:
package newerGameLogic;

public enum PieceEnum {
	King{public String toString(){return "K";}},
	Queen{public String toString(){return "Q";}},
	Bishop{public String toString(){return "B";}},
	Knight{public String toString(){return "N";}},
	Rook{public String toString(){return "R";}},
	Pawn{public String toString(){return "P";}}
}


text:
"""
Paging capabilities for IPython.core

Notes
-----

For now this uses IPython hooks, so it can't be in IPython.utils.  If we can get
rid of that dependency, we could move it there.
-----
"""

# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.

import os
import re
import sys
import tempfile

from io import UnsupportedOperation

from IPython import get_ipython
from IPython.core.display import display
from IPython.core.error import TryNext
from IPython.utils.data import chop
from IPython.utils.process import system
from IPython.utils.terminal import get_terminal_size
from IPython.utils import py3compat

def display_page(strng, start=0, screen_lines=25):
    """Just display, no paging. screen_lines is ignored."""
    if isinstance(strng, dict):
        data = strng
    else:
        if start:
            strng = u'\n'.join(strng.splitlines()[start:])
        data = { 'text/plain': strng }
    display(data, raw=True)

def as_hook(page_func):
    """Wrap a pager func to strip the `self` arg

    so it can be called as a hook.
    """
    return lambda self, *args, **kwargs: page_func(*args, **kwargs)

esc_re = re.compile(r"(\x1b[^m]+m)")

def page_dumb(strng, start=0, screen_lines=25):
    """Very dumb 'pager' in Python, for when nothing else works.

    Only moves forward, same interface as page(), except for pager_cmd and
    mode.
    """
    if isinstance(strng, dict):
        strng = strng.get('text/plain', '')
    out_ln  = strng.splitlines()[start:]
    screens = chop(out_ln,screen_lines-1)
    if len(screens) == 1:
        print(os.linesep.join(screens[0]))
    else:
        last_escape = ""
        for scr in screens[0:-1]:
            hunk = os.linesep.join(scr)
            print(last_escape + hunk)
            if not page_more():
                return
            esc_list = esc_re.findall(hunk)
            if len(esc_list) > 0:
                last_escape = esc_list[-1]
        print(last_escape + os.linesep.join(screens[-1]))

def _detect_screen_size(screen_lines_def):
    """Attempt to work out the number of lines on the screen.

    This is called by page(). It can raise an error (e.g. when run in the
    test suite), so it's separated out so it can easily be called in a try block.
    """
    TERM = os.environ.get('TERM',None)
    if not((TERM=='xterm' or TERM=='xterm-color') and sys.platform != 'sunos5'):
        # curses causes problems on many terminals other than xterm, and
        # some termios calls lock up on Sun OS5.
        return screen_lines_def

    try:
        import termios
        import curses
    except ImportError:
        return screen_lines_def

    # There is a bug in curses, where *sometimes* it fails to properly
    # initialize, and then after the endwin() call is made, the
    # terminal is left in an unusable state.  Rather than trying to
    # check everytime for this (by requesting and comparing termios
    # flags each time), we just save the initial terminal state and
    # unconditionally reset it every time.  It's cheaper than making
    # the checks.
    try:
        term_flags = termios.tcgetattr(sys.stdout)
    except termios.error as err:
        # can fail on Linux 2.6, pager_page will catch the TypeError
        raise TypeError('termios error: {0}'.format(err))

    try:
        scr = curses.initscr()
    except AttributeError:
        # Curses on Solaris may not be complete, so we can't use it there
        return screen_lines_def

    screen_lines_real,screen_cols = scr.getmaxyx()
    curses.endwin()

    # Restore terminal state in case endwin() didn't.
    termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
    # Now we have what we needed: the screen size in rows/columns
    return screen_lines_real
    #print '***Screen size:',screen_lines_real,'lines x',\
    #screen_cols,'columns.' # dbg

def pager_page(strng, start=0, screen_lines=0, pager_cmd=None):
    """Display a string, piping through a pager after a certain length.

    strng can be a mime-bundle dict, supplying multiple representations,
    keyed by mime-type.

    The screen_lines parameter specifies the number of *usable* lines of your
    terminal screen (total lines minus lines you need to reserve to show other
    information).

    If you set screen_lines to a number <=0, page() will try to auto-determine
    your screen size and will only use up to (screen_size+screen_lines) for
    printing, paging after that. That is, if you want auto-detection but need
    to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
    auto-detection without any lines reserved simply use screen_lines = 0.

    If a string won't fit in the allowed lines, it is sent through the
    specified pager command. If none given, look for PAGER in the environment,
    and ultimately default to less.

    If no system pager works, the string is sent through a 'dumb pager'
    written in python, very simplistic.
    """

    # for compatibility with mime-bundle form:
    if isinstance(strng, dict):
        strng = strng['text/plain']

    # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
    TERM = os.environ.get('TERM','dumb')
    if TERM in ['dumb','emacs'] and os.name != 'nt':
        print(strng)
        return
    # chop off the topmost part of the string we don't want to see
    str_lines = strng.splitlines()[start:]
    str_toprint = os.linesep.join(str_lines)
    num_newlines = len(str_lines)
    len_str = len(str_toprint)

    # Dumb heuristics to guesstimate number of on-screen lines the string
    # takes.  Very basic, but good enough for docstrings in reasonable
    # terminals. If someone later feels like refining it, it's not hard.
    numlines = max(num_newlines,int(len_str/80)+1)

    screen_lines_def = get_terminal_size()[1]

    # auto-determine screen size
    if screen_lines <= 0:
        try:
            screen_lines += _detect_screen_size(screen_lines_def)
        except (TypeError, UnsupportedOperation):
            print(str_toprint)
            return

    #print 'numlines',numlines,'screenlines',screen_lines  # dbg
    if numlines <= screen_lines :
        #print '*** normal print'  # dbg
        print(str_toprint)
    else:
        # Try to open pager and default to internal one if that fails.
        # All failure modes are tagged as 'retval=1', to match the return
        # value of a failed system command.  If any intermediate attempt
        # sets retval to 1, at the end we resort to our own page_dumb() pager.
        pager_cmd = get_pager_cmd(pager_cmd)
        pager_cmd += ' ' + get_pager_start(pager_cmd,start)
        if os.name == 'nt':
            if pager_cmd.startswith('type'):
                # The default WinXP 'type' command is failing on complex strings.
                retval = 1
            else:
                fd, tmpname = tempfile.mkstemp('.txt')
                try:
                    os.close(fd)
                    with open(tmpname, 'wt') as tmpfile:
                        tmpfile.write(strng)
                        cmd = "%s < %s" % (pager_cmd, tmpname)
                    # tmpfile needs to be closed for windows
                    if os.system(cmd):
                        retval = 1
                    else:
                        retval = None
                finally:
                    os.remove(tmpname)
        else:
            try:
                retval = None
                # if I use popen4, things hang. No idea why.
                #pager,shell_out = os.popen4(pager_cmd)
                pager = os.popen(pager_cmd, 'w')
                try:
                    pager_encoding = pager.encoding or sys.stdout.encoding
                    pager.write(strng)
                finally:
                    retval = pager.close()
            except IOError as msg:  # broken pipe when user quits
                if msg.args == (32, 'Broken pipe'):
                    retval = None
                else:
                    retval = 1
            except OSError:
                # Other strange problems, sometimes seen in Win2k/cygwin
                retval = 1
        if retval is not None:
            page_dumb(strng,screen_lines=screen_lines)

def page(data, start=0, screen_lines=0, pager_cmd=None):
    """Display content in a pager, piping through a pager after a certain length.

    data can be a mime-bundle dict, supplying multiple representations,
    keyed by mime-type, or text.

    Pager is dispatched via the `show_in_pager` IPython hook.
    If no hook is registered, `pager_page` will be used.
    """
    # Some routines may auto-compute start offsets incorrectly and pass a
    # negative value.  Offset to 0 for robustness.
    start = max(0, start)

    # first, try the hook
    ip = get_ipython()
    if ip:
        try:
            ip.hooks.show_in_pager(data, start=start, screen_lines=screen_lines)
            return
        except TryNext:
            pass

    # fallback on default pager
    return pager_page(data, start, screen_lines, pager_cmd)

def page_file(fname, start=0, pager_cmd=None):
    """Page a file, using an optional pager command and starting line.
    """

    pager_cmd = get_pager_cmd(pager_cmd)
    pager_cmd += ' ' + get_pager_start(pager_cmd,start)

    try:
        if os.environ['TERM'] in ['emacs','dumb']:
            raise EnvironmentError
        system(pager_cmd + ' ' + fname)
    except:
        try:
            if start > 0:
                start -= 1
            page(open(fname).read(),start)
        except:
            print('Unable to show file',repr(fname))

def get_pager_cmd(pager_cmd=None):
    """Return a pager command.

    Makes some attempts at finding an OS-correct one.
    """
    if os.name == 'posix':
        default_pager_cmd = 'less -R'  # -R for color control sequences
    elif os.name in ['nt','dos']:
        default_pager_cmd = 'type'

    if pager_cmd is None:
        try:
            pager_cmd = os.environ['PAGER']
        except:
            pager_cmd = default_pager_cmd

    if pager_cmd == 'less' and '-r' not in os.environ.get('LESS', '').lower():
        pager_cmd += ' -R'

    return pager_cmd

def get_pager_start(pager, start):
    """Return the string for paging files with an offset.

    This is the '+N' argument which less and more (under Unix) accept.
    """

    if pager in ['less','more']:
        if start:
            start_string = '+' + str(start)
        else:
            start_string = ''
    else:
        start_string = ''
    return start_string

# (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch()
if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
    import msvcrt
    def page_more():
        """ Smart pausing between pages

        @return:    True if need print more lines, False if quit
        """
        sys.stdout.write('---Return to continue, q to quit--- ')
        ans = msvcrt.getwch()
        if ans in ("q", "Q"):
            result = False
        else:
            result = True
        sys.stdout.write("\b"*37 + " "*37 + "\b"*37)
        return result
else:
    def page_more():
        ans = py3compat.input('---Return to continue, q to quit--- ')
        if ans.lower().startswith('q'):
            return False
        else:
            return True

def snip_print(str,width = 75,print_full = 0,header = ''):
    """Print a string snipping the midsection to fit in width.

    print_full: mode control:

      - 0: only snip long strings
      - 1: send to page() directly.
      - 2: snip long strings and ask for full length viewing with page()

    Return 1 if snipping was necessary, 0 otherwise."""

    if print_full == 1:
        page(header+str)
        return 0

    print(header, end=' ')
    if len(str) < width:
        print(str)
        snip = 0
    else:
        whalf = int((width -5)/2)
        print(str[:whalf] + ' <...> ' + str[-whalf:])
        snip = 1
    if snip and print_full == 2:
        if py3compat.input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
            page(str)
    return snip


text:
<?php
namespace Core\BetBundle;

use Symfony\Component\DomCrawler\Crawler;

class WebScrapper
{
  public function getPremierLeagueFixtures(){
    $fixtures = array();
    $crawler = new Crawler(file_get_contents('http://www.premierleague.com/en-gb/matchday/matches.html'));
    $tables = $crawler->filter('table.contentTable');
    foreach ($tables as $table){
      $node = new Crawler($table);
      $th = $node->filter('th');
      $date = null;
      foreach($th as $header){
        $date = date('Y-m-d',strtotime($header->textContent));
      }
      $rows = $node->filter('tr');
      foreach($rows as $row){
        $childrenCount = $row->childNodes->length;
        $match = array();
        foreach($row->childNodes as $td){
          if ($childrenCount != 1){
            if ($td instanceof \DOMElement && $td->getAttribute('class') == 'time'){
              $match['date'] = $date.' '.trim($td->textContent).':00';
            }
            if ($td instanceof \DOMElement && $td->getAttribute('class') == 'clubs'){
              list($match['team_1'], $match['team_2'])
                = explode(' v ', trim($td->textContent));
            }
          }
        }
        if (!empty($match)){
          $fixtures[] = $match;
        }
      }
    }
    return $fixtures;
  }

  public function getPremierLeagueStandings(){
    $crawler = new Crawler(file_get_contents('http://www.fifa.com/associations/association=eng/nationalleague/standings.html'));
    $table = $crawler->filter('table.maNlStandings');
    if (count($table)){
      foreach ($table as $node){
        $node->setAttribute('class', 'table table-hover table-bordered standings');
        $ths = $node->getElementsByTagName('th');
        foreach($ths as $th){
          if ($th->getAttribute('class') == 'maNlStandingsTitleDiff noHover'){
            $th->parentNode->removeChild($th);
          }
        }
        $tds = $node->getElementsByTagName('td');
        foreach($tds as $td){
          if ($td->getAttribute('class') == 'maNlStandingsDiff'){
            $td->parentNode->removeChild($td);
          }
        }
        $tableNode = $node;
      }
      $header = '
Current standings(Last update: '.date('Y-m-d H:i').')
';
      return $header . $tableNode->ownerDocument->saveHTML($tableNode);
    }else{
      return '
EPIC FAIL!
        Scrapping standings table went wrong! :(
Go whine about it to the author!
';
    }
  }

  public function getPremierLeagueOdds(){
    $crawler = new Crawler(file_get_contents('https://sports.bwin.com/en/sports/4/46/betting/premier-league'));
    $odds = $crawler->filter('table.options span.odds');
    if (count($odds)){
      $matches = array();
      $currentMatch = array();
      $label = '';
      foreach ($odds as $key => $odd){
        $currentMatch[] = $odd->textContent;
        $label .= $this->_normalizeClubName($odd->nextSibling->textContent);
        if (($key+1) % 3 == 0){
          $matches[$label] = $currentMatch;
          $currentMatch = array();
          $label = '';
        }
      }
    }else{
     throw new \Exception('FAIL! Scrapping odds from bwin.com went wrong!');
    }
    return $matches;
  }

  public function getPremierLeagueResults($emptyMatches){
    if (!empty($emptyMatches)){
      $crawler = new Crawler(file_get_contents('http://www.livefootball.com/football/england/premier-league/results/7-days/'));
      $results = $crawler->filter('dd.mElO1');
      $matchesScores = array();
      $label = '';
      foreach($results as $result){
        $label .= $this->_normalizeClubName($result->textContent).'X'.
          $this->_normalizeClubName($result->nextSibling->nextSibling->textContent);
        $matchesScores[$label] = explode(' - ', $result->nextSibling->lastChild->textContent);
        $label = '';
      }
      if (!empty($matchesScores)){
        foreach($emptyMatches as &$emptyMatch){
          $result = $matchesScores[$emptyMatch->getTeam1().'X'.$emptyMatch->getTeam2()];
          $emptyMatch->setScore1($result[0]);
          $emptyMatch->setScore2($result[1]);
        }
      }
    }
    return $emptyMatches;
  }

  /**
   * Making up for diffrences in club names between premiership.com and bwin.com
   * @param string $original
   * @return string club name modified to match the style from premiership.com fixtures
   */
  private function _normalizeClubName($original){
    switch($original){
    case 'Arsenal FC': return 'Arsenal'; break;
    case 'Chelsea FC': return 'Chelsea'; break;
    case 'Fulham FC': return 'Fulham'; break;
    case 'Liverpool FC': return 'Liverpool'; break;
    case 'Manchester City': return 'Man City'; break;
    case 'Manchester Utd': return 'Man Utd'; break;
    case 'Manchester United': return 'Man Utd'; break;
    case 'Newcastle United': return 'Newcastle'; break;
    case 'Norwich City': return 'Norwich'; break;
    case 'Queens Park Rangers': return 'QPR'; break;
    case 'Southampton FC': return 'Southampton'; break;
    case 'Stoke City': return 'Stoke'; break;
    case 'Swansea City': return 'Swansea'; break;
    case 'Tottenham Hotspur': return 'Tottenham'; break;
    case 'West Bromwich': return 'West Brom'; break;
    case 'West Bromwich Albion': return 'West Brom'; break;
    case 'West Ham United': return 'West Ham'; break;
    case 'Wigan Athletic': return 'Wigan'; break;
    default: return $original;
    }
  }
}


text:
package com.editize.editorkit;

import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import javax.swing.JEditorPane;
import javax.swing.event.CaretEvent;
import javax.swing.event.DocumentEvent;
import javax.swing.text.*;
import javax.swing.text.html.HTML;

import com.editize.EditizeDocument;
import javax.swing.text.AbstractDocument.BranchElement;

/**
 * Displays a dialog that allows the end user to edit a table's properties.
 *
 * @author Kevin Yank
 */

public class EditTableAction extends BooleanStateAwareTextAction
{
	private EditTableDialog dlg;

	public EditTableAction()
	{
		super("edit-table");
	}

	/**
	 * Performs the action.
	 * @param e ActionEvent
	 */
	public void actionPerformed(ActionEvent e)
	{
		final JEditorPane target = getAssignedEditor(e);
		if (target != null)
		{
			if ((! target.isEditable()) || (! target.isEnabled()))
			{
				target.getToolkit().beep();
				return;
			}

			EditizeDocument doc = getEditizeDocument(target);
			Element table = doc.getParagraphElement(target.
					getSelectionStart());

			// Detect table
			while (table != null &&
				   EditizeEditorKit.getElementName(table) != HTML.Tag.TABLE)
			{
				table = table.getParentElement();
			}
			if (table == null) {
				// Not inside a table!
				target.getToolkit().beep();
				return;
			}

			// Display table editing dialog
			if (dlg == null) dlg = new EditTableDialog(target);
			dlg.init(table);
			dlg.show();

			if (dlg.getCloseOption() == dlg.OK) {
				MutableAttributeSet atts = new SimpleAttributeSet();

				// Tag
				atts.addAttribute(StyleConstants.NameAttribute, HTML.Tag.TABLE);

				// Border
				int border;
				try {
					border = Integer.parseInt(dlg.getTableBorder());
				} catch (NumberFormatException ex) {
					border = 0;
				}
				if (border == 0) {
					atts.addAttribute("trueborder", "" + border);
					atts.addAttribute(HTML.Attribute.BORDER, "1");
					atts.addAttributes(doc.getStyleSheet().getDeclaration("border-style: solid; border-color: #cccccc;"));
				} else {
					atts.addAttribute(HTML.Attribute.BORDER, "" + border);
				}

				// Width
				String width = dlg.getTableWidth();
				if (width != null)
					atts.addAttribute(HTML.Attribute.WIDTH, width);

				// Height
				String height = dlg.getTableHeight();
				if (height != null)
					atts.addAttribute(HTML.Attribute.HEIGHT, height);

				// Cellpadding
				String pad = dlg.getTablePadding();
				if (pad != null)
					atts.addAttribute(HTML.Attribute.CELLPADDING, pad);

				// Cellspacing
				String space = dlg.getTableSpacing();
				if (space != null)
					atts.addAttribute(HTML.Attribute.CELLSPACING, space);

				// Align
				String align = dlg.getTableAlign();
				if (align != null)
					atts.addAttribute(HTML.Attribute.ALIGN, align);

				// Summary
				String sum = dlg.getTableSummary();
				if (sum != null)
					atts.addAttribute("summary", sum);

				// Class
				String className = dlg.getTableClass();
				if (className != null)
					atts.addAttribute("class", className);

				doc.replaceBranchElement((BranchElement)table, atts);
			}

			target.requestFocus();
		}
		else
		{
			Toolkit.getDefaultToolkit().beep();
		}
	}
    public boolean getStateFromCaretLocation(DocumentEvent e)
    {
		/**@todo Implement this com.editize.editorkit.BooleanStateAwareTextAction abstract method*/
		return false;
    }
    public boolean getStateFromCaretLocation(CaretEvent e)
    {
		/**@todo Implement this com.editize.editorkit.BooleanStateAwareTextAction abstract method*/
		return false;
    }
}


text:
//
//  ACRoute.h
//  A-cyclist
//
//  Created by tunny on 15/7/29.
//  Copyright (c) 2015年 tunny. All rights reserved.
//

#import <Foundation/Foundation.h>

@class BmobObject;
@interface ACRouteModel : NSObject <NSCoding>
/** 路线名称 */
@property (nonatomic, copy) NSString *routeName;
/** 轨迹 */
@property (nonatomic, strong) NSArray *steps;
/** 里程(km) */
@property (nonatomic, copy) NSNumber *distance;
/** 耗时(h:min) */
@property (nonatomic, copy) NSString *time;
/** 耗时(单位秒) */
@property (nonatomic, copy) NSNumber *timeNumber;
/** 平均速度(km/h) */
@property (nonatomic, copy) NSNumber *averageSpeed;
/** 极速(km/h) */
@property (nonatomic, copy) NSNumber *maxSpeed;
/** 最高海拔(m) */
@property (nonatomic, copy) NSString *maxAltitude;
/** 最低海拔(m) */
@property (nonatomic, copy) NSString *minAltitude;
/** 累计上升海拔(m) */
@property (nonatomic, copy) NSString *ascendAltitude;

/** 上坡耗时 */
@property (nonatomic, copy) NSString *ascendTime;
/** 上坡距离(km) */
@property (nonatomic, copy) NSString *ascendDistance;
/** 平地耗时 */
@property (nonatomic, copy) NSString *flatTime;
/** 平地距离(km) */
@property (nonatomic, copy) NSString *flatDistance;
/** 下坡耗时 */
@property (nonatomic, copy) NSString *descendTime;
/** 下坡距离(km) */
@property (nonatomic, copy) NSString *descendDistance;

/** 卡路里计算(kcal) */
@property (nonatomic, copy) NSNumber *kcal;

/** 用户的id */
@property (nonatomic, copy) NSString *userObjectId;

/** 是否共享 */
@property (nonatomic, assign) NSNumber *isShared;
/** personSharedRouteId */
@property (nonatomic, copy) NSString *personSharedRouteId;

/** 唯一键(用来从本地缓存中取出对应的路线) */
@property (nonatomic, copy) NSString *routeOne;
/** 数据库中存储的routeid */
@property (nonatomic, copy) NSString *objectId;
/** 骑行开始时间 */
@property (nonatomic, strong) NSDate *cyclingStartTime;
/** 骑行结束时间 */
@property (nonatomic, strong) NSDate *cyclingEndTime;

/** 将bmobObject对象转换成Route对象 */
+ (ACRouteModel *)routeModelWithBmobObject:(BmobObject *)bmobObj;

/** 将bmobObject对象数组转换成Route对象数组 */
+ (NSArray *)routeModelArrayWithBmobObjectArray:(NSArray *)bmobArray;
@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2018 NAVER Corp.
  ~
  ~ 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.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.navercorp.pinpoint</groupId>
        <artifactId>pinpoint-hbase2-module</artifactId>
        <version>2.5.0-SNAPSHOT</version>
    </parent>

    <artifactId>pinpoint-hbase2-collector</artifactId>
    <packaging>jar</packaging>

    <properties>
        <jdk.version>11</jdk.version>
        <jdk.home>${env.JAVA_11_HOME}</jdk.home>

        <javax.servlet.version>${javax.servlet4.version}</javax.servlet.version>
        <log4j2.version>${log4j2-jdk8.version}</log4j2.version>

        <pinpoint.collector.executable.name>${project.artifactId}-boot-${project.version}</pinpoint.collector.executable.name>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.navercorp.pinpoint</groupId>
            <artifactId>pinpoint-collector</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.hbase</groupId>
                    <artifactId>hbase-shaded-client</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.codehaus.jackson</groupId>
                    <artifactId>jackson-core-asl</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-client</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.navercorp.pinpoint.collector.Hbase2CollectorApp</mainClass>
                    <outputDirectory>${project.build.directory}/deploy</outputDirectory>
                    <executable>true</executable>
                    <attach>false</attach>
                    <finalName>${pinpoint.collector.executable.name}</finalName>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
package com.everis.everledger.ifaces.account;

import java.util.Collection;

/**
 * This interface defines a simple NON-normative
 * example contract that an AccountManger must
 * implement for local NON-ILP related operations.
 * Most probably any ledger will implement other interfaces
 *
 * The concrete implementation, on the otherside, must
 * also implement the standard/normative
 * IfaceILPSpecAccountManager in order to provide support
 * for the Interledger ILP protocol.
 * See SimpleLedgerAccountManager for more info.
 *
 */
public interface IfaceLocalAccountManager {

    int getTotalAccounts();

    boolean hasAccount(String name);

    IfaceAccount getAccountByName(String name);

    Collection<IfaceLocalAccount> getAccounts(int page, int pageSize);

    // If update == false and account already registered => throw exception
    IfaceAccount store(IfaceAccount account, boolean update);
}


text:
package com.bstek.designer.core.surface

import java.awt._
import java.util
import java.util.List
import javax.swing._

import com.bstek.designer.core.palette.{DoradoPaletteGroup, DoradoPaletteToolWindowContent}
import com.bstek.designer.core.{AbstractDoradoToolWindowManager, DoradoDesignerEditor}
import com.intellij.designer._
import com.intellij.designer.actions.DesignerActionPanel
import com.intellij.designer.componentTree.TreeComponentDecorator
import com.intellij.designer.designSurface._
import com.intellij.designer.designSurface.tools._
import com.intellij.designer.model._
import com.intellij.designer.palette.PaletteItem
import com.intellij.designer.propertyTable.InplaceContext
import com.intellij.openapi.actionSystem._
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.module.{Module, ModuleUtilCore}
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ThreeComponentsSplitter
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.{ReadonlyStatusHandler, VirtualFile}
import com.intellij.ui.components.JBLayeredPane
import com.intellij.util.ui.{AsyncProcessIcon, UIUtil}
import com.intellij.util.{ArrayUtil, ThrowableRunnable}
import org.jetbrains.annotations.{NonNls, Nullable}

import scala.beans.BeanProperty

/**
 * 编辑器主面板基类
 * Created by robin on 13-12-5.
 */
abstract class DoradoDesignerEditorPanel(@BeanProperty val editor: DoradoDesignerEditor, @BeanProperty val project: Project, val module: Module, @BeanProperty val file: VirtualFile) extends JPanel with DataProvider with ModuleProvider with RadPropertyContext {

  private final val LOG: Logger = Logger.getInstance("#com.intellij.designer.designSurface.DesignerEditorPanel")

  protected final val LAYER_COMPONENT: Integer = JLayeredPane.DEFAULT_LAYER

  protected final val LAYER_DECORATION: Integer = JLayeredPane.POPUP_LAYER

  protected final val LAYER_FEEDBACK: Integer = JLayeredPane.DRAG_LAYER

  //protected final val LAYER_GLASS: Integer = LAYER_FEEDBACK + 100

  //protected final val LAYER_INPLACE_EDITING: Integer = LAYER_GLASS + 100

  //private final val LAYER_PROGRESS: Integer = LAYER_INPLACE_EDITING + 100

  private final val DESIGNER_CARD: String = "designer"

  private final val ERROR_CARD: String = "error"

  private final val ERROR_STACK_CARD: String = "stack"

  private final val ERROR_NO_STACK_CARD: String = "no_stack"

  private final val myEditor: DoradoDesignerEditor = null

  private final val myProject: Project = null

  private var myModule: Module = null

  //protected final val myFile: VirtualFile = null

  private final val myLayout: CardLayout = new CardLayout

  private final val doradoContentSplitter: ThreeComponentsSplitter = new ThreeComponentsSplitter

  private final val myPanel: JPanel = new JPanel(myLayout)

  private var myDesignerCard: JPanel = null

  protected var myActionPanel: DesignerActionPanel = null

  protected var myHorizontalCaption: CaptionPanel = null

  protected var myVerticalCaption: CaptionPanel = null

  protected var myScrollPane: JScrollPane = null

  protected var myLayeredPane: JLayeredPane = null

  protected var myGlassLayer: GlassLayer = null

  private var myDecorationLayer: DecorationLayer = null

  private var myFeedbackLayer: FeedbackLayer = null

  private var myInplaceEditingLayer: InplaceEditingLayer = null

  protected var myToolProvider: ToolProvider = null

  @BeanProperty var mySurfaceArea: EditableArea = null

  @BeanProperty var myRootComponent: RadComponent = _

  protected var myQuickFixManager: QuickFixManager = null

  private var myActivePaletteItem: PaletteItem = null

  private var myExpandedComponents: List[_] = null

  private val mySelectionPropertyMap: java.util.Map[String, com.intellij.designer.model.Property[_]] = new util.HashMap[String, com.intellij.designer.model.Property[_]]()

  //private var myExpandedState: Array[Array[Int]] = nullArray

  private var mySelectionState: Array[Array[Int]] = null

  //private final val mySourceSelectionState: Map[String, Array[Array[Int]]] = new FixedHashMap(16)

  //private var myWarnAction: DesignerEditorPanel#FixableMessageAction = null

  private var myErrorPanel: JPanel = null

  protected var myErrorMessages: JPanel = null

  private var myErrorStackPanel: JPanel = null

  private var myErrorStackLayout: CardLayout = null

  private var myErrorStack: JTextArea = null

  private var myProgressPanel: JPanel = null

  private var myProgressIcon: AsyncProcessIcon = null

  private var myProgressMessage: JLabel = null

  //--初始化面板界面
  initUI

  //myToolProvider.loadDefaultTool

  private def initUI {
    setLayout(new BorderLayout)
    doradoContentSplitter.setDividerWidth(0)
    doradoContentSplitter.setDividerMouseZoneSize(Registry.intValue("ide.splitter.mouseZone"))
    add(doradoContentSplitter, BorderLayout.CENTER)
    createDesignerCard
    //    createErrorCard
    //    createProgressPanel
    //--将编辑器附属的两个子窗口通过事件分派线程完成操作,达到界面流畅运行
    UIUtil.invokeLaterIfNeeded(new Runnable {
      def run {
        val designer: DoradoDesignerEditorPanel = DoradoDesignerEditorPanel.this
        //--通过属性窗体管理类完成编辑器与属性工具窗体的绑定
        //--通过复写getDoradoDesignerWindowManager来完成子类个性化的属性设计器
        getDoradoDesignerWindowManager.bind(designer)
        //--通过调色版窗体管理类完成编辑器与调色板工具窗体的绑定
        getPaletteWindowManager.bind(designer)
      }
    })
  }

  private def createDesignerCard {
    val panel: JPanel = new JPanel(new FillLayout)
    doradoContentSplitter.setInnerComponent(panel)
    //    val myLayeredPane = new MyLayeredPane
    //    mySurfaceArea = createEditableArea
    myToolProvider = createToolProvider
    //
    //    myGlassLayer = new GlassLayer(myToolProvider, mySurfaceArea)
    //    myLayeredPane.add(myGlassLayer, LAYER_GLASS)
    //    myDecorationLayer = createDecorationLayer
    //
    //    myLayeredPane.add(myDecorationLayer, LAYER_DECORATION)
    //    myFeedbackLayer = createFeedbackLayer
    //
    //    myLayeredPane.add(myFeedbackLayer, LAYER_FEEDBACK)
    //    myInplaceEditingLayer = createInplaceEditingLayer
    //
    //    myLayeredPane.add(myInplaceEditingLayer, LAYER_INPLACE_EDITING)
    //
    //    val content: JPanel = new JPanel(new GridBagLayout)
    //    val gbc: GridBagConstraints = new GridBagConstraints
    //    gbc.gridx = 0
    //    gbc.gridy = 1
    //    gbc.fill = GridBagConstraints.VERTICAL
    //
    //    myVerticalCaption = createCaptionPanel(false)
    //    content.add(myVerticalCaption, gbc)
    //    gbc.gridx = 1
    //    gbc.gridy = 0
    //    gbc.fill = GridBagConstraints.HORIZONTAL
    //
    //    myHorizontalCaption = createCaptionPanel(true)
    //    content.add(myHorizontalCaption, gbc)
    //    gbc.gridx = 1
    //    gbc.gridy = 1
    //    gbc.weightx = 1
    //    gbc.weighty = 1
    //    gbc.fill = GridBagConstraints.BOTH
    //    myScrollPane = createScrollPane(myLayeredPane)
    //    content.add(myScrollPane, gbc)
    //
    //    myHorizontalCaption.attachToScrollPane(myScrollPane)
    //    myVerticalCaption.attachToScrollPane(myScrollPane)
    //    myQuickFixManager = new QuickFixManager(this, myGlassLayer, myScrollPane.getViewport)
    //myActionPanel = createActionPanel
    //myWarnAction = new DesignerEditorPanel#FixableMessageAction
    panel.add(new JPanel);
    panel.add(myPanel)

    //myDesignerCard = content

    //    myPanel.add(myDesignerCard, DESIGNER_CARD)
    //    mySurfaceArea.addSelectionListener(new ComponentSelectionListener {
    //      def selectionChanged(area: EditableArea) {
    //        storeSourceSelectionState
    //      }
    //    })
  }

  final def getDoradoContentSplitter: ThreeComponentsSplitter = {
    return doradoContentSplitter
  }

  //
  //
  //  protected def createEditableArea: EditableArea = {
  //    return new DesignerEditableArea
  //  }
  //
  //
  protected def createToolProvider: ToolProvider = {
    return new DesignerToolProvider
  }

  //
  //
  //  protected def createDecorationLayer: DecorationLayer = {
  //    return new DecorationLayer(this, mySurfaceArea)
  //  }
  //
  //
  //  protected def createFeedbackLayer: FeedbackLayer = {
  //    return new FeedbackLayer
  //  }
  //
  //
  //  protected def createInplaceEditingLayer: InplaceEditingLayer = {
  //    return new InplaceEditingLayer(this)
  //  }
  //
  //
  //  protected def createCaptionPanel(horizontal: Boolean): CaptionPanel = {
  //    return new CaptionPanel(this, horizontal, true)
  //  }
  //
  //
  //  protected def createScrollPane(@NotNull content: JLayeredPane): JScrollPane = {
  //    val scrollPane: JScrollPane = ScrollPaneFactory.createScrollPane(content)
  //    scrollPane.setBackground(new JBColor(Color.WHITE, UIUtil.getListBackground))
  //    return scrollPane
  //  }
  //
  //
  //    protected def createActionPanel: DesignerActionPanel = {
  //      return new DesignerActionPanel(this, myGlassLayer)
  //    }

  //    final def getActivePaletteItem: PaletteItem = {
  //      return myActivePaletteItem
  //    }
  //

  //    final def activatePaletteItem(paletteItem: PaletteItem) {
  //      myActivePaletteItem = paletteItem
  //      if (paletteItem != null) {
  //        myToolProvider.setActiveTool(new CreationTool(true, createCreationFactory(paletteItem)))
  //      }
  //      else if (myToolProvider.getActiveTool.isInstanceOf[CreationTool]) {
  //        myToolProvider.loadDefaultTool
  //      }
  //    }

  //
  //  protected final def showDesignerCard {
  //    myErrorMessages.removeAll
  //    myErrorStack.setText(null)
  //    myLayeredPane.revalidate
  //    myHorizontalCaption.update
  //    myVerticalCaption.update
  //    myLayout.show(myPanel, DESIGNER_CARD)
  //  }
  //
  //
  //  private def createErrorCard {
  //    myErrorPanel = new JPanel(new BorderLayout)
  //    myErrorMessages = new JPanel(new VerticalFlowLayout(VerticalFlowLayout.TOP, 10, 5, true, false))
  //    myErrorPanel.add(myErrorMessages, BorderLayout.PAGE_START)
  //    myErrorStack = new JTextArea(50, 20)
  //    myErrorStack.setEditable(false)
  //    myErrorStackLayout = new CardLayout
  //    myErrorStackPanel = new JPanel(myErrorStackLayout)
  //    myErrorStackPanel.add(new JLabel, ERROR_NO_STACK_CARD)
  //    myErrorStackPanel.add(ScrollPaneFactory.createScrollPane(myErrorStack), ERROR_STACK_CARD)
  //    myErrorPanel.add(myErrorStackPanel, BorderLayout.CENTER)
  //    myPanel.add(myErrorPanel, ERROR_CARD)
  //  }
  //
  //
  final def showError(message: String, e: Throwable) {
    //    if (isProjectClosed) {
    //      return
    //    }
    //    while (e.isInstanceOf[InvocationTargetException]) {
    //      //if (e.getCause == null) {
    //      //  break //todo: break is not supported
    //      // }
    //      val e = e.getCause
    //    }
    //    val info: DesignerEditorPanel.ErrorInfo = new DesignerEditorPanel.ErrorInfo
    //    info.myMessage = ({
    //      info.myDisplayMessage = message;
    //      info.myDisplayMessage
    //    })
    //    info.myThrowable = e
    //    configureError(info)
    //    if (info.myShowMessage) {
    //      showErrorPage(info)
    //    }
    //    if (info.myShowLog) {
    //      LOG.error(LogMessageEx.createEvent(info.myDisplayMessage, info.myMessage + "\n" + ExceptionUtil.getThrowableText(info.myThrowable), getErrorAttachments(info)))
    //    }
  }

  //
  //
  //  protected def getErrorAttachments(info: DesignerEditorPanel.ErrorInfo): Array[Attachment] = {
  //    return Array[Attachment](AttachmentFactory.createAttachment(myFile))
  //  }
  //
  //
  //  protected def configureError(@NotNull info: DesignerEditorPanel.ErrorInfo)
  //
  //
  //  protected def showErrorPage(info: DesignerEditorPanel.ErrorInfo) {
  //    storeState
  //    hideProgress
  //    myRootComponent = null
  //    myErrorMessages.removeAll
  //    if (info.myShowStack) {
  //      val stream: ByteArrayOutputStream = new ByteArrayOutputStream
  //      info.myThrowable.printStackTrace(new PrintStream(stream))
  //      myErrorStack.setText(stream.toString)
  //      myErrorStackLayout.show(myErrorStackPanel, ERROR_STACK_CARD)
  //    }
  //    else {
  //      myErrorStack.setText(null)
  //      myErrorStackLayout.show(myErrorStackPanel, ERROR_NO_STACK_CARD)
  //    }
  //    addErrorMessage(new DesignerEditorPanel.FixableMessageInfo(true, info.myDisplayMessage, "", "", null, null), Messages.getErrorIcon)
  //
  //    import scala.collection.JavaConversions._
  //
  //    for (message <- info.myMessages) {
  //      addErrorMessage(message, if (message.myErrorIcon) Messages.getErrorIcon else Messages.getWarningIcon)
  //    }
  //    myErrorPanel.revalidate
  //    myLayout.show(myPanel, ERROR_CARD)
  //    getDesignerToolWindow.refresh(true)
  //    repaint
  //  }
  //
  //
  //  protected def addErrorMessage(message: DesignerEditorPanel.FixableMessageInfo, icon: Icon) {
  //    if (message.myLinkText.length > 0 || message.myAfterLinkText.length > 0) {
  //      val warnLabel: HyperlinkLabel = new HyperlinkLabel
  //      warnLabel.setOpaque(false)
  //      warnLabel.setHyperlinkText(message.myBeforeLinkText, message.myLinkText, message.myAfterLinkText)
  //      warnLabel.setIcon(icon)
  //      if (message.myQuickFix != null) {
  //        warnLabel.addHyperlinkListener(new HyperlinkListener {
  //          def hyperlinkUpdate(e: HyperlinkEvent) {
  //            if (e.getEventType eq HyperlinkEvent.EventType.ACTIVATED) {
  //              message.myQuickFix.run
  //            }
  //          }
  //        })
  //      }
  //      myErrorMessages.add(warnLabel)
  //    }
  //    else {
  //      val warnLabel: JBLabel = new JBLabel
  //      warnLabel.setOpaque(false)
  //      warnLabel.setText("" + message.myBeforeLinkText.replace("\n", "
") + "")
  //      warnLabel.setIcon(icon)
  //      myErrorMessages.add(warnLabel)
  //    }
  //    if (message.myAdditionalFixes != null && message.myAdditionalFixes.size > 0) {
  //      val fixesPanel: JPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 0))
  //      fixesPanel.setBorder(IdeBorderFactory.createEmptyBorder(3, 0, 10, 0))
  //      fixesPanel.setOpaque(false)
  //      fixesPanel.add(Box.createHorizontalStrut(icon.getIconWidth))
  //
  //      import scala.collection.JavaConversions._
  //
  //      for (pair <- message.myAdditionalFixes) {
  //        val fixLabel: HyperlinkLabel = new HyperlinkLabel
  //        fixLabel.setOpaque(false)
  //        fixLabel.setHyperlinkText(pair.getFirst)
  //        val fix: Runnable = pair.getSecond
  //        fixLabel.addHyperlinkListener(new HyperlinkListener {
  //          def hyperlinkUpdate(e: HyperlinkEvent) {
  //            if (e.getEventType eq HyperlinkEvent.EventType.ACTIVATED) {
  //              fix.run
  //            }
  //          }
  //        })
  //        fixesPanel.add(fixLabel)
  //      }
  //      myErrorMessages.add(fixesPanel)
  //    }
  //  }
  //
  //
  //  protected final def showWarnMessages(messages: List[DesignerEditorPanel.FixableMessageInfo]) {
  //    if (messages == null) {
  //      myWarnAction.hide
  //    }
  //    else {
  //      myWarnAction.show(messages)
  //    }
  //  }
  //
  //
  //  private def createProgressPanel {
  //    myProgressIcon = new AsyncProcessIcon("Designer progress")
  //    myProgressMessage = new JLabel
  //    val progressBlock: JPanel = new JPanel
  //    progressBlock.add(myProgressIcon)
  //    progressBlock.add(myProgressMessage)
  //    progressBlock.setBorder(IdeBorderFactory.createRoundedBorder)
  //    myProgressPanel = new JPanel(new GridBagLayout)
  //    myProgressPanel.add(progressBlock, new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0))
  //    myProgressPanel.setOpaque(false)
  //  }
  //
  //
  //  protected final def showProgress(message: String) {
  //    myProgressMessage.setText(message)
  //    if (myProgressPanel.getParent == null) {
  //      myGlassLayer.setEnabled(false)
  //      myProgressIcon.resume
  //      myLayeredPane.add(myProgressPanel, LAYER_PROGRESS)
  //      myLayeredPane.repaint
  //    }
  //  }
  //
  //
  //  protected final def hideProgress {
  //    myGlassLayer.setEnabled(true)
  //    myProgressIcon.suspend
  //    myLayeredPane.remove(myProgressPanel)
  //  }
  //
  //
  final def getModule: Module = {
    if (myModule.isDisposed) {
      myModule = findModule(myProject, getFile)
      if (myModule == null) {
        throw new IllegalArgumentException("No module for file " + getFile + " in project " + myProject)
      }
    }
    return myModule
  }

  protected def findModule(project: Project, file: VirtualFile): Module = {
    return ModuleUtilCore.findModuleForFile(file, project)
  }

  //  final def getEditor: DoradoDesignerEditor = {
  //    return myEditor
  //  }

  final def isProjectClosed: Boolean = {
    return project.isDisposed || !project.isOpen
  }

  //
  //
  //  def getSurfaceArea: EditableArea = {
  //    return mySurfaceArea
  //  }
  //
  //
  def getToolProvider: ToolProvider = {
    return myToolProvider
  }

  //
  //
  //  def getActionPanel: DesignerActionPanel = {
  //    return myActionPanel
  //  }
  //
  //
  //  def getInplaceEditingLayer: InplaceEditingLayer = {
  //    return myInplaceEditingLayer
  //  }
  //
  //
  //  def getPreferredFocusedComponent: JComponent = {
  //    return if (myDesignerCard.isVisible) myGlassLayer else myErrorPanel
  //  }
  //
  //
  //  def getExpandedComponents: List[_] = {
  //    return myExpandedComponents
  //  }
  //
  //
  //  def setExpandedComponents(expandedComponents: List[_]) {
  //    myExpandedComponents = expandedComponents
  //  }
  //
  //
  def getSelectionProperty(key: String): com.intellij.designer.model.Property[_] = {
    return mySelectionPropertyMap.get(key)
  }

  def setSelectionProperty(key: String, selectionProperty: com.intellij.designer.model.Property[_]) {
    mySelectionPropertyMap.put(key, selectionProperty)
  }

  //
  //
  //  protected def storeState {
  //    if (myRootComponent != null && myExpandedState == null && mySelectionState == null) {
  //      myExpandedState = new Array[Array[Int]](if (myExpandedComponents == null) 0 else myExpandedComponents.size)
  //      for (i <- 0 to myExpandedState.length) {
  //        val path: IntArrayList = new IntArrayList
  //        componentToPath(myExpandedComponents.get(i).asInstanceOf[RadComponent], path)
  //        myExpandedState(i) = path.toArray
  //      }
  //      mySelectionState = getSelectionState
  //      myExpandedComponents = null
  //      val tool: InputTool = myToolProvider.getActiveTool
  //
  //      if (!(tool.isInstanceOf[MarqueeTracker]) && !(tool.isInstanceOf[CreationTool]) && !(tool.isInstanceOf[PasteTool])) {
  //        myToolProvider.loadDefaultTool
  //      }
  //
  //    }
  //  }
  //
  //
  //  private def storeSourceSelectionState {
  //    if (!CommonEditActionsProvider.isDeleting) {
  //      mySourceSelectionState.put(getEditorText, getSelectionState)
  //    }
  //  }
  //
  //
  //  private def getSelectionState: Array[Array[Int]] = {
  //    return getSelectionState(mySurfaceArea.getSelection)
  //  }
  //
  //
  //  protected def getSelectionState(selection: List[RadComponent]): Array[Array[Int]] = {
  //    val selectionState: Array[Array[Int]] = new Array[Array[Int]](selection.size)
  //
  //    for (i <- 0 to selectionState.lenght) {
  //      val path: IntArrayList = new IntArrayList
  //      componentToPath(selection.get(i), path)
  //      selectionState(i) = path.toArray
  //    }
  //    return selectionState
  //  }
  //
  //
  //  private def componentToPath(component: RadComponent, path: IntArrayList) {
  //    val parent: RadComponent = component.getParent
  //    if (parent != null) {
  //      path.add(0, parent.getChildren.indexOf(component))
  //      componentToPath(parent, path)
  //    }
  //  }
  //
  //
  protected def restoreState {
    val toolManager: DoradoPropertySheetToolWindowContent = getDesignerToolWindow
    //      if (myExpandedState != null) {
    //        val expanded: List[RadComponent] = new util.ArrayList[RadComponent]
    //        for (path <- myExpandedState) {
    //          pathToComponent(expanded, myRootComponent, path, 0)
    //        }
    //        myExpandedComponents = expanded
    //        toolManager.expandFromState
    //        myExpandedState = null
    //      }
    val selection: List[RadComponent] = new util.ArrayList[RadComponent]
    //      val selectionState: Array[Array[Int]] = mySourceSelectionState.get(getEditorText)
    //      if (selectionState != null) {
    //        for (path <- selectionState) {
    //          pathToComponent(selection, myRootComponent, path, 0)
    //        }
    //      }
    //      if (selection.isEmpty) {
    //        if (mySelectionState != null) {
    //          for (path <- mySelectionState) {
    //            pathToComponent(selection, myRootComponent, path, 0)
    //          }
    //        }
    //      }
    if (selection.isEmpty) {
      //toolManager.refresh(true)
    }
    //      else {
    //        mySurfaceArea.setSelection(selection)
    //      }
    //      mySelectionState = null
  }

  //
  //
  //  protected def pathToComponent(components: List[RadComponent], component: RadComponent, path: Array[Int], index: Int) {
  //    if (index == path.length) {
  //      components.add(component)
  //    }
  //    else {
  //      val children: List[RadComponent] = component.getChildren
  //      val componentIndex: Int = path(index)
  //      if (0 <= componentIndex && componentIndex < children.size) {
  //        pathToComponent(components, children.get(componentIndex), path, index + 1)
  //      }
  //    }
  //  }
  //
  //  def getPlatformTarget: String
  //
  //
  //  protected def findTarget(x: Int, y: Int, filter: ComponentTargetFilter): RadComponent = {
  //    if (myRootComponent != null) {
  //      val visitor: FindComponentVisitor = new FindComponentVisitor(myLayeredPane, filter, x, y)
  //      myRootComponent.accept(visitor, false)
  //      return visitor.getResult
  //    }
  //    return null
  //  }
  //
  //
  //  protected def getRootSelectionDecorator: ComponentDecorator
  //
  //  protected def processRootOperation(context: OperationContext): EditOperation = {
  //    return null
  //  }

  protected def execute(operation: ThrowableRunnable[Exception], updateProperties: Boolean): Boolean = {
    if (!ReadonlyStatusHandler.ensureFilesWritable(getProject(), file)) {
      return false
    }
    try {
      //myPsiChangeListener.stop()
      operation.run()
      ApplicationManager.getApplication().invokeLater(new Runnable() {
        override def run() {
          //var active = myPsiChangeListener.isActive()
          // if (active) {
          //  myPsiChangeListener.stop()
          //}
          //updateRenderer(updateProperties)
          //if (active) {
          //  myPsiChangeListener.start()
          //}
        }
      });
      return true
    }
    catch {
      case e: Throwable => showError("Execute Command", e);
        return false
    }
    finally {
      //myPsiChangeListener.start()
    }

  }

  protected def executeWithReparse(operation: ThrowableRunnable[Exception]) {

  }

  protected def execute(operations: List[EditOperation]) {

  }

  def getPaletteGroups: java.util.List[DoradoPaletteGroup]

  //  /**
  //   * Returns a suitable version label from the version attribute from a {@link PaletteItem} version
  //   */
  //  @NotNull def getVersionLabel(version: String): String = {
  //    return StringUtil.notNullize(version)
  //  }
  //
  //
  //  def isDeprecated(deprecatedIn: String): Boolean = {
  //    return !StringUtil.isEmpty(deprecatedIn)
  //  }
  //
  //
  protected def createDefaultTool: InputTool = {
    return new SelectionTool
  }

  //
  //  @NotNull protected def createCreationFactory(paletteItem: PaletteItem): ComponentCreationFactory
  //
  //  def createPasteFactory(xmlComponents: String): ComponentPasteFactory
  //
  //
  def getEditorText: String

  def activate {
  }

  //
  //
  //  def deactivate {
  //  }
  //
  def createState: DesignerEditorState = {
    return new DesignerEditorState(getFile,1f)
  }

  //
  //
  //  def isEditorValid: Boolean = {
  //    return myFile.isValid
  //  }
  //
  //
  //  def getData(dataId: String): AnyRef = {
  //    return myActionPanel.getData(dataId)
  //  }
  //
  //
  //  def dispose {
  //    Disposer.dispose(myProgressIcon)
  //    getDesignerWindowManager.dispose(this)
  //    getPaletteWindowManager.dispose(this)
  //    Disposer.dispose(myContentSplitter)
  //  }
  //
  //
  protected def getDoradoDesignerWindowManager: AbstractDoradoToolWindowManager

  protected def getPaletteWindowManager: AbstractDoradoToolWindowManager

  protected def getDesignerToolWindow: DoradoPropertySheetToolWindowContent

  protected def getPaletteToolWindow: DoradoPaletteToolWindowContent

  //  def getWrapInProvider: WrapInProvider[_ <: RadComponent] = {
  //    return null
  //  }
  //
  //  @Nullable def getRootComponent: RadComponent = {
  //    return myRootComponent
  //  }
  //
  //
  def getTreeRoots: Array[AnyRef] = {
    return if (myRootComponent == null) ArrayUtil.EMPTY_OBJECT_ARRAY else Array[AnyRef](myRootComponent)
  }

  def getTreeDecorator: TreeComponentDecorator

  //
  //
  //  def handleTreeArea(treeArea: TreeEditableArea) {
  //  }
  //
  //  @NotNull def getTablePanelActionPolicy: TablePanelActionPolicy = {
  //    return TablePanelActionPolicy.ALL
  //  }
  //
  //  @Nullable def getPropertyTableTabs: Array[PropertyTableTab] = {
  //    return null
  //  }
  //
  //
  def isZoomSupported: Boolean = {
    return false
  }

  def zoom(`type`: ZoomType) {
  }

  def setZoom(zoom: Double) {
  }

  def getZoom: Double = {
    return 1
  }

  //
  //
  //  protected def viewZoomed {
  //    myQuickFixManager.hideHint
  //  }
  //
  //
  //  def loadInspections(progress: ProgressIndicator) {
  //  }
  //
  //
  //  def updateInspections {
  //    myQuickFixManager.update
  //  }
  //
  private final val MINIMIZE_WIDTH: Int = 25

  private final class FillLayout extends LayoutManager2 {
    def addLayoutComponent(comp: Component, constraints: AnyRef) {
    }

    def getLayoutAlignmentX(target: Container): Float = {
      return 0.5f
    }

    def getLayoutAlignmentY(target: Container): Float = {
      return 0.5f
    }

    def invalidateLayout(target: Container) {
    }

    def addLayoutComponent(name: String, comp: Component) {
    }

    def removeLayoutComponent(comp: Component) {
    }

    def maximumLayoutSize(target: Container): Dimension = {
      return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE)
    }

    def preferredLayoutSize(parent: Container): Dimension = {
      val toolbar: Component = parent.getComponent(0)
      val toolbarSize: Dimension = if (toolbar.isVisible) toolbar.getPreferredSize else new Dimension
      val contentSize: Dimension = parent.getComponent(1).getPreferredSize
      var extraWidth: Int = 0
      val jParent: JComponent = parent.asInstanceOf[JComponent]
      if (jParent.getClientProperty(LightToolWindow.LEFT_MIN_KEY) != null) {
        extraWidth += MINIMIZE_WIDTH
      }
      if (jParent.getClientProperty(LightToolWindow.RIGHT_MIN_KEY) != null) {
        extraWidth += MINIMIZE_WIDTH
      }
      return new Dimension(Math.max(toolbarSize.width, contentSize.width + extraWidth), toolbarSize.height + contentSize.height)
    }

    def minimumLayoutSize(parent: Container): Dimension = {
      val toolbar: Component = parent.getComponent(0)
      val toolbarSize: Dimension = if (toolbar.isVisible) toolbar.getMinimumSize else new Dimension
      val contentSize: Dimension = parent.getComponent(1).getMinimumSize
      var extraWidth: Int = 0
      val jParent: JComponent = parent.asInstanceOf[JComponent]
      if (jParent.getClientProperty(LightToolWindow.LEFT_MIN_KEY) != null) {
        extraWidth += MINIMIZE_WIDTH
      }
      if (jParent.getClientProperty(LightToolWindow.RIGHT_MIN_KEY) != null) {
        extraWidth += MINIMIZE_WIDTH
      }
      return new Dimension(Math.max(toolbarSize.width, contentSize.width + extraWidth), toolbarSize.height + contentSize.height)
    }

    def layoutContainer(parent: Container) {
      var leftWidth: Int = 0
      var rightWidth: Int = 0
      val jParent: JComponent = parent.asInstanceOf[JComponent]
      val left: JComponent = jParent.getClientProperty(LightToolWindow.LEFT_MIN_KEY).asInstanceOf[JComponent]
      if (left != null) {
        leftWidth = MINIMIZE_WIDTH
      }
      val right: JComponent = jParent.getClientProperty(LightToolWindow.RIGHT_MIN_KEY).asInstanceOf[JComponent]
      if (right != null) {
        rightWidth = MINIMIZE_WIDTH
      }
      val extraWidth: Int = leftWidth + rightWidth
      val width: Int = parent.getWidth - extraWidth
      val height: Int = parent.getHeight
      val toolbar: Component = parent.getComponent(0)
      val toolbarSize: Dimension = if (toolbar.isVisible) toolbar.getPreferredSize else new Dimension
      toolbar.setBounds(leftWidth, 0, width, toolbarSize.height)
      parent.getComponent(1).setBounds(leftWidth, toolbarSize.height, width, height - toolbarSize.height)
      if (left != null) {
        left.setBounds(0, 0, leftWidth, height)
      }
      if (right != null) {
        right.setBounds(width + leftWidth, 0, rightWidth, height)
      }
    }
  }

  protected def getSceneSize(target: Component): Dimension = {
    var width: Int = 0
    var height: Int = 0
    if (myRootComponent != null) {
      val bounds: Rectangle = myRootComponent.getBounds(target)
      width = Math.max(width, bounds.getMaxX.asInstanceOf[Int])
      height = Math.max(height, bounds.getMaxY.asInstanceOf[Int])

      import scala.collection.JavaConversions._

      for (component <- myRootComponent.getChildren) {
        val childBounds: Rectangle = component.getBounds(target)
        width = Math.max(width, childBounds.getMaxX.asInstanceOf[Int])
        height = Math.max(height, childBounds.getMaxY.asInstanceOf[Int])
      }
    }
    width += 50
    height += 40
    return new Dimension(width, height)
  }

  //
  //  protected class DesignerEditableArea extends ComponentEditableArea {
  //    def this() {
  //      this()
  //      `super`(myLayeredPane)
  //    }
  //
  //    protected override def fireSelectionChanged {
  //      super.fireSelectionChanged
  //      myLayeredPane.revalidate
  //      myLayeredPane.repaint
  //    }
  //
  //    override def scrollToSelection {
  //      val selection: List[RadComponent] = getSelection
  //      if (selection.size == 1) {
  //        val bounds: Rectangle = selection.get(0).getBounds(myLayeredPane)
  //        if (bounds != null) {
  //          myLayeredPane.scrollRectToVisible(bounds)
  //        }
  //      }
  //    }
  //
  //    def findTarget(x: Int, y: Int, @Nullable filter: ComponentTargetFilter): RadComponent = {
  //      return DoradoDesignerEditorPanel.this.findTarget(x, y, filter)
  //    }
  //
  //    def findTargetTool(x: Int, y: Int): InputTool = {
  //      return myDecorationLayer.findTargetTool(x, y)
  //    }
  //
  //    def showSelection(value: Boolean) {
  //      myDecorationLayer.showSelection(value)
  //    }
  //
  //    def getRootSelectionDecorator: ComponentDecorator = {
  //      return DoradoDesignerEditorPanel.this.getRootSelectionDecorator
  //    }
  //
  //    @Nullable def processRootOperation(context: OperationContext): EditOperation = {
  //      return DoradoDesignerEditorPanel.this.processRootOperation(context)
  //    }
  //
  //    def getFeedbackLayer: FeedbackLayer = {
  //      return myFeedbackLayer
  //    }
  //
  //    def getRootComponent: RadComponent = {
  //      return myRootComponent
  //    }
  //
  //    def getPopupActions: ActionGroup = {
  //      return myActionPanel.getPopupActions(this)
  //    }
  //
  //    def getPopupPlace: String = {
  //      return ActionPlaces.GUI_DESIGNER_EDITOR_POPUP
  //    }
  //  }
  //
  protected class DesignerToolProvider extends ToolProvider {
    def loadDefaultTool {
      setActiveTool(createDefaultTool)
    }

    override def setActiveTool(tool: InputTool) {
      if (getActiveTool.isInstanceOf[CreationTool] && !(tool.isInstanceOf[CreationTool])) {
        getPaletteToolWindow.clearActiveItem
      }
      if (!(tool.isInstanceOf[SelectionTool])) {
        hideInspections
      }
      super.setActiveTool(tool)
    }

    def execute(operation: ThrowableRunnable[Exception], command: String, updateProperties: Boolean): Boolean = {
      val is: Array[Boolean] = Array(true)
      CommandProcessor.getInstance.executeCommand(getProject, new Runnable {
        def run {
          is(0) = DoradoDesignerEditorPanel.this.execute(operation, updateProperties)
        }
      }, command, null)
      return is(0)
    }

    def executeWithReparse(operation: ThrowableRunnable[Exception], command: String) {
      CommandProcessor.getInstance.executeCommand(getProject, new Runnable {
        def run {
          DoradoDesignerEditorPanel.this.executeWithReparse(operation)
        }
      }, command, null)
    }

    def execute(operations: List[EditOperation], command: String) {
      CommandProcessor.getInstance.executeCommand(getProject, new Runnable {
        def run {
          DoradoDesignerEditorPanel.this.execute(operations)
        }
      }, command, null)
    }

    def startInplaceEditing(@Nullable inplaceContext: InplaceContext) {
      myInplaceEditingLayer.startEditing(inplaceContext)
    }

    def hideInspections {
      myQuickFixManager.hideHint
    }

    def showError(@NonNls message: String, e: Throwable) {
      DoradoDesignerEditorPanel.this.showError(message, e)
    }

    def isZoomSupported: Boolean = {
      return DoradoDesignerEditorPanel.this.isZoomSupported
    }

    def zoom(`type`: ZoomType) {
      DoradoDesignerEditorPanel.this.zoom(`type`)
    }

    def setZoom(zoom: Double) {
      DoradoDesignerEditorPanel.this.setZoom(zoom)
    }

    def getZoom: Double = {
      return DoradoDesignerEditorPanel.this.getZoom
    }
  }

  private final class MyLayeredPane extends JBLayeredPane with Scrollable {
    override def doLayout {
      {
        var i: Int = getComponentCount - 1
        while (i >= 0) {
          {
            val component: Component = getComponent(i)
            component.setBounds(0, 0, getWidth, getHeight)
          }
          ({
            i -= 1;
            i + 1
          })
        }
      }
    }

    override def getMinimumSize: Dimension = {
      return getPreferredSize
    }

    override def getPreferredSize: Dimension = {
      val bounds: Rectangle = myScrollPane.getViewport.getBounds
      val size: Dimension = getSceneSize(this)
      size.width = Math.max(size.width, bounds.width)
      size.height = Math.max(size.height, bounds.height)
      return size
    }

    def getPreferredScrollableViewportSize: Dimension = {
      return getPreferredSize
    }

    def getScrollableUnitIncrement(visibleRect: Rectangle, orientation: Int, direction: Int): Int = {
      return 10
    }

    def getScrollableBlockIncrement(visibleRect: Rectangle, orientation: Int, direction: Int): Int = {
      if (orientation == SwingConstants.HORIZONTAL) {
        return visibleRect.width - 10
      }
      return visibleRect.height - 10
    }

    def getScrollableTracksViewportWidth: Boolean = {
      return false
    }

    def getScrollableTracksViewportHeight: Boolean = {
      return false
    }
  }

  //
  //  private class FixableMessageAction extends AbstractComboBoxAction[DesignerEditorPanel.FixableMessageInfo] {
  //    def this() {
  //      this()
  //      myActionPanel.getActionGroup.add(myActionGroup)
  //      val presentation: Presentation = getTemplatePresentation
  //      presentation.setDescription("Warnings")
  //      presentation.setIcon(AllIcons.Ide.Warning_notifications)
  //    }
  //
  //    def show(messages: List[DesignerEditorPanel.FixableMessageInfo]) {
  //      if (!myIsAdded) {
  //        myTitle = Integer.toString(messages.size)
  //        setItems(messages, null)
  //        myActionGroup.add(this)
  //        myActionPanel.update
  //        myIsAdded = true
  //      }
  //    }
  //
  //    def hide {
  //      if (myIsAdded) {
  //        myActionGroup.remove(this)
  //        myActionPanel.update
  //        myIsAdded = false
  //      }
  //    }
  //
  //    @NotNull protected override def createPopupActionGroup(button: JComponent): DefaultActionGroup = {
  //      val actionGroup: DefaultActionGroup = new DefaultActionGroup
  //      import scala.collection.JavaConversions._
  //      for (message <- myItems) {
  //        var action: AnAction = null
  //        if ((message.myQuickFix != null && (message.myLinkText.length > 0 || message.myAfterLinkText.length > 0)) || (message.myAdditionalFixes != null && message.myAdditionalFixes.size > 0)) {
  //          val defaultAction: Array[AnAction] = new Array[AnAction](1)
  //          val popupGroup: DefaultActionGroup = new DefaultActionGroup {
  //            override def canBePerformed(context: DataContext): Boolean = {
  //              return true
  //            }
  //
  //            override def actionPerformed(e: AnActionEvent) {
  //              defaultAction(0).actionPerformed(e)
  //            }
  //          }
  //          popupGroup.setPopup(true)
  //          action = popupGroup
  //          if (message.myQuickFix != null && (message.myLinkText.length > 0 || message.myAfterLinkText.length > 0)) {
  //            val popupAction: AnAction = new AnAction {
  //              def actionPerformed(e: AnActionEvent) {
  //                message.myQuickFix.run
  //              }
  //            }
  //            popupAction.getTemplatePresentation.setText(cleanText(message.myLinkText + message.myAfterLinkText))
  //            popupGroup.add(popupAction)
  //            defaultAction(0) = popupAction
  //          }
  //          if (message.myAdditionalFixes != null && message.myAdditionalFixes.size > 0) {
  //            import scala.collection.JavaConversions._
  //            for (pair <- message.myAdditionalFixes) {
  //              val popupAction: AnAction = new AnAction {
  //                def actionPerformed(e: AnActionEvent) {
  //                  pair.second.run
  //                }
  //              }
  //              popupAction.getTemplatePresentation.setText(cleanText(pair.first))
  //              popupGroup.add(popupAction)
  //              if (defaultAction(0) == null) {
  //                defaultAction(0) = popupAction
  //              }
  //            }
  //          }
  //        }
  //        else {
  //          action = new EmptyAction(true)
  //        }
  //        actionGroup.add(action)
  //        update(message, action.getTemplatePresentation, true)
  //      }
  //      return actionGroup
  //    }
  //
  //    protected def update(item: DesignerEditorPanel.FixableMessageInfo, presentation: Presentation, popup: Boolean) {
  //      if (popup) {
  //        presentation.setText(cleanText(item.myBeforeLinkText))
  //      }
  //      else {
  //        presentation.setText(myTitle)
  //      }
  //    }
  //
  //    private def cleanText(text: String): String = {
  //      if (text != null) {
  //        var text = text.trim
  //        text = StringUtil.replace(text, " ", " ")
  //        text = StringUtil.replace(text, "\n", " ")
  //        val builder: StringBuilder = new StringBuilder
  //        val length: Int = text.length
  //        var whitespace: Boolean = false
  //        for (i <- 0 to length) {
  //          val ch: Char = text.charAt(i)
  //          if (ch == ' ') {
  //            if (!whitespace) {
  //              whitespace = true
  //              builder.append(ch)
  //            }
  //          }
  //          else {
  //            whitespace = false
  //            builder.append(ch)
  //          }
  //        }
  //        text = builder.toString
  //      }
  //      return text
  //    }
  //
  //    protected def selectionChanged(item: DesignerEditorPanel.FixableMessageInfo): Boolean = {
  //      return false
  //    }
  //
  //    private final val myActionGroup: DefaultActionGroup = new DefaultActionGroup
  //    private var myTitle: String = null
  //    private var myIsAdded: Boolean = false
  //  }
  //
  //  final class ErrorInfo {
  //    var myMessage: String = null
  //    var myDisplayMessage: String = null
  //    final val myMessages: List[DesignerEditorPanel.FixableMessageInfo] = new util.ArrayList[DesignerEditorPanel.FixableMessageInfo]
  //    var myThrowable: Throwable = null
  //    var myShowMessage: Boolean = true
  //    var myShowStack: Boolean = true
  //    var myShowLog: Boolean = false
  //  }
  //
  //  final class FixableMessageInfo(errorIcon: Boolean, beforeLinkText: String, linkText: String, afterLinkText: String, quickFix: Runnable, additionalFixes: List[Pair[String, Runnable]]) {
  //  }
  //
  //  private class FixedHashMap(size: Int) extends util.HashMap[_, _] {
  //
  //    private final val myKeys: List[_] = new util.LinkedList[_]
  //
  //    override def put(key: AnyRef, value: AnyRef): AnyRef = {
  //      if (!myKeys.contains(key)) {
  //        if (myKeys.size >= mySize) {
  //          remove(myKeys.remove(0))
  //        }
  //        myKeys.add(key)
  //      }
  //      return super.put(key, value)
  //    }
  //
  //    override def get(key: AnyRef): AnyRef = {
  //      if (myKeys.contains(key)) {
  //        val index: Int = myKeys.indexOf(key)
  //        val last: Int = myKeys.size - 1
  //        myKeys.set(index, myKeys.get(last))
  //        myKeys.set(last, key)
  //      }
  //      return super.get(key)
  //    }
  //
  //
  //  }

}


text:
typedef NS_ENUM(NSUInteger, UAELBInstanceState) {
	UAELBInstanceStateUnknown = 0,
	UAELBInstanceStateInService = 1,
	UAELBInstanceStateOutOfService = 2
};

// UAELBInstanceStateReasonCode
typedef NS_ENUM(NSUInteger, UAELBInstanceStateReasonCode) {
	UAELBInstanceStateReasonCodeUnknown = 0,
	UAELBInstanceStateReasonCodeElb = 1,
	UAELBInstanceStateReasonCodeInstance = 2
};

// UAELBScheme
typedef NS_ENUM(NSUInteger, UAELBScheme) {
	UAELBSchemeUnknown = 0,
	UAELBSchemeInternetFacing = 1,
	UAELBSchemeInternal = 2
};


text:
package resolver

import (
	"github.com/miekg/dns"
	"github.com/shawn1m/overture/core/common"
	"net"
	"os"
	"testing"
)

var questionDomain = "www.yahoo.com."
var udpUpstream = &common.DNSUpstream{
	Name:          "Test-UDP",
	Address:       "114.114.114.114",
	Protocol:      "udp",
	SOCKS5Address: "",
	Timeout:       6,
	EDNSClientSubnet: &common.EDNSClientSubnetType{
		Policy:     "disable",
		ExternalIP: "",
		NoCookie:   false,
	},
}

var tcpUpstream = &common.DNSUpstream{
	Name:          "Test-TCP",
	Address:       "1.1.1.1",
	Protocol:      "tcp",
	SOCKS5Address: "",
	Timeout:       6,
	EDNSClientSubnet: &common.EDNSClientSubnetType{
		Policy:     "disable",
		ExternalIP: "",
		NoCookie:   false,
	},
}

var tcpTlsUpstream = &common.DNSUpstream{
	Name:          "Test-TCP-TLS",
	Address:       "dns.google@8.8.8.8",
	Protocol:      "tcp-tls",
	SOCKS5Address: "",
	Timeout:       8,
	EDNSClientSubnet: &common.EDNSClientSubnetType{
		Policy:     "disable",
		ExternalIP: "",
		NoCookie:   false,
	},
}

var httpsUpstream = &common.DNSUpstream{
	Name:          "Test-HTTPS",
	Address:       "https://dns.google/dns-query",
	Protocol:      "https",
	SOCKS5Address: "",
	Timeout:       8,
	EDNSClientSubnet: &common.EDNSClientSubnetType{
		Policy:     "disable",
		ExternalIP: "",
		NoCookie:   false,
	},
}

func init() {
	os.Chdir("../..")
}

func TestDispatcher(t *testing.T) {
	testUDP(t)
	testTCP(t)
	testTCPTLS(t)
	testHTTPS(t)
}

func testUDP(t *testing.T) {
	q := getQueryMsg(questionDomain, dns.TypeA)
	resolver := NewResolver(udpUpstream)
	resp, err := resolver.Exchange(q)
	if err != nil {
		t.Errorf("Got error: %s", err)
	}
	if net.ParseIP(common.FindRecordByType(resp, dns.TypeA)).To4() == nil {
		t.Error(questionDomain + " should have A record")
	}
}

func testTCP(t *testing.T) {
	q := getQueryMsg(questionDomain, dns.TypeA)
	resolver := NewResolver(tcpUpstream)
	resp, _ := resolver.Exchange(q)
	if net.ParseIP(common.FindRecordByType(resp, dns.TypeA)).To4() == nil {
		t.Error(questionDomain + " should have A record")
	}
}

func testTCPTLS(t *testing.T) {
	q := getQueryMsg(questionDomain, dns.TypeA)
	resolver := NewResolver(tcpTlsUpstream)
	resp, _ := resolver.Exchange(q)
	if net.ParseIP(common.FindRecordByType(resp, dns.TypeA)).To4() == nil {
		t.Error(questionDomain + " should have A record")
	}
}

func testHTTPS(t *testing.T) {
	q := getQueryMsg(questionDomain, dns.TypeA)
	resolver := NewResolver(httpsUpstream)
	resp, _ := resolver.Exchange(q)
	if net.ParseIP(common.FindRecordByType(resp, dns.TypeA)).To4() == nil {
		t.Error(questionDomain + " should have A record")
	}
}

func getQueryMsg(z string, t uint16) *dns.Msg {
	q := new(dns.Msg)
	q.SetQuestion(z, t)
	return q
}


text:
require_relative 'spec_helper'

describe 'openstack-common::client' do

  describe 'ubuntu' do

    let(:runner) { ChefSpec::Runner.new(UBUNTU_OPTS) }
    let(:node) { runner.node }
    let(:chef_run) do
      runner.converge(described_recipe)
    end

    it 'upgrades common client packages' do
      expect(chef_run).to upgrade_package('python-openstackclient')
    end
  end
end