text:
describe("Ext.util.Focusable", function() {
    var focusAndWait = jasmine.focusAndWait,
        waitAWhile = jasmine.waitAWhile,
        expectFocused = jasmine.expectFocused,
        c, container;

    function stdComponent(config) {
        return Ext.apply({
            xtype: 'component',
            renderTo: Ext.getBody(),
            width: 100,
            height: 100,
            focusable: true,
            tabIndex: 0,
            getFocusEl: function() {
                return this.el;
            }
        }, config);
    }

    function makeComponent(config) {
        var cmpCfg = stdComponent(config);

        c = new Ext.Component(cmpCfg);

        return c;
    }

    function makeContainer(config) {
        container = new Ext.container.Container(Ext.apply({
            renderTo: Ext.getBody(),
            width: 100,
            height: 200
        }, config));
    }

    function expectAria(attr, value) {
        return jasmine.expectAriaAttr(c, attr, value);
    }

    function expectNoAria(attr) {
        return jasmine.expectNoAriaAttr(c, attr);
    }

    afterEach(function() {
        if (container) {
            container.destroy();
        }

        if (c) {
            c.destroy();
        }

        c = container = null;
    });

    describe("tabIndex handling", function() {
        describe("component not focusable", function() {
            it("should not render tabindex attribute when tabIndex property is undefined", function() {
                makeComponent({
                    focusable: undefined,
                    tabIndex: undefined
                });

                expectNoAria('tabIndex');
            });

            it("should not render tabindex attribute when tabIndex property is defined", function() {
                makeComponent({
                    focusable: undefined,
                    tabIndex: 0
                });

                expectNoAria('tabIndex');
            });
        });

        describe("component is focusable", function() {
            it("should not render tabindex attribute when tabIndex property is undefined", function() {
                makeComponent({
                    focusable: true,
                    tabIndex: undefined
                });

                expectNoAria('tabIndex');
            });

            it("should render tabindex attribute when tabIndex property is defined", function() {
                makeComponent({
                    focusable: true,
                    tabIndex: 0
                });

                expectAria('tabIndex', '0');
            });
        });
    });

    describe("isFocusable", function() {
        describe("component", function() {
            describe("not rendered", function() {
                beforeEach(function() {
                    makeComponent({
                        renderTo: undefined
                    });
                });

                it("should return false", function() {
                    expect(c.isFocusable()).toBe(false);
                });
            });

            describe("rendered", function() {
                beforeEach(function() {
                    makeComponent();
                });

                describe("focusable === true", function() {
                    it("should return true when visible", function() {
                        expect(c.isFocusable()).toBe(true);
                    });

                    it("should return false when disabled", function() {
                        c.disable();

                        expect(c.isFocusable()).toBe(false);
                    });

                    it("should return false when invisible", function() {
                        c.hide();

                        expect(c.isFocusable()).toBe(false);
                    });

                    it("should return false when destroyed", function() {
                        c.destroy();

                        expect(c.isFocusable()).toBe(false);

                        c = null;
                    });
                });

                describe("focusable === false", function() {
                    beforeEach(function() {
                        c.focusable = false;
                    });

                    it("should return false", function() {
                        expect(c.isFocusable()).toBe(false);
                    });

                    it("should disregard deep parameter", function() {
                        spyOn(c, 'getFocusEl').andCallThrough();

                        expect(c.isFocusable(true)).toBe(false);
                        expect(c.getFocusEl).not.toHaveBeenCalled();
                    });
                });
            });
        });

        describe("container", function() {
            describe("not rendered", function() {
                beforeEach(function() {
                    makeContainer({
                        renderTo: undefined,
                        items: [
                            stdComponent({
                                renderTo: undefined
                            })
                        ]
                    });
                });

                it("should return false with deep === false", function() {
                    expect(container.isFocusable()).toBe(false);
                });

                it("should return false with deep === true", function() {
                    expect(container.isFocusable(true)).toBe(false);
                });
            });

            describe("rendered", function() {
                var fooCmp;

                beforeEach(function() {
                    makeContainer({
                        items: [
                            stdComponent({
                                renderTo: undefined,
                                itemId: 'foo'
                            })
                        ],

                        focusable: true,
                        tabIndex: 0
                    });

                    fooCmp = container.down('#foo');
                });

                describe("deep === false", function() {
                    describe("focusable === false", function() {
                        beforeEach(function() {
                            container.focusable = false;
                        });

                        it("should return false", function() {
                            expect(container.isFocusable()).toBe(false);
                        });
                    });

                    describe("focusable === true, no tabIndex", function() {
                        beforeEach(function() {
                            container.setTabIndex(undefined);
                        });

                        it("should return false", function() {
                            expect(container.isFocusable()).toBe(false);
                        });
                    });

                    describe("focusable === true, tabIndex === 0", function() {
                        it("should return true when container is visible", function() {
                            expect(container.isFocusable()).toBe(true);
                        });

                        it("should return false when container is hidden", function() {
                            container.hide();

                            expect(container.isFocusable()).toBe(false);
                        });

                        it("should return false when container is disabled", function() {
                            container.disable();

                            expect(container.isFocusable()).toBe(false);
                        });

                        it("should return false when container is destroyed", function() {
                            container.destroy();

                            expect(container.isFocusable()).toBe(false);

                            container = null;
                        });
                    });
                });

                describe("deep === true", function() {
                    beforeEach(function() {
                        container.defaultFocus = '#foo';
                    });

                    describe("container not focusable", function() {
                        beforeEach(function() {
                            container.focusable = false;
                        });

                        it("should return true when delegate is focusable", function() {
                            expect(container.isFocusable(true)).toBe(true);
                        });

                        it("should return false when delegate is not focusable", function() {
                            fooCmp.focusable = false;

                            expect(container.isFocusable(true)).toBe(false);
                        });

                        it("should return false when delegate is hidden", function() {
                            fooCmp.hide();

                            expect(container.isFocusable(true)).toBe(false);
                        });

                        it("should return false when delegate is disabled", function() {
                            fooCmp.disable();

                            expect(container.isFocusable(true)).toBe(false);
                        });

                        it("should return false when delegate is destroyed", function() {
                            fooCmp.destroy();

                            expect(container.isFocusable(true)).toBe(false);
                        });

                        describe("dynamic delegate", function() {
                            beforeEach(function() {
                                container.remove(fooCmp);
                                fooCmp.destroy();
                                fooCmp = null;
                            });

                            it("should return false when delegate is removed", function() {
                                expect(container.isFocusable(true)).toBe(false);
                            });

                            it("should return true when matching delegate is added", function() {
                                container.add(stdComponent({
                                    renderTo: undefined,
                                    itemId: 'foo'
                                }));

                                expect(container.isFocusable(true)).toBe(true);
                            });
                        });
                    });

                    describe("container is focusable", function() {
                        it("should return true", function() {
                            expect(container.isFocusable(true)).toBe(true);
                        });
                    });
                });
            });
        });
    });

    describe("getTabIndex", function() {
        beforeEach(function() {
            makeComponent({
                renderTo: undefined,
                tabIndex: 42
            });
        });

        it("should return undefined when !focusable", function() {
            c.focusable = false;

            expect(c.getTabIndex()).toBe(undefined);
        });

        it("should return configured tabIndex when component is not rendered", function() {
            expect(c.rendered).toBe(false);
            expect(c.getTabIndex()).toBe(42);
        });

        it("should return actual tabIndex when component is rendered", function() {
            c.render(Ext.getBody());
            c.el.set({ tabIndex: 1 });

            expect(c.rendered).toBe(true);
            expect(c.getTabIndex()).toBe(1);
        });
    });

    describe("setTabIndex", function() {
        beforeEach(function() {
            makeComponent({
                renderTo: undefined,
                tabIndex: 43
            });
        });

        it("should do nothing when !focusable", function() {
            c.focusable = false;

            c.setTabIndex(-1);

            expect(c.tabIndex).toBe(43);
        });

        it("should set tabIndex property when not rendered", function() {
            c.setTabIndex(-1);

            expect(c.tabIndex).toBe(-1);
        });

        it("should set tabIndex property when el is a string", function() {
            c.el = 'foo'; // element id

            c.setTabIndex(-1);

            expect(c.tabIndex).toBe(-1);
        });

        it("should set el tabindex when rendered", function() {
            c.render(Ext.getBody());

            c.setTabIndex(-1);

            var index = c.el.getAttribute('tabIndex') - 0;

            expect(index).toBe(-1);
        });
    });

    describe("container delegated getTabIndex/setTabIndex", function() {
        beforeEach(function() {
            makeContainer({
                focusable: true,

                items: [makeComponent({
                    renderTo: undefined,
                    tabIndex: 1
                })],

                getFocusEl: function() {
                    return this.child();
                }
            });
        });

        it("should return child's tabIndex", function() {
            expect(container.getTabIndex()).toBe(1);
        });

        it("should set child's tabIndex", function() {
            container.setTabIndex(88);

            var index = c.el.getAttribute('tabIndex') - 0;

            expect(index).toBe(88);
        });
    });

    describe("focusCls handling", function() {
        beforeEach(function() {
            makeComponent({
                renderTpl: [
                    '
foo
'
                ],

                childEls: ['focusClsEl'],

                getFocusClsEl: function() {
                    return this.focusClsEl;
                }
            });

            focusAndWait(c);
        });

        describe("focusing", function() {
            it("should add focusCls to focusClsEl", function() {
                expect(c.focusClsEl.hasCls('x-focus')).toBe(true);
            });

            it("should not add focusCls to el", function() {
                expect(c.el.hasCls('x-focus')).toBe(false);
            });
        });

        describe("blurring", function() {
            beforeEach(function() {
                c.blur();

                waitAWhile();
            });

            it("should remove focusCls from focusClsEl", function() {
                expect(c.focusClsEl.hasCls('x-focus')).toBe(false);
            });
        });

        describe("disabling", function() {
            beforeEach(function() {
                // Disabling is synchronous, so no wait necessary
                c.disable();
            });

            it("should remove focusCls from focusClsEl", function() {
                expect(c.focusClsEl.hasCls('x-focus')).toBe(false);
            });
        });
    });

    describe("blur/focus", function() {
        var focusCls = Ext.baseCSSPrefix + 'focus';

        beforeEach(function(){
            makeComponent({
                autoEl: 'button',
                focusCls: 'focus'
            });
        });

        it("should look up focused Component", function() {
            c.focus();

            waitsFor(function() {
                return c.el.hasCls(focusCls);
            }, 'CSS class to be added', 100);

            runs(function() {
                var cmp = Ext.ComponentManager.getActiveComponent();

                expect(cmp).toEqual(c);
            });
        });

        it("should cancel previous delayed focus", function() {
            var c2 = new Ext.Component({
                renderTo: Ext.getBody(),
                autoEl: 'button',
                focusCls: 'focus',
                focusable: true,
                getFocusEl: function() {
                    return this.el;
                }
            });

            spyOn(Ext.focusTask, 'delay');
            spyOn(Ext.focusTask, 'cancel');

            c.focus(false, true);

            expect(Ext.focusTask.delay).toHaveBeenCalled();

            c2.focus();

            expect(Ext.focusTask.cancel).toHaveBeenCalled();

            Ext.destroy(c2);
        });

        describe("focus delegation", function() {
            var fooCmp, barCmp;

            beforeEach(function() {
                makeContainer({
                    height: 200,

                    items: [
                        stdComponent({
                            itemId: 'foo',
                            renderTo: undefined
                        }),

                        stdComponent({
                            itemId: 'bar',
                            renderTo: undefined
                        })
                    ]
                });

                fooCmp = container.down('#foo');
                barCmp = container.down('#bar');
            });

            it("should focus foo", function() {
                container.defaultFocus = 'component';

                // We're calling container.focus() here but expecting
                // fooCmp to be focused
                focusAndWait(container, fooCmp);

                expectFocused(fooCmp);
            });

            it("should focus bar", function() {
                container.defaultFocus = '#bar';

                focusAndWait(container, barCmp);

                expectFocused(barCmp);
            });
        });

        describe("events", function(){
            it("should fire the focus event", function(){
                var fired;

                runs(function() {
                    c.on('focus', function(){
                        fired = true;
                    });
                    c.focus();
                });

                waitsFor(function() {
                    return fired;
                }, 'Event to fire', 100);

                runs(function() {
                    expect(fired).toBe(true);
                });
            });

            it("should not fire the focus event if the component has focus", function(){
                var fired = 0;

                runs(function() {
                    c.on('focus', function(){
                        ++fired;
                    });
                    c.focus();
                    c.focus();
                });

                waitsFor(function() {
                    return fired > 0;
                }, 'Event to fire', 100);

                // Enough time for the second event to fire, if any
                waits(50);

                runs(function() {
                    expect(fired).toBe(1);
                });
            });

            it("should fire the blur event", function(){
                var fired;

                runs(function() {
                    c.on('blur', function(){
                        fired = true;
                    });
                    c.focus();
                    c.blur();
                });

                waitsFor(function() {
                    return fired;
                }, 'Event to fire', 100);

                runs(function() {
                    expect(fired).toBe(true);
                });
            });
        });
    });

    describe("enable/disable tabbing", function() {
        describe("simple component", function() {
            beforeEach(function() {
                makeComponent();

                c.disableTabbing();
            });

            it("should disable tabbing", function() {
                expect(c.el.isTabbable()).toBe(false);
            });

            it("should re-enable tabbing", function() {
                c.enableTabbing();

                expect(c.el.isTabbable()).toBe(true);
            });
        });

        describe("non-focusable container with delegate", function() {
            var delegate;

            beforeEach(function() {
                makeContainer({
                    defaultFocus: 'foo',
                    items: [
                        stdComponent({ itemId: 'foo' })
                    ]
                });

                delegate = container.down('#foo');

                container.disableTabbing();
            });

            it("should disable tabbing", function() {
                expect(delegate.el.isTabbable()).toBe(false);
            });

            it("should re-enable tabbing", function() {
                container.enableTabbing();

                expect(delegate.el.isTabbable()).toBe(true);
            });
        });

        // We're simulating a window here
        describe("focusable container with delegate", function() {
            var delegate;

            beforeEach(function() {
                makeContainer({
                    floating: true,
                    focusable: true,
                    tabIndex: 0,
                    defaultFocus: 'bar',
                    items: [
                        stdComponent({ itemId: 'bar' })
                    ]
                });

                delegate = container.down('#bar');

                container.disableTabbing();
            });

            it("should disable tabbing on container", function() {
                expect(container.el.isTabbable()).toBe(false);
            });

            it("should disable tabbing on delegate", function() {
                expect(delegate.el.isTabbable()).toBe(false);
            });

            describe("re-enable", function() {
                beforeEach(function() {
                    container.enableTabbing();
                });

                it("should enable tabbing on container", function() {
                    expect(container.el.isTabbable()).toBe(true);
                });

                it("should enable tabbing on delegate", function() {
                    expect(delegate.el.isTabbable()).toBe(true);
                });
            });
        });

        // TODO Refactor this test not to depend on File field
        describe("focusEl outside of component DOM", function() {
            beforeEach(function() {
                c = new Ext.form.field.File({
                    renderTo: Ext.getBody()
                });

                c.disableTabbing();
            });

            it("should disable tabbing", function() {
                expect(c.button.fileInputEl.isTabbable()).toBe(false);
            });

            it("should re-enable tabbing", function() {
                c.enableTabbing();

                expect(c.button.fileInputEl.isTabbable()).toBe(true);
            });
        });
    });

    describe('Disabling focused component', function() {
        it('should move focus to a relation', function() {
            var p = new Ext.panel.Panel({
                renderTo: document.body,
                items: [{
                    xtype: 'textfield'
                }],
                bbar: [{
                    text: 'Button 1'
                }, {
                    text: 'Button 2'
                }]
            }),
            textfield = p.down('textfield'),
            button1 = p.down('[text=Button 1]'),
            button2 = p.down('[text=Button 2]'),
            textFieldFocusSpy = spyOn(textfield, 'focus'),
            button2FocusSpy = spyOn(button2, 'focus');

            // Fake focusing button 1 just so that it will call focus on button2.
            // Real focusing will not work in test situation.
            button1.hasFocus = true;
            button1.disable();

            // Disabling b1 should call button2.focus()
            expect(button2FocusSpy.callCount).toBe(1);

            button2.hasFocus = true;
            button2.disable();

            // Disabling b2 should call textfield.focus()
            expect(textFieldFocusSpy.callCount).toBe(1);

            p.destroy();
        });
    });

    describe('Focusing disabled component', function() {
        it('should move focus to a relation', function() {
            var p = new Ext.panel.Panel({
                renderTo: document.body,
                items: [{
                    xtype: 'textfield'
                }],
                bbar: [{
                    text: 'Button 1',
                    disabled: true
                }, {
                    text: 'Button 2'
                }]
            }),
            textfield = p.down('textfield'),
            button1 = p.down('[text=Button 1]'),
            button2 = p.down('[text=Button 2]'),
            textFieldFocusSpy = spyOn(textfield, 'focus'),
            button2FocusSpy = spyOn(button2, 'focus');

            // Because it is disabled, focus should move to button 2
            button1.focus();

            // Disabling b1 should call button2.focus()
            expect(button2FocusSpy.callCount).toBe(1);

            button2.hasFocus = true;
            button2.disable();

            // Disabling b2 should call textfield.focus()
            expect(textFieldFocusSpy.callCount).toBe(1);

            p.destroy();
        });
    });

    describe('Hiding a component which contains focus when previous focus has been disabled', function() {
        it('should move focus to a relation or the previously focused component', function() {
            var p = new Ext.panel.Panel({
                renderTo: document.body,
                items: [{
                    xtype: 'textfield'
                }, {
                    xtype: 'fieldset',
                    items: [{
                        xtype: 'textfield'
                    }]
                }],
                bbar: [{
                    text: 'Button 1'
                }, {
                    text: 'Button 2'
                }]
            }),
            fieldset = p.down('fieldset'),
            textfield = fieldset.down('textfield'),
            button1 = p.down('[text=Button 1]'),
            button2 = p.down('[text=Button 2]');

            button1.focus();
            waitsFor(function() {
                return button1.hasFocus;
            });

            // Focus enters the fieldset, and the previously focused component
            // (button1) should be cached at that point.
            runs(function() {
                textfield.focus();
            });

            waitsFor(function() {
                return fieldset.containsFocus;
            });

            // The hide should attempt to revert focus back to button1.
            // But now that is disabled, it should go to button2
            runs(function() {
                button1.disable();
                fieldset.hide();
            });

            waitsFor(function() {
                return button2.hasFocus;
            });

            runs(function() {
                p.destroy();
            });
        });
    });

    describe('Wrapping a Component which contains focus', function() {
        var container,
            cmp,
            newEl;

        afterEach(function() {
            container.destroy();
            newEl.destroy();
        });
        it('should not call onFocusLeave on a Component which is wrapped', function() {
            container = new Ext.Container({
                items: {
                    xtype: 'textfield'
                },
                renderTo: document.body
            }),
            cmp = container.child(),
            newEl;

            spyOn(container, 'onFocusLeave').andCallThrough();

            cmp.focus();

            waitsFor(function() {
                return container.containsFocus;
            });

            runs(function() {
                expect(Ext.Element.getActiveElement() === cmp.inputEl.dom).toBe(true);
                newEl = container.el.wrap();
            });

            // Wait for a possible (it would be a bug) focus leave of the component
            // we can't wait for anything, because we want NOTHING to happen.
            waits(10);

            // The Component must have retained focus
            runs(function() {
                expect(container.onFocusLeave).not.toHaveBeenCalled();
                expect(container.containsFocus).toBe(true);
                expect(Ext.Element.getActiveElement() === cmp.inputEl.dom).toBe(true);
            });
        });
    });
});


