text:
void function() {

  /**
   * Asserts that the displayed dialog is in the center of the screen.
   *
   * @param {HTMLDialogElement?} opt_dialog to check, or test default
   */
  function checkDialogCenter(opt_dialog) {
    var d = opt_dialog || dialog;
    var expectedTop = (window.innerHeight - d.offsetHeight) / 2;
    var expectedLeft = (window.innerWidth - d.offsetWidth) / 2;
    var rect = d.getBoundingClientRect();
    assert.closeTo(rect.top, expectedTop, 1, 'top should be nearby');
    assert.closeTo(rect.left, expectedLeft, 1, 'left should be nearby');
  }

  /**
   * Creates a fake KeyboardEvent.
   *
   * @param {number} keyCode to press
   * @param {string?} opt_type to use, default keydown
   * @return {!Event} event
   */
  function createKeyboardEvent(keyCode, opt_type) {
    var ev = document.createEvent('Events');
    ev.initEvent(opt_type || 'keydown', true, true);
    ev.keyCode = keyCode;
    ev.which = keyCode;
    return ev;
  }

  /**
   * Cleans up any passed DOM elements.
   *
   * @param {!Element} el to clean up
   * @return {!Element} the same element, for chaining
   */
  var cleanup = (function() {
    var e = [];
    teardown(function() {
      e.forEach(function(el) {
        try {
          el.close();  // try to close dialogs
        } catch (e) {}
        el.parentElement && el.parentElement.removeChild(el);
      });
      e = [];
    });

    return function(el) {
      e.push(el);
      return el;
    };
  })();

  /**
   * Creates a dialog for testing that will be cleaned up later.
   *
   * @param {string?} opt_content to be used as innerHTML
   */
  function createDialog(opt_content) {
    var dialog = document.createElement('dialog');
    dialog.innerHTML = opt_content || 'Dialog #' + (cleanup.length);
    document.body.appendChild(dialog);
    if (window.location.search == '?force') {
      dialogPolyfill.forceRegisterDialog(dialog);
    } else {
      dialogPolyfill.registerDialog(dialog);
    }
    return cleanup(dialog);
  }

  var dialog;  // global dialog for all tests
  setup(function() {
    dialog = createDialog('Default Dialog');
  });

  suite('basic', function() {
    test('show and close', function() {
      assert.isFalse(dialog.hasAttribute('open'));
      dialog.show();
      assert.isTrue(dialog.hasAttribute('open'));
      assert.isTrue(dialog.open);

      var returnValue = 1234;
      dialog.close(returnValue);
      assert.isFalse(dialog.hasAttribute('open'));
      assert.equal(dialog.returnValue, returnValue);

      dialog.show();
      dialog.close();
      assert.isFalse(dialog.open);
      assert.equal(dialog.returnValue, returnValue);
    });
    test('open property', function() {
      assert.isFalse(dialog.hasAttribute('open'));
      dialog.show();
      assert.isTrue(dialog.hasAttribute('open'));
      assert.isTrue(dialog.open);

      dialog.open = false;
      assert.isFalse(dialog.open);
      assert.isFalse(dialog.hasAttribute('open'),
          'open property should clear attribute');
      assert.throws(dialog.close);

      var overlay = document.querySelector('._dialog_overlay');
      assert.isNull(overlay);
    });
    test('show/showModal interaction', function() {
      assert.isFalse(dialog.hasAttribute('open'));
      dialog.show();

      // If the native dialog is being tested, show/showModal are not already
      // bound, so wrap them in helper methods for throws/doesNotThrow.
      var show = function() { dialog.show(); };
      var showModal = function() { dialog.showModal(); };

      assert.doesNotThrow(show);
      assert.throws(showModal);

      dialog.open = false;
      assert.doesNotThrow(showModal);
      assert.doesNotThrow(show);  // show after showModal does nothing
      assert.throws(showModal);
      // TODO: check dialog is still modal

      assert.isTrue(dialog.open);
    });
    test('setAttribute reflects property', function() {
      dialog.setAttribute('open', '');
      assert.isTrue(dialog.open, 'attribute opens dialog');
    });
    test('changing open to dummy value is ignored', function() {
      dialog.showModal();

      dialog.setAttribute('open', 'dummy, ignored');
      assert.isTrue(dialog.open, 'dialog open with dummy open value');

      var overlay = document.querySelector('._dialog_overlay');
      assert(overlay, 'dialog is still modal');
    });
    test('show/showModal outside document', function() {
      dialog.open = false;
      dialog.parentNode.removeChild(dialog);

      assert.throws(function() { dialog.showModal(); });

      assert.doesNotThrow(function() { dialog.show(); });
      assert.isTrue(dialog.open, 'can open non-modal outside document');
      assert.isFalse(document.body.contains(dialog));
    });
    test('has a11y property', function() {
      assert.equal(dialog.getAttribute('role'), 'dialog', 'role should be dialog');
    });
  });

  suite('DOM', function() {
    setup(function(done) {
      // DOM tests wait for modal to settle, so MutationOberver doesn't coalesce attr changes
      dialog.showModal();
      window.setTimeout(done, 0);
    });
    test('DOM direct removal', function(done) {
      assert.isTrue(dialog.open);
      assert.isNotNull(document.querySelector('.backdrop'));

      var parentNode = dialog.parentNode;
      parentNode.removeChild(dialog);

      // DOMNodeRemoved defers its task a frame (since it occurs before removal, not after). This
      // doesn't effect MutationObserver, just delays the test a frame.
      window.setTimeout(function() {
        assert.isNull(document.querySelector('.backdrop'), 'dialog removal should clear modal');

        assert.isTrue(dialog.open, 'removed dialog should still be open');
        parentNode.appendChild(dialog);

        assert.isTrue(dialog.open, 're-added dialog should still be open');
        assert.isNull(document.querySelector('.backdrop'), 're-add dialog should not be modal');

        done();
      }, 0);
    });
    test('DOM removal inside other element', function(done) {
      var div = cleanup(document.createElement('div'));
      document.body.appendChild(div);
      div.appendChild(dialog);

      document.body.removeChild(div);

      window.setTimeout(function() {
        assert.isNull(document.querySelector('.backdrop'), 'dialog removal should clear modal');
        assert.isTrue(dialog.open, 'removed dialog should still be open');
        done();
      }, 0);
    });
    test('DOM instant remove/add', function(done) {
      var div = cleanup(document.createElement('div'));
      document.body.appendChild(div);
      dialog.parentNode.removeChild(dialog);
      div.appendChild(dialog);

      window.setTimeout(function() {
        assert.isNull(document.querySelector('.backdrop'), 'backdrop should disappear');
        assert.isTrue(dialog.open);
        done();
      }, 0);
    });
  });

  suite('position', function() {
    test('non-modal is not centered', function() {
      var el = cleanup(document.createElement('div'));
      dialog.parentNode.insertBefore(el, dialog);
      var testRect = el.getBoundingClientRect();

      dialog.show();
      var rect = dialog.getBoundingClientRect();

      assert.equal(rect.top, testRect.top, 'dialog should not be centered');
    });
    test('default modal centering', function() {
      dialog.showModal();
      checkDialogCenter();
      assert.ok(dialog.style.top, 'expected top to be set');
      dialog.close();
      assert.notOk(dialog.style.top, 'expected top to be cleared');
    });
    test('modal respects static position', function() {
      dialog.style.top = '10px';
      dialog.showModal();

      var rect = dialog.getBoundingClientRect();
      assert.equal(rect.top, 10);
    });
    test('modal recentering', function() {
      var pX = document.body.scrollLeft;
      var pY = document.body.scrollTop;
      var big = cleanup(document.createElement('div'));
      big.style.height = '200vh';  // 2x view height
      document.body.appendChild(big);

      try {
        var scrollValue = 200;  // don't use incredibly large values
        dialog.showModal();
        dialog.close();

        window.scrollTo(0, scrollValue);
        dialog.showModal();
        checkDialogCenter();  // must be centered, even after scroll
        var rectAtScroll = dialog.getBoundingClientRect();

        // after scroll, we aren't recentered, check offset
        window.scrollTo(0, 0);
        var rect = dialog.getBoundingClientRect();
        assert.closeTo(rectAtScroll.top + scrollValue, rect.top, 1);
      } finally {
        window.scrollTo(pX, pY);
      }
    });
    test('clamped to top of page', function() {
      var big = cleanup(document.createElement('div'));
      big.style.height = '200vh';  // 2x view height
      document.body.appendChild(big);
      document.documentElement.scrollTop = document.documentElement.scrollHeight / 2;

      dialog.style.height = document.documentElement.scrollHeight + 200 + 'px';
      dialog.showModal();

      var visibleRect = dialog.getBoundingClientRect();
      assert.equal(visibleRect.top, 0, 'large dialog should be visible at top of page');

      var style = window.getComputedStyle(dialog);
      assert.equal(style.top, document.documentElement.scrollTop + 'px',
          'large dialog should be absolutely positioned at scroll top');
    });
  });

  suite('backdrop', function() {
    test('backdrop div on modal', function() {
      dialog.showModal();
      var foundBackdrop = document.querySelector('.backdrop');
      assert.isNotNull(foundBackdrop);

      var sibling = dialog.nextElementSibling;
      assert.strictEqual(foundBackdrop, sibling);
    });
    test('no backdrop on non-modal', function() {
      dialog.show();
      assert.isNull(document.querySelector('.backdrop'));
      dialog.close();
    });
    test('backdrop click appears as dialog', function() {
      dialog.showModal();
      var backdrop = dialog.nextElementSibling;

      var clickFired = 0;
      var helper = function(ev) {
        assert.equal(ev.target, dialog);
        ++clickFired;
      };

      dialog.addEventListener('click', helper)
      backdrop.click();
      assert.equal(clickFired, 1);
    });
    test('backdrop click focuses dialog', function() {
      dialog.showModal();
      dialog.tabIndex = 0;

      var input = document.createElement('input');
      input.type = 'text';
      dialog.appendChild(input);

      // TODO: It would be nice to check `input` instead here, but there's no more reliable ways
      // to emulate a browser tab event (Firefox, Chrome etc have made it a security violation).

      var backdrop = dialog.nextElementSibling;
      backdrop.click();
      assert.equal(document.activeElement, dialog);
    });
  });

  suite('form focus', function() {
    test('non-modal inside modal is focusable', function() {
      var sub = createDialog();
      dialog.appendChild(sub);

      var input = document.createElement('input');
      input.type = 'text';
      sub.appendChild(input);

      dialog.showModal();
      sub.show();

      // trick Safari into allowing focus
      input.offsetLeft;
      input.focus();
      input.offsetLeft;

      assert.equal(input, document.activeElement);
    });
    test('clear focus when nothing focusable in modal', function() {
      var input = cleanup(document.createElement('input'));
      input.type = 'text';
      document.body.appendChild(input);
      input.focus();

      var previous = document.activeElement;
      dialog.showModal();
      assert.notEqual(previous, document.activeElement);
    });
    test('default focus on modal', function() {
      var input = cleanup(document.createElement('input'));
      input.type = 'text';
      dialog.appendChild(input);

      var anotherInput = cleanup(document.createElement('input'));
      anotherInput.type = 'text';
      dialog.appendChild(anotherInput);

      dialog.showModal();
      assert.equal(document.activeElement, input);
    });
    test('default focus on non-modal', function() {
      var div = cleanup(document.createElement('div'));
      div.tabIndex = 4;
      dialog.appendChild(div);

      dialog.show();
      assert.equal(document.activeElement, div);
    });
    test('autofocus element chosen', function() {
      var input = cleanup(document.createElement('input'));
      input.type = 'text';
      dialog.appendChild(input);

      var inputAF = cleanup(document.createElement('input'));
      inputAF.type = 'text';
      inputAF.autofocus = true;
      dialog.appendChild(inputAF);

      dialog.showModal();
      assert.equal(document.activeElement, inputAF);
    });
    test('child modal dialog', function() {
      dialog.showModal();

      var input = cleanup(document.createElement('input'));
      input.type = 'text';
      dialog.appendChild(input);
      input.focus();
      assert.equal(document.activeElement, input);

      // NOTE: This is a single sub-test, but all the above tests could be run
      // again in a sub-context (i.e., dialog within dialog).
      var child = createDialog();
      child.showModal();
      assert.notEqual(document.activeElement, input,
          'additional modal dialog should clear parent focus');

      child.close();
      assert.notEqual(document.activeElement, input,
          'parent focus should not be restored');
    });
    test('don\'t scroll anything into focus', function() {
      // https://github.com/GoogleChrome/dialog-polyfill/issues/119

      var div = cleanup(document.createElement('div'));
      document.body.appendChild(div);

      var inner = document.createElement('div');
      inner.style.height = '10000px';
      div.appendChild(inner);

      div.appendChild(dialog);

      var input = cleanup(document.createElement('input'));
      input.type = 'text';
      dialog.appendChild(input);

      var prev = document.documentElement.scrollTop;
      dialog.showModal();
      assert.equal(document.documentElement.scrollTop, prev);
    });
  });

  suite('top layer / inert', function() {
    test('background focus allowed on non-modal', function() {
      var input = cleanup(document.createElement('input'));
      input.type = 'text';
      document.body.appendChild(input);
      input.focus();

      dialog.show();
      assert.notEqual(document.activeElement, input,
        'non-modal dialog should clear focus, even with no dialog content');

      document.body.focus();
      input.focus();
      assert.equal(document.activeElement, input,
          'non-modal should allow background focus');
    });
    test('modal disallows background focus', function() {
      var input = cleanup(document.createElement('input'));
      input.type = 'text';
      document.body.appendChild(input);

      dialog.showModal();
      input.focus();

      if (!document.hasFocus()) {
        // Browsers won't trigger a focus event if they're not in the
        // foreground, so we can't intercept it. However, they'll fire one when
        // restored, before a user can get to any incorrectly focused element.
        console.warn('background focus test requires document focus');
        document.documentElement.focus();
      }
      assert.notEqual(document.activeElement, input,
          'modal should disallow background focus');
    });
    test('overlay is a sibling of topmost dialog', function() {
      var stacking = cleanup(document.createElement('div'));
      stacking.style.opacity = 0.8;  // creates stacking context
      document.body.appendChild(stacking);
      stacking.appendChild(dialog);
      dialog.showModal();

      var overlay = document.querySelector('._dialog_overlay');
      assert.isNotNull(overlay);
      assert.equal(overlay.parentNode, dialog.parentNode);
    });
    test('overlay is between topmost and remaining dialogs', function() {
      dialog.showModal();

      var other = cleanup(createDialog());
      document.body.appendChild(other);
      other.showModal();

      var overlay = document.querySelector('._dialog_overlay');
      assert.isNotNull(overlay);
      assert.equal(overlay.parentNode, other.parentNode);

      assert.isAbove(+other.style.zIndex, +overlay.style.zIndex, 'top-most dialog above overlay');
      assert.isAbove(+overlay.style.zIndex, +dialog.style.zIndex, 'overlay above other dialogs');
    });
  });

  suite('events', function() {
    test('close event', function() {
      var closeFired = 0;
      dialog.addEventListener('close', function() {
        ++closeFired;
      });

      dialog.show();
      assert.equal(closeFired, 0);

      dialog.close();
      assert.equal(closeFired, 1);

      assert.throws(dialog.close);  // can't close already closed dialog
      assert.equal(closeFired, 1);

      dialog.showModal();
      dialog.close();
      assert.equal(closeFired, 2);
    });
    test('cancel event', function() {
      dialog.showModal();
      dialog.dispatchEvent(createKeyboardEvent(27));
      assert.isFalse(dialog.open, 'esc should close modal');

      var cancelFired = 0;
      dialog.addEventListener('cancel', function() {
        ++cancelFired;
      });
      dialog.showModal();
      dialog.dispatchEvent(createKeyboardEvent(27));
      assert.equal(cancelFired, 1, 'expected cancel to be fired');
      assert.isFalse(dialog.open, 'esc should close modal again');

      // Sanity-check that non-modals aren't effected.
      dialog.show();
      dialog.dispatchEvent(createKeyboardEvent(27));
      assert.isTrue(dialog.open, 'esc should only close modal dialog');
      assert.equal(cancelFired, 1);
    });
    test('cancel event via oncancel', function() {
      dialog.showModal();

      var cancelFired = 0;
      dialog.oncancel = function(event) {
        ++cancelFired;
        event.preventDefault();
      };

      dialog.dispatchEvent(createKeyboardEvent(27));
      assert.equal(cancelFired, 1, 'expected cancel to be fired');
      assert.isTrue(dialog.open, 'behavior should be prevented');
    });
    test('overlay click is prevented', function() {
      dialog.showModal();

      var overlay = document.querySelector('._dialog_overlay');
      assert.isNotNull(overlay);

      var helper = function(ev) {
        throw Error('body should not be clicked');
      };
      try {
        document.body.addEventListener('click', helper);
        overlay.click();
      } finally {
        document.body.removeEventListener('click', helper);
      }
    });
  });

  suite('form', function() {
    test('method attribute is translated to property', function() {
      var form = document.createElement('form');
      form.method = 'dialog';
      assert.equal(form.method, 'dialog');

      form.method = 'PoSt';
      assert.equal(form.method, 'post');
      assert.equal(form.getAttribute('method'), 'PoSt');
    });
    test('dialog method input', function() {
      var value = 'ExpectedValue' + Math.random();

      var form = document.createElement('form');
      try {
        form.method = 'dialog';
      } catch (e) {
        // Setting the method directly throws an exception in <=IE9.
        form.setAttribute('method', 'dialog');
      }
      dialog.appendChild(form);

      var input = document.createElement('input');
      input.type = 'submit';
      input.value = value;
      form.appendChild(input);

      var closeCount = 0;
      dialog.addEventListener('close', function() {
        ++closeCount;
      });

      dialog.show();
      input.focus();  // emulate user focus action
      input.click();

      assert.isFalse(dialog.open);
      assert.equal(dialog.returnValue, value);
      assert.equal(closeCount, 1);
    });
    test('dialog with form submit preventDefault does not trigger close', function() {
      var form = document.createElement('form');
      form.setAttribute('method', 'dialog');
      dialog.appendChild(form);

      var input = document.createElement('input');
      input.type = 'submit';
      input.value = 'Does not matter';
      form.appendChild(input);

      form.addEventListener('submit', function(ev) {
        ev.preventDefault();
      });

      dialog.showModal();
      form.dispatchEvent(new Event('submit', { cancelable: true, bubbles: true }));

      assert.isTrue(dialog.open, 'dialog should remain open');
      assert.equal(dialog.returnValue, '');
    });
    test('dialog with button preventDefault does not trigger submit', function() {
      var form = document.createElement('form');
      form.setAttribute('method', 'dialog');
      dialog.appendChild(form);

      var button = document.createElement('button');
      button.value = 'does not matter';
      form.appendChild(button);
      button.addEventListener('click', function(ev) {
        ev.preventDefault();
      });

      dialog.showModal();
      button.click();

      assert.isTrue(dialog.open, 'dialog should remain open');
      assert.equal(dialog.returnValue, '');
    });
    test('dialog programmatic submit does not change returnValue', function() {
      var form = document.createElement('form');
      form.setAttribute('method', 'dialog');

      dialog.returnValue = 'manually set';  // set before appending
      dialog.appendChild(form);

      dialog.showModal();
      form.submit();
      assert.isFalse(dialog.open);

      assert.equal(dialog.returnValue, 'manually set', 'returnValue should not change');
    });
    test('dialog method button', function() {
      var value = 'ExpectedValue' + Math.random();

      var form = document.createElement('form');
      form.setAttribute('method', 'dialog');
      dialog.appendChild(form);

      var button = document.createElement('button');
      button.value = value;
      form.appendChild(button);

      dialog.showModal();
      button.focus();  // emulate user focus action
      button.click();

      assert.isFalse(dialog.open);
      assert.equal(dialog.returnValue, value);

      // Clear button value, confirm textContent is not used as value.
      button.value = 'blah blah';
      button.removeAttribute('value');
      button.textContent = value;
      dialog.show();
      button.focus();  // emulate user focus action
      button.click();

      assert.equal(dialog.returnValue, button.value,
          'don\'t take button textContent as value');
    });
    test('boring form inside dialog', function() {
      var form = document.createElement('form');
      dialog.appendChild(form);  // don't specify method
      form.addEventListener('submit', function(ev) {
        ev.preventDefault();
      });

      var button = document.createElement('button');
      button.value = 'Moot';
      form.appendChild(button);

      dialog.showModal();
      button.focus();  // emulate user focus action
      button.click();

      assert.isTrue(dialog.open, 'non-dialog form should not close dialog')
      assert(!dialog.returnValue);
    });
    test('type="image" submitter', function() {
      var form = document.createElement('form');
      form.setAttribute('method', 'dialog');
      dialog.appendChild(form);
      dialog.show();

      var image = document.createElement('input');
      image.type = 'image';
      image.src = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
      image.setAttribute('value', 'image should not accept value');
      form.appendChild(image);
      image.click();

      assert.notEqual(image.getAttribute('value'), dialog.returnValue);
      assert.equal(dialog.returnValue, '0,0');
    });
    test('form submitter across dialogs', function() {
      var form1 = document.createElement('form');
      form1.setAttribute('method', 'dialog');
      dialog.appendChild(form1);

      var button1 = document.createElement('button');
      button1.value = 'from form1: first value';
      form1.appendChild(button1);
      dialog.showModal();

      var dialog2 = createDialog();
      dialog2.returnValue = 'dialog2 default close value';
      var form2 = document.createElement('form');
      form2.setAttribute('method', 'dialog');
      dialog2.appendChild(form2);
      dialog2.showModal();

      button1.click();
      assert.isFalse(dialog.open);

      // nb. this never fires 'submit' so the .returnValue can't be wrong: is there another way
      // to submit a form that doesn't involve a click (enter implicitly 'clicks') or submit?
      form2.submit();
      assert.isFalse(dialog2.open);

      assert.equal(dialog2.returnValue, 'dialog2 default close value',
          'second dialog shouldn\'t reuse formSubmitter');
    });
    test('form submit inside SD', function(done) {
      if (!window.ShadowRoot) {
        return;
      }
      const iframeName = 'iframe_secret_blah';

      var holder = document.createElement('div');
      document.body.append(holder);
      cleanup(holder);

      var root = holder.attachShadow({mode: 'open'});
      var rootHolder = document.createElement('div');
      root.append(rootHolder);
      rootHolder.append(dialog);

      var iframe = document.createElement('iframe');
      iframe.setAttribute('name', iframeName);
      document.body.append(iframe);
      cleanup(iframe);

      var form = document.createElement('form');
      form.setAttribute('method', 'dialog');
      form.setAttribute('target', iframeName);
      form.setAttribute('action', '/test-invalid.html');
      dialog.append(form);

      var button = document.createElement('button');
      button.value = 'from form1: first value';
      form.append(button);
      dialog.showModal();

      iframe.addEventListener('load', function() {
        var href = iframe.contentWindow.location.href;
        if (href !== 'about:blank') {
          assert.fail('should not load a new page: ' + href);
        }
      });
      button.click();

      window.setTimeout(function() {
        assert.isFalse(dialog.open, 'dialog should be closed by button');
        if (iframe.contentWindow && iframe.contentWindow.location) {
          assert.notStrictEqual(iframe.contentWindow.location.pathname, '/test-invalid.html');
        }
        done();
      }, 50);
    });
    test('form submit with formmethod', function(done) {
      const iframeName = 'formmethod_test_frame';

      var iframe = document.createElement('iframe');
      iframe.setAttribute('name', iframeName);
      document.body.append(iframe);
      cleanup(iframe);

      var form = document.createElement('form');
      form.setAttribute('method', 'dialog');
      form.setAttribute('target', iframeName);
      form.setAttribute('action', '/test-invalid.html');
      dialog.append(form);
      dialog.show();

      var button = document.createElement('button');
      button.setAttribute('formmethod', 'get');
      form.append(button);
      button.value = '123';
      button.textContent = 'Long button';

      var timeout = window.setTimeout(function() {
        assert.fail('page should load (form submit with formmethod)');
      }, 500);
      iframe.addEventListener('load', function() {
        window.clearTimeout(timeout);
        assert.isTrue(dialog.open);
        done();
      });
      button.click();
    });
    test('form method="dialog" prevented outside dialog', function(done) {
      const iframeName = 'outside_dialog_test';

      var iframe = document.createElement('iframe');
      iframe.setAttribute('name', iframeName);
      document.body.append(iframe);
      cleanup(iframe);

      var form = document.createElement('form');
      form.setAttribute('method', 'dialog');
      form.setAttribute('target', iframeName);
      form.setAttribute('action', '/test-invalid.html');
      document.body.append(form);
      cleanup(form);

      iframe.addEventListener('load', function() {
        if (iframe.contentWindow.location.href !== 'about:blank') {
          assert.fail('should not load a new page: ' + iframe.contentWindow.location.href);
        }
      });

      form.submit();

      // Try with an actual button, too.
      var button = document.createElement('button');
      form.append(button);
      button.click();

      var timeout = window.setTimeout(function() {
        done();
      }, 1000);
    });
  });

  suite('order', function() {
    test('non-modal unchanged', function() {
      var one = createDialog();
      var two = createDialog();

      one.style.zIndex = 100;
      two.style.zIndex = 200;
      one.show();
      two.show();

      assert.equal(window.getComputedStyle(one).zIndex, 100);
      assert.equal(window.getComputedStyle(two).zIndex, 200);

      two.close();
      assert.equal(window.getComputedStyle(two).zIndex, 200);
    });
    test('modal stacking order', function() {
      dialog.showModal();

      // Create incorrectly-named dialogs: front has a lower z-index, and back
      // has a higher z-index.
      var front = createDialog();
      var back = createDialog();
      front.style.zIndex = 100;
      back.style.zIndex = 200;

      // Show back first, then front. Thus we expect back to be behind front.
      back.showModal();
      front.showModal();

      var zf = +window.getComputedStyle(front).zIndex;
      var zb = +window.getComputedStyle(back).zIndex;
      assert.isAbove(zf, zb, 'showModal order dictates z-index');

      var backBackdrop = back.nextElementSibling;
      var zbb = +window.getComputedStyle(backBackdrop).zIndex;
      assert.equal(backBackdrop.className, 'backdrop');
      assert.isBelow(zbb, zb, 'backdrop below dialog');

      var frontBackdrop = front.nextElementSibling;
      var zfb = +window.getComputedStyle(frontBackdrop).zIndex
      assert.equal(frontBackdrop.className, 'backdrop');
      assert.isBelow(zfb, zf,' backdrop below dialog');

      assert.isAbove(zfb, zb, 'front backdrop is above back dialog');

      front.close();
      assert.notOk(front.style.zIndex, 'modal close should clear zindex');
    });
  });

  suite('press tab key', function() {
    test('tab key', function() {
      var dialog = createDialog();
      dialog.showModal();

      document.documentElement.dispatchEvent(createKeyboardEvent(9));

      var ev = document.createEvent('Events');
      ev.initEvent('focus', true, true);
      document.documentElement.dispatchEvent(ev);

      dialog.close();
    });
  });
}();


