text:
var http          = require('http'),
    URL           = require('url'),
    HtmlToDom     = require('./htmltodom').HtmlToDom,
    domToHtml     = require('./domtohtml').domToHtml,
    htmlencoding  = require('./htmlencoding'),
    HTMLEncode    = htmlencoding.HTMLEncode,
    HTMLDecode    = htmlencoding.HTMLDecode,
    jsdom         = require('../../jsdom'),
    Location      = require('./location'),
    History       = require('./history'),
    NOT_IMPLEMENTED = require('./utils').NOT_IMPLEMENTED,
    CSSStyleDeclaration = require('cssstyle').CSSStyleDeclaration,
    toFileUrl = require('../utils').toFileUrl,
    Contextify    = require('contextify');

function matchesDontThrow(el, selector) {
  try {
    return el.matchesSelector(selector);
  } catch (e) {
    return false;
  }
}

/**
 * Creates a window having a document. The document can be passed as option,
 * if omitted, a new document will be created.
 */
exports.windowAugmentation = function(dom, options) {
  options = options || {};
  var window = exports.createWindow(dom, options);

  if (!options.document) {
    var browser = browserAugmentation(dom, options);

    options.document = (browser.HTMLDocument)             ?
                        new browser.HTMLDocument(options) :
                        new browser.Document(options);

    options.document.write('');
  }

  var doc = window.document = options.document;

  if (doc.addEventListener) {
    if (doc.readyState == 'complete') {
      var ev = doc.createEvent('HTMLEvents');
      ev.initEvent('load', false, false);
      process.nextTick(function () {
        window.dispatchEvent(ev);
      });
    }
    else {
      doc.addEventListener('load', function(ev) {
        window.dispatchEvent(ev);
      });
    }
  }

  return window;
};

/**
 * Creates a document-less window.
 */
