# Stream

    Stability: 2 - Stable

A stream is an abstract interface implemented by various objects in
Node.js.  For example a [request to an HTTP
server](https://iojs.org/dist/v5.0.0/doc/api/http.html#http_http_incomingmessage) is a stream, as is
[stdout][]. Streams are readable, writable, or both. All streams are
instances of [EventEmitter][]

You can load the Stream base classes by doing `require('stream')`.
There are base classes provided for [Readable][] streams, [Writable][]
streams, [Duplex][] streams, and [Transform][] streams.

This document is split up into 3 sections.  The first explains the
parts of the API that you need to be aware of to use streams in your
programs.  If you never implement a streaming API yourself, you can
stop there.

The second section explains the parts of the API that you need to use
if you implement your own custom streams yourself.  The API is
designed to make this easy for you to do.

The third section goes into more depth about how streams work,
including some of the internal mechanisms and functions that you
should probably not modify unless you definitely know what you are
doing.

## API for Stream Consumers

<!--type=misc-->

Streams can be either [Readable][], [Writable][], or both ([Duplex][]).

All streams are EventEmitters, but they also have other custom methods
and properties depending on whether they are Readable, Writable, or
Duplex.

If a stream is both Readable and Writable, then it implements all of
the methods and events below.  So, a [Duplex][] or [Transform][] stream is
fully described by this API, though their implementation may be
somewhat different.

It is not necessary to implement Stream interfaces in order to consume
streams in your programs.  If you **are** implementing streaming
interfaces in your own program, please also refer to
[API for Stream Implementors][] below.

Almost all Node.js programs, no matter how simple, use Streams in some
way. Here is an example of using Streams in an Node.js program:

```javascript
var http = require('http');

var server = http.createServer(function (req, res) {
  // req is an http.IncomingMessage, which is a Readable Stream
  // res is an http.ServerResponse, which is a Writable Stream

  var body = '';
  // we want to get the data as utf8 strings
  // If you don't set an encoding, then you'll get Buffer objects
  req.setEncoding('utf8');

  // Readable streams emit 'data' events once a listener is added
  req.on('data', function (chunk) {
    body += chunk;
  });

  // the end event tells you that you have entire body
  req.on('end', function () {
    try {
      var data = JSON.parse(body);
    } catch (er) {
      // uh oh!  bad json!
      res.statusCode = 400;
      return res.end('error: ' + er.message);
    }

    // write back something interesting to the user:
    res.write(typeof data);
    res.end();
  });
});

server.listen(1337);

// $ curl localhost:1337 -d '{}'
// object
// $ curl localhost:1337 -d '"foo"'
// string
// $ curl localhost:1337 -d 'not json'
// error: Unexpected token o
```

### Class: stream.Readable

<!--type=class-->

The Readable stream interface is the abstraction for a *source* of
data that you are reading from.  In other words, data comes *out* of a
Readable stream.

A Readable stream will not start emitting data until you indicate that
you are ready to receive it.

Readable streams have two "modes": a **flowing mode** and a **paused
mode**.  When in flowing mode, data is read from the underlying system
and provided to your program as fast as possible.  In paused mode, you
must explicitly call `stream.read()` to get chunks of data out.
Streams start out in paused mode.

**Note**: If no data event handlers are attached, and there are no
[`pipe()`][] destinations, and the stream is switched into flowing
mode, then data will be lost.

You can switch to flowing mode by doing any of the following:

* Adding a [`'data'` event][] handler to listen for data.
* Calling the [`resume()`][] method to explicitly open the flow.
* Calling the [`pipe()`][] method to send the data to a [Writable][].

You can switch back to paused mode by doing either of the following:

* If there are no pipe destinations, by calling the [`pause()`][]
  method.
* If there are pipe destinations, by removing any [`'data'` event][]
  handlers, and removing all pipe destinations by calling the
  [`unpipe()`][] method.

Note that, for backwards compatibility reasons, removing `'data'`
event handlers will **not** automatically pause the stream.  Also, if
there are piped destinations, then calling `pause()` will not
guarantee that the stream will *remain* paused once those
destinations drain and ask for more data.

Examples of readable streams include:

* [http responses, on the client](https://iojs.org/dist/v5.0.0/doc/api/http.html#http_http_incomingmessage)
* [http requests, on the server](https://iojs.org/dist/v5.0.0/doc/api/http.html#http_http_incomingmessage)
* [fs read streams](https://iojs.org/dist/v5.0.0/doc/api/fs.html#fs_class_fs_readstream)
* [zlib streams][]
* [crypto streams][]
* [tcp sockets][]
* [child process stdout and stderr][]
* [process.stdin][]

#### Event: 'readable'

When a chunk of data can be read from the stream, it will emit a
`'readable'` event.

In some cases, listening for a `'readable'` event will cause some data
to be read into the internal buffer from the underlying system, if it
hadn't already.

```javascript
var readable = getReadableStreamSomehow();
readable.on('readable', function() {
  // there is some data to read now
});
```

Once the internal buffer is drained, a `readable` event will fire
again when more data is available.

The `readable` event is not emitted in the "flowing" mode with the
sole exception of the last one, on end-of-stream.

The 'readable' event indicates that the stream has new information:
either new data is available or the end of the stream has been reached.
In the former case, `.read()` will return that data. In the latter case,
`.read()` will return null. For instance, in the following example, `foo.txt`
is an empty file:

```javascript
var fs = require('fs');
var rr = fs.createReadStream('foo.txt');
rr.on('readable', function() {
  console.log('readable:', rr.read());
});
rr.on('end', function() {
  console.log('end');
});
```

The output of running this script is:

```
bash-3.2$ node test.js
readable: null
end
```

#### Event: 'data'

* `chunk` {Buffer | String} The chunk of data.

Attaching a `data` event listener to a stream that has not been
explicitly paused will switch the stream into flowing mode. Data will
then be passed as soon as it is available.

If you just want to get all the data out of the stream as fast as
possible, this is the best way to do so.

```javascript
var readable = getReadableStreamSomehow();
readable.on('data', function(chunk) {
  console.log('got %d bytes of data', chunk.length);
});
```

#### Event: 'end'

This event fires when there will be no more data to read.

Note that the `end` event **will not fire** unless the data is
completely consumed.  This can be done by switching into flowing mode,
or by calling `read()` repeatedly until you get to the end.

```javascript
var readable = getReadableStreamSomehow();
readable.on('data', function(chunk) {
  console.log('got %d bytes of data', chunk.length);
});
readable.on('end', function() {
  console.log('there will be no more data.');
});
```

#### Event: 'close'

Emitted when the stream and any of its underlying resources (a file
descriptor, for example) have been closed. The event indicates that
no more events will be emitted, and no further computation will occur.

Not all streams will emit the 'close' event.

#### Event: 'error'

* {Error Object}

Emitted if there was an error receiving data.

#### readable.read([size])

* `size` {Number} Optional argument to specify how much data to read.
* Return {String | Buffer | null}

The `read()` method pulls some data out of the internal buffer and
returns it.  If there is no data available, then it will return
`null`.

If you pass in a `size` argument, then it will return that many
bytes.  If `size` bytes are not available, then it will return `null`,
unless we've ended, in which case it will return the data remaining
in the buffer.

If you do not specify a `size` argument, then it will return all the
data in the internal buffer.

This method should only be called in paused mode.  In flowing mode,
this method is called automatically until the internal buffer is
drained.

```javascript
var readable = getReadableStreamSomehow();
readable.on('readable', function() {
  var chunk;
  while (null !== (chunk = readable.read())) {
    console.log('got %d bytes of data', chunk.length);
  }
});
```

If this method returns a data chunk, then it will also trigger the
emission of a [`'data'` event][].

Note that calling `readable.read([size])` after the `end` event has been
triggered will return `null`. No runtime error will be raised.

#### readable.setEncoding(encoding)

* `encoding` {String} The encoding to use.
* Return: `this`

Call this function to cause the stream to return strings of the
specified encoding instead of Buffer objects.  For example, if you do
`readable.setEncoding('utf8')`, then the output data will be
interpreted as UTF-8 data, and returned as strings.  If you do
`readable.setEncoding('hex')`, then the data will be encoded in
hexadecimal string format.

This properly handles multi-byte characters that would otherwise be
potentially mangled if you simply pulled the Buffers directly and
called `buf.toString(encoding)` on them.  If you want to read the data
as strings, always use this method.

```javascript
var readable = getReadableStreamSomehow();
readable.setEncoding('utf8');
readable.on('data', function(chunk) {
  assert.equal(typeof chunk, 'string');
  console.log('got %d characters of string data', chunk.length);
});
```

#### readable.resume()

* Return: `this`

This method will cause the readable stream to resume emitting `data`
events.

This method will switch the stream into flowing mode.  If you do *not*
want to consume the data from a stream, but you *do* want to get to
its `end` event, you can call [`readable.resume()`][] to open the flow of
data.

```javascript
var readable = getReadableStreamSomehow();
readable.resume();
readable.on('end', function() {
  console.log('got to the end, but did not read anything');
});
```

#### readable.pause()

* Return: `this`

This method will cause a stream in flowing mode to stop emitting
`data` events, switching out of flowing mode.  Any data that becomes
available will remain in the internal buffer.

```javascript
var readable = getReadableStreamSomehow();
readable.on('data', function(chunk) {
  console.log('got %d bytes of data', chunk.length);
  readable.pause();
  console.log('there will be no more data for 1 second');
  setTimeout(function() {
    console.log('now data will start flowing again');
    readable.resume();
  }, 1000);
});
```

#### readable.isPaused()

* Return: `Boolean`

This method returns whether or not the `readable` has been **explicitly**
paused by client code (using `readable.pause()` without a corresponding
`readable.resume()`).

```javascript
var readable = new stream.Readable

readable.isPaused() // === false
readable.pause()
readable.isPaused() // === true
readable.resume()
readable.isPaused() // === false
```

#### readable.pipe(destination[, options])

* `destination` {[Writable][] Stream} The destination for writing data
* `options` {Object} Pipe options
  * `end` {Boolean} End the writer when the reader ends. Default = `true`

This method pulls all the data out of a readable stream, and writes it
to the supplied destination, automatically managing the flow so that
the destination is not overwhelmed by a fast readable stream.

Multiple destinations can be piped to safely.

```javascript
var readable = getReadableStreamSomehow();
var writable = fs.createWriteStream('file.txt');
// All the data from readable goes into 'file.txt'
readable.pipe(writable);
```

This function returns the destination stream, so you can set up pipe
chains like so:

```javascript
var r = fs.createReadStream('file.txt');
var z = zlib.createGzip();
var w = fs.createWriteStream('file.txt.gz');
r.pipe(z).pipe(w);
```

For example, emulating the Unix `cat` command:

```javascript
process.stdin.pipe(process.stdout);
```

By default [`end()`][] is called on the destination when the source stream
emits `end`, so that `destination` is no longer writable. Pass `{ end:
false }` as `options` to keep the destination stream open.

This keeps `writer` open so that "Goodbye" can be written at the
end.

```javascript
reader.pipe(writer, { end: false });
reader.on('end', function() {
  writer.end('Goodbye\n');
});
```

Note that `process.stderr` and `process.stdout` are never closed until
the process exits, regardless of the specified options.

#### readable.unpipe([destination])

* `destination` {[Writable][] Stream} Optional specific stream to unpipe

This method will remove the hooks set up for a previous `pipe()` call.

If the destination is not specified, then all pipes are removed.

If the destination is specified, but no pipe is set up for it, then
this is a no-op.

```javascript
var readable = getReadableStreamSomehow();
var writable = fs.createWriteStream('file.txt');
// All the data from readable goes into 'file.txt',
// but only for the first second
readable.pipe(writable);
setTimeout(function() {
  console.log('stop writing to file.txt');
  readable.unpipe(writable);
  console.log('manually close the file stream');
  writable.end();
}, 1000);
```

#### readable.unshift(chunk)

* `chunk` {Buffer | String} Chunk of data to unshift onto the read queue

This is useful in certain cases where a stream is being consumed by a
parser, which needs to "un-consume" some data that it has
optimistically pulled out of the source, so that the stream can be
passed on to some other party.

Note that `stream.unshift(chunk)` cannot be called after the `end` event
has been triggered; a runtime error will be raised.

If you find that you must often call `stream.unshift(chunk)` in your
programs, consider implementing a [Transform][] stream instead.  (See API
for Stream Implementors, below.)

```javascript
// Pull off a header delimited by \n\n
// use unshift() if we get too much
// Call the callback with (error, header, stream)
var StringDecoder = require('string_decoder').StringDecoder;
function parseHeader(stream, callback) {
  stream.on('error', callback);
  stream.on('readable', onReadable);
  var decoder = new StringDecoder('utf8');
  var header = '';
  function onReadable() {
    var chunk;
    while (null !== (chunk = stream.read())) {
      var str = decoder.write(chunk);
      if (str.match(/\n\n/)) {
        // found the header boundary
        var split = str.split(/\n\n/);
        header += split.shift();
        var remaining = split.join('\n\n');
        var buf = new Buffer(remaining, 'utf8');
        if (buf.length)
          stream.unshift(buf);
        stream.removeListener('error', callback);
        stream.removeListener('readable', onReadable);
        // now the body of the message can be read from the stream.
        callback(null, header, stream);
      } else {
        // still reading the header.
        header += str;
      }
    }
  }
}
```
Note that, unlike `stream.push(chunk)`, `stream.unshift(chunk)` will not
end the reading process by resetting the internal reading state of the
stream. This can cause unexpected results if `unshift` is called during a
read (i.e. from within a `_read` implementation on a custom stream). Following
the call to `unshift` with an immediate `stream.push('')` will reset the
reading state appropriately, however it is best to simply avoid calling
`unshift` while in the process of performing a read.

#### readable.wrap(stream)

* `stream` {Stream} An "old style" readable stream

Versions of Node.js prior to v0.10 had streams that did not implement the
entire Streams API as it is today.  (See "Compatibility" below for
more information.)

If you are using an older Node.js library that emits `'data'` events and
has a [`pause()`][] method that is advisory only, then you can use the
`wrap()` method to create a [Readable][] stream that uses the old stream
as its data source.

You will very rarely ever need to call this function, but it exists
as a convenience for interacting with old Node.js programs and libraries.

For example:

```javascript
var OldReader = require('./old-api-module.js').OldReader;
var oreader = new OldReader;
var Readable = require('stream').Readable;
var myReader = new Readable().wrap(oreader);

myReader.on('readable', function() {
  myReader.read(); // etc.
});
```

### Class: stream.Writable

<!--type=class-->

The Writable stream interface is an abstraction for a *destination*
that you are writing data *to*.

Examples of writable streams include:

* [http requests, on the client](https://iojs.org/dist/v5.0.0/doc/api/http.html#http_class_http_clientrequest)
* [http responses, on the server](https://iojs.org/dist/v5.0.0/doc/api/http.html#http_class_http_serverresponse)
* [fs write streams](https://iojs.org/dist/v5.0.0/doc/api/fs.html#fs_class_fs_writestream)
* [zlib streams][]
* [crypto streams][]
* [tcp sockets][]
* [child process stdin](https://iojs.org/dist/v5.0.0/doc/api/child_process.html#child_process_child_stdin)
* [process.stdout][], [process.stderr][]

#### writable.write(chunk[, encoding][, callback])

* `chunk` {String | Buffer} The data to write
* `encoding` {String} The encoding, if `chunk` is a String
* `callback` {Function} Callback for when this chunk of data is flushed
* Returns: {Boolean} True if the data was handled completely.

This method writes some data to the underlying system, and calls the
supplied callback once the data has been fully handled.

The return value indicates if you should continue writing right now.
If the data had to be buffered internally, then it will return
`false`.  Otherwise, it will return `true`.

This return value is strictly advisory.  You MAY continue to write,
even if it returns `false`.  However, writes will be buffered in
memory, so it is best not to do this excessively.  Instead, wait for
the `drain` event before writing more data.

#### Event: 'drain'

If a [`writable.write(chunk)`][] call returns false, then the `drain`
event will indicate when it is appropriate to begin writing more data
to the stream.

```javascript
// Write the data to the supplied writable stream one million times.
// Be attentive to back-pressure.
function writeOneMillionTimes(writer, data, encoding, callback) {
  var i = 1000000;
  write();
  function write() {
    var ok = true;
    do {
      i -= 1;
      if (i === 0) {
        // last time!
        writer.write(data, encoding, callback);
      } else {
        // see if we should continue, or wait
        // don't pass the callback, because we're not done yet.
        ok = writer.write(data, encoding);
      }
    } while (i > 0 && ok);
    if (i > 0) {
      // had to stop early!
      // write some more once it drains
      writer.once('drain', write);
    }
  }
}
```

#### writable.cork()

Forces buffering of all writes.

Buffered data will be flushed either at `.uncork()` or at `.end()` call.

#### writable.uncork()

Flush all data, buffered since `.cork()` call.

#### writable.setDefaultEncoding(encoding)

* `encoding` {String} The new default encoding

Sets the default encoding for a writable stream.

#### writable.end([chunk][, encoding][, callback])

* `chunk` {String | Buffer} Optional data to write
* `encoding` {String} The encoding, if `chunk` is a String
* `callback` {Function} Optional callback for when the stream is finished

Call this method when no more data will be written to the stream.  If
supplied, the callback is attached as a listener on the `finish` event.

Calling [`write()`][] after calling [`end()`][] will raise an error.

```javascript
// write 'hello, ' and then end with 'world!'
var file = fs.createWriteStream('example.txt');
file.write('hello, ');
file.end('world!');
// writing more now is not allowed!
```

#### Event: 'finish'

When the [`end()`][] method has been called, and all data has been flushed
to the underlying system, this event is emitted.

```javascript
var writer = getWritableStreamSomehow();
for (var i = 0; i < 100; i ++) {
  writer.write('hello, #' + i + '!\n');
}
writer.end('this is the end\n');
writer.on('finish', function() {
  console.error('all writes are now complete.');
});
```

#### Event: 'pipe'

* `src` {[Readable][] Stream} source stream that is piping to this writable

This is emitted whenever the `pipe()` method is called on a readable
stream, adding this writable to its set of destinations.

```javascript
var writer = getWritableStreamSomehow();
var reader = getReadableStreamSomehow();
writer.on('pipe', function(src) {
  console.error('something is piping into the writer');
  assert.equal(src, reader);
});
reader.pipe(writer);
```

#### Event: 'unpipe'

* `src` {[Readable][] Stream} The source stream that [unpiped][] this writable

This is emitted whenever the [`unpipe()`][] method is called on a
readable stream, removing this writable from its set of destinations.

```javascript
var writer = getWritableStreamSomehow();
var reader = getReadableStreamSomehow();
writer.on('unpipe', function(src) {
  console.error('something has stopped piping into the writer');
  assert.equal(src, reader);
});
reader.pipe(writer);
reader.unpipe(writer);
```

#### Event: 'error'

* {Error object}

Emitted if there was an error when writing or piping data.

### Class: stream.Duplex

Duplex streams are streams that implement both the [Readable][] and
[Writable][] interfaces.  See above for usage.

Examples of Duplex streams include:

* [tcp sockets][]
* [zlib streams][]
* [crypto streams][]

### Class: stream.Transform

Transform streams are [Duplex][] streams where the output is in some way
computed from the input.  They implement both the [Readable][] and
[Writable][] interfaces.  See above for usage.

Examples of Transform streams include:

* [zlib streams][]
* [crypto streams][]

## API for Stream Implementors

<!--type=misc-->

To implement any sort of stream, the pattern is the same:

1. Extend the appropriate parent class in your own subclass.  (The
   [`util.inherits`][] method is particularly helpful for this.)
2. Call the appropriate parent class constructor in your constructor,
   to be sure that the internal mechanisms are set up properly.
2. Implement one or more specific methods, as detailed below.

The class to extend and the method(s) to implement depend on the sort
of stream class you are writing:

<table>
  <thead>
    <tr>
      <th>
        <p>Use-case</p>
      </th>
      <th>
        <p>Class</p>
      </th>
      <th>
        <p>Method(s) to implement</p>
      </th>
    </tr>
  </thead>
  <tr>
    <td>
      <p>Reading only</p>
    </td>
    <td>
      <p>[Readable](#stream_class_stream_readable_1)</p>
    </td>
    <td>
      <p><code>[_read][]</code></p>
    </td>
  </tr>
  <tr>
    <td>
      <p>Writing only</p>
    </td>
    <td>
      <p>[Writable](#stream_class_stream_writable_1)</p>
    </td>
    <td>
      <p><code>[_write][]</code>, <code>_writev</code></p>
    </td>
  </tr>
  <tr>
    <td>
      <p>Reading and writing</p>
    </td>
    <td>
      <p>[Duplex](#stream_class_stream_duplex_1)</p>
    </td>
    <td>
      <p><code>[_read][]</code>, <code>[_write][]</code>, <code>_writev</code></p>
    </td>
  </tr>
  <tr>
    <td>
      <p>Operate on written data, then read the result</p>
    </td>
    <td>
      <p>[Transform](#stream_class_stream_transform_1)</p>
    </td>
    <td>
      <p><code>_transform</code>, <code>_flush</code></p>
    </td>
  </tr>
</table>

In your implementation code, it is very important to never call the
methods described in [API for Stream Consumers][] above.  Otherwise, you
can potentially cause adverse side effects in programs that consume
your streaming interfaces.

### Class: stream.Readable

<!--type=class-->

`stream.Readable` is an abstract class designed to be extended with an
underlying implementation of the [`_read(size)`][] method.

Please see above under [API for Stream Consumers][] for how to consume
streams in your programs.  What follows is an explanation of how to
implement Readable streams in your programs.

#### Example: A Counting Stream

<!--type=example-->

This is a basic example of a Readable stream.  It emits the numerals
from 1 to 1,000,000 in ascending order, and then ends.

```javascript
var Readable = require('stream').Readable;
var util = require('util');
util.inherits(Counter, Readable);

function Counter(opt) {
  Readable.call(this, opt);
  this._max = 1000000;
  this._index = 1;
}

Counter.prototype._read = function() {
  var i = this._index++;
  if (i > this._max)
    this.push(null);
  else {
    var str = '' + i;
    var buf = new Buffer(str, 'ascii');
    this.push(buf);
  }
};
```

#### Example: SimpleProtocol v1 (Sub-optimal)

This is similar to the `parseHeader` function described above, but
implemented as a custom stream.  Also, note that this implementation
does not convert the incoming data to a string.

However, this would be better implemented as a [Transform][] stream.  See
below for a better implementation.

```javascript
// A parser for a simple data protocol.
// The "header" is a JSON object, followed by 2 \n characters, and
// then a message body.
//
// NOTE: This can be done more simply as a Transform stream!
// Using Readable directly for this is sub-optimal.  See the
// alternative example below under the Transform section.

var Readable = require('stream').Readable;
var util = require('util');

util.inherits(SimpleProtocol, Readable);

function SimpleProtocol(source, options) {
  if (!(this instanceof SimpleProtocol))
    return new SimpleProtocol(source, options);

  Readable.call(this, options);
  this._inBody = false;
  this._sawFirstCr = false;

  // source is a readable stream, such as a socket or file
  this._source = source;

  var self = this;
  source.on('end', function() {
    self.push(null);
  });

  // give it a kick whenever the source is readable
  // read(0) will not consume any bytes
  source.on('readable', function() {
    self.read(0);
  });

  this._rawHeader = [];
  this.header = null;
}

SimpleProtocol.prototype._read = function(n) {
  if (!this._inBody) {
    var chunk = this._source.read();

    // if the source doesn't have data, we don't have data yet.
    if (chunk === null)
      return this.push('');

    // check if the chunk has a \n\n
    var split = -1;
    for (var i = 0; i < chunk.length; i++) {
      if (chunk[i] === 10) { // '\n'
        if (this._sawFirstCr) {
          split = i;
          break;
        } else {
          this._sawFirstCr = true;
        }
      } else {
        this._sawFirstCr = false;
      }
    }

    if (split === -1) {
      // still waiting for the \n\n
      // stash the chunk, and try again.
      this._rawHeader.push(chunk);
      this.push('');
    } else {
      this._inBody = true;
      var h = chunk.slice(0, split);
      this._rawHeader.push(h);
      var header = Buffer.concat(this._rawHeader).toString();
      try {
        this.header = JSON.parse(header);
      } catch (er) {
        this.emit('error', new Error('invalid simple protocol data'));
        return;
      }
      // now, because we got some extra data, unshift the rest
      // back into the read queue so that our consumer will see it.
      var b = chunk.slice(split);
      this.unshift(b);
      // calling unshift by itself does not reset the reading state
      // of the stream; since we're inside _read, doing an additional
      // push('') will reset the state appropriately.
      this.push('');

      // and let them know that we are done parsing the header.
      this.emit('header', this.header);
    }
  } else {
    // from there on, just provide the data to our consumer.
    // careful not to push(null), since that would indicate EOF.
    var chunk = this._source.read();
    if (chunk) this.push(chunk);
  }
};

// Usage:
// var parser = new SimpleProtocol(source);
// Now parser is a readable stream that will emit 'header'
// with the parsed header data.
```

#### new stream.Readable([options])

* `options` {Object}
  * `highWaterMark` {Number} The maximum number of bytes to store in
    the internal buffer before ceasing to read from the underlying
    resource.  Default=16kb, or 16 for `objectMode` streams
  * `encoding` {String} If specified, then buffers will be decoded to
    strings using the specified encoding.  Default=null
  * `objectMode` {Boolean} Whether this stream should behave
    as a stream of objects. Meaning that stream.read(n) returns
    a single value instead of a Buffer of size n.  Default=false

In classes that extend the Readable class, make sure to call the
Readable constructor so that the buffering settings can be properly
initialized.

#### readable.\_read(size)

* `size` {Number} Number of bytes to read asynchronously

Note: **Implement this method, but do NOT call it directly.**

This method is prefixed with an underscore because it is internal to the
class that defines it and should only be called by the internal Readable
class methods. All Readable stream implementations must provide a _read
method to fetch data from the underlying resource.

When _read is called, if data is available from the resource, `_read` should
start pushing that data into the read queue by calling `this.push(dataChunk)`.
`_read` should continue reading from the resource and pushing data until push
returns false, at which point it should stop reading from the resource. Only
when _read is called again after it has stopped should it start reading
more data from the resource and pushing that data onto the queue.

Note: once the `_read()` method is called, it will not be called again until
the `push` method is called.

The `size` argument is advisory.  Implementations where a "read" is a
single call that returns data can use this to know how much data to
fetch.  Implementations where that is not relevant, such as TCP or
TLS, may ignore this argument, and simply provide data whenever it
becomes available.  There is no need, for example to "wait" until
`size` bytes are available before calling [`stream.push(chunk)`][].

#### readable.push(chunk[, encoding])

* `chunk` {Buffer | null | String} Chunk of data to push into the read queue
* `encoding` {String} Encoding of String chunks.  Must be a valid
  Buffer encoding, such as `'utf8'` or `'ascii'`
* return {Boolean} Whether or not more pushes should be performed

Note: **This method should be called by Readable implementors, NOT
by consumers of Readable streams.**

If a value other than null is passed, The `push()` method adds a chunk of data
into the queue for subsequent stream processors to consume. If `null` is
passed, it signals the end of the stream (EOF), after which no more data
can be written.

The data added with `push` can be pulled out by calling the `read()` method
when the `'readable'`event fires.

This API is designed to be as flexible as possible.  For example,
you may be wrapping a lower-level source which has some sort of
pause/resume mechanism, and a data callback.  In those cases, you
could wrap the low-level source object by doing something like this:

```javascript
// source is an object with readStop() and readStart() methods,
// and an `ondata` member that gets called when it has data, and
// an `onend` member that gets called when the data is over.

util.inherits(SourceWrapper, Readable);

function SourceWrapper(options) {
  Readable.call(this, options);

  this._source = getLowlevelSourceObject();
  var self = this;

  // Every time there's data, we push it into the internal buffer.
  this._source.ondata = function(chunk) {
    // if push() returns false, then we need to stop reading from source
    if (!self.push(chunk))
      self._source.readStop();
  };

  // When the source ends, we push the EOF-signaling `null` chunk
  this._source.onend = function() {
    self.push(null);
  };
}

// _read will be called when the stream wants to pull more data in
// the advisory size argument is ignored in this case.
SourceWrapper.prototype._read = function(size) {
  this._source.readStart();
};
```

### Class: stream.Writable

<!--type=class-->

`stream.Writable` is an abstract class designed to be extended with an
underlying implementation of the [`_write(chunk, encoding, callback)`][] method.

Please see above under [API for Stream Consumers][] for how to consume
writable streams in your programs.  What follows is an explanation of
how to implement Writable streams in your programs.

#### new stream.Writable([options])

* `options` {Object}
  * `highWaterMark` {Number} Buffer level when [`write()`][] starts
    returning false. Default=16kb, or 16 for `objectMode` streams
  * `decodeStrings` {Boolean} Whether or not to decode strings into
    Buffers before passing them to [`_write()`][].  Default=true
  * `objectMode` {Boolean} Whether or not the `write(anyObj)` is
    a valid operation. If set you can write arbitrary data instead
    of only `Buffer` / `String` data.  Default=false

In classes that extend the Writable class, make sure to call the
constructor so that the buffering settings can be properly
initialized.

#### writable.\_write(chunk, encoding, callback)

* `chunk` {Buffer | String} The chunk to be written. Will **always**
  be a buffer unless the `decodeStrings` option was set to `false`.
* `encoding` {String} If the chunk is a string, then this is the
  encoding type. If chunk is a buffer, then this is the special
  value - 'buffer', ignore it in this case.
* `callback` {Function} Call this function (optionally with an error
  argument) when you are done processing the supplied chunk.

All Writable stream implementations must provide a [`_write()`][]
method to send data to the underlying resource.

Note: **This function MUST NOT be called directly.**  It should be
implemented by child classes, and called by the internal Writable
class methods only.

Call the callback using the standard `callback(error)` pattern to
signal that the write completed successfully or with an error.

If the `decodeStrings` flag is set in the constructor options, then
`chunk` may be a string rather than a Buffer, and `encoding` will
indicate the sort of string that it is.  This is to support
implementations that have an optimized handling for certain string
data encodings.  If you do not explicitly set the `decodeStrings`
option to `false`, then you can safely ignore the `encoding` argument,
and assume that `chunk` will always be a Buffer.

This method is prefixed with an underscore because it is internal to
the class that defines it, and should not be called directly by user
programs.  However, you **are** expected to override this method in
your own extension classes.

#### writable.\_writev(chunks, callback)

* `chunks` {Array} The chunks to be written.  Each chunk has following
  format: `{ chunk: ..., encoding: ... }`.
* `callback` {Function} Call this function (optionally with an error
  argument) when you are done processing the supplied chunks.

Note: **This function MUST NOT be called directly.**  It may be
implemented by child classes, and called by the internal Writable
class methods only.

This function is completely optional to implement. In most cases it is
unnecessary.  If implemented, it will be called with all the chunks
that are buffered in the write queue.

### Class: stream.Duplex

<!--type=class-->

A "duplex" stream is one that is both Readable and Writable, such as a
TCP socket connection.

Note that `stream.Duplex` is an abstract class designed to be extended
with an underlying implementation of the `_read(size)` and
[`_write(chunk, encoding, callback)`][] methods as you would with a
Readable or Writable stream class.

Since JavaScript doesn't have multiple prototypal inheritance, this
class prototypally inherits from Readable, and then parasitically from
Writable.  It is thus up to the user to implement both the lowlevel
`_read(n)` method as well as the lowlevel
[`_write(chunk, encoding, callback)`][] method on extension duplex classes.

#### new stream.Duplex(options)

* `options` {Object} Passed to both Writable and Readable
  constructors. Also has the following fields:
  * `allowHalfOpen` {Boolean} Default=true.  If set to `false`, then
    the stream will automatically end the readable side when the
    writable side ends and vice versa.
  * `readableObjectMode` {Boolean} Default=false. Sets `objectMode`
    for readable side of the stream. Has no effect if `objectMode`
    is `true`.
  * `writableObjectMode` {Boolean} Default=false. Sets `objectMode`
    for writable side of the stream. Has no effect if `objectMode`
    is `true`.

In classes that extend the Duplex class, make sure to call the
constructor so that the buffering settings can be properly
initialized.

### Class: stream.Transform

A "transform" stream is a duplex stream where the output is causally
connected in some way to the input, such as a [zlib][] stream or a
[crypto][] stream.

There is no requirement that the output be the same size as the input,
the same number of chunks, or arrive at the same time.  For example, a
Hash stream will only ever have a single chunk of output which is
provided when the input is ended.  A zlib stream will produce output
that is either much smaller or much larger than its input.

Rather than implement the [`_read()`][] and [`_write()`][] methods, Transform
classes must implement the `_transform()` method, and may optionally
also implement the `_flush()` method.  (See below.)

#### new stream.Transform([options])

* `options` {Object} Passed to both Writable and Readable
  constructors.

In classes that extend the Transform class, make sure to call the
constructor so that the buffering settings can be properly
initialized.

#### transform.\_transform(chunk, encoding, callback)

* `chunk` {Buffer | String} The chunk to be transformed. Will **always**
  be a buffer unless the `decodeStrings` option was set to `false`.
* `encoding` {String} If the chunk is a string, then this is the
  encoding type. If chunk is a buffer, then this is the special
  value - 'buffer', ignore it in this case.
* `callback` {Function} Call this function (optionally with an error
  argument and data) when you are done processing the supplied chunk.

Note: **This function MUST NOT be called directly.**  It should be
implemented by child classes, and called by the internal Transform
class methods only.

All Transform stream implementations must provide a `_transform`
method to accept input and produce output.

`_transform` should do whatever has to be done in this specific
Transform class, to handle the bytes being written, and pass them off
to the readable portion of the interface.  Do asynchronous I/O,
process things, and so on.

Call `transform.push(outputChunk)` 0 or more times to generate output
from this input chunk, depending on how much data you want to output
as a result of this chunk.

Call the callback function only when the current chunk is completely
consumed.  Note that there may or may not be output as a result of any
particular input chunk. If you supply a second argument to the callback
it will be passed to the push method. In other words the following are
equivalent:

```javascript
transform.prototype._transform = function (data, encoding, callback) {
  this.push(data);
  callback();
};

transform.prototype._transform = function (data, encoding, callback) {
  callback(null, data);
};
```

This method is prefixed with an underscore because it is internal to
the class that defines it, and should not be called directly by user
programs.  However, you **are** expected to override this method in
your own extension classes.

#### transform.\_flush(callback)

* `callback` {Function} Call this function (optionally with an error
  argument) when you are done flushing any remaining data.

Note: **This function MUST NOT be called directly.**  It MAY be implemented
by child classes, and if so, will be called by the internal Transform
class methods only.

In some cases, your transform operation may need to emit a bit more
data at the end of the stream.  For example, a `Zlib` compression
stream will store up some internal state so that it can optimally
compress the output.  At the end, however, it needs to do the best it
can with what is left, so that the data will be complete.

In those cases, you can implement a `_flush` method, which will be
called at the very end, after all the written data is consumed, but
before emitting `end` to signal the end of the readable side.  Just
like with `_transform`, call `transform.push(chunk)` zero or more
times, as appropriate, and call `callback` when the flush operation is
complete.

This method is prefixed with an underscore because it is internal to
the class that defines it, and should not be called directly by user
programs.  However, you **are** expected to override this method in
your own extension classes.

#### Events: 'finish' and 'end'

The [`finish`][] and [`end`][] events are from the parent Writable
and Readable classes respectively. The `finish` event is fired after
`.end()` is called and all chunks have been processed by `_transform`,
`end` is fired after all data has been output which is after the callback
in `_flush` has been called.

#### Example: `SimpleProtocol` parser v2

The example above of a simple protocol parser can be implemented
simply by using the higher level [Transform][] stream class, similar to
the `parseHeader` and `SimpleProtocol v1` examples above.

In this example, rather than providing the input as an argument, it
would be piped into the parser, which is a more idiomatic Node.js stream
approach.

```javascript
var util = require('util');
var Transform = require('stream').Transform;
util.inherits(SimpleProtocol, Transform);

function SimpleProtocol(options) {
  if (!(this instanceof SimpleProtocol))
    return new SimpleProtocol(options);

  Transform.call(this, options);
  this._inBody = false;
  this._sawFirstCr = false;
  this._rawHeader = [];
  this.header = null;
}

SimpleProtocol.prototype._transform = function(chunk, encoding, done) {
  if (!this._inBody) {
    // check if the chunk has a \n\n
    var split = -1;
    for (var i = 0; i < chunk.length; i++) {
      if (chunk[i] === 10) { // '\n'
        if (this._sawFirstCr) {
          split = i;
          break;
        } else {
          this._sawFirstCr = true;
        }
      } else {
        this._sawFirstCr = false;
      }
    }

    if (split === -1) {
      // still waiting for the \n\n
      // stash the chunk, and try again.
      this._rawHeader.push(chunk);
    } else {
      this._inBody = true;
      var h = chunk.slice(0, split);
      this._rawHeader.push(h);
      var header = Buffer.concat(this._rawHeader).toString();
      try {
        this.header = JSON.parse(header);
      } catch (er) {
        this.emit('error', new Error('invalid simple protocol data'));
        return;
      }
      // and let them know that we are done parsing the header.
      this.emit('header', this.header);

      // now, because we got some extra data, emit this first.
      this.push(chunk.slice(split));
    }
  } else {
    // from there on, just provide the data to our consumer as-is.
    this.push(chunk);
  }
  done();
};

// Usage:
// var parser = new SimpleProtocol();
// source.pipe(parser)
// Now parser is a readable stream that will emit 'header'
// with the parsed header data.
```

### Class: stream.PassThrough

This is a trivial implementation of a [Transform][] stream that simply
passes the input bytes across to the output.  Its purpose is mainly
for examples and testing, but there are occasionally use cases where
it can come in handy as a building block for novel sorts of streams.

## Simplified Constructor API

<!--type=misc-->

In simple cases there is now the added benefit of being able to construct a stream without inheritance.

This can be done by passing the appropriate methods as constructor options:

Examples:

### Readable
```javascript
var readable = new stream.Readable({
  read: function(n) {
    // sets this._read under the hood
  }
});
```

### Writable
```javascript
var writable = new stream.Writable({
  write: function(chunk, encoding, next) {
    // sets this._write under the hood
  }
});

// or

var writable = new stream.Writable({
  writev: function(chunks, next) {
    // sets this._writev under the hood
  }
});
```

### Duplex
```javascript
var duplex = new stream.Duplex({
  read: function(n) {
    // sets this._read under the hood
  },
  write: function(chunk, encoding, next) {
    // sets this._write under the hood
  }
});

// or

var duplex = new stream.Duplex({
  read: function(n) {
    // sets this._read under the hood
  },
  writev: function(chunks, next) {
    // sets this._writev under the hood
  }
});
```

### Transform
```javascript
var transform = new stream.Transform({
  transform: function(chunk, encoding, next) {
    // sets this._transform under the hood
  },
  flush: function(done) {
    // sets this._flush under the hood
  }
});
```

## Streams: Under the Hood

<!--type=misc-->

### Buffering

<!--type=misc-->

Both Writable and Readable streams will buffer data on an internal
object which can be retrieved from `_writableState.getBuffer()` or
`_readableState.buffer`, respectively.

The amount of data that will potentially be buffered depends on the
`highWaterMark` option which is passed into the constructor.

Buffering in Readable streams happens when the implementation calls
[`stream.push(chunk)`][].  If the consumer of the Stream does not call
`stream.read()`, then the data will sit in the internal queue until it
is consumed.

Buffering in Writable streams happens when the user calls
[`stream.write(chunk)`][] repeatedly, even when `write()` returns `false`.

The purpose of streams, especially with the `pipe()` method, is to
limit the buffering of data to acceptable levels, so that sources and
destinations of varying speed will not overwhelm the available memory.

### `stream.read(0)`

There are some cases where you want to trigger a refresh of the
underlying readable stream mechanisms, without actually consuming any
data.  In that case, you can call `stream.read(0)`, which will always
return null.

If the internal read buffer is below the `highWaterMark`, and the
stream is not currently reading, then calling `read(0)` will trigger
a low-level `_read` call.

There is almost never a need to do this. However, you will see some
cases in Node.js's internals where this is done, particularly in the
Readable stream class internals.

### `stream.push('')`

Pushing a zero-byte string or Buffer (when not in [Object mode][]) has an
interesting side effect.  Because it *is* a call to
[`stream.push()`][], it will end the `reading` process.  However, it
does *not* add any data to the readable buffer, so there's nothing for
a user to consume.

Very rarely, there are cases where you have no data to provide now,
but the consumer of your stream (or, perhaps, another bit of your own
code) will know when to check again, by calling `stream.read(0)`.  In
those cases, you *may* call `stream.push('')`.

So far, the only use case for this functionality is in the
[tls.CryptoStream][] class, which is deprecated in Node.js/io.js v1.0.  If you
find that you have to use `stream.push('')`, please consider another
approach, because it almost certainly indicates that something is
horribly wrong.

### Compatibility with Older Node.js Versions

<!--type=misc-->

In versions of Node.js prior to v0.10, the Readable stream interface was
simpler, but also less powerful and less useful.

* Rather than waiting for you to call the `read()` method, `'data'`
  events would start emitting immediately.  If you needed to do some
  I/O to decide how to handle data, then you had to store the chunks
  in some kind of buffer so that they would not be lost.
* The [`pause()`][] method was advisory, rather than guaranteed.  This
  meant that you still had to be prepared to receive `'data'` events
  even when the stream was in a paused state.

In Node.js v0.10, the Readable class described below was added.
For backwards compatibility with older Node.js programs, Readable streams
switch into "flowing mode" when a `'data'` event handler is added, or
when the [`resume()`][] method is called.  The effect is that, even if
you are not using the new `read()` method and `'readable'` event, you
no longer have to worry about losing `'data'` chunks.

Most programs will continue to function normally.  However, this
introduces an edge case in the following conditions:

* No [`'data'` event][] handler is added.
* The [`resume()`][] method is never called.
* The stream is not piped to any writable destination.

For example, consider the following code:

```javascript
// WARNING!  BROKEN!
net.createServer(function(socket) {

  // we add an 'end' method, but never consume the data
  socket.on('end', function() {
    // It will never get here.
    socket.end('I got your message (but didnt read it)\n');
  });

}).listen(1337);
```

In versions of Node.js prior to v0.10, the incoming message data would be
simply discarded.  However, in Node.js v0.10 and beyond,
the socket will remain paused forever.

The workaround in this situation is to call the `resume()` method to
start the flow of data:

```javascript
// Workaround
net.createServer(function(socket) {

  socket.on('end', function() {
    socket.end('I got your message (but didnt read it)\n');
  });

  // start the flow of data, discarding it.
  socket.resume();

}).listen(1337);
```

In addition to new Readable streams switching into flowing mode,
pre-v0.10 style streams can be wrapped in a Readable class using the
`wrap()` method.

### Object Mode

<!--type=misc-->

Normally, Streams operate on Strings and Buffers exclusively.

Streams that are in **object mode** can emit generic JavaScript values
other than Buffers and Strings.

A Readable stream in object mode will always return a single item from
a call to `stream.read(size)`, regardless of what the size argument
is.

A Writable stream in object mode will always ignore the `encoding`
argument to `stream.write(data, encoding)`.

The special value `null` still retains its special value for object
mode streams.  That is, for object mode readable streams, `null` as a
return value from `stream.read()` indicates that there is no more
data, and [`stream.push(null)`][] will signal the end of stream data
(`EOF`).

No streams in Node.js core are object mode streams.  This pattern is only
used by userland streaming libraries.

You should set `objectMode` in your stream child class constructor on
the options object.  Setting `objectMode` mid-stream is not safe.

For Duplex streams `objectMode` can be set exclusively for readable or
writable side with `readableObjectMode` and `writableObjectMode`
respectively. These options can be used to implement parsers and
serializers with Transform streams.

```javascript
var util = require('util');
var StringDecoder = require('string_decoder').StringDecoder;
var Transform = require('stream').Transform;
util.inherits(JSONParseStream, Transform);

// Gets \n-delimited JSON string data, and emits the parsed objects
function JSONParseStream() {
  if (!(this instanceof JSONParseStream))
    return new JSONParseStream();

  Transform.call(this, { readableObjectMode : true });

  this._buffer = '';
  this._decoder = new StringDecoder('utf8');
}

JSONParseStream.prototype._transform = function(chunk, encoding, cb) {
  this._buffer += this._decoder.write(chunk);
  // split on newlines
  var lines = this._buffer.split(/\r?\n/);
  // keep the last partial line buffered
  this._buffer = lines.pop();
  for (var l = 0; l < lines.length; l++) {
    var line = lines[l];
    try {
      var obj = JSON.parse(line);
    } catch (er) {
      this.emit('error', er);
      return;
    }
    // push the parsed object out to the readable consumer
    this.push(obj);
  }
  cb();
};

JSONParseStream.prototype._flush = function(cb) {
  // Just handle any leftover
  var rem = this._buffer.trim();
  if (rem) {
    try {
      var obj = JSON.parse(rem);
    } catch (er) {
      this.emit('error', er);
      return;
    }
    // push the parsed object out to the readable consumer
    this.push(obj);
  }
  cb();
};
```

[EventEmitter]: https://iojs.org/dist/v5.0.0/doc/api/events.html#events_class_events_eventemitter
[Object mode]: #stream_object_mode
[`stream.push(chunk)`]: #stream_readable_push_chunk_encoding
[`stream.push(null)`]: #stream_readable_push_chunk_encoding
[`stream.push()`]: #stream_readable_push_chunk_encoding
[`unpipe()`]: #stream_readable_unpipe_destination
[unpiped]: #stream_readable_unpipe_destination
[tcp sockets]: https://iojs.org/dist/v5.0.0/doc/api/net.html#net_class_net_socket
[zlib streams]: zlib.html
[zlib]: zlib.html
[crypto streams]: crypto.html
[crypto]: crypto.html
[tls.CryptoStream]: https://iojs.org/dist/v5.0.0/doc/api/tls.html#tls_class_cryptostream
[process.stdin]: https://iojs.org/dist/v5.0.0/doc/api/process.html#process_process_stdin
[stdout]: https://iojs.org/dist/v5.0.0/doc/api/process.html#process_process_stdout
[process.stdout]: https://iojs.org/dist/v5.0.0/doc/api/process.html#process_process_stdout
[process.stderr]: https://iojs.org/dist/v5.0.0/doc/api/process.html#process_process_stderr
[child process stdout and stderr]: https://iojs.org/dist/v5.0.0/doc/api/child_process.html#child_process_child_stdout
[API for Stream Consumers]: #stream_api_for_stream_consumers
[API for Stream Implementors]: #stream_api_for_stream_implementors
[Readable]: #stream_class_stream_readable
[Writable]: #stream_class_stream_writable
[Duplex]: #stream_class_stream_duplex
[Transform]: #stream_class_stream_transform
[`end`]: #stream_event_end
[`finish`]: #stream_event_finish
[`_read(size)`]: #stream_readable_read_size_1
[`_read()`]: #stream_readable_read_size_1
[_read]: #stream_readable_read_size_1
[`writable.write(chunk)`]: #stream_writable_write_chunk_encoding_callback
[`write(chunk, encoding, callback)`]: #stream_writable_write_chunk_encoding_callback
[`write()`]: #stream_writable_write_chunk_encoding_callback
[`stream.write(chunk)`]: #stream_writable_write_chunk_encoding_callback
[`_write(chunk, encoding, callback)`]: #stream_writable_write_chunk_encoding_callback_1
[`_write()`]: #stream_writable_write_chunk_encoding_callback_1
[_write]: #stream_writable_write_chunk_encoding_callback_1
[`util.inherits`]: https://iojs.org/dist/v5.0.0/doc/api/util.html#util_util_inherits_constructor_superconstructor
[`end()`]: #stream_writable_end_chunk_encoding_callback
[`'data'` event]: #stream_event_data
[`resume()`]: #stream_readable_resume
[`readable.resume()`]: #stream_readable_resume
[`pause()`]: #stream_readable_pause
[`unpipe()`]: #stream_readable_unpipe_destination
[`pipe()`]: #stream_readable_pipe_destination_options

{'repo_name': 'fengjundev/React-Native-Remote-Update', 'stars': '457', 'repo_language': 'Java', 'file_name': 'Info.plist', 'mime_type': 'text/xml', 'hash': -5605100847760276708, 'source_dataset': 'data'}


package com.happyheng.sport_android.utils;

import android.os.Handler;
import android.os.Looper;

/**
 * 线程的工具类
 * Created by liuheng on 16/6/9.
 */
public class ThreadUtils {

    /**
     * 在子线程中执行
     * @param runnable
     */
    public static void runOnNewThread(Runnable runnable){
        new Thread(runnable).start();
    }

    /**
     * 在主线程中执行
     * @param runnable
     */
    public static void runOnMainThread(Runnable runnable){
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(runnable);
    }

}

{'repo_name': 'happyheng/Sport_Android', 'stars': '165', 'repo_language': 'Java', 'file_name': 'ExampleUnitTest.java', 'mime_type': 'text/x-java', 'hash': 1012639377063558120, 'source_dataset': 'data'}


using Android.App;
using Android.Net;
using Android.OS;
using Android.Widget;
using Android.Util;

namespace NetworkDetection
{

	[Activity(Label = "Network Detection", MainLauncher = true, Icon = "@drawable/icon")]
    public class Activity1 : Activity
    {
		static readonly string TAG = typeof(Activity1).FullName;

        private ImageView _isConnectedImage;
        private ImageView _roamingImage;
        private ImageView _wifiImage;
		TextView _connectionType;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Main);

            _wifiImage = FindViewById<ImageView>(Resource.Id.wifi_image);
            _roamingImage = FindViewById<ImageView>(Resource.Id.roaming_image);
            _isConnectedImage = FindViewById<ImageView>(Resource.Id.is_connected_image);
			_connectionType = FindViewById<TextView>(Resource.Id.connection_type_text);
        }

		protected override void OnResume()
		{
			base.OnResume();
			DetectNetwork();
		}

        private void DetectNetwork()
        {
			ConnectivityManager connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);
			NetworkInfo info = connectivityManager.ActiveNetworkInfo;
			bool isOnline = info.IsConnected;

			Log.Debug(TAG, "IsOnline = {0}", isOnline);

			if (isOnline)
			{
				_isConnectedImage.SetImageResource(Resource.Drawable.green_square);

				// Display the type of connectionn
				NetworkInfo.State activeState = info.GetState();
				_connectionType.Text = info.TypeName;

				// Check for a WiFi connection
				bool isWifi = info.Type == ConnectivityType.Wifi;
				if(isWifi)
				{
					Log.Debug(TAG, "Wifi connected.");
					_wifiImage.SetImageResource(Resource.Drawable.green_square);
				} else
				{
					Log.Debug(TAG, "Wifi disconnected.");
					_wifiImage.SetImageResource(Resource.Drawable.red_square);
				}

				// Check if roaming
				if (info.IsRoaming)
				{
					Log.Debug(TAG, "Roaming.");
					_roamingImage.SetImageResource(Resource.Drawable.green_square);
				} else
				{
					Log.Debug(TAG, "Not roaming.");
					_roamingImage.SetImageResource(Resource.Drawable.red_square);
				}
			} else
			{
				_isConnectedImage.SetImageResource(Resource.Drawable.red_square);
				_wifiImage.SetImageResource(Resource.Drawable.red_square);
				_roamingImage.SetImageResource(Resource.Drawable.red_square);
				_connectionType.Text = "N/A";
			}
        }
    }
}

{'repo_name': 'xamarin/docs-archive', 'stars': '546', 'repo_language': 'Java', 'file_name': 'applinks-metadata-sample.html', 'mime_type': 'text/html', 'hash': 9063743247485821354, 'source_dataset': 'data'}


//
//     Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50).
//
//     class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//

#import <objc/NSObject.h>

@class NSMutableDictionary;

@interface ASKEventHandlerDataSource : NSObject
{
    NSMutableDictionary *_eventHandlers;
}

- (void)removeEventHandler_ask:(id)arg1;
- (void)addEventHandler_ask:(id)arg1;
- (id)eventHandlerWithName_ask:(id)arg1;
- (id)eventHandlers_ask;
- (void)dealloc;
- (id)init;

@end

{'repo_name': 'LeoNatan/Apple-Runtime-Headers', 'stars': '131', 'repo_language': 'None', 'file_name': 'CDStructures.h', 'mime_type': 'text/x-c', 'hash': -1268613731678072627, 'source_dataset': 'data'}


/*
 * Created on 10-Dec-2004
 * Created by Paul Gardner
 * Copyright (C) Azureus Software, Inc, All Rights Reserved.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 */

package com.biglybt.ui.swt.views.tableitems.myshares;

import com.biglybt.pif.sharing.ShareResource;
import com.biglybt.pif.torrent.TorrentAttribute;
import com.biglybt.pif.ui.tables.TableCell;
import com.biglybt.pif.ui.tables.TableCellRefreshListener;
import com.biglybt.pif.ui.tables.TableManager;
import com.biglybt.pifimpl.local.torrent.TorrentManagerImpl;
import com.biglybt.ui.swt.views.table.CoreTableColumnSWT;

/**
 * @author parg
 *
 */

public class
CategoryItem
	extends CoreTableColumnSWT
	implements TableCellRefreshListener
{
		/** Default Constructor */

	protected static final TorrentAttribute	category_attribute =
		TorrentManagerImpl.getSingleton().getAttribute( TorrentAttribute.TA_CATEGORY );

	public
	CategoryItem()
	{
		super("category", POSITION_LAST, 100, TableManager.TABLE_MYSHARES);

		setRefreshInterval(INTERVAL_LIVE);
	}

	@Override
	public void
	refresh(TableCell cell)
	{
		ShareResource item = (ShareResource)cell.getDataSource();

		if (item == null){

			cell.setText("");

		}else{

			String	value = item.getAttribute(category_attribute);

			cell.setText( value==null?"":value);
		}
	}
}

{'repo_name': 'BiglySoftware/BiglyBT', 'stars': '501', 'repo_language': 'Java', 'file_name': 'PropertyFilesTest.java', 'mime_type': 'text/x-java', 'hash': -470377125032331084, 'source_dataset': 'data'}


```yaml
images:                             # map[string]struct | Images to be built and pushed
  image1:                           # string   | Name of the image
    image: dscr.io/username/image   # string   | Image repository and name
    tags:                           # string[] | Image tags (may be a tagging schema with variables)
    - latest
    - 0.0.1
    - dev-${DEVSPACE_GIT_COMMIT}
    dockerfile: ./Dockerfile        # string   | Relative path to the Dockerfile used for building (Default: ./Dockerfile)
    context: ./                     # string   | Relative path to the context used for building (Default: ./)
    entrypoint: []                  # string[] | Override ENTRYPOINT defined in Dockerfile
    cmd: []                         # string[] | Override CMD defined in Dockerfile
    createPullSecret: true          # bool     | Create a pull secret containing your Docker credentials (Default: false)
    build: ...                      # struct   | Build options for this image
  image2: ...
```

{'repo_name': 'devspace-cloud/devspace', 'stars': '1528', 'repo_language': 'Go', 'file_name': 'config_test.go', 'mime_type': 'text/plain', 'hash': 10767920157391466, 'source_dataset': 'data'}


include/group_replication.inc
Warnings:
Note	####	Sending passwords in plain text without SSL/TLS is extremely insecure.
Note	####	Storing MySQL user name or password information in the master info repository is not secure and is therefore not recommended. Please consider using the USER and PASSWORD connection options for START SLAVE; see the 'START SLAVE Syntax' in the MySQL Manual for more information.
[connection server1]

############################################################
# 1. Install clone plugin on server1.
[connection server1]
INSTALL PLUGIN clone SONAME 'CLONE_PLUGIN';
SET GLOBAL clone_ddl_timeout = 0;

############################################################
# 2. Bootstrap server1 and add some data
include/start_and_bootstrap_group_replication.inc
CREATE TABLE t1 (c1 INT NOT NULL PRIMARY KEY) ENGINE=InnoDB;
INSERT INTO t1 VALUES (1);
INSERT INTO t1 VALUES (2);

#######################################################################
# 3. Restart server 2 with a monitoring process (mysqld_safe) if needed
[connection server2]
include/spawn_monitoring_process.inc

############################################################
# 4. Setup the server so group replication starts on boot
#    Install the Clone plugin
INSTALL PLUGIN clone SONAME 'CLONE_PLUGIN';

############################################################
# 5. On a empty server2 start group replication
#    Pause it and execute a DDL query on the donor
#    The clone process should fail on the joiner
SET GLOBAL group_replication_clone_threshold= 1;
SET GLOBAL clone_autotune_concurrency = OFF;
SET GLOBAL clone_max_concurrency = 1;
SET GLOBAL clone_ddl_timeout = 0;
SET @@GLOBAL.DEBUG='+d,gr_clone_wait';
START GROUP_REPLICATION;
SET DEBUG_SYNC = 'now WAIT_FOR gr_clone_paused';
SET @@GLOBAL.DEBUG='-d,gr_clone_wait';
[connection server_1_1]
ALTER TABLE t1 ADD COLUMN col2 int, ALGORITHM=COPY;
[connection server1]
[connection server2]
SET DEBUG_SYNC = 'now SIGNAL gr_clone_continue';
include/gr_wait_for_member_state.inc
include/assert.inc [Clone should have failed]
include/assert_grep.inc [Clone failed and no recovery is possible]

############################################################
# 6. Restart Group replication
#    The clone process should now be successful
include/stop_group_replication.inc
START GROUP_REPLICATION;
include/rpl_reconnect.inc
include/gr_wait_for_member_state.inc
include/diff_tables.inc [server1:test.t1 ,server2:test.t1]

############################################################
# 7. Cleanup
SET GLOBAL group_replication_clone_threshold= CLONE_THRESHOLD_VALUE;
RESET PERSIST IF EXISTS group_replication_group_name;
RESET PERSIST IF EXISTS group_replication_local_address;
RESET PERSIST IF EXISTS group_replication_group_seeds;
RESET PERSIST IF EXISTS group_replication_start_on_boot;
SET GLOBAL group_replication_start_on_boot= START_ON_BOOT_VALUE;
[connection server_1_1]
DROP TABLE t1;
include/rpl_sync.inc
[connection server2]
include/clean_monitoring_process.inc
set session sql_log_bin=0;
call mtr.add_suppression("Clone removing all user data for provisioning: Started");
call mtr.add_suppression("Clone removing all user data for provisioning: Finished");
call mtr.add_suppression("This member will start distributed recovery using clone. It is due to the number of missing transactions being higher than the configured threshold of 1.");
call mtr.add_suppression("Internal query: CLONE INSTANCE FROM \'root\'@\'127.0.0.1\':[0-9]+ IDENTIFIED BY \'\\*\\*\\*\\*\\*\' REQUIRE NO SSL; result in error. Error number:*");
call mtr.add_suppression("There was an issue when cloning from another server: Error number: 3862 Error message: Clone Donor Error: 3633 : Concurrent DDL is performed during clone operation. Please try again.");
call mtr.add_suppression("Due to a critical cloning error or lack of donors, distributed recovery cannot be executed. The member will now leave the group.");
call mtr.add_suppression("Skipping leave operation: concurrent attempt to leave the group is on-going.");
set session sql_log_bin=1;
[connection server1]
UNINSTALL PLUGIN clone;
[connection server2]
UNINSTALL PLUGIN clone;
include/group_replication_end.inc

{'repo_name': 'percona/percona-xtrabackup', 'stars': '608', 'repo_language': 'C++', 'file_name': 'idx_compare_esms_global_by_event_name.result', 'mime_type': 'text/plain', 'hash': -4675765833294821431, 'source_dataset': 'data'}


[/
    Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

    Official repository: https://github.com/boostorg/beast
]

[section:echo Echo __example__]

This example develops an initiating function called [*echo].
The operation will read up to the first newline on a stream, and
then write the same line including the newline back on the stream.
First we define the input parameters and results, then declare our
initiation function. For our echo operation the only inputs are the
stream and the completion token. The output is the error code which
is usually included in all completion handler signatures.

[example_core_echo_op_2]

Now that we have a declaration, we will define the body of the function.
We want to achieve the following goals: perform static type checking on
the input parameters, set up the return value as per __N3747__, and launch
the composed operation by constructing an intermediate, stateful completion
handler and invoking it.

The initiating function contains a few relatively simple parts. There is
the customization of the return value type, static type checking, building
the return value type using the helper, and creating and launching the
`echo_op` composed operation object.

The implementation strategy is to make the composed object meet the
requirements of a completion handler by being movable, and by making it
invocable so it can be used as a continuation for the asynchronous operations
it launches. Rather than using `std::bind` or `boost::bind`, which destroys
the type information and therefore breaks the allocation and invocation hooks,
we will simply pass `std::move(*this)` as the completion handler parameter for
any operations that we initiate. For the move to work correctly, care must be
taken to ensure that no access to data members are made after the move takes
place. Here is the complete implementation of our composed operation:

[example_core_echo_op_3]

There are some common mistakes that should be avoided when writing
composed operations:

* Type erasing the final handler. This will cause undefined behavior.

* Forgetting to include a return statement after calling an
  initiating function.

* Calling a synchronous function by accident. In general composed
  operations should not block for long periods of time, since this
  ties up a thread running on the __io_context__.

* Forgetting to provide `executor_type` and `get_executor` for the
  composed operation. This will cause undefined behavior. For example,
  if someone  calls the initiating function with a strand-wrapped
  function object, and there is more than thread running on the
  __io_context__, the underlying stream may be accessed in a fashion
  that violates safety guarantees. Beast provides class templates
  to take care of this boilerplate for you.

* Forgetting to create an object of type __executor_work_guard__ with the
  type of executor returned by the stream's `get_executor` member function.

* For operations which complete immediately (i.e. without calling an
  intermediate initiating function), forgetting to use __post__ to
  invoke the final handler. This breaks the following initiating
  function guarantee: ['Regardless of whether the asynchronous operation
  completes immediately or not, the handler will not be invoked from
  within this function. Invocation of the handler will be performed
  in a manner equivalent to using __post__]. The function
  __bind_handler__ is provided for this purpose.

The listing for a complete, runnable version of this example is in
[path_link example/echo-op/echo_op.cpp echo_op.cpp].

[endsect]

{'repo_name': 'boostorg/beast', 'stars': '2628', 'repo_language': 'C++', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': -1713511209319966390, 'source_dataset': 'data'}


CREATE TABLE [mp_PollOptions](
	[OptionGuid] [uniqueidentifier] NOT NULL,
	[PollGuid] [uniqueidentifier] NOT NULL,
	[Answer] [nvarchar](255) NOT NULL,
	[Votes] [int] NOT NULL,
	[Order] [int] NOT NULL,
 CONSTRAINT [PK_mp_PollOptions] PRIMARY KEY
(
	[OptionGuid]
)
)
GO

CREATE TABLE [mp_PollUsers](
	[PollGuid] [uniqueidentifier] NOT NULL,
	[UserGuid] [uniqueidentifier] NOT NULL,
	[OptionGuid] [uniqueidentifier] NOT NULL,
 CONSTRAINT [PK_mp_PollUsers] PRIMARY KEY
(
	[PollGuid] ,
	[UserGuid]
)
)
GO

CREATE TABLE [mp_PollModules](
	[PollGuid] [uniqueidentifier] NOT NULL,
	[ModuleID] [int] NOT NULL,
 CONSTRAINT [PK_mp_PollModules] PRIMARY KEY
(
	[PollGuid] ,
	[ModuleID]
)
)
GO

CREATE TABLE [mp_Polls](
	[PollGuid] [uniqueidentifier] NOT NULL,
	[SiteGuid] [uniqueidentifier] NOT NULL,
	[Question] [nvarchar](255) NOT NULL,
	[Active] [bit] NOT NULL,
	[AnonymousVoting] [bit] NOT NULL,
	[AllowViewingResultsBeforeVoting] [bit] NOT NULL,
	[ShowOrderNumbers] [bit] NOT NULL,
	[ShowResultsWhenDeactivated] [bit] NOT NULL,
	[ActiveFrom] [datetime] NOT NULL,
	[ActiveTo] [datetime] NOT NULL,
 CONSTRAINT [PK_mp_Polls] PRIMARY KEY
(
	[PollGuid]
)
)
GO

ALTER TABLE [mp_PollOptions] ADD  CONSTRAINT [DF_mp_PollOption_Votes]  DEFAULT ((0)) FOR [Votes]
GO

ALTER TABLE [mp_PollOptions] ADD  CONSTRAINT [DF_mp_PollOptions_Order]  DEFAULT ((1)) FOR [Order]
GO

ALTER TABLE [mp_Polls] ADD  CONSTRAINT [DF_mp_Poll_Active]  DEFAULT ((1)) FOR [Active]
GO

ALTER TABLE [mp_Polls] ADD  CONSTRAINT [DF_mp_Polls_AnonymousVoting]  DEFAULT ((0)) FOR [AnonymousVoting]
GO

ALTER TABLE [mp_Polls] ADD  CONSTRAINT [DF_mp_Polls_AllowViewingResultsBeforeVoting]  DEFAULT ((0)) FOR [AllowViewingResultsBeforeVoting]
GO

ALTER TABLE [mp_Polls] ADD  CONSTRAINT [DF_mp_Polls_ShowOrderNumbers]  DEFAULT ((0)) FOR [ShowOrderNumbers]
GO

ALTER TABLE [mp_Polls] ADD  CONSTRAINT [DF_mp_Polls_ShowResultsWhenDeactivated]  DEFAULT ((0)) FOR [ShowResultsWhenDeactivated]
GO

ALTER TABLE [mp_Polls] ADD  CONSTRAINT [DF_mp_Polls_ActiveFrom]  DEFAULT (getdate()) FOR [ActiveFrom]
GO

ALTER TABLE [mp_Polls] ADD  CONSTRAINT [DF_mp_Polls_ActiveTo]  DEFAULT (getdate()) FOR [ActiveTo]
GO

{'repo_name': 'i7MEDIA/mojoportal', 'stars': '147', 'repo_language': 'C#', 'file_name': 'DBGallery.cs', 'mime_type': 'text/plain', 'hash': -1160868594089231983, 'source_dataset': 'data'}


//
//     Generated by class-dump 3.5 (64 bit) (Debug version compiled Jun  9 2015 22:53:21).
//
//     class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2014 by Steve Nygard.
//

#import <AppKit/NSWindowController.h>

@class IOBluetoothDevice, IOBluetoothHostController, NSButton, NSTextField, NSTimer;

@interface NumericComparisonWindowControllerSMP : NSWindowController
{
    NSButton *_buttonYes;
    NSButton *_buttonNo;
    NSTextField *_textFieldPasskey;
    NSTextField *_textFieldDeviceName;
    NSTextField *_textFieldDescription;
    NSButton *_ignoreDevice;
    NSTimer *_timer;
    IOBluetoothDevice *_device;
    struct BluetoothDeviceAddress _deviceAddress;
    IOBluetoothHostController *_hostController;
}

@property(retain) IOBluetoothDevice *device; // @synthesize device=_device;
- (void).cxx_destruct;
- (void)sendXPCmessage:(BOOL)arg1 addressString:(id)arg2;
- (void)handleNoButton:(id)arg1;
- (void)handleYesButton:(id)arg1;
- (void)BluetoothHCIEventNotificationMessage:(id)arg1 inNotificationMessage:(const struct IOBluetoothHCIEventNotificationMessage *)arg2;
- (void)deviceDisconnected:(id)arg1 device:(id)arg2;
- (void)controlTextDidChange:(id)arg1;
- (void)timeoutTimerFired:(id)arg1;
- (void)cleanupAndQuit;
- (void)startForDevice:(id)arg1 inNumericValue:(id)arg2 sc:(BOOL)arg3;
- (void)awakeFromNib;
- (id)windowNibName;

@end

{'repo_name': 'w0lfschild/macOS_headers', 'stars': '304', 'repo_language': 'None', 'file_name': 'NSTextFinderBarContainer-Protocol.h', 'mime_type': 'text/x-objective-c', 'hash': 3843356361257569159, 'source_dataset': 'data'}


/* -*- Mode: js; js-indent-level: 2; -*- */
/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

var util = require('./util');
var has = Object.prototype.hasOwnProperty;
var hasNativeMap = typeof Map !== "undefined";

/**
 * A data structure which is a combination of an array and a set. Adding a new
 * member is O(1), testing for membership is O(1), and finding the index of an
 * element is O(1). Removing elements from the set is not supported. Only
 * strings are supported for membership.
 */
function ArraySet() {
  this._array = [];
  this._set = hasNativeMap ? new Map() : Object.create(null);
}

/**
 * Static method for creating ArraySet instances from an existing array.
 */
ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  var set = new ArraySet();
  for (var i = 0, len = aArray.length; i < len; i++) {
    set.add(aArray[i], aAllowDuplicates);
  }
  return set;
};

/**
 * Return how many unique items are in this ArraySet. If duplicates have been
 * added, than those do not count towards the size.
 *
 * @returns Number
 */
ArraySet.prototype.size = function ArraySet_size() {
  return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
};

/**
 * Add the given string to this set.
 *
 * @param String aStr
 */
ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
  var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  var idx = this._array.length;
  if (!isDuplicate || aAllowDuplicates) {
    this._array.push(aStr);
  }
  if (!isDuplicate) {
    if (hasNativeMap) {
      this._set.set(aStr, idx);
    } else {
      this._set[sStr] = idx;
    }
  }
};

/**
 * Is the given string a member of this set?
 *
 * @param String aStr
 */
ArraySet.prototype.has = function ArraySet_has(aStr) {
  if (hasNativeMap) {
    return this._set.has(aStr);
  } else {
    var sStr = util.toSetString(aStr);
    return has.call(this._set, sStr);
  }
};

/**
 * What is the index of the given string in the array?
 *
 * @param String aStr
 */
ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  if (hasNativeMap) {
    var idx = this._set.get(aStr);
    if (idx >= 0) {
        return idx;
    }
  } else {
    var sStr = util.toSetString(aStr);
    if (has.call(this._set, sStr)) {
      return this._set[sStr];
    }
  }

  throw new Error('"' + aStr + '" is not in the set.');
};

/**
 * What is the element at the given index?
 *
 * @param Number aIdx
 */
ArraySet.prototype.at = function ArraySet_at(aIdx) {
  if (aIdx >= 0 && aIdx < this._array.length) {
    return this._array[aIdx];
  }
  throw new Error('No element indexed by ' + aIdx);
};

/**
 * Returns the array representation of this set (which has the proper indices
 * indicated by indexOf). Note that this is a copy of the internal array used
 * for storing the members so that no one can mess with internal state.
 */
ArraySet.prototype.toArray = function ArraySet_toArray() {
  return this._array.slice();
};

exports.ArraySet = ArraySet;

{'repo_name': 'in28minutes/full-stack-with-react-and-spring-boot', 'stars': '172', 'repo_language': 'JavaScript', 'file_name': 'README.md', 'mime_type': 'text/plain', 'hash': -3916456581324495351, 'source_dataset': 'data'}


/*************************************************************
 *
 *  MathJax/jax/output/HTML-CSS/fonts/STIX-Web/SansSerif/Bold/Main.js
 *
 *  Copyright (c) 2013-2014 The MathJax Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['STIXMathJax_SansSerif-bold'] = {
  directory: 'SansSerif/Bold',
  family: 'STIXMathJax_SansSerif',
  weight: 'bold',
  testString: '\u00A0\uD835\uDDD4\uD835\uDDD5\uD835\uDDD6\uD835\uDDD7\uD835\uDDD8\uD835\uDDD9\uD835\uDDDA\uD835\uDDDB\uD835\uDDDC\uD835\uDDDD\uD835\uDDDE\uD835\uDDDF\uD835\uDDE0\uD835\uDDE1',
  0x20: [0,0,250,0,0],
  0xA0: [0,0,250,0,0],
  0x1D5D4: [690,0,690,25,665],
  0x1D5D5: [676,0,636,80,594],
  0x1D5D6: [691,19,723,49,688],
  0x1D5D7: [676,0,709,80,674],
  0x1D5D8: [676,0,635,80,597],
  0x1D5D9: [676,0,582,80,570],
  0x1D5DA: [691,19,746,37,671],
  0x1D5DB: [676,0,715,80,635],
  0x1D5DC: [676,0,440,65,375],
  0x1D5DD: [676,96,481,15,406],
  0x1D5DE: [676,0,712,80,707],
  0x1D5DF: [676,0,603,80,587],
  0x1D5E0: [676,0,913,80,833],
  0x1D5E1: [676,18,724,80,644],
  0x1D5E2: [692,18,778,35,743],
  0x1D5E3: [676,0,581,80,569],
  0x1D5E4: [691,176,779,35,754],
  0x1D5E5: [676,0,670,80,657],
  0x1D5E6: [691,19,554,35,511],
  0x1D5E7: [676,0,641,14,627],
  0x1D5E8: [676,19,699,75,624],
  0x1D5E9: [676,18,690,25,665],
  0x1D5EA: [676,15,997,30,967],
  0x1D5EB: [676,0,740,40,700],
  0x1D5EC: [676,0,694,20,674],
  0x1D5ED: [676,0,653,25,623],
  0x1D5EE: [473,14,489,23,428],
  0x1D5EF: [676,13,512,55,487],
  0x1D5F0: [473,14,462,25,442],
  0x1D5F1: [676,14,518,25,463],
  0x1D5F2: [473,13,452,25,433],
  0x1D5F3: [691,0,340,14,374],
  0x1D5F4: [473,206,504,28,490],
  0x1D5F5: [676,0,510,55,455],
  0x1D5F6: [688,0,245,50,195],
  0x1D5F7: [688,203,324,-57,269],
  0x1D5F8: [676,0,519,55,506],
  0x1D5F9: [676,0,235,55,180],
  0x1D5FA: [473,0,776,55,721],
  0x1D5FB: [473,0,510,55,455],
  0x1D5FC: [473,14,501,25,476],
  0x1D5FD: [473,205,512,55,487],
  0x1D5FE: [473,205,512,25,457],
  0x1D5FF: [473,0,411,55,406],
  0x1D600: [473,13,385,25,357],
  0x1D601: [630,12,386,7,371],
  0x1D602: [461,15,518,55,463],
  0x1D603: [461,14,462,15,447],
  0x1D604: [461,14,701,17,684],
  0x1D605: [461,0,506,20,486],
  0x1D606: [461,205,472,18,455],
  0x1D607: [461,0,441,21,417],
  0x1D756: [690,0,690,25,665],
  0x1D757: [676,0,636,80,594],
  0x1D758: [676,0,591,80,569],
  0x1D759: [690,0,720,40,680],
  0x1D75A: [676,0,635,80,597],
  0x1D75B: [676,0,653,25,623],
  0x1D75C: [676,0,715,80,635],
  0x1D75D: [691,19,778,35,743],
  0x1D75E: [676,0,440,65,375],
  0x1D75F: [676,0,712,80,707],
  0x1D760: [690,0,706,40,666],
  0x1D761: [676,0,913,80,833],
  0x1D762: [676,18,724,80,644],
  0x1D763: [676,0,640,35,605],
  0x1D764: [692,18,778,35,743],
  0x1D765: [676,0,715,80,635],
  0x1D766: [676,0,581,80,569],
  0x1D767: [691,19,778,35,743],
  0x1D768: [676,0,674,28,632],
  0x1D769: [676,0,641,14,627],
  0x1D76A: [691,0,748,20,728],
  0x1D76B: [676,0,800,25,775],
  0x1D76C: [676,0,740,40,700],
  0x1D76D: [691,0,806,15,791],
  0x1D76E: [691,0,752,32,720],
  0x1D76F: [664,30,735,45,685],
  0x1D770: [473,14,662,40,629],
  0x1D771: [692,205,512,39,487],
  0x1D772: [473,205,502,10,477],
  0x1D773: [692,14,502,25,477],
  0x1D774: [473,14,451,25,434],
  0x1D775: [692,205,500,28,488],
  0x1D776: [473,205,510,35,474],
  0x1D777: [692,14,500,23,477],
  0x1D778: [461,14,319,53,296],
  0x1D779: [473,0,527,55,512],
  0x1D77A: [692,14,554,18,520],
  0x1D77B: [461,205,550,39,517],
  0x1D77C: [473,14,492,55,472],
  0x1D77D: [692,205,501,28,489],
  0x1D77E: [473,14,501,25,476],
  0x1D77F: [461,14,594,10,572],
  0x1D780: [473,205,511,38,486],
  0x1D781: [473,205,498,26,486],
  0x1D782: [461,14,520,25,552],
  0x1D783: [461,14,479,6,472],
  0x1D784: [473,14,514,35,489],
  0x1D785: [473,205,634,25,609],
  0x1D786: [473,205,573,9,553],
  0x1D787: [473,205,680,25,699],
  0x1D788: [461,14,740,42,689],
  0x1D789: [691,14,501,25,476],
  0x1D78A: [473,14,462,25,440],
  0x1D78B: [692,14,536,35,522],
  0x1D78C: [473,14,570,14,554],
  0x1D78D: [692,205,634,25,609],
  0x1D78E: [473,205,494,25,469],
  0x1D78F: [461,14,848,6,839],
  0x1D7EC: [688,13,500,24,476],
  0x1D7ED: [688,0,500,82,334],
  0x1D7EE: [688,0,500,20,474],
  0x1D7EF: [688,13,500,18,479],
  0x1D7F0: [688,0,500,19,484],
  0x1D7F1: [676,13,500,13,483],
  0x1D7F2: [688,13,500,26,475],
  0x1D7F3: [676,0,500,35,471],
  0x1D7F4: [688,13,500,28,472],
  0x1D7F5: [688,13,500,26,475]
};

MathJax.Callback.Queue(
  ["initFont",MathJax.OutputJax["HTML-CSS"],"STIXMathJax_SansSerif-bold"],
  ["loadComplete",MathJax.Ajax,MathJax.OutputJax["HTML-CSS"].fontDir+"/SansSerif/Bold/Main.js"]
);

{'repo_name': 'rhiokim/haroopad', 'stars': '1458', 'repo_language': 'JavaScript', 'file_name': 'default.css', 'mime_type': 'text/plain', 'hash': -2213288543546792910, 'source_dataset': 'data'}


# -*- coding: utf-8 -*-
#*****************************************************************************
#       Copyright (C) 2006  Jorgen Stenarson. <jorgen.stenarson@bostream.nu>
#
#  Distributed under the terms of the BSD License.  The full license is in
#  the file COPYING, distributed as part of this software.
#*****************************************************************************
import socket

try:
    import msvcrt
except ImportError:
    msvcrt=None
    print "problem"

port =8081

s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

s.bind(("",port))
s.settimeout(0.05)

print "Starting logserver on port:",port
print "Press q to quit logserver",port
singleline=False

def check_key():
    if msvcrt is None:
        return False
    else:
        if msvcrt.kbhit()!=0:
            q=msvcrt.getch()

            return q in "q"
        else:
            return False

while 1:
    try:
        data,addr=s.recvfrom(1024)
    except socket.timeout:
        if check_key():
            print "Quitting logserver"
            break
        else:
            continue
    if data.startswith("@@"):
        continue
    if singleline:
        print "\r"," "*78,"\r",data,#,addr
    else:
        print data

{'repo_name': 'RamadhanAmizudin/malware', 'stars': '338', 'repo_language': 'C++', 'file_name': 'xpcIJSWeakReference.h', 'mime_type': 'text/x-c++', 'hash': 3675242438278921146, 'source_dataset': 'data'}


{'repo_name': 'PeterLemon/N64', 'stars': '198', 'repo_language': 'C++', 'file_name': 'make.bat', 'mime_type': 'text/plain', 'hash': -4664572290979667472, 'source_dataset': 'data'}


Bare Bones Demo
======

This demo database contains:

- DDL of latest schema
- Minimum reference data required for deployment of platform which is:
  -  Its mandatory to have one selected currency so we default to US Dollar
  -  Its mandatory to have one root or head office, so we have one created by default called a 'Head Office'
  -  Permissions supported/needed by latest release of software are setup
  -  Its mandatory to have at least one role when creating new users so we have one role created by default called 'Super user' which has the special permission 'Full Authorisation'. Any user with this role can do anything in the system.
  -  Its required to have at least one application user setup so remaining setup can be done through ui so we have on application user created by default with username 'mifos' with a password of 'password'. Application users must be associated with an office and a role so this user is associated with 'Head office' and 'Super user' role allowing this user to do any operation in any office(branch).
- Configuration
  - No 'additional data' through the 'datatables' approach is setup
  - One 'code' is setup called 'Client Identifier' with default values of {'Passport number'} - (required for Client Identity Document functionalty)
  - Enable/Disable configuration has one entry named 'maker-checker' to allow people to enable disable this feature at global level. It is off or disabled by default.
- No products (loans, deposit, savings) are setup
- No Charges (fees or penalties) are setup
- No Staff (employees) are setup (loan officers are optional when submiting new loan application)
- No Portfolio data (no clients, groups, loan accounts, deposit accounts, savings accounts)
- No Accounting data (no chart of accounts is setup, by default accounting with respect to portfolio items is off unless enabled when creating a loan product.)

{'repo_name': 'apache/fineract', 'stars': '456', 'repo_language': 'Java', 'file_name': 'Drizzle.BSD', 'mime_type': 'text/plain', 'hash': -6234567399227145527, 'source_dataset': 'data'}


# frozen_string_literal: true

# This migration comes from active_storage (originally 20180723000244)
class AddForeignKeyConstraintToActiveStorageAttachmentsForBlobId < ActiveRecord::Migration[6.0]
  def up
    return if foreign_key_exists?(:active_storage_attachments, column: :blob_id)

    if table_exists?(:active_storage_blobs)
      add_foreign_key :active_storage_attachments, :active_storage_blobs, column: :blob_id
    end
  end
end

{'repo_name': 'fjordllc/bootcamp', 'stars': '109', 'repo_language': 'Ruby', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': -6785239072139376974, 'source_dataset': 'data'}


/*
 * Copyright 2015 Karl Dahlgren
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.castlemock.web.mock.soap.web.view.command.project;

import com.castlemock.core.mock.soap.model.project.domain.SoapMockResponse;
import com.castlemock.core.mock.soap.model.project.domain.SoapOperation;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * The WSDLFileUploadForm is a class that represent a form which contains a multipart files, URL to a specific WSDL
 * file and a boolean value used to indicate if SOAP mocked responses will be generated for each created
 * SOAP operation
 * @author Karl Dahlgren
 * @since 1.0
 * @see javax.wsdl.extensions.soap.SOAPOperation
 * @see SoapMockResponse
 */
public class WSDLFileUploadForm {

    private boolean generateResponse;
    private boolean includeImports;
    private List<MultipartFile> files;
    private String link;

    /**
     * Returns the multipart files
     * @return The multipart files
     */
    public List<MultipartFile> getFiles() {
        return files;
    }

    /**
     * Set new value to the multipart file list.
     * @param files The new value for the multipart list
     */
    public void setFiles(List<MultipartFile> files) {
        this.files = files;
    }

    /**
     * The value represent if one response will be generated upon operation creation.
     * True will generate SOAP mock responses for each SOAP operation created. False will not
     * create any mock responses
     * @return The generate response value
     * @see SoapOperation
     */
    public boolean isGenerateResponse() {
        return generateResponse;
    }

    /**
     * Set a new value to the generate response value
     * @param generateResponse The new value of the generate response, which will response the old one.
     */
    public void setGenerateResponse(boolean generateResponse) {
        this.generateResponse = generateResponse;
    }

    /**
     * The link to the WSDL. This option is used if the user does not upload a WSDL file, but links it instead
     * to an external source
     * @return The link to the WSDL file
     */
    public String getLink() {
        return link;
    }

    /**
     * Set a new value to the link
     * @param link The new value of the link, which will replace the old one
     */
    public void setLink(String link) {
        this.link = link;
    }

    public boolean isIncludeImports() {
        return includeImports;
    }

    public void setIncludeImports(boolean includeImports) {
        this.includeImports = includeImports;
    }
}

{'repo_name': 'castlemock/castlemock', 'stars': '107', 'repo_language': 'Java', 'file_name': 'RandomDateExpressionTest.java', 'mime_type': 'text/x-java', 'hash': 5414774825243254974, 'source_dataset': 'data'}


package im.zhaojun.common.shiro.realm;

import im.zhaojun.common.constants.AuthcTypeEnum;
import org.springframework.stereotype.Component;

/**
 * Github OAuth2 Realm
 */
@Component
public class OAuth2GithubRealm extends OAuth2Realm {

    @Override
    public AuthcTypeEnum getAuthcTypeEnum() {
        return AuthcTypeEnum.GITHUB;
    }
}

{'repo_name': 'zhaojun1998/Shiro-Action', 'stars': '314', 'repo_language': 'Java', 'file_name': 'SystemController.java', 'mime_type': 'text/x-java', 'hash': 4973739757488376056, 'source_dataset': 'data'}


// Copyright (C) 2014 Andrzej Krzemienski.
//
// Use, modification, and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/lib/optional for documentation.
//
// You are welcome to contact the author at:
//  akrzemi1@gmail.com

#include "boost/optional/optional.hpp"

#ifdef __BORLANDC__
#pragma hdrstop
#endif

using boost::optional;

#if (!defined BOOST_OPTIONAL_DETAIL_NO_IS_CONSTRUCTIBLE_TRAIT)

struct X {};
struct Y {};

struct Resource
{
  explicit Resource(const X&) {}
};

BOOST_STATIC_ASSERT((  boost::is_constructible<Resource, const X&>::value ));
BOOST_STATIC_ASSERT(( !boost::is_constructible<Resource, const Y&>::value ));

BOOST_STATIC_ASSERT((  boost::is_constructible<optional<Resource>, const X&>::value ));
BOOST_STATIC_ASSERT(( !boost::is_constructible<optional<Resource>, const Y&>::value ));

#ifndef BOOST_OPTIONAL_DETAIL_NO_SFINAE_FRIENDLY_CONSTRUCTORS
BOOST_STATIC_ASSERT((  boost::is_constructible< optional< optional<int> >, optional<int> >::value ));
BOOST_STATIC_ASSERT(( !boost::is_constructible< optional<int>, optional< optional<int> > >::value ));

BOOST_STATIC_ASSERT((  boost::is_constructible< optional< optional<int> >, const optional<int>& >::value ));
BOOST_STATIC_ASSERT(( !boost::is_constructible< optional<int>, const optional< optional<int> >& >::value ));

BOOST_STATIC_ASSERT((  boost::is_constructible<optional<Resource>, const optional<X>&>::value ));
BOOST_STATIC_ASSERT(( !boost::is_constructible<optional<Resource>, const optional<Y>&>::value ));
#endif

#endif

int main() { }

{'repo_name': 'vslavik/poedit', 'stars': '1009', 'repo_language': 'C++', 'file_name': 'eat.qbk', 'mime_type': 'text/plain', 'hash': -6696167310291159687, 'source_dataset': 'data'}


/*
 * Copyright (C) 2003, 2006, 2008 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_FONTS_FONT_FAMILY_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_FONTS_FONT_FAMILY_H_

#include "base/macros.h"
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"

namespace blink {

class SharedFontFamily;

class PLATFORM_EXPORT FontFamily {
  DISALLOW_NEW();

 public:
  FontFamily() = default;
  ~FontFamily();

  void SetFamily(const AtomicString& family) { family_ = family; }
  const AtomicString& Family() const { return family_; }
  bool FamilyIsEmpty() const { return family_.IsEmpty(); }

  const FontFamily* Next() const;

  void AppendFamily(scoped_refptr<SharedFontFamily>);
  void AppendFamily(AtomicString family);
  scoped_refptr<SharedFontFamily> ReleaseNext();

  // Returns this font family's name followed by all subsequent linked
  // families delimited by commas.
  String ToString() const;

 private:
  AtomicString family_;
  scoped_refptr<SharedFontFamily> next_;
};

class PLATFORM_EXPORT SharedFontFamily : public FontFamily,
                                         public RefCounted<SharedFontFamily> {
  USING_FAST_MALLOC(SharedFontFamily);
 public:
  static scoped_refptr<SharedFontFamily> Create() {
    return base::AdoptRef(new SharedFontFamily);
  }

 private:
  SharedFontFamily() = default;

  DISALLOW_COPY_AND_ASSIGN(SharedFontFamily);
};

PLATFORM_EXPORT bool operator==(const FontFamily&, const FontFamily&);
inline bool operator!=(const FontFamily& a, const FontFamily& b) {
  return !(a == b);
}

inline FontFamily::~FontFamily() {
  scoped_refptr<SharedFontFamily> reaper = std::move(next_);
  while (reaper && reaper->HasOneRef()) {
    // implicitly protects reaper->next, then derefs reaper
    reaper = reaper->ReleaseNext();
  }
}

inline const FontFamily* FontFamily::Next() const {
  return next_.get();
}

inline void FontFamily::AppendFamily(scoped_refptr<SharedFontFamily> family) {
  next_ = std::move(family);
}

inline scoped_refptr<SharedFontFamily> FontFamily::ReleaseNext() {
  return std::move(next_);
}

}  // namespace blink

#endif

{'repo_name': 'RainwayApp/spitfire', 'stars': '140', 'repo_language': 'C++', 'file_name': 'DataChannelObserver.h', 'mime_type': 'text/x-c++', 'hash': -7475662436513589866, 'source_dataset': 'data'}