text:
'''Generate configuration files for decoding via Kaldi.

The input directory (wavdir) should contain 16-bit 8KHz wav files,
with the naming convention <spk_id>_<utt_id>.wav.
For example: 0001_0001.wav, 0002_0001.wav etc.
'''

import sys
import os
from glob import glob

def get_filepaths(directory):
    '''This function will generate the file names in a directory
    tree by walking the tree either top-down or bottom-up. For each
    directory in the tree rooted at directory top (including top itself),
    it yields a 3-tuple (dirpath, dirnames, filenames).
    '''
    file_paths = []  # List which will store all of the full filepaths.
    # Walk the tree.
    for root, directories, files in os.walk(directory):
        for filename in files:
            # Join the two strings in order to form the full filepath.
            filepath = os.path.join(root, filename)
            if filepath.endswith('.wav') or filepath.endswith('.flac'):
                file_paths.append(filepath)  # Add it to the list.
    return file_paths  # Self-explanatory.

def get_wavscp(wavs):
    out = {}
    for path in wavs:
        _, wav = os.path.split(path)
        wav = wav.strip('.wav')
        out[wav] = path
    return out

def get_spk2utt(wavscp):
    out = {}
    for wav in wavscp.keys():
        spk, utt = wav.split('_')
        if spk in out:
            out[spk].append(wav)
        else:
            out[spk] = [wav]
    return out