exports.createWindow = function(dom, options) {
  var timers = [];
  var cssSelectorSplitRE = /((?:[^,"']|"[^"]*"|'[^']*')+)/;

  function startTimer(startFn, stopFn, callback, ms) {
	  var res = startFn(callback, ms);
	  timers.push( [ res, stopFn ] );
	  return res;
  }

  function stopTimer(id) {
	  if (typeof id === 'undefined') {
		  return;
	  }
	  for (var i in timers) {
		  if (timers[i][0] === id) {
			  timers[i][1].call(this, id);
			  timers.splice(i, 1);
			  break;
		  }
	  }
  }

  function stopAllTimers() {
	  timers.forEach(function (t) {
		  t[1].call(this, t[0]);
	  });
	  timers = [];
  }

  function DOMWindow(options) {
    var url = (options || {}).url || toFileUrl(__filename);
    this.location = new Location(url, this);
    this.history = new History(this);

    this.console._window = this;

    if (options && options.document) {
      options.document.location = this.location;
    }

    this.addEventListener = function() {
      dom.Node.prototype.addEventListener.apply(window, arguments);
    };
    this.removeEventListener = function() {
      dom.Node.prototype.removeEventListener.apply(window, arguments);
    };
    this.dispatchEvent = function() {
      dom.Node.prototype.dispatchEvent.apply(window, arguments);
    };
    this.raise = function(){
      dom.Node.prototype.raise.apply(window.document, arguments);
    };

    this.setTimeout = function (fn, ms) { return startTimer(setTimeout, clearTimeout, fn, ms); };
    this.setInterval = function (fn, ms) { return startTimer(setInterval, clearInterval, fn, ms); };
    this.clearInterval = stopTimer;
    this.clearTimeout = stopTimer;
    this.__stopAllTimers = stopAllTimers;
  }

  DOMWindow.prototype = {
    __proto__: dom,
    // This implements window.frames.length, since window.frames returns a
    // self reference to the window object.  This value is incremented in the
    // HTMLFrameElement init function (see: level2/html.js).
    _length : 0,
    get length () {
      return this._length;
    },
    close : function() {
      // Recursively close child frame windows, then ourselves.
      var currentWindow = this;
      (function windowCleaner (window) {
        var i;
        // We could call window.frames.length etc, but window.frames just points
        // back to window.
        if (window.length > 0) {
          for (i = 0; i < window.length; i++) {
            windowCleaner(window[i]);
          }
        }
        // We're already in our own window.close().
        if (window !== currentWindow) {
          window.close();
        }
      })(this);

      if (this.document) {
        if (this.document.body) {
          this.document.body.innerHTML = "";
        }

        if (this.document.close) {
          // We need to empty out the event listener array because
          // document.close() causes 'load' event to re-fire.
          this.document._listeners = [];
          this.document.close();
        }
        delete this.document;
      }

      stopAllTimers();
      // Clean up the window's execution context.
      // dispose() is added by Contextify.
      this.dispose();
    },
    getComputedStyle: function(node) {
      var s = node.style,
          cs = new CSSStyleDeclaration(),
          forEach = Array.prototype.forEach;

      function setPropertiesFromRule(rule) {
        if (!rule.selectorText) {
          return;
        }

        var selectors = rule.selectorText.split(cssSelectorSplitRE);
        var matched = false;
        selectors.forEach(function (selectorText) {
          if (selectorText !== '' && selectorText !== ',' && !matched && matchesDontThrow(node, selectorText)) {
            matched = true;
            forEach.call(rule.style, function (property) {
              cs.setProperty(property, rule.style.getPropertyValue(property), rule.style.getPropertyPriority(property));
            });
          }
        });
      }

      forEach.call(node.ownerDocument.styleSheets, function (sheet) {
        forEach.call(sheet.cssRules, function (rule) {
          if (rule.media) {
            if (Array.prototype.indexOf.call(rule.media, 'screen') !== -1) {
              forEach.call(rule.cssRules, setPropertiesFromRule);
            }
          } else {
            setPropertiesFromRule(rule);
          }
        });
      });

      forEach.call(s, function (property) {
        cs.setProperty(property, s.getPropertyValue(property), s.getPropertyPriority(property));
      });

      return cs;
    },
    console: {
      log:   function(message) { this._window.raise('log',   message) },
      info:  function(message) { this._window.raise('info',  message) },
      warn:  function(message) { this._window.raise('warn',  message) },
      error: function(message) { this._window.raise('error', message) }
    },
    navigator: {
      userAgent: 'Node.js (' + process.platform + '; U; rv:' + process.version + ')',
      appName: 'Node.js jsDom',
      platform: process.platform,
      appVersion: process.version,
      noUI: true
    },
    XMLHttpRequest: function() {
      var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
      var xhr = new XMLHttpRequest();
      var lastUrl = '';
      xhr._open = xhr.open;
      xhr.open = function(method, url, async, user, password) {
        url = URL.resolve(options.url, url);
        lastUrl = url;
        return xhr._open(method, url, async, user, password);
      };
      xhr._send = xhr.send;
      xhr.send = function(data) {
        if (window.document.cookie) {
          var cookieDomain = window.document._cookieDomain;
          var url = URL.parse(lastUrl);
          var host = url.host.split(':')[0];
          if (host.indexOf(cookieDomain, host.length - cookieDomain.length) !== -1) {
            xhr.setDisableHeaderCheck(true);
            xhr.setRequestHeader('cookie', window.document.cookie);
            xhr.setDisableHeaderCheck(false);
          }
        }
        return xhr._send(data);
      };
      return xhr;
    },

    name: 'nodejs',
    innerWidth: 1024,
    innerHeight: 768,
    outerWidth: 1024,
    outerHeight: 768,
    pageXOffset: 0,
    pageYOffset: 0,
    screenX: 0,
    screenY: 0,
    screenLeft: 0,
    screenTop: 0,
    scrollX: 0,
    scrollY: 0,
    scrollTop: 0,
    scrollLeft: 0,
    alert: NOT_IMPLEMENTED(null, 'window.alert'),
    blur: NOT_IMPLEMENTED(null, 'window.blur'),
    confirm: NOT_IMPLEMENTED(null, 'window.confirm'),
    createPopup: NOT_IMPLEMENTED(null, 'window.createPopup'),
    focus: NOT_IMPLEMENTED(null, 'window.focus'),
    moveBy: NOT_IMPLEMENTED(null, 'window.moveBy'),
    moveTo: NOT_IMPLEMENTED(null, 'window.moveTo'),
    open: NOT_IMPLEMENTED(null, 'window.open'),
    print: NOT_IMPLEMENTED(null, 'window.print'),
    prompt: NOT_IMPLEMENTED(null, 'window.prompt'),
    resizeBy: NOT_IMPLEMENTED(null, 'window.resizeBy'),
    resizeTo: NOT_IMPLEMENTED(null, 'window.resizeTo'),
    scroll: NOT_IMPLEMENTED(null, 'window.scroll'),
    scrollBy: NOT_IMPLEMENTED(null, 'window.scrollBy'),
    scrollTo: NOT_IMPLEMENTED(null, 'window.scrollTo'),
    screen : {
      width : 0,
      height : 0
    },
    Image : NOT_IMPLEMENTED(null, 'window.Image'),

    // Note: these will not be necessary for newer Node.js versions, which have
    // typed arrays in V8 and thus on every global object. (That is, in newer
    // versions we'll get `ArrayBuffer` just as automatically as we get
    // `Array`.) But to support older versions, we explicitly set them here.
    Int8Array: Int8Array,
    Int16Array: Int16Array,
    Int32Array: Int32Array,
    Float32Array: Float32Array,
    Float64Array: Float64Array,
    Uint8Array: Uint8Array,
    Uint8ClampedArray: Uint8ClampedArray,
    Uint16Array: Uint16Array,
    Uint32Array: Uint32Array,
    ArrayBuffer: ArrayBuffer
  };

  var window = new DOMWindow(options);

  Contextify(window);

  // We need to set up self references using Contextify's getGlobal() so that
  // the global object identity is correct (window === this).
  // See Contextify README for more info.
  var global = window.getGlobal();

  // Set up the window as if it's a top level window.
  // If it's not, then references will be corrected by frame/iframe code.
  // Note: window.frames is maintained in the HTMLFrameElement init function.
  window.window = window.frames
                = window.self
                = window.parent
                = window.top = global;

  return window;
};

//Caching for HTMLParser require. HUGE performace boost.
/**
* 5000 iterations
* Without cache: ~1800+ms
* With cache: ~80ms
*/
// TODO: is this even needed in modern Node.js versions?
var defaultParser = null;
var getDefaultParser = exports.getDefaultParser = function () {
  if (defaultParser === null) {
    defaultParser = require('htmlparser2');
  }
  return defaultParser;
}

/**
 * Export getter/setter of default parser to facilitate testing
 * with different HTML parsers.
 */
exports.setDefaultParser = function (parser) {
  if (typeof parser == 'object') {
    defaultParser = parser;
  } else if (typeof parser == 'string')
    defaultParser = require(parser);
}

/**
 * Augments the given DOM by adding browser-specific properties and methods (BOM).
 * Returns the augmented DOM.
 */
var browserAugmentation = exports.browserAugmentation = function(dom, options) {

  if(!options) {
    options = {};
  }

  // set up html parser - use a provided one or try and load from library
  var parser = options.parser || getDefaultParser();

  if (dom._augmented && dom._parser === parser) {
    return dom;
  }

  dom._parser = parser;
  var htmltodom = new HtmlToDom(parser);

  if (!dom.HTMLDocument) {
    dom.HTMLDocument = dom.Document;
  }
  if (!dom.HTMLDocument.prototype.write) {
    dom.HTMLDocument.prototype.write = function(html) {
      this.innerHTML = html;
    };
  }

  dom.Element.prototype.getElementsByClassName = function(className) {

    function filterByClassName(child) {
      if (!child) {
        return false;
      }

      if (child.nodeType &&
          child.nodeType === dom.Node.ENTITY_REFERENCE_NODE)
      {
        child = child._entity;
      }

      var classString = child.className;
      if (classString) {
        var s = classString.split(" ");
        for (var i=0; i<s.length; i++) {
          if (s[i] === className) {
            return true;
          }
        }
      }
      return false;
    }

    return new dom.NodeList(this.ownerDocument || this, dom.mapper(this, filterByClassName));
  };

  dom.Element.prototype.__defineGetter__('sourceIndex', function() {
    /*
    * According to QuirksMode:
    * Get the sourceIndex of element x. This is also the index number for
    * the element in the document.getElementsByTagName('*') array.
    * http://www.quirksmode.org/dom/w3c_core.html#t77
    */
    var items = this.ownerDocument.getElementsByTagName('*'),
        len = items.length;

    for (var i = 0; i < len; i++) {
      if (items[i] === this) {
        return i;
      }
    }
  });

  dom.Document.prototype.__defineGetter__('outerHTML', function() {
    return domToHtml(this, true);
  });

  dom.Element.prototype.__defineGetter__('outerHTML', function() {
    return domToHtml(this, true);
  });

  dom.Element.prototype.__defineGetter__('innerHTML', function() {
    if (/^(?:script|style)$/.test(this._tagName)) {
      var type = this.getAttribute('type');
      if (!type || /^text\//i.test(type) || /\/javascript$/i.test(type)) {
        return domToHtml(this._childNodes, true, true);
      }
    }

    return domToHtml(this._childNodes, true);
  });

  dom.Element.prototype.__defineSetter__('doctype', function() {
    throw new dom.DOMException(dom.NO_MODIFICATION_ALLOWED_ERR);
  });
  dom.Element.prototype.__defineGetter__('doctype', function() {
    var r = null;
    if (this.nodeName == '#document') {
        if (this._doctype) {
         r = this._doctype;
        }
    }
    return r;
  });

  dom.Element.prototype.__defineSetter__('innerHTML', function(html) {
    //Clear the children first:
    var child;
    while ((child = this._childNodes[0])) {
      this.removeChild(child);
    }

    if (this.nodeName === '#document') {
      parseDocType(this, html);
    }
    if (html !== "" && html != null) {
      htmltodom.appendHtmlToElement(html, this);
    }
    return html;
  });

  dom.Document.prototype.__defineGetter__('innerHTML', function() {
    return domToHtml(this._childNodes, true);
  });

  dom.Document.prototype.__defineSetter__('innerHTML', function(html) {
    //Clear the children first:
    var child;
    while ((child = this._childNodes[0])) {
      this.removeChild(child);
    }

    if (this.nodeName === '#document') {
      parseDocType(this, html);
    }
    if (html !== "" && html != null) {
      htmltodom.appendHtmlToElement(html, this);
    }
    return html;
  });

  var DOC_HTML5      = /<!doctype html>/i,
      DOC_TYPE       = /<!DOCTYPE (\w(.|\n)*)">/i,
      DOC_TYPE_START = '<!DOCTYPE ',
      DOC_TYPE_END   = '">';

  function parseDocType(doc, html) {
    var publicID = '',
        systemID = '',
        fullDT = '',
        name = 'HTML',
        set = true,
        doctype = html.match(DOC_HTML5);

    //Default, No doctype === null
    doc._doctype = null;

    if (doctype && doctype[0]) { //Handle the HTML shorty doctype
      fullDT = doctype[0];
    } else { //Parse the doctype
      // find the start
      var start     = html.indexOf(DOC_TYPE_START),
          end       = html.indexOf(DOC_TYPE_END),
          docString;

      if (start < 0 || end < 0) {
        return;
      }

      docString = html.substr(start, (end-start)+DOC_TYPE_END.length);
      doctype = docString.replace(/[\n\r]/g,'').match(DOC_TYPE);

      if (!doctype) {
        return;
      }

      fullDT = doctype[0];
      doctype = doctype[1].split(' "');
      var _id1 = doctype.length ? doctype.pop().replace(/"/g, '') : '',
          _id2 = doctype.length ? doctype.pop().replace(/"/g, '') : '';

      if (_id1.indexOf('-//') !== -1) {
        publicID = _id1;
      }
      if (_id2.indexOf('-//') !== -1) {
        publicID = _id2;
      }
      if (_id1.indexOf('://') !== -1) {
        systemID = _id1;
      }
      if (_id2.indexOf('://') !== -1) {
        systemID = _id2;
      }
      if (doctype.length) {
        doctype = doctype[0].split(' ');
        name = doctype[0].toUpperCase();
      }
    }
    doc._doctype = new dom.DOMImplementation().createDocumentType(name, publicID, systemID);
    doc._doctype._ownerDocument = doc;
    doc._doctype._fullDT = fullDT;
    doc._doctype.toString = function() {
      return this._fullDT;
    };
  }

  dom.Document.prototype.getElementsByClassName = function(className) {

    function filterByClassName(child) {
      if (!child) {
        return false;
      }

      if (child.nodeType &&
          child.nodeType === dom.Node.ENTITY_REFERENCE_NODE)
      {
        child = child._entity;
      }

      var classString = child.className;
      if (classString) {
        var s = classString.split(" ");
        for (var i=0; i<s.length; i++) {
          if (s[i] === className) {
            return true;
          }
        }
      }
      return false;
    }

    return new dom.NodeList(this.ownerDocument || this, dom.mapper(this, filterByClassName));
  };

  dom.Element.prototype.__defineGetter__('nodeName', function(val) {
    return this._nodeName.toUpperCase();
  });

  dom.Element.prototype.__defineGetter__('tagName', function(val) {
    var t = this._tagName.toUpperCase();
    //Document should not return a tagName
    if (this.nodeName === '#document') {
      t = null;
    }
    return t;
  });

  dom.Element.prototype.scrollTop = 0;
  dom.Element.prototype.scrollLeft = 0;

  dom.Document.prototype.__defineGetter__('parentWindow', function() {
    if (!this._parentWindow) {
      this.parentWindow = exports.windowAugmentation(dom, {document: this, url: this.URL});
    }
    return this._parentWindow;
  });

  dom.Document.prototype.__defineSetter__('parentWindow', function(window) {
    // Contextify does not support getters and setters, so we have to set them
    // on the original object instead.
    window._frame = function (name, frame) {
      if (typeof frame === 'undefined') {
        delete window[name];
      } else {
        window.__defineGetter__(name, function () { return frame.contentWindow; });
      }
    };
    this._parentWindow = window.getGlobal();
  });

  dom.Document.prototype.__defineGetter__('defaultView', function() {
    return this.parentWindow;
  });

  dom._augmented = true;
  return dom;
};


text:
import pytest

# Salt libs
import salt.beacons.smartos_vmadm as vmadm
from tests.support.mock import MagicMock, patch

@pytest.fixture
def configure_loader_modules():
    return {vmadm: {"__context__": {}, "__salt__": {}}}

@pytest.fixture
def mock_clean_state():
    return {"first_run": True, "vms": []}

@pytest.fixture
def mock_vm_none():
    return {}

@pytest.fixture
def mock_vm_one():
    return {
        "00000000-0000-0000-0000-000000000001": {
            "state": "running",
            "alias": "vm1",
            "hostname": "vm1",
            "dns_domain": "example.org",
        },
    }

@pytest.fixture
def mock_vm_two_stopped():
    return {
        "00000000-0000-0000-0000-000000000001": {
            "state": "running",
            "alias": "vm1",
            "hostname": "vm1",
            "dns_domain": "example.org",
        },
        "00000000-0000-0000-0000-000000000002": {
            "state": "stopped",
            "alias": "vm2",
            "hostname": "vm2",
            "dns_domain": "example.org",
        },
    }

@pytest.fixture
def mock_vm_two_started():
    return {
        "00000000-0000-0000-0000-000000000001": {
            "state": "running",
            "alias": "vm1",
            "hostname": "vm1",
            "dns_domain": "example.org",
        },
        "00000000-0000-0000-0000-000000000002": {
            "state": "running",
            "alias": "vm2",
            "hostname": "vm2",
            "dns_domain": "example.org",
        },
    }

def test_non_list_config():
    """
    We only have minimal validation so we test that here
    """
    config = {}

    ret = vmadm.validate(config)

    assert ret == (False, "Configuration for vmadm beacon must be a list!")

def test_created_startup(mock_clean_state, mock_vm_one):
    """
    Test with one vm and startup_create_event
    """
    # NOTE: this should yield 1 created event + one state event
    with patch.dict(vmadm.VMADM_STATE, mock_clean_state), patch.dict(
        vmadm.__salt__, {"vmadm.list": MagicMock(return_value=mock_vm_one)}
    ):

        config = [{"startup_create_event": True}]

        ret = vmadm.validate(config)
        assert ret == (True, "Valid beacon configuration")

        ret = vmadm.beacon(config)
        res = [
            {
                "alias": "vm1",
                "tag": "created/00000000-0000-0000-0000-000000000001",
                "hostname": "vm1",
                "dns_domain": "example.org",
            },
            {
                "alias": "vm1",
                "tag": "running/00000000-0000-0000-0000-000000000001",
                "hostname": "vm1",
                "dns_domain": "example.org",
            },
        ]
        assert ret == res

def test_created_nostartup(mock_clean_state, mock_vm_one):
    """
    Test with one image and startup_import_event unset/false
    """
    # NOTE: this should yield 0 created event _ one state event
    with patch.dict(vmadm.VMADM_STATE, mock_clean_state), patch.dict(
        vmadm.__salt__, {"vmadm.list": MagicMock(return_value=mock_vm_one)}
    ):

        config = []

        ret = vmadm.validate(config)
        assert ret == (True, "Valid beacon configuration")

        ret = vmadm.beacon(config)
        res = [
            {
                "alias": "vm1",
                "tag": "running/00000000-0000-0000-0000-000000000001",
                "hostname": "vm1",
                "dns_domain": "example.org",
            }
        ]

        assert ret == res

def test_created(mock_clean_state, mock_vm_one, mock_vm_two_started):
    """
    Test with one vm, create a 2nd one
    """
    # NOTE: this should yield 1 created event + state event
    with patch.dict(vmadm.VMADM_STATE, mock_clean_state), patch.dict(
        vmadm.__salt__,
        {"vmadm.list": MagicMock(side_effect=[mock_vm_one, mock_vm_two_started])},
    ):

        config = []

        ret = vmadm.validate(config)
        assert ret == (True, "Valid beacon configuration")

        # Initial pass (Initialized state and do not yield created events at startup)
        ret = vmadm.beacon(config)

        # Second pass (After create a new vm)
        ret = vmadm.beacon(config)
        res = [
            {
                "alias": "vm2",
                "tag": "created/00000000-0000-0000-0000-000000000002",
                "hostname": "vm2",
                "dns_domain": "example.org",
            },
            {
                "alias": "vm2",
                "tag": "running/00000000-0000-0000-0000-000000000002",
                "hostname": "vm2",
                "dns_domain": "example.org",
            },
        ]

        assert ret == res

def test_deleted(mock_clean_state, mock_vm_two_stopped, mock_vm_one):
    """
    Test with two vms and one gets destroyed
    """
    # NOTE: this should yield 1 destroyed event
    with patch.dict(vmadm.VMADM_STATE, mock_clean_state), patch.dict(
        vmadm.__salt__,
        {"vmadm.list": MagicMock(side_effect=[mock_vm_two_stopped, mock_vm_one])},
    ):

        config = []

        ret = vmadm.validate(config)
        assert ret == (True, "Valid beacon configuration")

        # Initial pass (Initialized state and do not yield created vms at startup)
        ret = vmadm.beacon(config)

        # Second pass (Destroying one vm)
        ret = vmadm.beacon(config)
        res = [
            {
                "alias": "vm2",
                "tag": "deleted/00000000-0000-0000-0000-000000000002",
                "hostname": "vm2",
                "dns_domain": "example.org",
            }
        ]

        assert ret == res

def test_complex(
    mock_clean_state, mock_vm_one, mock_vm_two_started, mock_vm_two_stopped
):
    """
    Test with two vms, stop one, delete one
    """
    # NOTE: this should yield 1 delete and 2 import events
    with patch.dict(vmadm.VMADM_STATE, mock_clean_state), patch.dict(
        vmadm.__salt__,
        {
            "vmadm.list": MagicMock(
                side_effect=[mock_vm_two_started, mock_vm_two_stopped, mock_vm_one]
            )
        },
    ):

        config = []

        ret = vmadm.validate(config)
        assert ret == (True, "Valid beacon configuration")

        # Initial pass (Initialized state and do not yield created events at startup)
        ret = vmadm.beacon(config)

        # Second pass (Stop one vm)
        ret = vmadm.beacon(config)
        res = [
            {
                "alias": "vm2",
                "tag": "stopped/00000000-0000-0000-0000-000000000002",
                "hostname": "vm2",
                "dns_domain": "example.org",
            }
        ]

        assert ret == res

        # Third pass (Delete one vm)
        ret = vmadm.beacon(config)
        res = [
            {
                "alias": "vm2",
                "tag": "deleted/00000000-0000-0000-0000-000000000002",
                "hostname": "vm2",
                "dns_domain": "example.org",
            }
        ]

        assert ret == res

redpajama_set_name: RedPajamaGithub


text:
using Arch.Data.Common.Logging;
using System;

namespace Arch.Data.DbEngine.Executor
{
    public interface IExecutor
    {
        void Daemon();

        void Dispose();

        Boolean EnqueueLogEntry(ILogEntry entry);

        Boolean EnqueueCallback(Action callback);

        void StartRWCallback(Action callback, Int32 delay);

    }
}


text:
<?php

namespace frontend\models;

/**
 * This is the ActiveQuery class for [[Gender]].
 *
 * @see Gender
 */
class GenderQuery extends \yii\db\ActiveQuery
{
    /*public function active()
    {
        $this->andWhere('[[status]]=1');
        return $this;
    }*/

    /**
     * @inheritdoc
     * @return Gender[]|array
     */
    public function all($db = null)
    {
        return parent::all($db);
    }

    /**
     * @inheritdoc
     * @return Gender|array|null
     */
    public function one($db = null)
    {
        return parent::one($db);
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package id.ac.itb.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author billysusanto
 */
@Entity
@Table(name = "mahasiswa")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Mahasiswa.findAll", query = "SELECT m FROM Mahasiswa m"),
    @NamedQuery(name = "Mahasiswa.findByIdMhs", query = "SELECT m FROM Mahasiswa m WHERE m.idMhs = :idMhs"),
    @NamedQuery(name = "Mahasiswa.findByNim", query = "SELECT m FROM Mahasiswa m WHERE m.nim = :nim"),
    @NamedQuery(name = "Mahasiswa.findByNoRegistrasi", query = "SELECT m FROM Mahasiswa m WHERE m.noRegistrasi = :noRegistrasi"),
    @NamedQuery(name = "Mahasiswa.findByEmail", query = "SELECT m FROM Mahasiswa m WHERE m.email = :email"),
    @NamedQuery(name = "Mahasiswa.findByNama", query = "SELECT m FROM Mahasiswa m WHERE m.nama = :nama"),
    @NamedQuery(name = "Mahasiswa.findByAlamat", query = "SELECT m FROM Mahasiswa m WHERE m.alamat = :alamat"),
    @NamedQuery(name = "Mahasiswa.findByStatus", query = "SELECT m FROM Mahasiswa m WHERE m.status = :status"),
    @NamedQuery(name = "Mahasiswa.findByWali", query = "SELECT m FROM Mahasiswa m, WaliMhs w WHERE m.idMhs = w.idMhs AND w.idDosen = :idDosen")})
public class Mahasiswa extends AbstractModel implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id_mhs")
    private Integer idMhs;
    @Basic(optional = false)
    @NotNull
    @Column(name = "NIM")
    private int nim;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 20)
    @Column(name = "no_registrasi")
    private String noRegistrasi;
    // @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 20)
    @Column(name = "email")
    private String email;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 50)
    @Column(name = "nama")
    private String nama;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 50)
    @Column(name = "alamat")
    private String alamat;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 20)
    @Column(name = "status")
    private String status;

    public Mahasiswa() {
    }

    public Mahasiswa(Integer idMhs) {
        this.idMhs = idMhs;
    }

    public Mahasiswa(Integer idMhs, int nim, String noRegistrasi, String email, String nama, String alamat, String status) {
        this.idMhs = idMhs;
        this.nim = nim;
        this.noRegistrasi = noRegistrasi;
        this.email = email;
        this.nama = nama;
        this.alamat = alamat;
        this.status = status;
    }

    public Integer getIdMhs() {
        return idMhs;
    }

    public void setIdMhs(Integer idMhs) {
        this.idMhs = idMhs;
    }

    public int getNim() {
        return nim;
    }

    public void setNim(int nim) {
        this.nim = nim;
    }

    public String getNoRegistrasi() {
        return noRegistrasi;
    }

    public void setNoRegistrasi(String noRegistrasi) {
        this.noRegistrasi = noRegistrasi;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getNama() {
        return nama;
    }

    public void setNama(String nama) {
        this.nama = nama;
    }

    public String getAlamat() {
        return alamat;
    }

    public void setAlamat(String alamat) {
        this.alamat = alamat;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (idMhs != null ? idMhs.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Mahasiswa)) {
            return false;
        }
        Mahasiswa other = (Mahasiswa) object;
        if ((this.idMhs == null && other.idMhs != null) || (this.idMhs != null && !this.idMhs.equals(other.idMhs))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "id.ac.itb.model.Mahasiswa[ idMhs=" + idMhs + " ]";
    }

    @Override
    @JsonIgnore
    public String getName() {
        return "" + this.nama;
    }

    @Override
    @JsonIgnore
    public String getPkUrl() {
        return "" + this.idMhs;
    }

}


text:
package com.google.gdata.data.webmastertools;

import com.google.gdata.data.ExtensionDescription;
import com.google.gdata.data.ValueConstruct;

/**
 * Detail of the crawl issue.
 *
 *
 */
@ExtensionDescription.Default(
    nsAlias = Namespaces.WT_ALIAS,
    nsUri = Namespaces.WT,
    localName = CrawlIssueDetail.XML_NAME)
public class CrawlIssueDetail extends ValueConstruct {

  /** XML element name */
  static final String XML_NAME = "detail";

  /**
   * Default mutable constructor.
   */
  public CrawlIssueDetail() {
    this(null);
  }

  /**
   * Constructor (mutable or immutable).
   *
   * @param detail immutable value or null for a mutable value
   */
  public CrawlIssueDetail(String detail) {
    super(Namespaces.WT_NS, XML_NAME, null, detail);
    setRequired(false);
  }

  /**
   * Returns the value.
   *
   * @return value
   */
  public String getDetail() {
    return getValue();
  }

  /**
   * Sets the value.
   *
   * @param detail value or null to reset
   */
  public void setDetail(String detail) {
    setValue(detail);
  }

  /**
   * Returns whether it has the value.
   *
   * @return whether it has the value
   */
  public boolean hasDetail() {
    return hasValue();
  }

  /**
   * Returns the extension description, specifying whether it is required, and
   * whether it is repeatable.
   *
   * @param required   whether it is required
   * @param repeatable whether it is repeatable
   * @return extension description
   */
  public static ExtensionDescription getDefaultDescription(boolean required,
      boolean repeatable) {
    ExtensionDescription desc =
        ExtensionDescription.getDefaultDescription(CrawlIssueDetail.class);
    desc.setRequired(required);
    desc.setRepeatable(repeatable);
    return desc;
  }

  @Override
  public String toString() {
    return "{CrawlIssueDetail detail=" + getValue() + "}";
  }

}


text:
package middleware

import (
	"net/http"
)

// New : Create new chainable middleware app.
func New(funcs ...func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)) *App {
	app := new(App)
	app.handlers = funcs
	return app
}