text:
"use strict";

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

// Generated by CoffeeScript 2.5.1
var SpecialString, i, len, prop, ref;

module.exports = SpecialString = function () {
  var self;

  var SpecialString = /*#__PURE__*/function () {
    function SpecialString(str) {
      _classCallCheck(this, SpecialString);

      if (!(this instanceof self)) {
        return new self(str);
      }

      this._str = String(str);
      this._len = 0;
    }

    _createClass(SpecialString, [{
      key: "_getStr",
      value: function _getStr() {
        return this._str;
      }
    }, {
      key: "set",
      value: function set(str) {
        this._str = String(str);
        return this;
      }
    }, {
      key: "clone",
      value: function clone() {
        return new SpecialString(this._str);
      }
    }, {
      key: "isEmpty",
      value: function isEmpty() {
        return this._str === '';
      }
    }, {
      key: "isOnlySpecialChars",
      value: function isOnlySpecialChars() {
        return !this.isEmpty() && this.length === 0;
      }
    }, {
      key: "_reset",
      value: function _reset() {
        return this._len = 0;
      }
    }, {
      key: "splitIn",
      value: function splitIn(limit) {
        var trimLeftEachLine = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
        var buffer, bufferLength, justSkippedSkipChar, lines;
        buffer = '';
        bufferLength = 0;
        lines = [];
        justSkippedSkipChar = false;

        self._countChars(this._str, function (char, charLength) {
          if (bufferLength > limit || bufferLength + charLength > limit) {
            lines.push(buffer);
            buffer = '';
            bufferLength = 0;
          }

          if (bufferLength === 0 && char === ' ' && !justSkippedSkipChar && trimLeftEachLine) {
            return justSkippedSkipChar = true;
          } else {
            buffer += char;
            bufferLength += charLength;
            return justSkippedSkipChar = false;
          }
        });

        if (buffer.length > 0) {
          lines.push(buffer);
        }

        return lines;
      }
    }, {
      key: "trim",
      value: function trim() {
        return new SpecialString(this.str.trim());
      }
    }, {
      key: "trimLeft",
      value: function trimLeft() {
        return new SpecialString(this.str.replace(/^\s+/, ''));
      }
    }, {
      key: "trimRight",
      value: function trimRight() {
        return new SpecialString(this.str.replace(/\s+$/, ''));
      }
    }, {
      key: "_getLength",
      value: function _getLength() {
        var sum;
        sum = 0;

        self._countChars(this._str, function (char, charLength) {
          sum += charLength;
        });

        return sum;
      }
    }, {
      key: "cut",
      value: function cut(from, to) {
        var _this = this;

        var trimLeft = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
        var after, before, cur, cut;

        if (to == null) {
          to = this.length;
        }

        from = parseInt(from);

        if (from >= to) {
          throw Error("`from` shouldn't be larger than `to`");
        }

        before = '';
        after = '';
        cut = '';
        cur = 0;

        self._countChars(this._str, function (char, charLength) {
          if (_this.str === 'ab<tag>') {
            console.log(charLength, char);
          }

          if (cur === from && char.match(/^\s+$/) && trimLeft) {
            return;
          }

          if (cur < from) {
            before += char; // let's be greedy
          } else if (cur < to || cur + charLength <= to) {
            cut += char;
          } else {
            after += char;
          }

          cur += charLength;
        });

        this._str = before + after;

        this._reset();

        return new SpecialString(cut);
      }
    }], [{
      key: "_countChars",
      value: function _countChars(text, cb) {
        var char, charLength, m;

        while (text.length !== 0) {
          if (m = text.match(self._tagRx)) {
            char = m[0];
            charLength = 0;
            text = text.substr(char.length, text.length);
          } else if (m = text.match(self._quotedHtmlRx)) {
            char = m[0];
            charLength = 1;
            text = text.substr(char.length, text.length);
          } else if (text.match(self._tabRx)) {
            char = "\t";
            charLength = 8;
            text = text.substr(1, text.length);
          } else {
            char = text[0];
            charLength = 1;
            text = text.substr(1, text.length);
          }

          cb.call(null, char, charLength);
        }
      }
    }]);

    return SpecialString;
  }();

  ;
  self = SpecialString;
  SpecialString._tabRx = /^\t/;
  SpecialString._tagRx = /^<[^>]+>/;
  SpecialString._quotedHtmlRx = /^&(gt|lt|quot|amp|apos|sp);/;
  return SpecialString;
}.call(void 0);