def get_utt2spk(spk2utt):
    out = {}
    for spk, utts in spk2utt.iteritems():
        for utt in utts:
            out[utt] = spk
    return out

def write_scp(dirname, filename, data):
    f = open(os.path.join(dirname, filename), 'w')
    for key, val in iter(sorted(data.iteritems())):
        if type(val) == list:
            val = ' '.join(sorted(val))
        f.write("%s %s\n" % (key, val))

def filegen(wavdir, outdir):
    '''Generate wav.scp, spk2utt, utt2spk using wav files.
    Args:
        wavdir -- Path to directory having the wav files
        outdir -- Path to directory where the config files will be written
    '''
    wavs = get_filepaths(wavdir)
    wavscp = get_wavscp(wavs)
    # print wavscp
    write_scp(outdir, 'wav.scp', wavscp)
    spk2utt = get_spk2utt(wavscp)
    # print spk2utt
    write_scp(outdir, 'spk2utt', spk2utt)
    utt2spk = get_utt2spk(spk2utt)
    # print utt2spk
    write_scp(outdir, 'utt2spk', utt2spk)

def main():
    if (len(sys.argv) < 3):
        print "Usage: %s <wavdir> <outdir>" % (sys.argv[0])
        exit(1)
    wavdir = sys.argv[1]
    outdir = sys.argv[2]
    filegen(wavdir, outdir)

if __name__ == '__main__':
    main()

redpajama_set_name: RedPajamaGithub


text:
/* iFuseLib.c - The misc lib functions for the iRODS/Fuse server.
 */

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>
#include <assert.h>
#include "irodsFs.hpp"
#include "iFuseLib.hpp"
#include "iFuseOper.hpp"
#include "hashtable.hpp"
#include "list.hpp"

/* some global variables */

rodsEnv MyRodsEnv;

static specialPath_t SpecialPath[] = {
    {"/tls", 4},
    {"/i686", 5},
    {"/sse2", 5},
    {"/lib", 4},
    {"/librt.so.1", 11},
    {"/libacl.so.1", 12},
    {"/libselinux.so.1", 16},
    {"/libc.so.6", 10},
    {"/libpthread.so.0", 16},
    {"/libattr.so.1", 13},
};

static int NumSpecialPath = sizeof( SpecialPath ) / sizeof( specialPath_t );

int
isSpecialPath( char *inPath ) {
    int len;
    char *endPtr;
    int i;

    if ( inPath == NULL ) {
        rodsLog( LOG_ERROR,
                 "isSpecialPath: input inPath is NULL" );
        return ( SYS_INTERNAL_NULL_INPUT_ERR );
    }

    len = strlen( inPath );
    endPtr = inPath + len;
    for ( i = 0; i < NumSpecialPath; i++ ) {
        if ( len < SpecialPath[i].len ) { continue; }
        if ( strcmp( SpecialPath[i].path, endPtr - SpecialPath[i].len ) == 0 ) {
            return ( 1 );
        }
    }
    return 0;
}

int
ifusePut( rcComm_t *conn, char *objPath, char *cachePath, int mode,
          rodsLong_t srcSize ) {
    dataObjInp_t dataObjInp;
    int status;

    memset( &dataObjInp, 0, sizeof( dataObjInp ) );
    rstrcpy( dataObjInp.objPath, objPath, MAX_NAME_LEN );
    dataObjInp.dataSize = srcSize;
    dataObjInp.createMode = mode;
    dataObjInp.openFlags = O_RDWR;
    addKeyVal( &dataObjInp.condInput, FORCE_FLAG_KW, "" );
    addKeyVal( &dataObjInp.condInput, DATA_TYPE_KW, "generic" );
    if ( strlen( MyRodsEnv.rodsDefResource ) > 0 ) {
        addKeyVal( &dataObjInp.condInput, DEST_RESC_NAME_KW,
                   MyRodsEnv.rodsDefResource );
    }

    status = rcDataObjPut( conn, &dataObjInp, cachePath );
    return ( status );
}

int
closeIrodsFd( rcComm_t *conn, int fd ) {
    int status;

    openedDataObjInp_t dataObjCloseInp;

    bzero( &dataObjCloseInp, sizeof( dataObjCloseInp ) );
    dataObjCloseInp.l1descInx = fd;
    status = rcDataObjClose( conn, &dataObjCloseInp );
    return ( status );
}

int
fillFileStat( struct stat *stbuf, uint mode, rodsLong_t size, uint ctime,
              uint mtime, uint atime ) {
    if ( mode >= 0100 ) {
        stbuf->st_mode = S_IFREG | mode;
    }
    else {
        stbuf->st_mode = S_IFREG | DEF_FILE_MODE;
    }
    stbuf->st_size = size;

    stbuf->st_blksize = FILE_BLOCK_SZ;
    stbuf->st_blocks = ( stbuf->st_size / FILE_BLOCK_SZ ) + 1;

    stbuf->st_nlink = 1;
    stbuf->st_ino = random();
    stbuf->st_ctime = ctime;
    stbuf->st_mtime = mtime;
    stbuf->st_atime = atime;
    stbuf->st_uid = getuid();
    stbuf->st_gid = getgid();

    return 0;
}

int
fillDirStat( struct stat *stbuf, uint ctime, uint mtime, uint atime ) {
    stbuf->st_mode = S_IFDIR | DEF_DIR_MODE;
    stbuf->st_size = DIR_SZ;

    stbuf->st_nlink = 2;
    stbuf->st_ino = random();
    stbuf->st_ctime = ctime;
    stbuf->st_mtime = mtime;
    stbuf->st_atime = atime;
    stbuf->st_uid = getuid();
    stbuf->st_gid = getgid();

    return 0;
}

/* need to call getIFuseConn before calling irodsMknodWithCache */
int
irodsMknodWithCache( char *path, mode_t mode, char *cachePath ) {
    int status;
    int fd;

    if ( ( status = getFileCachePath( path, cachePath ) ) < 0 ) {
        return status;
    }

    /* fd = creat (cachePath, mode); WRONLY */
    fd = open( cachePath, O_CREAT | O_EXCL | O_RDWR, mode );
    if ( fd < 0 ) {
        rodsLog( LOG_ERROR,
                 "irodsMknodWithCache: local cache creat error for %s, errno = %d",
                 cachePath, errno );
        return( errno ? ( -1 * errno ) : -1 );
    }
    else {
        return fd;
    }
}