//ServeHTTP : Serve app as http.
func ServeHTTP(app HandlerSlice, w http.ResponseWriter, r *http.Request) {
	ServeMiddleware(app, w, r, voidNextFunc)
}

// ServeMiddleware : Serve  app as middleware.
func ServeMiddleware(app HandlerSlice, w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	composeHandler(app.Handlers()...)(w, r, next)
}

func composeHandler(series ...func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)) func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	return func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
		if len(series) == 0 {
			next(w, r)
			return
		}
		h := series[0]
		if h == nil {
			composeHandler(series[1:]...)(w, r, next)
			return
		}
		series[0](w, r, func(w http.ResponseWriter, r *http.Request) {
			composeHandler(series[1:]...)(w, r, next)
		})
	}
}

//Chain : Append All middlewares in src to dst.
//Dst will not change when new middleware appended to src.
func Chain(dst HandlerChain, src ...HandlerSlice) {
	if len(src) == 0 {
		return
	}
	funcs := dst.Handlers()
	funcs = append(funcs, AppToMiddlewares(src...)...)
	f := make([]func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc), len(funcs))
	copy(f, funcs)
	dst.SetHandlers(f)
}

//AppToMiddlewares : Convert App to slice of middleware.
func AppToMiddlewares(app ...HandlerSlice) []func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	funcs := []func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc){}
	for _, v := range app {
		funcs = append(funcs, v.Handlers()...)
	}
	return funcs
}

//Append : Append middlewares tp app.
func Append(app HandlerChain, middlewares ...func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)) {
	funcs := append(app.Handlers(), middlewares...)
	f := make([]func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc), len(funcs))
	copy(f, funcs)
	app.SetHandlers(f)
}

// WrapFunc : Wrap http.HandlerFunc [func(w http.ResponseWriter, r *http.Request)] to middleware.
// Next will be called after handlerFunc finish .
func WrapFunc(handlerFunc http.HandlerFunc) func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	return func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
		handlerFunc(w, r)
		next(w, r)
	}
}

// Wrap : Wrap http.Handler to middleware.
// Next will be called after handlerFunc finish .
func Wrap(f http.Handler) func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	return func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
		f.ServeHTTP(w, r)
		next(w, r)
	}
}

func voidNextFunc(w http.ResponseWriter, r *http.Request) {
}
func voidMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	next(w, r)
}

// HandlerSlice : interface which contains slice of middlewares.
type HandlerSlice interface {
	Handlers() []func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)
}