ref = ['str', 'length'];

for (i = 0, len = ref.length; i < len; i++) {
  prop = ref[i];

  (function () {
    var methodName;
    methodName = '_get' + prop[0].toUpperCase() + prop.substr(1, prop.length);
    return SpecialString.prototype.__defineGetter__(prop, function () {
      return this[methodName]();
    });
  })();
}

redpajama_set_name: RedPajamaGithub


text:
using Newtonsoft.Json;
using System;
namespace SuperMap.WindowsPhone.REST
{
    ///
    /// 	<para>${WP_REST_PrimeMeridian_Title}</para>
    /// 	<para>${WP_REST_PrimeMeridian_Description}</para>
    ///
    public class PrimeMeridian
    {
        /// ${WP_REST_PrimeMeridian_constructor_D}
        public PrimeMeridian()
        { }
        /// ${WP_REST_PrimeMeridian_attribute_Name_D}
        [JsonProperty("name")]
        public string Name { get; set; }
        /// ${WP_REST_PrimeMeridian_attribute_LongitudeValue_D}
        [JsonProperty("longitudeValue")]
        public double LongitudeValue { get; set; }
        /// ${WP_REST_PrimeMeridian_attribute_Type_D}
        [JsonProperty("type")]
        public PrimeMeridianType Type { get; set; }

    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.googlecode.playn</groupId>
    <artifactId>playn-payments-project</artifactId>
    <version>1.7-SNAPSHOT</version>
  </parent>

  <artifactId>playn-payments-html</artifactId>
  <name>PlayN payments HTML</name>
  <packaging>jar</packaging>

  <dependencies>
    <dependency>
      <groupId>com.googlecode.playn</groupId>
      <artifactId>playn-payments-core</artifactId>
      <version>${project.version}</version>
    </dependency>

	<dependency>
      <groupId>com.googlecode.playn</groupId>
      <artifactId>playn-html</artifactId>
      <version>${project.version}</version>
    </dependency>

  </dependencies>

  <build>
    <sourceDirectory>src</sourceDirectory>

    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-source-plugin</artifactId>
      </plugin>
    </plugins>

    <resources>
      <resource>
        <directory>${basedir}/src</directory>
      </resource>
    </resources>
  </build>
</project>


text:
/**
 *
 * Editor
 *
 */

import React from 'react';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';

const customContentStyle = {
  width: '60%',
  maxWidth: 'none',
};

class Editor extends React.Component { // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);
    this.state = {
      open: false,
      previewImage: '',
    };
  }

  componentWillReceiveProps(nextProps) {
    this.setState({open: nextProps.popState});
  }

  handleOpen = () => {
    this.setState({open: true});
  };

  handleClose = () => {
    this.setState({open: false});
  };
  render() {
    const actions = [
      <FlatButton
        label="Cancel"
        primary={true}
        onTouchTap={this.handleClose}
      />,
      <FlatButton
        label="Submit"
        primary={true}
        disabled={true}
        onTouchTap={this.handleClose}
      />,
    ];
    return (
      <MuiThemeProvider>

          <Dialog contentStyle={customContentStyle} actions={actions} modal={true} open={this.state.open}>

Add Images & Markup

                                  Rotate 90o
                                  Straighten<input type="range" name="straighten" className="active"/>62

                                  <input type="range"/>

                                   Text Numbering
                                   A | Free Hand text

                                  Main cover

                                  Reference

                                  Other

                            {/*

 */}

                            {/*Trigger*/}
                            <button className="btn btn-primary dropdown-toggle waves-effect waves-light mbl-h-btns" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></button>
                            {/*Menu*/}

                                <form className="form-inline-fields">
                                  <button className="btn btn-primary mbl-h-btns-desktop hide-tabs"></button>
                                  <button className="btn btn-primary mbl-h-btns-desktop hide-tabs"></button>

                                    W
                                    <input type="text" className="form-control" placeholder="3.25"/>

                                    H
                                    <input type="text" className="form-control" placeholder="3.25"/>

                                  <button className="btn btn-primary mbl-h-btns-desktop"></button>

                                    <select className="browser-default">
                                      <option value={1}>In</option>
                                      <option value={2}>cm</option>
                                      <option value={3}>mm</option>
                                    </select>

                                  <button className="btn btn-primary mbl-h-btns-desktop"></button>
                                  <button className="btn btn-primary mbl-h-btns-desktop hide-tabs"></button>
                                </form>

                                {
                                  (this.props.previewImage != "")
                                    ?

                                    :
                                    <canvas></canvas>
                                }

                                 Attach New

                                       Computer

                                       Dropbox

                                       Google Drive

                                       One drive

                                       Box

                                       Facebook

                                       Flickr

                                      <input type="email" id="form9" className="form-control validate" placeholder="Paste url to capture from web..."/>

                                    <button type="button" className="btn btn-amber waves-effect waves-light">Capture</button>

                                {/* <input type="file" name="library-new"> */}

 Library

                              Add a Whiteboard

          </Dialog>

      </MuiThemeProvider>
    );
  }
}

export default Editor;


text:
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace TechTourGdl.ViewModel
{
	public class BaseViewModel : INotifyPropertyChanged
	{
		string _title = string.Empty;

		public BaseViewModel()
		{
		}

		public string Title
		{
			get
			{
				return _title;
			}
			set
			{
				if (_title == value)
					return;
				_title = value;
				NotifyPropertyChanged();
			}
		}

		#region INotifyPropertyChanged

		public event PropertyChangedEventHandler PropertyChanged;

		public void NotifyPropertyChanged([CallerMemberName]string propertyName = null)
		{
			var handler = PropertyChanged;
			if (handler != null)
			{
				handler(this, new PropertyChangedEventArgs(propertyName));
			}
		}

		#endregion
	}
}


text:
package org.gradle.tooling.model.idea;

import org.gradle.api.Incubating;
import org.gradle.tooling.model.DomainObjectSet;

import java.io.File;
import java.util.Set;

/**
 * Contains content root information.
 */
public interface IdeaContentRoot {

