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

    QUnit.module('CFW_Modal', {
        before: function() {
            // Simulate scrollbars in PhantomJS
            $('html').css('padding-right', '16px');
            // Add full-width fixed/sticky test element
            $('').appendTo('head');
        },
        afterEach: function() {
            $('.modal, .modal-backdrop').remove();
            $(document.body)
                .removeAttr('style')
                .removeClass('modal-open');
            $('#qunit-fixture').empty();
        },
        after: function() {
            $('html').removeAttr('style');
            $('#styleFixed').remove();
        }
    });

    QUnit.test('should be defined on jquery object', function(assert) {
        assert.expect(1);
        assert.ok($(document.body).CFW_Modal, 'CFW_Modal method is defined');
    });

    QUnit.test('should return jquery collection containing the element', function(assert) {
        assert.expect(2);
        var $el = $('

');
        var $col = $el.CFW_Modal();
        assert.ok($col instanceof $, 'returns jquery collection');
        assert.strictEqual($col[0], $el[0], 'collection contains element');
    });

    QUnit.test('should fire beforeShow event when show is called', function(assert) {
        assert.expect(1);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('

').appendTo(document.body);

        $target.on('beforeShow.cfw.modal', function() {
            assert.ok(true, 'show event fired');
            done();
        });
        $trigger.CFW_Modal();
        $trigger.CFW_Modal('show');
    });

    QUnit.test('should not fire afterShow when beforeShow is prevented', function(assert) {
        assert.expect(1);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('

').appendTo(document.body);

        $target
            .on('beforeShow.cfw.modal', function(e) {
                e.preventDefault();
                assert.ok(true, 'beforeShow event fired');
                done();
            })
            .on('afterShow.cfw.modal', function() {
                assert.ok(false, 'afterShow event fired');
            });

        $trigger.CFW_Modal();
        $trigger.CFW_Modal('show');
    });

    QUnit.test('should show modal when show is called (no transition)', function(assert) {
        assert.expect(1);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('

').css('transition', 'none').appendTo(document.body);

        $target
            .on('afterShow.cfw.modal', function() {
                assert.ok($target.is(':visible'), 'modal visible');
                done();
            });
        $trigger.CFW_Modal();
        $trigger.CFW_Modal('show');
    });

    QUnit.test('should show modal when show is called (with transition)', function(assert) {
        assert.expect(1);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('

').css('transition', '.05s').appendTo(document.body);

        $target
            .on('afterShow.cfw.modal', function() {
                assert.ok($target.is(':visible'), 'modal visible');
                done();
            });
        $trigger.CFW_Modal();
        $trigger.CFW_Modal('show');
    });

    QUnit.test('should hide modal when hide is called (no transition)', function(assert) {
        assert.expect(2);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('

').css('transition', 'none').appendTo(document.body);

        $target
            .on('afterShow.cfw.modal', function() {
                assert.ok($target.is(':visible'), 'modal visible');
                $trigger.CFW_Modal('hide');
            })
            .on('afterHide.cfw.modal', function() {
                assert.ok(!$target.is(':visible'), 'modal hidden');
                done();
            });
        $trigger.CFW_Modal();
        $trigger.CFW_Modal('show');
    });

    QUnit.test('should hide modal when hide is called (with transition)', function(assert) {
        assert.expect(2);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('

').css('transition', '.05s').appendTo(document.body);

        $target
            .on('afterShow.cfw.modal', function() {
                assert.ok($target.is(':visible'), 'modal visible');
                $trigger.CFW_Modal('hide');
            })
            .on('afterHide.cfw.modal', function() {
                assert.ok(!$target.is(':visible'), 'modal hidden');
                done();
            });
        $trigger.CFW_Modal();
        $trigger.CFW_Modal('show');
    });

    QUnit.test('should toggle when toggle is called', function(assert) {
        assert.expect(2);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('

').appendTo(document.body);

        $target
            .on('afterShow.cfw.modal', function() {
                assert.ok($target.is(':visible'), 'modal visible');
                $trigger.CFW_Modal('toggle');
            })
            .on('afterHide.cfw.modal', function() {
                assert.ok(!$target.is(':visible'), 'modal hidden');
                done();
            });
        $trigger.CFW_Modal();
        $trigger.CFW_Modal('toggle');
    });

    QUnit.test('should hide modal when click [data-cfw-dismiss="modal"] inside modal element', function(assert) {
        assert.expect(2);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('
<button id="XYZ" class="close" data-cfw-dismiss="modal"></button>
').appendTo(document.body);

        $target
            .on('afterShow.cfw.modal', function() {
                assert.ok($target.is(':visible'), 'modal visible');
                document.querySelector('.close').click();
            })
            .on('afterHide.cfw.modal', function() {
                assert.ok(!$target.is(':visible'), 'modal hidden');
                done();
            });

        $trigger.CFW_Modal();
        $trigger.CFW_Modal('show');
    });

    QUnit.test('should hide modal when click [data-cfw-dismiss="modal"] outside modal element', function(assert) {
        assert.expect(2);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('

').appendTo(document.body);
        var $dismiss = $('<button class="close" data-cfw-dismiss="modal" data-cfw-modal-target="#modal"></button>').appendTo('#qunit-fixture');

        $target
            .on('afterShow.cfw.modal', function() {
                assert.ok($target.is(':visible'), 'modal visible');
                $dismiss.trigger('click');
            })
            .on('afterHide.cfw.modal', function() {
                assert.ok(!$target.is(':visible'), 'modal hidden');
                done();
            });
        $trigger.CFW_Modal();
        $trigger.CFW_Modal('show');
    });

    QUnit.test('should allow modal close with "backdrop:false"', function(assert) {
        assert.expect(2);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal" data-cfw-modal-backdrop="false">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('

').appendTo(document.body);

        $target
            .on('afterShow.cfw.modal', function() {
                assert.ok($target.is(':visible'), 'modal visible');
                $trigger.CFW_Modal('hide');
            })
            .on('afterHide.cfw.modal', function() {
                assert.ok(!$target.is(':visible'), 'modal hidden');
                done();
            });

        $trigger.CFW_Modal();
        $trigger.CFW_Modal('show');
    });

    QUnit.test('should close modal when escape key is pressed via keydown', function(assert) {
        assert.expect(2);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('

').appendTo(document.body);

        $target
            .on('afterShow.cfw.modal', function() {
                assert.ok($target.is(':visible'), 'modal visible');
                $target.trigger($.Event('keydown', {
                    which: 27 // Esc
                }));

                setTimeout(function() {
                    assert.ok(!$target.is(':visible'), 'modal hidden');
                    done();
                }, 0);
            });

        $trigger.CFW_Modal();
        $trigger.CFW_Modal('show');
    });

    QUnit.test('should not close modal when escape key is pressed via keyup', function(assert) {
        assert.expect(2);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('

').appendTo(document.body);

        $target
            .on('afterShow.cfw.modal', function() {
                assert.ok($target.is(':visible'), 'modal visible');
                $target.trigger($.Event('keyup', {
                    which: 27 // Esc
                }));

                setTimeout(function() {
                    assert.ok($target.is(':visible'), 'modal still visible');
                    done();
                }, 0);
            });

        $trigger.CFW_Modal();
        $trigger.CFW_Modal('show');
    });

    QUnit.test('should not close modal when escape key is pressed via keydown with "keyboard:false"', function(assert) {
        assert.expect(2);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal" data-cfw-modal-keyboard="false">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('

').appendTo(document.body);

        $target
            .on('afterShow.cfw.modal', function() {
                assert.ok($target.is(':visible'), 'modal visible');
                $target.trigger($.Event('keydown', {
                    which: 27 // Esc
                }));

                setTimeout(function() {
                    assert.ok($target.is(':visible'), 'modal still visible');
                    done();
                }, 0);
            });

        $trigger.CFW_Modal();
        $trigger.CFW_Modal('show');
    });

    QUnit.test('should not close modal when clicking modal-content or modal-dialog', function(assert) {
        assert.expect(1);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal" data-cfw-modal-backdrop="static">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('

').appendTo(document.body);

        $target
            .on('afterShow.cfw.modal', function() {
                $('.modal-dialog').trigger('click');
                $('.modal-content').trigger('click');
                assert.ok($target.is(':visible'), 'modal still visible');
                done();
            });

        $trigger.CFW_Modal();
        $trigger.CFW_Modal('show');
    });

    QUnit.test('should not close modal when clicking outside of modal-content with "backdrop:static"', function(assert) {
        assert.expect(1);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal" data-cfw-modal-backdrop="static">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('

').appendTo(document.body);

        $target
            .on('afterShow.cfw.modal', function() {
                $target.trigger('click');
                assert.ok($target.is(':visible'), 'modal still visible');
                done();
            });

        $trigger.CFW_Modal();
        $trigger.CFW_Modal('show');
    });

    QUnit.test('should not close modal when clicking outside of modal-content with "backdrop:false"', function(assert) {
        assert.expect(1);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal" data-cfw-modal-backdrop="false">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('

').appendTo(document.body);

        $target
            .on('afterShow.cfw.modal', function() {
                $target.trigger('click');
                assert.ok($target.is(':visible'), 'modal still visible');
                done();
            });

        $trigger.CFW_Modal();
        $trigger.CFW_Modal('show');
    });

    QUnit.test('should close modal when clicking outside of modal-content', function(assert) {
        assert.expect(2);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('

').appendTo(document.body);

        $target
            .on('afterShow.cfw.modal', function() {
                $('.contents').trigger('click');
                assert.ok($target.is(':visible'), 'modal visible');
                $target.trigger('click');
            })
            .on('afterHide.cfw.modal', function() {
                assert.ok(!$target.is(':visible'), 'modal hidden');
                done();
            });

        $trigger.CFW_Modal();
        $trigger.CFW_Modal('show');
    });

    QUnit.test('should trigger hide event once when clicking outside of modal-content', function(assert) {
        assert.expect(1);
        var done = assert.async();

        var triggered;

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('

').appendTo(document.body);

        $target
            .on('afterShow.cfw.modal', function() {
                triggered = 0;
                $target.trigger('click');
            })
            .on('afterHide.cfw.modal', function() {
                triggered += 1;
                assert.strictEqual(triggered, 1, 'modal hide triggered once');
                done();
            });

        $trigger.CFW_Modal();
        $trigger.CFW_Modal('show');
    });

    QUnit.test('should close reopened modal with [data-cfw-dismiss="modal"] click', function(assert) {
        assert.expect(2);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('
<button class="close" data-cfw-dismiss="modal"></button>
').appendTo(document.body);

        $target
            .one('afterShow.cfw.modal', function() {
                $(this).find('.close').trigger('click');
            })
            .one('afterHide.cfw.modal', function() {
                // after one open-close cycle
                assert.ok(!$target.is(':visible'), 'modal hidden');
                $(this)
                    .one('afterShow.cfw.modal', function() {
                        $(this).find('.close').trigger('click');
                    })
                    .one('afterHide.cfw.modal', function() {
                        assert.ok(!$target.is(':visible'), 'modal hidden');
                        done();
                    });
                $trigger.CFW_Modal('show');
            });

        $trigger.CFW_Modal();
        $trigger.CFW_Modal('show');
    });

    QUnit.test('should restore focus to trigger element when modal is hidden', function(assert) {
        assert.expect(1);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('

').appendTo(document.body);

        $target
            .on('afterShow.cfw.modal', function() {
                $trigger.CFW_Modal('hide');
            })
            .on('afterHide.cfw.modal', function() {
                setTimeout(function() {
                    assert.ok($(document.activeElement).is($trigger), 'trigger element is once again focused');
                    done();
                }, 0);
            });

        $trigger.CFW_Modal();
        $trigger.CFW_Modal('show');
    });

    QUnit.test('should not parse target as html', function(assert) {
        assert.expect(1);
        var done = assert.async();

        var $toggleBtn = $('<button data-cfw="modal" data-cfw-modal-target="<div id="modal"><div class="contents"<div<div id="close" data-cfw-dismiss="modal"/></div></div>"></button>')
            .appendTo('#qunit-fixture');

        $toggleBtn
            .CFW_Modal()
            .trigger('click');

        setTimeout(function() {
            assert.strictEqual($('#modal').length, 0, 'target has not been parsed and added to the document');
            done();
        }, 1);
    });

    QUnit.test('should not execute js from target', function(assert) {
        assert.expect(0);
        var done = assert.async();

        // This toggle button contains XSS payload in its data-target
        // Note: it uses the onerror handler of an img element to execute the js, because a simple script element does not work here
        //       a script element works in manual tests though, so here it is likely blocked by the qunit framework
        var $toggleBtn = $('<button data-cfw="modal" data-cfw-modal-target="<div><image src="missing.png" onerror="$('#qunit-fixture button.control').trigger('click')"></div>"></button>')
            .appendTo('#qunit-fixture');

        // The XSS payload above does not have a closure over this function and cannot access the assert object directly
        // However, it can send a click event to the following control button, which will then fail the assert
        $('<button>')
            .addClass('control')
            .on('click', function() {
                assert.notOk(true, 'XSS payload is not executed as js');
            })
            .appendTo('#qunit-fixture');

        $toggleBtn
            .CFW_Modal()
            .trigger('click');

        setTimeout(done, 500);
    });

    QUnit.test('should not try to open a modal which is already visible', function(assert) {
        assert.expect(1);
        var done = assert.async();
        var count = 0;

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('

').appendTo(document.body);

        $target
            .on('afterShow.cfw.modal', function() {
                count++;
            }).on('afterHide.cfw.modal', function() {
                assert.strictEqual(count, 1, 'show() runs only once');
                done();
            });

        $trigger
            .CFW_Modal()
            .CFW_Modal('show')
            .CFW_Modal('show')
            .CFW_Modal('hide');
    });

    QUnit.test('should enforce focus by default', function(assert) {
        assert.expect(2);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('
<button class="close" data-cfw-dismiss="modal"></button>
').appendTo(document.body);
        var $close = $('.close');

        $target.one('afterShow.cfw.modal', function() {
            setTimeout(function() {
                $target.one('focusin', function() {
                    setTimeout(function() {
                        assert.strictEqual(document.activeElement, $close[0], 'focused moved inside modal');
                        done();
                    });
                });
                assert.strictEqual(document.activeElement, $target[0], 'modal is focused');
                $trigger.trigger('focusin');
            });
        });

        $trigger
            .CFW_Modal()
            .CFW_Modal('show');
    });

    QUnit.test('should add aria-modal attribute when shown, remove it again when hidden', function(assert) {
        assert.expect(3);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('
<button class="close" data-cfw-dismiss="modal"></button>
').appendTo(document.body);

        $target
            .on('afterShow.cfw.modal', function() {
                assert.ok($('#modal').is('[aria-modal]'), 'aria-modal attribute added');
                assert.strictEqual($('#modal').attr('aria-modal'), 'true', 'correct aria-modal="true" added');
                $(this).CFW_Modal('hide');
            })
            .on('afterHide.cfw.modal', function() {
                assert.notOk($('#modal').is('[aria-modal]'), 'aria-modal attribute removed');
                done();
            });

        $trigger
            .CFW_Modal()
            .CFW_Modal('show');
    });

    QUnit.test('should set .modal scrollTop to 0', function(assert) {
        assert.expect(1);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('

').appendTo(document.body);

        $target
            .on('afterShow.cfw.modal', function() {
                assert.strictEqual($('#modal').scrollTop(), 0, 'scrollTop is 0');
                done();
            });

        $trigger
            .CFW_Modal()
            .CFW_Modal('show');
    });

    QUnit.test('should set .modal-dialog scrollTop to 0', function(assert) {
        assert.expect(1);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('

').appendTo(document.body);

        $target
            .on('afterShow.cfw.modal', function() {
                assert.strictEqual($('#modal .modal-dialog').scrollTop(), 0, 'scrollTop is 0');
                done();
            });

        $trigger
            .CFW_Modal()
            .CFW_Modal('show');
    });

    QUnit.test('should set .modal-body scrollTop to 0', function(assert) {
        assert.expect(1);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('

').appendTo(document.body);

        $target
            .on('afterShow.cfw.modal', function() {
                assert.strictEqual($('#modal .modal-body').scrollTop(), 0, 'scrollTop is 0');
                done();
            });

        $trigger
            .CFW_Modal()
            .CFW_Modal('show');
    });

    QUnit.test('unlink method should detach events and data', function(assert) {
        assert.expect(7);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>')
            .appendTo('#qunit-fixture')
            .on('custom.foo', $.noop);
        var $target = $('

').appendTo(document.body);

        $trigger.CFW_Modal();

        assert.ok($trigger.data('cfw.modal'), 'trigger has data');
        assert.ok($._data($trigger[0], 'events').click, 'trigger has click event');
        assert.strictEqual($._data($trigger[0], 'events').custom[0].namespace, 'foo', 'trigger has extra custom.foo event');

        $target.one('afterShow.cfw.modal', function() {
            $(document).one('afterUnlink.cfw.modal', $target, function() {
                assert.ok(!$target.hasClass('in'), 'target is hidden');
                assert.ok(!$trigger.data('cfw.modal'), 'trigger does not have data');
                assert.strictEqual($._data($trigger[0], 'events').custom[0].namespace, 'foo', 'trigger still has custom.foo');
                assert.ok(!$._data($trigger[0], 'events').click, 'trigger does not have any events');
                done();
            });
            $trigger.CFW_Modal('unlink');
        });
        $trigger.CFW_Modal('show');
    });

    QUnit.test('unlink option should detach events and data after hide', function(assert) {
        assert.expect(7);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>')
            .appendTo('#qunit-fixture')
            .on('custom.foo', $.noop);
        var $target = $('

').appendTo(document.body);

        $trigger.CFW_Modal({
            unlink: true
        });

        assert.ok($trigger.data('cfw.modal'), 'trigger has data');
        assert.ok($._data($trigger[0], 'events').click, 'trigger has click event');
        assert.strictEqual($._data($trigger[0], 'events').custom[0].namespace, 'foo', 'trigger has extra custom.foo event');

        $target.one('afterShow.cfw.modal', function() {
            $(document).one('afterUnlink.cfw.modal', $target, function() {
                assert.ok(!$target.hasClass('in'), 'target is hidden');
                assert.ok(!$trigger.data('cfw.modal'), 'trigger does not have data');
                assert.strictEqual($._data($trigger[0], 'events').custom[0].namespace, 'foo', 'trigger still has custom.foo');
                assert.ok(!$._data($trigger[0], 'events').click, 'trigger does not have any events');
                done();
            });
            $trigger.CFW_Modal('hide');
        });
        $trigger.CFW_Modal('show');
    });

    QUnit.test('dispose method should unlink and remove modal', function(assert) {
        assert.expect(8);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>')
            .appendTo('#qunit-fixture')
            .on('custom.foo', $.noop);
        var $target = $('

').appendTo(document.body);

        $trigger.CFW_Modal();

        assert.ok($trigger.data('cfw.modal'), 'trigger has data');
        assert.ok($._data($trigger[0], 'events').click, 'trigger has click event');
        assert.strictEqual($._data($trigger[0], 'events').custom[0].namespace, 'foo', 'trigger has extra custom.foo event');

        $target.one('afterShow.cfw.modal', function() {
            $(document).one('dispose.cfw.modal', $target, function() {
                assert.ok(!$target.hasClass('in'), 'target is hidden');
                assert.ok(!$trigger.data('cfw.modal'), 'trigger does not have data');
                assert.strictEqual($._data($trigger[0], 'events').custom[0].namespace, 'foo', 'trigger still has custom.foo');
                assert.ok(!$._data($trigger[0], 'events').click, 'trigger does not have any events');
                // Slight delay since item removed after the event fires
                setTimeout(function() {
                    assert.strictEqual($('.modal').length, 0);
                }, 0);
                done();
            });
            $trigger.CFW_Modal('dispose');
        });
        $trigger.CFW_Modal('show');
    });

    QUnit.test('dispose option should unlink and remove modal after hide', function(assert) {
        assert.expect(8);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>')
            .appendTo('#qunit-fixture')
            .on('custom.foo', $.noop);
        var $target = $('

').appendTo(document.body);

        $trigger.CFW_Modal({
            dispose: true
        });

        assert.ok($trigger.data('cfw.modal'), 'trigger has data');
        assert.ok($._data($trigger[0], 'events').click, 'trigger has click event');
        assert.strictEqual($._data($trigger[0], 'events').custom[0].namespace, 'foo', 'trigger has extra custom.foo event');

        $target.one('afterShow.cfw.modal', function() {
            $(document).one('dispose.cfw.modal', $target, function() {
                assert.ok(!$target.hasClass('in'), 'target is hidden');
                assert.ok(!$trigger.data('cfw.modal'), 'trigger does not have data');
                assert.strictEqual($._data($trigger[0], 'events').custom[0].namespace, 'foo', 'trigger still has custom.foo');
                assert.ok(!$._data($trigger[0], 'events').click, 'trigger does not have any events');
                // Slight delay since item removed after the event fires
                setTimeout(function() {
                    assert.strictEqual($('.modal').length, 0);
                }, 0);
                done();
            });
            $trigger.CFW_Modal('hide');
        });
        $trigger.CFW_Modal('show');
    });

    QUnit.test('`chain` method should hide originating modal and open target modal', function(assert) {
        assert.expect(3);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('

').appendTo(document.body);
        var $trigger2 = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal2">Modal</button>').appendTo($target);
        var $target2 = $('

').appendTo(document.body);

        $target
            .on('afterShow.cfw.modal', function() {
                assert.ok(true, 'show event fired');
                $('#modal').CFW_Modal('chain', '#modal2');
            })
            .on('afterHide.cfw.modal', function() {
                assert.ok($target.is(':hidden'), 'first modal hidden');
            });
        $target2
            .on('afterShow.cfw.modal', function() {
                assert.ok($target2.is(':visible'), 'second modal visible');
                done();
            });

        $trigger.CFW_Modal();
        $trigger2.CFW_Modal();
        $trigger.CFW_Modal('show');
    });

    QUnit.test('should append backdrop to specified element defined by rootElement option', function(assert) {
        assert.expect(2);
        var done = assert.async();
        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $modalRoot = $('

').appendTo('#qunit-fixture');
        var $target = $('

').appendTo($modalRoot);

        $target.on('afterShow.cfw.modal', function() {
            assert.strictEqual($modalRoot[0], document.querySelector('.modal-open'));
            assert.strictEqual($modalRoot[0], document.querySelector('.modal-backdrop').parentElement);

            done();
        });

        $trigger.CFW_Modal({
            rootElement: '#modal-root'
        });
        $trigger.CFW_Modal('show');
    });

    QUnit.test('manual=true option should not add click toggle to trigger', function(assert) {
        assert.expect(1);

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('
<button class="close" data-cfw-dismiss="modal"></button>
').appendTo(document.body);

        $trigger
            .CFW_Modal({
                manual: true
            })
            .trigger('focus')
            .trigger('click');

        assert.notOk($target.hasClass('in'), 'modal visible');
    });

    QUnit.test('manual=true should still enforce focus by default', function(assert) {
        assert.expect(2);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('
<button class="close" data-cfw-dismiss="modal"></button>
').appendTo(document.body);
        var $close = $('.close');

        $target.one('afterShow.cfw.modal', function() {
            setTimeout(function() {
                $target.one('focusin', function() {
                    setTimeout(function() {
                        assert.strictEqual(document.activeElement, $close[0], 'focused moved inside modal');
                        done();
                    });
                });
                assert.strictEqual(document.activeElement, $target[0], 'modal is focused');
                $trigger.trigger('focusin');
            });
        });

        $trigger
            .CFW_Modal({
                manual: true
            })
            .CFW_Modal('show');
    });

    QUnit.test('manual=true should not return focus to trigger on close', function(assert) {
        assert.expect(2);
        var done = assert.async();

        var $trigger = $('<button type="button" class="btn" data-cfw="modal" data-cfw-modal-target="#modal">Modal</button>').appendTo('#qunit-fixture');
        var $target = $('
<button class="close" data-cfw-dismiss="modal"></button>
').appendTo(document.body);
        var $close = $('.close');

        $target.one('afterShow.cfw.modal', function() {
            setTimeout(function() {
                assert.strictEqual(document.activeElement, $target[0], 'modal is focused');
                $close.trigger('click');
            });
        });
        $target.one('afterHide.cfw.modal', function() {
            setTimeout(function() {
                assert.notEqual(document.activeElement, $trigger[0], 'trigger is not focused');
                done();
            });
        });

        $trigger
            .CFW_Modal({
                manual: true
            })
            .CFW_Modal('show');
    });
});


text:
package com.parse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;

/**
 * An operation that adds a new element to an array field, only if it wasn't already present.
 */
/** package */ class ParseAddUniqueOperation implements ParseFieldOperation {
  protected final LinkedHashSet<Object> objects = new LinkedHashSet<>();

  public ParseAddUniqueOperation(Collection<?> col) {
    objects.addAll(col);
  }

  @Override
  public JSONObject encode(ParseEncoder objectEncoder) throws JSONException {
    JSONObject output = new JSONObject();
    output.put("__op", "AddUnique");
    output.put("objects", objectEncoder.encode(new ArrayList<>(objects)));
    return output;
  }

  @Override
  @SuppressWarnings("unchecked")
  public ParseFieldOperation mergeWithPrevious(ParseFieldOperation previous) {
    if (previous == null) {
      return this;
    } else if (previous instanceof ParseDeleteOperation) {
      return new ParseSetOperation(objects);
    } else if (previous instanceof ParseSetOperation) {
      Object value = ((ParseSetOperation) previous).getValue();
      if (value instanceof JSONArray || value instanceof List) {
        return new ParseSetOperation(this.apply(value, null));
      } else {
        throw new IllegalArgumentException("You can only add an item to a List or JSONArray.");
      }
    } else if (previous instanceof ParseAddUniqueOperation) {
      List<Object> previousResult =
          new ArrayList<>(((ParseAddUniqueOperation) previous).objects);
      return new ParseAddUniqueOperation((List<Object>) this.apply(previousResult, null));
    } else {
      throw new IllegalArgumentException("Operation is invalid after previous operation.");
    }
  }

  @Override
  public Object apply(Object oldValue, String key) {
    if (oldValue == null) {
      return new ArrayList<>(objects);
    } else if (oldValue instanceof JSONArray) {
      ArrayList<Object> old = ParseFieldOperations.jsonArrayAsArrayList((JSONArray) oldValue);
      @SuppressWarnings("unchecked")
      ArrayList<Object> newValue = (ArrayList<Object>) this.apply(old, key);
      return new JSONArray(newValue);
    } else if (oldValue instanceof List) {
      ArrayList<Object> result = new ArrayList<>((List<?>) oldValue);

      // Build up a Map of objectIds of the existing ParseObjects in this field.
      HashMap<String, Integer> existingObjectIds = new HashMap<>();
      for (int i = 0; i < result.size(); i++) {
        if (result.get(i) instanceof ParseObject) {
          existingObjectIds.put(((ParseObject) result.get(i)).getObjectId(), i);
        }
      }

      // Iterate over the objects to add. If it already exists in the field,
      // remove the old one and add the new one. Otherwise, just add normally.
      for (Object obj : objects) {
        if (obj instanceof ParseObject) {
          String objectId = ((ParseObject) obj).getObjectId();
          if (objectId != null && existingObjectIds.containsKey(objectId)) {
            result.set(existingObjectIds.get(objectId), obj);
          } else if (!result.contains(obj)) {
            result.add(obj);
          }
        } else {
          if (!result.contains(obj)) {
            result.add(obj);
          }
        }
      }
      return result;
    } else {
      throw new IllegalArgumentException("Operation is invalid after previous operation.");
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef _CLIENT_LOGGING_H_
#define _CLIENT_LOGGING_H_

#if LOGGING && ANDROID
#include <android/log.h>
#define LOG_TAG "c-libjingle-webrtc"  // As in WEBRTC Native...
#define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define  LOGE(...)  __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#elif LOGGING && IOS
#define LOGI(...) printf(__VA_ARGS__);printf("\n")
#define LOGE(...) printf(__VA_ARGS__);printf("\n")
#else
#define LOGI(...) (void)0
#define LOGE(...) (void)0
#endif

#endif  // _CLIENT_LOGGING_H_


text:
package builds

import (
	"path/filepath"

	g "github.com/onsi/ginkgo"
	o "github.com/onsi/gomega"
	exutil "github.com/openshift/origin/test/extended/util"
)

var _ = g.Describe("[builds][Slow] extremely long build/bc names are not problematic", func() {
	defer g.GinkgoRecover()
	var (
		testDataBaseDir  = exutil.FixturePath("testdata", "long_names")
		longNamesFixture = filepath.Join(testDataBaseDir, "fixture.json")
		oc               = exutil.NewCLI("long-names", exutil.KubeConfigPath())
	)

	g.Describe("build with long names", func() {
		oc.SetOutputDir(exutil.TestContext.OutputDir)

		g.It("delete builds with long names without collateral damage", func() {
			g.By("creating long_names fixtures")
			err := oc.Run("create").Args("-f", longNamesFixture).Execute()
			o.Expect(err).NotTo(o.HaveOccurred())

			// Names can be a maximum of 253 chars. These build config names are 201 (to allow for suffixes appiled during the test process, e.g. -1, -2 for builds and log filenames)
			// and the names differ only in the last character.
			bcA := "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890a"
			bcB := "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890b"

			g.By("starting long name build config A-1")
			bnA1, err := oc.Run("start-build").Args(bcA).Output()
			o.Expect(err).NotTo(o.HaveOccurred())

			g.By("starting long name build config B-1")
			bnB1, err := oc.Run("start-build").Args(bcB).Output()
			o.Expect(err).NotTo(o.HaveOccurred())

			g.By("starting long name build config A-2")
			bnA2, err := oc.Run("start-build").Args(bcA).Output()
			o.Expect(err).NotTo(o.HaveOccurred())

			g.By("starting long name build config B-2")
			bnB2, err := oc.Run("start-build").Args(bcB).Output()
			o.Expect(err).NotTo(o.HaveOccurred())

			builds := [...]string{bnA1, bnB1, bnA2, bnB2}

			g.By("checking the status of the builds")
			for _, bn := range builds {
				err = exutil.WaitForABuild(oc.REST().Builds(oc.Namespace()), bn, exutil.CheckBuildSuccessFn, exutil.CheckBuildFailedFn)
				if err != nil {
					exutil.DumpNamedBuildLogs(bn, oc)
				}
				o.Expect(err).NotTo(o.HaveOccurred())
			}

			g.By("Verifying gets for build configs and builds")
			for _, bn := range builds {
				err = oc.Run("get").Args("build", bn).Execute()
				o.Expect(err).NotTo(o.HaveOccurred())
			}

			g.By("Deleting build config B (which should cascade to builds it created)")
			err = oc.Run("delete").Args("bc", bcB).Execute()
			o.Expect(err).NotTo(o.HaveOccurred())

			err = oc.Run("get").Args("bc", bcB).Execute()
			o.Expect(err).To(o.HaveOccurred())

			err = oc.Run("get").Args("build", bnB1).Execute()
			o.Expect(err).To(o.HaveOccurred())

			err = oc.Run("get").Args("build", bnB2).Execute()
			o.Expect(err).To(o.HaveOccurred())

			g.By("Verifying build config A was untouched by delete")
			err = oc.Run("get").Args("bc", bcA).Execute()
			o.Expect(err).NotTo(o.HaveOccurred())

			err = oc.Run("get").Args("build", bnA1).Execute()
			o.Expect(err).NotTo(o.HaveOccurred())

			err = oc.Run("get").Args("build", bnA2).Execute()
			o.Expect(err).NotTo(o.HaveOccurred())
		})

	})
})


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE190_Integer_Overflow__int64_t_rand_square_82_goodG2B.cpp
Label Definition File: CWE190_Integer_Overflow.label.xml
Template File: sources-sinks-82_goodG2B.tmpl.cpp
*/
/*
 * @description
 * CWE: 190 Integer Overflow
 * BadSource: rand Set data to result of rand()
 * GoodSource: Set data to a small, non-zero number (two)
 * Sinks: square
 *    GoodSink: Ensure there will not be an overflow before squaring data
 *    BadSink : Square data, which can lead to overflow
 * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer
 *
 * */
#ifndef OMITGOOD

#include "std_testcase.h"
#include "CWE190_Integer_Overflow__int64_t_rand_square_82.h"

#include <math.h>

namespace CWE190_Integer_Overflow__int64_t_rand_square_82
{

void CWE190_Integer_Overflow__int64_t_rand_square_82_goodG2B::action(int64_t data)
{
    {
        /* POTENTIAL FLAW: if (data*data) > LLONG_MAX, this will overflow */
        int64_t result = data * data;
        printLongLongLine(result);
    }
}

}
#endif /* OMITGOOD */


text:
@interface BarcelonaCityBikeCity : FlatJSONListCity
@end

@implementation BarcelonaCityBikeCity

#pragma mark City Data Update

- (NSArray *)updateURLStrings
{
    return @[@"https://www.bicing.cat/localizaciones/getJsonObject.php"];
}

- (NSDictionary*) districts
{
    return @{@"26": @"10",
             @"106": @"6",
             @"193": @"4",
             @"238": @"9",
             @"101": @"5",
             @"5": @"1",
             @"1": @"2",
             @"276": @"7",
             @"93": @"3",
             @"275": @"8"
             };
}

- (RegionInfo *) regionInfoFromStation:(Station *)station values:(NSDictionary *)values patchs:(NSDictionary *)patchs requestURL:(NSString *)urlString
{
    NSString * districtCode = values[@"DisctrictCode"];
    NSString * patchedCode = self.districts[districtCode];
    if(patchedCode)
        districtCode = patchedCode;
    if([districtCode length])
        return [RegionInfo infoWithName:districtCode number:districtCode];
    else
        return nil;
}

#pragma mark Annotations

- (NSString *) titleForRegion:(Region*)region { return [NSString stringWithFormat:@"%@°",region.number]; }
- (NSString *) subtitleForRegion:(Region*)region { return @"dte."; }

- (NSDictionary *)KVCMapping
{
    return @{@"AddressGmapsLatitude": @"latitude",
             @"StationAvailableBikes": @"status_available",
             @"AddressStreet1": @"name",
             @"StationID": @"number",
             @"AddressGmapsLongitude": @"longitude",
             @"StationFreeSlot": @"status_free"
             };
}

- (NSArray *)stationAttributesArraysFromData:(NSData *)data
{
    // For some reason, Bicing has invented the JSON-in-JSON format.
    NSError* error;
    NSArray * rawJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
    if (rawJSON==nil ||
        ![rawJSON isKindOfClass:[NSArray class]] ||
        ![rawJSON count]>1 ||
        ![[rawJSON objectAtIndex:1] isKindOfClass:[NSDictionary class]] ||
        ![[[rawJSON objectAtIndex:1] objectForKey:@"data"] isKindOfClass:[NSString class]]
        ) {
        if([[NSUserDefaults standardUserDefaults] boolForKey:@"BicycletteLogParsingDetails"])
            DebugLog(@"Invalid Data : %@,%@",error, data);
        return nil;
    }
    NSString * json = [[rawJSON objectAtIndex:1] objectForKey:@"data"];
    NSData * jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];

    return [super stationAttributesArraysFromData:jsonData];
}

@end


text:
import re, os.path, platform
from HTMLParser import HTMLParser
import pymel.util as util
import pymel.versions as versions
import plogging
from pymel.mayautils import getMayaLocation

try:
    from pymel.util.external.BeautifulSoup import BeautifulSoup, NavigableString
except ImportError:
    from BeautifulSoup import BeautifulSoup, NavigableString
from keyword import iskeyword as _iskeyword

_logger = plogging.getLogger(__name__)

def mayaIsRunning():
    """
    Returns True if maya.cmds have  False otherwise.

    Early in interactive startup it is possible for commands to exist but for Maya to not yet be initialized.

    :rtype: bool
    """

    # Implementation is essentially just a wrapper for getRunningMayaVersionString -
    # this function was included for clearer / more readable code

    try :
        from maya.cmds import about
        about(version=True)
        return True
    except :
        return False

def mayaDocsLocation(version=None):
    docLocation = None
    if (version == None or version == versions.installName() ) and mayaIsRunning():
        # Return the doc location for the running version of maya
        from maya.cmds import showHelp
        docLocation = showHelp("", q=True, docs=True)

        # Older implementations had no trailing slash, but the result returned by
        # showHelp has a trailing slash... so eliminate any trailing slashes for
        # consistency
        while docLocation != "" and os.path.basename(docLocation) == "":
            docLocation = os.path.dirname(docLocation)

    # Want the docs for a different version, or maya isn't initialized yet
    if not docLocation or not os.path.isdir(docLocation):
        docLocation = getMayaLocation(version) # use original version
        if docLocation is None :
            docLocation = getMayaLocation(None)
            _logger.warning("Could not find an installed Maya for exact version %s, using first installed Maya location found in %s" % (version, docLocation) )

        if version:
            short_version = versions.parseVersionStr(version, extension=False)
        else:
            short_version = versions.shortName()
        if platform.system() == 'Darwin':
            docLocation = os.path.dirname(os.path.dirname(docLocation))

        docLocation = os.path.join(docLocation , 'docs/Maya%s/en_US' % short_version)

    return os.path.realpath(docLocation)

#---------------------------------------------------------------
#        Doc Parser
#---------------------------------------------------------------
class CommandDocParser(HTMLParser):

    def __init__(self, command):
        self.command = command
        self.flags = {}  # shortname, args, docstring, and a list of modes (i.e. edit, create, query)
        self.currFlag = ''
        # iData is used to track which type of data we are putting into flags, and corresponds with self.datatypes
        self.iData = 0
        self.pcount = 0
        self.active = False  # this is set once we reach the portion of the document that we want to parse
        self.description = ''
        self.example = ''
        self.emptyModeFlags = [] # when flags are in a sequence ( lable1, label2, label3 ), only the last flag has queryedit modes. we must gather them up and fill them when the last one ends
        HTMLParser.__init__(self)

    def startFlag(self, data):
        #_logger.debug(self, data)
        #assert data == self.currFlag
        self.iData = 0
        self.flags[self.currFlag] = {'longname': self.currFlag, 'shortname': None, 'args': None, 'numArgs': None, 'docstring': '', 'modes': [] }

    def addFlagData(self, data):
        # Shortname
        if self.iData == 0:
            self.flags[self.currFlag]['shortname'] = data.lstrip('-')

        # Arguments
        elif self.iData == 1:
            typemap = {
             'string'  : unicode,
             'float'   : float,
             'double'  : float,
             'linear'  : float,
             'angle'   : float,
             'int'     : int,
             'uint'    : int,
             'index'   : int,
             'integer'  : int,
             'boolean'  : bool,
             'script'   : 'script',
             'name'     : 'PyNode',
             'select'   : 'PyNode'
            }
            args = [ typemap.get( x.strip(), x.strip() ) for x in data.strip('[]').split(',') ]
            numArgs = len(args)
            if numArgs == 0:
                args = bool
                numArgs = 1
            elif numArgs == 1:
                args = args[0]

            self.flags[self.currFlag]['args'] = args
            self.flags[self.currFlag]['numArgs'] = numArgs

        # Docstring
        else:
            #self.flags[self.currFlag]['docstring'] += data.replace( '\r\n', ' ' ).strip() + " "
            data = data.replace( 'In query mode, this flag needs a value.', '' )
            data = data.replace( 'Flag can appear in Create mode of command', '' )
            data = data.replace( 'Flag can appear in Edit mode of command', '' )
            data = data.replace( 'Flag can appear in Query mode of command', '' )
            data = data.replace( '\r\n', ' ' ).lstrip()
            data = data.replace( '\n', ' ' ).lstrip()
            data = data.strip('{}\t')
            data = data.replace('*', '\*') # for reStructuredText
            self.flags[self.currFlag]['docstring'] += data
        self.iData += 1

    def endFlag(self):
        # cleanup last flag
        #data = self.flags[self.currFlag]['docstring']

        #_logger.debug(("ASSERT", data.pop(0), self.currFlag))
        try:
            if not self.flags[self.currFlag]['modes']:
                self.emptyModeFlags.append(self.currFlag)
            elif self.emptyModeFlags:
                    #_logger.debug("past empty flags:", self.command, self.emptyModeFlags, self.currFlag)
                    basename = re.match( '([a-zA-Z]+)', self.currFlag ).groups()[0]
                    modes = self.flags[self.currFlag]['modes']
                    self.emptyModeFlags.reverse()
                    for flag in self.emptyModeFlags:
                        if re.match( '([a-zA-Z]+)', flag ).groups()[0] == basename:
                            self.flags[flag]['modes'] = modes
                        else:
                            break

                    self.emptyModeFlags = []
        except KeyError, msg:
            pass
            #_logger.debug(self.currFlag, msg)

    def handle_starttag(self, tag, attrs):
        #_logger.debug("begin: %s tag: %s" % (tag, attrs))
        if not self.active:
            if tag == 'a':
                if attrs[0][1] == 'hFlags':
                    #_logger.debug('ACTIVE')
                    self.active = 'flag'
                elif attrs[0][1] == 'hExamples':
                    #_logger.debug("start examples")
                    self.active = 'examples'
        elif tag == 'a' and attrs[0][0] == 'name':
            self.endFlag()
            newFlag = attrs[0][1][4:]
            newFlag = newFlag.lstrip('-')
            self.currFlag = newFlag
            self.iData = 0
            #_logger.debug("NEW FLAG", attrs)
            #self.currFlag = attrs[0][1][4:]

        elif tag == 'img' and len(attrs) > 4:
            #_logger.debug("MODES", attrs[1][1])
            self.flags[self.currFlag]['modes'].append(attrs[1][1])
        elif tag == 'h2':
            self.active = False

    def handle_endtag(self, tag):
        #if tag == 'p' and self.active == 'command': self.active = False
        #_logger.debug("end: %s" % tag)
        if not self.active:
            if tag == 'p':
                if self.pcount == 3:
                    self.active = 'command'
                else:
                    self.pcount += 1
        elif self.active == 'examples' and tag == 'pre':
            self.active = False

    def handle_entityref(self,name):
        if self.active == 'examples':
            self.example += r'"'

    def handle_data(self, data):
        if not self.active:
            return
        elif self.active == 'flag':
            if self.currFlag:
                stripped = data.strip()
                if stripped == 'Return value':
                    self.active=False
                    return

                if data and stripped and stripped not in ['(',')', '=', '], [']:
                    #_logger.debug("DATA", data)

                    if self.currFlag in self.flags:
                        self.addFlagData(data)
                    else:
                        self.startFlag(data)
        elif self.active == 'command':
            data = data.replace( '\r\n', ' ' )
            data = data.replace( '\n', ' ' )
            data = data.lstrip()
            data = data.strip('{}')
            data = data.replace('*', '\*') # for reStructuredText
            if '{' not in data and '}' not in data:
                self.description += data
            #_logger.debug(data)
            #self.active = False
        elif self.active == 'examples' and data != 'Python examples':
            #_logger.debug("Example\n")
            #_logger.debug(data)
            data = data.replace( '\r\n', '\n' )
            self.example += data
            #self.active = False

# class MayaDocsLoc(str) :
#    """ Path to the Maya docs, cached at pymel start """
#    __metaclass__ = util.Singleton

# TODO : cache doc location or it's evaluated for each getCmdInfo !
# MayaDocsLoc(mayaDocsLocation())

class NodeHierarchyDocParser(HTMLParser):

    def parse(self):
        docloc = mayaDocsLocation(self.version)
        if not os.path.isdir( docloc ):
            raise IOError, "Cannot find maya documentation. Expected to find it at %s" % docloc

        f = open( os.path.join( docloc , 'Nodes/index_hierarchy.html' ) )
        self.feed( f.read() )
        f.close()
        return self.tree

    def __init__(self, version=None):
        self.version = version
        self.currentTag = None
        self.depth = 0
        self.lastDepth = -1
        self.tree = None
        self.currentLeaves = []

        HTMLParser.__init__(self)
    def handle_starttag(self, tag, attrs):
        #_logger.debug(tag, attrs)
        self.currentTag = tag

    def handle_data(self, data):
        _logger.info("data %s", data)
        if self.currentTag == 'tt':
            self.depth = data.count('>')
            #_logger.debug("lastDepth", self.lastDepth, "depth", self.depth)

        elif self.currentTag == 'a':
            data = data.lstrip()

            if self.depth == 0:
                if self.tree is None:
                    #_logger.debug("starting brand new tree: %s %s", self.depth, data)
                    self.tree = [data]
                else:
                    #_logger.debug("skipping %s", data)
                    return

            elif self.depth == self.lastDepth and self.depth > 0:
                #_logger.debug("adding to current level", self.depth, data)
                self.tree[ self.depth ].append( data )

            elif self.depth > self.lastDepth:
                #_logger.debug("starting new level: %s %s", self.depth, data)
                self.tree.append( [data] )

            elif self.depth < self.lastDepth:

                    for i in range(0, self.lastDepth-self.depth):
                        branch = self.tree.pop()
                        #_logger.debug("closing level", self.lastDepth, self.depth, self.tree[-1])
                        currTree = self.tree[-1]
                        #if isinstance(currTree, list):
                        currTree.append( branch )
                        #else:
                        #    _logger.info("skipping", data)
                        #    self.close()
                        #    return

                    #_logger.debug("adding to level", self.depth, data)
                    self.tree[ self.depth ].append( data )
            else:
                return
            self.lastDepth = self.depth
            # with 2009 and the addition of the MPxNode, the hierarchy closes all the way out ( i.e. no  >'s )
            # this prevents the depth from getting set properly. as a workaround, we'll set it to 0 here,
            # then if we encounter '> >' we set the appropriate depth, otherwise it defaults to 0.
            self.depth = 0

def printTree( tree, depth=0 ):
    for branch in tree:
        if util.isIterable(branch):
            printTree( branch, depth+1)
        else:
            _logger.info('> '*depth, branch)

class CommandModuleDocParser(HTMLParser):

    def parse(self):

        f = open( os.path.join( self.docloc , 'Commands/cat_' + self.category + '.html' ) )
        self.feed( f.read() )
        f.close()
        return self.cmdList

    def __init__(self, category, version=None ):
        self.cmdList = []
        self.category = category
        self.version = version

        docloc = mayaDocsLocation( '2009' if self.version=='2008' else self.version)
        self.docloc = docloc
        HTMLParser.__init__(self)

    def handle_starttag(self, tag, attrs):
        try:
            attrs = attrs[0]
            #_logger.debug(attrs)
            if tag == 'a' and attrs[0]=='href':
                cmd = attrs[1].split("'")[1].split('.')[0]
                self.cmdList.append( cmd )
                #_logger.debug(cmd)
        except IndexError: return

class ApiDocParser(object):
    OBSOLETE_MSG = ['NO SCRIPT SUPPORT.', 'This method is not available in Python.']
    DEPRECATED_MSG = ['This method is obsolete.', 'Deprecated:']
    def __init__(self, apiModule, version=None, verbose=False):
        version = versions.installName() if version is None else version
        self.apiModule = apiModule
        self.verbose = verbose
        self.docloc = mayaDocsLocation('2009' if version=='2008' else version)
        if not os.path.isdir(self.docloc):
            raise IOError, "Cannot find maya documentation. Expected to find it at %s" % self.docloc

    def xprint(self, *args):
        if self.verbose:
            print self.apiClassName + '.' + self.currentMethod + ':', ' '.join( [ str(x) for x in args ] )

    def getPymelMethodNames(self):

        setReg = re.compile('set([A-Z].*)')

        allFnMembers = self.methods.keys()
        pymelNames = {}
        pairs = {}
        pairsList = []

        def addSetGetPair(setmethod, getMethod):
            pairsList.append( (setMethod,getMethod) )
            # pair 'set' with 'is/get'
            pairs[setMethod] = getMethod
            for info in self.methods[setMethod]:
                info['inverse'] = (getMethod, True)

            # pair 'is/get' with 'set'
            pairs[getMethod] = setMethod
            for info in self.methods[getMethod]:
                info['inverse'] = (setMethod, False)

        for member in allFnMembers:
            m = setReg.match(member)
            if m:
                # MFn api naming convention usually uses setValue(), value() convention for its set and get methods, respectively
                # setSomething()  &  something()  becomes  setSomething() & getSomething()
                # setIsSomething() & isSomething() becomes setSomething() & isSomething()
                basename = m.group(1)
                origGetMethod = util.uncapitalize(basename)
                setMethod = member  # for name clarity
                if origGetMethod in allFnMembers:
                    # fix set
                    if re.match( 'is[A-Z].*', origGetMethod):
                        newSetMethod = 'set' + origGetMethod[2:] # remove 'is' #member[5:]
                        pymelNames[setMethod] = newSetMethod
                        for info in self.methods[setMethod]:
                            info['pymelName'] = newSetMethod
                        addSetGetPair( setMethod, origGetMethod)

                    # fix get
                    else:
                        newGetMethod = 'g' + setMethod[1:] # remove 's'
                        pymelNames[origGetMethod] = newGetMethod
                        for info in self.methods[origGetMethod]:
                            info['pymelName'] = newGetMethod
                        addSetGetPair( setMethod, origGetMethod)

                else:
                    getMethod = 'get' + basename
                    isMethod = 'is' + basename
                    if getMethod in allFnMembers:
                        addSetGetPair( setMethod, getMethod )
                    elif isMethod in allFnMembers:
                        addSetGetPair( setMethod, isMethod )

        return pymelNames, pairsList

    def getClassFilename(self):
        filename = 'class'
        for tok in re.split( '([A-Z][a-z]*)', self.apiClassName ):
            if tok:
                if tok[0].isupper():
                    filename += '_' + tok.lower()
                else:
                    filename += tok
        return filename

    def getPymelEnums(self, enumDict):
        """remove all common prefixes from list of enum values"""
        if len(enumDict) > 1:
            enumList = enumDict.keys()
            splitEnums = [ [ y for y in re.split( '([A-Z0-9][a-z0-9]*)', x ) if y ] for x in enumList ]
            splitEnumsCopy = splitEnums[:]
            for partList in zip( *splitEnumsCopy ):
                if  tuple([partList[0]]*len(partList)) == partList:
                    [ x.pop(0) for x in splitEnums ]
                else: break
            joinedEnums = [ util.uncapitalize(''.join(x), preserveAcronymns=True ) for x in splitEnums]
            for i, enum in enumerate(joinedEnums):
                if _iskeyword(enum):
                    joinedEnums[i] = enum+'_'
                    self.xprint( "bad enum", enum )
                elif enum[0].isdigit():
                    joinedEnums[i] = 'k' + enum
                    self.xprint( "bad enum", enum )

                    #print joinedEnums
                    #print enumList
                    #break

            pymelEnumDict = dict( [ (k2,enumDict[k1]) for k1, k2 in zip( enumList, joinedEnums ) ] )

            #print "enums", joinedEnums
            return pymelEnumDict

        return enumDict

    def handleEnums( self, type ):
        missingTypes = ['MUint64']
        otherTypes = ['void', 'char', 'uchar',
                    'double', 'double2', 'double3', 'double4',
                    'float', 'float2', 'float3', 'float4',
                    'bool',
                    'int', 'int2', 'int3', 'int4',
                    'uint', 'uint2', 'uint3', 'uint4',
                    'short', 'short2', 'short3', 'short4',
                    'long', 'long2', 'long3',
                    'MString', 'MStringArray']
        notTypes = ['MCallbackId']

        if type is None: return type

        # the enum is on another class
        if '::' in type:
            type = self.apiModule.Enum( type.split( '::') )

        # the enum is on this class
        elif type in self.enums:
            type = self.apiModule.Enum( [self.apiClassName, type] )

        elif type[0].isupper() and 'Ptr' not in type and not hasattr( self.apiModule, type ) and type not in otherTypes+missingTypes+notTypes:
            type = self.apiModule.Enum( [self.apiClassName, type] )
            if type not in self.badEnums:
                self.badEnums.append(type)
                _logger.warn( "Suspected Bad Enum: %s", type )
        else:
            type = str(type)
        return type

    def handleEnumDefaults( self, default, type ):

        if default is None: return default

        if isinstance( type, self.apiModule.Enum ):

            # the enum is on another class
            if '::' in default:
                apiClass, enumConst = default.split( '::')
                assert apiClass == type[0]
            else:
                enumConst = default

            return self.apiModule.Enum([type[0], type[1], enumConst])

        return default

    def getOperatorName(self, methodName):
        op = methodName[8:]
        #print "operator", methodName, op
        if op == '=':
            methodName = None
        else:

            methodName = {
                '*=' : '__rmult__',
                '*'  : '__mul__',
                '+=' : '__radd__',
                '+'  : '__add__',
                '-=' : '__rsub__',
                '-'  : '__sub__',
                '/=' : '__rdiv__',
                '/'  : '__div__',
                '==' : '__eq__',
                '!=' : '__neq__',
                '[]' : '__getitem__'}.get( op, None )
        return methodName

    def isSetMethod(self):
        if re.match( 'set[A-Z]', self.currentMethod ):
            return True
        else:
            return False

    def isGetMethod(self):
        if re.match( 'get[A-Z]', self.currentMethod ):
            return True
        else:
            return False

    def parse(self, apiClassName):

        self.enums = {}
        self.pymelEnums = {}
        self.methods=util.defaultdict(list)
        self.currentMethod=None
        self.badEnums = []

        self.apiClassName = apiClassName
        self.apiClass = getattr(self.apiModule, self.apiClassName)

        self.docfile = os.path.join( self.docloc , 'API', self.getClassFilename() + '.html' )

        _logger.info( "parsing file %s" , self.docfile )

        f = open( self.docfile )

        soup = BeautifulSoup( f.read(), convertEntities='html' )
        f.close()

        for proto in soup.body.findAll( 'div', **{'class':'memproto'} ):

            returnDoc = ''

            # NAME AND RETURN TYPE
            memb = proto.findAll( 'td', **{'class':'memname'} )[0]
            buf = [ x.strip() for x in memb.findAll( text=True )]
            if len(buf) ==1:
                buf = [ x for x in buf[0].split() if x not in ['const', 'unsigned'] ]
                if len(buf)==1:
                    returnType = None
                    methodName = buf[0]
                else:
                    returnType = ''.join(buf[:-1])
                    methodName = buf[-1]
            else:
                returnType = buf[0]
                methodName = buf[1]
                buf = [ x for x in buf[0].split() if x not in ['const', 'unsigned'] ]
                if len(buf) > 1:
                    returnType += buf[0]
                    methodName = buf[1]

            methodName = methodName.split('::')[-1]

            # convert operators to python special methods
            if methodName.startswith('operator'):
                methodName = self.getOperatorName(methodName)

                if methodName is None: continue

            # no MStatus in python
            if returnType in ['MStatus', 'void']:
                returnType = None
            else:
                returnType = self.handleEnums(returnType)

            # convert to unicode
            self.currentMethod = str(methodName)

            #constructors and destructors
            if self.currentMethod.startswith('~') or self.currentMethod == self.apiClassName:
                continue

            # ENUMS
            if returnType == 'enum':
                self.xprint( "ENUM", returnType)
                #print returnType, methodName
                try:
                    enumValues={}
                    enumDocs={}
                    for em in proto.findNextSiblings( 'div', limit=1)[0].findAll( 'em'):
                        enumKey = str(em.contents[-1])
                        try:
                            enumVal = getattr(self.apiClass, enumKey)
                        except:
                            _logger.warn( "%s.%s of enum %s does not exist" % ( self.apiClassName, enumKey, self.currentMethod))
                            enumVal = None
                        enumValues[ enumKey ] = enumVal

                        docItem = em.next.next.next.next.next

                        if isinstance( docItem, NavigableString ):
                            enumDocs[enumKey] = str(docItem).strip()
                        else:
                            enumDocs[enumKey] = str(docItem.contents[0]).strip()

                    #self.enums[self.currentMethod] = dict( [ (x,i) for i, x in enumerate(enumList) ] )
                    #self.pymelEnums[self.currentMethod] = dict( [ (x,i) for i, x in enumerate(pymelEnumList) ] )
                    pymelEnumList = self.getPymelEnums( enumValues )
                    for val, pyval in zip(enumValues,pymelEnumList):
                        enumDocs[pyval] = enumDocs[val]

                    enumInfo = {'values' : util.Enum(self.currentMethod, enumValues),
                                'valueDocs' : enumDocs,

                                  #'doc' : methodDoc
                                }

                    #print enumList

                    self.enums[self.currentMethod] = enumInfo
                    self.pymelEnums[self.currentMethod] = util.Enum(self.currentMethod, pymelEnumList)

                except AttributeError, msg:
                    _logger.error( "FAILED ENUM: %s", msg )

            # ARGUMENTS
            else:
                self.xprint( "RETURN", returnType)

                argInfo={}
                argList=[]
                defaults={}
                names=[]
                directions={}
                docs={}
                inArgs=[]
                outArgs=[]
                types ={}
                typeQualifiers={}
                methodDoc = ''
                deprecated = False

                # Static methods
                static = False
                try:
                    code = proto.findAll('code')[-1].string
                    if code and code.strip() == '[static]':
                        static = True
                except IndexError: pass

                tmpTypes=[]
                # TYPES
                for paramtype in proto.findAll( 'td', **{'class':'paramtype'} ) :
                    buf = []
                    [ buf.extend(x.split()) for x in paramtype.findAll( text=True ) ] #if x.strip() not in ['', '*', '&', 'const', 'unsigned'] ]
                    buf = [ str(x.strip()) for x in buf if x.strip() ]

                    i=0
                    for i, each in enumerate(buf):
                        if each not in [ '*', '&', 'const', 'unsigned']:
                            argtype = buf.pop(i)
                            break
                    else:
                        # We didn't find any arg type - therefore everything
                        # in buf is in the set('*', '&', 'const', 'unsigned')
                        # ... so it's implicitly an unsigned int
                        argtype = 'int'

                    if 'unsigned' in buf and argtype in ('char','int', 'int2',
                                                         'int3', 'int4'):
                        argtype = 'u' + argtype

                    argtype = self.handleEnums(argtype)

                    #print '\targtype', argtype, buf
                    tmpTypes.append( (argtype, buf) )

                # ARGUMENT NAMES
                i = 0
                for paramname in  proto.findAll( 'td', **{'class':'paramname'} )  :
                    buf = [ x.strip() for x in paramname.findAll( text=True ) if x.strip() not in['',','] ]
                    if buf:
                        argname = buf[0]
                        data = buf[1:]

                        type, qualifiers = tmpTypes[i]
                        default=None
                        joined = ''.join(data).strip()

                        if joined:
                            # break apart into index and defaults :  '[3] = NULL'
                            brackets, default = re.search( '([^=]*)(?:\s*=\s*(.*))?', joined ).groups()

                            if brackets:
                                numbuf = re.split( r'\[|\]', brackets)
                                if len(numbuf) > 1:
                                    # Note that these two args need to be cast differently:
                                    #   int2 foo;
                                    #   int bar[2];
                                    # ... so, instead of storing the type of both as
                                    # 'int2', we make the second one 'int__array2'
                                    type = type + '__array' + numbuf[1]
                                else:
                                    print "this is not a bracketed number", repr(brackets), joined

                            if default is not None:
                                try:
                                    # Constants
                                    default = {
                                        'true' : True,
                                        'false': False,
                                        'NULL' : None
                                    }[default]
                                except KeyError:
                                    try:
                                        if type in ['int', 'uint','long', 'uchar']:
                                            default = int(default)
                                        elif type in ['float', 'double']:
                                            # '1.0 / 24.0'
                                            if '/' in default:
                                                default = eval(default.encode('ascii', 'ignore'))
                                            # '1.0e-5F'  --> '1.0e-5'
                                            elif default.endswith('F'):
                                                default = float(default[:-1])
                                            else:
                                                default = float(default)
                                        else:
                                            default = self.handleEnumDefaults(default, type)
                                    except ValueError:
                                        default = self.handleEnumDefaults(default, type)
                                # default must be set here, because 'NULL' may be set to back to None, but this is in fact the value we want
                                self.xprint('DEFAULT', default)
                                defaults[argname] = default

                        types[argname] = type
                        typeQualifiers[argname] = qualifiers
                        names.append(argname)
                        i+=1

                try:
                    # ARGUMENT DIRECTION AND DOCUMENTATION
                    addendum = proto.findNextSiblings( 'div', limit=1)[0]
                    #try: self.xprint( addendum.findAll(text=True ) )
                    #except: pass

                    #if addendum.findAll( text = re.compile( '(This method is obsolete.)|(Deprecated:)') ):

                    if addendum.findAll( text=lambda x: x in self.OBSOLETE_MSG ):
                        self.xprint( "OBSOLETE" )
                        self.currentMethod = None
                        continue

                    #if self.currentMethod == 'createColorSet': raise NotImplementedError
                    if addendum.findAll( text=lambda x: x in self.DEPRECATED_MSG ):
                        self.xprint( "DEPRECATED" )
                        #print self.apiClassName + '.' + self.currentMethod + ':' + ' DEPRECATED'
                        deprecated = True

                    methodDoc = ' '.join( addendum.p.findAll( text=True ) )

                    tmpDirs = []
                    tmpNames = []
                    tmpDocs = []

                    #extraInfo = addendum.dl.table
                    extraInfos = addendum.findAll('table')

                    if extraInfos:
                        #print "NUMBER OF TABLES", len(extraInfos)
                        for extraInfo in extraInfos:
                            tmpDirs += extraInfo.findAll( text=lambda text: text in ['[in]', '[out]'] )

                            #tmpNames += [ em.findAll( text=True, limit=1 )[0] for em in extraInfo.findAll( 'em') ]
                            tmpNames = []
                            for tr in extraInfo.findAll( 'tr'):
                                assert tr, "could not find name tr"
                                em = tr.findNext( 'em' )
                                assert tr, "could not find name em"
                                name = em.findAll( text=True, limit=1 )[0]
                                tmpNames.append(name)

#                            for td in extraInfo.findAll( 'td' ):
#                                assert td, "could not find doc td"
#                                for doc in td.findAll( text=lambda text: text.strip(), recursive=False) :
#                                    if doc: tmpDocs.append( ''.join(doc) )

                            for doc in [td.findAll( text=lambda text: text.strip(), recursive=False) for td in extraInfo.findAll( 'td' )]:
                                if doc: tmpDocs.append( ''.join(doc) )

                        assert len(tmpDirs) == len(tmpNames) == len(tmpDocs), 'names and types lists are of unequal lengths: %s vs. %s vs. %s' % (tmpDirs, tmpNames, tmpDocs)
                        assert sorted(tmpNames) == sorted(typeQualifiers.keys()), 'name list mismatch %s %s' %  (sorted(tmpNames), sorted(typeQualifiers.keys()) )

                        #self.xprint(  sorted(tmpNames), sorted(typeQualifiers.keys()), sorted(typeQualifiers.keys()) )

                        for name, dir, doc in zip(tmpNames, tmpDirs, tmpDocs) :
                            if dir == '[in]':
                                # attempt to correct bad in/out docs
                                if re.search(r'\b([fF]ill|[sS]tor(age)|(ing))|([rR]esult)', doc ):
                                    _logger.warn( "%s.%s(%s): Correcting suspected output argument '%s' based on doc '%s'" % (
                                                                        self.apiClassName,self.currentMethod,', '.join(names), name, doc))
                                    dir = 'out'
                                elif not re.match( 'set[A-Z]', self.currentMethod) and '&' in typeQualifiers[name] and types[name] in ['int', 'double', 'float', 'uint', 'uchar']:
                                    _logger.warn( "%s.%s(%s): Correcting suspected output argument '%s' based on reference type '%s &' ('%s')'" % (
                                                                        self.apiClassName,self.currentMethod,', '.join(names), name, types[name], doc))
                                    dir = 'out'
                                else:
                                    dir = 'in'
                            elif dir == '[out]':
                                dir = 'out'
                            else: raise

                            assert name in names
                            directions[name] = dir
                            docs[name] = doc

                        # Documentation for Return Values
                        if returnType:
                            try:
                                returnDocBuf = addendum.findAll( 'dl', limit=1, **{'class':'return'} )[0].findAll( text=True )
                            except IndexError:
                                pass
                            else:
                                if returnDocBuf:
                                    returnDoc = ''.join( returnDocBuf[1:] ).strip('\n')
                                self.xprint(  'RETURN_DOC', repr(returnDoc)  )

                except (AttributeError, AssertionError), msg:
                    self.xprint( "FAILED", str(msg) )
                    pass

#                print names
#                print types
#                print defaults
#                print directions
#                print docs

                for argname in names[:] :
                    type = types[argname]
                    direction = directions.get(argname, 'in')
                    doc = docs.get( argname, '')

                    if type == 'MStatus':
                        types.pop(argname)
                        defaults.pop(argname,None)
                        directions.pop(argname,None)
                        docs.pop(argname,None)
                        idx = names.index(argname)
                        names.pop(idx)
                    else:
                        if direction == 'in':
                            inArgs.append(argname)
                        else:
                            outArgs.append(argname)
                        argInfo[ argname ] = {'type': type, 'doc': doc }

                # correct bad outputs
                if self.isGetMethod() and not returnType and not outArgs:
                    for argname in names:
                        if '&' in typeQualifiers[argname]:
                            doc = docs.get(argname, '')
                            directions[argname] = 'out'
                            idx = inArgs.index(argname)
                            inArgs.pop(idx)
                            outArgs.append(argname)

                            _logger.warn( "%s.%s(%s): Correcting suspected output argument '%s' because there are no outputs and the method is prefixed with 'get' ('%s')" % (
                                                                           self.apiClassName,self.currentMethod, ', '.join(names), argname, doc))

                # now that the directions are correct, make the argList
                for argname in names:
                    type = types[argname]
                    direction = directions.get(argname, 'in')
                    data = ( argname, type, direction)
                    if self.verbose: self.xprint( "ARG", data )
                    argList.append(  data )

                methodInfo = { 'argInfo': argInfo,
                              'returnInfo' : { 'type' : returnType, 'doc' : returnDoc },
                              'args' : argList,
                              'returnType' : returnType,
                              'inArgs' : inArgs,
                              'outArgs' : outArgs,
                              'doc' : methodDoc,
                              'defaults' : defaults,
                              #'directions' : directions,
                              'types' : types,
                              'static' : static,
                              'typeQualifiers' : typeQualifiers,
                              'deprecated' : deprecated }
                self.methods[self.currentMethod].append(methodInfo)

                # reset
                self.currentMethod=None

        pymelNames, invertibles = self.getPymelMethodNames()

        return { 'methods' : dict(self.methods),
                 'enums' : self.enums,
                 'pymelEnums' : self.pymelEnums,
                 'pymelMethods' :  pymelNames,
                 'invertibles' : invertibles
                }


text:
<?php

/**
 * The "mutes" collection of methods.
 * Typical usage is:
 *  <code>
 *   $reportcardService = new Google_Service_Reportcard(...);
 *   $mutes = $reportcardService->mutes;
 *  </code>
 */
class Google_Service_Reportcard_Resource_Mutes extends Google_Service_Resource
{
  /**
   * Deletes a Mute. (mutes.delete)
   *
   * @param string $mutesId The Mute id.
   * @param array $optParams Optional parameters.
   */
  public function delete($mutesId, $optParams = array())
  {
    $params = array('mutesId' => $mutesId);
    $params = array_merge($params, $optParams);
    return $this->call('delete', array($params));
  }
  /**
   * Gets a Mute by id. (mutes.get)
   *
   * @param string $mutesId The Mute id.
   * @param array $optParams Optional parameters.
   * @return Google_Service_Reportcard_Mute
   */
  public function get($mutesId, $optParams = array())
  {
    $params = array('mutesId' => $mutesId);
    $params = array_merge($params, $optParams);
    return $this->call('get', array($params), "Google_Service_Reportcard_Mute");
  }
  /**
   * Inserts a new Mute. (mutes.insert)
   *
   * @param Google_Service_Reportcard_Mute $postBody
   * @param array $optParams Optional parameters.
   * @return Google_Service_Reportcard_Mute
   */
  public function insert(Google_Service_Reportcard_Mute $postBody, $optParams = array())
  {
    $params = array('postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('insert', array($params), "Google_Service_Reportcard_Mute");
  }
  /**
   * Returns a list of Mutes, maybe filtering by 'consumer' or 'groupKey',
   * 'sourceKey' and 'supplier'. (mutes.listMutes)
   *
   * @param array $optParams Optional parameters.
   *
   * @opt_param string consumer Only return Mutes for this consumer
   * @opt_param string groupKey Only return Mutes created with this group_key.
   * Supplier and source_key must also be set.
   * @opt_param string sourceKey Only return Mutes created with this source_key.
   * Supplier must also be set.
   * @opt_param string supplier Only return Mutes created by this supplier.
   * @return Google_Service_Reportcard_MutesListResponse
   */
  public function listMutes($optParams = array())
  {
    $params = array();
    $params = array_merge($params, $optParams);
    return $this->call('list', array($params), "Google_Service_Reportcard_MutesListResponse");
  }
  /**
   * Updates an existing Mute. This method supports patch semantics. (mutes.patch)
   *
   * @param string $mutesId The Mute id.
   * @param Google_Service_Reportcard_Mute $postBody
   * @param array $optParams Optional parameters.
   * @return Google_Service_Reportcard_Mute
   */
  public function patch($mutesId, Google_Service_Reportcard_Mute $postBody, $optParams = array())
  {
    $params = array('mutesId' => $mutesId, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('patch', array($params), "Google_Service_Reportcard_Mute");
  }
  /**
   * Updates an existing Mute. (mutes.update)
   *
   * @param string $mutesId The Mute id.
   * @param Google_Service_Reportcard_Mute $postBody
   * @param array $optParams Optional parameters.
   * @return Google_Service_Reportcard_Mute
   */
  public function update($mutesId, Google_Service_Reportcard_Mute $postBody, $optParams = array())
  {
    $params = array('mutesId' => $mutesId, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('update', array($params), "Google_Service_Reportcard_Mute");
  }
}


text:
package ssse3

// go:noescape

// PABSBm128byte Packed Absolute Value Integers
func PABSBm128byte(X1 []byte, X2 []byte)

// go:noescape

// PABSBm128int8 Packed Absolute Value Integers
func PABSBm128int8(X1 []int8, X2 []int8)

// go:noescape

// PABSDm128byte Packed Absolute Value Integers
func PABSDm128byte(X1 []byte, X2 []byte)

// go:noescape

// PABSDm128int32 Packed Absolute Value Integers
func PABSDm128int32(X1 []int32, X2 []int32)

// go:noescape

// PABSWm128byte Packed Absolute Value Integers
func PABSWm128byte(X1 []byte, X2 []byte)

// go:noescape

// PABSWm128int16 Packed Absolute Value Integers
func PABSWm128int16(X1 []int16, X2 []int16)

// go:noescape

// PHADDDm128byte Packed Horizontal Add
func PHADDDm128byte(X1 []byte, X2 []byte)

// go:noescape

// PHADDSWm128byte Packed Horizontal Add and Saturate
func PHADDSWm128byte(X1 []byte, X2 []byte)

// go:noescape

// PHADDWm128byte Packed Horizontal Add
func PHADDWm128byte(X1 []byte, X2 []byte)

// go:noescape

// PHSUBDm128byte Packed Horizontal Subtract
func PHSUBDm128byte(X1 []byte, X2 []byte)

// go:noescape

// PHSUBSWm128byte Packed Horizontal Subtract and Saturate
func PHSUBSWm128byte(X1 []byte, X2 []byte)

// go:noescape

// PHSUBWm128byte Packed Horizontal Subtract
func PHSUBWm128byte(X1 []byte, X2 []byte)

// go:noescape

// PMADDUBSWm128byte Multiply and Add Packed Signed and Unsigned Bytes
func PMADDUBSWm128byte(X1 []byte, X2 []byte)

// go:noescape

// PMULHRSWm128byte Packed Multiply High with Round and Scale
func PMULHRSWm128byte(X1 []byte, X2 []byte)

// go:noescape

// PSHUFBm128byte Packed Shuffle Bytes
func PSHUFBm128byte(X1 []byte, X2 []byte)

// go:noescape

// PSIGNBm128byte Packed SIGN
func PSIGNBm128byte(X1 []byte, X2 []byte)

// go:noescape

// PSIGNDm128byte Packed SIGN
func PSIGNDm128byte(X1 []byte, X2 []byte)

// go:noescape

// PSIGNWm128byte Packed SIGN
func PSIGNWm128byte(X1 []byte, X2 []byte)


text:
import {
  NSPhoneEventEmitter,
  sms,
  dial,
  requestCallPermission,
  SMSEvents,
  DialEvents
} from 'nativescript-phone';
import { Observable } from '@nativescript/core';
const vm = new Observable();

vm.set('number', '800-555-5555');

NSPhoneEventEmitter.on(SMSEvents.FAILED, args => {
  console.log('FAILED', args.data);
});

NSPhoneEventEmitter.on(SMSEvents.SUCCESS, args => {
  console.log('SMS Successful');
});

NSPhoneEventEmitter.on(SMSEvents.CANCELLED, args => {
  console.log('SMS Cancelled');
});

NSPhoneEventEmitter.on(SMSEvents.ERROR, args => {
  console.log('SMS ERROR', args.data);
});

NSPhoneEventEmitter.on(SMSEvents.UNKNOWN, args => {
  console.log('SMS UNKNOWN', args.data);
});

// Event handler for Page "loaded" event attached in main-page.xml
export function pageLoaded(args) {
  const page = args.object;
  page.bindingContext = vm;
}

export function callNumber() {
  const number = vm.get('number');

  NSPhoneEventEmitter.once(DialEvents.FAILED, args => {
    console.log('Dial FAILED', args.data);
  });
  NSPhoneEventEmitter.once(DialEvents.ERROR, args => {
    console.log('Dial ERROR', args.data);
  });

  const dialResult = dial(number, true);
  console.log(`dialResult: ${dialResult}`);
}

export function callNumberWithoutPrompt() {
  const number = vm.get('number');

  NSPhoneEventEmitter.once(DialEvents.FAILED, args => {
    console.log('Dial FAILED', args.data);
  });
  NSPhoneEventEmitter.once(DialEvents.ERROR, args => {
    console.log('Dial ERROR', args.data);
  });

  const dialResult = dial(number, false);
  console.log(`dialResult: ${dialResult}`);
}

export function requestAndroidPerm() {
  try {
    requestCallPermission(
      'We need this permission to call the number without prompting user to confirm the number.'
    ).then(()=>console.log("OK"))
    .catch(err=> console.log(err));
  } catch (e) {
    console.log(e);
  }
}

export function textNumber() {
  const number = vm.get('number');

  sms([number], 'testing');
}


text:
using System;

class BonusScore
{
    static void Main()
    {
        Console.Write("Enter score of the student: ");
        int score = int.Parse(Console.ReadLine());

        if (score > 0 && score <= 3)
        {
            Console.WriteLine(score * 10);
        }
        else if (score > 3 && score <= 6)
        {
            Console.WriteLine(score * 100);
        }
        else if (score > 6 && score <= 9)
        {
            Console.WriteLine(score * 1000);
        }
        else if(score == 0 || score >= 9)
        {
            Console.WriteLine("Invalid score");
        }
    }
}


text:
function Human(name) {
  this.age = 0;
  this.name = name;
  this.init();
};

Human.prototype.init = function() {
  Iroh.log("Bearded drug addict with name", this.name, "created!");
  this.age = ((Math.random() * 1e3) + 1) | 0;
};

Human.prototype.shout = function() {
  Iroh.log("Hello, I'am", this.name);
};

let human = new Human("Gandalf");
let human2 = new Human("Gandalf");

Iroh.assert(
  "Correct prototype",
  Human.prototype.constructor.name === "Human"
);

Iroh.assert(
  "Instances have different addresses",
  human !== human2
);

Iroh.assert(
  "Correct constructor",
  Object.getPrototypeOf(human).constructor.name === "Human"
);

Iroh.assert(
  "Instantiated properties setted",
  human.hasOwnProperty("age") &&
  human.hasOwnProperty("name")
);

Iroh.assert(
  "This on instantiated Function",
  human.name === "Gandalf"
);

Iroh.assert(
  "Instantiated properties correctly filled",
  human.name === "Gandalf" &&
  human.age > 0
);


text:
"""Evaluates a TFGAN trained CIFAR model."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf

import data_provider
import networks
import util

flags = tf.flags
FLAGS = tf.flags.FLAGS
tfgan = tf.contrib.gan

flags.DEFINE_string('master', '', 'Name of the TensorFlow master to use.')

flags.DEFINE_string('checkpoint_dir', '/tmp/cifar10/',
                    'Directory where the model was written to.')

flags.DEFINE_string('eval_dir', '/tmp/cifar10/',
                    'Directory where the results are saved to.')

flags.DEFINE_string('dataset_dir', None, 'Location of data.')

flags.DEFINE_integer('num_images_generated', 100,
                     'Number of images to generate at once.')

flags.DEFINE_integer('num_inception_images', 10,
                     'The number of images to run through Inception at once.')

flags.DEFINE_boolean('eval_real_images', False,
                     'If `True`, run Inception network on real images.')

flags.DEFINE_boolean('conditional_eval', False,
                     'If `True`, set up a conditional GAN.')

flags.DEFINE_boolean('eval_frechet_inception_distance', True,
                     'If `True`, compute Frechet Inception distance using real '
                     'images and generated images.')

flags.DEFINE_integer('num_images_per_class', 10,
                     'When a conditional generator is used, this is the number '
                     'of images to display per class.')

flags.DEFINE_integer('max_number_of_evaluations', None,
                     'Number of times to run evaluation. If `None`, run '
                     'forever.')

flags.DEFINE_boolean('write_to_disk', True, 'If `True`, run images to disk.')

def main(_, run_eval_loop=True):
  # Fetch and generate images to run through Inception.
  with tf.name_scope('inputs'):
    real_data, num_classes = _get_real_data(
        FLAGS.num_images_generated, FLAGS.dataset_dir)
    generated_data = _get_generated_data(
        FLAGS.num_images_generated, FLAGS.conditional_eval, num_classes)

  # Compute Frechet Inception Distance.
  if FLAGS.eval_frechet_inception_distance:
    fid = util.get_frechet_inception_distance(
        real_data, generated_data, FLAGS.num_images_generated,
        FLAGS.num_inception_images)
    tf.summary.scalar('frechet_inception_distance', fid)

  # Compute normal Inception scores.
  if FLAGS.eval_real_images:
    inc_score = util.get_inception_scores(
        real_data, FLAGS.num_images_generated, FLAGS.num_inception_images)
  else:
    inc_score = util.get_inception_scores(
        generated_data, FLAGS.num_images_generated, FLAGS.num_inception_images)
  tf.summary.scalar('inception_score', inc_score)

  # If conditional, display an image grid of difference classes.
  if FLAGS.conditional_eval and not FLAGS.eval_real_images:
    reshaped_imgs = util.get_image_grid(
        generated_data, FLAGS.num_images_generated, num_classes,
        FLAGS.num_images_per_class)
    tf.summary.image('generated_data', reshaped_imgs, max_outputs=1)

  # Create ops that write images to disk.
  image_write_ops = None
  if FLAGS.conditional_eval and FLAGS.write_to_disk:
    reshaped_imgs = util.get_image_grid(
        generated_data, FLAGS.num_images_generated, num_classes,
        FLAGS.num_images_per_class)
    uint8_images = data_provider.float_image_to_uint8(reshaped_imgs)
    image_write_ops = tf.write_file(
        '%s/%s'% (FLAGS.eval_dir, 'conditional_cifar10.png'),
        tf.image.encode_png(uint8_images[0]))
  else:
    if FLAGS.num_images_generated >= 100 and FLAGS.write_to_disk:
      reshaped_imgs = tfgan.eval.image_reshaper(
          generated_data[:100], num_cols=FLAGS.num_images_per_class)
      uint8_images = data_provider.float_image_to_uint8(reshaped_imgs)
      image_write_ops = tf.write_file(
          '%s/%s'% (FLAGS.eval_dir, 'unconditional_cifar10.png'),
          tf.image.encode_png(uint8_images[0]))

  # For unit testing, use `run_eval_loop=False`.
  if not run_eval_loop: return
  tf.contrib.training.evaluate_repeatedly(
      FLAGS.checkpoint_dir,
      master=FLAGS.master,
      hooks=[tf.contrib.training.SummaryAtEndHook(FLAGS.eval_dir),
             tf.contrib.training.StopAfterNEvalsHook(1)],
      eval_ops=image_write_ops,
      max_number_of_evaluations=FLAGS.max_number_of_evaluations)

def _get_real_data(num_images_generated, dataset_dir):
  """Get real images."""
  data, _, _, num_classes = data_provider.provide_data(
      num_images_generated, dataset_dir)
  return data, num_classes

def _get_generated_data(num_images_generated, conditional_eval, num_classes):
  """Get generated images."""
  noise = tf.random_normal([num_images_generated, 64])
  # If conditional, generate class-specific images.
  if conditional_eval:
    conditioning = util.get_generator_conditioning(
        num_images_generated, num_classes)
    generator_inputs = (noise, conditioning)
    generator_fn = networks.conditional_generator
  else:
    generator_inputs = noise
    generator_fn = networks.generator
  # In order for variables to load, use the same variable scope as in the
  # train job.
  with tf.variable_scope('Generator'):
    data = generator_fn(generator_inputs, is_training=False)

  return data

if __name__ == '__main__':
  tf.app.run()