// HandlerChain : interface which contains slice of middlewares which can be updated.
type HandlerChain interface {
	HandlerSlice
	SetHandlers([]func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc))
}

// App : Slice of middlewares with tons of helpful method.
type App struct {
	handlers []func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)
}

// Handlers : Return all middlewares in app.
func (a *App) Handlers() []func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	return a.handlers
}

// SetHandlers : Set app's middlewares.
func (a *App) SetHandlers(h []func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)) {
	a.handlers = h
}

// ServeMiddleware : Use app as a middleware.
func (a *App) ServeMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	ServeMiddleware(a, w, r, next)
}

// ServeHTTP : Use app as a http handler.
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	ServeHTTP(a, w, r)
}

// HandleFunc : Use http HandlerFunc as last middleware.
func (a *App) HandleFunc(HandlerFunc http.HandlerFunc) *App {
	Append(a, WrapFunc(HandlerFunc))
	return a
}

// Handle : Use http Handler as last middleware.
func (a *App) Handle(Handler http.Handler) *App {
	Append(a, Wrap(Handler))
	return a
}

//Append : Append middlewares tp app.
func (a *App) Append(middlewares ...func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)) {
	Append(a, middlewares...)

}

// Use : Append middlewares to app and return app self.
func (a *App) Use(middlewares ...func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)) *App {
	a.Append(middlewares...)
	return a
}

// Chain : Append All middlewares in src to app.
//App will not change when new middleware appended to src.
func (a *App) Chain(src ...HandlerSlice) *App {
	Chain(a, src...)
	return a
}

// UseApp : Append apps as middlewares to app.
// App will change when new middleware appended to apps.
func (a *App) UseApp(apps ...*App) *App {
	funcs := make([]func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc), len(apps))
	for k := range apps {
		funcs[k] = apps[k].ServeMiddleware
	}
	Append(a, funcs...)
	return a
}

//Middleware middleware interface.
type Middleware func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)

// Handlers : Return all middlewares in app.
func (m Middleware) Handlers() []func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	return []func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc){m}
}

// ServeHTTP : Use middleware as a http handler.
func (m Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	ServeHTTP(m, w, r)
}

// Middlewares middleware list interaface.
type Middlewares []func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)

// Handlers : Return all middlewares in middlewares.
func (m *Middlewares) Handlers() []func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	return *m
}

// SetHandlers : Set middlewares's middlewares.
func (m *Middlewares) SetHandlers(h []func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)) {
	ms := make([]func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc), len(h))
	copy(h, ms)
	*m = ms
}

//Append : Append middlewares tp app.
func (m *Middlewares) Append(middlewares ...func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)) {
	Append(m, middlewares...)

}

// Use : Append middlewares and return middlewares self.
func (m *Middlewares) Use(middlewares ...func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)) *Middlewares {
	m.Append(middlewares...)
	return m

}

//App create app with middlewares
func (m *Middlewares) App(handler func(w http.ResponseWriter, r *http.Request)) *App {
	app := New(m.Handlers()...)
	app.HandleFunc(handler)
	return app
}

// ServeMiddleware : Use middlewares as a middleware.
func (m *Middlewares) ServeMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	ServeMiddleware(m, w, r, next)
}

// ServeHTTP : Use middlewares as a http handler.
func (m *Middlewares) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	ServeHTTP(m, w, r)
}

//NewMiddlewares create new middlewares with given handlers
func NewMiddlewares(middlewares ...func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)) *Middlewares {
	ms := make([]func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc), len(middlewares))
	copy(middlewares, ms)
	m := Middlewares(ms)
	return &m
}


text:
<?php

namespace Zend\Form;

interface ElementAttributeRemovalInterface
{
    /**
     * Remove a single element attribute
     *
     * @param  string $key
     * @return ElementAttributeRemovalInterface
     */
    public function removeAttribute($key);

    /**
     * Remove many attributes at once
     *
     * @param array $keys
     * @return ElementAttributeRemovalInterface
     */
    public function removeAttributes(array $keys);

    /**
     * Remove all attributes at once
     *
     * @return ElementAttributeRemovalInterface
     */
    public function clearAttributes();
}


text: <canvas id="myChart" width="400" height="400"></canvas>


text:
"""
Module checking the behaviour of iPOPO with PEP-557 Data Classes

:author: Thomas Calmant
:copyright: Copyright 2020, Thomas Calmant
:license: Apache License 2.0

..

    Copyright 2020 Thomas Calmant

    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.
"""

try:
    dataclass
except NameError:
    try:
        from dataclasses import dataclass
    except ImportError:
        raise Exception("dataclass decorator not available "
                        "(Python 3.6+ required)")

from pelix.ipopo.decorators import ComponentFactory, Property, Provides, \
    Requires

@ComponentFactory("dataclass.before")
@Provides("dataclass.before")
@Property("property_set", "property.set", "SAMPLE")
@Property("property_default", "property.default")
@Requires("requirement", "dataclass.check")
@dataclass
class DataClassBeforeManipulation:
    some_value: str = "42"
    instance_name: str = None
    requirement: object = None
    property_set: str = "Default"
    property_default: str = "Default"

@dataclass
@ComponentFactory("dataclass.after")
@Provides("dataclass.after")
@Property("property_set", "property.set", "SAMPLE")
@Property("property_default", "property.default")
@Requires("requirement", "dataclass.check")
class DataClassAfterManipulation:
    some_value: str = "42"
    instance_name: str = None
    requirement: object = None
    property_set: str = "Default"
    property_default: str = "Default"


text:
#ifndef R_EXASOL_ODBC_SESSION_INFO_IMPL_H
#define R_EXASOL_ODBC_SESSION_INFO_IMPL_H

#include <r_exasol/connection/async_executor/async_executor_session_info.h>
#include <r_exasol/external/r_odbc_fwd.h>
#include <r_exasol/external/sql.h>

namespace exa {
    /**
     * Implementation of the AsyncExecutorSessionInfo which stores the ODBCHandle and Query.
     */
    struct OdbcSessionInfoImpl : public exa::AsyncExecutorSessionInfo {
        OdbcSessionInfoImpl(pRODBCHandle handle, SQLCHAR *query);
        /**
         * Creates an instance of @class OdbcAsyncExecutorImpl.
         * @return  instance of @class OdbcAsyncExecutorImpl.
         */
        std::unique_ptr<AsyncExecutor> createAsyncExecutor() const override;
        /**
         * External Odbc handle.
         */
        ::pRODBCHandle mHandle;
        /**
         * Query string.
         */
        ::SQLCHAR *mQuery;
    };
}

#endif //R_EXASOL_ODBC_SESSION_INFO_IMPL_H


text:
.class Landroid/speech/tts/TextToSpeechService$CallbackMap;
.super Landroid/os/RemoteCallbackList;
.source "TextToSpeechService.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/speech/tts/TextToSpeechService;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x2
    name = "CallbackMap"
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Landroid/os/RemoteCallbackList",
        "<",
        "Landroid/speech/tts/ITextToSpeechCallback;",
        ">;"
    }
.end annotation

# instance fields
.field private final mCallerToCallback:Ljava/util/HashMap;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/HashMap",
            "<",
            "Landroid/os/IBinder;",
            "Landroid/speech/tts/ITextToSpeechCallback;",
            ">;"
        }
    .end annotation
.end field

.field final synthetic this$0:Landroid/speech/tts/TextToSpeechService;

# direct methods
.method private constructor <init>(Landroid/speech/tts/TextToSpeechService;)V
    .locals 1

    .prologue
    .line 1329
    iput-object p1, p0, Landroid/speech/tts/TextToSpeechService$CallbackMap;->this$0:Landroid/speech/tts/TextToSpeechService;

    invoke-direct {p0}, Landroid/os/RemoteCallbackList;-><init>()V

    .line 1330
    new-instance v0, Ljava/util/HashMap;

    invoke-direct {v0}, Ljava/util/HashMap;-><init>()V

    iput-object v0, p0, Landroid/speech/tts/TextToSpeechService$CallbackMap;->mCallerToCallback:Ljava/util/HashMap;

    return-void
.end method

.method synthetic constructor <init>(Landroid/speech/tts/TextToSpeechService;Landroid/speech/tts/TextToSpeechService$1;)V
    .locals 0
    .param p1, "x0"    # Landroid/speech/tts/TextToSpeechService;
    .param p2, "x1"    # Landroid/speech/tts/TextToSpeechService$1;

    .prologue
    .line 1329
    invoke-direct {p0, p1}, Landroid/speech/tts/TextToSpeechService$CallbackMap;-><init>(Landroid/speech/tts/TextToSpeechService;)V

    return-void
.end method