    /**
     * The content root directory.
     */
    File getRootDirectory();

    /**
     * The set of source directories.
     */
    DomainObjectSet<? extends IdeaSourceDirectory> getSourceDirectories();

    /**
     * The set of generated source directories. This is a subset of those directories returned by {@link #getSourceDirectories()}.
     *
     * @since 2.2
     */
    @Incubating
    DomainObjectSet<? extends IdeaSourceDirectory> getGeneratedSourceDirectories();

    /**
     * The set of test source directories.
     */
    DomainObjectSet<? extends IdeaSourceDirectory> getTestDirectories();

    /**
     * The set of generated test directories. This is a subset of those directories returned by {@link #getTestDirectories()}.
     *
     * @since 2.2
     */
    @Incubating
    DomainObjectSet<? extends IdeaSourceDirectory> getGeneratedTestDirectories();

    /**
     * The set of excluded directories.
     */
    Set<File> getExcludeDirectories();
}


text:
![](https://img.shields.io/github/license/mashape/apistatus.svg "License")

Projeto da disciplina de Engenharia de Software II, desenvolvido durante a graduação em Engenharia de Computação no Instituto Nacional de Telecomunicações [(@INATEL)](https://www.inatel.br "Inatel's Homepage").

**Dependências:**
- **qtcreator:**
    ```bash
    $  sudo apt-get install qtcreator
    ```
- **mysql:**
    ```bash
    $  sudo apt-get install mysql-server
    ```
- **libqt5sql5:**
    ```bash
    $  sudo apt-get install libqt5sql5
    ```
- **libqt5sql5-mysql**
    ```bash
    $  sudo apt-get install libqt5sql5-mysql
    ```

**Desenvolvedores:**
- Samuel Pereira, samuelp@inatel.br;
- Vitor R. Di Toro", vitorrditoro@gmail.com;

<br>

**Mochila:**
- Allan Rafael C. V. Boas, allanrafael@gec.inatel.br;


text:
import { CodeMirror } from "./CodeMirror"
import { activeElt } from "../util/dom"
import { off, on } from "../util/event"
import { copyObj } from "../util/misc"

export function fromTextArea(textarea, options) {
  options = options ? copyObj(options) : {}
  options.value = textarea.value
  if (!options.tabindex && textarea.tabIndex)
    options.tabindex = textarea.tabIndex
  if (!options.placeholder && textarea.placeholder)
    options.placeholder = textarea.placeholder
  // Set autofocus to true if this textarea is focused, or if it has
  // autofocus and no other element is focused.
  if (options.autofocus == null) {
    var hasFocus = activeElt()
    options.autofocus = hasFocus == textarea ||
      textarea.getAttribute("autofocus") != null && hasFocus == document.body
  }

  function save() {textarea.value = cm.getValue()}
  if (textarea.form) {
    on(textarea.form, "submit", save)
    // Deplorable hack to make the submit method do the right thing.
    if (!options.leaveSubmitMethodAlone) {
      var form = textarea.form, realSubmit = form.submit
      try {
        var wrappedSubmit = form.submit = function() {
          save()
          form.submit = realSubmit
          form.submit()
          form.submit = wrappedSubmit
        }
      } catch(e) {}
    }
  }

  options.finishInit = function(cm) {
    cm.save = save
    cm.getTextArea = function() { return textarea }
    cm.toTextArea = function() {
      cm.toTextArea = isNaN // Prevent this from being ran twice
      save()
      textarea.parentNode.removeChild(cm.getWrapperElement())
      textarea.style.display = ""
      if (textarea.form) {
        off(textarea.form, "submit", save)
        if (typeof textarea.form.submit == "function")
          textarea.form.submit = realSubmit
      }
    }
  }

  textarea.style.display = "none"
  var cm = CodeMirror(function(node) {
    textarea.parentNode.insertBefore(node, textarea.nextSibling)
  }, options)
  return cm
}


text:
@extends($stats_layout)

@section('page-contents')

@stop

@section('inline-javascript')
    @include(
        'pragmarx/tracker::_datatables',
        array(
            'datatables_ajax_route' => route('tracker.stats.api.log', array('uuid' => $uuid)),
            'datatables_columns' =>
            '
                { "data" : "method",        "title" : "'.trans('tracker::tracker.method').'", "orderable": true, "searchable": false },
                { "data" : "route_name",    "title" : "'.trans('tracker::tracker.route_name_action').'", "orderable": true, "searchable": false },
                { "data" : "route",         "title" : "'.trans('tracker::tracker.route').'", "orderable": true, "searchable": false },
                { "data" : "query",         "title" : "'.trans('tracker::tracker.query').'", "orderable": true, "searchable": false },
                { "data" : "is_ajax",       "title" : "'.trans('tracker::tracker.is_ajax').'", "orderable": true, "searchable": false },
                { "data" : "is_secure",     "title" : "'.trans('tracker::tracker.is_secure').'", "orderable": true, "searchable": false },
                { "data" : "is_json",       "title" : "'.trans('tracker::tracker.is_json').'", "orderable": true, "searchable": false },
                { "data" : "wants_json",    "title" : "'.trans('tracker::tracker.wants_json').'", "orderable": true, "searchable": false },
                { "data" : "error",         "title" : "'.trans('tracker::tracker.error_q').'", "orderable": true, "searchable": false },
                { "data" : "created_at",    "title" : "'.trans('tracker::tracker.created_at').'", "orderable": true, "searchable": false },
            '
        )
    )
@stop


text:
package org.apache.ranger.patch;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.ranger.biz.RangerBizUtil;
import org.apache.ranger.biz.ServiceDBStore;
import org.apache.ranger.common.JSONUtil;
import org.apache.ranger.common.RangerValidatorFactory;
import org.apache.ranger.common.StringUtil;
import org.apache.ranger.db.RangerDaoManager;
import org.apache.ranger.entity.XXServiceDef;
import org.apache.ranger.plugin.model.RangerServiceDef;
import org.apache.ranger.plugin.model.validation.RangerServiceDefValidator;
import org.apache.ranger.plugin.model.validation.RangerValidator.Action;
import org.apache.ranger.plugin.store.EmbeddedServiceDefsUtil;
import org.apache.ranger.service.RangerPolicyService;
import org.apache.ranger.service.XPermMapService;
import org.apache.ranger.service.XPolicyService;
import org.apache.ranger.util.CLIUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class PatchForHiveServiceDefUpdate_J10030 extends BaseLoader {
	private static final Logger logger = Logger.getLogger(PatchForHiveServiceDefUpdate_J10030.class);
	public static final String SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME  = "hive";
	public static final String HIVE_URL_MATCHER ="RangerURLResourceMatcher";

	@Autowired
	RangerDaoManager daoMgr;

	@Autowired
	ServiceDBStore svcDBStore;

	@Autowired
	JSONUtil jsonUtil;

	@Autowired
	RangerPolicyService policyService;

	@Autowired
	StringUtil stringUtil;

	@Autowired
	XPolicyService xPolService;

	@Autowired
	XPermMapService xPermMapService;

	@Autowired
	RangerBizUtil bizUtil;

	@Autowired
	RangerValidatorFactory validatorFactory;

	@Autowired
	ServiceDBStore svcStore;

	public static void main(String[] args) {
		logger.info("main()");
		try {
			PatchForHiveServiceDefUpdate_J10030 loader = (PatchForHiveServiceDefUpdate_J10030) CLIUtil.getBean(PatchForHiveServiceDefUpdate_J10030.class);
			loader.init();
			while (loader.isMoreToProcess()) {
				loader.load();
			}
			logger.info("Load complete. Exiting!!!");
			System.exit(0);
		} catch (Exception e) {
			logger.error("Error loading", e);
			System.exit(1);
		}
	}

	@Override
	public void init() throws Exception {
		// Do Nothing
	}

	@Override
	public void execLoad() {
		logger.info("==> PatchForHiveServiceDefUpdateForURLTypeResourceUpdate.execLoad()");
		try {
			updateHiveServiceDef();
		} catch (Exception e) {
			logger.error("Error whille updateHiveServiceDef()data.", e);
		}
		logger.info("<== PatchForHiveServiceDefUpdateForURLTypeResourceUpdate.execLoad()");
	}

	@Override
	public void printStats() {
		logger.info("PatchForHiveServiceDefUpdateForURLTypeResourceUpdate data ");
	}

	private void updateHiveServiceDef(){
		RangerServiceDef embeddedHiveServiceDef = null;
		RangerServiceDef dbHiveServiceDef 		= null;
		XXServiceDef xXServiceDefObj			= null;
		try{
			embeddedHiveServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME);

			if (embeddedHiveServiceDef != null) {
				xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME);
				if (xXServiceDefObj == null) {
					logger.error("Service def for " + SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME + " is not found!!");
					return;
				}

				String jsonStrPreUpdate = xXServiceDefObj.getDefOptions();
				Map<String, String> serviceDefOptionsPreUpdate = jsonUtil.jsonToMap(jsonStrPreUpdate);
				String valueBeforeUpdate = serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES);

				dbHiveServiceDef = svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME);

				if(dbHiveServiceDef != null) {
					boolean isServiceDefUpdated = updateServiceDef(dbHiveServiceDef, embeddedHiveServiceDef);

					if (isServiceDefUpdated) {
						xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME);

						if (xXServiceDefObj != null) {
							String jsonStrPostUpdate = xXServiceDefObj.getDefOptions();
							Map<String, String> serviceDefOptionsPostUpdate = jsonUtil.jsonToMap(jsonStrPostUpdate);
							String valueAfterUpdate = serviceDefOptionsPostUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES);

							if (!StringUtils.equals(valueBeforeUpdate, valueAfterUpdate)) {
								if (StringUtils.isEmpty(valueBeforeUpdate)) {
									serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES);
								} else {
									serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, valueBeforeUpdate);
								}
								xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate));
								daoMgr.getXXServiceDef().update(xXServiceDefObj);
							}
						}
					}
				}
			}
		} catch(Exception e) {
			logger.error("Error while updating "+SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME+"service-def", e);
		}
	}

	private boolean updateServiceDef(RangerServiceDef serviceDef, RangerServiceDef embeddedHiveServiceDef ) throws Exception {
		boolean ret = false;

		List<RangerServiceDef.RangerResourceDef> embeddedHiveResourceDefs   = null;

		embeddedHiveResourceDefs = embeddedHiveServiceDef.getResources();

			if (checkHiveURLResourceMatcherPresent(embeddedHiveResourceDefs)) {
			// This is to check if URL resource matcher is added to the resource definition, if so update the resource def
			if (embeddedHiveResourceDefs != null) {
				serviceDef.setResources(embeddedHiveResourceDefs);
			}
			ret = true;
		}

		RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore);
		validator.validate(serviceDef, Action.UPDATE);
		svcStore.updateServiceDef(serviceDef);

		return ret;
	}

	private boolean checkHiveURLResourceMatcherPresent(List<RangerServiceDef.RangerResourceDef> resourceDefs) {
		boolean ret = false;
		for(RangerServiceDef.RangerResourceDef resourceDef : resourceDefs) {
			String urlResourceMatcher = resourceDef.getMatcher();
			if (StringUtils.isNotEmpty(urlResourceMatcher) && urlResourceMatcher.endsWith(HIVE_URL_MATCHER) ) {
				ret = true ;
				break;
			}
		}
		return ret;
	}

	private String mapToJsonString(Map<String, String> map) throws Exception {
		String ret = null;
		if(map != null) {
			ret = jsonUtil.readMapToString(map);
		}
		return ret;
	}
}