/* need to call getIFuseConn before calling irodsOpenWithReadCache */

int
dataObjCreateByFusePath( rcComm_t *conn, char *path, int mode,
                         char *irodsPath ) {
    dataObjInp_t dataObjInp;
    int status;

    memset( &dataObjInp, 0, sizeof( dataObjInp ) );
    rstrcpy( dataObjInp.objPath, irodsPath, MAX_NAME_LEN );

    if ( strlen( MyRodsEnv.rodsDefResource ) > 0 ) {
        addKeyVal( &dataObjInp.condInput, RESC_NAME_KW,
                   MyRodsEnv.rodsDefResource );
    }

    addKeyVal( &dataObjInp.condInput, DATA_TYPE_KW, "generic" );
    /* dataObjInp.createMode = DEF_FILE_CREATE_MODE; */
    dataObjInp.createMode = mode;
    dataObjInp.openFlags = O_RDWR;
    dataObjInp.dataSize = -1;

    status = rcDataObjCreate( conn, &dataObjInp );
    clearKeyVal( &dataObjInp.condInput );

    return status;
}

int
renmeLocalPath( char *from, char *to, char *toIrodsPath ) {
    pathCache_t *fromPathCache = NULL;
    pathCache_t *tmpPathCache = NULL;

    /* do not check existing path here as path cache may be out of date */
    matchAndLockPathCache( from, &fromPathCache );
    if ( fromPathCache == NULL ) {
        return 0;
    }

    LOCK( PathCacheLock );
    if ( fromPathCache->fileCache != NULL ) {
        LOCK_STRUCT( *( fromPathCache->fileCache ) );
        free( fromPathCache->fileCache->localPath );
        fromPathCache->fileCache->localPath = strdup( to );
        free( fromPathCache->fileCache->objPath );
        fromPathCache->fileCache->objPath = strdup( toIrodsPath );

        _pathReplace( ( char * ) to, fromPathCache->fileCache, &fromPathCache->stbuf, &tmpPathCache );

        UNLOCK_STRUCT( *( fromPathCache->fileCache ) );
    }
    else {
        _pathReplace( ( char * ) to, NULL /* fromPathCache->fileCache */, &fromPathCache->stbuf, &tmpPathCache );

    }

    /* need to unlock fileCache here since the following function call ness to lock fileCache */
    _pathNotExist( ( char * ) from );

    UNLOCK_STRUCT( *fromPathCache );
    UNLOCK( PathCacheLock );
    return 0;
}


text:
/**
 * Class for Default Constants of the Module
 */
export class Config {
    public static getConfig() {
        return new Config();
    }

    public baseUrl = 'http://localhost:3000';
    public loginMethod = 'POST';
    public loginUrl = '/login';
    public loginEventName = 'oauth2:login';
    public loginEventFailureName = 'oauth2:login:error';
    public signupMethod = 'POST';
    public signupUrl = '/signup';
    public logoutMethod = 'POST';
    public logoutUrl = '/logout';
    public logoutEventName = 'oauth2:logout';
    public logoutFailureEventName = 'oauth2:logout:error';
    public storageType = 'localStorage';
    public tokenName = 'AccessToken';
    public refreshTokenName = 'RefreshToken';
    public refreshTokenUrl = '/refresh';
    public tokenHeader = 'Authorization';
    public tokenType = 'Bearer';
    public tokenErrorEventName = 'oauth2:token:error';

    public providers = {
        facebook: {
            name: 'facebook',
            url: '/auth/facebook',
            authorizationEndpoint: 'https://www.facebook.com/v2.5/dialog/oauth',
            redirectUri: window.location.origin + '/',
            requiredUrlParams: ['display', 'scope', 'app_id', 'redirect_uri'],
            responseParams: ['code'],
            scope: ['email'],
            scopeDelimiter: ',',
            display: 'popup',
            oauthType: '2.0',
            popupOptions: { width: 580, height: 400 }
        },
        google: {
            name: 'google',
            url: '/auth/google',
            authorizationEndpoint: 'https://accounts.google.com/o/oauth2/auth',
            redirectUri: window.location.origin,
            requiredUrlParams: ['scope', 'response_type'],
            optionalUrlParams: ['display', 'state', 'client_id', 'redirect_uri'],
            responseParams: ['code'],
            scope: ['profile', 'email'],
            scopePrefix: 'openid',
            scopeDelimiter: ' ',
            display: 'popup',
            oauthType: '2.0',
            responseType: 'token',
            popupOptions: { width: 452, height: 633 }
        }
    };
}


text:
/* ******************************
 * Copyleft 2014 Verbalsaint
 * ******************************/

#ifndef _LOADSO_HPP
#define _LOADSO_HPP
#include <dl_interface.hpp>
#include <typehelper.hpp>

#include "dl_include.hpp"

/*
 * TODO create shared_ptr, unique_ptr interface.
 * while refcnt == 0; the passed in class Deleter template argument type
 * will dedicate the resource clean up to loaded library.
 */

namespace vsd {
namespace dl {

using namespace vsd::type_helper;

using checksum_type = decltype(std::declval<boost::crc_32_type>().checksum());

class LoadSo final
{
   /*
    * declare type and variable in front of class as a cautious design.
    */
private:
   using Handler_Type = void *;
   using Key = checksum_type; //chksum of .so binary file
   using CreateObjects = std::vector<DLObject*>;
   using Content = std::pair<Handler_Type, CreateObjects>;
   using ModuleMap = std::unordered_map<Key, Content>;

private:
   enum {DEFAULT_OBJECTS = 5};
   enum class CLEANUP {NOPURGE, PURGE};
   // TODO use implemented hopscotch later
   ModuleMap moduleMap_;
   const char* getModule{"GetModule"};
   const char* deleteModule{"DeleteModule"};

private:
   /*
    * no need mutable, all mem_fn are non-const
    */
   std::mutex loadSoMutex_;

public:
   /**
    * id : [in] Key to register, this is checksum of so file
    */
   auto RegisterModule(const Key& id/*checksum of so file*/, std::string soname) ->bool;

   /**
    * Load module with module's checksum, can passin arguments to library's
    * createobj's function
    */
   template<typename RetFuncType, typename... Args>
   DLObject* GetObject(
      const Key&,
      Args...);

   void DeleteObject(
      const Key&,
      std::initializer_list<std::reference_wrapper<DLObject*>> olist);

   void DeleteObject(
      const Key&,
      DLObject*&);

   auto UnregisterModule(const Key& id) ->bool;

private:
   void DeleteObject(
      ModuleMap::iterator Result_Iter,
      std::initializer_list<std::reference_wrapper<DLObject*>> olist,
                            CLEANUP = CLEANUP::NOPURGE);

   auto dlopen(const Key& id, const char*)->bool;

   auto dlclose(void *)->bool;
};

auto LoadSo::RegisterModule(
   const Key& id,
   std::string soname) ->bool
{
   return dlopen(id, soname.c_str());
}

template<
   typename RetFuncType,
   typename... Args>
DLObject* LoadSo::GetObject(
   const Key& id,
   Args... args)
{

   std::lock_guard<std::mutex> lock(loadSoMutex_);

   auto Result_Iter = moduleMap_.find(id);

   if (Result_Iter == moduleMap_.end())
   {
      return nullptr;
   }
   else
   {
      /*
       * Support only return pointer to func that is used to create
       * plugin's internal object
       */
      static_assert(
         boost::mpl::eval_if<
            std::is_pointer<RetFuncType>,
            std::is_function<remove_pointer_t<RetFuncType>>,
            boost::mpl::false_>::type::value,
         "[static_assert] RetFuncType should be a pointer to funtion type");

      RetFuncType rft;

      *reinterpret_cast<void **>(&rft) = ::dlsym((*Result_Iter).second.first, getModule);

      if (rft == nullptr)
      {
         return nullptr;
      }

      auto createObject = (*rft)()(args...);

      (*Result_Iter).second.second.push_back(createObject);
      std::cout << "createid :" << createObject << std::endl;

      return createObject;
   }
}

void LoadSo::DeleteObject(
   const Key& id,
   std::initializer_list<std::reference_wrapper<DLObject*>> olist)
{

   std::lock_guard<std::mutex> lock(loadSoMutex_);
   auto Result_Iter = moduleMap_.find(id);

   if (Result_Iter == moduleMap_.end())
   {
      return;
   }
   else
   {
      DeleteObject(Result_Iter, olist);
   }
}

void LoadSo::DeleteObject(
   const Key& id,
   DLObject*& obj)
{
   DeleteObject(
      id,
      /*std::initializer_list<std::reference_wrapper<DLObject*>>{std::ref(obj)} );*/
      std::initializer_list<std::reference_wrapper<DLObject*>>{obj} );
}

void LoadSo::DeleteObject(
    ModuleMap::iterator Result_Iter,
    std::initializer_list<std::reference_wrapper<DLObject*>> olist, CLEANUP cleanup)
{

   DeleteModuleFunc_Type rft;

   *reinterpret_cast<void **>(&rft) = ::dlsym((*Result_Iter).second.first, deleteModule);

   if(rft == nullptr)
   {
      //TODO throw can not free resource
   }

   auto& objects = (*Result_Iter).second.second;

   switch(cleanup)
   {
      case CLEANUP::NOPURGE:
         for(auto o : olist)
         {
            objects.erase(
               std::remove(objects.begin(), objects.end(), o.get()),
               objects.end());

            (*rft)(o.get());

            o.get() = nullptr;
         }
         break;

      case CLEANUP::PURGE:
         for(auto o : objects)
         {
            (*rft)(o);
            o = nullptr;
         }
         break;
   }
}

auto LoadSo::UnregisterModule(
      const Key& id) -> bool
{
   std::lock_guard<std::mutex> lock(loadSoMutex_);
   auto Result_Iter = moduleMap_.find(id);

   if (Result_Iter == moduleMap_.end())
   {
      return false;
   }
   else
   {
      // delete all objects create by this module
      DeleteObject(Result_Iter, {}, CLEANUP::PURGE);

      if (dlclose(Result_Iter->second.first))
      {
         /*
          * Will throw if compare object throw
          */
         try
         {
            if (moduleMap_.erase(id) == 1)
            {
               return true;
            }
            else
            {
               return false;
            }
         }
         catch(...)
         {
            return false;
         }
      }
      else return false;
   }
}

auto LoadSo::dlopen(
   const Key& id,
   const char* soname) ->bool
{
   /*
    * prevent reloading, dlopen maintains a ref count.
    */
   std::lock_guard<std::mutex> lock(loadSoMutex_);

   if ( moduleMap_.find(id) != moduleMap_.end() )
   {
      return true;
   }

   Handler_Type ht = ::dlopen(soname , RTLD_LAZY | RTLD_LOCAL /*| RTLD_DEEPBIND*/);

   if (ht == nullptr)
   {
      // TODO throw
      std::cout << ::dlerror() << std::endl;
      return false;
   }
   else
   {
      CreateObjects objectList;
      objectList.reserve(DEFAULT_OBJECTS);

      return moduleMap_.insert(
            std::make_pair(id, std::make_pair(ht, std::move(objectList)))).second;
   }
}

auto LoadSo::dlclose(void *handle) -> bool
{
   int erret = ::dlclose(handle);

   if (erret == 0)
   {
      return true;
   }
   else
   {
      //debug
      std::cout << "[debug] " << ::dlerror() << std::endl;
      return false;
   }
}

}} // vsd::dl

#endif // for #ifndef _LOADSO_HPP


text:
import veritable
import veritable.utils
import json
import sys

TABLE_NAME = 'movielens'