.method private getCallbackFor(Ljava/lang/Object;)Landroid/speech/tts/ITextToSpeechCallback;
    .locals 4
    .param p1, "caller"    # Ljava/lang/Object;

    .prologue
    .line 1409
    move-object v0, p1

    check-cast v0, Landroid/os/IBinder;

    .line 1410
    .local v0, "asBinder":Landroid/os/IBinder;
    iget-object v3, p0, Landroid/speech/tts/TextToSpeechService$CallbackMap;->mCallerToCallback:Ljava/util/HashMap;

    monitor-enter v3

    .line 1411
    :try_start_0
    iget-object v2, p0, Landroid/speech/tts/TextToSpeechService$CallbackMap;->mCallerToCallback:Ljava/util/HashMap;

    invoke-virtual {v2, v0}, Ljava/util/HashMap;->get(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Landroid/speech/tts/ITextToSpeechCallback;

    .line 1412
    .local v1, "cb":Landroid/speech/tts/ITextToSpeechCallback;
    monitor-exit v3

    .line 1414
    return-object v1

    .line 1412
    .end local v1    # "cb":Landroid/speech/tts/ITextToSpeechCallback;
    :catchall_0
    move-exception v2

    monitor-exit v3
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    throw v2
.end method

# virtual methods
.method public dispatchOnError(Ljava/lang/Object;Ljava/lang/String;I)V
    .locals 5
    .param p1, "callerIdentity"    # Ljava/lang/Object;
    .param p2, "utteranceId"    # Ljava/lang/String;
    .param p3, "errorCode"    # I

    .prologue
    .line 1381
    invoke-direct {p0, p1}, Landroid/speech/tts/TextToSpeechService$CallbackMap;->getCallbackFor(Ljava/lang/Object;)Landroid/speech/tts/ITextToSpeechCallback;

    move-result-object v0

    .line 1382
    .local v0, "cb":Landroid/speech/tts/ITextToSpeechCallback;
    if-nez v0, :cond_0

    .line 1388
    :goto_0
    return-void

    .line 1384
    :cond_0
    :try_start_0
    invoke-interface {v0, p2, p3}, Landroid/speech/tts/ITextToSpeechCallback;->onError(Ljava/lang/String;I)V
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    goto :goto_0

    .line 1385
    :catch_0
    move-exception v1

    .line 1386
    .local v1, "e":Landroid/os/RemoteException;
    const-string v2, "TextToSpeechService"

    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string v4, "Callback onError failed: "

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    invoke-static {v2, v3}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    goto :goto_0
.end method

.method public dispatchOnStart(Ljava/lang/Object;Ljava/lang/String;)V
    .locals 5
    .param p1, "callerIdentity"    # Ljava/lang/Object;
    .param p2, "utteranceId"    # Ljava/lang/String;

    .prologue
    .line 1369
    invoke-direct {p0, p1}, Landroid/speech/tts/TextToSpeechService$CallbackMap;->getCallbackFor(Ljava/lang/Object;)Landroid/speech/tts/ITextToSpeechCallback;

    move-result-object v0

    .line 1370
    .local v0, "cb":Landroid/speech/tts/ITextToSpeechCallback;
    if-nez v0, :cond_0

    .line 1377
    :goto_0
    return-void

    .line 1372
    :cond_0
    :try_start_0
    invoke-interface {v0, p2}, Landroid/speech/tts/ITextToSpeechCallback;->onStart(Ljava/lang/String;)V
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    goto :goto_0

    .line 1373
    :catch_0
    move-exception v1

    .line 1374
    .local v1, "e":Landroid/os/RemoteException;
    const-string v2, "TextToSpeechService"

    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string v4, "Callback onStart failed: "

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    invoke-static {v2, v3}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    goto :goto_0
.end method

.method public dispatchOnStop(Ljava/lang/Object;Ljava/lang/String;)V
    .locals 5
    .param p1, "callerIdentity"    # Ljava/lang/Object;
    .param p2, "utteranceId"    # Ljava/lang/String;

    .prologue
    .line 1349
    invoke-direct {p0, p1}, Landroid/speech/tts/TextToSpeechService$CallbackMap;->getCallbackFor(Ljava/lang/Object;)Landroid/speech/tts/ITextToSpeechCallback;

    move-result-object v0

    .line 1350
    .local v0, "cb":Landroid/speech/tts/ITextToSpeechCallback;
    if-nez v0, :cond_0

    .line 1356
    :goto_0
    return-void

    .line 1352
    :cond_0
    :try_start_0
    invoke-interface {v0, p2}, Landroid/speech/tts/ITextToSpeechCallback;->onStop(Ljava/lang/String;)V
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    goto :goto_0

    .line 1353
    :catch_0
    move-exception v1

    .line 1354
    .local v1, "e":Landroid/os/RemoteException;
    const-string v2, "TextToSpeechService"

    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string v4, "Callback onStop failed: "

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    invoke-static {v2, v3}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    goto :goto_0
.end method

.method public dispatchOnSuccess(Ljava/lang/Object;Ljava/lang/String;)V
    .locals 5
    .param p1, "callerIdentity"    # Ljava/lang/Object;
    .param p2, "utteranceId"    # Ljava/lang/String;

    .prologue
    .line 1359
    invoke-direct {p0, p1}, Landroid/speech/tts/TextToSpeechService$CallbackMap;->getCallbackFor(Ljava/lang/Object;)Landroid/speech/tts/ITextToSpeechCallback;

    move-result-object v0

    .line 1360
    .local v0, "cb":Landroid/speech/tts/ITextToSpeechCallback;
    if-nez v0, :cond_0

    .line 1366
    :goto_0
    return-void

    .line 1362
    :cond_0
    :try_start_0
    invoke-interface {v0, p2}, Landroid/speech/tts/ITextToSpeechCallback;->onSuccess(Ljava/lang/String;)V
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    goto :goto_0

    .line 1363
    :catch_0
    move-exception v1

    .line 1364
    .local v1, "e":Landroid/os/RemoteException;
    const-string v2, "TextToSpeechService"

    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string v4, "Callback onDone failed: "

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    invoke-static {v2, v3}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    goto :goto_0
.end method

.method public kill()V
    .locals 2

    .prologue
    .line 1401
    iget-object v1, p0, Landroid/speech/tts/TextToSpeechService$CallbackMap;->mCallerToCallback:Ljava/util/HashMap;

    monitor-enter v1

    .line 1402
    :try_start_0
    iget-object v0, p0, Landroid/speech/tts/TextToSpeechService$CallbackMap;->mCallerToCallback:Ljava/util/HashMap;

    invoke-virtual {v0}, Ljava/util/HashMap;->clear()V

    .line 1403
    invoke-super {p0}, Landroid/os/RemoteCallbackList;->kill()V

    .line 1404
    monitor-exit v1

    .line 1405
    return-void

    .line 1404
    :catchall_0
    move-exception v0

    monitor-exit v1
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    throw v0
.end method

.method public bridge synthetic onCallbackDied(Landroid/os/IInterface;Ljava/lang/Object;)V
    .locals 0

    .prologue
    .line 1329
    check-cast p1, Landroid/speech/tts/ITextToSpeechCallback;

    invoke-virtual {p0, p1, p2}, Landroid/speech/tts/TextToSpeechService$CallbackMap;->onCallbackDied(Landroid/speech/tts/ITextToSpeechCallback;Ljava/lang/Object;)V

    return-void
.end method

.method public onCallbackDied(Landroid/speech/tts/ITextToSpeechCallback;Ljava/lang/Object;)V
    .locals 3
    .param p1, "callback"    # Landroid/speech/tts/ITextToSpeechCallback;
    .param p2, "cookie"    # Ljava/lang/Object;

    .prologue
    .line 1392
    move-object v0, p2

    check-cast v0, Landroid/os/IBinder;

    .line 1393
    .local v0, "caller":Landroid/os/IBinder;
    iget-object v2, p0, Landroid/speech/tts/TextToSpeechService$CallbackMap;->mCallerToCallback:Ljava/util/HashMap;

    monitor-enter v2

    .line 1394
    :try_start_0
    iget-object v1, p0, Landroid/speech/tts/TextToSpeechService$CallbackMap;->mCallerToCallback:Ljava/util/HashMap;

    invoke-virtual {v1, v0}, Ljava/util/HashMap;->remove(Ljava/lang/Object;)Ljava/lang/Object;

    .line 1395
    monitor-exit v2

    .line 1397
    return-void

    .line 1395
    :catchall_0
    move-exception v1

    monitor-exit v2
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    throw v1
.end method

.method public setCallback(Landroid/os/IBinder;Landroid/speech/tts/ITextToSpeechCallback;)V
    .locals 3
    .param p1, "caller"    # Landroid/os/IBinder;
    .param p2, "cb"    # Landroid/speech/tts/ITextToSpeechCallback;

    .prologue
    .line 1334
    iget-object v2, p0, Landroid/speech/tts/TextToSpeechService$CallbackMap;->mCallerToCallback:Ljava/util/HashMap;

    monitor-enter v2

    .line 1336
    if-eqz p2, :cond_1

    .line 1337
    :try_start_0
    invoke-virtual {p0, p2, p1}, Landroid/speech/tts/TextToSpeechService$CallbackMap;->register(Landroid/os/IInterface;Ljava/lang/Object;)Z

    .line 1338
    iget-object v1, p0, Landroid/speech/tts/TextToSpeechService$CallbackMap;->mCallerToCallback:Ljava/util/HashMap;

    invoke-virtual {v1, p1, p2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/speech/tts/ITextToSpeechCallback;

    .line 1342
    .local v0, "old":Landroid/speech/tts/ITextToSpeechCallback;
    :goto_0
    if-eqz v0, :cond_0

    if-eq v0, p2, :cond_0

    .line 1343
    invoke-virtual {p0, v0}, Landroid/speech/tts/TextToSpeechService$CallbackMap;->unregister(Landroid/os/IInterface;)Z

    .line 1345
    :cond_0
    monitor-exit v2

    .line 1346
    return-void

    .line 1340
    .end local v0    # "old":Landroid/speech/tts/ITextToSpeechCallback;
    :cond_1
    iget-object v1, p0, Landroid/speech/tts/TextToSpeechService$CallbackMap;->mCallerToCallback:Ljava/util/HashMap;

    invoke-virtual {v1, p1}, Ljava/util/HashMap;->remove(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/speech/tts/ITextToSpeechCallback;

    .restart local v0    # "old":Landroid/speech/tts/ITextToSpeechCallback;
    goto :goto_0

    .line 1345
    .end local v0    # "old":Landroid/speech/tts/ITextToSpeechCallback;
    :catchall_0
    move-exception v1

    monitor-exit v2
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    throw v1
.end method


text:
// Boost.Bimap
//
// Copyright (c) 2006-2007 Matias Capeletto
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

/// \file relation/support/is_tag_of_member_at.hpp
/// \brief is_tag_of_member_at<tag,relation> metafunction

#ifndef BOOST_BIMAP_RELATION_SUPPORT_IS_TAG_OF_MEMBER_AT_HPP
#define BOOST_BIMAP_RELATION_SUPPORT_IS_TAG_OF_MEMBER_AT_HPP

#if defined(_MSC_VER) && (_MSC_VER>=1200)
#pragma once
#endif

#include <boost/config.hpp>

#include <boost/bimap/relation/member_at.hpp>
#include <boost/type_traits/is_same.hpp>

#include <boost/mpl/bool.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/bimap/relation/support/member_with_tag.hpp>

/** \struct boost::bimaps::relation::support::is_tag_of_member_at_left

\brief Metafunction to test if a user tag is refering to the left member.

\code

template< class Tag, class Relation >
struct is_tag_of_member_at_left : {true_|false_} {};

\endcode

This metafunction is somewhat redundant with member_with_tag, but it is included
because it is a lot easier to metaprogram with it. The result type is the
same that:

\code

 is_same< member_with_tag<Tag,Relation>::type , member_at::left >::type

\endcode

See also member_with_tag, member_at, is_tag_of_member_at_right.
\ingroup relation_group
                                                                             **/

/** \struct boost::bimaps::relation::support::is_tag_of_member_at_right

\brief Metafunction to test if a user tag is refering to the left member.

\code

template< class Tag, class Relation >
struct is_tag_of_member_at_right : {true_|false_} {};

\endcode

This metafunction is somewhat redundat with member_with_tag, but it is included
because it is a lot easier to metaprogram with it. The result type is the
same that:

\code

 is_same< member_with_tag<Tag,Relation>::type , member_at::right >::type

\endcode

See also member_with_tag, member_at, is_tag_of_member_at_left.
\ingroup relation_group
                                                                             **/

#ifndef BOOST_BIMAP_DOXYGEN_WILL_NOT_PROCESS_THE_FOLLOWING_LINES

namespace boost {
namespace bimaps {
namespace relation {
namespace support {

// Metafunction is_tag_of_member_at_left
// Easiear metaprogramming

template
<
    class Tag,
    class Relation,
    class Enable = void
>
struct is_tag_of_member_at_left :
    ::boost::mpl::false_ {};

template< class Tag, class Relation >
struct is_tag_of_member_at_left
<
    Tag, Relation,
    BOOST_DEDUCED_TYPENAME enable_if
    <
        is_same
        <
            BOOST_DEDUCED_TYPENAME member_with_tag<Tag,Relation>::type,
            member_at::left
        >

    >::type
> :
    ::boost::mpl::true_ {};

// Metafunction is_tag_of_member_at_right
// Easiear metaprogramming

template
<
    class Tag,
    class Relation,
    class Enable = void
>
struct is_tag_of_member_at_right :
    ::boost::mpl::false_ {};

template< class Tag, class Relation >
struct is_tag_of_member_at_right
<
    Tag, Relation,
    BOOST_DEDUCED_TYPENAME enable_if
    <
        is_same
        <
            BOOST_DEDUCED_TYPENAME member_with_tag<Tag,Relation>::type,
            member_at::right
        >

    >::type
> :
    ::boost::mpl::true_ {};

// Metafunction is_tag_of_member_at_info
// Easiear metaprogramming

template
<
    class Tag,
    class Relation,
    class Enable = void
>
struct is_tag_of_member_at_info :
    ::boost::mpl::false_ {};

template< class Tag, class Relation >
struct is_tag_of_member_at_info
<
    Tag, Relation,
    BOOST_DEDUCED_TYPENAME enable_if
    <
        is_same
        <
            BOOST_DEDUCED_TYPENAME member_with_tag<Tag,Relation>::type,
            member_at::info
        >

    >::type
> :
    ::boost::mpl::true_ {};

} // namespace support
} // namespace relation
} // namespace bimaps
} // namespace boost

#endif // BOOST_BIMAP_DOXYGEN_WILL_NOT_PROCESS_THE_FOLLOWING_LINES

#endif // BOOST_BIMAP_RELATION_SUPPORT_IS_TAG_OF_MEMBER_AT_HPP


text:
package com.bearapp.androidtraining;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ReceiveDataFromOtherAppActivity extends Activity {

    @BindView(R.id.tv_text)
    TextView textView;
    @BindView(R.id.iv_image)
    ImageView imageView;

    private static final int REQUEST_EXTERNAL_STORAGE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receive_data_from_other_app);
        ButterKnife.bind(this);
        checkPermission();
    }

    private void checkPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                // should show the explanation
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("提示")
                        .setMessage("应用需要读取本地存储")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                requestPermission();
                            }
                        });
                builder.show();

            } else {
                requestPermission();
            }
        } else {
            handleIntent();
        }
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_EXTERNAL_STORAGE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_EXTERNAL_STORAGE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    handleIntent();
                } else {
                    Toast.makeText(getApplicationContext(), "未获得权限!", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private void handleIntent() {
        Intent intent = getIntent();
        String action = intent.getAction();
        String type = intent.getType();
        Bundle bundle = intent.getExtras();
        if (Intent.ACTION_SEND.equals(action) && type != null) {
            if (type.startsWith("text/")) {
                handleSendText(intent);
            } else if (type.startsWith("image/")) {
                handleSendImage(intent);
                handleSendText(intent);
            }
        } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
            if (type.startsWith("image/")) {
                handleSendMultipleImages(intent);
                handleSendText(intent);
            }
        } else {
            // handle other intents
        }

    }

    private void handleSendText(Intent intent) {
        String text = intent.getStringExtra(Intent.EXTRA_TEXT);
        if (text != null) {
            textView.setText(text);
        }
    }

    private void handleSendImage(Intent intent) {
        Uri imageUri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
        if (imageUri != null) {
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
                imageView.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void handleSendMultipleImages(Intent intent) {
        ArrayList<Uri> uriArrayList = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
        Uri imageUri = uriArrayList.get(0);
        if (imageUri != null) {
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
                imageView.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}


text:
@class NewShapeGameViewController;

@interface NewShapeGameAppDelegate : NSObject <UIApplicationDelegate>

@property (nonatomic, retain) IBOutlet UIWindow *window;

@property (nonatomic, retain) IBOutlet NewShapeGameViewController *viewController;

@end


text:
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Fody;
#pragma warning disable 618

static class WeavingHelper
{
    public static TestResult CreateIsolatedAssemblyCopy(string assemblyPath, string config, IEnumerable<string> references, string assemblyName)
    {
        var weavingTask = new ModuleWeaver
        {
            Config = XElement.Parse(config),
            ReferenceCopyLocalPaths = references.Select(r => Path.Combine(CodeBaseLocation.CurrentDirectory, r)).ToList(),
        };
        return weavingTask.ExecuteTestRun(assemblyPath,
            assemblyName: assemblyName,
            ignoreCodes: new []{ "0x80131869" },
            runPeVerify:false);
    }
}


text:
import numpy as np
import pandas as pd

import pypsa

#%matplotlib inline

# Generator marginal (m) and capital (c) costs in EUR/MWh - numbers chosen for simple answer
generators = {
    "coal": {"m": 2, "c": 15},
    "gas": {"m": 12, "c": 10},
    "load-shedding": {"m": 1012, "c": 0},
}

# Screening curve intersections at 0.01 and 0.5
x = np.linspace(0, 1, 101)
df = pd.DataFrame(
    {key: pd.Series(item["c"] + x * item["m"], x) for key, item in generators.items()}
)
df.plot(ylim=[0, 50], title="Screening Curve")

n = pypsa.Network()

num_snapshots = 1001

snapshots = np.linspace(0, 1, num_snapshots)

n.set_snapshots(snapshots)

n.snapshot_weightings = n.snapshot_weightings / num_snapshots

n.add("Bus", name="bus")

n.add("Load", name="load", bus="bus", p_set=1000 - 1000 * snapshots)

for gen in generators:
    n.add(
        "Generator",
        name=gen,
        bus="bus",
        p_nom_extendable=True,
        marginal_cost=float(generators[gen]["m"]),
        capital_cost=float(generators[gen]["c"]),
    )

n.loads_t.p_set.plot(title="Load Duration Curve")

n.lopf(solver_name="cbc")

print(n.objective)

# capacity set by total electricity required
# NB: no load shedding since all prices < 1e4
n.generators.p_nom_opt.round(2)

n.buses_t.marginal_price.plot(title="Price Duration Curve")

# The prices correspond either to VOLL (1012) for first 0.01 or the marginal costs (12 for 0.49 and 2 for 0.5)

# EXCEPT for (infinitesimally small) points at the screening curve intersections, which
# correspond to changing the load duration near the intersection, so that capacity changes
# This explains 7 = (12+10 - 15) (replacing coal with gas) and 22 = (12+10) (replacing load-shedding with gas)

# I have no idea what is causing \l = 0; it should be 2.

n.buses_t.marginal_price.round(2).sum(axis=1).value_counts()

n.generators_t.p.plot(ylim=[0, 600], title="Generation Dispatch")

# Demonstrate zero-profit condition
print("Total costs:")
print(
    n.generators.p_nom_opt * n.generators.capital_cost
    + n.generators_t.p.multiply(n.snapshot_weightings.generators, axis=0).sum()
    * n.generators.marginal_cost
)

print("\nTotal revenue:")
print(
    n.generators_t.p.multiply(n.snapshot_weightings.generators, axis=0)
    .multiply(n.buses_t.marginal_price["bus"], axis=0)
    .sum()
)

## Without expansion optimisation
#
# Take the capacities from the above long-term equilibrium, then disallow expansion.
#
# Show that the resulting market prices are identical.
#
# This holds in this example, but does NOT necessarily hold and breaks down in some circumstances (for example, when there is a lot of storage and inter-temporal shifting).

n.generators.p_nom_extendable = False
n.generators.p_nom = n.generators.p_nom_opt

n.lopf(solver_name="glpk")

n.buses_t.marginal_price.plot(title="Price Duration Curve")

n.buses_t.marginal_price.sum(axis=1).value_counts()

# Demonstrate zero-profit condition

# Differences are due to singular times, see above, not a problem

print("Total costs:")
print(
    n.generators.p_nom * n.generators.capital_cost
    + n.generators_t.p.multiply(n.snapshot_weightings.generators, axis=0).sum()
    * n.generators.marginal_cost
)

print("Total revenue:")
print(
    n.generators_t.p.multiply(n.snapshot_weightings.generators, axis=0)
    .multiply(n.buses_t.marginal_price["bus"], axis=0)
    .sum()
)


text:
var Q = require('q');
var SauceTunnel = require('sauce-tunnel');
var request = require('request');
var TestRunner = require('./TestRunner');
var WebServer = require('./WebServer');
var chalk = require('chalk');

function getBrowsers(browsers, callback) {
	request('http://saucelabs.com/rest/v1/info/browsers/webdriver', function(error, response, body) {
		var platformLookup = {
			'XP': 'Windows 2012',
			'Windows 7': 'Windows 2008'
		};

		var browserLookup = {
			'googlechrome': 'chrome'
		};

		if (!error && response.statusCode == 200) {
			var allBrowsers = JSON.parse(body);

			allBrowsers.sort(function(a, b) {
				a = parseInt(a.short_version, 10);
				b = parseInt(b.short_version, 10);

				if (a < b) {
					return 1;
				}

				if (a > b) {
					return -1;
				}

				return 0;
			});

			browsers.forEach(function(browser) {
				// Find latest browser and use that
				if (browser.version == 'latest') {
					for (var i = 0; i < allBrowsers.length; i++) {
						var os = platformLookup[browser.platform] || browser.platform;
						var apiName = browserLookup[browser.browserName] || browser.browserName;

						if (allBrowsers[i].api_name == apiName && allBrowsers[i].os == os) {
							browser.version = allBrowsers[i].short_version;
							return;
						}
					}

					delete browser.version;
				}
			});

			callback();
		}
	});
}

function log() {
	console.log.apply(this, arguments);
}

function reportProgress(notification) {
	switch (notification.type) {
		case 'tunnelOpen':
			//log('=> Starting Tunnel to Sauce Labs');
			break;

		case 'tunnelOpened':
			log('Connected to Saucelabs');
			break;

		case 'tunnelClose':
			//log('=> Stopping Tunnel to Sauce Labs');
			break;

		case 'tunnelEvent':
			/*if (notification.verbose) {
				log(notification.text);
			} else {
				log(notification.text);
			}*/
			break;

		case 'jobStarted':
			log(notification.startedJobs, '/', notification.numberOfJobs, 'tests started');
			break;

		case 'jobCompleted':
			if (notification.passed) {
				log(chalk.green("[PASSED] %s"), notification.platform);
			} else {
				log(chalk.red("[FAILED] %s"), notification.platform);
			}

			break;

		case 'testCompleted':
			//log('All tests completed with status %s', notification.passed);
			break;

		case 'retrying':
			log('Timed out, retrying');
			break;

		default:
			log('Unexpected notification type');
	}
}

function createTunnel(arg) {
	var tunnel;

	reportProgress({
		type: 'tunnelOpen'
	});

	tunnel = new SauceTunnel(arg.username, arg.key, arg.identifier, true, ['-P', '0'].concat(arg.tunnelArgs));

	['write', 'writeln', 'error', 'ok', 'debug'].forEach(function (method) {
		tunnel.on('log:' + method, function (text) {
			reportProgress({
				type: 'tunnelEvent',
				verbose: false,
				method: method,
				text: text
			});
		});
		tunnel.on('verbose:' + method, function (text) {
			reportProgress({
				type: 'tunnelEvent',
				verbose: true,
				method: method,
				text: text
			});
		});
	});

	return tunnel;
}

function runTask(arg, framework, callback) {
	var tunnel;

	Q.fcall(function () {
		var deferred;

		if (arg.tunneled) {
			deferred = Q.defer();

			tunnel = createTunnel(arg);
			tunnel.start(function (succeeded) {
				if (!succeeded) {
					if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
						deferred.reject(
							'Could not create tunnel to Sauce Labs. ' +
							'Could be the missing SAUCE_USERNAME/SAUCE_ACCESS_KEY environment variables.'
						);
					} else {
						deferred.reject('Could not create tunnel to Sauce Labs');
					}
				} else {
					reportProgress({
						type: 'tunnelOpened'
					});

					deferred.resolve();
				}
			});

			return deferred.promise;
		}
	})
	.then(
		function () {
			var testRunner = new TestRunner(arg, framework, reportProgress);
			return testRunner.runTests();
		}, function (error) {
			log(error.toString());
			callback(false);
		}
	)
	.fin(function () {
		var deferred;

		if (tunnel) {
			deferred = Q.defer();

			reportProgress({
				type: 'tunnelClose'
			});

			tunnel.stop(function () {
				deferred.resolve();
			});

			return deferred.promise;
		}
	})
	.then(
		function (passed) {
			callback(passed);
		},
		function (error) {
			log(error.toString());
			callback(false);
		}
	)
	.done();
}

function qunit(settings) {
	var defaults = {
		username: process.env.SAUCE_USERNAME,
		key: process.env.SAUCE_ACCESS_KEY,
		tunneled: true,
		identifier: Math.floor((new Date()).getTime() / 1000 - 1230768000).toString(),
		pollInterval: 1000 * 2,
		testname: '',
		browsers: [{}],
		tunnelArgs: ['-lsc.log'],
		sauceConfig: {},
		maxRetries: 0
	};

	for (var name in defaults) {
		if (name in settings) {
			continue;
		}

		settings[name] = defaults[name];
	}

	var webServer = new WebServer();

	webServer.start(function() {
		getBrowsers(settings.browsers, function() {
			runTask(settings, 'qunit', function(result) {
				webServer.stop();
			});
		});
	});
}

module.exports.saucelabs = {
	qunit: qunit
};


text:
var ga_radSize; // this will store the radio buttons for Size
var ga_chkTopping; // this will store the checkboxes for toppings

var g_sMsg; // this will store the msg that we will display to the user (in the bottom box)

window.onload = Init;

function Init() {

	// Grab the radio buttons (there's something special about this one)
	ga_radSize = document.getElementsByName("radSize");

	// NEXT: Same thing with the checkboxes
	ga_chkTopping = document.getElementsByName("chkTopping");

	// NEXT: Declare object variables first, i.e. variables you will need to hold objects that you get with getElementById(), and assign them
	var txtAddress = document.getElementById("txtAddress");

	// NEXT: Change the version number in the line below, if necessary, so it accurately reflects this particular version of PizzaTime.
	document.getElementById("h1Title").innerHTML = "PizzaTime 2.0";

	// NEXT: event handler hook-up: hook up the click event of the button to the Place Order() function
	document.getElementById("btnPlaceOrder").onclick = PlaceOrder;

	// NEXT: Delivery Address code
	txtAddress.disabled = "disabled";
	// Give txtAddress a class attribute of "disabled".  Why?  Take a look at the CSS code.
	txtAddress.className = "disabled";

	// NEXT: event handler hook-up for the "Deliver to:" checkbox
	document.getElementById("chkDelivery").onclick =
		function() {
			if (this.checked === true) {
				txtAddress.disabled = "";
				txtAddress.className = "";
				txtAddress.focus();

			} else {
				// Not checked?  Then, disable txtAddress, set the class attribute, and clear any text in txtAddress.
				txtAddress.disabled = "disabled";
				txtAddress.className = "disabled";
				txtAddress.value = "";
			}
		};
} // function Init()

// ** FUNCTIONS ***************************************

function PlaceOrder() {
	// This event handler function executes when the user clicks the Place Order button.
	// Declare object variables and assign them
	var divErrors = document.getElementById("divErrors");
	var txtName = document.getElementById("txtName");
	var txtAddress = document.getElementById("txtAddress");

	g_sMsg = "";
	divErrors.innerHTML = "";
	divErrors.style.display = "block";

	if (ga_radSize[0].checked === true) {
		AddSizeMsg(0);

	} else if (ga_radSize[1].checked === true) {
		AddSizeMsg(1);

	} else if (ga_radSize[2].checked === true) {
		AddSizeMsg(2);

	} else if (ga_radSize[3].checked === true) {
		AddSizeMsg(3);

	} else {
		divErrors.innerHTML = "Select a pizza size";
		return;
	}

	// Version 2
	// Once again, we have some major redundancy.	Let's simplify the code by calling a function.  Comment out the previous group of
	// IF statements and UNcomment the code below.   Check out the AddToppingMsg() function.  Then get back to me.

	AddToppingMsg(0);
	AddToppingMsg(1);
	AddToppingMsg(2);
	AddToppingMsg(3);
	AddToppingMsg(4);
	AddToppingMsg(5);
	AddToppingMsg(6);
	AddToppingMsg(7);

	if (document.getElementById("selSmell").selectedIndex === 0) {
		// If the selectedIndex is zero, that means the first item is selected.  In this particular dropdown, the first item is blank
		// (look back at the HTML), meaning that the user didn't really select anything.
		// So display an error, set focus to the select box and get out of here.
		divErrors.innerHTML = "Select a smell";
		document.getElementById("selSmell").focus();
		return; // get out!
	} else {
		// The user DID select a smell, so let's continue building our display msg.
		g_sMsg += "
Your pizza will smell like " + document.getElementById("selSmell").value + ".
";
		// Note that the *value* property gives us the html value attribute of whichever item is selected
	}

	// NEXT:
	// if txtName is blank, display error msg and set focus
	if (txtName.value === "") {
		divErrors.innerHTML = "Enter a customer name";
		txtName.focus();
		return; // now get the hell out of here
	}

	// NEXT: Delivery Address code
	// Is the Delivery checkbox checked?
	if (document.getElementById("chkDelivery").checked === true) {
		// Yes: Check that txtAddress contains a value.  If it doesn't, display an error msg
		if (txtAddress.value === "") {
			// Bummer.  No address entered.
			divErrors.innerHTML = "Enter your address";
			txtAddress.focus();
			return;
		} else {
			// otherwise, display a nice msg to them
			g_sMsg += "
Your order will be delivered to:
" + txtAddress.value + "
";
		}
	} else {
		// The delivery checkbox is NOT checked, i.e. it's a pickup order
		g_sMsg += "
Your order will be ready for pickup in 20 minutes.
";
	}

	g_sMsg += "
Thank you for coming to PizzaTime!
";

	// We've finished building our display msg for the user.  Now we need to stick it into divOrder
	// so they can see it
	document.getElementById("divOrder").innerHTML = g_sMsg;

	divErrors.style.display = "none"; // No errors, so hide divErrors.
	return;

} // function PlaceOrder()

// Version 2
function AddSizeMsg (p_iSizeIndex) {
	// This function takes one parameter - an integer which is the index of a specific radio button item that is checked.  Remember that the first radio button has an index of zero.

	g_sMsg += "" + txtName.value + " ordered a " + ga_radSize[p_iSizeIndex].value + " Pizza with:
";
	// For example, ga_radSize[0].value gives us the html value attribute of the first radio button
}

// Version 2 - Uncomment out the following function code for Version 2
function AddToppingMsg (p_iToppingIndex) {
	// This function takes one parameter - an integer which is the index of a specific checkbox item.  Remember that the first checkbox
	// has an index of zero.

	// Let's see if this checkbox item is checked
	if (ga_chkTopping[p_iToppingIndex].checked === true) {
		// this one IS checked!  Concatenate the topping value to g_sMsg
		g_sMsg += ga_chkTopping[p_iToppingIndex].value + "
";
	}
}


text:
<?php
//use frontend\assets\AppAsset;
use yii\helpers\Html;
use yii\widgets\DetailView;
use common\models\User;
use frontend\assets\AppAsset;

/* @var $this yii\web\View */
/* @var $model app\models\Post */
AppAsset::register($this);
$asset = frontend\assets\AppAsset::register($this);
$baseUrl = $asset->baseUrl;
$this->title = $model->titulo;
?>

    <?=$this->render('../layouts/rightblog');?>

<?=$model->titulo?>

                            <?= Html::a(User::findOne(['id' => $model->autor])->username, ['/user/profile/show', 'id' => $model->autor]); ?>
                             Bootstrap
                             <?=$model->fecha?>
                             3 Comments

                            <?=$model->descripcion?>

                             Tags CSS3 HTML5 WordPress Joomla


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

exports.default = function (items /* modified */, fieldNames, transformer) {
  (Array.isArray(items) ? items : [items]).forEach(function (item) {
    fieldNames.forEach(function (fieldName) {
      transformer(item, fieldName, (0, _getByDot2.default)(item, fieldName));
    });
  });
};

var _getByDot = require('./get-by-dot');

var _getByDot2 = _interopRequireDefault(_getByDot);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

module.exports = exports['default'];

// transformer(item /* modified */, fieldName, value)


text:
title: Using Vuex & vue-router
type: references
order: 9.2
version: 2.1
---

# Using Vuex & vue-router

Work in progresss.


text:
package com.spotify.heroic.metric;

import com.spotify.heroic.common.Series;
import lombok.Data;
import lombok.RequiredArgsConstructor;

import java.util.Optional;

@Data
@RequiredArgsConstructor
public class BackendKey {
    private final Series series;
    private final long base;
    private final MetricType type;
    private final Optional<Long> token;

    public BackendKey(final Series series, final long base) {
        this(series, base, MetricType.POINT, Optional.empty());
    }
}


text:
package org.apache.maven.repository.metadata;

import org.apache.maven.artifact.ArtifactScopeEnum;

/**
 * Resolves conflicts in the supplied dependency graph.
 * Different implementations will implement different conflict resolution policies.
 *
 * @author Oleg Gusakov
 * @version $Id: GraphConflictResolver.java 958295 2010-06-26 23:16:18Z hboutemy $
 */
public interface GraphConflictResolver
{
    String ROLE = GraphConflictResolver.class.getName();

    /**
     * Cleanses the supplied graph by leaving only one directed versioned edge\
     * between any two nodes, if multiple exists. Uses scope relationships, defined
     * in ArtifactScopeEnum
     *
     * @param graph the "dirty" graph to be simplified via conflict resolution
     * @param scope scope for which the graph should be resolved
     *
     * @return resulting "clean" graph for the specified scope
     *
     * @since 3.0
     */
    MetadataGraph resolveConflicts( MetadataGraph graph, ArtifactScopeEnum scope )
        throws GraphConflictResolutionException;
}


text:
package org.dcm4chee.web.common.util;

import org.apache.wicket.Component;
import org.joda.time.format.DateTimeFormat;

/**
 * @author Gunter Zeilinger <gunterze@gmail.com>
 * @version $Revision$ $Date$
 * @since Dec 19, 2008
 */
public class DateUtils {

    public static String da2str(String da) {
        if (da == null) {
            return null;
        }
        if (da.length() != 8) {
            return da;
        }
        StringBuilder sb = new StringBuilder(10);
        sb.append(da.substring(0, 4))
                .append('-')
                .append(da.substring(4, 6))
                .append('-')
                .append(da.substring(6));
        return sb.toString();
    }

    public static String str2da(String str) {
        String s = str.trim();
        if (s.length() != 10) {
            return s;
        }
        StringBuilder sb = new StringBuilder(8);
        sb.append(s.substring(0, 4))
                .append(s.substring(5, 7))
                .append(s.substring(8));
        return sb.toString();
    }

    public static String tm2str(String tm) {
        if (tm == null) {
            return null;
        }
        if (tm.length() < 4 || tm.charAt(2) == ':') {
            return tm;
        }
        StringBuilder sb = new StringBuilder(10);
        sb.append(tm.substring(0, 2))
                .append(':')
                .append(tm.substring(2, 4));
        if (tm.length() >= 6) {
            sb.append(':').append(tm.substring(4,6));
        }
        return sb.toString();
    }

    public static String str2tm(String str) {
        String s = str.trim();
        int colon = s.indexOf(':');
        if (colon == -1) {
            return s;
        }
        StringBuilder sb = new StringBuilder(s.length());
        int pos = 0;
        do {
            sb.append(s.substring(pos, colon));
            pos = colon + 1;
            colon = s.indexOf(':', pos);
        } while (colon != -1);
        sb.append(s.substring(pos));
        return sb.toString();
    }

    public static String datm2str(String da, String tm) {
        return da2str(da) + " " + tm2str(tm);
    }

    public static String[] str2datm(String str) {
        String s = str.trim();
        int space = s.indexOf(' ');
        String[] datm = new String[2];
        if (space == -1) {
            datm[0] = str2da(s);
        } else {
            datm[0] = str2da(s.substring(0, space));
            datm[1] = str2tm(s.substring(space+1).trim());
        }
        return datm;
    }

    public static String getDatePattern(Component c) {
        String pattern = DateTimeFormat.patternForStyle("S-", c.getLocale());
        int pos1 = pattern.indexOf('y');
        if (pos1 != -1) {
            if (pattern.length() <= pos1+2) {
                pattern = pattern + "yy";
            } else if ( pattern.charAt(pos1+2)!='y') {
                pattern = pattern.substring(0,pos1)+"yyyy"+pattern.substring(pos1+2);
            }
        }
        return pattern;
    }

}


text:
template <typename _world_property, typename _edge_value_type>
class COperatorAbstract {
public:
    typedef _edge_value_type _edge_value_type;

protected:
    typedef CConditionState<_world_property> inherited;
    typedef inherited CSConditionState;
    typedef _world_property COperatorCondition;

protected:
    CSConditionState m_conditions;
    CSConditionState m_effects;
    bool* m_actuality;
    mutable bool m_weight_actual;
    mutable _edge_value_type m_min_weight;

protected:
    IC void actual(bool value);

public:
    IC COperatorAbstract();
    IC COperatorAbstract(const CSConditionState& conditions, const CSConditionState& effects);
    virtual ~COperatorAbstract();
    virtual void Load(LPCSTR section);
    virtual void setup(bool* actuality);
    IC const CSConditionState& conditions() const;
    IC const CSConditionState& effects() const;
    IC void add_condition(const COperatorCondition& condition);
    IC void add_effect(const COperatorCondition& effect);
    IC void remove_condition(const typename COperatorCondition::_condition_type& condition);
    IC void remove_effect(const typename COperatorCondition::_condition_type& effect);
    IC _edge_value_type min_weight() const;

    template <typename T>
    IC bool applicable(const CSConditionState& condition, const CSConditionState& start,
                       const CSConditionState& self_condition, T& problem_solver) const;

    virtual bool applicable_reverse(const CSConditionState& condition,
                                    const CSConditionState& start,
                                    const CSConditionState& self_condition) const;

    template <typename T>
    IC const CSConditionState&
    apply(const CSConditionState& condition, const CSConditionState& self_condition,
          CSConditionState& result, CSConditionState& current, T& problem_solver) const;
    virtual const CSConditionState& apply(const CSConditionState& condition,
                                          const CSConditionState& self_condition,
                                          CSConditionState& result) const;

    virtual bool apply_reverse(const CSConditionState& condition, const CSConditionState& start,
                               CSConditionState& result,
                               const CSConditionState& self_condition) const;
    virtual _edge_value_type weight(const CSConditionState& condition0,
                                    const CSConditionState& condition1) const;
};

#include "operator_abstract_inline.h"


text:
Vuex - это **паттерн управления состоянием и библиотека** для приложений на Vue.js. Он служит центральным хранилищем данных для всех компонентов приложения и обеспечивает предсказуемость изменения данных при помощи определённых правил. Кроме того, Vuex интегрируется с официальным [расширением инструментов разработчика](https://github.com/vuejs/vue-devtools) Vue, предоставляя "из коробки" такие продвинутые возможности как "машину времени" при отладке и экспорт/импорт слепков состояния данных.

### Что такое "паттерн управления состоянием"?

Давайте начнём с простого приложения, реализующего счётчик с использованием Vue:

``` js
new Vue({
  // состояние
  data () {
    return {
      count: 0
    }
  },
  // представление
  template: `
    <div>{{ count }}</div>
  `,
  // действия
  methods: {
    increment () {
      this.count++
    }
  }
})
```

Это самостоятельное приложение состоит из следующих частей:

- **Состояние** — "источник истины", управляющий приложением;
- **Представление** — декларативно заданное отображение **состояния**;
- **Действия** — возможные пути изменения состояния приложения в ответ на взаимодействие пользователя с **представлением**.

Вот простейшее представление концепции "однонаправленного потока данных":

Простота, к сожалению, быстро исчезает при появлении **нескольких компонентов, основывающихся на одном и том же состоянии**, когда:

- Несколько представлений могут зависеть от одной и той же части состояния приложения
- Действия из разных представлений могут оказывать влияние на одни и те же части состояния приложения

Разбираясь с первой проблемой, вам придётся передавать одни и те же данные в несколько глубоко вложенных компонентов. Это часто сложно и неприятно, а для соседних компонентов такое и вовсе не сработает. Решая вторую проблему, приходится обращаться напрямую к родителям и потомкам компонента, или синхронизовать изменения с другими местами в приложении событиями. Оба подхода хрупки и быстро приводят к появлению кода, который невозможно поддерживать.

Так почему бы не вынести всё общее состояние приложения из компонентов в глобальный синглтон? При использовании этого подхода, дерево компонентов превращается в одно большое "представление", а каждый компонент получает доступ к состоянию приложения, наряду с возможностью вызывать действия для изменения состояния, независимо от расположения этого компонента в дереве.

Кроме того, чётко определяя и разделяя концепции, возникающие при управлении состоянием и требуя соблюдения некоторых правил, мы улучшаем структурированность и поддерживаемость нашего кода.

Такова основная идея, лежащая в основе Vuex, вдохновлённого [Flux](https://facebook.github.io/flux/docs/overview.html), [Redux](http://redux.js.org/) и [Архитектурой Elm](https://guide.elm-lang.org/architecture/). В отличие от других паттернов, Vuex реализован в виде библиотеки, специально заточенной на использование совместно с Vue.js и использующей его производительную систему реактивных обновлений.

![vuex](./images/vuex.png)

### В каких случаях следует использовать Vuex?

Vuex помогает управлять совместно используемым состоянием ценой привнесения новых концепций и вспомогательного кода. Кратковременная продуктивность страдает во благо долгосрочной.

Если вам ещё не доводилось создавать крупномасштабные одностраничные приложения, Vuex может показаться многословным и обескураживающим. Это нормально — несложные приложения вполне могут обойтись и без Vuex. Возможно, вам вполне хватит простой [глобальной шины событий](https://ru.vuejs.org/v2/guide/components.html#Коммуникация-между-компонентами-не-связанными-иерархически). Но если вы создаёте SPA среднего или крупного размера, вероятно вам уже приходилось сталкиваться с ситуациями, заставляющими задуматься о методах более эффективного управления состоянием приложения за пределами компонентов Vue, и Vuex в таком случае может оказаться вполне естественным следующим шагом. Вот неплохая цитата от Дэна Абрамова, автора Redux:

> Flux-библиотеки подобны очкам: если они вам действительно нужны, вы на этот счёт не сомневаетесь.


text:
#include <boost/lexical_cast.hpp>

#include <Wt/WLineEdit>
#include <Wt/WIntValidator>
#include <Wt/WText>
#include <Wt/WPushButton>
#include <Wt/WApplication>
#include <Wt/WBreak>

#include "RoundedWidget.h"
#include "StyleExample.h"

char loremipsum[] = "Lorem ipsum dolor sit amet, consectetur adipisicing "
   "elit, sed do eiusmod tempor incididunt ut labore et "
   "dolore magna aliqua. Ut enim ad minim veniam, quis "
   "nostrud exercitation ullamco laboris nisi ut aliquip "
   "ex ea commodo consequat. Duis aute irure dolor in "
   "reprehenderit in voluptate velit esse cillum dolore eu "
   "fugiat nulla pariatur. Excepteur sint occaecat cupidatat "
   "non proident, sunt in culpa qui officia deserunt mollit "
   "anim id est laborum.";

StyleExample::StyleExample(WContainerWidget *parent)
  : WContainerWidget(parent)
{
  w_ = new RoundedWidget(RoundedWidget::All, this);

  new WText(loremipsum, w_->contents());
  new WBreak(this);

  new WText("Color (rgb): ", this);
  r_ = createValidateLineEdit(w_->backgroundColor().red(), 0, 255);
  g_ = createValidateLineEdit(w_->backgroundColor().green(), 0, 255);
  b_ = createValidateLineEdit(w_->backgroundColor().blue(), 0, 255);

  new WBreak(this);

  new WText("Radius (px): ", this);
  radius_ = createValidateLineEdit(w_->cornerRadius(), 1, 500);

  new WBreak(this);

  WPushButton *p = new WPushButton("Update!", this);
  p->clicked().connect(this, &StyleExample::updateStyle);

  new WBreak(this);

  error_ = new WText("", this);
}

WLineEdit *StyleExample::createValidateLineEdit(int value, int min, int max)
{
  WLineEdit *le = new WLineEdit(boost::lexical_cast<std::wstring>(value), this);
  le->setTextSize(3);
  le->setValidator(new WIntValidator(min, max));

  return le;
}

void StyleExample::updateStyle()
{
  if ((r_->validate() != WValidator::Valid)
      || (g_->validate() != WValidator::Valid)
      || (b_->validate() != WValidator::Valid))
    error_->setText("Color components must be numbers between 0 and 255.");
  else if (radius_->validate() != WValidator::Valid)
    error_->setText("Radius must be between 1 and 500.");
  else {
    w_->setBackgroundColor(WColor(boost::lexical_cast<int>(r_->text()),
				  boost::lexical_cast<int>(g_->text()),
				  boost::lexical_cast<int>(b_->text())));
    w_->setCornerRadius(boost::lexical_cast<int>(radius_->text()));
    error_->setText("");
  }
}

WApplication *createApplication(const WEnvironment& env)
{
  WApplication *app = new WApplication(env);
  app->setTitle("Style example");

  app->root()->addWidget(new StyleExample());
  return app;
}

int main(int argc, char **argv)
{
   return WRun(argc, argv, &createApplication);
}


text:
import java.lang.Math.*;
public class Problem4 {
	public static void main(String[] args) {
		System.out.println(findPalindromeNumber(3));

	}

	public static double findPalindromeNumber(int numberOfSumDigits) {
		double currentHighest = 0;
		for (double i = (Math.pow(10.0, numberOfSumDigits) - 1); i > (Math.pow(10.0, numberOfSumDigits - 1)); i--) {
			for (double y = (Math.pow(10.0, numberOfSumDigits - 1)); y < (Math.pow(10.0, numberOfSumDigits)); y++) {
				Double number = i * y;
				String inputString = String.valueOf(number.intValue());
				if (inputString.equals(reverseString(inputString))) {
					if (number > currentHighest) {
						currentHighest = number;
					}
				}
			}
		}
		return currentHighest;
	}

	public static String reverseString(String inputString) {
		if (inputString == null || inputString.isEmpty()) {
			return "";
		}
		if (inputString.length() == 1) {
			return inputString;
		}
		return inputString.substring(inputString.length() - 1) + reverseString(inputString.substring(0, inputString.length() - 1));
	}
}