text:
const initialState = {
  text: '',
};

export default function demo(state = initialState, action) {
  switch (action.type) {
    case 'DEMO_SHOW_TEXT':
      return {
        ...state,
        text: action.text,
      };
    default:
      return state;
  }
}


text:
'use strict'

const moment = require('moment')
const _ = require('lodash')

/**
 * @brief Class that manages a stream of activities (i.e., result starting,
 * result failed, etc.). It is essentially a time series database that can
 * be queried to retrieve activities past a certain point in time.
 */
class ActivityStream {
  constructor() {
    this.events = new Map()
    this.lastEventTime = moment("2004-09-08T08:02:17-05:00")
  }

  /**
   * @brief Compute the key for an activity. An activity's key is
   *        the result's name appended with the time in unix epoch format.
   *
   * @param {String} act.name Name of the result
   * @param {moment} act.modified Time when this activity occured
   */
  key(act) {
     return `${act.name}${act.modified.format('x')}`
  }

  /**
   * @brief Add a set of activities to the stream.
   *
   * @param {Array} activities An array of activity objects, each with name and time.
   */
  add(activities) {
    _.each(activities, act => {
      const key = this.key(act)
      //if (!this.events.has(key))
        this.events.set(key, act)
    })
  }

  /**
   * @brief Retrieve a set of activities that have occured since the last time
   *        this function was called.
   * @return {Array} An array of activity objects, each with name and time.
   */
  since() {
    const latest = _.filter(Array.from(this.events.values()), act =>
      act.modified.isAfter(this.lastEventTime)
    )

    // Update the latest time if there's been a new activity
    if (latest.length > 0) {
      const newest = _.maxBy(latest, act => act.modified)
      this.lastEventTime = newest.modified
    }

    // Return new activites sorted by time
    return _.sortBy(latest, 'modified')
  }
}

module.exports = ActivityStream;


text:
id: payments-checkout-subscription
title: Subscriptions
sectionid: docs
permalink: integration/checkout/subscription
---

# Subscription

*Subscription* is a recurring billing payment solution of [Checkout API](/integration/checkout-home). It allows you to bill your customer based on a specific schedule automatically. Once a user makes his first payment via *subscription*, our system signs him up for recurring billing.

> The user will be charged based on the subscription schedule. E.g. if you specify the product length as 1 month, we will charge the user every month. Next payment will happen the same day of the next month. If a payment happens on 30th of January, the next payment will be made in first days of March.

Integrating it only requires 3 steps:

* [Build payment page](#build-payment-page).

* [Handle pingback](#handle-pingback).

* [Client-side action](#client-side-action).

Before starting, make sure you have product selection step finished in your application. The deduction period for each products needs to be clearly defined and the total period length of the *subscription* shall not exceed 6 months.

***

## Payment methods for subscription

*Subscirption* supports certain payment methods:

|Payment method| Payment system short code| Notes |
|---|---|---|
| PayPal| paypal | Requires [spiderpipe](/guides/spiderpipe/paypal) for PayPal to be activated for your Paymentwall account.|
| MercadoPago | mercadopago |  |
| Qiwi wallet | qiwiwallet | |
| Credit cards | cc | Requires credit card activation flow.|
| Mobiamo | mobilegateway | Mobiamo has a special coverage of price points, see [Mobiamo coverage](http://www.mobiamo.com/coverage). |
| SEPA | sepadirectdebit | |

***

## Build payment page

Payment link can be built by ```widget``` object. The configuration difference between [single payment methods](/integration/checkout-home#checkout-api-uni) and [all payment methods](/integration/checkout-home#checkout-api-multi) is the value of ```ps``` parameter.

> See [parameter definition](/apis#section-checkout-subscription) for the requirement and meaning of each parameters while using *subscription*.

{% assign codeId = "code-checkout-subscription" %}

      PHP

      Node.js

      Java

      Ruby

      Python

      .NET

    {% for docscode in site.docscode-php %}
    {% if docscode.codeId == codeId %}
    {{ docscode.content }}
    {% break %}
    {% endif %}
    {% endfor %}

    {% for docscode in site.docscode-js %}
    {% if docscode.codeId == codeId %}
    {{ docscode.content }}
    {% break %}
    {% endif %}
    {% endfor %}

    {% for docscode in site.docscode-java %}
    {% if docscode.codeId == codeId %}
    {{ docscode.content }}
    {% break %}
    {% endif %}
    {% endfor %}

    {% for docscode in site.docscode-ruby %}
    {% if docscode.codeId == codeId %}
    {{ docscode.content }}
    {% break %}
    {% endif %}
    {% endfor %}

    {% for docscode in site.docscode-python %}
    {% if docscode.codeId == codeId %}
    {{ docscode.content }}
    {% break %}
    {% endif %}
    {% endfor %}

    {% for docscode in site.docscode-dotnet %}
    {% if docscode.codeId == codeId %}
    {{ docscode.content }}
    {% break %}
    {% endif %}
    {% endfor %}

***

## Handle pingback

Every time a user is billed, we will send a new *pingback* to inform you the customer has make a payment for his subscription. On your server side, put the following code as an online server interface to interact with our *Pingback*:

{% assign codeId = "pingback-listener-dg" %}

      PHP

      Node.js

      Java

      Ruby

      Python

      .NET

    {% for docscode in site.docscode-php %}
    {% if docscode.codeId == codeId %}
    {{ docscode.content }}
    {% break %}
    {% endif %}
    {% endfor %}

    {% for docscode in site.docscode-js %}
    {% if docscode.codeId == codeId %}
    {{ docscode.content }}
    {% break %}
    {% endif %}
    {% endfor %}

    {% for docscode in site.docscode-java %}
    {% if docscode.codeId == codeId %}
    {{ docscode.content }}
    {% break %}
    {% endif %}
    {% endfor %}

    {% for docscode in site.docscode-ruby %}
    {% if docscode.codeId == codeId %}
    {{ docscode.content }}
    {% break %}
    {% endif %}
    {% endfor %}

    {% for docscode in site.docscode-python %}
    {% if docscode.codeId == codeId %}
    {{ docscode.content }}
    {% break %}
    {% endif %}
    {% endfor %}

    {% for docscode in site.docscode-dotnet %}
    {% if docscode.codeId == codeId %}
    {{ docscode.content }}
    {% break %}
    {% endif %}
    {% endfor %}

A *pingback* request typically contains all the information for you to do the product delivery. As an addition,Paymentwall provides a series of reversed parameters as [custom pingback parameters](/reference/pingback/custom-parameter) for specific needs, you can also add your own parameters as *custom pingback parameter* in order to implement parameter transmission.

Below is a sample with default format:

```
http://www.yourserver.com/pingback_path?uid=pwuser&goodsid=gold_membership&slength=3&speriod=day&type=0&ref=b1493048890&sign_version=2&sig=d94b23ba8585f29978706dd1b153ead9
```

After validating the *pingback*, your server is always expected to be able to proceed the delivery process and respond to it with only ```OK``` in the body of *response*.

Other than successful *subscription*, there are other cases for *pingback*:

* From the moment that the recurring was cancelled, Paymentwall will send a *pingback* with ```type=12```. A *subscription* can be cancelled by either cancelled via submitting a ticket by using [cancellation API](/apis#section-tools-cancellation) or deactivating in [Dashboard](https://api.paymentwall.com/developers/reports/recurring-subscriptions/).

* A *pingback* with ```type=13``` is always generated when the recurring billing period is expired.

* If a user has insufficient funds or a payment fails for any other reason, Paymentwall will make 2 re-attempts (3 attempts in total) to charge the user. [Payment Status API](/apis#section-tools-payment-status) can report active status of the subscription with ```date_next``` for the date of next attempt. The *subscription* will be stopped if all of the attempts fail. And once it is stopped, it will no longer process an attempt to charge the user for the next scheduled payment. Paymentwall will send a *pingback* with ```type=14``` in this case , means the corresponding recurring billing payment failed.

***

## Client-side action

In most cases, a complete payment experience is required wherein the end-users can be redirected back to the original application after making a payment.

There would be a *link* shown up in the payment successful page which is hosted by Paymentwall or our partners if you have ```success_url``` presented as [optional parameter](/apis#section-param-optional) while building the link of *payment page*. Your customers are then able to click it and go back to your applications.

Alternatively, [client-side callback](/reference/client-side-callback) is suitable if you have additional requirements about client-side actions once a payment is finished.

***

## Relevant topics

* [Test your payment system](/sandbox/test-payment).

* [Pingback](/reference/pingback-home).

* [Project Review](/guides/review-home).


text:
'use strict';

const Datastore = require('@google-cloud/datastore');
const config = require('../config');

// [START config]
const ds = Datastore({
  projectId: config.get('GCLOUD_PROJECT')
});
const kind = 'Volunteer';
// [END config]

// Translates from Datastore's entity format to
// the format expected by the application.
//
// Datastore format:
//   {
//     key: [kind, id],
//     data: {
//       property: value
//     }
//   }
//
// Application format:
//   {
//     id: id,
//     property: value
//   }
function fromDatastore (obj) {
  obj.id = obj[Datastore.KEY].id;
  return obj;
}

// Translates from the application's format to the datastore's
// extended entity property format. It also handles marking any
// specified properties as non-indexed. Does not translate the key.
//
// Application format:
//   {
//     id: id,
//     property: value,
//     unindexedProperty: value
//   }
//
// Datastore extended format:
//   [
//     {
//       name: property,
//       value: value
//     },
//     {
//       name: unindexedProperty,
//       value: value,
//       excludeFromIndexes: true
//     }
//   ]
function toDatastore (obj, nonIndexed) {
  nonIndexed = nonIndexed || [];
  const results = [];
  Object.keys(obj).forEach((k) => {
    if (obj[k] === undefined) {
      return;
    }
    results.push({
      name: k,
      value: obj[k],
      excludeFromIndexes: nonIndexed.indexOf(k) !== -1
    });
  });
  return results;
}

// [START list]
function list (limit, token, cb) {
  const q = ds.createQuery([kind])
    .limit(limit)
    .order('email')
    .start(token);

  ds.runQuery(q, (err, entities, nextQuery) => {
    if (err) {
      cb(err);
      return;
    }
    const hasMore = nextQuery.moreResults !== Datastore.NO_MORE_RESULTS ? nextQuery.endCursor : false;
    cb(null, entities.map(fromDatastore), hasMore);
  });
}
// [END list]

// [START exports]
module.exports = {
  list
};
// [END exports]


text:
import React, { Component } from 'react';
import { Form, Select, Input, Button } from 'antd';
import LzEditor from 'react-lz-editor'
import styles from './PublishTopic.css';

const FormItem = Form.Item;
const Option = Select.Option;

class PublishTopic extends Component {
  constructor(props) {
    super(props);
    this.state = {
      content: `<h1>一级标题 Head level 1</h1>`
    };
    this.receiveHtml = this.receiveHtml.bind(this);
  }
  handleSubmit = (e) => {
    e.preventDefault();
    const { dispatch, loginData } = this.props;
    const { accessToken } = loginData;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { select, title } = values;
        const content = JSON.stringify(this.state.content);
        console.log('Received values of form: ', values, this.state.content, loginData);
        dispatch({ type: 'publish/fetchPublishTopic', payload: { accessToken, select, title, content } });
        this.props.showModal();
      }
    });
  }
  receiveHtml = (content) => {
    this.setState({ content });
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form className={styles.normal} layout="horizontal" onSubmit={this.handleSubmit}>
        <FormItem
          label="请选择主题类别"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 8 }}
        >
          {getFieldDecorator('select', {
            rules: [{ required: true, message: '请选择分类' }],
          })(
            <Select placeholder="请选择">
              <Option value="ask">问答</Option>
              <Option value="share">分享</Option>
              <Option value="job">招聘</Option>
            </Select>
          )}
        </FormItem>
        <FormItem
          label="标题"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 8 }}
        >
          {getFieldDecorator('title', {
            rules: [{ required: true, min: 10, message: '标题最少10个字符' }],
          })(
            <Input placeholder="请输入标题,不少于10个字符" />,
          )}
        </FormItem>
        <FormItem
          label="内容"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 8 }}
        >
          <LzEditor
            active={true}
            importContent={this.state.content}
            cbReceiver={this.receiveHtml}
            fullScreen={false}
            image={false}
            video={false}
            convertFormat="html"
          />
        </FormItem>
        <FormItem
          wrapperCol={{ span: 8, offset: 8 }}
        >
          <Button type="primary" htmlType="submit">
            Submit
          </Button>
        </FormItem>
      </Form>
    );
  }
}

export default Form.create()(PublishTopic);


text:
"""
Message Handle
"""

import ast
import curses
import importlib
from curses import panel

from google.protobuf import text_format

APOLLO_ROOT = '../../../..'

class ModuleConf(object):
    """
    ModuleConf Class
    """

    def __init__(self, name, proto_file, proto_class, conf_file, stdscr):
        self.name = name
        self.proto_file = proto_file
        self.proto_class = proto_class
        self.conf_file = conf_file
        self.stdscr = stdscr
        self.found_conf = True

    def parse_from_file(self):
        mod = importlib.import_module(self.proto_file)
        self.proto = ast.literal_eval("mod." + self.proto_class)

        try:
            with open(APOLLO_ROOT + self.conf_file, 'r') as prototxt:
                text_format.Parse(prototxt.read(), self.proto)
        except:
            self.found_conf = False
        return

    def show(self):
        cornerx = 2
        cornery = 10
        self.field = Field(self.proto, self.stdscr, self.proto.DESCRIPTOR,
                           cornerx, cornery, self.proto, self.conf_file, False)
        self.field.process_input()

class Field(object):
    """
    Item in Message Class
    """

    def __init__(self, item, win, descriptor, cornerx, cornery, proto_root,
                 conf_file, is_repeated):
        self.item = item
        self.select = 0
        self.descriptor = descriptor
        self.index = 0
        self.basex = 2
        self.basey = 4
        self.cornerx = cornerx
        self.cornery = cornery
        self.proto_root = proto_root
        self.conf_file = conf_file
        self.is_repeated = is_repeated

        x, y = win.getmaxyx()
        self.win = curses.newwin(x - 3, y - 12, cornerx, cornery)
        self.win.clear()
        self.win.box()
        self.panel = curses.panel.new_panel(self.win)
        self.panel.top()
        curses.panel.update_panels()
        self.winy, self.winx = self.win.getmaxyx()
        self.setup()
        self.print_out()

    def setup(self):
        self.elelist = []
        if self.descriptor.containing_type is not None and \
                self.descriptor.label == self.descriptor.LABEL_REPEATED:
            printstring = self.descriptor.name + " [Index: " + str(
                self.index) + "]"
            self.win.addstr(1, 2, printstring, curses.A_BOLD)

            self.prefetch(self.item[self.index], self.descriptor, self.basex,
                          self.basey, [self.index])
        else:
            self.win.addstr(1, 2, self.descriptor.name, curses.A_BOLD)
            self.prefetch(self.item, self.descriptor, self.basex, self.basey,
                          [])

    def prefetch(self, entity, descriptor, row, col, descript_path):
        if descriptor.containing_type is None or \
           descriptor.type == descriptor.TYPE_MESSAGE:
            for descript, item in entity.ListFields():
                if row >= self.winy - 1:
                    if col >= (self.winx / 3) * 2:
                        return row, col
                    row = self.basex
                    col = col + self.winx / 3

                descript_path.append(descript.name)
                if descript.label == descript.LABEL_REPEATED:
                    ele = element(row, col, descript, item, self.cornerx,
                                  self.cornery, self.item,
                                  list(descript_path), True)
                    self.elelist.append(ele)
                elif descript.type == descript.TYPE_MESSAGE:
                    self.win.addstr(row, col, descript.name + ": ")
                    row, col = self.prefetch(item, descript, row + 1, col + 2,
                                             descript_path)
                    row -= 1
                    col -= 2
                else:
                    self.prefetch(item, descript, row, col, descript_path)
                row += 1
                descript_path.pop()
            return row, col

        ele = element(row, col, descriptor, entity, self.cornerx, self.cornery,
                      self.item, list(descript_path), False)
        self.elelist.append(ele)
        return row, col

    def print_out(self):
        """
        Display every element
        """
        for i in range(len(self.elelist)):
            self.elelist[i].print_element(self.win, True
                                          if i == self.select else False)
        self.win.refresh()

    def write_to_file(self):
        with open(APOLLO_ROOT + self.conf_file, 'w') as prototxt:
            prototxt.write(text_format.MessageToString(self.proto_root))

    def process_input(self):
        self.win.keypad(1)
        while True:
            user_input = self.win.getch()
            if user_input == curses.KEY_DOWN:
                self.select = min(self.select + 1, len(self.elelist) - 1)
            elif user_input == curses.KEY_UP:
                self.select = max(self.select - 1, 0)
            elif user_input == curses.KEY_LEFT:
                if self.is_repeated:
                    self.index = max(self.index - 1, 0)
                    self.setup()
            elif user_input == curses.KEY_RIGHT:
                if self.is_repeated:
                    self.index = min(self.index + 1, len(self.item) - 1)
                    self.setup()
            elif user_input == ord('q') or user_input == 27:
                del self.win
                del self.panel
                curses.panel.update_panels()
                return
            elif user_input == ord('\n'):
                if self.select < len(self.elelist):
                    if self.elelist[self.select].is_repeated:
                        proto = self.elelist[self.select].value
                        descript = self.elelist[self.select].descriptor
                        field = Field(proto, self.win, descript,
                                      self.cornerx + 2, self.cornery + 10,
                                      self.proto_root, self.conf_file, True)
                        field.process_input()
                    else:
                        self.elelist[self.select].edit()

            elif user_input == ord('w'):
                for ele in self.elelist:
                    ele.update_proto()
                self.write_to_file()

            self.print_out()