'''
Perform analysis on the given data file and and schema, creating the
table first if needed and uploading the data.
'''
def main(data_file, schema_file):
    rows = json.loads(open(data_file).read())
    schema = json.loads(open(schema_file).read())

    api = veritable.connect()

    if not api.table_exists(TABLE_NAME):
        print 'Creating table'
        table = api.create_table(TABLE_NAME)
    else:
        print 'Getting table'
        table = api.get_table(TABLE_NAME)

    print 'Uploading rows'
    table.batch_upload_rows(rows)
    print 'Creating analysis'
    analysis = table.create_analysis(schema)

if __name__ == '__main__':
    main(sys.argv[1], sys.argv[2])


text:
package com.github.zion;

import static org.eclipse.egit.github.core.RepositoryId.createFromUrl;
import android.content.Intent;

import java.io.Serializable;
import java.util.ArrayList;

import org.eclipse.egit.github.core.Gist;
import org.eclipse.egit.github.core.GistFile;
import org.eclipse.egit.github.core.Issue;
import org.eclipse.egit.github.core.Repository;
import org.eclipse.egit.github.core.RepositoryId;
import org.eclipse.egit.github.core.User;

/**
 * Helper for creating intents
 */
public class Intents {

    /**
     * Prefix for all intents created
     */
    public static final String INTENT_PREFIX = "jp.forkhub.mobile.";

    /**
     * Prefix for all extra data added to intents
     */
    public static final String INTENT_EXTRA_PREFIX = INTENT_PREFIX + "extra.";

    /**
     * Repository handle
     */
    public static final String EXTRA_REPOSITORY = INTENT_EXTRA_PREFIX
            + "REPOSITORY";

    /**
     * Repository ids collection handle
     */
    public static final String EXTRA_REPOSITORIES = INTENT_EXTRA_PREFIX
            + "REPOSITORIES";

    /**
     * Repository name
     */
    public static final String EXTRA_REPOSITORY_NAME = INTENT_EXTRA_PREFIX
            + "REPOSITORY_NAME";

    /**
     * Repository owner
     */
    public static final String EXTRA_REPOSITORY_OWNER = INTENT_EXTRA_PREFIX
            + "REPOSITORY_OWNER";

    /**
     * Issue number
     */
    public static final String EXTRA_ISSUE_NUMBER = INTENT_EXTRA_PREFIX
            + "ISSUE_NUMBER";

    /**
     * Issue handle
     */
    public static final String EXTRA_ISSUE = INTENT_EXTRA_PREFIX + "ISSUE";

    /**
     * Issue number collection handle
     */
    public static final String EXTRA_ISSUE_NUMBERS = INTENT_EXTRA_PREFIX
            + "ISSUE_NUMBERS";

    /**
     * Gist id
     */
    public static final String EXTRA_GIST_ID = INTENT_EXTRA_PREFIX + "GIST_ID";

    /**
     * List of Gist ids
     */
    public static final String EXTRA_GIST_IDS = INTENT_EXTRA_PREFIX
            + "GIST_IDS";

    /**
     * Gist handle
     */
    public static final String EXTRA_GIST = INTENT_EXTRA_PREFIX + "GIST";

    /**
     * Gist file handle
     */
    public static final String EXTRA_GIST_FILE = INTENT_EXTRA_PREFIX
            + "GIST_FILE";

    /**
     * User handle
     */
    public static final String EXTRA_USER = INTENT_EXTRA_PREFIX + "USER";

    /**
     * {@link ArrayList} handle of {@link User} objects
     */
    public static final String EXTRA_USERS = INTENT_EXTRA_PREFIX + "USERS";

    /**
     * Boolean value which indicates if a user is a collaborator on the repo
     */
    public static final String EXTRA_IS_COLLABORATOR = INTENT_EXTRA_PREFIX + "IS_COLLABORATOR";

    /**
     * Issue filter handle
     */
    public static final String EXTRA_ISSUE_FILTER = INTENT_EXTRA_PREFIX
            + "ISSUE_FILTER";

    /**
     * Comment body
     */
    public static final String EXTRA_COMMENT_BODY = INTENT_EXTRA_PREFIX
            + "COMMENT_BODY";

    /**
     * Comments handle
     */
    public static final String EXTRA_COMMENTS = INTENT_EXTRA_PREFIX
            + "COMMENTS";

    /**
     * Comment handle
     */
    public static final String EXTRA_COMMENT = INTENT_EXTRA_PREFIX + "COMMENT";

    /**
     * Integer position
     */
    public static final String EXTRA_POSITION = INTENT_EXTRA_PREFIX
            + "POSITION";

    /**
     * Base commit name
     */
    public static final String EXTRA_BASE = INTENT_EXTRA_PREFIX + "BASE";

    /**
     * Base commit names
     */
    public static final String EXTRA_BASES = INTENT_EXTRA_PREFIX + "BASES";

    /**
     * Base commit name
     */
    public static final String EXTRA_HEAD = INTENT_EXTRA_PREFIX + "HEAD";

    /**
     * Handle to a {@link String} path
     */
    public static final String EXTRA_PATH = INTENT_EXTRA_PREFIX + "PATH";

    /**
     * Resolve the {@link RepositoryId} referenced by the given intent
     *
     * @param intent
     * @return repository id
     */
    public static RepositoryId repoFrom(Intent intent) {
        String repoName = intent.getStringExtra(EXTRA_REPOSITORY_NAME);
        String repoOwner = intent.getStringExtra(EXTRA_REPOSITORY_OWNER);
        return RepositoryId.create(repoOwner, repoName);
    }

    /**
     * Builder for generating an intent configured with extra data such as an
     * issue, repository, or gist
     */
    public static class Builder {

        private final Intent intent;

        /**
         * Create builder with suffix
         *
         * @param actionSuffix
         */
        public Builder(String actionSuffix) {
            // actionSuffix = e.g. "repos.VIEW"
            intent = new Intent(INTENT_PREFIX + actionSuffix);
        }

        /**
         * Add repository id to intent being built up
         *
         * @param repositoryId
         * @return this builder
         */
        public Builder repo(RepositoryId repositoryId) {
            return add(EXTRA_REPOSITORY_NAME, repositoryId.getName()).add(
                    EXTRA_REPOSITORY_OWNER, repositoryId.getOwner());
        }

        /**
         * Add repository to intent being built up
         *
         * @param repository
         * @return this builder
         */
        public Builder repo(Repository repository) {
            return add(EXTRA_REPOSITORY, repository);
        }

        /**
         * Add issue to intent being built up
         *
         * @param issue
         * @return this builder
         */
        public Builder issue(Issue issue) {
            return repo(createFromUrl(issue.getHtmlUrl())).add(EXTRA_ISSUE,
                    issue).add(EXTRA_ISSUE_NUMBER, issue.getNumber());
        }

        /**
         * Add gist to intent being built up
         *
         * @param gist
         * @return this builder
         */
        public Builder gist(Gist gist) {
            return add(EXTRA_GIST, gist);
        }

        /**
         * Add gist id to intent being built up
         *
         * @param gist
         * @return this builder
         */
        public Builder gist(String gist) {
            return add(EXTRA_GIST_ID, gist);
        }

        /**
         * Add gist file to intent being built up
         *
         * @param file
         * @return this builder
         */
        public Builder gistFile(GistFile file) {
            return add(EXTRA_GIST_FILE, file);
        }

        /**
         * Add user to intent being built up
         *
         * @param user
         * @return this builder;
         */
        public Builder user(User user) {
            return add(EXTRA_USER, user);
        }

        /**
         * Add extra field data value to intent being built up
         *
         * @param fieldName
         * @param value
         * @return this builder
         */
        public Builder add(String fieldName, String value) {
            intent.putExtra(fieldName, value);
            return this;
        }

        /**
         * Add extra field data values to intent being built up
         *
         * @param fieldName
         * @param values
         * @return this builder
         */
        public Builder add(String fieldName, CharSequence[] values) {
            intent.putExtra(fieldName, values);
            return this;
        }

        /**
         * Add extra field data value to intent being built up
         *
         * @param fieldName
         * @param value
         * @return this builder
         */
        public Builder add(String fieldName, int value) {
            intent.putExtra(fieldName, value);
            return this;
        }

        /**
         * Add extra field data value to intent being built up
         *
         * @param fieldName
         * @param values
         * @return this builder
         */
        public Builder add(String fieldName, int[] values) {
            intent.putExtra(fieldName, values);
            return this;
        }

        /**
         * Add extra field data value to intent being built up
         *
         * @param fieldName
         * @param values
         * @return this builder
         */
        public Builder add(String fieldName, boolean[] values) {
            intent.putExtra(fieldName, values);
            return this;
        }

        /**
         * Add extra field data value to intent being built up
         *
         * @param fieldName
         * @param value
         * @return this builder
         */
        public Builder add(String fieldName, Serializable value) {
            intent.putExtra(fieldName, value);
            return this;
        }

        /**
         * Get built intent
         *
         * @return intent
         */
        public Intent toIntent() {
            return intent;
        }
    }
}


text:
(function(){
	ex.ui.check = {};

	ex.ui.check.createWindow = function() {
		var win = Ti.UI.createWindow($.mixin({
			title: L("check_api"),
			layout: 'vertical'
		}, $$.window));

		var check = Ti.UI.createButton($.mixin({
			title: L("check")
		}, $$.button));
		check.addEventListener('click', function(){
			mixi.graphApi.share({
				parameters: {
					key: mixi.key,
					title: "いいね!タイトル",
					primary_url: mixi.primary_url,
					privacy: {visibility: "self"}
				},
				success: function(json){
					alert(json);
				}
			});
		});

		win.add(check);

		return win;
	};
})();


text:
var path          = require('path'),
    cp            = require('child-process-debug'),
    processHelper = require('./../process-helper.js'),
    log           = require('./../log'),
    _             = require('underscore'),
    colors        = require('colors'),
    glob          = require('glob'),
    fs            = require('fs-extra');

/**
 * Mocha Constructor
 *
 * @param {Object} options
 * @api public
 */

function Mocha (options) {
  this.options = options;
  this.mochaChild = null;
}

/**
 * Run Mocha specs
 *
 * @param {Function} callback
 * @api public
 */

Mocha.prototype.start = function (callback) {

  var self = this;
  if (glob.sync(self.options.path).length === 0) {
    log.info('[chimp][mocha] Directory', self.options.path, 'does not exist. Not running');
    callback();
    return;
  }

  log.debug('[chimp][mocha] Running...');

  var opts = {
    env: process.env,
    silent: true
  };

  var port;
  if (this.options.debugMocha) {
    port = parseInt(this.options.debugMocha);
    if (port > 1) {
      opts.execArgv = ['--debug=' + port];
    } else {
      opts.execArgv = ['--debug'];
    }
  }

  if (this.options.debugBrkMocha) {
    port = parseInt(this.options.debugBrkMocha);
    if (port > 1) {
      opts.execArgv = ['--debug-brk=' + port];
    } else {
      opts.execArgv = ['--debug-brk'];
    }
  }

  self.mochaChild = cp.fork(path.join(__dirname, 'mocha-wrapper.js'), [
    '--color'
  ], opts);

  self.mochaChild.stdout.pipe(process.stdout);
  self.mochaChild.stderr.pipe(process.stderr);

  var result = null;
  self.mochaChild.on('message', function (res) {
    log.debug('[chimp][mocha] Received message from Mocha child. Result:', res);
    result = res;
  });

  self.mochaChild.on('close', function (code) {
    log.debug('[chimp][mocha] Closed with code', code);
    if (!self.mochaChild.stopping) {
      log.debug('[chimp][mocha] Mocha not in a stopping state');
      callback(code !== 0 ? 'Mocha failed' : null, result);
    }
  });

};

