text:
describe('DashParser.Live', function() {
  var Dash;
  var errorCallback;
  var fakeNetEngine;
  var newPeriod;
  var oldNow;
  var parser;
  var realTimeout;
  var updateTime = 5;
  var Util;
  var loop;

  beforeEach(function() {
    jasmine.clock().install();
    var retry = shaka.net.NetworkingEngine.defaultRetryParameters();
    fakeNetEngine = new shaka.test.FakeNetworkingEngine();
    newPeriod = jasmine.createSpy('newPeriod');
    errorCallback = jasmine.createSpy('error callback');
    parser = new shaka.dash.DashParser();
    parser.configure({
      retryParameters: retry,
      dash: { clockSyncUri: '', customScheme: function(node) { return null; } }
    });
  });

  beforeAll(function() {
    Dash = shaka.test.Dash;
    Util = shaka.test.Util;
    realTimeout = window.setTimeout;
    oldNow = Date.now;
  });

  afterEach(function() {
    if (loop) {
      loop.abort();
      loop = null;
    }
    // Dash parser stop is synchronous.
    parser.stop();
    jasmine.clock().uninstall();
  });

  afterAll(function() {
    Date.now = oldNow;
  });

  /**
   * Returns a promise that waits until manifest updates.
   *
   * @return {!Promise}
   */
  function delayForUpdatePeriod() {
    // Tick the virtual clock to trigger an update and resolve all Promises.
    loop = Util.fakeEventLoop(updateTime, realTimeout);
    return loop;
  }

  /**
   * Makes a simple live manifest with the given representation contents.
   *
   * @param {!Array.<string>} lines
   * @param {number} updatePeriod
   * @param {number=} opt_duration
   * @return {string}
   */
  function makeSimpleLiveManifestText(lines, updatePeriod, opt_duration) {
    var attr = opt_duration ? 'duration="PT' + opt_duration + 'S"' : '';
    var template = [
      '<MPD type="dynamic" minimumUpdatePeriod="PT%(updatePeriod)dS">',
      '  <Period id="1" %(attr)s>',
      '    <AdaptationSet mimeType="video/mp4">',
      '      <Representation id="3" bandwidth="500">',
      '        <BaseURL>http://example.com</BaseURL>',
      '%(contents)s',
      '      </Representation>',
      '    </AdaptationSet>',
      '  </Period>',
      '</MPD>'
    ].join('\n');
    var text = sprintf(template, {
      attr: attr,
      contents: lines.join('\n'),
      updatePeriod: updatePeriod
    });
    return text;
  }

  /**
   * Creates tests that test the behavior common between SegmentList and
   * SegmentTemplate.
   *
   * @param {!Array.<string>} basicLines
   * @param {!Array.<!shaka.media.SegmentReference>} basicRefs
   * @param {!Array.<string>} updateLines
   * @param {!Array.<!shaka.media.SegmentReference>} updateRefs
   * @param {!Array.<string>} partialUpdateLines
   */
  function testCommonBehaviors(
      basicLines, basicRefs, updateLines, updateRefs, partialUpdateLines) {
    /**
     * Tests that an update will show the given references.
     *
     * @param {function()} done
     * @param {!Array.<string>} firstLines The Representation contents for the
     *   first manifest.
     * @param {!Array.<!shaka.media.SegmentReference>} firstReferences The media
     *   references for the first parse.
     * @param {!Array.<string>} secondLines The Representation contents for the
     *   updated manifest.
     * @param {!Array.<!shaka.media.SegmentReference>} secondReferences The
     *   media references for the updated manifest.
     */
    function testBasicUpdate(
        done, firstLines, firstReferences, secondLines, secondReferences) {
      var firstManifest = makeSimpleLiveManifestText(firstLines, updateTime);
      var secondManifest = makeSimpleLiveManifestText(secondLines, updateTime);

      fakeNetEngine.setResponseMapAsText({'dummy://foo': firstManifest});
      parser.start('dummy://foo', fakeNetEngine, newPeriod, errorCallback)
          .then(function(manifest) {
            Dash.verifySegmentIndex(manifest, firstReferences, 0);

            fakeNetEngine.setResponseMapAsText({'dummy://foo': secondManifest});
            return delayForUpdatePeriod().then(function() {
              Dash.verifySegmentIndex(manifest, secondReferences, 0);
            });
          })
          .catch(fail)
          .then(done);
    }

    it('basic support', function(done) {
      testBasicUpdate(done, basicLines, basicRefs, updateLines, updateRefs);
    });

    it('new manifests don\'t need to include old references', function(done) {
      testBasicUpdate(
          done, basicLines, basicRefs, partialUpdateLines, updateRefs);
    });

    it('evicts old references for single-period live stream', function(done) {
      var template = [
        '<MPD type="dynamic" minimumUpdatePeriod="PT%(updateTime)dS"',
        '    timeShiftBufferDepth="PT1S"',
        '    availabilityStartTime="1970-01-01T00:00:00Z">',
        '  <Period id="1">',
        '    <AdaptationSet mimeType="video/mp4">',
        '      <Representation id="3" bandwidth="500">',
        '        <BaseURL>http://example.com</BaseURL>',
        '%(contents)s',
        '      </Representation>',
        '    </AdaptationSet>',
        '  </Period>',
        '</MPD>'
      ].join('\n');
      var text = sprintf(
          template, {updateTime: updateTime, contents: basicLines.join('\n')});

      fakeNetEngine.setResponseMapAsText({'dummy://foo': text});
      Date.now = function() { return 0; };
      parser.start('dummy://foo', fakeNetEngine, newPeriod, errorCallback)
          .then(function(manifest) {
            expect(manifest).toBeTruthy();
            var stream = manifest.periods[0].streamSets[0].streams[0];
            expect(stream).toBeTruthy();

            expect(stream.findSegmentPosition).toBeTruthy();
            expect(stream.findSegmentPosition(0)).not.toBe(null);
            Dash.verifySegmentIndex(manifest, basicRefs, 0);

            // 15 seconds for @timeShiftBufferDepth, the first segment duration,
            // and the @suggestedPresentationDuration.
            Date.now = function() { return (2 * 15 + 5) * 1000; };
            return delayForUpdatePeriod().then(function() {
              // The first reference should have been evicted.
              expect(stream.findSegmentPosition(0)).toBe(null);
              Dash.verifySegmentIndex(manifest, basicRefs.slice(1), 0);
            });
          })
          .catch(fail)
          .then(done);
    });

    it('evicts old references for multi-period live stream', function(done) {
      var template = [
        '<MPD type="dynamic" minimumUpdatePeriod="PT%(updateTime)dS"',
        '    timeShiftBufferDepth="PT1S"',
        '    availabilityStartTime="1970-01-01T00:00:00Z">',
        '  <Period id="1">',
        '    <AdaptationSet mimeType="video/mp4">',
        '      <Representation id="3" bandwidth="500">',
        '        <BaseURL>http://example.com</BaseURL>',
        '%(contents)s',
        '      </Representation>',
        '    </AdaptationSet>',
        '  </Period>',
        '  <Period id="2" start="PT%(pStart)dS">',
        '    <AdaptationSet mimeType="video/mp4">',
        '      <Representation id="4" bandwidth="500">',
        '        <BaseURL>http://example.com</BaseURL>',
        '%(contents)s',
        '      </Representation>',
        '    </AdaptationSet>',
        '  </Period>',
        '</MPD>'
      ].join('\n');
      // Set the period start to the sum of the durations of the references
      // in the previous period.
      var durs = basicRefs.map(function(r) { return r.endTime - r.startTime });
      var pStart = durs.reduce(function(p, d) { return p + d}, 0);
      var args = {
        updateTime: updateTime,
        pStart: pStart,
        contents: basicLines.join('\n')
      };
      var text = sprintf(template, args);

      fakeNetEngine.setResponseMapAsText({'dummy://foo': text});
      Date.now = function() { return 0; };
      parser.start('dummy://foo', fakeNetEngine, newPeriod, errorCallback)
          .then(function(manifest) {
            Dash.verifySegmentIndex(manifest, basicRefs, 0);
            Dash.verifySegmentIndex(manifest, basicRefs, 1);

            // 15 seconds for @timeShiftBufferDepth, the first segment duration,
            // and the @suggestedPresentationDuration.
            Date.now = function() { return (2 * 15 + 5) * 1000; };
            return delayForUpdatePeriod().then(function() {
              // The first reference should have been evicted.
              Dash.verifySegmentIndex(manifest, basicRefs.slice(1), 0);
              Dash.verifySegmentIndex(manifest, basicRefs, 1);
              // Same as above, but 1 period length later
              Date.now = function() { return (2 * 15 + 5 + pStart) * 1000; };
              return delayForUpdatePeriod();
            }).then(function() {
              Dash.verifySegmentIndex(manifest, [], 0);
              Dash.verifySegmentIndex(manifest, basicRefs.slice(1), 1);
            });
          })
          .catch(fail)
          .then(done);
    });

    it('sets infinite duration for single-period live streams', function(done) {
      var template = [
        '<MPD type="dynamic" minimumUpdatePeriod="PT%(updateTime)dS"',
        '    timeShiftBufferDepth="PT1S"',
        '    availabilityStartTime="1970-01-01T00:00:00Z">',
        '  <Period id="1">',
        '    <AdaptationSet mimeType="video/mp4">',
        '      <Representation id="3" bandwidth="500">',
        '        <BaseURL>http://example.com</BaseURL>',
        '%(contents)s',
        '      </Representation>',
        '    </AdaptationSet>',
        '  </Period>',
        '</MPD>'
      ].join('\n');
      var text = sprintf(
          template, {updateTime: updateTime, contents: basicLines.join('\n')});

      fakeNetEngine.setResponseMapAsText({'dummy://foo': text});
      Date.now = function() { return 0; };
      parser.start('dummy://foo', fakeNetEngine, newPeriod, errorCallback)
          .then(function(manifest) {
            expect(manifest.periods.length).toBe(1);
            var timeline = manifest.presentationTimeline;
            expect(timeline.getDuration()).toBe(Number.POSITIVE_INFINITY);
          }).catch(fail).then(done);
    });

    it('sets infinite duration for multi-period live streams', function(done) {
      var template = [
        '<MPD type="dynamic" minimumUpdatePeriod="PT%(updateTime)dS"',
        '    timeShiftBufferDepth="PT1S"',
        '    availabilityStartTime="1970-01-01T00:00:00Z">',
        '  <Period id="1">',
        '    <AdaptationSet mimeType="video/mp4">',
        '      <Representation id="3" bandwidth="500">',
        '        <BaseURL>http://example.com</BaseURL>',
        '%(contents)s',
        '      </Representation>',
        '    </AdaptationSet>',
        '  </Period>',
        '  <Period id="2" start="PT60S">',
        '    <AdaptationSet mimeType="video/mp4">',
        '      <Representation id="4" bandwidth="500">',
        '        <BaseURL>http://example.com</BaseURL>',
        '%(contents)s',
        '      </Representation>',
        '    </AdaptationSet>',
        '  </Period>',
        '</MPD>'
      ].join('\n');
      var text = sprintf(
          template, {updateTime: updateTime, contents: basicLines.join('\n')});

      fakeNetEngine.setResponseMapAsText({'dummy://foo': text});
      Date.now = function() { return 0; };
      parser.start('dummy://foo', fakeNetEngine, newPeriod, errorCallback)
          .then(function(manifest) {
            expect(manifest.periods.length).toBe(2);
            expect(manifest.periods[1].startTime).toBe(60);
            var timeline = manifest.presentationTimeline;
            expect(timeline.getDuration()).toBe(Number.POSITIVE_INFINITY);
          }).catch(fail).then(done);
    });
  }

  it('can add Periods', function(done) {
    var lines = [
      '<SegmentTemplate startNumber="1" media="s$Number$.mp4" duration="2" />'
    ];
    var template = [
      '<MPD type="dynamic" minimumUpdatePeriod="PT%(updateTime)dS">',
      '  <Period id="4">',
      '    <AdaptationSet mimeType="video/mp4">',
      '      <Representation id="6" bandwidth="500">',
      '        <BaseURL>http://example.com</BaseURL>',
      '%(contents)s',
      '      </Representation>',
      '    </AdaptationSet>',
      '  </Period>',
      '</MPD>'
    ].join('\n');
    var secondManifest =
        sprintf(template, {updateTime: updateTime, contents: lines.join('\n')});
    var firstManifest = makeSimpleLiveManifestText(lines, updateTime);

    fakeNetEngine.setResponseMapAsText({'dummy://foo': firstManifest});
    parser.start('dummy://foo', fakeNetEngine, newPeriod, errorCallback)
        .then(function(manifest) {
          expect(manifest.periods.length).toBe(1);
          expect(newPeriod.calls.count()).toBe(1);

          fakeNetEngine.setResponseMapAsText({'dummy://foo': secondManifest});
          return delayForUpdatePeriod().then(function() {
            // Should update the same manifest object.
            expect(manifest.periods.length).toBe(2);
            expect(newPeriod.calls.count()).toBe(2);
          });
        })
        .catch(fail)
        .then(done);
  });

  it('uses redirect URL for manifest BaseURL', function(done) {
    var template = [
      '<MPD type="dynamic" minimumUpdatePeriod="PT%(updatePeriod)dS">',
      '  <Period id="1" duration="PT30S">',
      '    <AdaptationSet mimeType="video/mp4">',
      '      <Representation id="3" bandwidth="500">',
      '        <SegmentTemplate startNumber="1" media="s$Number$.mp4">',
      '          <SegmentTimeline>',
      '            <S d="10" t="0" />',
      '            <S d="5" />',
      '            <S d="15" />',
      '          </SegmentTimeline>',
      '        </SegmentTemplate>',
      '      </Representation>',
      '    </AdaptationSet>',
      '  </Period>',
      '</MPD>'
    ].join('\n');
    var manifestText = sprintf(template, {updatePeriod: updateTime});
    var manifestData = shaka.util.StringUtils.toUTF8(manifestText);
    var originalUri = 'http://example.com/';
    var redirectedUri = 'http://redirected.com/';

    // The initial manifest request will be redirected.
    fakeNetEngine.request.and.returnValue(
        Promise.resolve({uri: redirectedUri, data: manifestData}));

    parser.start(originalUri, fakeNetEngine, newPeriod, errorCallback)
        .then(function(manifest) {
          // The manifest request was made to the original URL.
          expect(fakeNetEngine.request.calls.count()).toBe(1);
          var netRequest = fakeNetEngine.request.calls.argsFor(0)[1];
          expect(netRequest.uris).toEqual([originalUri]);

          // Since the manifest request was redirected, the segment refers to
          // the redirected base.
          var stream = manifest.periods[0].streamSets[0].streams[0];
          var segmentUri = stream.getSegmentReference(1).getUris()[0];
          expect(segmentUri).toBe(redirectedUri + 's1.mp4');
        })
        .catch(fail)
        .then(done);
  });

  it('failures in update call error callback', function(done) {
    var lines = [
      '<SegmentTemplate startNumber="1" media="s$Number$.mp4" duration="2" />'
    ];
    var manifest = makeSimpleLiveManifestText(lines, updateTime);

    fakeNetEngine.setResponseMapAsText({'dummy://foo': manifest});
    parser.start('dummy://foo', fakeNetEngine, newPeriod, errorCallback)
        .then(function(manifest) {
          expect(fakeNetEngine.request.calls.count()).toBe(1);

          var error = new shaka.util.Error(
              shaka.util.Error.Category.NETWORK,
              shaka.util.Error.Code.BAD_HTTP_STATUS);
          var promise = Promise.reject(error);
          fakeNetEngine.request.and.returnValue(promise);

          return delayForUpdatePeriod().then(function() {
            expect(errorCallback.calls.count()).toBe(1);
          });
        })
        .catch(fail)
        .then(done);
  });

  it('uses @minimumUpdatePeriod', function(done) {
    var lines = [
      '<SegmentTemplate startNumber="1" media="s$Number$.mp4" duration="2" />'
    ];
    // updateTime parameter sets @minimumUpdatePeriod in the manifest.
    var manifest = makeSimpleLiveManifestText(lines, updateTime);

    fakeNetEngine.setResponseMapAsText({'dummy://foo': manifest});
    parser.start('dummy://foo', fakeNetEngine, newPeriod, errorCallback)
        .then(function(manifest) {
          expect(fakeNetEngine.request.calls.count()).toBe(1);
          expect(manifest).toBeTruthy();

          var partialTime = updateTime * 1000 * 3 / 4;
          var remainingTime = updateTime * 1000 - partialTime;
          jasmine.clock().tick(partialTime);
          return Util.delay(0.01, realTimeout)
              .then(function() {
                // Update period has not passed yet.
                expect(fakeNetEngine.request.calls.count()).toBe(1);
                jasmine.clock().tick(remainingTime);
                return Util.delay(0.01, realTimeout);
              })
              .then(function() {
                // Update period has passed.
                expect(fakeNetEngine.request.calls.count()).toBe(2);
              });
        })
        .catch(fail)
        .then(done);
  });

  it('uses Mpd.Location', function(done) {
    var manifest = [
      '<MPD type="dynamic" minimumUpdatePeriod="PT' + updateTime + 'S">',
      '  <Location>http://foobar</Location>',
      '  <Location>http://foobar2</Location>',
      '  <Period id="1" duration="PT10S">',
      '    <AdaptationSet mimeType="video/mp4">',
      '      <Representation id="3" bandwidth="500">',
      '<SegmentTemplate startNumber="1" media="s$Number$.mp4" duration="2" />',
      '      </Representation>',
      '    </AdaptationSet>',
      '  </Period>',
      '</MPD>'
    ].join('\n');
    fakeNetEngine.setResponseMapAsText({'dummy://foo': manifest});

    var manifestRequest = shaka.net.NetworkingEngine.RequestType.MANIFEST;
    parser.start('dummy://foo', fakeNetEngine, newPeriod, errorCallback)
        .then(function(manifest) {
          expect(fakeNetEngine.request.calls.count()).toBe(1);
          fakeNetEngine.expectRequest('dummy://foo', manifestRequest);
          fakeNetEngine.request.calls.reset();

          // Create a mock so we can verify it gives two URIs.
          fakeNetEngine.request.and.callFake(function(type, request) {
            expect(type).toBe(manifestRequest);
            expect(request.uris).toEqual(['http://foobar', 'http://foobar2']);
            var data = shaka.util.StringUtils.toUTF8(manifest);
            return Promise.resolve(
                {uri: request.uris[0], data: data, headers: {}});
          });

          return delayForUpdatePeriod();
        })
        .then(function() {
          expect(fakeNetEngine.request.calls.count()).toBe(1);
        })
        .catch(fail)
        .then(done);
  });

  it('uses @suggestedPresentationDelay', function(done) {
    var manifest = [
      '<MPD type="dynamic" suggestedPresentationDelay="PT60S"',
      '    minimumUpdatePeriod="PT5S"',
      '    timeShiftBufferDepth="PT2M"',
      '    maxSegmentDuration="PT10S"',
      '    availabilityStartTime="1970-01-01T00:05:00Z">',
      '  <Period id="1">',
      '    <AdaptationSet mimeType="video/mp4">',
      '      <Representation id="3" bandwidth="500">',
      '        <BaseURL>http://example.com</BaseURL>',
      '<SegmentTemplate startNumber="1" media="s$Number$.mp4" duration="2" />',
      '      </Representation>',
      '    </AdaptationSet>',
      '  </Period>',
      '</MPD>'
    ].join('\n');
    fakeNetEngine.setResponseMapAsText({'dummy://foo': manifest});

    Date.now = function() { return 600000; /* 10 minutes */ };
    parser.start('dummy://foo', fakeNetEngine, newPeriod, errorCallback)
        .then(function(manifest) {
          expect(manifest).toBeTruthy();
          var timeline = manifest.presentationTimeline;
          expect(timeline).toBeTruthy();

          //  We are 5 minutes into the presentation, with a
          //  @timeShiftBufferDepth of 120 seconds and a @maxSegmentDuration of
          //  10 seconds, the normal start will be 2:50; but with a 60
          //  @suggestedPresentationDelay it should be 1:50.
          expect(timeline.getSegmentAvailabilityStart()).toBe(110);
          // Similarly, normally the end should be 4:50; but with the delay
          // it will be 3:50 minutes.
          expect(timeline.getSegmentAvailabilityEnd()).toBe(290);
          expect(timeline.getSeekRangeEnd()).toBe(230);
        })
        .catch(fail)
        .then(done);
  });

  describe('maxSegmentDuration', function() {
    it('uses @maxSegmentDuration', function(done) {
      var manifest = [
        '<MPD type="dynamic" suggestedPresentationDelay="PT0S"',
        '    minimumUpdatePeriod="PT5S"',
        '    timeShiftBufferDepth="PT2M"',
        '    maxSegmentDuration="PT15S"',
        '    availabilityStartTime="1970-01-01T00:05:00Z">',
        '  <Period id="1">',
        '    <AdaptationSet id="2" mimeType="video/mp4">',
        '      <Representation id="3" bandwidth="500">',
        '        <BaseURL>http://example.com</BaseURL>',
        '<SegmentTemplate media="s$Number$.mp4" duration="2" />',
        '      </Representation>',
        '    </AdaptationSet>',
        '  </Period>',
        '</MPD>'
      ].join('\n');
      fakeNetEngine.setResponseMapAsText({'dummy://foo': manifest});

      Date.now = function() { return 600000; /* 10 minutes */ };
      parser.start('dummy://foo', fakeNetEngine, newPeriod, errorCallback)
          .then(function(manifest) {
            expect(manifest).toBeTruthy();
            var timeline = manifest.presentationTimeline;
            expect(timeline).toBeTruthy();
            expect(timeline.getSegmentAvailabilityStart()).toBe(165);
            expect(timeline.getSegmentAvailabilityEnd()).toBe(285);
          })
          .catch(fail)
          .then(done);
    });

    it('derived from SegmentTemplate w/ SegmentTimeline', function(done) {
      var lines = [
        '<SegmentTemplate media="s$Number$.mp4">',
        '  <SegmentTimeline>',
        '    <S t="0" d="7" />',
        '    <S d="8" />',
        '    <S d="6" />',
        '  </SegmentTimeline>',
        '</SegmentTemplate>'
      ];
      testDerived(lines, done);
    });

    it('derived from SegmentTemplate w/ @duration', function(done) {
      var lines = [
        '<SegmentTemplate media="s$Number$.mp4" duration="8" />'
      ];
      testDerived(lines, done);
    });

    it('derived from SegmentList', function(done) {
      var lines = [
        '<SegmentList duration="8">',
        '  <SegmentURL media="s1.mp4" />',
        '  <SegmentURL media="s2.mp4" />',
        '</SegmentList>'
      ];
      testDerived(lines, done);
    });

    it('derived from SegmentList w/ SegmentTimeline', function(done) {
      var lines = [
        '<SegmentList duration="8">',
        '  <SegmentTimeline>',
        '    <S t="0" d="5" />',
        '    <S d="4" />',
        '    <S d="8" />',
        '  </SegmentTimeline>',
        '  <SegmentURL media="s1.mp4" />',
        '  <SegmentURL media="s2.mp4" />',
        '</SegmentList>'
      ];
      testDerived(lines, done);
    });

    function testDerived(lines, done) {
      var template = [
        '<MPD type="dynamic" suggestedPresentationDelay="PT0S"',
        '    minimumUpdatePeriod="PT5S"',
        '    timeShiftBufferDepth="PT2M"',
        '    availabilityStartTime="1970-01-01T00:05:00Z">',
        '  <Period id="1">',
        '    <AdaptationSet id="2" mimeType="video/mp4">',
        '      <Representation id="3" bandwidth="500">',
        '        <BaseURL>http://example.com</BaseURL>',
        '%(contents)s',
        '      </Representation>',
        '    </AdaptationSet>',
        '  </Period>',
        '</MPD>'
      ].join('\n');
      var manifest = sprintf(template, { contents: lines.join('\n') });

      fakeNetEngine.setResponseMapAsText({'dummy://foo': manifest});
      Date.now = function() { return 600000; /* 10 minutes */ };
      parser.start('dummy://foo', fakeNetEngine, newPeriod, errorCallback)
          .then(function(manifest) {
            expect(manifest).toBeTruthy();
            var timeline = manifest.presentationTimeline;
            expect(timeline).toBeTruthy();

            // NOTE: the largest segment is 8 seconds long in each test.
            expect(timeline.getSegmentAvailabilityStart()).toBe(172);
            expect(timeline.getSegmentAvailabilityEnd()).toBe(292);
          })
          .catch(fail)
          .then(done);
    }
  });

  describe('stop', function() {
    var manifestUri;
    var dateUri;
    var manifestRequestType;
    var dateRequestType;

    beforeAll(function() {
      manifestUri = 'dummy://foo';
      dateUri = 'http://foo.bar/date';
      manifestRequestType = shaka.net.NetworkingEngine.RequestType.MANIFEST;
      dateRequestType = shaka.net.NetworkingEngine.RequestType.MANIFEST;
    });

    beforeEach(function() {
      var manifest = [
        '<MPD type="dynamic" minimumUpdatePeriod="PT' + updateTime + 'S">',
        '  <UTCTiming schemeIdUri="urn:mpeg:dash:utc:http-xsdate:2014"',
        '      value="http://foo.bar/date" />',
        '  <UTCTiming schemeIdUri="urn:mpeg:dash:utc:http-xsdate:2014"',
        '      value="http://foo.bar/date" />',
        '  <Period id="1">',
        '    <AdaptationSet mimeType="video/mp4">',
        '      <Representation id="3" bandwidth="500">',
        '        <BaseURL>http://example.com</BaseURL>',
        '        <SegmentTemplate startNumber="1" media="s$Number$.mp4"',
        '            duration="2" />',
        '      </Representation>',
        '    </AdaptationSet>',
        '  </Period>',
        '</MPD>'
      ].join('\n');
      fakeNetEngine.setResponseMapAsText({
        'http://foo.bar/date': '1970-01-01T00:00:30Z',
        'dummy://foo': manifest
      });
    });

    it('stops updates', function(done) {
      parser.start(manifestUri, fakeNetEngine, newPeriod, errorCallback)
          .then(function(manifest) {
            fakeNetEngine.expectRequest(manifestUri, manifestRequestType);
            fakeNetEngine.request.calls.reset();

            parser.stop();
            return delayForUpdatePeriod().then(function() {
              expect(fakeNetEngine.request).not.toHaveBeenCalled();
            });
          })
          .catch(fail)
          .then(done);
    });

    it('stops initial parsing', function(done) {
      parser.start('dummy://foo', fakeNetEngine, newPeriod, errorCallback)
          .then(function(manifest) {
            expect(manifest).toBe(null);
            fakeNetEngine.expectRequest(manifestUri, manifestRequestType);
            fakeNetEngine.request.calls.reset();
            return delayForUpdatePeriod();
          })
          .then(function() {
            // An update should not occur.
            expect(fakeNetEngine.request).not.toHaveBeenCalled();
          })
          .catch(fail)
          .then(done);

      // start will only begin the network request, calling stop here will be
      // after the request has started but before any parsing has been done.
      expect(fakeNetEngine.request.calls.count()).toBe(1);
      parser.stop();
    });

    it('interrupts manifest updates', function(done) {
      parser.start('dummy://foo', fakeNetEngine, newPeriod, errorCallback)
          .then(function(manifest) {
            expect(manifest).toBeTruthy();
            fakeNetEngine.expectRequest(manifestUri, manifestRequestType);
            fakeNetEngine.request.calls.reset();
            var delay = fakeNetEngine.delayNextRequest();

            return delayForUpdatePeriod().then(function() {
              // The request was made but should not be resolved yet.
              expect(fakeNetEngine.request.calls.count()).toBe(1);
              fakeNetEngine.expectRequest(manifestUri, manifestRequestType);
              fakeNetEngine.request.calls.reset();
              parser.stop();
              delay.resolve();
              return Util.delay(0.1, realTimeout);
            }).then(function() {
              // Wait for another update period.
              return delayForUpdatePeriod();
            }).then(function() {
              // A second update should not occur.
              expect(fakeNetEngine.request).not.toHaveBeenCalled();
            });
          })
          .catch(fail)
          .then(done);
    });

    it('interrupts UTCTiming requests', function(done) {
      var delay = fakeNetEngine.delayNextRequest();
      Util.delay(0.2, realTimeout).then(function() {
        // This is the initial manifest request.
        expect(fakeNetEngine.request.calls.count()).toBe(1);
        fakeNetEngine.expectRequest(manifestUri, manifestRequestType);
        fakeNetEngine.request.calls.reset();
        // Resolve the manifest request and wait on the UTCTiming request.
        delay.resolve();
        delay = fakeNetEngine.delayNextRequest();
        return Util.delay(0.2, realTimeout);
      }).then(function() {
        // This is the first UTCTiming request.
        expect(fakeNetEngine.request.calls.count()).toBe(1);
        fakeNetEngine.expectRequest(dateUri, dateRequestType);
        fakeNetEngine.request.calls.reset();
        // Interrupt the parser, then fail the request.
        parser.stop();
        delay.reject();
        return Util.delay(0.1, realTimeout);
      }).then(function() {
        // Wait for another update period.
        return delayForUpdatePeriod();
      }).then(function() {
        // No more updates should occur.
        expect(fakeNetEngine.request).not.toHaveBeenCalled();
      }).catch(fail).then(done);

      parser.start('dummy://foo', fakeNetEngine, newPeriod, errorCallback)
          .catch(fail);
    });
  });

  describe('SegmentTemplate w/ SegmentTimeline', function() {
    var basicLines = [
      '<SegmentTemplate startNumber="1" media="s$Number$.mp4">',
      '  <SegmentTimeline>',
      '    <S d="10" t="0" />',
      '    <S d="5" />',
      '    <S d="15" />',
      '  </SegmentTimeline>',
      '</SegmentTemplate>'
    ];
    var basicRefs = [
      shaka.test.Dash.makeReference('s1.mp4', 1, 0, 10),
      shaka.test.Dash.makeReference('s2.mp4', 2, 10, 15),
      shaka.test.Dash.makeReference('s3.mp4', 3, 15, 30)
    ];
    var updateLines = [
      '<SegmentTemplate startNumber="1" media="s$Number$.mp4">',
      '  <SegmentTimeline>',
      '    <S d="10" t="0" />',
      '    <S d="5" />',
      '    <S d="15" />',
      '    <S d="10" />',
      '  </SegmentTimeline>',
      '</SegmentTemplate>'
    ];
    var updateRefs = [
      shaka.test.Dash.makeReference('s1.mp4', 1, 0, 10),
      shaka.test.Dash.makeReference('s2.mp4', 2, 10, 15),
      shaka.test.Dash.makeReference('s3.mp4', 3, 15, 30),
      shaka.test.Dash.makeReference('s4.mp4', 4, 30, 40)
    ];
    var partialUpdateLines = [
      '<SegmentTemplate startNumber="3" media="s$Number$.mp4">',
      '  <SegmentTimeline>',
      '    <S d="15" t="15" />',
      '    <S d="10" />',
      '  </SegmentTimeline>',
      '</SegmentTemplate>'
    ];

    testCommonBehaviors(
        basicLines, basicRefs, updateLines, updateRefs, partialUpdateLines);
  });

  describe('SegmentList w/ SegmentTimeline', function() {
    var basicLines = [
      '<SegmentList>',
      '  <SegmentURL media="s1.mp4" />',
      '  <SegmentURL media="s2.mp4" />',
      '  <SegmentURL media="s3.mp4" />',
      '  <SegmentTimeline>',
      '    <S d="10" t="0" />',
      '    <S d="5" />',
      '    <S d="15" />',
      '  </SegmentTimeline>',
      '</SegmentList>'
    ];
    var basicRefs = [
      shaka.test.Dash.makeReference('s1.mp4', 1, 0, 10),
      shaka.test.Dash.makeReference('s2.mp4', 2, 10, 15),
      shaka.test.Dash.makeReference('s3.mp4', 3, 15, 30)
    ];
    var updateLines = [
      '<SegmentList>',
      '  <SegmentURL media="s1.mp4" />',
      '  <SegmentURL media="s2.mp4" />',
      '  <SegmentURL media="s3.mp4" />',
      '  <SegmentURL media="s4.mp4" />',
      '  <SegmentTimeline>',
      '    <S d="10" t="0" />',
      '    <S d="5" />',
      '    <S d="15" />',
      '    <S d="10" />',
      '  </SegmentTimeline>',
      '</SegmentList>'
    ];
    var updateRefs = [
      shaka.test.Dash.makeReference('s1.mp4', 1, 0, 10),
      shaka.test.Dash.makeReference('s2.mp4', 2, 10, 15),
      shaka.test.Dash.makeReference('s3.mp4', 3, 15, 30),
      shaka.test.Dash.makeReference('s4.mp4', 4, 30, 40)
    ];
    var partialUpdateLines = [
      '<SegmentList startNumber="3">',
      '  <SegmentURL media="s3.mp4" />',
      '  <SegmentURL media="s4.mp4" />',
      '  <SegmentTimeline>',
      '    <S d="15" t="15" />',
      '    <S d="10" />',
      '  </SegmentTimeline>',
      '</SegmentList>'
    ];

    testCommonBehaviors(
        basicLines, basicRefs, updateLines, updateRefs, partialUpdateLines);
  });

  describe('SegmentList w/ @duration', function() {
    var basicLines = [
      '<SegmentList duration="10">',
      '  <SegmentURL media="s1.mp4" />',
      '  <SegmentURL media="s2.mp4" />',
      '  <SegmentURL media="s3.mp4" />',
      '</SegmentList>'
    ];
    var basicRefs = [
      shaka.test.Dash.makeReference('s1.mp4', 1, 0, 10),
      shaka.test.Dash.makeReference('s2.mp4', 2, 10, 20),
      shaka.test.Dash.makeReference('s3.mp4', 3, 20, 30)
    ];
    var updateLines = [
      '<SegmentList duration="10">',
      '  <SegmentURL media="s1.mp4" />',
      '  <SegmentURL media="s2.mp4" />',
      '  <SegmentURL media="s3.mp4" />',
      '  <SegmentURL media="s4.mp4" />',
      '</SegmentList>'
    ];
    var updateRefs = [
      shaka.test.Dash.makeReference('s1.mp4', 1, 0, 10),
      shaka.test.Dash.makeReference('s2.mp4', 2, 10, 20),
      shaka.test.Dash.makeReference('s3.mp4', 3, 20, 30),
      shaka.test.Dash.makeReference('s4.mp4', 4, 30, 40)
    ];
    var partialUpdateLines = [
      '<SegmentList startNumber="3" duration="10">',
      '  <SegmentURL media="s3.mp4" />',
      '  <SegmentURL media="s4.mp4" />',
      '</SegmentList>'
    ];

    testCommonBehaviors(
        basicLines, basicRefs, updateLines, updateRefs, partialUpdateLines);
  });
});


text:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using SpentBook.Web.Helpers;
using System.Linq;
using System.Net;

namespace SpentBook.Web.Filters
{
    public class JsonOutputWhenModelInvalidAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!filterContext.HttpContext.Request.IsAjaxRequest())
                return;

            var modelState = ((Controller)filterContext.Controller).ViewData.ModelState;
            if (!modelState.IsValid)
            {
                var errorModel =
                        from x in modelState.Keys
                        where modelState[x].Errors.Count > 0
                        select new
                        {
                            key = x,
                            errors = modelState[x].Errors.
                                                   Select(y => y.ErrorMessage).
                                                   ToArray()
                        };

                filterContext.Result = new JsonResult(errorModel);
                filterContext.HttpContext.Response.StatusCode =
                                                      (int)HttpStatusCode.BadRequest;
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
---
uid: SolidEdgeAssembly.Wire.Application
summary:
remarks:
---


text:
from .version import __version__
from .sendgrid import SendGridClient
from .exceptions import SendGridError, SendGridClientError, SendGridServerError
from .message import Mail


text:
LTC1661
=======

Adruino Library for Linear Technology LTC1661 10bit dual DAC
Created by Stefan Wallnoefer, Feb 8, 2014.
Readme for Version 1.0 (Feb 9, 2014

This Library provides functions to set both (VOUT A and VOUT B) outputs of the LTC1661

Pins on LTC1661:

  1 CS/LD - chip selct
  2 SCK - Serial clock
  3 DIN - Data in (MOSI)
  4 REF - 0V <= VREF <= VCC
  5 VOUT B
  6 VCC - Supply Voltage 2.7V to 5.5V
  7 GND
  8 VOUT A
     ___
  1 | u | 8
  2 |   | 7
  3 |   | 6
  4 |___| 5

Functions:

	LTC1661(): constructor, no arguemt, CS must be set in mainprogam (for non Arduino outputs, DIN, SDK on Arduino standard SPI pins D11, D13)
	LTC1661(CS): constructor, Chipselctpin as argument (DIN, SDK on Arduino standard SPI pins D11, D13)
	LTC1661(DIN, SDK): constructor, custom DIN and SDK as argument, CS must be set in mainprogam (for non Arduino outputs)
	LTC1661(CS, DIN, SDK): constructor, custom CS, DIN and SDK as argument

	sleep(): Goes to Sleep, Input and DAC Regs Unchanged, DAC Outputs Set to High Impedance State
	wakeUp(): Part Wakes Up, Input and DAC Regs Unchanged, DAC Outputs Reflect Existing Contents of DAC Regs
	update(): Load Both DAC Regs with Existing Contents of Input Regs, Outputs Update, Part Wakes Up

	dWrite(channel, state): like digitalWrite

	Variables for all functions:
		value of type int (0...1023) or float/double (0...1.0)
		channel of type char ('A' or 'B') or int (0 or 1)
	loadA(value): Load Input Register A with Data, DAC Outputs Unchanged, Power-Down Status Unchanged
	loadB(value): Load Input Register B with Data, DAC Outputs Unchanged, Power-Down Status Unchanged
	loUpA(value): Load Input Reg A, Load DAC Regs with New Contents of Input Reg A and Existing Contents of Reg B, Outputs Update, Part Wakes Up
	loUpB(value): Load Input Reg B, Load DAC Regs with New Contents of Input Reg B and Existing Contents of Reg A, Outputs Update, Part Wakes Up
	loUp(value):  Load Both Input Regs with same Data, Load Both DAC Regs with New Contents of Input Regs. Outputs Update, Part Wakes Up
	load(valueA, valueB): Load Both Input Regs with diffrent Data ,DAC Outputs Unchanged, Power-Down Status Unchanged
	loUp(valueA, valueB): Load Both Input Regs with diffrent Data, Load Both DAC Regs with New Contents of Input Regs. Outputs Update, Part Wakes Up
	loadCH(channel, value): Load Input Register of selcted Channel with Data, DAC Outputs Unchanged, Power-Down Status Unchanged
	loUpCH(channel, value): Load Input Reg of selcted Channel, Load DAC Regs with New Contents of Input Reg of selcted Channel and Existing Contents of Reg of the other Channel,
	                        Outputs Update, Part Wakes Up

Copyright (c) 2014 Stefan Wallnoefer(walle86) under The MIT License (MIT)


text:
#include "tt_horiheader.h"
#include "doc/tt_horiheader.h"

#include "face.h"

#include FT_TRUETYPE_TABLES_H

#define MAKE_TT_HORIHEADER_GETTER(name, convert_func, member)   \
    MAKE_GETTER(Py_TT_HoriHeader, name, convert_func, member)
#define TT_HORIHEADER_DEF_GETTER(name) DEF_GETTER(name, doc_TT_HoriHeader_ ## name)

/****************************************************************************
 Object basics
*/

typedef struct {
    ftpy_Object base;
    TT_HoriHeader *x;
} Py_TT_HoriHeader;

static PyTypeObject Py_TT_HoriHeader_Type;

PyObject *
Py_TT_HoriHeader_cnew(PyObject *face)
{
    Py_Face *f = (Py_Face *)face;
    Py_TT_HoriHeader *self;
    TT_HoriHeader *orig;

    orig = (TT_HoriHeader *)FT_Get_Sfnt_Table(f->x, ft_sfnt_hhea);
    if (orig == NULL) {
        PyErr_SetString(PyExc_AttributeError, "No hhea found");
        return NULL;
    }

    self = (Py_TT_HoriHeader *)(&Py_TT_HoriHeader_Type)->tp_alloc(&Py_TT_HoriHeader_Type, 0);
    if (self == NULL) {
        return NULL;
    }
    Py_INCREF(face);
    self->base.owner = face;
    self->x = orig;
    return (PyObject *)self;
}

static int
Py_TT_HoriHeader_init(Py_TT_HoriHeader *self, PyObject *args, PyObject *kwds)
{
    PyErr_SetString(
        PyExc_RuntimeError,
        "TT_HoriHeader objects may not be instantiated directly. "
        "Use Face.tt_horiheader instead.");
    return -1;
}

/****************************************************************************
 Getters
*/

MAKE_TT_HORIHEADER_GETTER(version, ftpy_PyFloat_FromFT_FIXED, self->x->Version);
MAKE_TT_HORIHEADER_GETTER(ascender, PyLong_FromLong, self->x->Ascender);
MAKE_TT_HORIHEADER_GETTER(descender, PyLong_FromLong, self->x->Descender);
MAKE_TT_HORIHEADER_GETTER(line_gap, PyLong_FromLong, self->x->Line_Gap);
MAKE_TT_HORIHEADER_GETTER(advance_width_max, PyLong_FromUnsignedLong, self->x->advance_Width_Max);
MAKE_TT_HORIHEADER_GETTER(min_left_side_bearing, PyLong_FromLong, self->x->min_Left_Side_Bearing);
MAKE_TT_HORIHEADER_GETTER(min_right_side_bearing, PyLong_FromLong, self->x->min_Right_Side_Bearing);
MAKE_TT_HORIHEADER_GETTER(xmax_extent, PyLong_FromLong, self->x->xMax_Extent);
MAKE_TT_HORIHEADER_GETTER(caret_slope_rise, PyLong_FromLong, self->x->caret_Slope_Rise);
MAKE_TT_HORIHEADER_GETTER(caret_slope_run, PyLong_FromLong, self->x->caret_Slope_Run);
MAKE_TT_HORIHEADER_GETTER(caret_offset, PyLong_FromLong, self->x->caret_Offset);
MAKE_TT_HORIHEADER_GETTER(metric_data_format, PyLong_FromLong, self->x->metric_Data_Format);
MAKE_TT_HORIHEADER_GETTER(number_of_hmetrics, PyLong_FromLong, self->x->number_Of_HMetrics);

static PyGetSetDef Py_TT_HoriHeader_getset[] = {
    TT_HORIHEADER_DEF_GETTER(version),
    TT_HORIHEADER_DEF_GETTER(ascender),
    TT_HORIHEADER_DEF_GETTER(descender),
    TT_HORIHEADER_DEF_GETTER(line_gap),
    TT_HORIHEADER_DEF_GETTER(advance_width_max),
    TT_HORIHEADER_DEF_GETTER(min_left_side_bearing),
    TT_HORIHEADER_DEF_GETTER(min_right_side_bearing),
    TT_HORIHEADER_DEF_GETTER(xmax_extent),
    TT_HORIHEADER_DEF_GETTER(caret_slope_rise),
    TT_HORIHEADER_DEF_GETTER(caret_slope_run),
    TT_HORIHEADER_DEF_GETTER(caret_offset),
    TT_HORIHEADER_DEF_GETTER(metric_data_format),
    TT_HORIHEADER_DEF_GETTER(number_of_hmetrics),
    {NULL}
};

/* TODO: hmtx table */

/****************************************************************************
 Setup
*/

static PyTypeObject Py_TT_HoriHeader_Type;

int setup_TT_HoriHeader(PyObject *m)
{
    memset(&Py_TT_HoriHeader_Type, 0, sizeof(PyTypeObject));
    Py_TT_HoriHeader_Type = (PyTypeObject) {
        .tp_name = "freetypy.TT_HoriHeader",
        .tp_basicsize = sizeof(Py_TT_HoriHeader),
        .tp_doc = doc_TT_HoriHeader__init__,
        .tp_getset = Py_TT_HoriHeader_getset,
        .tp_init = (initproc)Py_TT_HoriHeader_init,
    };

    ftpy_setup_type(m, &Py_TT_HoriHeader_Type);

    return 0;
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Lecanora atrosanguinea G. Merr.

### Remarks
null


text:
package org.apache.accumulo.core.client.mapred;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.BatchWriterConfig;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.Instance;
import org.apache.accumulo.core.client.MultiTableBatchWriter;
import org.apache.accumulo.core.client.MutationsRejectedException;
import org.apache.accumulo.core.client.TableExistsException;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.client.ZooKeeperInstance;
import org.apache.accumulo.core.client.mapreduce.lib.util.OutputConfigurator;
import org.apache.accumulo.core.client.mock.MockInstance;
import org.apache.accumulo.core.client.security.SecurityErrorCode;
import org.apache.accumulo.core.client.security.tokens.AuthenticationToken;
import org.apache.accumulo.core.data.ColumnUpdate;
import org.apache.accumulo.core.data.KeyExtent;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.security.ColumnVisibility;
import org.apache.accumulo.core.security.CredentialHelper;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.OutputFormat;
import org.apache.hadoop.mapred.RecordWriter;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.util.Progressable;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

/**
 * This class allows MapReduce jobs to use Accumulo as the sink for data. This {@link OutputFormat} accepts keys and values of type {@link Text} (for a table
 * name) and {@link Mutation} from the Map and Reduce functions.
 *
 * The user must specify the following via static configurator methods:
 *
 *

 *
{@link AccumuloOutputFormat#setConnectorInfo(JobConf, String, AuthenticationToken)}
 *
{@link AccumuloOutputFormat#setZooKeeperInstance(JobConf, String, String)} OR {@link AccumuloOutputFormat#setMockInstance(JobConf, String)}
 *

 *
 * Other static methods are optional.
 */
public class AccumuloOutputFormat implements OutputFormat<Text,Mutation> {

  private static final Class<?> CLASS = AccumuloOutputFormat.class;
  protected static final Logger log = Logger.getLogger(CLASS);

  /**
   * Sets the connector information needed to communicate with Accumulo in this job.
   *
   *

   * WARNING: The serialized token is stored in the configuration and shared with all MapReduce tasks. It is BASE64 encoded to provide a charset safe
   * conversion to a string, and is not intended to be secure.
   *
   * @param job
   *          the Hadoop job instance to be configured
   * @param principal
   *          a valid Accumulo user name (user must have Table.CREATE permission if {@link #setCreateTables(JobConf, boolean)} is set to true)
   * @param token
   *          the user's password
   * @throws AccumuloSecurityException
   * @since 1.5.0
   */
  public static void setConnectorInfo(JobConf job, String principal, AuthenticationToken token) throws AccumuloSecurityException {
    OutputConfigurator.setConnectorInfo(CLASS, job, principal, token);
  }

  /**
   * Determines if the connector has been configured.
   *
   * @param job
   *          the Hadoop context for the configured job
   * @return true if the connector has been configured, false otherwise
   * @since 1.5.0
   * @see #setConnectorInfo(JobConf, String, AuthenticationToken)
   */
  protected static Boolean isConnectorInfoSet(JobConf job) {
    return OutputConfigurator.isConnectorInfoSet(CLASS, job);
  }

  /**
   * Gets the principal from the configuration.
   *
   * @param job
   *          the Hadoop context for the configured job
   * @return the user name
   * @since 1.5.0
   * @see #setConnectorInfo(JobConf, String, AuthenticationToken)
   */
  protected static String getPrincipal(JobConf job) {
    return OutputConfigurator.getPrincipal(CLASS, job);
  }

  /**
   * Gets the serialized token class from the configuration.
   *
   * @param job
   *          the Hadoop context for the configured job
   * @return the user name
   * @since 1.5.0
   * @see #setConnectorInfo(JobConf, String, AuthenticationToken)
   */
  protected static String getTokenClass(JobConf job) {
    return OutputConfigurator.getTokenClass(CLASS, job);
  }

  /**
   * Gets the password from the configuration. WARNING: The password is stored in the Configuration and shared with all MapReduce tasks; It is BASE64 encoded to
   * provide a charset safe conversion to a string, and is not intended to be secure.
   *
   * @param job
   *          the Hadoop context for the configured job
   * @return the decoded user password
   * @since 1.5.0
   * @see #setConnectorInfo(JobConf, String, AuthenticationToken)
   */
  protected static byte[] getToken(JobConf job) {
    return OutputConfigurator.getToken(CLASS, job);
  }

  /**
   * Configures a {@link ZooKeeperInstance} for this job.
   *
   * @param job
   *          the Hadoop job instance to be configured
   * @param instanceName
   *          the Accumulo instance name
   * @param zooKeepers
   *          a comma-separated list of zookeeper servers
   * @since 1.5.0
   */
  public static void setZooKeeperInstance(JobConf job, String instanceName, String zooKeepers) {
    OutputConfigurator.setZooKeeperInstance(CLASS, job, instanceName, zooKeepers);
  }

  /**
   * Configures a {@link MockInstance} for this job.
   *
   * @param job
   *          the Hadoop job instance to be configured
   * @param instanceName
   *          the Accumulo instance name
   * @since 1.5.0
   */
  public static void setMockInstance(JobConf job, String instanceName) {
    OutputConfigurator.setMockInstance(CLASS, job, instanceName);
  }

  /**
   * Initializes an Accumulo {@link Instance} based on the configuration.
   *
   * @param job
   *          the Hadoop context for the configured job
   * @return an Accumulo instance
   * @since 1.5.0
   * @see #setZooKeeperInstance(JobConf, String, String)
   * @see #setMockInstance(JobConf, String)
   */
  protected static Instance getInstance(JobConf job) {
    return OutputConfigurator.getInstance(CLASS, job);
  }

  /**
   * Sets the log level for this job.
   *
   * @param job
   *          the Hadoop job instance to be configured
   * @param level
   *          the logging level
   * @since 1.5.0
   */
  public static void setLogLevel(JobConf job, Level level) {
    OutputConfigurator.setLogLevel(CLASS, job, level);
  }

  /**
   * Gets the log level from this configuration.
   *
   * @param job
   *          the Hadoop context for the configured job
   * @return the log level
   * @since 1.5.0
   * @see #setLogLevel(JobConf, Level)
   */
  protected static Level getLogLevel(JobConf job) {
    return OutputConfigurator.getLogLevel(CLASS, job);
  }

  /**
   * Sets the default table name to use if one emits a null in place of a table name for a given mutation. Table names can only be alpha-numeric and
   * underscores.
   *
   * @param job
   *          the Hadoop job instance to be configured
   * @param tableName
   *          the table to use when the tablename is null in the write call
   * @since 1.5.0
   */
  public static void setDefaultTableName(JobConf job, String tableName) {
    OutputConfigurator.setDefaultTableName(CLASS, job, tableName);
  }

  /**
   * Gets the default table name from the configuration.
   *
   * @param job
   *          the Hadoop context for the configured job
   * @return the default table name
   * @since 1.5.0
   * @see #setDefaultTableName(JobConf, String)
   */
  protected static String getDefaultTableName(JobConf job) {
    return OutputConfigurator.getDefaultTableName(CLASS, job);
  }

  /**
   * Sets the configuration for for the job's {@link BatchWriter} instances. If not set, a new {@link BatchWriterConfig}, with sensible built-in defaults is
   * used. Setting the configuration multiple times overwrites any previous configuration.
   *
   * @param job
   *          the Hadoop job instance to be configured
   * @param bwConfig
   *          the configuration for the {@link BatchWriter}
   * @since 1.5.0
   */
  public static void setBatchWriterOptions(JobConf job, BatchWriterConfig bwConfig) {
    OutputConfigurator.setBatchWriterOptions(CLASS, job, bwConfig);
  }

  /**
   * Gets the {@link BatchWriterConfig} settings.
   *
   * @param job
   *          the Hadoop context for the configured job
   * @return the configuration object
   * @since 1.5.0
   * @see #setBatchWriterOptions(JobConf, BatchWriterConfig)
   */
  protected static BatchWriterConfig getBatchWriterOptions(JobConf job) {
    return OutputConfigurator.getBatchWriterOptions(CLASS, job);
  }

  /**
   * Sets the directive to create new tables, as necessary. Table names can only be alpha-numeric and underscores.
   *
   *

   * By default, this feature is disabled.
   *
   * @param job
   *          the Hadoop job instance to be configured
   * @param enableFeature
   *          the feature is enabled if true, disabled otherwise
   * @since 1.5.0
   */
  public static void setCreateTables(JobConf job, boolean enableFeature) {
    OutputConfigurator.setCreateTables(CLASS, job, enableFeature);
  }

  /**
   * Determines whether tables are permitted to be created as needed.
   *
   * @param job
   *          the Hadoop context for the configured job
   * @return true if the feature is disabled, false otherwise
   * @since 1.5.0
   * @see #setCreateTables(JobConf, boolean)
   */
  protected static Boolean canCreateTables(JobConf job) {
    return OutputConfigurator.canCreateTables(CLASS, job);
  }

  /**
   * Sets the directive to use simulation mode for this job. In simulation mode, no output is produced. This is useful for testing.
   *
   *

   * By default, this feature is disabled.
   *
   * @param job
   *          the Hadoop job instance to be configured
   * @param enableFeature
   *          the feature is enabled if true, disabled otherwise
   * @since 1.5.0
   */
  public static void setSimulationMode(JobConf job, boolean enableFeature) {
    OutputConfigurator.setSimulationMode(CLASS, job, enableFeature);
  }

  /**
   * Determines whether this feature is enabled.
   *
   * @param job
   *          the Hadoop context for the configured job
   * @return true if the feature is enabled, false otherwise
   * @since 1.5.0
   * @see #setSimulationMode(JobConf, boolean)
   */
  protected static Boolean getSimulationMode(JobConf job) {
    return OutputConfigurator.getSimulationMode(CLASS, job);
  }

  /**
   * A base class to be used to create {@link RecordWriter} instances that write to Accumulo.
   */
  protected static class AccumuloRecordWriter implements RecordWriter<Text,Mutation> {
    private MultiTableBatchWriter mtbw = null;
    private HashMap<Text,BatchWriter> bws = null;
    private Text defaultTableName = null;

    private boolean simulate = false;
    private boolean createTables = false;

    private long mutCount = 0;
    private long valCount = 0;

    private Connector conn;

    protected AccumuloRecordWriter(JobConf job) throws AccumuloException, AccumuloSecurityException, IOException {
      Level l = getLogLevel(job);
      if (l != null)
        log.setLevel(getLogLevel(job));
      this.simulate = getSimulationMode(job);
      this.createTables = canCreateTables(job);

      if (simulate)
        log.info("Simulating output only. No writes to tables will occur");

      this.bws = new HashMap<Text,BatchWriter>();

      String tname = getDefaultTableName(job);
      this.defaultTableName = (tname == null) ? null : new Text(tname);

      if (!simulate) {
        this.conn = getInstance(job).getConnector(getPrincipal(job), CredentialHelper.extractToken(getTokenClass(job), getToken(job)));
        mtbw = conn.createMultiTableBatchWriter(getBatchWriterOptions(job));
      }
    }

    /**
     * Push a mutation into a table. If table is null, the defaultTable will be used. If canCreateTable is set, the table will be created if it does not exist.
     * The table name must only contain alphanumerics and underscore.
     */
    @Override
    public void write(Text table, Mutation mutation) throws IOException {
      if (table == null || table.toString().isEmpty())
        table = this.defaultTableName;

      if (!simulate && table == null)
        throw new IOException("No table or default table specified. Try simulation mode next time");

      ++mutCount;
      valCount += mutation.size();
      printMutation(table, mutation);

      if (simulate)
        return;

      if (!bws.containsKey(table))
        try {
          addTable(table);
        } catch (Exception e) {
          e.printStackTrace();
          throw new IOException(e);
        }

      try {
        bws.get(table).addMutation(mutation);
      } catch (MutationsRejectedException e) {
        throw new IOException(e);
      }
    }

    public void addTable(Text tableName) throws AccumuloException, AccumuloSecurityException {
      if (simulate) {
        log.info("Simulating adding table: " + tableName);
        return;
      }

      log.debug("Adding table: " + tableName);
      BatchWriter bw = null;
      String table = tableName.toString();

      if (createTables && !conn.tableOperations().exists(table)) {
        try {
          conn.tableOperations().create(table);
        } catch (AccumuloSecurityException e) {
          log.error("Accumulo security violation creating " + table, e);
          throw e;
        } catch (TableExistsException e) {
          // Shouldn't happen
        }
      }

      try {
        bw = mtbw.getBatchWriter(table);
      } catch (TableNotFoundException e) {
        log.error("Accumulo table " + table + " doesn't exist and cannot be created.", e);
        throw new AccumuloException(e);
      } catch (AccumuloException e) {
        throw e;
      } catch (AccumuloSecurityException e) {
        throw e;
      }

      if (bw != null)
        bws.put(tableName, bw);
    }

    private int printMutation(Text table, Mutation m) {
      if (log.isTraceEnabled()) {
        log.trace(String.format("Table %s row key: %s", table, hexDump(m.getRow())));
        for (ColumnUpdate cu : m.getUpdates()) {
          log.trace(String.format("Table %s column: %s:%s", table, hexDump(cu.getColumnFamily()), hexDump(cu.getColumnQualifier())));
          log.trace(String.format("Table %s security: %s", table, new ColumnVisibility(cu.getColumnVisibility()).toString()));
          log.trace(String.format("Table %s value: %s", table, hexDump(cu.getValue())));
        }
      }
      return m.getUpdates().size();
    }

    private String hexDump(byte[] ba) {
      StringBuilder sb = new StringBuilder();
      for (byte b : ba) {
        if ((b > 0x20) && (b < 0x7e))
          sb.append((char) b);
        else
          sb.append(String.format("x%02x", b));
      }
      return sb.toString();
    }

    @Override
    public void close(Reporter reporter) throws IOException {
      log.debug("mutations written: " + mutCount + ", values written: " + valCount);
      if (simulate)
        return;

      try {
        mtbw.close();
      } catch (MutationsRejectedException e) {
        if (e.getAuthorizationFailuresMap().size() >= 0) {
          HashMap<String,Set<SecurityErrorCode>> tables = new HashMap<String,Set<SecurityErrorCode>>();
          for (Entry<KeyExtent,Set<SecurityErrorCode>> ke : e.getAuthorizationFailuresMap().entrySet()) {
            Set<SecurityErrorCode> secCodes = tables.get(ke.getKey().getTableId().toString());
            if (secCodes == null) {
              secCodes = new HashSet<SecurityErrorCode>();
              tables.put(ke.getKey().getTableId().toString(), secCodes);
            }
            secCodes.addAll(ke.getValue());
          }

          log.error("Not authorized to write to tables : " + tables);
        }

        if (e.getConstraintViolationSummaries().size() > 0) {
          log.error("Constraint violations : " + e.getConstraintViolationSummaries().size());
        }
      }
    }
  }

  @Override
  public void checkOutputSpecs(FileSystem ignored, JobConf job) throws IOException {
    if (!isConnectorInfoSet(job))
      throw new IOException("Connector info has not been set.");
    try {
      // if the instance isn't configured, it will complain here
      Connector c = getInstance(job).getConnector(getPrincipal(job), CredentialHelper.extractToken(getTokenClass(job), getToken(job)));
      if (!c.securityOperations().authenticateUser(getPrincipal(job), CredentialHelper.extractToken(getTokenClass(job), getToken(job))))
        throw new IOException("Unable to authenticate user");
    } catch (AccumuloException e) {
      throw new IOException(e);
    } catch (AccumuloSecurityException e) {
      throw new IOException(e);
    }
  }

  @Override
  public RecordWriter<Text,Mutation> getRecordWriter(FileSystem ignored, JobConf job, String name, Progressable progress) throws IOException {
    try {
      return new AccumuloRecordWriter(job);
    } catch (Exception e) {
      throw new IOException(e);
    }
  }

}


text:
bootstrap-select
================

A custom select for @twitter bootstrap using button dropdown, designed to behave like regular Bootstrap selects;
originally by [Silvio Moreto](http://github.com/silviomoreto) and [Ana Carolina](http://github.com/anacarolinats).
 See an [example](http://caseyjhol.github.com/bootstrap-select/).
# Usage

Create your `<select>` with the `.selectpicker` class.

    <select class="selectpicker">
      <option>Mustard</select>
      <option>Ketchup</select>
      <option>Barbecue</select>
    </select>

Enable Bootstrap-Select via JavaScript:

    $('.selectpicker').selectpicker();

Or just

    $('select').selectpicker();

Options can be passed via data attributes or JavaScript.

    $('.selectpicker').selectpicker({
      style: 'btn-info',
      size: 4
    });

You can set different Bootstrap classes on the button via the `data-style` attribute. Classes are applied to `.btn-group`.Apply `.span*` class to the selects to set the width. Add the `disabled` attribute to the select to apply the `.disabled` class. The `size` option is set to `'auto'` by default. When `size` is set to `'auto'`, the menu always opens up to show as many items as the window will allow without being cut off. Set `size` to `false` to always show all items. The size of the menu can also be specifed using the `data-size` attribute. Specify a number for `data-size` to choose the maximum number of items to show in the menu. Make the select a dropup menu by adding the `.dropup` class to the select.


text:
<select name="<?php echo $fieldname; ?>" id="">
    <?php foreach($option->getShopOptionValue() as $value): ?>
        <option value="<?php echo $value->getId() ?>" <?php echo ($product->checkValue($value->getId()))?'selected':''; ?>><?php echo $value ?></option>
    <?php endforeach; ?>
</select>


text:
package com.ztemt.test.mtbf;

import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.uiautomator.core.UiObject;
import com.android.uiautomator.core.UiObjectNotFoundException;
import com.android.uiautomator.core.UiSelector;

/**
 * 下载图片文件并打开
 * 循环次数:5
 * @author 0016001973
 *
 */
public class Cer_MTBF_11 extends Cer_MTBF_Browser implements UiAutomatorTestable {

    @Override
    public void test() throws UiObjectNotFoundException {
        loop(5);
    }

    @Override
    protected void execute() throws UiObjectNotFoundException {
        super.execute();

        // 设置允许加载图片
        setLoadPicture();

        // 下载指定图片文件
        load("testplat.server.ztemt.com.cn/resource/Picture.jpg");

        // 断言图片显示
        UiObject picture = new UiObject(new UiSelector().descriptionStartsWith(
                "Picture.jpg"));
        assertTrue("Unable to load picture", picture.waitForExists(8000));

        // 退出浏览器
        exit();
    }

    protected void setLoadPicture() throws UiObjectNotFoundException {
        // 点击更多按钮
        showMore();

        // 选择设置
        UiObject settings = new UiObject(new UiSelector().resourceId(
                "android:id/title").text("设置"));
        settings.clickAndWaitForNewWindow();

        // 选择带宽管理
        UiObject privacy = new UiObject(new UiSelector().resourceId(
                "android:id/title").text("带宽管理"));
        privacy.clickAndWaitForNewWindow();

        // 勾选加载图片
        UiObject list = new UiObject(new UiSelector().className(ListView.class));
        for (int i = 0; i < list.getChildCount(); i++) {
            UiObject ll = list.getChild(new UiSelector().className(
                    LinearLayout.class).index(i));
            UiObject tv = ll.getChild(new UiSelector()
                    .className(TextView.class).index(0));
            if (tv.getText().equals("加载图片")) {
                UiObject enable = ll.getChild(new UiSelector().resourceId(
                        "android:id/checkbox"));
                if (enable.isCheckable() && !enable.isChecked()) {
                    enable.click();
                }
                break;
            }
        }

        // 返回浏览界面
        getUiDevice().pressBack();
        getUiDevice().pressBack();
    }
}


text:
package io.jcoder.tutorials.ch05.declaration;

/**
 * Example class used to show different access level modifiers in Java.
 *
 * <p>
 * https://jcoder.io/content/course/java/beginners/ch05/declaration1
 * </p>
 *
 * @author Camilo Gonzalez
 */
public class JavaClassDeclarationApp {

    public static void main(String[] args) {
        Light bedroomLight = new Light();
        bedroomLight.printLightDetails();

        Light studioLight = new Light(true, "YELLOW");
        studioLight.printLightDetails();

        studioLight.setPower(100);
    }

}


text:
<?php

/**
 * This file is part of the Spryker Demoshop.
 * For full license information, please view the LICENSE file that was distributed with this source code.
 */

namespace Pyz\Zed\Url;

use Spryker\Zed\Navigation\Communication\Plugin\DetachNavigationUrlAfterUrlDeletePlugin;
use Spryker\Zed\Navigation\Communication\Plugin\TouchNavigationAfterUrlUpdatePlugin;
use Spryker\Zed\Url\UrlDependencyProvider as SprykerUrlDependencyProvider;

class UrlDependencyProvider extends SprykerUrlDependencyProvider
{
    /**
     * @return \Spryker\Zed\Url\Dependency\Plugin\UrlUpdatePluginInterface[]
     */
    protected function getUrlAfterUpdatePlugins()
    {
        return [
            new TouchNavigationAfterUrlUpdatePlugin(),
        ];
    }

    /**
     * @return \Spryker\Zed\Url\Dependency\Plugin\UrlDeletePluginInterface[]
     */
    protected function getUrlBeforeDeletePlugins()
    {
        return [
            new DetachNavigationUrlAfterUrlDeletePlugin(),
        ];
    }
}


text:
import freedomMocker = require('../freedom/mocks/mock-freedom-in-module-env');
declare var freedom: freedom.FreedomInModuleEnv;
freedom = freedomMocker.makeMockFreedomInModuleEnv();

import arraybuffers = require('../arraybuffers/arraybuffers');
import peerconnection = require('../webrtc/peerconnection');
import signals = require('../webrtc/signals');
import handler = require('../handler/queue');

import rtc_to_net = require('./rtc-to-net');
import net = require('../net/net.types');
import tcp = require('../net/tcp');
import socks = require('../socks-common/socks-headers');

import logging = require('../logging/logging');

import ProxyConfig = require('./proxyconfig');

var log :logging.Log = new logging.Log('socks-to-rtc spec');

var mockBoundEndpoint :net.Endpoint = {
  address: '127.0.0.1',
  port: 1234
};

var voidPromise = Promise.resolve<void>();

var mockProxyConfig :ProxyConfig = {
  allowNonUnicast: false
};

var mockRemoteEndpoint :net.Endpoint = {
  // This address and port are both reserved for testing.
  address: '192.0.2.111',
  port: 1023
};

var mockConnectionInfo :tcp.ConnectionInfo = {
  bound: mockBoundEndpoint,
  remote: mockRemoteEndpoint
};

// Neither fulfills nor rejects.
// Useful in a bunch of tests where a promise must be returned
// for chaining purposes.
var noopPromise = new Promise<any>((F, R) => {});

describe('RtcToNet', function() {
  var server :rtc_to_net.RtcToNet;

  var mockPeerconnection
      :peerconnection.PeerConnection<signals.Message>;

  beforeEach(function() {
    server = new rtc_to_net.RtcToNet();

    mockPeerconnection = <any>{
      dataChannels: {},
      negotiateConnection: jasmine.createSpy('negotiateConnection'),
      onceConnected: noopPromise,
      onceClosed: noopPromise,
      peerOpenedChannelQueue: new handler.Queue(),
      close: jasmine.createSpy('close')
    };
  });

  it('onceReady fulfills on peerconnection success', (done) => {
    mockPeerconnection.onceConnected = voidPromise;
    // We're not testing termination.

    server.start(mockProxyConfig, mockPeerconnection).then(done);
  });

  it('onceReady rejects on peerconnection setup failure', (done) => {
    mockPeerconnection.onceConnected =
        Promise.reject(new Error('failed to establish connection'));
    // We're not testing termination.

    server.start(mockProxyConfig, mockPeerconnection).catch(done);
  });

  it('onceStopped fulfills on peerconnection termination', (done) => {
    mockPeerconnection.onceConnected = voidPromise;
    mockPeerconnection.onceClosed = <any>Promise.resolve();

    server.start(mockProxyConfig, mockPeerconnection)
      .then(() => { return server.onceStopped; })
      .then(done);
  });

  it('onceStopped fulfills on call to stop', (done) => {
    mockPeerconnection.onceConnected = voidPromise;
    // Calling stop() alone should be sufficient to initiate shutdown.

    server.start(mockProxyConfig, mockPeerconnection)
      .then(server.stop)
      .then(() => { return server.onceStopped; })
      .then(done);
  });
});

describe('RtcToNet session', function() {
  var session :rtc_to_net.Session;

  var mockTcpConnection :tcp.Connection;
  var mockDataChannel :peerconnection.DataChannel;
  var mockDataFromPeerQueue :handler.Queue<peerconnection.Data,void>;
  var mockBytesReceived :handler.Queue<number,void>;
  var mockBytesSent :handler.Queue<number,void>;

  beforeEach(function() {
    mockTcpConnection = jasmine.createSpyObj('tcp connection', [
        'onceConnected',
        'onceClosed',
        'isClosed',
        'close',
        'send',
        'pause',
        'resume'
      ]);
    (<any>mockTcpConnection.send).and.returnValue(Promise.resolve({ bytesWritten: 1 }));
    mockTcpConnection.dataFromSocketQueue = new handler.Queue<ArrayBuffer,void>();
    mockDataFromPeerQueue = new handler.Queue<peerconnection.Data,void>();

    mockDataChannel = <any>{
      close: jasmine.createSpy('close'),
      closeDataChannel: noopPromise,
      dataFromPeerQueue: mockDataFromPeerQueue,
      getLabel: jasmine.createSpy('getLabel'),
      onceClosed: noopPromise,
      send: jasmine.createSpy('send'),
      isInOverflow: jasmine.createSpy('isInOverflow').and.returnValue(false),
      setOverflowListener: jasmine.createSpy('setOverflowListener')
    };
    (<any>mockDataChannel.send).and.returnValue(voidPromise);

    mockBytesReceived = new handler.Queue<number, void>();
    mockBytesSent = new handler.Queue<number, void>();
    session = new rtc_to_net.Session(
        mockDataChannel,
        mockProxyConfig,
        mockBytesReceived,
        mockBytesSent);
  });

  it('onceReady fulfills with listening endpoint on successful negotiation', (done) => {
    spyOn(session, 'receiveEndpointFromPeer_').and.returnValue(Promise.resolve(mockRemoteEndpoint));
    spyOn(session, 'replyToPeer_').and.returnValue(Promise.resolve());
    spyOn(session, 'getTcpConnection_').and.returnValue(Promise.resolve(mockTcpConnection));

    mockTcpConnection.onceConnected = Promise.resolve(mockConnectionInfo);
    mockTcpConnection.onceClosed = noopPromise;

    session.start().then(done);
  });

  it('onceReady rejects and onceStopped fulfills on unsuccessful endpoint negotiation', (done) => {
    spyOn(session, 'receiveEndpointFromPeer_').and.returnValue(Promise.reject(new Error('bad format')));
    spyOn(session, 'replyToPeer_').and.returnValue(Promise.resolve());
    spyOn(session, 'getTcpConnection_').and.returnValue(Promise.resolve(mockTcpConnection));

    mockTcpConnection.onceConnected = Promise.resolve(mockConnectionInfo);
    mockTcpConnection.onceClosed = noopPromise;

    session.start().catch(session.onceStopped).then(done);
  });

  it('onceStopped fulfills on datachannel termination', (done) => {
    spyOn(session, 'receiveEndpointFromPeer_').and.returnValue(Promise.resolve(mockRemoteEndpoint));
    spyOn(session, 'replyToPeer_').and.returnValue(Promise.resolve());
    spyOn(session, 'getTcpConnection_').and.returnValue(Promise.resolve(mockTcpConnection));

    mockTcpConnection.onceConnected = Promise.resolve(mockConnectionInfo);
    mockTcpConnection.onceClosed = noopPromise;
    mockDataChannel.onceClosed = Promise.resolve<void>();

    session.start().then(session.onceStopped).then(done);
  });

  it('onceStopped fulfills on TCP connection termination', (done) => {
    spyOn(session, 'receiveEndpointFromPeer_').and.returnValue(Promise.resolve(mockRemoteEndpoint));
    spyOn(session, 'replyToPeer_').and.returnValue(Promise.resolve());
    spyOn(session, 'getTcpConnection_').and.returnValue(Promise.resolve(mockTcpConnection));

    mockTcpConnection.onceConnected = Promise.resolve(mockConnectionInfo);
    mockTcpConnection.onceClosed = Promise.resolve(tcp.SocketCloseKind.WE_CLOSED_IT);

    session.start().then(session.onceStopped).then(done);
  });

  it('onceStopped fulfills on call to stop', (done) => {
    spyOn(session, 'receiveEndpointFromPeer_').and.returnValue(Promise.resolve(mockRemoteEndpoint));
    spyOn(session, 'replyToPeer_').and.returnValue(Promise.resolve());
    spyOn(session, 'getTcpConnection_').and.returnValue(Promise.resolve(mockTcpConnection));

    mockTcpConnection.onceConnected = Promise.resolve(mockConnectionInfo);
    mockTcpConnection.onceClosed = noopPromise;

    session.start().then(session.stop).then(session.onceStopped).then(done);
  });

  it('bytes sent counter', (done) => {
    spyOn(session, 'receiveEndpointFromPeer_').and.returnValue(Promise.resolve(mockRemoteEndpoint));
    spyOn(session, 'replyToPeer_').and.returnValue(Promise.resolve());
    spyOn(session, 'getTcpConnection_').and.returnValue(Promise.resolve(mockTcpConnection));

    mockTcpConnection.onceConnected = Promise.resolve(mockConnectionInfo);
    mockTcpConnection.onceClosed = noopPromise;

    var buffer = new Uint8Array([1,2,3]).buffer;
    session.start().then(() => {
      mockTcpConnection.dataFromSocketQueue.handle(buffer);
    });
    mockBytesSent.setSyncNextHandler((numBytes:number) => {
      expect(numBytes).toEqual(buffer.byteLength);
      done();
    });
  });

  it('bytes received counter', (done) => {
    spyOn(session, 'receiveEndpointFromPeer_').and.returnValue(Promise.resolve(mockRemoteEndpoint));
    spyOn(session, 'replyToPeer_').and.returnValue(Promise.resolve());
    spyOn(session, 'getTcpConnection_').and.returnValue(Promise.resolve(mockTcpConnection));

    mockTcpConnection.onceConnected = Promise.resolve(mockConnectionInfo);
    mockTcpConnection.onceClosed = noopPromise;

    var message :peerconnection.Data = {
      buffer: new Uint8Array([1,2,3]).buffer
    };
    session.start().then(() => {
      mockDataFromPeerQueue.handle(message);
    });
    mockBytesReceived.setSyncNextHandler((numBytes:number) => {
      expect(numBytes).toEqual(message.buffer.byteLength);
      done();
    });
  });

  it('channel queue drains before termination', (done) => {
    spyOn(session, 'receiveEndpointFromPeer_').and.returnValue(Promise.resolve(mockRemoteEndpoint));
    spyOn(session, 'replyToPeer_').and.returnValue(Promise.resolve());
    spyOn(session, 'getTcpConnection_').and.returnValue(Promise.resolve(mockTcpConnection));

    mockTcpConnection.onceConnected = Promise.resolve(mockConnectionInfo);
    mockTcpConnection.onceClosed = noopPromise;

    // The data channel is closed before the session starts.
    mockDataChannel.onceClosed = voidPromise;

    var message :peerconnection.Data = {
      buffer: new Uint8Array([1,2,3]).buffer
    };
    var onceMessageHandled = mockDataFromPeerQueue.handle(message);

    session.start().then(session.onceStopped).then(() => {
      return onceMessageHandled;
    }).then(() => {
      expect(mockDataChannel.dataFromPeerQueue.getLength()).toEqual(0);
      done();
    });
  });

  it('socket queue drains before termination', (done) => {
    spyOn(session, 'receiveEndpointFromPeer_').and.returnValue(Promise.resolve(mockRemoteEndpoint));
    spyOn(session, 'replyToPeer_').and.returnValue(Promise.resolve());
    spyOn(session, 'getTcpConnection_').and.returnValue(Promise.resolve(mockTcpConnection));

    // The TCP connection is closed before the session starts.
    mockTcpConnection.onceConnected = Promise.resolve(mockConnectionInfo);
    mockTcpConnection.onceClosed = Promise.resolve(tcp.SocketCloseKind.WE_CLOSED_IT);
    (<any>mockTcpConnection.isClosed).and.returnValue(true);

    var buffer = new Uint8Array([1,2,3]).buffer;
    var onceMessageHandled = mockTcpConnection.dataFromSocketQueue.handle(buffer);

    session.start().then(session.onceStopped).then(() => {
      return onceMessageHandled;
    }).then(() => {
      expect(mockTcpConnection.dataFromSocketQueue.getLength()).toEqual(0);
      done();
    });
  });

  it('backpressure', (done) => {
    spyOn(session, 'receiveEndpointFromPeer_').and.returnValue(Promise.resolve(mockRemoteEndpoint));
    spyOn(session, 'replyToPeer_').and.returnValue(Promise.resolve());
    spyOn(session, 'getTcpConnection_').and.returnValue(Promise.resolve(mockTcpConnection));

    mockTcpConnection.onceConnected = Promise.resolve(mockConnectionInfo);
    mockTcpConnection.onceClosed = noopPromise;

    var overflowListener :(overflow:boolean) => void;
    mockDataChannel.setOverflowListener = (listener) => { overflowListener = listener; };

    var buffer = new Uint8Array([1,2,3]).buffer;

    // Messages received before start sit in the TCP receive queue.
    mockTcpConnection.dataFromSocketQueue.handle(buffer);
    expect(mockTcpConnection.dataFromSocketQueue.getLength()).toEqual(1);
    expect(mockDataChannel.send).not.toHaveBeenCalled();

    session.start().then(() => {
      // After start, the TCP queue should be drained into the datachannel.
      expect(mockTcpConnection.dataFromSocketQueue.getLength()).toEqual(0);
      expect(mockDataChannel.send).toHaveBeenCalled();

      // After draining the queue, the TCP connection should be resumed.
      expect(mockTcpConnection.pause).not.toHaveBeenCalled();
      expect(mockTcpConnection.resume).toHaveBeenCalled();

      // Enter overflow state.  This should trigger a call to pause.
      overflowListener(true);
      expect(mockTcpConnection.pause).toHaveBeenCalled();

      // In the paused state, messages are still forwarded
      mockTcpConnection.dataFromSocketQueue.handle(buffer);
      expect(mockTcpConnection.dataFromSocketQueue.getLength()).toEqual(0);
      expect((<any>mockDataChannel.send).calls.count()).toEqual(2);

      // Exit overflow state.  This should trigger a call to resume.
      overflowListener(false);
      expect((<any>mockTcpConnection.resume).calls.count()).toEqual(2);

      done();
    });
  });

  it('backpressure with early flood', (done) => {
    spyOn(session, 'receiveEndpointFromPeer_').and.returnValue(Promise.resolve(mockRemoteEndpoint));
    spyOn(session, 'replyToPeer_').and.returnValue(Promise.resolve());
    spyOn(session, 'getTcpConnection_').and.returnValue(Promise.resolve(mockTcpConnection));

    mockTcpConnection.onceConnected = Promise.resolve(mockConnectionInfo);
    mockTcpConnection.onceClosed = noopPromise;

    var overflowListener :(overflow:boolean) => void;
    mockDataChannel.setOverflowListener = (listener) => { overflowListener = listener; };
    mockDataChannel.isInOverflow = <any>jasmine.createSpy('isInOverflow').and.returnValue(true);

    var buffer = new Uint8Array([1,2,3]).buffer;

    // Messages received before start sit in the TCP receive queue.
    mockTcpConnection.dataFromSocketQueue.handle(buffer);
    expect(mockTcpConnection.dataFromSocketQueue.getLength()).toEqual(1);
    expect(mockDataChannel.send).not.toHaveBeenCalled();

    session.start().then(() => {
      // After start, the TCP queue should be drained into the datachannel.
      expect(mockTcpConnection.dataFromSocketQueue.getLength()).toEqual(0);
      expect(mockDataChannel.send).toHaveBeenCalled();

      // If the initial queue is enough to trigger overflow, then the
      // socket should not be resumed.
      expect(mockTcpConnection.pause).not.toHaveBeenCalled();
      expect(mockTcpConnection.resume).not.toHaveBeenCalled();

      // Exit overflow state.  This should trigger a call to resume.
      overflowListener(false);
      expect(mockTcpConnection.resume).toHaveBeenCalled();

      done();
    });
  });
});


text:
<?php

/**
 * iframe actions.
 *
 * @package    site_cms
 * @subpackage iframeDisplay
 * @author     Jo Carter
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class iframeDisplayActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
    $sitetree = siteManager::getInstance()->initCurrentSitetreeNode();
    $iframe   = IframeTable::getInstance()->findOneBySitetreeId($sitetree->id);

    $this->forward404Unless($iframe, 'No iframe info found');
    $this->forward404Unless((!empty($iframe->url) || !empty($iframe->file_name)), 'No target set for iframe');

    $this->iframeTarget = $iframe->url;

    if (empty($this->iframeTarget))
    {
      $this->iframeTarget = $this->generateUrl(str_replace('@','',siteManager::getInstance()->getRoutingProxy()->generateInternalUrl($sitetree, 'render')));
    }

    $this->setLayout($iframe->layout);

    $this->setVar('sitetree', $sitetree, true);
  }

  /**
   * Render file contents into a page for iframe
   *
   * @param sfWebRequest $request
   */
  public function executeRender(sfWebRequest $request)
  {
    $sitetree = siteManager::getInstance()->initCurrentSitetreeNode();
    $iframe   = IframeTable::getInstance()->findOneBySitetreeId($sitetree->id);

    $this->forward404Unless($iframe, 'No iframe found');

    $config   = sfConfig::get('app_site_iframe', array());
    $location = $config['folder'];
    $fileName = $location . DIRECTORY_SEPARATOR . $iframe->file_name;

    $this->forward404Unless(is_file($fileName), 'File no longer exists');

    $content = file_get_contents($fileName);

    // Check whether in iframe - need to inject some javascript
    $sitetreeUrl = $this->generateUrl($sitetree->route_name, array(), true);
    $js          = <<<EOF
    <script type="text/javascript">
      if (parent.location.href === window.location.href) window.location.href = '$sitetreeUrl';
    </script>
EOF;
    $content = str_ireplace('<body>', "<body>\n".$js."\n", $content);

    sfConfig::set('sf_web_debug', false);

    return $this->renderText($content);
  }
}


text:
import urllib
import json
import os
import twilio.twiml
from flask import Flask
from flask import jsonify
from flask import url_for
from flask import request
from flask import make_response
from twilio.rest import TwilioRestClient

# Flask app should start in global layout
app = Flask(__name__)

# Entry to webhook from Api.ai
@app.route('/webhook', methods=['POST'])
def webhook():
	req = request.get_json(silent=True, force=True)
	print("Request:")
	print(json.dumps(req, indent=4))
	res = processRequest(req)
	res = json.dumps(res, indent=4)
    	# print(res)
	r = make_response(res)
	r.headers['Content-Type'] = 'application/json'
	return r

def processRequest(req):
	result = req.get("result")
	metadata = result.get("metadata")
	intentname = metadata.get("intentName")
	parameters = result.get("parameters")
	actionname = parameters.get("action")
	accounttype = parameters.get("type")
	accountNo = parameters.get("account")
	phoneNo = parameters.get("phonenumber")
	Savingsbalance = getSavingsAccountBalance(accountNo)
	Checkingbalance = getCheckingAccountBalance(accountNo)
	Dueamount = getDueAmount(accountNo)
	Lasttransactions = getLastTransactions(accountNo)

	if intentname == "Balance_amount":

    		if accounttype == "Savings":
			speech = "Your balance is " + Savingsbalance + " dollars"
			#message = client.messages.create(to="+919840610434", from_="+12014307839", body="Your balance is " + Savingsbalance + " dollars")
		else:
            		speech = "Your balance is " + Checkingbalance + " dollars"
	elif intentname == "Due_amount":
		speech = "Your due amount is " + Dueamount + " dollars"
	elif intentname == "Last_transactions":
		speech = "Your last 5 transactions are " + Lasttransactions
	elif intentname == "Reach_ivr":
		speech = "You will be receiving a call to this number shortly"
		client =  TwilioRestClient(os.environ.get('TWILIO_ACCOUNT_SID'), os.environ.get('TWILIO_AUTH_TOKEN'))
		client.calls.create(from_=os.environ.get('TWILIO_NUMBER'), to=phoneNo, url="http://outboundclik.herokuapp.com/outbound")

	else:
		speech  = "Our deposit interest rates are available at www.abcbank.com/deposit/rates"

	return {
	"speech": speech,
	"displayText": speech,
	# "data": data,
	# "contextOut": [],
	"source": "apiai-account-sample"
	}
	return res

def getSavingsAccountBalance(accountNo):
	accounts = {}
    	accounts['123456'] = "100"
    	accounts['654321'] = "200"
    	accounts['111111'] = "111"
    	accounts['222222'] = "222"
    	accounts['333333'] = "333"
    	accounts['444444'] = "444"

	if accountNo in accounts:
		return accounts[accountNo]
	else:
		return "0"

def getCheckingAccountBalance(accountNo1):
	accounts1 = {}
    	accounts1['666666'] = "500"
    	accounts1['777777'] = "600"
    	accounts1['888888'] = "700"
    	accounts1['999999'] = "800"
    	accounts1['555555'] = "900"
    	accounts1['246810'] = "1000"

	if accountNo1 in accounts1:
		return accounts1[accountNo1]
	else:
		return "0"

def getDueAmount(accountNo2):
	accounts2 = {}
	accounts2['454545'] = "400"
	accounts2['565656'] = "500"
	accounts2['676767'] = "8500"
	accounts2['787878'] = "870"
	accounts2['898989'] = "760"
	accounts2['909090'] = "1500"

	if accountNo2 in accounts2:
		return accounts2[accountNo2]
	else:
		return "0"

def getLastTransactions(accountNo3):
	accounts3 = {}
	accounts3['123456'] = "$35 at Target, $45 at Macdonalds, $120 at Home Depot, $500 at Amazon, $1500 at United Airlines"
	accounts3['654321'] = "$85 at Costco, $35 at KFC, $150 at Lowes, $600 at Ebay, $120 at Holiday Inn"

	if accountNo3 in accounts3:
		return accounts3[accountNo3]
	else:
		return "0"

if __name__ == '__main__':
	port = int(os.getenv('PORT', 5000))
	print "Starting app on port %d" % port
	app.run(debug=False, port=port, host='0.0.0.0')


text:
package org.kaazing.k3po.driver.internal.behavior.handler.command;

import static org.kaazing.k3po.driver.internal.netty.channel.Channels.abortInput;

import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandlerContext;

public class ReadAbortHandler extends AbstractCommandHandler {

    @Override
    protected void invokeCommand(ChannelHandlerContext ctx) throws Exception {

        ChannelFuture handlerFuture = getHandlerFuture();
        abortInput(ctx, handlerFuture);
    }

    @Override
    protected StringBuilder describe(StringBuilder sb) {
        return sb.append("read abort");
    }

}


text:
<?php

namespace Ovh\License\Worklight;

use Ovh\Common\Exception\NotImplementedYetException;
use Ovh\Common\Exception\NotImplementedYetByOvhException;
use Ovh\Common\Ovh;
use Ovh\License\Worklight\WorklightClient;
use Ovh\Common\Task;

class Worklight
{
	private $domain = null;
	private static $WorklightClient = null;

	/**
	 * @param string $domain
	 */
	public function __construct($domain)
	{
		$this->setDomain($domain);
	}

	/**
	 * Return Worklight client
	 *
	 * @return null|WorklightClient
	 */
	private static function getClient()
	{
		if (!self::$WorklightClient instanceof WorklightClient){
			self::$WorklightClient=new WorklightClient();
		};
		return self::$WorklightClient;
	}

	/**
	 * Set domain
	 *
	 * @param string $domain
	 */
	public function setDomain($domain)
	{
		$this->domain = $domain;
	}

	/**
	 * Get domain
	 *
	 * @return null | string domain
	 */
	public function getDomain()
	{
		return $this->domain;
	}

	###
	# Mains methods from OVH Rest API
	##
	/**
	 *  Get Orderable Versions
	 *
	 *  @param  ip - Ip on which to placel license
	 *  @return object
	 *
	*/
	public function getOrderableVersions($ip){
        return json_decode(self::getClient()->getProperties($this->getDomain(),$ip));
    }

    /**
	 *  Get Properties of supplied licence
	 *
	 *  @return object
	 *
	*/
	public function getProperties(){
        return json_decode(self::getClient()->getProperties($this->getDomain()));
    }
}


text:
<?php

namespace HipsterJazzbo\Telegraph\Laravel;

use HipsterJazzbo\Telegraph\Push;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;

class TelegraphServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $configPath = function_exists('config_path') ? config_path('telegraph.php') : 'telegraph.php';

        $this->publishes([
            realpath(__DIR__ . '/../../config/telegraph.php') => $configPath
        ]);
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(Push::class, function (Application $app) {
            $config = $app['config']->get('telegraph');

            $serviceConfigs = array_get($config, 'services', []);
            $strict  = array_get($config, 'strict', false);

            return new Push($serviceConfigs, $strict);
        });
    }
}


text:
<?php

namespace Flavordex\Exception;

/**
 * Exception to report a 500 Internal Server Error error.
 *
 * @author Steve Guidetti
 */
class InternalErrorException extends HttpException {

    /**
     * @param string $message The error message
     */
    public function __construct($message = null) {
        parent::__construct('Internal Server Error', 500, $message);
    }

}


text:
/**
 * Internal dependencies
 */
import Chip from './Chip';

const Template = ( args ) => <Chip { ...args } />;

export const DefaultChip = Template.bind( {} );
DefaultChip.storyName = 'Default Chip';
DefaultChip.args = {
	id: 'default',
	label: 'Default Chip',
};

export const SelectedChip = Template.bind( {} );
SelectedChip.storyName = 'Selected Chip';
SelectedChip.args = {
	id: 'selected',
	label: 'Selected Chip',
	selected: true,
};

export default {
	title: 'Components/Chip',
	component: Chip,
};


text:
package org.apache.activemq.protobuf;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public interface Message<T> {

    public T clone() throws CloneNotSupportedException;

    public int serializedSizeUnframed();

    public int serializedSizeFramed();

    public void clear();

    public T assertInitialized() throws UninitializedMessageException;

    public T mergeFrom(T other);

    public T mergeUnframed(byte[] data) throws InvalidProtocolBufferException;

    public T mergeFramed(byte[] data) throws InvalidProtocolBufferException;

    public T mergeUnframed(Buffer buffer) throws InvalidProtocolBufferException;

    public T mergeFramed(Buffer buffer) throws InvalidProtocolBufferException;

    public T mergeUnframed(InputStream input) throws IOException;

    public T mergeFramed(InputStream input) throws IOException;

    public T mergeUnframed(CodedInputStream input) throws IOException;

    public T mergeFramed(CodedInputStream input) throws IOException;

    public Buffer toUnframedBuffer();

    public Buffer toFramedBuffer();

    public byte[] toUnframedByteArray();

    public byte[] toFramedByteArray();

    public void writeUnframed(CodedOutputStream output) throws java.io.IOException;

    public void writeFramed(CodedOutputStream output) throws java.io.IOException;

    public void writeUnframed(OutputStream output) throws IOException;

    public void writeFramed(OutputStream output) throws java.io.IOException;

}


text:
<?php

namespace EXSyst\Bundle\ApiDocBundle\RouteDescriber;

use EXSyst\Component\Swagger\Swagger;
use Symfony\Component\Routing\Route;

interface RouteDescriberInterface
{
    public function describe(Swagger $api, Route $route, \ReflectionMethod $reflectionMethod);
}


text:
/**
 * @file
 * Deluxe Paint Animation decoder
 */

#include "avcodec.h"
#include "bytestream.h"
#include "internal.h"

typedef struct AnmContext {
    AVFrame *frame;
    int palette[AVPALETTE_COUNT];
    GetByteContext gb;
    int x;  ///< x coordinate position
} AnmContext;

static av_cold int decode_init(AVCodecContext *avctx)
{
    AnmContext *s = avctx->priv_data;
    int i;

    avctx->pix_fmt = AV_PIX_FMT_PAL8;

    s->frame = av_frame_alloc();
    if (!s->frame)
        return AVERROR(ENOMEM);

    bytestream2_init(&s->gb, avctx->extradata, avctx->extradata_size);
    if (bytestream2_get_bytes_left(&s->gb) < 16 * 8 + 4 * 256)
        return AVERROR_INVALIDDATA;

    bytestream2_skipu(&s->gb, 16 * 8);
    for (i = 0; i < 256; i++)
        s->palette[i] = bytestream2_get_le32u(&s->gb);

    return 0;
}

/**
 * Perform decode operation
 * @param dst     pointer to destination image buffer
 * @param dst_end pointer to end of destination image buffer
 * @param gb GetByteContext (optional, see below)
 * @param pixel Fill color (optional, see below)
 * @param count Pixel count
 * @param x Pointer to x-axis counter
 * @param width Image width
 * @param linesize Destination image buffer linesize
 * @return non-zero if destination buffer is exhausted
 *
 * a copy operation is achieved when 'gb' is set
 * a fill operation is achieved when 'gb' is null and pixel is >= 0
 * a skip operation is achieved when 'gb' is null and pixel is < 0
 */
static inline int op(uint8_t **dst, const uint8_t *dst_end,
                     GetByteContext *gb,
                     int pixel, int count,
                     int *x, int width, int linesize)
{
    int remaining = width - *x;
    while(count > 0) {
        int striplen = FFMIN(count, remaining);
        if (gb) {
            if (bytestream2_get_bytes_left(gb) < striplen)
                goto exhausted;
            bytestream2_get_bufferu(gb, *dst, striplen);
        } else if (pixel >= 0)
            memset(*dst, pixel, striplen);
        *dst      += striplen;
        remaining -= striplen;
        count     -= striplen;
        if (remaining <= 0) {
            *dst      += linesize - width;
            remaining  = width;
        }
        if (linesize > 0) {
            if (*dst >= dst_end) goto exhausted;
        } else {
            if (*dst <= dst_end) goto exhausted;
        }
    }
    *x = width - remaining;
    return 0;

exhausted:
    *x = width - remaining;
    return 1;
}

static int decode_frame(AVCodecContext *avctx,
                        void *data, int *got_frame,
                        AVPacket *avpkt)
{
    AnmContext *s = avctx->priv_data;
    const int buf_size = avpkt->size;
    uint8_t *dst, *dst_end;
    int count, ret;

    if ((ret = ff_reget_buffer(avctx, s->frame)) < 0)
        return ret;
    dst     = s->frame->data[0];
    dst_end = s->frame->data[0] + s->frame->linesize[0]*avctx->height;

    bytestream2_init(&s->gb, avpkt->data, buf_size);

    if (bytestream2_get_byte(&s->gb) != 0x42) {
        avpriv_request_sample(avctx, "Unknown record type");
        return AVERROR_INVALIDDATA;
    }
    if (bytestream2_get_byte(&s->gb)) {
        avpriv_request_sample(avctx, "Padding bytes");
        return AVERROR_PATCHWELCOME;
    }
    bytestream2_skip(&s->gb, 2);

    s->x = 0;
    do {
        /* if statements are ordered by probability */
#define OP(gb, pixel, count) \
    op(&dst, dst_end, (gb), (pixel), (count), &s->x, avctx->width, s->frame->linesize[0])

        int type = bytestream2_get_byte(&s->gb);
        count = type & 0x7F;
        type >>= 7;
        if (count) {
            if (OP(type ? NULL : &s->gb, -1, count)) break;
        } else if (!type) {
            int pixel;
            count = bytestream2_get_byte(&s->gb);  /* count==0 gives nop */
            pixel = bytestream2_get_byte(&s->gb);
            if (OP(NULL, pixel, count)) break;
        } else {
            int pixel;
            type = bytestream2_get_le16(&s->gb);
            count = type & 0x3FFF;
            type >>= 14;
            if (!count) {
                if (type == 0)
                    break; // stop
                if (type == 2) {
                    avpriv_request_sample(avctx, "Unknown opcode");
                    return AVERROR_PATCHWELCOME;
                }
                continue;
            }
            pixel = type == 3 ? bytestream2_get_byte(&s->gb) : -1;
            if (type == 1) count += 0x4000;
            if (OP(type == 2 ? &s->gb : NULL, pixel, count)) break;
        }
    } while (bytestream2_get_bytes_left(&s->gb) > 0);

    memcpy(s->frame->data[1], s->palette, AVPALETTE_SIZE);

    *got_frame = 1;
    if ((ret = av_frame_ref(data, s->frame)) < 0)
        return ret;

    return buf_size;
}

static av_cold int decode_end(AVCodecContext *avctx)
{
    AnmContext *s = avctx->priv_data;

    av_frame_free(&s->frame);
    return 0;
}

AVCodec ff_anm_decoder = {
    .name           = "anm",
    .long_name      = NULL_IF_CONFIG_SMALL("Deluxe Paint Animation"),
    .type           = AVMEDIA_TYPE_VIDEO,
    .id             = AV_CODEC_ID_ANM,
    .priv_data_size = sizeof(AnmContext),
    .init           = decode_init,
    .close          = decode_end,
    .decode         = decode_frame,
    .capabilities   = CODEC_CAP_DR1,
};


text:
layout: posts_by_category
categories: talks
title: talks
permalink: /category/talks
---


text:
import type { FastifyInstance } from 'fastify';
import { IncomingMessage, ServerResponse } from 'node:http';
declare const SolrProxy: {
    start: (port?: any, userOptions?: any) => Promise<FastifyInstance<import("fastify").RawServerDefault, IncomingMessage, ServerResponse<IncomingMessage>, import("fastify").FastifyBaseLogger, import("fastify").FastifyTypeProviderDefault>>;
};
export default SolrProxy;
//# sourceMappingURL=index.d.ts.map


text:
#include "../ModuleInterface.h"
#include "VKRenderSystem.h"

namespace LLGL
{

namespace ModuleVulkan
{
    int GetRendererID()
    {
        return LLGL::RendererID::Vulkan;
    }

    const char* GetModuleName()
    {
        return "Vulkan";
    }

    const char* GetRendererName()
    {
        return "Vulkan";
    }

    RenderSystem* AllocRenderSystem(const LLGL::RenderSystemDescriptor* renderSystemDesc)
    {
        return new VKRenderSystem(*renderSystemDesc);
    }
} // /namespace ModuleVulkan

} // /namespace LLGL

#ifndef LLGL_BUILD_STATIC_LIB

extern "C"
{

LLGL_EXPORT int LLGL_RenderSystem_BuildID()
{
    return LLGL_BUILD_ID;
}

LLGL_EXPORT int LLGL_RenderSystem_RendererID()
{
    return LLGL::ModuleVulkan::GetRendererID();
}

LLGL_EXPORT const char* LLGL_RenderSystem_Name()
{
    return LLGL::ModuleVulkan::GetRendererName();
}

LLGL_EXPORT void* LLGL_RenderSystem_Alloc(const void* renderSystemDesc)
{
    auto desc = reinterpret_cast<const LLGL::RenderSystemDescriptor*>(renderSystemDesc);
    return LLGL::ModuleVulkan::AllocRenderSystem(desc);
}

} // /extern "C"

#endif // /LLGL_BUILD_STATIC_LIB

// ================================================================================