class element(object):

    def __init__(self, row, col, descriptor, value, cornerx, cornery,
                 proto_root, descript_path, is_repeated):
        self.row = row
        self.col = col
        self.descriptor = descriptor
        self.value = value
        self.modified = False
        self.cornerx = cornerx
        self.cornery = cornery
        self.value_length = 0
        self.proto_root = proto_root
        self.descript_path = descript_path
        self.is_repeated = is_repeated

    def print_element(self, win, highlight):
        win.addstr(self.row, self.col, self.descriptor.name + ": ")
        attr = curses.A_REVERSE if highlight else curses.A_NORMAL
        if self.modified:
            attr = attr | curses.color_pair(1)

        if self.is_repeated:
            printstring = "[Repeated Item: " + str(len(self.value)) + "]"
            win.addstr(printstring, attr)
        elif self.descriptor.type == self.descriptor.TYPE_ENUM:
            enum_type = self.descriptor.enum_type.values_by_number[
                self.value].name
            win.addstr(enum_type, attr)
            if len(enum_type) < self.value_length:
                win.addstr(' ' * (self.value_length - len(enum_type)))
            self.value_length = len(enum_type)
        else:
            printstr = str(self.value)
            win.addstr(printstr, attr)
            if len(printstr) < self.value_length:
                win.addstr(' ' * (self.value_length - len(printstr)))
            self.value_length = len(printstr)

    def update_proto(self):
        if not self.modified:
            return

        cur = self.proto_root
        for i in range(len(self.descript_path) - 1):
            if isinstance(self.descript_path[i], int):
                cur = cur[self.descript_path[i]]
            else:
                cur = getattr(cur, self.descript_path[i])
        if isinstance(self.descript_path[-1], int):
            cur[self.descript_path[-1]] = self.value
        else:
            setattr(cur, self.descript_path[-1], self.value)
        self.modified = False

    def get_input(self, options, select):
        for i in range(len(options)):
            self.win.addstr(i, 0, options[i], curses.A_REVERSE
                            if select == i else curses.A_NORMAL)
        self.win.refresh()
        self.win.keypad(1)
        while True:
            user_input = self.win.getch()
            if user_input == curses.KEY_DOWN:
                select = min(select + 1, len(options) - 1)
            elif user_input == curses.KEY_UP:
                select = max(select - 1, 0)
            elif user_input == 27:
                return select, False
            elif user_input == ord('\n'):
                return select, True
            for i in range(len(options)):
                self.win.addstr(i, 0, options[i], curses.A_REVERSE
                                if select == i else curses.A_NORMAL)
            self.win.refresh()

    def edit(self):
        x = self.row + self.cornerx
        y = self.col + self.cornery + len(self.descriptor.name) + 2
        if self.descriptor.type == self.descriptor.TYPE_ENUM:
            options = len(self.descriptor.enum_type.values)
            self.win = curses.newwin(options, 20, x, y)
        elif self.descriptor.type == self.descriptor.TYPE_BOOL:
            self.win = curses.newwin(2, 6, x, y)
        else:
            self.win = curses.newwin(1, 20, x, y)
        self.win.bkgd(' ', curses.color_pair(3))
        self.win.erase()
        self.panel = curses.panel.new_panel(self.win)
        self.panel.top()
        curses.panel.update_panels()
        self.win.refresh()

        if self.descriptor.type == self.descriptor.TYPE_ENUM:
            options = [value.name for value in self.descriptor.enum_type.values]
            value, modified = self.get_input(options, self.value)
            if modified and value != self.value:
                self.value = value
                self.modified = modified

        elif self.descriptor.type == self.descriptor.TYPE_BOOL:
            options = ["False", "True"]
            select = 1 if self.value else 0
            value, modified = self.get_input(options, select)
            value = True if value == 1 else False
            if modified and value != self.value:
                self.value = value
                self.modified = modified
        else:
            curses.echo()
            s = self.win.getstr(0, 0, 20)
            if len(s) == 0:
                pass
            elif self.descriptor.type == self.descriptor.TYPE_FLOAT or \
                    self.descriptor.type == self.descriptor.TYPE_DOUBLE:
                try:
                    value = float(s)
                    self.modified = True
                    self.value = value
                except ValueError:
                    pass
            elif self.descriptor.type == self.descriptor.TYPE_STRING:
                if s != self.value:
                    self.value = s
                    self.modified = True
            else:
                try:
                    value = int(s)
                    self.modified = True
                    self.value = value
                except ValueError:
                    pass
            curses.noecho()

        del self.win
        del self.panel
        curses.panel.update_panels()


text:
/* CSS definitions for AccountManagerPlugin */
/* styles for login page - new style */
/* Copy this file into your <env>/htdocs/ folder, add the style definitions
   below to an existing one or include in another way, if you already have
   some Trac customization in place. */