Mocha.prototype.interrupt = function (callback) {

  log.debug('[chimp][mocha] interrupting mocha');

  var self = this;

  if (!self.mochaChild) {
    log.debug('[chimp][mocha] no child to interrupt');
    return callback();
  }
  self.mochaChild.stopping = true;

  var options = {
    child: self.mochaChild,
    prefix: 'mocha'
  };

  processHelper.kill(options, function (err, res) {
    self.mochaChild = null;
    if (callback) {
      callback(err, res);
    }
  });

};

module.exports = Mocha;


text:
package com.gls.framework.datasource;

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

public class DynamicDataSourceContextHolder {

    /**
     * 当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本, 所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。
     */
    private static final ThreadLocal<DynamicDataSourceType> contextHolder = new ThreadLocal<DynamicDataSourceType>();

    /**
     * 管理所有的数据源id; 主要是为了判断数据源是否存在;
     */
    private static List<DynamicDataSourceType> dynamicDataSourceTypes = new ArrayList<DynamicDataSourceType>();

    public static void addDataSourceType(DynamicDataSourceType dynamicDataSourceType) {
        dynamicDataSourceTypes.add(dynamicDataSourceType);
    }

    public static void clearDataSourceType() {
        contextHolder.remove();
    }

    /**
     * 判断指定DataSrouce当前是否存在
     *
     * @param dynamicDataSourceType
     * @return
     * @author SHANHY
     * @create 2016年1月24日
     */
    public static boolean containsDataSource(DynamicDataSourceType dynamicDataSourceType) {
        return dynamicDataSourceTypes.contains(dynamicDataSourceType);
    }

    public static DynamicDataSourceType getDataSourceType() {
        return contextHolder.get();
    }

    /**
     * 使用setDataSourceType设置当前的
     *
     * @param dynamicDataSourceType
     */
    public static void setDataSourceType(DynamicDataSourceType dynamicDataSourceType) {
        contextHolder.set(dynamicDataSourceType);
    }

}


text:
import ast
import sys

class _CatchDisplay(object):
    """Class to temporarily catch sys.displayhook"""
    def __init__(self):
        self.output = None

    def __enter__(self):
        self.old_hook = sys.displayhook
        sys.displayhook = self
        return self

    def __exit__(self, type, value, traceback):
        sys.displayhook = self.old_hook
        # Returning False will cause exceptions to propagate
        return False

    def __call__(self, output):
        self.output = output

def eval_block(code, namespace=None, filename='<string>'):
    """
    Execute a multi-line block of code in the given namespace

    If the final statement in the code is an expression, return
    the result of the expression.
    """
    tree = ast.parse(code, filename='<ast>', mode='exec')
    if namespace is None:
        namespace = {}
    catch_display = _CatchDisplay()

    if isinstance(tree.body[-1], ast.Expr):
        to_exec, to_eval = tree.body[:-1], tree.body[-1:]
    else:
        to_exec, to_eval = tree.body, []

    for node in to_exec:
        compiled = compile(ast.Module([node]),
                           filename=filename, mode='exec')
        exec(compiled, namespace)

    with catch_display:
        for node in to_eval:
            compiled = compile(ast.Interactive([node]),
                               filename=filename, mode='single')
            exec(compiled, namespace)

    return catch_display.output


text:
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :invitable, :database_authenticatable,
         :recoverable, :rememberable, :trackable, :validatable, :timeoutable, :async

  validates_presence_of :private_token
  validates_presence_of :email
  validates :email, presence: true, email: {strict_mode: true}, uniqueness: true

  has_and_belongs_to_many :roles
  has_one :profile, :dependent => :destroy
  has_many :projects, :dependent => :destroy
  has_many :builds, :through => :projects
  has_many :user_roles, :dependent => :destroy
  has_many :runners, :dependent => :destroy

  after_create :create_profile_default
  after_initialize :create_token_default

  has_paper_trail

  rails_admin do
    edit do
      field :email
      field :password
      field :password_confirmation
    end
    list do
      field :email
      field :profile
      field :stringify_roles do
        label "Roles"
      end
      field :projects_count
    end
  end

  class PrivateEntity < Grape::Entity
    expose :private_token
    expose :id
  end

  def add_role(abbr)
    role = Role.where(:abbr => abbr).first
    self.user_roles.create(:role_id => role.id) if role
  end

  def stringify_roles(sep = ',')
    self.roles.map{|r| r.name}.join(sep)
  end

  def projects_count
    self.projects.count
  end

  def self.required_profile_attributes
    ["gitlab_ci_url", "gitlab_private_token", "gitlab_url"]
  end

  def blank_required_profile_attributes
    self.profile.attributes.select{|k,v| v.blank?}.keys & self.class.required_profile_attributes
  end

  def avaiable_gitlab_ci_projects
    options = {:headers => {"Content-Type" => "application/json"}, :query => {:per_page => 10000, :private_token => self.profile.gitlab_private_token, :url => self.profile.gitlab_url}}
    endpoint = File.join(self.profile.base_gitlab_ci_api_url, 'projects')
    response = HTTParty.get(endpoint, options)

    if response.code == 200
      response.parsed_response
    else
      nil
    end
  end

  def has_imported_gitlab_ci_project?(gitlab_ci_project_id)
    Project.where(:gitlab_ci_id => gitlab_ci_project_id, :user_id => self.id).first
  end

  def has_role?(abbr)
    self.roles.where(abbr: abbr).count > 0
  end

  def self.authenticate_by_token(token, role_abbr = nil)
    user = User.where(:private_token => token).first
    return nil if user && role_abbr && !user.has_role?(role_abbr)
    user
  end

  private

  def create_token_default
    require 'securerandom'
    self.private_token ||= SecureRandom.hex
  end

  def create_profile_default
    self.create_profile({:gitlab_email => self.email}) unless self.profile
  end
end


text:
package org.onetwo.ext.poi.excel.generator;

import java.util.Iterator;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.onetwo.ext.poi.excel.data.RowContextData;
import org.onetwo.ext.poi.excel.exception.ExcelException;
import org.onetwo.ext.poi.excel.utils.ExcelUtils;

@SuppressWarnings("unchecked")
public class IteratorRowProcessor extends DefaultRowProcessor {

	private RowProcessor titleRowProcessor;

	public IteratorRowProcessor(PoiExcelGenerator excelGenerator, RowProcessor titleRowProcessor) {
		super(excelGenerator);
		this.titleRowProcessor = titleRowProcessor;
	}

	public void processRow(RowContextData rowContext) {

		if(rowContext.getRowModel().isRenderHeader()){
//			RowModel header = rowModel.copy();
//			header.setType(RowModel.Type.HEADER_KEY);
			this.titleRowProcessor.processRow(rowContext);
		}
		processIterator(rowContext);
	}

	@SuppressWarnings("rawtypes")
	public int processIterator(RowContextData rowContext) {
//		Sheet sheet = rowContext.getSheet();
		RowModel iterator = rowContext.getRowModel();

		Object dataSourceValue = rowContext.parseValue(iterator.getDatasource());
//		Object dataSourceValue = rowContext.getSheetDatas();
		Iterator it = ExcelUtils.convertIterator(dataSourceValue);
		if(it==null)
			return 0;

		int index = 0;
		Map context = rowContext.getSelfContext();
		String indexName = StringUtils.isBlank(iterator.getIndex())?"rowIndex":iterator.getIndex();

//		FieldProcessor fieldProcessor = getFieldProcessor(iterator, context);
		for (Object ele = null; it.hasNext(); index++) {
//			UtilTimerStack.push(iterator.getName());
			if(index%1000==0)
				logger.info("create row " + index);

//			String pname = "pre-field-"+index;
//			UtilTimerStack.push(pname);
			ele = it.next();
			rowContext.setCurrentRowObject(ele);
			Row row = createRow(rowContext);
			rowContext.setCurrentRow(row);

			if(context!=null){
				context.put(iterator.getName(), ele);
				context.put(indexName, index);
			}
//			UtilTimerStack.pop(pname);

			FieldModel field = null;
			try {
				for (int i = 0; i < iterator.size(); i++) {
//					String name = "field-"+i;
//					UtilTimerStack.push(name);
					field = iterator.getField(i);
					this.processField(getFieldRootValue(rowContext, field), rowContext, field);
//					UtilTimerStack.pop(name);
				}
			} catch (Exception e) {
				throw new ExcelException("generate field["+iterator.getTemplate().getLabel()+","+iterator.getName()+","+field.getName()+"] error: "+e.getMessage() , e);
			}finally{
				rowContext.setCurrentRow(null);
				rowContext.setCurrentRowObject(null);
				if(context!=null){
					context.remove(iterator.getName());
					context.remove(indexName);
				}
			}

//			UtilTimerStack.pop(iterator.getName());
		}
		int size = ExcelUtils.size(dataSourceValue);
		return size;
	}
}


text:
package com.amazonaws.services.cloudsearchv2.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.cloudsearchv2.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;

/**
 * DescribeDomainsRequest Marshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeDomainsRequestMarshaller implements Marshaller<Request<DescribeDomainsRequest>, DescribeDomainsRequest> {

    public Request<DescribeDomainsRequest> marshall(DescribeDomainsRequest describeDomainsRequest) {

        if (describeDomainsRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        Request<DescribeDomainsRequest> request = new DefaultRequest<DescribeDomainsRequest>(describeDomainsRequest, "AmazonCloudSearchv2");
        request.addParameter("Action", "DescribeDomains");
        request.addParameter("Version", "2013-01-01");
        request.setHttpMethod(HttpMethodName.POST);

        com.amazonaws.internal.SdkInternalList<String> domainNamesList = (com.amazonaws.internal.SdkInternalList<String>) describeDomainsRequest
                .getDomainNames();
        if (!domainNamesList.isEmpty() || !domainNamesList.isAutoConstruct()) {
            int domainNamesListIndex = 1;

            for (String domainNamesListValue : domainNamesList) {
                if (domainNamesListValue != null) {
                    request.addParameter("DomainNames.member." + domainNamesListIndex, StringUtils.fromString(domainNamesListValue));
                }
                domainNamesListIndex++;
            }
        }

        return request;
    }

}


text:
<?php
namespace Stathat;

/**
* Classic Stathat Client
*/
class ClassicClient implements StathatClientInterface
{
	const COUNT_API_URL = 'http://api.stathat.com/c';
	const VALUE_API_URL = 'http://api.stathat.com/v';

	protected $userKey;
	protected $httpClient;

	public function __construct($userKey, $httpClient)
	{
		$this->userKey = $userKey;
		$this->httpClient = $httpClient;
	}

	/**
	 * Make a count against a stat asynchronously
	 *
	 * @param  string 	$stat_name
	 * @param  int 		$count
	 * @param  string 	$accountId
	 * @return void
	 */
	public function count($stat_name, $count = 1, $accountId = '')
	{
		return $this->httpClient->doAsyncPostRequest(
			self::COUNT_API_URL,
			array(
				'key' 	=> $stat_name,
				'ukey' 	=> $this->getUserKey($accountId),
				'count' => $count
			)
		);
	}

	/**
	 * Log a value against a stat asynchronously
	 *
	 * @param  string 	$stat_name
	 * @param  int 		$value
	 * @param  string 	$accountId
	 * @return void
	 */
	public function value($stat_name, $value, $accountId = '')
	{
		$this->httpClient->doAsyncPostRequest(
			self::VALUE_API_URL,
			array(
				'key' => $stat_name,
				'ukey' => $this->getUserKey($accountId),
				'value' => $value
			)
		);
	}

	/**
	 * Make a count against a stat
	 *
	 * @param  string 	$stat_name
	 * @param  int 		$value
	 * @param  string 	$accountId
	 * @return void
	 */
	public function countSync($stat_name, $count = 1, $accountId = '')
	{
		$accountId = $this->getUserKey($accountId);

		return $this->httpClient->doPostRequest(
			self::COUNT_API_URL,
			"key=$stat_name&ukey=$accountId&count=$count"
		);
	}

	/**
	 * Log a value against a stat
	 *
	 * @param  string 	$stat_name
	 * @param  int 		$value
	 * @param  string 	$accountId
	 * @return void
	 */
	public function valueSync($stat_name, $value, $accountId = '')
	{
		$accountId = $this->getUserKey($accountId);

		return $this->httpClient->doPostRequest(
			self::VALUE_API_URL,
			"key=$stat_name&ukey=$accountId&value=$value"
		);
	}

	/**
	 * Return account's user key
	 *
	 * @param string $default
	 * @return string
	 */
	protected function getUserKey($default = null)
	{
		return ($default) ? $default : $this->userKey;
	}
}

?>


text:
package appfw

type Appfwprofilecontenttypebinding struct {
	Alertonly      string `json:"alertonly,omitempty"`
	Comment        string `json:"comment,omitempty"`
	Contenttype    string `json:"contenttype,omitempty"`
	Isautodeployed string `json:"isautodeployed,omitempty"`
	Name           string `json:"name,omitempty"`
	Resourceid     string `json:"resourceid,omitempty"`
	State          string `json:"state,omitempty"`
}


text:
inline static bool Do_Feed_To_End_Maybe_Stale_Throws(
    REBVAL *out,  // must be initialized, unchanged if all empty/invisible
    struct Reb_Feed *feed  // feed mechanics always call va_end() if va_list
){
    DECLARE_FRAME (f, feed, EVAL_MASK_DEFAULT);

    bool threw;
    Push_Frame(out, f);
    do {
        threw = (*PG_Eval_Maybe_Stale_Throws)(f);
    } while (not threw and NOT_END(feed->value));
    Drop_Frame(f);

    return threw;
}

inline static bool Do_Any_Array_At_Throws(
    REBVAL *out,
    const RELVAL *any_array,  // same as `out` is allowed
    REBSPC *specifier
){
    DECLARE_FEED_AT_CORE (feed, any_array, specifier);

    Init_Void(out);  // ^-- *after* feed initialization (if any_array == out)

    bool threw = Do_Feed_To_End_Maybe_Stale_Throws(out, feed);
    CLEAR_CELL_FLAG(out, OUT_MARKED_STALE);
    return threw;
}

// !!! When working with an array outside of the context of a REBVAL it was
// extracted from, then that means automatic determination of the CONST rules
// isn't possible.  This primitive is currently used in a few places where
// the desire is not to inherit any "wave of constness" from the parent's
// frame, or from a value.  The cases need review--in particular the use for
// the kind of shady frame translations used by HIJACK and ports.
//
inline static bool Do_At_Mutable_Maybe_Stale_Throws(
    REBVAL *out,
    const RELVAL *opt_first,  // optional element to inject *before* the array
    REBARR *array,
    REBCNT index,
    REBSPC *specifier  // must match array, but also opt_first if relative
){
    struct Reb_Feed feed_struct;  // opt_first so can't use DECLARE_ARRAY_FEED
    struct Reb_Feed *feed = &feed_struct;
    Prep_Array_Feed(
        feed,
        opt_first,
        array,
        index,
        specifier,
        FEED_MASK_DEFAULT  // different: does not
    );

    return Do_Feed_To_End_Maybe_Stale_Throws(out, feed);
}

inline static bool Do_At_Mutable_Throws(
    REBVAL *out,
    REBARR *array,
    REBCNT index,
    REBSPC *specifier
){
    Init_Void(out);

    bool threw = Do_At_Mutable_Maybe_Stale_Throws(
        out,
        nullptr,
        array,
        index,
        specifier
    );
    CLEAR_CELL_FLAG(out, OUT_MARKED_STALE);
    return threw;
}

// Takes a list of arguments terminated by an end marker and will do something
// similar to R3-Alpha's "apply/only" with a value.  If that value is a
// function, it will be called...if it's a SET-WORD! it will be assigned, etc.
//
// This is equivalent to putting the value at the head of the input and
// then calling EVAL/ONLY on it.  If all the inputs are not consumed, an
// error will be thrown.
//
inline static bool RunQ_Throws(
    REBVAL *out,
    bool fully,
    const void *p,  // last param before ... mentioned in va_start()
    ...
){
    va_list va;
    va_start(va, p);

    bool threw = Eval_Step_In_Va_Throws_Core(
        SET_END(out),  // start at END to detect error if no eval product
        FEED_MASK_DEFAULT | FLAG_QUOTING_BYTE(1),
        p,  // opt_first
        &va,  // va_end() handled by Eval_Va_Core on success/fail/throw
        EVAL_MASK_DEFAULT
            | (fully ? EVAL_FLAG_NO_RESIDUE : 0)
    );

    if (IS_END(out))
        fail ("Run_Throws() empty or just COMMENTs/ELIDEs/BAR!s");

    return threw;
}

// Conditional constructs allow branches that are either BLOCK!s or ACTION!s.
// If an action, the triggering condition is passed to it as an argument:
// https://trello.com/c/ay9rnjIe
//
// Allowing other values was deemed to do more harm than good:
// https://forum.rebol.info/t/backpedaling-on-non-block-branches/476
//
inline static bool Do_Branch_Core_Throws(
    REBVAL *out,
    const REBVAL *branch,
    const REBVAL *condition // can be END or nullptr--can't be a NULLED cell!
){
    assert(branch != out and condition != out);

    if (IS_QUOTED(branch)) {
        Unquotify(Move_Value(out, branch), 1);
        return false;
    }

    if (IS_BLOCK(branch))
        return Do_Any_Array_At_Throws(out, branch, SPECIFIED);

    assert(IS_ACTION(branch));
    return RunQ_Throws(
        out,
        false, // !fully, e.g. arity-0 functions can ignore condition
        rebU1(branch),
        condition, // may be an END marker, if not Do_Branch_With() case
        rebEND // ...but if condition wasn't an END marker, we need one
    );
}

#define Do_Branch_With_Throws(out,branch,condition) \
    Do_Branch_Core_Throws((out), (branch), NULLIFY_NULLED(condition))

#define Do_Branch_Throws(out,branch) \
    Do_Branch_Core_Throws((out), (branch), END_NODE)


text:
<?php
namespace Tsoha;

  class DB{

      public static function connection(){
        // Haetaan tietokantakonfiguraatio
        $connection_config = DatabaseConfig::connection_config();
        $config = $connection_config['config'];

        try {
            // Alustetaan PDO
            if(isset($config['username'])){
              $connection = new \PDO($config['resource'], $config['username'], $config['password']);
            }else{
              $connection = new \PDO($config['resource']);
            }

            // Asetetaan tietokannan kenttien koodaukseksi utf8
            $connection->exec("set names utf8");

        } catch (\PDOException $e) {
            die('Virhe tietokantayhteydessä: ' . $e->getMessage());
        }

        return $connection;
      }

      public static function test_connection(){
        require 'vendor/ConnectionTest/connection_test.php';

        exit();
      }

  }


text:
package etcdmain

import (
	"fmt"
	"os"
	"runtime"
	"strings"
	"time"

	"go.etcd.io/etcd/client/pkg/v3/fileutil"
	"go.etcd.io/etcd/client/pkg/v3/logutil"
	"go.etcd.io/etcd/client/pkg/v3/types"
	"go.etcd.io/etcd/pkg/v3/osutil"
	"go.etcd.io/etcd/server/v3/embed"
	"go.etcd.io/etcd/server/v3/etcdserver/api/v2discovery"
	"go.etcd.io/etcd/server/v3/etcdserver/errors"
	"go.uber.org/zap"
	"google.golang.org/grpc"
)

type dirType string

var (
	dirMember = dirType("member")
	dirProxy  = dirType("proxy")
	dirEmpty  = dirType("empty")
)

func startEtcdOrProxyV2(args []string) {
	grpc.EnableTracing = false

	cfg := newConfig()
	defaultInitialCluster := cfg.ec.InitialCluster

	err := cfg.parse(args[1:])
	lg := cfg.ec.GetLogger()
	// If we failed to parse the whole configuration, print the error using
	// preferably the resolved logger from the config,
	// but if does not exists, create a new temporary logger.
	if lg == nil {
		var zapError error
		// use this logger
		lg, zapError = logutil.CreateDefaultZapLogger(zap.InfoLevel)
		if zapError != nil {
			fmt.Printf("error creating zap logger %v", zapError)
			os.Exit(1)
		}
	}
	lg.Info("Running: ", zap.Strings("args", args))
	if err != nil {
		lg.Warn("failed to verify flags", zap.Error(err))
		switch err {
		case embed.ErrUnsetAdvertiseClientURLsFlag:
			lg.Warn("advertise client URLs are not set", zap.Error(err))
		}
		os.Exit(1)
	}

	cfg.ec.SetupGlobalLoggers()

	defer func() {
		logger := cfg.ec.GetLogger()
		if logger != nil {
			logger.Sync()
		}
	}()

	defaultHost, dhErr := (&cfg.ec).UpdateDefaultClusterFromName(defaultInitialCluster)
	if defaultHost != "" {
		lg.Info(
			"detected default host for advertise",
			zap.String("host", defaultHost),
		)
	}
	if dhErr != nil {
		lg.Info("failed to detect default host", zap.Error(dhErr))
	}

	if cfg.ec.Dir == "" {
		cfg.ec.Dir = fmt.Sprintf("%v.etcd", cfg.ec.Name)
		lg.Warn(
			"'data-dir' was empty; using default",
			zap.String("data-dir", cfg.ec.Dir),
		)
	}

	var stopped <-chan struct{}
	var errc <-chan error

	which := identifyDataDirOrDie(cfg.ec.GetLogger(), cfg.ec.Dir)
	if which != dirEmpty {
		lg.Info(
			"server has already been initialized",
			zap.String("data-dir", cfg.ec.Dir),
			zap.String("dir-type", string(which)),
		)
		switch which {
		case dirMember:
			stopped, errc, err = startEtcd(&cfg.ec)
		case dirProxy:
			lg.Panic("v2 http proxy has already been deprecated in 3.6", zap.String("dir-type", string(which)))
		default:
			lg.Panic(
				"unknown directory type",
				zap.String("dir-type", string(which)),
			)
		}
	} else {
		lg.Info(
			"Initialize and start etcd server",
			zap.String("data-dir", cfg.ec.Dir),
			zap.String("dir-type", string(which)),
		)
		stopped, errc, err = startEtcd(&cfg.ec)
	}

	if err != nil {
		if derr, ok := err.(*errors.DiscoveryError); ok {
			switch derr.Err {
			case v2discovery.ErrDuplicateID:
				lg.Warn(
					"member has been registered with discovery service",
					zap.String("name", cfg.ec.Name),
					zap.String("discovery-token", cfg.ec.Durl),
					zap.Error(derr.Err),
				)
				lg.Warn(
					"but could not find valid cluster configuration",
					zap.String("data-dir", cfg.ec.Dir),
				)
				lg.Warn("check data dir if previous bootstrap succeeded")
				lg.Warn("or use a new discovery token if previous bootstrap failed")

			case v2discovery.ErrDuplicateName:
				lg.Warn(
					"member with duplicated name has already been registered",
					zap.String("discovery-token", cfg.ec.Durl),
					zap.Error(derr.Err),
				)
				lg.Warn("cURL the discovery token URL for details")
				lg.Warn("do not reuse discovery token; generate a new one to bootstrap a cluster")

			default:
				lg.Warn(
					"failed to bootstrap; discovery token was already used",
					zap.String("discovery-token", cfg.ec.Durl),
					zap.Error(err),
				)
				lg.Warn("do not reuse discovery token; generate a new one to bootstrap a cluster")
			}
			os.Exit(1)
		}

		if strings.Contains(err.Error(), "include") && strings.Contains(err.Error(), "--initial-cluster") {
			lg.Warn("failed to start", zap.Error(err))
			if cfg.ec.InitialCluster == cfg.ec.InitialClusterFromName(cfg.ec.Name) {
				lg.Warn("forgot to set --initial-cluster?")
			}
			if types.URLs(cfg.ec.APUrls).String() == embed.DefaultInitialAdvertisePeerURLs {
				lg.Warn("forgot to set --initial-advertise-peer-urls?")
			}
			if cfg.ec.InitialCluster == cfg.ec.InitialClusterFromName(cfg.ec.Name) && len(cfg.ec.Durl) == 0 && len(cfg.ec.DiscoveryCfg.Endpoints) == 0 {
				lg.Warn("V2 discovery settings (i.e., --discovery) or v3 discovery settings (i.e., --discovery-token, --discovery-endpoints) are not set")
			}
			os.Exit(1)
		}
		lg.Fatal("discovery failed", zap.Error(err))
	}

	osutil.HandleInterrupts(lg)

	// At this point, the initialization of etcd is done.
	// The listeners are listening on the TCP ports and ready
	// for accepting connections. The etcd instance should be
	// joined with the cluster and ready to serve incoming
	// connections.
	notifySystemd(lg)

	select {
	case lerr := <-errc:
		// fatal out on listener errors
		lg.Fatal("listener failed", zap.Error(lerr))
	case <-stopped:
	}

	osutil.Exit(0)
}