body { background-color:#efefef; }
div.login {
    background-color:#ffffff;
    margin:2em auto 0; width:420px;
    border:1px solid #666666;
    }
div.login h1 { margin-top:1em; text-align:center; width:100%; }
div#login_options ul { margin:1em 0pt; text-align:center; }
.central { text-align:center; }
.spacer { height:7em; }
.textbox { text-indent:0.5em; margin:0 120px 0.5em; }


text:
This readme describes how to setup Greenplum that is running inside docker.

## Pre-requisites:
- [docker-compose](http://docs.docker.com/compose)

# Verify the docker instance is running
Make sure the docker instances are running by running `docker ps`
```
  $ docker ps
CONTAINER ID        IMAGE                                COMMAND                  CREATED             STATUS              PORTS                                                                                NAMES
95e091b03024        gettyimages/spark:2.1.1-hadoop-2.7   "bin/spark-class o..."   7 minutes ago       Up 7 minutes        7012-7016/tcp, 8881/tcp, 0.0.0.0:8081->8081/tcp                                                                                docker_worker_1
150ab427ab05        docker_gpdb                          "/bin/sh -c 'echo ..."   7 minutes ago       Up 6 minutes        0.0.0.0:5005->5005/tcp, 0.0.0.0:5010->5010/tcp, 0.0.0.0:5432->5432/tcp, 0.0.0.0:9090->9090/tcp, 0.0.0.0:40000-40002->40000-40002/tcp, 0.0.0.0:9022->22/tcp   docker_gpdb_1
a8bd0238cfab        gettyimages/spark:2.1.1-hadoop-2.7   "bin/spark-class o..."   7 minutes ago       Up 7 minutes        0.0.0.0:4040->4040/tcp, 0.0.0.0:6066->6066/tcp, 0.0.0.0:7077->7077/tcp, 0.0.0.0:8080->8080/tcp, 7001-7006/tcp                                                docker_master_1
```

##  How to run the setupDB.sh
1. Connect to the GPDB docker image
The Greenplum DB cluster will be running at `docker_gpdb_1` with two segments. To access this docker instance, exec into a container:
```
  $ docker exec -it docker_gpdb_1 bin/bash
```

2. Execute the command below to access the scripts folder under "/code/data"
```
[root@d632f535db87]# cd /code/data
```

3. Run `scripts/setupDB.sh`, in order to create a database and table.
```
[root@d632f535db87 data]# scripts/setupDB.sh
psql:./sample_table.sql:1: NOTICE:  table "basictable" does not exist, skipping
DROP TABLE
psql:./sample_table.sql:5: NOTICE:  CREATE TABLE will create implicit sequence "basictable_id_seq" for serial column "basictable.id"
CREATE TABLE
INSERT 0 1
INSERT 0 1
INSERT 0 1
INSERT 0 1
INSERT 0 1
INSERT 0 1
INSERT 0 1
INSERT 0 1
INSERT 0 1
INSERT 0 9
INSERT 0 18
INSERT 0 36
INSERT 0 72
INSERT 0 144
INSERT 0 288
INSERT 0 576
INSERT 0 1152
INSERT 0 2304
INSERT 0 4608
```

4. Run the following psql command to verify database (basic_db) and table (basictable) are created correctly.
```
[root@d632f535db87 data]# psql -h localhost -U gpadmin -d basic_db -c "\dt" -w pivotal
psql: warning: extra command-line argument "pivotal" ignored
           List of relations
 Schema |    Name    | Type  |  Owner
--------+------------+-------+---------
 public | basictable | table | gpadmin
(1 row)

[root@d632f535db87 data]# psql -h localhost -U gpadmin -d basic_db -c "select count(*) from basictable" -w pivotal
psql: warning: extra command-line argument "pivotal" ignored
 count
-------
  9216
(1 row)

```


text:
<?php
namespace IComeFromTheNet\PointsMachine\DB\Gateway;

use DateTime;
use IComeFromTheNet\PointsMachine\DB\CommonTable;
use IComeFromTheNet\PointsMachine\DB\Query\EventTypeQuery;

/**
 * Table gateway pt_event_type
 *
 * @author Lewis Dyer <getintouch@icomefromthenet.com>
 * @since 1.0
 */
class EventTypeGateway extends CommonTable
{
    /**
    * Create a new instance of the querybuilder
    *
    * @access public
    * @return IComeFromTheNet\PointsMachine\DB\Query\EventTypeQuery
    */
    public function newQueryBuilder()
    {
        $this->head = new EventTypeQuery($this->adapter,$this);
        $this->head->setDefaultAlias($this->getTableQueryAlias());

        return $this->head;
    }

     /**
     * Check if a event type with the given id is current
     *
     * NOW should be date fetch from the database.
     *
     * @param string    $sEventTypeId  The Entity ID
     * @param DateTime  $oNow       The Now data form the database
     */
    public function checkEventTypeIsCurrent($sEventTypeId, DateTime $oNow)
    {

        return (boolean) $this->newQueryBuilder()
                    ->select(1)
                    ->from($this->getMetaData()->getName(),$this->getTableQueryAlias())
                    ->filterByCurrent($oNow)
                    ->filterByEventType($sEventTypeId)
                    ->end()
                ->fetchColumn(0);

    }

}
/* End of Class */


text:
package org.lwjgl.opengl.swt;

import static org.lwjgl.opengles.GLES20.*;

import java.nio.FloatBuffer;
import java.nio.IntBuffer;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.swt.GLData.API;
import org.lwjgl.opengles.GLES;
import org.lwjgl.system.Configuration;
import org.lwjgl.system.Platform;

/**
 * Shows how to use OpenGL ES with SWT.
 *
 * @author Kai Burjack
 */
public class NvGLESDemo {
	public static void main(String[] args) {
		final Display display = new Display();
		final Shell shell = new Shell(display, SWT.SHELL_TRIM | SWT.NO_BACKGROUND | SWT.NO_REDRAW_RESIZE);
		shell.setLayout(new FillLayout());
        shell.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                if (e.stateMask == SWT.ALT && (e.keyCode == SWT.KEYPAD_CR || e.keyCode == SWT.CR)) {
                    if (Platform.get() == Platform.WINDOWS) {
                        // Fix crappy/buggy fullscreen mode in SWT
                        SwtHelperWin32.properFullscreen(shell);
                    } else {
                        shell.setFullScreen(!shell.getFullScreen());
                    }
                }
            }
        });
		GLData data = new GLData();
		data.api = API.GLES;
		data.majorVersion = 2;
		data.minorVersion = 0;
		data.samples = 4;
		data.swapInterval = 1;
		final GLCanvas canvas = new GLCanvas(shell, SWT.NO_BACKGROUND | SWT.NO_REDRAW_RESIZE, data);
		canvas.setCurrent();

		// Enable LWJGL3 to use GLES via GL library
		// From: http://bedroomcoders.co.uk/gles2-0-everywhere-thanks-to-lwjgl3/
		if (Platform.get() == Platform.WINDOWS ) {
			// pretend we're using GLES in windows, instead use a subset of OpenGL 2.0 as GLES 2.0
			Configuration.OPENGLES_LIBRARY_NAME.set("OpenGL32");
			Configuration.OPENGLES_EXPLICIT_INIT.set(true);
			org.lwjgl.opengles.GLES.create(org.lwjgl.opengl.GL.getFunctionProvider()); // omg?!
		}

		GLES.createCapabilities();

		final Rectangle rect = new Rectangle(0, 0, 0, 0);
		canvas.addListener(SWT.Resize, new Listener() {
			public void handleEvent(@SuppressWarnings("unused") Event event) {
				Rectangle bounds = canvas.getBounds();
				rect.width = bounds.width;
				rect.height = bounds.height;
			}
		});
		shell.addListener(SWT.Traverse, new Listener() {
			public void handleEvent(Event event) {
				switch (event.detail) {
				case SWT.TRAVERSE_ESCAPE:
					shell.close();
					event.detail = SWT.TRAVERSE_NONE;
					event.doit = false;
					break;
				}
			}
		});

		glClearColor(0.3f, 0.5f, 0.8f, 1.0f);

		// Create a simple shader program
		int program = glCreateProgram();
		int vs = glCreateShader(GL_VERTEX_SHADER);
		glShaderSource(vs,
				"#version 100\n" +
				"attribute vec3 vertex;" +
				"uniform float rot;" +
				"uniform float aspect;" +
				"void main(void) {" +
				"  vec3 v = vertex * 0.5;" +
				"  vec3 v_ = vec3(0.0, 0.0, 0.0);" +
				"  v_.x = v.x * cos(rot) - v.y * sin(rot);" +
				"  v_.y = v.y * cos(rot) + v.x * sin(rot);" +
				"  v_.x /= aspect;" +
				"  gl_Position = vec4(v_, 1.0);" +
				"}");
		glCompileShader(vs);
		glAttachShader(program, vs);
		int fs = glCreateShader(GL_FRAGMENT_SHADER);
		glShaderSource(fs,
				"#version 100\n" +
				"precision mediump float;" +
				"void main(void) {" +
				"  gl_FragColor = vec4(0.1, 0.3, 0.5, 1.0);" +
				"}");
		glCompileShader(fs);
		glAttachShader(program, fs);
		glBindAttribLocation(program, 0, "vertex");
		glLinkProgram(program);
		glUseProgram(program);
		final int rotLocation = glGetUniformLocation(program, "rot");
		final int aspectLocation = glGetUniformLocation(program, "aspect");

		// Create a simple quad
		int vbo = glGenBuffers();
		int ibo = glGenBuffers();
		float[] vertices = {
			-1, -1, 0,
			 1, -1, 0,
			 1,  1, 0,
			-1,  1, 0
		};
		int[] indices = {
			0, 1, 2,
			2, 3, 0
		};
		glBindBuffer(GL_ARRAY_BUFFER, vbo);
		glBufferData(GL_ARRAY_BUFFER, (FloatBuffer) BufferUtils.createFloatBuffer(vertices.length).put(vertices).flip(), GL_STATIC_DRAW);
		glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0L);
		glEnableVertexAttribArray(0);
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
		glBufferData(GL_ELEMENT_ARRAY_BUFFER, (IntBuffer) BufferUtils.createIntBuffer(indices.length).put(indices).flip(), GL_STATIC_DRAW);

		shell.setSize(800, 600);
		shell.open();

		display.asyncExec(new Runnable() {
			float rot;
			long lastTime = System.nanoTime();
			public void run() {
				if (!canvas.isDisposed()) {
					canvas.setCurrent();
					glClear(GL_COLOR_BUFFER_BIT);
					glViewport(0, 0, rect.width, rect.height);

					float aspect = (float) rect.width / rect.height;
					glUniform1f(aspectLocation, aspect);
					glUniform1f(rotLocation, rot);
					glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

					canvas.swapBuffers();
					display.asyncExec(this);

					long thisTime = System.nanoTime();
					float delta = (thisTime - lastTime) / 1E9f;
					rot += delta * 0.1f;
					if (rot > 2.0 * Math.PI) {
						rot -= 2.0f * (float) Math.PI;
					}
					lastTime = thisTime;
				}
			}
		});

		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		display.dispose();
	}
}


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/scom/plugins/SCOM_COMP_ID_Parse.C $                   */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016                             */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include "errludparser.H"
#include "scomUdParserFactory.H"

ERRL_MAKE_UD_PARSER(SCOM::UserDetailsParserFactory, hbfw::SCOM_COMP_ID)


text:
/**
 * @fileoverview Rule to disallow use of the new operator with global non-constructor functions
 * @author Sosuke Suzuki
 */

"use strict";

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

const nonConstructorGlobalFunctionNames = ["Symbol", "BigInt"];

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

/** @type {import('../shared/types').Rule} */
module.exports = {
    meta: {
        type: "problem",

        docs: {
            description: "Disallow `new` operators with global non-constructor functions",
            recommended: false,
            url: "https://eslint.org/docs/rules/no-new-native-nonconstructor"
        },

        schema: [],

        messages: {
            noNewNonconstructor: "`{{name}}` cannot be called as a constructor."
        }
    },

    create(context) {

        return {
            "Program:exit"() {
                const globalScope = context.getScope();

                for (const nonConstructorName of nonConstructorGlobalFunctionNames) {
                    const variable = globalScope.set.get(nonConstructorName);

                    if (variable && variable.defs.length === 0) {
                        variable.references.forEach(ref => {
                            const node = ref.identifier;
                            const parent = node.parent;

                            if (parent && parent.type === "NewExpression" && parent.callee === node) {
                                context.report({
                                    node,
                                    messageId: "noNewNonconstructor",
                                    data: { name: nonConstructorName }
                                });
                            }
                        });
                    }
                }
            }
        };

    }
};