// startEtcd runs StartEtcd in addition to hooks needed for standalone etcd.
func startEtcd(cfg *embed.Config) (<-chan struct{}, <-chan error, error) {
	e, err := embed.StartEtcd(cfg)
	if err != nil {
		return nil, nil, err
	}
	osutil.RegisterInterruptHandler(e.Close)
	select {
	case <-e.Server.ReadyNotify(): // wait for e.Server to join the cluster
	case <-e.Server.StopNotify(): // publish aborted from 'ErrStopped'
	case <-time.After(cfg.ExperimentalWaitClusterReadyTimeout):
		e.GetLogger().Warn("startEtcd: timed out waiting for the ready notification")
	}
	return e.Server.StopNotify(), e.Err(), nil
}

// identifyDataDirOrDie returns the type of the data dir.
// Dies if the datadir is invalid.
func identifyDataDirOrDie(lg *zap.Logger, dir string) dirType {
	names, err := fileutil.ReadDir(dir)
	if err != nil {
		if os.IsNotExist(err) {
			return dirEmpty
		}
		lg.Fatal("failed to list data directory", zap.String("dir", dir), zap.Error(err))
	}

	var m, p bool
	for _, name := range names {
		switch dirType(name) {
		case dirMember:
			m = true
		case dirProxy:
			p = true
		default:
			lg.Warn(
				"found invalid file under data directory",
				zap.String("filename", name),
				zap.String("data-dir", dir),
			)
		}
	}

	if m && p {
		lg.Fatal("invalid datadir; both member and proxy directories exist")
	}
	if m {
		return dirMember
	}
	if p {
		return dirProxy
	}
	return dirEmpty
}

func checkSupportArch() {
	lg, err := logutil.CreateDefaultZapLogger(zap.InfoLevel)
	if err != nil {
		panic(err)
	}
	// to add a new platform, check https://github.com/etcd-io/website/blob/main/content/en/docs/next/op-guide/supported-platform.md
	if runtime.GOARCH == "amd64" ||
		runtime.GOARCH == "arm64" ||
		runtime.GOARCH == "ppc64le" ||
		runtime.GOARCH == "s390x" {
		return
	}
	// unsupported arch only configured via environment variable
	// so unset here to not parse through flag
	defer os.Unsetenv("ETCD_UNSUPPORTED_ARCH")
	if env, ok := os.LookupEnv("ETCD_UNSUPPORTED_ARCH"); ok && env == runtime.GOARCH {
		lg.Info("running etcd on unsupported architecture since ETCD_UNSUPPORTED_ARCH is set", zap.String("arch", env))
		return
	}

	lg.Error("running etcd on unsupported architecture since ETCD_UNSUPPORTED_ARCH is set", zap.String("arch", runtime.GOARCH))
	os.Exit(1)
}


text:
namespace DeviceSQL.Device.MODBUS
{
    internal static class Device
    {

        #region Enums

        internal enum DataType
        {
            Boolean,
            Short,
            UShort,
            Long,
            Float,
            String,
            HistoryArchive,
            EventArchive
        }

        #endregion

        #region Constants

        public const int DefaultRetries = 3;
        public const int DefaultWaitToRetryMilliseconds = 250;
        public const int MinimumFrameSize = 3;
        public const int MinimumFrameSizeWithExtendedUnitId = 4;

        // MODBUS Functions
        public const byte ReadCoils = 1;
        public const byte ReadDiscreteInputs = 2;
        public const byte ReadHoldingRegisters = 3;
        public const byte ReadInputRegisters = 4;
        public const byte WriteSingleCoil = 5;
        public const byte WriteMultipleRegisters = 16;

        // MODBUS slave exception offset that is added to the function code, to flag an exception
        public const byte ExceptionOffset = 128;

        // MODBUS slave exception codes
        public const byte IllegalFunction = 1;
        public const byte IllegalDataAddress = 2;
        public const byte IllegalDataValue = 3;
        public const byte SlaveDeviceFailure = 4;
        public const byte Acknowledge = 5;
        public const byte SlaveDeviceBusy = 6;
        public const byte NegativeAcknowlegde = 7;
        public const byte MemoryParityError = 8;

        #endregion

    }
}


text:
package packet_injector

import (
	"bytes"
	"fmt"
	"net/http"

	"github.com/skydive-project/skydive/common"
	shttp "github.com/skydive-project/skydive/http"
	"github.com/skydive-project/skydive/logging"
	"github.com/skydive-project/skydive/topology/graph"
)

const (
	Namespace = "Packet_Injection"
)

type PacketInjectorServer struct {
	shttp.DefaultWSClientEventHandler
	WSAsyncClientPool *shttp.WSAsyncClientPool
	Graph             *graph.Graph
}

func (pis *PacketInjectorServer) injectPacket(msg shttp.WSMessage) (bool, string) {
	params := struct {
		SrcNode interface{}
		DstNode interface{}
		Type    string
		Payload string
		Count   int
	}{}
	if err := common.JsonDecode(bytes.NewBuffer([]byte(*msg.Obj)), &params); err != nil {
		e := fmt.Sprintf("Unable to decode packet inject param message %v", msg)
		return false, e
	}

	var srcNode graph.Node
	if err := srcNode.Decode(params.SrcNode); err != nil {
		e := fmt.Sprintf("Unable to decode source node %s", err.Error())
		return false, e
	}

	var dstNode graph.Node
	if err := dstNode.Decode(params.DstNode); err != nil {
		e := fmt.Sprintf("Unable to decode destination node %s", err.Error())
		return false, e
	}

	pip := PacketParams{
		SrcNode: &srcNode,
		DstNode: &dstNode,
		Type:    params.Type,
		Payload: params.Payload,
		Count:   params.Count,
	}

	if err := InjectPacket(&pip, pis.Graph); err != nil {
		e := fmt.Sprintf("Failed to inject packet: %s", err.Error())
		return false, e
	}
	return true, ""
}

func (pis *PacketInjectorServer) OnMessage(c *shttp.WSAsyncClient, msg shttp.WSMessage) {
	if msg.Namespace != Namespace {
		return
	}

	switch msg.Type {
	case "InjectPacket":
		status := http.StatusOK
		result, e := pis.injectPacket(msg)
		if !result {
			logging.GetLogger().Errorf(e)
			status = http.StatusBadRequest
		}
		reply := msg.Reply(e, "PIResult", status)
		c.SendWSMessage(reply)
	}
}

func NewServer(wspool *shttp.WSAsyncClientPool, graph *graph.Graph) *PacketInjectorServer {
	s := &PacketInjectorServer{
		WSAsyncClientPool: wspool,
		Graph:             graph,
	}
	wspool.AddEventHandler(s)

	return s
}


text:
{% extends "zerver/portico.html" %}

{# Login page. #}
{% block portico_content %}

Useful development URLs

        Below is a list of useful tools and data sets available only in the Zulip
        development environment that are often useful when contributing to Zulip.
        Most of these require you to run a command to build/generate the relevant
        content. This table specifies which command to use to update the data served
        by each page (since several of these, like test coverage, require a special
        command to be run to generate the data). Make sure your development server is still running
        when you visit these!

                URL
                Command
                Description

                /coverage/index.html
                ./tools/test-backend --coverage
                View backend coverage report

                /node-coverage/index.html
                ./tools/test-js-with-node --coverage
                View node coverage report

                /docs/index.html
                ./tools/build-docs
                View Zulip documentation

                /emails
                ./tools/inline-email-css

                    Run the command if you made changes to source.html email templates.

                Preview all email templates.

                /static/html/5xx.html
                ./manage.py collectstatic --noinput
                Error 5xx page served by nginx (used when Django is totally broken)

                /errors/404
                None needed
                Error 404 page served by Django

                /errors/5xx
                None needed
                Error 5xx page served by Django

Development-specific management commands live in zilencer/management/commands.  Highlights include:

./manage.py populate_db: Rebuilds database.  Has options to e.g. create 3K users for testing.

./manage.py mark_all_messages_unread: Useful for testing reading messages.

./manage.py add_new_realm: Add a new realm. Useful for testing onboarding.

./manage.py add_new_user: Add a new user. Useful for testing onboarding.

./manage.py add_mock_conversation: Add test messages, streams, images, emoji, etc.
                into the dev environment. First edit zilencer/management/commands/add_mock_conversation.py
                to add the data you're testing.

You can find docs on testing Google & GitHub authentication over here.

{% endblock %}


text:
package assignment4.object;

public class Birth {

	private int id;
	private long time;
	private String room;
	private int mother_id;

	public Birth(){
	}

	public int getId() {
		return id;
	}

	public long getTime() {
		return time;
	}

	public String getRoom() {
		return room;
	}

	public int getMother_id() {
		return mother_id;
	}

	public void setMother_id(int mother_id) {
		this.mother_id = mother_id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public void setTime(long time) {
		this.time = time;
	}

	public void setRoom(String room) {
		this.room = room;
	}

}


text:
package org.cloudfoundry.client.v3;

import org.cloudfoundry.AbstractCloudFoundryException;

import java.util.List;
import java.util.stream.Collectors;

/**
 * An exception encapsulating an error returned from Cloud Foundry V3 APIs
 */
public final class ClientV3Exception extends AbstractCloudFoundryException {

    private static final long serialVersionUID = 3422415564722151878L;

    private final List<Error> errors;

    /**
     * Creates a new instance
     *
     * @param statusCode the status code
     * @param errors     the errors
     */
    public ClientV3Exception(Integer statusCode, List<Error> errors) {
        super(statusCode, errors.stream().map(ClientV3Exception::toErrorString).collect(Collectors.joining(", ")));
        this.errors = errors;
    }

    /**
     * Returns the errors
     */
    public List<Error> getErrors() {
        return this.errors;
    }

    private static String toErrorString(Error error) {
        return String.format("%s(%d): %s", error.getTitle(), error.getCode(), error.getDetail());
    }

}