text:
namespace media {

class AudioDecoderConfig;
class DecoderBuffer;
class VideoDecoderConfig;
class VideoFrame;

// Decrypts (and decodes) encrypted buffer.
//
// All methods are called on the (video/audio) decoder thread. Decryptor
// implementations must be thread safe when methods are called this way.
// Depending on the implementation callbacks may be fired synchronously or
// asynchronously.
class MEDIA_EXPORT Decryptor {
 public:
  enum Status {
    kSuccess,  // Decryption successfully completed. Decrypted buffer ready.
    kNoKey,    // No key is available to decrypt.
    kNeedMoreData,  // Decoder needs more data to produce a frame.
    kError,         // Key is available but an error occurred during decryption.
    kStatusMax = kError
  };

  static const char* GetStatusName(Status status);

  // TODO(xhwang): Unify this with DemuxerStream::Type.
  enum StreamType { kAudio, kVideo, kStreamTypeMax = kVideo };

  Decryptor();

  Decryptor(const Decryptor&) = delete;
  Decryptor& operator=(const Decryptor&) = delete;

  virtual ~Decryptor();

  // Indicates completion of a decryption operation.
  //
  // First parameter: The status of the decryption operation.
  // - Set to kSuccess if the encrypted buffer is successfully decrypted and
  //   the decrypted buffer is ready to be read.
  // - Set to kNoKey if no decryption key is available to decrypt the encrypted
  //   buffer. In this case the decrypted buffer must be NULL.
  // - Set to kError if unexpected error has occurred. In this case the
  //   decrypted buffer must be NULL.
  // - This parameter should not be set to kNeedMoreData.
  // Second parameter: The decrypted buffer.
  // - Only |data|, |data_size| and |timestamp| are set in the returned
  //   DecoderBuffer. The callback handler is responsible for setting other
  //   fields as appropriate.
  using DecryptCB =
      base::OnceCallback<void(Status, scoped_refptr<DecoderBuffer>)>;

  // Decrypts the |encrypted| buffer. The decrypt status and decrypted buffer
  // are returned via the provided callback |decrypt_cb|. The |encrypted| buffer
  // must not be NULL.
  // Decrypt() should not be called until any previous DecryptCB of the same
  // |stream_type| has completed. Thus, only one DecryptCB may be pending at
  // a time for a given |stream_type|.
  virtual void Decrypt(StreamType stream_type,
                       scoped_refptr<DecoderBuffer> encrypted,
                       DecryptCB decrypt_cb) = 0;

  // Cancels the scheduled decryption operation for |stream_type| and fires the
  // pending DecryptCB immediately with kSuccess and NULL.
  // Decrypt() should not be called again before the pending DecryptCB for the
  // same |stream_type| is fired.
  virtual void CancelDecrypt(StreamType stream_type) = 0;

  // Indicates completion of audio/video decoder initialization.
  //
  // First Parameter: Indicates initialization success.
  // - Set to true if initialization was successful. False if an error occurred.
  using DecoderInitCB = base::OnceCallback<void(bool)>;

  // Initializes a decoder with the given |config|, executing the |init_cb|
  // upon completion.
  virtual void InitializeAudioDecoder(const AudioDecoderConfig& config,
                                      DecoderInitCB init_cb) = 0;
  virtual void InitializeVideoDecoder(const VideoDecoderConfig& config,
                                      DecoderInitCB init_cb) = 0;

  // Helper structure for managing multiple decoded audio buffers per input.
  typedef std::list<scoped_refptr<AudioBuffer> > AudioFrames;

  // Indicates completion of audio/video decrypt-and-decode operation.
  //
  // First parameter: The status of the decrypt-and-decode operation.
  // - Set to kSuccess if the encrypted buffer is successfully decrypted and
  //   decoded. In this case, the decoded frame/buffers can be/contain:
  //   1) NULL, which means the operation has been aborted.
  //   2) End-of-stream (EOS) frame, which means that the decoder has hit EOS,
  //      flushed all internal buffers and cannot produce more video frames.
  //   3) Decrypted and decoded video frame or audio buffer.
  // - Set to kNoKey if no decryption key is available to decrypt the encrypted
  //   buffer. In this case the returned frame(s) must be NULL/empty.
  // - Set to kNeedMoreData if more data is needed to produce a video frame. In
  //   this case the returned frame(s) must be NULL/empty.
  // - Set to kError if unexpected error has occurred. In this case the
  //   returned frame(s) must be NULL/empty.
  // Second parameter: The decoded video frame or audio buffers.
  using AudioDecodeCB = base::OnceCallback<void(Status, const AudioFrames&)>;
  using VideoDecodeCB =
      base::OnceCallback<void(Status, scoped_refptr<VideoFrame>)>;

  // Decrypts and decodes the |encrypted| buffer. The status and the decrypted
  // buffer are returned via the provided callback.
  // The |encrypted| buffer must not be NULL.
  // At end-of-stream, this method should be called repeatedly with
  // end-of-stream DecoderBuffer until no frame/buffer can be produced.
  // These methods can only be called after the corresponding decoder has
  // been successfully initialized.
  // DecryptAndDecodeAudio() should not be called until any previous
  // AudioDecodeCB has completed. Thus, only one AudioDecodeCB may be pending at
  // any time. Same for DecryptAndDecodeVideo();
  virtual void DecryptAndDecodeAudio(scoped_refptr<DecoderBuffer> encrypted,
                                     AudioDecodeCB audio_decode_cb) = 0;
  virtual void DecryptAndDecodeVideo(scoped_refptr<DecoderBuffer> encrypted,
                                     VideoDecodeCB video_decode_cb) = 0;

  // Resets the decoder to an initialized clean state, cancels any scheduled
  // decrypt-and-decode operations, and fires any pending
  // AudioDecodeCB/VideoDecodeCB immediately with kError and NULL.
  // This method can only be called after the corresponding decoder has been
  // successfully initialized.
  virtual void ResetDecoder(StreamType stream_type) = 0;

  // Releases decoder resources, deinitializes the decoder, cancels any
  // scheduled initialization or decrypt-and-decode operations, and fires
  // any pending DecoderInitCB/AudioDecodeCB/VideoDecodeCB immediately.
  // DecoderInitCB should be fired with false. AudioDecodeCB/VideoDecodeCB
  // should be fired with kError.
  // This method can be called any time after Initialize{Audio|Video}Decoder()
  // has been called (with the correct stream type).
  // After this operation, the decoder is set to an uninitialized state.
  // The decoder can be reinitialized after it is uninitialized.
  virtual void DeinitializeDecoder(StreamType stream_type) = 0;

  // Returns whether or not the decryptor implementation supports decrypt-only.
  virtual bool CanAlwaysDecrypt();
};

}  // namespace media

#endif  // MEDIA_BASE_DECRYPTOR_H_


text:
"""
WebDAV COPY and MOVE methods.
"""

__all__ = ["http_COPY", "http_MOVE"]

from twisted.internet.defer import waitForDeferred, deferredGenerator

from twext.python.log import Logger
from txweb2 import responsecode
from txweb2.dav.fileop import move
from txweb2.http import HTTPError, StatusResponse
from txweb2.filter.location import addLocation
from txdav.xml import element as davxml
from txweb2.dav.idav import IDAVResource
from txweb2.dav.method import put_common
from txweb2.dav.util import parentForURL

# FIXME: This is circular
import txweb2.dav.static

log = Logger()

def http_COPY(self, request):
    """
    Respond to a COPY request. (RFC 2518, section 8.8)
    """
    r = waitForDeferred(prepareForCopy(self, request))
    yield r
    r = r.getResult()

    destination, destination_uri, depth = r

    #
    # Check authentication and access controls
    #
    x = waitForDeferred(self.authorize(request, (davxml.Read(),), recurse=True))
    yield x
    x.getResult()

    if destination.exists():
        x = waitForDeferred(destination.authorize(
            request,
            (davxml.WriteContent(), davxml.WriteProperties()),
            recurse=True
        ))
        yield x
        x.getResult()
    else:
        destparent = waitForDeferred(request.locateResource(parentForURL(destination_uri)))
        yield destparent
        destparent = destparent.getResult()

        x = waitForDeferred(destparent.authorize(request, (davxml.Bind(),)))
        yield x
        x.getResult()

        # May need to add a location header
        addLocation(request, destination_uri)

    # x = waitForDeferred(copy(self.fp, destination.fp, destination_uri, depth))
    x = waitForDeferred(put_common.storeResource(request,
                                                 source=self,
                                                 source_uri=request.uri,
                                                 destination=destination,
                                                 destination_uri=destination_uri,
                                                 deletesource=False,
                                                 depth=depth
                                                 ))
    yield x
    yield x.getResult()

http_COPY = deferredGenerator(http_COPY)

def http_MOVE(self, request):
    """
    Respond to a MOVE request. (RFC 2518, section 8.9)
    """
    r = waitForDeferred(prepareForCopy(self, request))
    yield r
    r = r.getResult()

    destination, destination_uri, depth = r

    #
    # Check authentication and access controls
    #
    parentURL = parentForURL(request.uri)
    parent = waitForDeferred(request.locateResource(parentURL))
    yield parent
    parent = parent.getResult()

    x = waitForDeferred(parent.authorize(request, (davxml.Unbind(),)))
    yield x
    x.getResult()

    if destination.exists():
        x = waitForDeferred(destination.authorize(
            request,
            (davxml.Bind(), davxml.Unbind()),
            recurse=True
        ))
        yield x
        x.getResult()
    else:
        destparentURL = parentForURL(destination_uri)
        destparent = waitForDeferred(request.locateResource(destparentURL))
        yield destparent
        destparent = destparent.getResult()

        x = waitForDeferred(destparent.authorize(request, (davxml.Bind(),)))
        yield x
        x.getResult()

        # May need to add a location header
        addLocation(request, destination_uri)

    #
    # RFC 2518, section 8.9 says that we must act as if the Depth header is set
    # to infinity, and that the client must omit the Depth header or set it to
    # infinity.
    #
    # This seems somewhat at odds with the notion that a bad request should be
    # rejected outright; if the client sends a bad depth header, the client is
    # broken, and section 8 suggests that a bad request should be rejected...
    #
    # Let's play it safe for now and ignore broken clients.
    #
    if self.isCollection() and depth != "infinity":
        msg = "Client sent illegal depth header value for MOVE: %s" % (depth,)
        log.error(msg)
        raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, msg))

    # Lets optimise a move within the same directory to a new resource as a simple move
    # rather than using the full transaction based storeResource api. This allows simple
    # "rename" operations to work quickly.
    if (not destination.exists()) and destparent == parent:
        x = waitForDeferred(move(self.fp, request.uri, destination.fp, destination_uri, depth))
    else:
        x = waitForDeferred(put_common.storeResource(request,
                                                     source=self,
                                                     source_uri=request.uri,
                                                     destination=destination,
                                                     destination_uri=destination_uri,
                                                     deletesource=True,
                                                     depth=depth))
    yield x
    yield x.getResult()

http_MOVE = deferredGenerator(http_MOVE)

def prepareForCopy(self, request):
    #
    # Get the depth
    #

    depth = request.headers.getHeader("depth", "infinity")

    if depth not in ("0", "infinity"):
        msg = ("Client sent illegal depth header value: %s" % (depth,))
        log.error(msg)
        raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, msg))

    #
    # Verify this resource exists
    #

    if not self.exists():
        log.error("File not found: %s" % (self,))
        raise HTTPError(StatusResponse(
            responsecode.NOT_FOUND,
            "Source resource %s not found." % (request.uri,)
        ))

    #
    # Get the destination
    #

    destination_uri = request.headers.getHeader("destination")

    if not destination_uri:
        msg = "No destination header in %s request." % (request.method,)
        log.error(msg)
        raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, msg))

    d = request.locateResource(destination_uri)
    d.addCallback(_prepareForCopy, destination_uri, request, depth)

    return d

def _prepareForCopy(destination, destination_uri, request, depth):
    #
    # Destination must be a DAV resource
    #

    try:
        destination = IDAVResource(destination)
    except TypeError:
        log.error("Attempt to %s to a non-DAV resource: (%s) %s"
                  % (request.method, destination.__class__, destination_uri))
        raise HTTPError(StatusResponse(
            responsecode.FORBIDDEN,
            "Destination %s is not a WebDAV resource." % (destination_uri,)
        ))

    #
    # FIXME: Right now we don't know how to copy to a non-DAVFile resource.
    # We may need some more API in IDAVResource.
    # So far, we need: .exists(), .fp.parent()
    #

    if not isinstance(destination, txweb2.dav.static.DAVFile):
        log.error("DAV copy between non-DAVFile DAV resources isn't implemented")
        raise HTTPError(StatusResponse(
            responsecode.NOT_IMPLEMENTED,
            "Destination %s is not a DAVFile resource." % (destination_uri,)
        ))

    #
    # Check for existing destination resource
    #

    overwrite = request.headers.getHeader("overwrite", True)

    if destination.exists() and not overwrite:
        log.error("Attempt to %s onto existing file without overwrite flag enabled: %s"
                  % (request.method, destination))
        raise HTTPError(StatusResponse(
            responsecode.PRECONDITION_FAILED,
            "Destination %s already exists." % (destination_uri,)
        ))

    #
    # Make sure destination's parent exists
    #

    if not destination.parent().isCollection():
        log.error("Attempt to %s to a resource with no parent: %s"
                  % (request.method, destination.fp.path))
        raise HTTPError(StatusResponse(responsecode.CONFLICT, "No parent collection."))

    return destination, destination_uri, depth

redpajama_set_name: RedPajamaGithub


text:
set -e

echo " * rustc version: `rustc --version`"

if [ "$PLATFORM" == "native" ]; then
  # build unit tests
  echo " * building zinc"
  cargo test --features test --lib --verbose
  echo " * building ioreg"
  (cd ./ioreg; cargo build --verbose; cargo test --verbose)
  echo " * building platformtree"
  (cd ./platformtree; cargo build --verbose; cargo test --verbose)
  echo " * building platformtree macro"
  (cd ./macro_platformtree; cargo build --verbose; cargo test --verbose)
  echo " * building zinc macro"
  (cd ./macro_zinc; cargo test --verbose)

  echo " * generating coverage data"
  if [ "$TRAVIS_JOB_ID" != "" ]; then
    kcov-master/tmp/usr/local/bin/kcov --coveralls-id=$TRAVIS_JOB_ID --exclude-pattern=/.cargo target/kcov target/debug/zinc-*
    kcov-master/tmp/usr/local/bin/kcov --coveralls-id=$TRAVIS_JOB_ID --exclude-pattern=/.cargo target/kcov ioreg/target/debug/test-*
    kcov-master/tmp/usr/local/bin/kcov --coveralls-id=$TRAVIS_JOB_ID --exclude-pattern=/.cargo target/kcov platformtree/target/debug/platformtree-*
  else
    kcov cov/ target/debug/zinc-*
    support/fixcov.py src/ cov/zinc-????????????????/cobertura.xml
    kcov cov/ ioreg/target/debug/test-*
    support/fixcov.py ioreg/src/ cov/test-????????????????/cobertura.xml
    kcov cov/ platformtree/target/debug/platformtree-*
    support/fixcov.py platformtree/src/ cov/platformtree-????????????????/cobertura.xml
  fi

else
  # build cross-compiled lib and examples
  case "$PLATFORM" in
    lpc11xx )
      TARGET=thumbv6m-none-eabi
      EXAMPLES="empty"
      ;;
    lpc17xx )
      TARGET=thumbv7m-none-eabi
      EXAMPLES="empty blink_lpc17xx blink_pt uart dht22 rgb_pwm_lpc17xx adc_lpc17xx"
      ;;
    k20 )
      TARGET=thumbv7em-none-eabi
      EXAMPLES="empty blink_k20 blink_k20_isr"
      ;;
    stm32f1 )
      TARGET=thumbv7m-none-eabi
      EXAMPLES="empty blink_stm32f1 usart_stm32f1"
      ;;
    stm32f4 )
      TARGET=thumbv7em-none-eabi
      EXAMPLES="empty blink_stm32f4"
      ;;
    stm32l1 )
      TARGET=thumbv7m-none-eabi
      EXAMPLES="empty blink_stm32l1 bluenrg_stm32l1 usart_stm32l1"
      ;;
  esac

  cargo build --target=$TARGET --verbose --features "mcu_$PLATFORM" --lib

  for e in $EXAMPLES; do
    pushd "examples/$e"
    cargo build --target=$TARGET --verbose --features "mcu_$PLATFORM" --release
    popd
  done
fi


text:
import debug from 'debug';
import { resolve, basename } from 'path';
import { writeFileSync } from 'fs';
import shell from 'shelljs';
import inquirer from 'inquirer';
import { merge } from 'lodash';
import stringify from "../utils/stringify";

import logger from '../logger';
import Context from '../Context';

const _debug = debug('plutarch');

const context = new Context();
const { paths: { app, tpls } } = context;

inquirer.prompt([{
  type: 'list',
  name: 'type',
  message: 'which project do you want to initilize?',
  choices: ['dva', 'redux', 'mobx', 'lib']
}, {
  type: 'input',
  name: 'name',
  message: `project name: `,
  default: basename(app)
}, {
  type: 'input',
  name: 'version',
  message: `version: `,
  default: '0.0.1'
}, {
  type: 'input',
  name: 'description',
  message: `description: `
}, {
  type: 'input',
  name: 'entry',
  message: `entry point: `,
  default: 'index.js'
}, {
  type: 'input',
  name: 'keywords',
  message: 'keywords: '
}, {
  type: 'input',
  name: 'git',
  message: 'git repository: '
}, {
  type: 'input',
  name: 'author',
  message: 'author: '
}, {
  type: 'input',
  name: 'license',
  message: 'license: ',
  default: 'ISC'
}]).then(answers => {
  const { type, entry, keywords, git, ...pkgConifg } = answers;

  _debug(`init ${type} project`);

  const tplPath = resolve(tpls, `${type}-project`);
  const pkgPath = resolve(app, 'package.json');
  let pkg = require(resolve(tplPath, 'package.json'));
  pkg = merge(pkg, {
    ...pkgConifg,
    main: entry,
    keywords: keywords ? keywords : [],
    repository: {
      type: 'git',
      url: git
    },
  });

  try{
    logger.blue(`begin to initilaize ${type} project`);

    shell.cp('-R', `${tplPath}/*`, app);

    writeFileSync(pkgPath, stringify(pkg), { encoding: 'utf8' });

    logger.blue('Done');
  }catch(e){
    logger.red(e);
  };
});


text:
package org.apache.felix.gogo.runtime;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.PrintStream;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.Channel;
import java.nio.channels.Channels;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.felix.service.command.Job;
import org.apache.felix.service.command.Job.Status;
import org.apache.felix.service.command.Process;
import org.apache.felix.gogo.runtime.CommandSessionImpl.JobImpl;
import org.apache.felix.gogo.runtime.Parser.Statement;
import org.apache.felix.gogo.runtime.Pipe.Result;
import org.apache.felix.service.command.Converter;
import org.apache.felix.service.threadio.ThreadIO;

public class Pipe implements Callable<Result>, Process
{
    private static final ThreadLocal<Pipe> CURRENT = new ThreadLocal<>();

    public static class Result implements org.apache.felix.service.command.Result {
        public final Object result;
        public final Exception exception;
        public final int error;

        public Result(Object result) {
            this.result = result;
            this.exception = null;
            this.error = 0;
        }

        public Result(Exception exception) {
            this.result = null;
            this.exception = exception;
            this.error = 1;
        }

        public Result(int error) {
            this.result = null;
            this.exception = null;
            this.error = error;
        }

        public boolean isSuccess() {
            return exception == null && error == 0;
        }

        @Override
        public Object result() {
            return result;
        }

        @Override
        public Exception exception() {
            return exception;
        }

        @Override
        public int error() {
            return error;
        }
    }

    public static Pipe getCurrentPipe() {
        return CURRENT.get();
    }

    private static Pipe setCurrentPipe(Pipe pipe) {
        Pipe previous = CURRENT.get();
        CURRENT.set(pipe);
        return previous;
    }

    final Closure closure;
    final Job job;
    final Statement statement;
    final Channel[] streams;
    final boolean[] toclose;
    final boolean endOfPipe;
    int error;

    InputStream in;
    PrintStream out;
    PrintStream err;

    public Pipe(Closure closure, JobImpl job, Statement statement, Channel[] streams, boolean[] toclose, boolean endOfPipe)
    {
        this.closure = closure;
        this.job = job;
        this.statement = statement;
        this.streams = streams;
        this.toclose = toclose;
        this.endOfPipe = endOfPipe;
    }

    public String toString()
    {
        return "pipe<" + statement + "> out=" + streams[1];
    }

    private static final int READ = 1;
    private static final int WRITE = 2;

    private void setStream(Channel ch, int fd, int readWrite) throws IOException {
        if ((readWrite & (READ | WRITE)) == 0) {
            throw new IllegalArgumentException("Should specify READ and/or WRITE");
        }
        if ((readWrite & READ) != 0 && !(ch instanceof ReadableByteChannel)) {
            throw new IllegalArgumentException("Channel is not readable");
        }
        if ((readWrite & WRITE) != 0 && !(ch instanceof WritableByteChannel)) {
            throw new IllegalArgumentException("Channel is not writable");
        }
        if (fd == 0 && (readWrite & READ) == 0) {
            throw new IllegalArgumentException("Stdin is not readable");
        }
        if (fd == 1 && (readWrite & WRITE) == 0) {
            throw new IllegalArgumentException("Stdout is not writable");
        }
        if (fd == 2 && (readWrite & WRITE) == 0) {
            throw new IllegalArgumentException("Stderr is not writable");
        }
        if (streams[fd] != null && (readWrite & READ) != 0 && (readWrite & WRITE) != 0) {
            throw new IllegalArgumentException("Can not do multios with read/write streams");
        }
        // If channel is inherited (for example standard input / output), replace it
        if (streams[fd] != null && !toclose[fd]) {
            streams[fd] = ch;
            toclose[fd] = true;
        }
        // Else do multios
        else {
            MultiChannel mrbc;
            // If the channel is already multios
            if (streams[fd] instanceof MultiChannel) {
                mrbc = (MultiChannel) streams[fd];
            }
            // Else create a multios channel
            else {
                mrbc = new MultiChannel();
                mrbc.addChannel(streams[fd], toclose[fd]);
                streams[fd] = mrbc;
                toclose[fd] = true;
            }
            mrbc.addChannel(ch, true);
        }
    }

    @Override
    public InputStream in() {
        return in;
    }

    @Override
    public PrintStream out() {
        return out;
    }

    @Override
    public PrintStream err() {
        return err;
    }

    @Override
    public Job job() {
        return job;
    }

    public boolean isTty(int fd) {
        // TODO: this assumes that the session is always created with input/output tty streams
        if (fd < 0 || fd > streams.length) {
            return false;
        }
        return streams[fd] != null && !toclose[fd];
    }

    public void error(int error) {
        this.error = error;
    }

    @Override
    public Result call() throws Exception {
        Thread thread = Thread.currentThread();
        String name = thread.getName();
        try {
            thread.setName("pipe-" + statement);
            return doCall();
        } finally {
            thread.setName(name);
        }
    }

    private Result doCall()
    {
        // The errChannel will be used to print errors to the error stream
        // Before the command is actually executed (i.e. during the initialization,
        // including the redirection processing), it will be the original error stream.
        // This value may be modified by redirections and the redirected error stream
        // will be effective just before actually running the command.
        WritableByteChannel errChannel = (WritableByteChannel) streams[2];

        ThreadIO threadIo = closure.session().threadIO();

        try
        {
            List<Token> tokens = statement.redirections();
            for (int i = 0; i < tokens.size(); i++)
            {
                Token t = tokens.get(i);
                Matcher m;
                if ((m = Pattern.compile("(?:([0-9])?|(&)?)>(>)?").matcher(t)).matches())
                {
                    int fd;
                    if (m.group(1) != null)
                    {
                        fd = Integer.parseInt(m.group(1));
                    }
                    else if (m.group(2) != null)
                    {
                        fd = -1; // both 1 and 2
                    }
                    else
                    {
                        fd = 1;
                    }
                    boolean append = m.group(3) != null;
                    Set<StandardOpenOption> options = new HashSet<>();
                    options.add(StandardOpenOption.WRITE);
                    options.add(StandardOpenOption.CREATE);
                    options.add(append ? StandardOpenOption.APPEND : StandardOpenOption.TRUNCATE_EXISTING);
                    Token tok = tokens.get(++i);
                    Object val = Expander.expand(tok, closure);
                    for (Path p : toPaths(val))
                    {
                        p = closure.session().currentDir().resolve(p);
                        Channel ch = Files.newByteChannel(p, options);
                        if (fd >= 0)
                        {
                            setStream(ch, fd, WRITE);
                        }
                        else
                        {
                            setStream(ch, 1, WRITE);
                            setStream(ch, 2, WRITE);
                        }
                    }
                }
                else if ((m = Pattern.compile("([0-9])?>&([0-9])").matcher(t)).matches())
                {
                    int fd0 = 1;
                    if (m.group(1) != null)
                    {
                        fd0 = Integer.parseInt(m.group(1));
                    }
                    int fd1 = Integer.parseInt(m.group(2));
                    if (streams[fd0] != null && toclose[fd0])
                    {
                        streams[fd0].close();
                    }
                    // If the stream has to be closed, close it when both streams are closed
                    if (toclose[fd1])
                    {
                        Channel channel = streams[fd1];
                        AtomicInteger references = new AtomicInteger();
                        streams[fd0] = new RefByteChannel(channel, references);
                        streams[fd1] = new RefByteChannel(channel, references);
                        toclose[fd0] = true;
                    }
                    else
                    {
                        streams[fd0] = streams[fd1];
                        toclose[fd0] = false;
                    }
                }
                else if ((m = Pattern.compile("([0-9])?<(>)?").matcher(t)).matches())
                {
                    int fd = 0;
                    if (m.group(1) != null)
                    {
                        fd = Integer.parseInt(m.group(1));
                    }
                    boolean output = m.group(2) != null;
                    Set<StandardOpenOption> options = new HashSet<>();
                    options.add(StandardOpenOption.READ);
                    if (output)
                    {
                        options.add(StandardOpenOption.WRITE);
                        options.add(StandardOpenOption.CREATE);
                    }
                    Token tok = tokens.get(++i);
                    Object val = Expander.expand(tok, closure);
                    for (Path p : toPaths(val))
                    {
                        p = closure.session().currentDir().resolve(p);
                        Channel ch = Files.newByteChannel(p, options);
                        setStream(ch, fd, READ + (output ? WRITE : 0));
                    }
                }
                else if ((m = Pattern.compile("<<-?").matcher(t)).matches())
                {
                    final Token hereDoc = tokens.get(++i);
                    final boolean stripLeadingTabs = t.charAt(t.length() - 1) == '-';
                    InputStream doc = new InputStream()
                    {
                        final byte[] bytes = hereDoc.toString().getBytes();
                        int index = 0;
                        boolean nl = true;
                        @Override
                        public int read() throws IOException
                        {
                            if (nl && stripLeadingTabs)
                            {
                                while (index < bytes.length && bytes[index] == '\t')
                                {
                                    index++;
                                }
                            }
                            if (index < bytes.length)
                            {
                                int ch = bytes[index++];
                                nl = ch == '\n';
                                return ch;
                            }
                            return -1;
                        }
                    };
                    Channel ch = Channels.newChannel(doc);
                    setStream(ch, 0, READ);
                }
                else if (Token.eq("<<<", t))
                {
                    Token word = tokens.get(++i);
                    Object val = Expander.expand("\"" + word + "\"", closure);
                    String str = val != null ? String.valueOf(val) : "";
                    Channel ch = Channels.newChannel(new ByteArrayInputStream(str.getBytes()));
                    setStream(ch, 0, READ);
                }
            }

            for (int i = 0; i < streams.length; i++) {
                streams[i] = wrap(streams[i]);
            }

            // Create streams
            in = Channels.newInputStream((ReadableByteChannel) streams[0]);
            out = new PrintStream(Channels.newOutputStream((WritableByteChannel) streams[1]), true);
            err = new PrintStream(Channels.newOutputStream((WritableByteChannel) streams[2]), true);
            // Change the error stream to the redirected one, now that
            // the command is about to be executed.
            errChannel = (WritableByteChannel) streams[2];

            if (threadIo != null)
            {
                threadIo.setStreams(in, out, err);
            }

            Pipe previous = setCurrentPipe(this);
            try
            {
                Object result;
                // Very special case for empty statements with redirection
                if (statement.tokens().isEmpty() && toclose[0])
                {
                    ByteBuffer bb = ByteBuffer.allocate(1024);
                    while (((ReadableByteChannel) streams[0]).read(bb) >= 0 || bb.position() != 0)
                    {
                        bb.flip();
                        ((WritableByteChannel) streams[1]).write(bb);
                        bb.compact();
                    }
                    result = null;
                }
                else
                {
                    result = closure.execute(statement);
                }
                // If an error has been set
                if (error != 0)
                {
                    return new Result(error);
                }
                // We don't print the result if we're at the end of the pipe
                if (result != null && !endOfPipe && !Boolean.FALSE.equals(closure.session().get(".FormatPipe")))
                {
                    out.println(closure.session().format(result, Converter.INSPECT));
                }
                return new Result(result);

            }
            finally
            {
                setCurrentPipe(previous);
            }
        }
        catch (Exception e)
        {
            if (!endOfPipe)
            {
                String msg = "gogo: " + e.getClass().getSimpleName() + ": " + e.getMessage() + "\n";
                try
                {
                    errChannel.write(ByteBuffer.wrap(msg.getBytes()));
                }
                catch (IOException ioe)
                {
                    e.addSuppressed(ioe);
                }
            }
            return new Result(e);
        }
        finally
        {
            if (out != null)
            {
                out.flush();
            }
            if (err != null)
            {
                err.flush();
            }
            if (threadIo != null)
            {
                threadIo.close();
            }

            try
            {
                for (int i = 0; i < 10; i++)
                {
                    if (toclose[i] && streams[i] != null)
                    {
                        streams[i].close();
                    }
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    private List<Path> toPaths(Object val) throws IOException
    {
        List<Path> paths = new ArrayList<>();
        if (val instanceof Collection)
        {
            for (Object o : (Collection) val)
            {
                Path p = toPath(o);
                if (p != null)
                {
                    paths.add(p);
                }
            }
        }
        else if (val != null)
        {
            Path p = toPath(val);
            if (p != null)
            {
                paths.add(p);
            }
        }
        if (paths.isEmpty())
        {
            throw new IOException("no such file or directory");
        }
        return paths;
    }

    private Path toPath(Object o)
    {
        if (o instanceof Path)
        {
            return (Path) o;
        }
        else if (o instanceof File)
        {
            return ((File) o).toPath();
        }
        else if (o instanceof URI)
        {
            return Paths.get((URI) o);
        }
        else if (o != null)
        {
            String s = String.valueOf(o);
            if (!s.isEmpty())
            {
                return Paths.get(String.valueOf(o));
            }
        }
        return null;
    }

    private Channel wrap(Channel channel)
    {
        if (channel == null)
        {
            return null;
        }
        if (channel instanceof MultiChannel)
        {
            return channel;
        }
        MultiChannel mch = new MultiChannel();
        mch.addChannel(channel, true);
        return mch;
    }

    private class RefByteChannel implements ByteChannel {

        private final Channel channel;
        private final AtomicInteger references;
        private final AtomicBoolean closed = new AtomicBoolean(false);

        public RefByteChannel(Channel channel, AtomicInteger references) {
            this.channel = channel;
            this.references = references;
            references.incrementAndGet();
        }

        @Override
        public int read(ByteBuffer dst) throws IOException {
            ensureOpen();
            return ((ReadableByteChannel) channel).read(dst);
        }

        @Override
        public int write(ByteBuffer src) throws IOException {
            ensureOpen();
            return ((WritableByteChannel) channel).write(src);
        }

        @Override
        public boolean isOpen() {
            return !closed.get();
        }

        private void ensureOpen() throws ClosedChannelException {
            if (closed.get()) throw new ClosedChannelException();
        }

        @Override
        public void close() throws IOException {
            if (closed.compareAndSet(false, true)) {
                if (references.decrementAndGet() == 0) {
                    channel.close();
                }
            }
        }

    }

    private class MultiChannel implements ByteChannel {
        protected final List<Channel> channels = new ArrayList<>();
        protected final List<Channel> toClose = new ArrayList<>();
        protected final AtomicBoolean opened = new AtomicBoolean(true);
        int index = 0;

        public void addChannel(Channel channel, boolean toclose) {
            channels.add(channel);
            if (toclose) {
                toClose.add(channel);
            }
        }

        public boolean isOpen() {
            return opened.get();
        }

        public void close() throws IOException {
            if (opened.compareAndSet(true, false)) {
                for (Channel channel : toClose) {
                    channel.close();
                }
            }
        }

        public int read(ByteBuffer dst) throws IOException {
            int nbRead = -1;
            while (nbRead < 0 && index < channels.size()) {
                Channel ch = channels.get(index);
                checkSuspend(ch);
                nbRead = ((ReadableByteChannel) ch).read(dst);
                if (nbRead < 0) {
                    index++;
                } else {
                    break;
                }
            }
            return nbRead;
        }

        public int write(ByteBuffer src) throws IOException {
            int pos = src.position();
            for (Channel ch : channels) {
                checkSuspend(ch);
                src.position(pos);
                while (src.hasRemaining()) {
                    ((WritableByteChannel) ch).write(src);
                }
            }
            return src.position() - pos;
        }

        private void checkSuspend(Channel ch) throws IOException {
            Channel[] sch = closure.session().channels;
            if (ch == sch[0] || ch == sch[1] || ch == sch[2]) {
                synchronized (job) {
                    if (job.status() == Status.Background) {
                        // TODO: Send SIGTIN / SIGTOU
                        job.suspend();
                    }
                }
            }
            synchronized (job) {
                while (job.status() == Status.Suspended) {
                    try {
                        job.wait();
                    } catch (InterruptedException e) {
                        throw (IOException) new InterruptedIOException().initCause(e);
                    }
                }
            }
        }
    }

}


text:
import Ember from 'ember';

export default Ember.Route.extend({
  idName: 'raffle_ticket_id',
  modelName: 'raffle-ticket',

  model: function(params) {
    const raffle = this.modelFor('events.show.raffles.show');
    const idName = this.get('idName');
    const modelName = this.get('modelName');

    const record = this.store.findRecord(modelName, params[idName], {
      adapterOptions: {
        query: {
          raffle_id: raffle.get('id'),
          include: 'registrations'
        }
      }
    });

    return record;
  }
});


text:
SELECT 'hello world';
select N'testing conflict on N - spec symbol and N - as identifier' as n;
select n'abc' as tstConstrN;
select N'abc' "bcd" 'asdfasdf' as tstConstNAndConcat;
select 'afdf' "erwhg" "ads" 'dgs' "rter" as tstDiffQuoteConcat;
select 'some string' COLLATE latin1_danish_ci as tstCollate;
select _latin1'some string' COLLATE latin1_danish_ci as tstCollate;
select '\'' as c1, '\"' as c2, '\b' as c3, '\n' as c4, '\r' as c5, '\t' as c6, '\Z' as c7, '\\' as c8, '\%' as c9, '\_' as c10;
select * from t1 for update skip locked;
select * from t1 lock in share mode nowait;
#end
#begin
-- -- -- String literal spec symbols
-- bug: two symbols ' afer each other: ''
select '\'Quoted string\'' col1, 'backslash \\ ' ', two double quote "" ' ', two single quote ''' as col2;
select '\'Quoted string\' ' col1, 'backslash \\ ' ', two double quote "" ' ', two single quote ''' as col2;
select * from `select` where `varchar` = 'abc \' ' and `varchar2` = '\'bca';
#end
#begin
-- -- -- Number literal
SELECT 1;
select 1.e-3 as 123e;
select del1.e123 as c from del1;
select -1, 3e-2, 2.34E0;
SELECT -4.1234e-2, 0.2e-3 as c;
SELECT .1e10;
SELECT -.1e10;
select 15e3, .2e5 as col1;
select .2e3 c1, .2e-4 as c5;
#end
#begin
-- -- -- Number float collision test
select t1e2 as e1 from t;
select 1e2t as col from t;
#end
#begin
-- -- -- Hexadecimal literal
select X'4D7953514C';
select x'4D7953514C';
select 0x636174;
select 0x636174 c1;
select x'4D7953514C' c1, 0x636174 c2;
select x'79' as `select`, 0x2930 cc, 0x313233 as c2;

#end
#begin
-- -- -- Null literal
SELECT null;
SELECT not null;
select \N;
select ((\N));
select not ((\N));
#end
#begin
-- -- -- mixed literals
select \N as c1, null as c2, N'string';
select 4e15 colum, 'hello, ' 'world', X'53514C';
select 'abc' ' bcd' ' \' \' ' as col, \N c2, -.1e-3;
#end

#begin
-- -- Variables
SELECT @myvar;
select * from t1 limit @varcount;
select * from t1 limit @varoffset, @varcount;
select * from t1 limit @varcount offset @varoffset;
#end

#begin
-- select_column tests
select * from `select`;
select *, `select`.*, `select`.* from `select`;
select *, 'abc' from `select`;
select *, 1, \N, N'string' 'string2' from `select`;
#end

#begin
-- UNION tests
select 1 union select 2 limit 0,5;
select * from (select 1 union select 2 union select 0) as t order by 1 limit 0,10;
select col1 from t1 union select * from (select 1 as col2) as newt;
select col1 from t1 union (select * from (select 1 as col2) as newt);
select 1 as c1 union (((select 2)));
#end
#begin
-- -- -- subquery in UNION
select 1 union select * from (select 2 union select 3) as table1;
select 1 union (select * from (select 2 union select 3) as table1);
#end
#begin
-- subquery FROM
select * from (((((((select col1 from t1) as ttt))))));
select ship_power.gun_power, ship_info.*
FROM
	(
		select s.name as ship_name, sum(g.power) as gun_power, max(callibr) as max_callibr
		from
			ships s inner join ships_guns sg on s.id = sg.ship_id inner join guns g on g.id = sg.guns_id
		group by s.name
	) ship_power
	inner join
	(
		select s.name as ship_name, sc.class_name, sc.tonange, sc.max_length, sc.start_build, sc.max_guns_size
		from
			ships s inner join ship_class sc on s.class_id = sc.id
	) ship_info using (ship_name)
order by ship_power.ship_name;
#end
#begin
-- JOIN
-- -- -- join condition
select * from t1 inner join (t1 as tt1, t2 as tt2) on t1.col1 = tt1.col1;
select * from  (t1 as tt1, t2 as tt2) inner join t1 on t1.col1 = tt1.col1;
select * from  t1 as tt1, t2 as tt2 inner join t1 on true;
#end
#begin
-- where_condition test
select col1 from t1 inner join t2 on (t1.col1 = t2.col2);
select table_name from information_schema.TABLES where table_schema = DATABASE();
#end
#begin
-- identifiers tests
select 1 as 123e;
#end
#begin
-- not latin1 literals
select CONVERT( LEFT( CONVERT( '自動下書き' USING binary ), 100 ) USING utf8 ) AS x_0;
select CONVERT( LEFT( CONVERT( '自動' USING binary ), 6 ) USING utf8 ) AS x_0;
select  t.*, tt.* FROM wptests_terms AS t  INNER JOIN wptests_term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy IN ('category') AND t.name IN ('远征手记') ORDER BY t.name ASC;
#end
#begin
-- JSON functions
SELECT JSON_ARRAY(1, "abc", NULL, TRUE, CURTIME());
SELECT JSON_OBJECT('id', 87, 'name', 'carrot');
SELECT JSON_QUOTE('null'), JSON_QUOTE('"null"');
SELECT JSON_CONTAINS(@j, @j2, '$.a');
SELECT JSON_CONTAINS_PATH(@j, 'one', '$.a', '$.e');
SELECT JSON_EXTRACT('[10, 20, [30, 40]]', '$[1]');
SELECT JSON_KEYS('{"a": 1, "b": {"c": 30}}');
SELECT JSON_OVERLAPS("[1,3,5,7]", "[2,5,7]");
SELECT JSON_SEARCH(@j, 'one', 'abc');
SELECT JSON_ARRAY_APPEND(@j, '$[1]', 1);
SELECT JSON_ARRAY_INSERT(@j, '$[1]', 'x');
SELECT JSON_INSERT(@j, '$.a', 10, '$.c', '[true, false]');
SELECT JSON_MERGE('[1, 2]', '[true, false]');
SELECT JSON_MERGE_PATCH('[1, 2]', '[true, false]');
SELECT JSON_MERGE_PRESERVE('[1, 2]', '[true, false]');
SELECT JSON_REMOVE(@j, '$[1]');
SELECT JSON_REPLACE(@j, '$.a', 10, '$.c', '[true, false]');
SELECT JSON_SET(@j, '$.a', 10, '$.c', '[true, false]');
SELECT @j, JSON_UNQUOTE(@j);
SELECT JSON_DEPTH('{}'), JSON_DEPTH('[]'), JSON_DEPTH('true');
SELECT JSON_LENGTH('[1, 2, {"a": 3}]');
SELECT JSON_TYPE(@j);
SELECT JSON_VALID('{"a": 1}');
SELECT JSON_SCHEMA_VALID(@schema, @document);
SELECT JSON_SCHEMA_VALIDATION_REPORT(@schema, @document);
SELECT JSON_PRETTY('123');
SELECT JSON_STORAGE_FREE(jcol), JSON_STORAGE_FREE(jcol) FROM jtable;
SELECT o_id, JSON_ARRAYAGG(attribute) AS attributes FROM t3 GROUP BY o_id;
SELECT o_id, JSON_OBJECTAGG(attribute, value) FROM t3 GROUP BY o_id;
#end
SELECT trigger.num FROM test `trigger`;
-- Valid when SELECT is in stored procedure
SELECT * FROM test LIMIT LIMIT1,LIMIT2;
-- SCHEMA as a function name
SELECT SCHEMA();
-- Functions
SELECT mod(3,2);SELECT * FROM TEST WHERE TB_SCHEMA = SCHEMA();
-- Group By with computed column
SELECT 1 AS col1, t1.Id FROM t1 GROUP BY col1;
-- Non Aggregate Functions
SELECT pk, LEAD(pk) OVER (ORDER BY pk) AS l;
SELECT COALESCE(LAG(last_eq.end_variation) OVER (PARTITION BY eq.account_id, eq.execution_name_id, eq.currency ORDER BY eq.start_date), 0) AS start_variation FROM t1;
-- Window Functions
SELECT
    e.id,
    SUM(e.bin_volume) AS bin_volume,
    SUM(e.bin_volume) OVER(PARTITION BY id, e.bin_volume ORDER BY id) AS bin_volume_o,
    COALESCE(bin_volume, 0) AS bin_volume2,
    COALESCE(LAG(e.bin_volume) OVER(PARTITION BY id ORDER BY e.id), 0) AS bin_volume3,
    FIRST_VALUE(id) OVER() AS fv,
    DENSE_RANK() OVER(PARTITION BY bin_name ORDER BY id) AS drk,
    RANK() OVER(PARTITION BY bin_name) AS rk,
    ROW_NUMBER ( ) OVER(PARTITION BY bin_name) AS rn,
    NTILE(2) OVER() AS nt
FROM table1 e;
SELECT
    id,
    SUM(bin_volume) OVER w AS bin_volume_o,
    LAG(bin_volume) OVER w AS bin_volume_l,
    LAG(bin_volume, 2) OVER w AS bin_volume_l2,
    FIRST_VALUE(id) OVER w2 AS fv,
    GROUP_CONCAT(bin_volume order by id) AS `rank`
FROM table2
    WINDOW w AS (PARTITION BY id, bin_volume ORDER BY id ROWS UNBOUNDED PRECEDING),
           w2 AS (PARTITION BY id, bin_volume ORDER BY id DESC ROWS 10 PRECEDING);
-- Index hints: https://dev.mysql.com/doc/refman/5.7/en/index-hints.html
SELECT * FROM table1 USE INDEX (col1_index,col2_index) WHERE col1=1 AND col2=2 AND col3=3;
SELECT * FROM table1 FORCE INDEX (col1_index,col2_index) WHERE col1=1 AND col2=2 AND col3=3;
SELECT * FROM t1 USE INDEX (PRIMARY) ORDER BY a;
SELECT * FROM t1 FORCE INDEX (PRIMARY) ORDER BY a;


text:
const providers = {
  env: require('./provider/env'),
  file: require('./provider/file'),
  provided: require('./provider/provided'),
  http: require('./provider/http')
}

function getProvider(type, providers, extensions) {
  const extension = extensions[type]
  if (extension === undefined) {
    return providers[type]
  }

  return extensions[type]
}

module.exports.resolve = (config, extensions, cb) => {
  const providerType = config.type
  const provider = getProvider(providerType, providers, extensions)

  if (provider === undefined) {
    cb(new Error(`Provider ${providerType} not found.`))
  } else {
    provider.init(config, cb)
  }
}


text:
module.exports['assert_options'] = require('./assert_options')
module.exports['getenv'] = require('./getenv')
module.exports['ini_get'] = require('./ini_get')
module.exports['ini_set'] = require('./ini_set')
module.exports['set_time_limit'] = require('./set_time_limit')
module.exports['version_compare'] = require('./version_compare')


text:
/* $NoKeywords: $ */
/*
//
// Copyright (c) 1993-2012 Robert McNeel & Associates. All rights reserved.
// OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert
// McNeel & Associates.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY.
// ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF
// MERCHANTABILITY ARE HEREBY DISCLAIMED.
//
// For complete openNURBS copyright information see <http://www.opennurbs.org>.
//
////////////////////////////////////////////////////////////////
*/

#include "opennurbs.h"

#if defined(ON_DLL_EXPORTS)
// When compiling a Windows DLL opennurbs, we
// statically link ./zlib/.../zlib....lib into
// the opennurbs DLL.

#define OPENNURBS_ZLIB_FILE_NAME "zlib.lib"

//////////////////////////////////////////////////////////////
//
// OPENNURBS_ZLIB_OUTPUT_DIR is the directory containing zlib
// relative to the "opennurbs" directory.
//
// OPENNURBS_ZLIB_OUTPUT_DIR must not have a trailing slash
//
#define OPENNURBS_ZLIB_OUTPUT_ROOT_DIR "."

#if defined(WIN64) && defined(_M_X64)

// 64 bit Windows zlib linking instructions

#if defined(NDEBUG)

// release x64 libs
#define OPENNURBS_CONFIGURATION_DIR "x64/Release"

#else // _DEBUG

// debug  x64 libs
#define OPENNURBS_CONFIGURATION_DIR "x64/Debug"

#endif // if NDEBUG else _DEBUG

#elif defined(WIN32) && defined(_M_IX86)

// 32 bit Windows zlib linking instructions

#if defined(NDEBUG)

// release 32 bit WIndows libs
#define OPENNURBS_CONFIGURATION_DIR "Release"

#else // _DEBUG

// debug 32 bit WIndows libs
#define OPENNURBS_CONFIGURATION_DIR "Debug"

#endif // if NDEBUG else _DEBUG

#endif // if WIN64 else WIN32

#pragma comment(lib, "\"" OPENNURBS_ZLIB_OUTPUT_ROOT_DIR "/" OPENNURBS_CONFIGURATION_DIR "/" OPENNURBS_ZLIB_FILE_NAME "\"")

#endif // ON_DLL_EXPORTS

bool ON_BinaryArchive::WriteCompressedBuffer(
        size_t sizeof__inbuffer,  // sizeof uncompressed input data
        const void* inbuffer  // uncompressed input data
        )
{
  size_t compressed_size = 0;
  bool rc = false;

  if ( !WriteMode() )
    return false;
  if ( sizeof__inbuffer > 0 && 0 == inbuffer )
    return false;

  // number of bytes of uncompressed data

  if (!WriteSize(sizeof__inbuffer))
    return false;
  if ( 0 == sizeof__inbuffer )
    return true;

  // 32 bit crc of uncompressed data
  const unsigned int buffer_crc = ON_CRC32( 0, sizeof__inbuffer, inbuffer );
  if (!WriteInt(buffer_crc))
    return false;

  unsigned char method = (sizeof__inbuffer > 128) ? 1 : 0;
  if ( method ) {
    if ( !CompressionInit() ) {
      CompressionEnd();
      method = 0;
    }
  }
  if ( !WriteChar(method) )
    return false;

  switch ( method )
  {
  case 0: // uncompressed
    rc = WriteByte(sizeof__inbuffer, inbuffer);
    if ( rc )
    {
      compressed_size = sizeof__inbuffer;
    }
    break;

  case 1: // compressed
    compressed_size = WriteDeflate( sizeof__inbuffer, inbuffer );
    rc = ( compressed_size > 0 ) ? true : false;
    CompressionEnd();
    break;
  }

  return rc;
}

bool ON_BinaryArchive::ReadCompressedBufferSize( size_t* sizeof__outbuffer )
{
  return ReadSize(sizeof__outbuffer);
}

bool ON_BinaryArchive::ReadCompressedBuffer( // read and uncompress
  size_t sizeof__outbuffer,  // sizeof of uncompressed buffer to read
  void* outbuffer,           // uncompressed output data returned here
  int* bFailedCRC
  )
{
  bool rc = false;
  unsigned int buffer_crc0 = 0;
  unsigned int buffer_crc1 = 0;
  char method = 0;

  if ( bFailedCRC)
    *bFailedCRC = false;
  if ( !ReadMode() )
    return false;
  if ( 0 == sizeof__outbuffer )
    return true;
  if ( 0 == outbuffer )
    return false;

  if ( !ReadInt(&buffer_crc0) ) // 32 bit crc of uncompressed buffer
    return false;

  if ( !ReadChar(&method) )
    return false;

  if ( method != 0 && method != 1 )
    return false;

  switch(method)
  {
  case 0: // uncompressed
    rc = ReadByte(sizeof__outbuffer, outbuffer);
    break;
  case 1: // compressed
    rc = CompressionInit();
    if (rc)
      rc = ReadInflate( sizeof__outbuffer, outbuffer );
    CompressionEnd();
    break;
  }

  if (rc )
  {
    buffer_crc1 = ON_CRC32( 0, sizeof__outbuffer, outbuffer );
    if ( buffer_crc1 != buffer_crc0 )
    {
      ON_ERROR("ON_BinaryArchive::ReadCompressedBuffer() crc error");
      if ( bFailedCRC )
        *bFailedCRC = true;
    }
  }

  return rc;
}

size_t ON_BinaryArchive::WriteDeflate( // returns number of bytes written
        size_t sizeof___inbuffer,  // sizeof uncompressed input data ( > 0 )
        const void* in___buffer     // uncompressed input data ( != NULL )
        )
{
  /*
    In "standard" (in 2005) 32 bit code

      sizeof(int)     = 4 bytes,
      sizeof(long)    = 4 bytes,
      sizeof(pointer) = 4 bytes, and
      sizeof(size_t)  = 4 bytes.

    Theoretically I don't need to use multiple input buffer
    chunks in case.  But I'm paranoid and I will use multiple
    input chunks when sizeof_inbuffer > 2GB in order to dodge
    any potential zlib signed verses unsigned compare bugs or
    having a signed int i++ roll over to a negative number.

    In "standard" code that has 64 bit pointers

      sizeof(int)     >= 4 bytes, (it's 4 on MS VS2005)
      sizeof(long)    >= 4 bytes, (it's 4 on MS VS2005)
      sizeof(pointer)  = 8 bytes, and
      sizeof(size_t)   = 8 bytes.

    So, I'm going to assume the ints and longs in the zlib code
    are 4 bytes, but I could have sizeof_inbuffer > 4GB.
    This means I have to use multiple input buffer chunks.
    In this case I still use multiple input chunks when
    sizeof_inbuffer > 2GB in order to dodge any potential zlib
    signed verses unsigned compare bugs or having a signed
    int i++ roll over to a negative number.

    So, I set

       const size_t max_avail = (largest signed 4 byte integer - 15)

    and feed inflate and deflate buffers with size <= max_avail.

    This information below is from the zlib 1.2.3 FAQ.

    32. Can zlib work with greater than 4 GB of data?

        Yes. inflate() and deflate() will process any amount of data correctly.
        Each call of inflate() or deflate() is limited to input and output chunks
        of the maximum value that can be stored in the compiler's "unsigned int"
        type, but there is no limit to the number of chunks. Note however that the
        strm.total_in and strm_total_out counters may be limited to 4 GB. These
        counters are provided as a convenience and are not used internally by
        inflate() or deflate(). The application can easily set up its own counters
        updated after each call of inflate() or deflate() to count beyond 4 GB.
        compress() and uncompress() may be limited to 4 GB, since they operate in a
        single call. gzseek() and gztell() may be limited to 4 GB depending on how
        zlib is compiled. See the zlibCompileFlags() function in zlib.h.

        The word "may" appears several times above since there is a 4 GB limit
        only if the compiler's "long" type is 32 bits. If the compiler's "long"
        type is 64 bits, then the limit is 16 exabytes.
  */

  const size_t max_avail = 0x7FFFFFF0;

  //  Compressed information is saved in a chunk.
  bool rc = BeginWrite3dmChunk(TCODE_ANONYMOUS_CHUNK,0);
  if ( !rc )
    return false;

  size_t out__count = 0;
  int zrc = Z_OK;

  size_t my_avail_in = sizeof___inbuffer;
  unsigned char* my_next_in = (unsigned char*)in___buffer;

  size_t d = my_avail_in;
  if ( d > max_avail )
    d = max_avail;
  m_zlib.strm.next_in = my_next_in;
  m_zlib.strm.avail_in = (unsigned int)d;
  my_avail_in -= d;
  my_next_in  += d;

  m_zlib.strm.next_out = m_zlib.buffer;
  m_zlib.strm.avail_out = m_zlib.sizeof_x_buffer;

  // counter guards prevents infinte loops if there is a bug in zlib return codes.
  int counter = 512;
  int flush = Z_NO_FLUSH;

  size_t deflate_output_count = 0;

  while( rc && counter > 0 )
  {
    // Call zlib's deflate function.  It can either process
    // more input from m_zlib.strm.next_in[], create more
    // compressed output in m_zlib.strm.next_out[], or do both.
    if ( 0 == my_avail_in && 0 == m_zlib.strm.avail_in )
    {
      // no uncompressed input is left - switch to finish mode
      flush = Z_FINISH;
    }
    zrc = z_deflate( &m_zlib.strm, flush );
    if ( zrc < 0 )
    {
      // Something went haywire - bail out.
      ON_ERROR("ON_BinaryArchive::WriteDeflate - z_deflate failure");
      rc = false;
      break;
    }

    deflate_output_count = m_zlib.sizeof_x_buffer - m_zlib.strm.avail_out;
    if ( deflate_output_count > 0 )
    {
      // The last call to deflate created output.  Send
      // this output to the archive.
      rc = WriteChar( deflate_output_count, m_zlib.buffer );
      if ( !rc )
        break;
      out__count += deflate_output_count;
      m_zlib.strm.next_out  = m_zlib.buffer;
      m_zlib.strm.avail_out = m_zlib.sizeof_x_buffer;
    }

    if ( Z_FINISH == flush && Z_STREAM_END == zrc )
    {
      // no input left, all pending compressing is finished,
      // and all compressed output has been returned.
      break;
    }

    if ( my_avail_in > 0 && m_zlib.strm.avail_in < max_avail )
    {
      // inbuffer[] had more than max_zlib_avail_in bytes in it
      // and I am feeding inbuffer[] to deflate in smaller chunks
      // that the 32 bit integers in the zlib code can handle.
      if ( 0 == m_zlib.strm.avail_in || 0 == m_zlib.strm.next_in )
      {
        // The call to deflate() used up all the input
        // in m_zlib.strm.next_in[].  I can feed it another chunk
        // from inbuffer[]
        d = my_avail_in;
        if ( d > max_avail )
          d = max_avail;
        m_zlib.strm.next_in = my_next_in;
        m_zlib.strm.avail_in = (unsigned int)d;
      }
      else
      {
        // The call to deflate left some input in m_zlib.strm.next_in[],
        // but I can increase m_zlib.strm.avail_in.
        d =  max_avail - m_zlib.strm.avail_in;
        if ( d > my_avail_in )
          d = my_avail_in;
        m_zlib.strm.avail_in += (unsigned int)d;
      }

      my_avail_in -= d;
      my_next_in  += d;
    }
    else if ( 0 == deflate_output_count )
    {
      // no buffer changes this time
      counter--;
    }

    if ( zrc != Z_OK )
    {
      break;
    }
  }

  if ( !EndWrite3dmChunk() )
  {
    rc = false;
  }

  if ( 0 == counter )
  {
    rc = false;
  }

  return (rc ? out__count : 0);
}

bool ON_BinaryArchive::ReadInflate(
        size_t sizeof___outbuffer,  // sizeof uncompressed data
        void* out___buffer          // buffer for uncompressed data
        )
{
  const size_t max_avail = 0x7FFFFFF0; // See max_avail comment in ON_BinaryArchive::WriteInflate

  size_t sizeof__inbuffer = 0;
  void* in___buffer = 0;
  bool rc = false;

  // read compressed buffer from 3dm archive
  bool bValidCompressedBuffer = false;
  {
    ON__UINT32 tcode = 0;
    ON__INT64  big_value = 0;
    rc = BeginRead3dmBigChunk(&tcode,&big_value );
    if (!rc)
    {
      if ( 0 != out___buffer && sizeof___outbuffer > 0 )
        memset(out___buffer,0,sizeof___outbuffer);
      return false;
    }
    if (   tcode == TCODE_ANONYMOUS_CHUNK
        && big_value > 4
        && sizeof___outbuffer > 0
        && 0 != out___buffer )
    {
      // read compressed buffer from the archive
      sizeof__inbuffer = (size_t)(big_value-4); // the last 4 bytes in this chunk are a 32 bit crc
      in___buffer = onmalloc(sizeof__inbuffer);
      if ( !in___buffer )
      {
        rc = false;
      }
      else
      {
        rc = ReadByte( sizeof__inbuffer, in___buffer );
      }
    }
    else
    {
      // Either I have the wrong chunk, or the input
      // parameters are bogus.
      rc = false;
    }
    int c0 = m_bad_CRC_count;
    if ( !EndRead3dmChunk() )
    {
      rc = false;
    }
    bValidCompressedBuffer = ( m_bad_CRC_count > c0 )
                           ? false
                           : rc;
  }

  if ( !bValidCompressedBuffer && 0 != out___buffer && sizeof___outbuffer > 0 )
  {
    // Decompression will fail, but we might get something valid
    // at the start if the data flaw was near the end of the buffer.
    memset(out___buffer,0,sizeof___outbuffer);
  }

  if ( !rc )
  {
    if ( in___buffer )
    {
      onfree(in___buffer);
      in___buffer = 0;
    }
    return false;
  }

  int zrc = -1;

  // set up zlib in buffer
  unsigned char* my_next_in = (unsigned char*)in___buffer;
  size_t my_avail_in = sizeof__inbuffer;

  size_t d = my_avail_in;
  if ( d > max_avail )
    d = max_avail;
  m_zlib.strm.next_in  = my_next_in;
  m_zlib.strm.avail_in = (unsigned int)d;
  my_next_in  += d;
  my_avail_in -= d;

  // set up zlib out buffer
  unsigned char* my_next_out = (unsigned char*)out___buffer;
  size_t my_avail_out = sizeof___outbuffer;

  d = my_avail_out;
  if ( d > max_avail )
    d = max_avail;
  m_zlib.strm.next_out  = my_next_out;
  m_zlib.strm.avail_out = (unsigned int)d;
  my_next_out  += d;
  my_avail_out -= d;

  // counter guards against infinte loop if there are
  // bugs in zlib return codes
  int counter = 512;
  int flush = Z_NO_FLUSH;

  while ( rc && counter > 0 )
  {
    // Call zlib's inflate function.  It can either process
    // more input from m_zlib.strm.next_in[], create more
    // uncompressed output in m_zlib.strm.next_out[], or do both.
    if ( 0 == my_avail_in && 0 == m_zlib.strm.avail_in )
    {
      // no compressed input is left - switch to finish mode
      flush = Z_FINISH;
    }
    zrc = z_inflate( &m_zlib.strm, flush );
    if ( zrc < 0 )
    {
      // Something went haywire - bail out.
      ON_ERROR("ON_BinaryArchive::ReadInflate - z_inflate failure");
      rc = false;
      break;
    }

    if ( Z_FINISH == flush && Z_STREAM_END == zrc )
    {
      // no input left, all pending decompression is finished,
      // and all decompressed output has been returned.
      break;
    }

    d = 0;
    if ( my_avail_in > 0 && m_zlib.strm.avail_in < max_avail )
    {
      if ( 0 == m_zlib.strm.avail_in || 0 == m_zlib.strm.next_in )
      {
        // The call to inflate() used up all the input
        // in m_zlib.strm.next_in[].  I can feed it another chunk
        // from inbuffer[]
        d = my_avail_in;
        if ( d > max_avail )
          d = max_avail;
        m_zlib.strm.next_in  = my_next_in;
        m_zlib.strm.avail_in = (unsigned int)d;
      }
      else
      {
        // The call to inflate() left some input in m_zlib.strm.next_in[],
        // but I can increase m_zlib.strm.avail_in.
        d =  max_avail - m_zlib.strm.avail_in;
        if ( d > my_avail_in )
          d = my_avail_in;
        m_zlib.strm.avail_in += (unsigned int)d;
      }
      my_next_in  += d;
      my_avail_in -= d;
    }

    if ( my_avail_out > 0 && m_zlib.strm.avail_out < max_avail )
    {
      // increase m_zlib.strm.next_out[] buffer
      if ( 0 == m_zlib.strm.avail_out || 0 == m_zlib.strm.next_out )
      {
        d = my_avail_out;
        if ( d > max_avail )
          d = max_avail;
        m_zlib.strm.next_out  = my_next_out;
        m_zlib.strm.avail_out = (unsigned int)d;
      }
      else
      {
        d = max_avail - m_zlib.strm.avail_out;
        if ( d > my_avail_out )
          d = my_avail_out;
        m_zlib.strm.avail_out += ((unsigned int)d);
      }
      my_next_out  += d;
      my_avail_out -= d;
    }
    else if ( 0 == d )
    {
      // no buffer changes
      counter--;
    }
  }

  if (in___buffer )
  {
    onfree(in___buffer);
    in___buffer = 0;
  }

  if ( 0 == counter )
  {
    rc = false;
  }

  return rc;
}

bool ON_BinaryArchive::CompressionInit()
{
  // inflateInit() and deflateInit() are in zlib 1.3.3
  bool rc = false;
  if ( WriteMode() ) {
    rc = ( m_zlib.mode == ON::write ) ? true : false;
    if ( !rc ) {
      CompressionEnd();
      if ( Z_OK == deflateInit( &m_zlib.strm, Z_BEST_COMPRESSION ) ) {
        m_zlib.mode = ON::write;
        rc = true;
      }
      else {
        memset(&m_zlib.strm,0,sizeof(m_zlib.strm));
      }
    }
  }
  else if ( ReadMode() ) {
    rc = ( m_zlib.mode == ON::read ) ? true : false;
    if ( !rc ) {
      CompressionEnd();
      if ( Z_OK == inflateInit( &m_zlib.strm ) ) {
        m_zlib.mode = ON::read;
        rc = true;
      }
      else {
        memset(&m_zlib.strm,0,sizeof(m_zlib.strm));
      }
    }
  }
  else {
    CompressionEnd();
  }
  return rc;
}

void ON_BinaryArchive::CompressionEnd()
{
  // inflateEnd() and deflateEnd() are in zlib 1.3.3
  switch ( m_zlib.mode ) {
  case ON::read:
  case ON::read3dm:
    inflateEnd(&m_zlib.strm);
    break;
  case ON::write:
  case ON::write3dm:
    deflateEnd(&m_zlib.strm);
    break;
  default: // to quiet lint
    break;
  }
  memset(&m_zlib.strm,0,sizeof(m_zlib.strm));
  m_zlib.mode = ON::unknown_archive_mode;
}

struct ON_CompressedBufferHelper
{
  int action; // 1 = compress, 2 = uncompress
  enum
  {
    sizeof_x_buffer = 16384
  };
  unsigned char    buffer[sizeof_x_buffer];
  z_stream         strm;
  size_t           m_buffer_compressed_capacity;
};

ON_CompressedBuffer::ON_CompressedBuffer()
                    : m_sizeof_uncompressed(0),
                      m_sizeof_compressed(0),
                      m_crc_uncompressed(0),
                      m_crc_compressed(0),
                      m_method(0),
                      m_sizeof_element(0),
                      m_buffer_compressed_capacity(0),
                      m_buffer_compressed(0)
{
}

ON_CompressedBuffer::~ON_CompressedBuffer()
{
  Destroy();
}

ON_CompressedBuffer::ON_CompressedBuffer(const ON_CompressedBuffer& src)
                    : m_sizeof_uncompressed(0),
                      m_sizeof_compressed(0),
                      m_crc_uncompressed(0),
                      m_crc_compressed(0),
                      m_method(0),
                      m_sizeof_element(0),
                      m_buffer_compressed_capacity(0),
                      m_buffer_compressed(0)
{
  *this = src;
}

ON_CompressedBuffer& ON_CompressedBuffer::operator=(const ON_CompressedBuffer& src)
{
  if ( this != &src )
  {
    Destroy();
    if( src.m_buffer_compressed && src.m_sizeof_compressed > 0 )
    {
      m_sizeof_uncompressed = src.m_sizeof_uncompressed;
      m_sizeof_compressed   = src.m_sizeof_compressed;
      m_crc_uncompressed    = src.m_crc_uncompressed;
      m_crc_compressed      = src.m_crc_compressed;
      m_method              = src.m_method;
      m_sizeof_element      = src.m_sizeof_element;

      m_buffer_compressed = onmalloc(m_sizeof_compressed);
      if( m_buffer_compressed )
      {
        m_buffer_compressed_capacity = m_sizeof_compressed;
        memcpy(m_buffer_compressed,src.m_buffer_compressed,m_sizeof_compressed);
      }
    }
  }
  return *this;
}

bool ON_CompressedBuffer::Write( ON_BinaryArchive& binary_archive ) const
{
  bool rc = binary_archive.BeginWrite3dmChunk(TCODE_ANONYMOUS_CHUNK,1,0);
  if ( !rc )
    return false;

  for(;;)
  {
    rc = binary_archive.WriteSize(m_sizeof_uncompressed);
    if (!rc)
      break;
    rc = binary_archive.WriteSize((m_buffer_compressed && m_sizeof_compressed>0) ? m_sizeof_compressed : 0);
    if (!rc)
      break;
    rc = binary_archive.WriteInt(m_crc_uncompressed);
    if (!rc)
      break;
    rc = binary_archive.WriteInt(m_crc_compressed);
    if (!rc)
      break;
    rc = binary_archive.WriteInt(m_method);
    if (!rc)
      break;
    rc = binary_archive.WriteInt(m_sizeof_element);
    if (!rc)
      break;
    if ( m_buffer_compressed && m_sizeof_compressed > 0 )
    {
      rc = binary_archive.WriteByte(m_sizeof_compressed,m_buffer_compressed);
      if (!rc)
        break;
    }
    break;
  }

  if ( !binary_archive.EndWrite3dmChunk() )
    rc = false;

  return rc;
}

bool ON_CompressedBuffer::Read( ON_BinaryArchive& binary_archive )
{
  int major_version = 0;
  int minor_version = 0;
  bool rc = binary_archive.BeginRead3dmChunk(TCODE_ANONYMOUS_CHUNK,&major_version,&minor_version);
  if ( !rc )
    return false;

  for(;;)
  {
    rc = ( 1 == major_version );
    if ( !rc )
      break;
    rc = binary_archive.ReadSize(&m_sizeof_uncompressed);
    if (!rc)
      break;
    rc = binary_archive.ReadSize(&m_sizeof_compressed);
    if (!rc)
      break;
    rc = binary_archive.ReadInt(&m_crc_uncompressed);
    if (!rc)
      break;
    rc = binary_archive.ReadInt(&m_crc_compressed);
    if (!rc)
      break;
    rc = binary_archive.ReadInt(&m_method);
    if (!rc)
      break;
    rc = binary_archive.ReadInt(&m_sizeof_element);
    if (!rc)
      break;
    if ( m_sizeof_compressed > 0 )
    {
      m_buffer_compressed = onmalloc(m_sizeof_compressed);
      if ( m_buffer_compressed )
      {
        m_buffer_compressed_capacity = m_sizeof_compressed;
        rc = binary_archive.ReadByte(m_sizeof_compressed,m_buffer_compressed);
      }
      else
      {
        m_sizeof_compressed =0;
      }
      if (!rc)
        break;
    }

    break;
  }

  if ( !binary_archive.EndRead3dmChunk() )
    rc = false;

  return rc;
}

void ON_CompressedBuffer::Destroy()
{
  if ( m_buffer_compressed )
    onfree(m_buffer_compressed);

  m_sizeof_uncompressed = 0;
  m_sizeof_compressed   = 0;
  m_crc_uncompressed    = 0;
  m_crc_compressed      = 0;
  m_method              = 0;
  m_sizeof_element      = 0;
  m_buffer_compressed   = 0;
  m_buffer_compressed_capacity = 0;
}

bool ON_CompressedBuffer::Compress(
        size_t sizeof__inbuffer,  // sizeof uncompressed input data
        const void* inbuffer,     // uncompressed input data
        int sizeof_element
        )
{
  Destroy();

  //size_t compressed_size = 0;
  bool rc = false;

  if ( sizeof__inbuffer > 0 && 0 == inbuffer )
    return false;

  if ( 0 == sizeof__inbuffer )
    return true;

  // number of bytes of uncompressed data
  m_sizeof_uncompressed = sizeof__inbuffer;

  ON_CompressedBufferHelper helper;
  memset(&helper,0,sizeof(helper));
  helper.action = 1;

  bool bToggleByteOrder = false;
  switch(sizeof_element)
  {
  case 2:
  case 4:
  case 8:
    if ( 0 == (sizeof__inbuffer%sizeof_element) )
    {
      m_sizeof_element = sizeof_element;
      bToggleByteOrder = (ON::big_endian == ON::Endian());
    }
    break;
  };

  if ( bToggleByteOrder )
  {
    ON_BinaryFile::ToggleByteOrder(
      (int)(sizeof__inbuffer/m_sizeof_element),
      m_sizeof_element,
      inbuffer,
      (void*)inbuffer
      );
  }

  m_method = (sizeof__inbuffer > 128) ? 1 : 0;
  if ( m_method )
  {
    if ( !CompressionInit(&helper) )
    {
      CompressionEnd(&helper);
      m_method = 0;
    }
    else
    {
      m_buffer_compressed = onmalloc(sizeof__inbuffer/4);
      size_t sizeof_compressed = DeflateHelper( &helper, sizeof__inbuffer, inbuffer );
      CompressionEnd(&helper);
      if ( sizeof_compressed > 0 && sizeof_compressed == m_sizeof_compressed )
      {
        rc = true;
        if ( 2*m_buffer_compressed_capacity > 3*m_sizeof_compressed )
        {
          // release memory we don't need
          m_buffer_compressed_capacity = m_sizeof_compressed;
          m_buffer_compressed = onrealloc(m_buffer_compressed,m_buffer_compressed_capacity);
        }
      }
      else
      {
        Destroy();
        m_method = 0;
      }
    }
  }

  if ( 0 ==  m_method )
  {
    // uncompressed
    m_buffer_compressed = onmalloc(sizeof__inbuffer);
    if ( m_buffer_compressed )
    {
      m_sizeof_compressed = sizeof__inbuffer;
      m_buffer_compressed_capacity = sizeof__inbuffer;
      memcpy(m_buffer_compressed,inbuffer,sizeof__inbuffer);
      rc = true;
    }
  }

  if ( bToggleByteOrder )
  {
    ON_BinaryFile::ToggleByteOrder(
      (int)(sizeof__inbuffer/m_sizeof_element),
      m_sizeof_element,
      inbuffer,
      (void*)inbuffer
      );
  }

  if (rc)
  {
    m_crc_uncompressed = ON_CRC32( 0, sizeof__inbuffer, inbuffer );
    m_crc_compressed   = ON_CRC32( 0, m_sizeof_compressed, m_buffer_compressed );
  }

  return rc;
}

bool ON_CompressedBuffer::Uncompress(
          void* outbuffer,
          int* bFailedCRC
          ) const
{
  bool rc = false;

  if ( bFailedCRC)
    *bFailedCRC = false;
  if ( 0 == m_sizeof_uncompressed )
    return true;
  if ( 0 == outbuffer )
    return false;

  if ( m_method != 0 && m_method != 1 )
    return false;

  ON__UINT32 compressed_crc = ON_CRC32( 0, m_sizeof_compressed, m_buffer_compressed );
  if ( compressed_crc != m_crc_compressed )
  {
    // m_buffer_compressed is corrupt - let's hope the corruption
    // is near the end and we ge something useful from the
    // beginning.
    memset(outbuffer,0,m_sizeof_uncompressed);
    if ( bFailedCRC)
      *bFailedCRC = false;
  }

  switch(m_method)
  {
  case 0: // uncompressed
    if (    m_buffer_compressed
         && m_sizeof_uncompressed == m_sizeof_compressed
         )
    {
      memcpy(outbuffer,m_buffer_compressed,m_sizeof_uncompressed);
      rc = true;
    }
    break;

  case 1: // compressed
    {
      ON_CompressedBufferHelper helper;
      memset(&helper,0,sizeof(helper));
      helper.action = 2;
      rc = CompressionInit(&helper);
      if (rc)
      {
        rc = InflateHelper( &helper, m_sizeof_uncompressed, outbuffer );
        CompressionEnd(&helper);
      }
    }
    break;
  }

  switch(m_sizeof_element)
  {
  case 2:
  case 4:
  case 8:
    if ( 0 == (m_sizeof_uncompressed%m_sizeof_element) )
    {
      if ( ON::big_endian == ON::Endian() )
      {
        ON_BinaryFile::ToggleByteOrder(
          (int)(m_sizeof_uncompressed/m_sizeof_element),
          m_sizeof_element,
          outbuffer,
          outbuffer
          );
      }
    }
    break;
  };

  if (rc )
  {
    ON__UINT32 uncompressed_crc = ON_CRC32( 0, m_sizeof_uncompressed, outbuffer );
    if ( uncompressed_crc != m_crc_uncompressed )
    {
      ON_ERROR("ON_CompressedBuffer::Uncompress() crc error");
      if ( bFailedCRC )
        *bFailedCRC = true;
    }
  }

  return rc;
}

bool ON_CompressedBuffer::WriteChar(
        size_t count, const void* buffer
        )
{
  bool rc = true;
  if ( count > 0 && buffer )
  {
    if ( count + m_sizeof_compressed > m_buffer_compressed_capacity )
    {
      size_t delta = count + m_sizeof_compressed - m_buffer_compressed_capacity;
      if ( delta < 2048 )
        delta = 2048;
      if ( delta < m_buffer_compressed_capacity/4 )
        delta = m_buffer_compressed_capacity/4;
      m_buffer_compressed_capacity += delta;
      m_buffer_compressed = onrealloc(m_buffer_compressed,m_buffer_compressed_capacity);
      if ( !m_buffer_compressed )
      {
        m_buffer_compressed_capacity = 0;
        m_sizeof_compressed = 0;
        return false;
      }
    }
    memcpy(((char*)m_buffer_compressed)+m_sizeof_compressed,buffer,count);
    m_sizeof_compressed += count;
  }
  else
  {
    rc = (0 == count);
  }
  return rc;
}

size_t ON_CompressedBuffer::DeflateHelper( // returns number of bytes written
        ON_CompressedBufferHelper* helper,
        size_t sizeof___inbuffer,  // sizeof uncompressed input data ( > 0 )
        const void* in___buffer     // uncompressed input data ( != NULL )
        )
{
  /*
    In "standard" (in 2005) 32 bit code

      sizeof(int)     = 4 bytes,
      sizeof(long)    = 4 bytes,
      sizeof(pointer) = 4 bytes, and
      sizeof(size_t)  = 4 bytes.

    Theoretically I don't need to use multiple input buffer
    chunks in case.  But I'm paranoid and I will use multiple
    input chunks when sizeof_inbuffer > 2GB in order to dodge
    any potential zlib signed verses unsigned compare bugs or
    having a signed int i++ roll over to a negative number.

    In "standard" code that has 64 bit pointers

      sizeof(int)     >= 4 bytes, (it's 4 on MS VS2005)
      sizeof(long)    >= 4 bytes, (it's 4 on MS VS2005)
      sizeof(pointer)  = 8 bytes, and
      sizeof(size_t)   = 8 bytes.

    So, I'm going to assume the ints and longs in the zlib code
    are 4 bytes, but I could have sizeof_inbuffer > 4GB.
    This means I have to use multiple input buffer chunks.
    In this case I still use multiple input chunks when
    sizeof_inbuffer > 2GB in order to dodge any potential zlib
    signed verses unsigned compare bugs or having a signed
    int i++ roll over to a negative number.

    So, I set

       const size_t max_avail = (largest signed 4 byte integer - 15)

    and feed inflate and deflate buffers with size <= max_avail.

    This information below is from the zlib 1.2.3 FAQ.

    32. Can zlib work with greater than 4 GB of data?

        Yes. inflate() and deflate() will process any amount of data correctly.
        Each call of inflate() or deflate() is limited to input and output chunks
        of the maximum value that can be stored in the compiler's "unsigned int"
        type, but there is no limit to the number of chunks. Note however that the
        strm.total_in and strm_total_out counters may be limited to 4 GB. These
        counters are provided as a convenience and are not used internally by
        inflate() or deflate(). The application can easily set up its own counters
        updated after each call of inflate() or deflate() to count beyond 4 GB.
        compress() and uncompress() may be limited to 4 GB, since they operate in a
        single call. gzseek() and gztell() may be limited to 4 GB depending on how
        zlib is compiled. See the zlibCompileFlags() function in zlib.h.

        The word "may" appears several times above since there is a 4 GB limit
        only if the compiler's "long" type is 32 bits. If the compiler's "long"
        type is 64 bits, then the limit is 16 exabytes.
  */

  const size_t max_avail = 0x7FFFFFF0;

  //  Compressed information is saved in a chunk.
  bool rc = true;

  size_t out__count = 0;
  int zrc = Z_OK;

  size_t my_avail_in = sizeof___inbuffer;
  unsigned char* my_next_in = (unsigned char*)in___buffer;

  size_t d = my_avail_in;
  if ( d > max_avail )
    d = max_avail;

  ON_CompressedBufferHelper& m_zlib = *helper;

  m_zlib.strm.next_in = my_next_in;
  m_zlib.strm.avail_in = (unsigned int)d;
  my_avail_in -= d;
  my_next_in  += d;

  m_zlib.strm.next_out = m_zlib.buffer;
  m_zlib.strm.avail_out = m_zlib.sizeof_x_buffer;

  // counter guards prevents infinte loops if there is a bug in zlib return codes.
  int counter = 512;
  int flush = Z_NO_FLUSH;

  size_t deflate_output_count = 0;

  while( rc && counter > 0 )
  {
    // Call zlib's deflate function.  It can either process
    // more input from m_zlib.strm.next_in[], create more
    // compressed output in m_zlib.strm.next_out[], or do both.
    if ( 0 == my_avail_in && 0 == m_zlib.strm.avail_in )
    {
      // no uncompressed input is left - switch to finish mode
      flush = Z_FINISH;
    }
    zrc = z_deflate( &m_zlib.strm, flush );
    if ( zrc < 0 )
    {
      // Something went haywire - bail out.
      ON_ERROR("ON_CompressedBuffer::DeflateHelper - z_deflate failure");
      rc = false;
      break;
    }

    deflate_output_count = m_zlib.sizeof_x_buffer - m_zlib.strm.avail_out;
    if ( deflate_output_count > 0 )
    {
      // The last call to deflate created output.  Send
      // this output to the archive.
      rc = WriteChar( deflate_output_count, m_zlib.buffer );
      if ( !rc )
        break;
      out__count += deflate_output_count;
      m_zlib.strm.next_out  = m_zlib.buffer;
      m_zlib.strm.avail_out = m_zlib.sizeof_x_buffer;
    }

    if ( Z_FINISH == flush && Z_STREAM_END == zrc )
    {
      // no input left, all pending compressing is finished,
      // and all compressed output has been returned.
      break;
    }

    if ( my_avail_in > 0 && m_zlib.strm.avail_in < max_avail )
    {
      // inbuffer[] had more than max_zlib_avail_in bytes in it
      // and I am feeding inbuffer[] to deflate in smaller chunks
      // that the 32 bit integers in the zlib code can handle.
      if ( 0 == m_zlib.strm.avail_in || 0 == m_zlib.strm.next_in )
      {
        // The call to deflate() used up all the input
        // in m_zlib.strm.next_in[].  I can feed it another chunk
        // from inbuffer[]
        d = my_avail_in;
        if ( d > max_avail )
          d = max_avail;
        m_zlib.strm.next_in = my_next_in;
        m_zlib.strm.avail_in = (unsigned int)d;
      }
      else
      {
        // The call to deflate left some input in m_zlib.strm.next_in[],
        // but I can increase m_zlib.strm.avail_in.
        d =  max_avail - m_zlib.strm.avail_in;
        if ( d > my_avail_in )
          d = my_avail_in;
        m_zlib.strm.avail_in += (unsigned int)d;
      }

      my_avail_in -= d;
      my_next_in  += d;
    }
    else if ( 0 == deflate_output_count )
    {
      // no buffer changes this time
      counter--;
    }

    if ( zrc != Z_OK )
    {
      break;
    }
  }

  if ( 0 == counter )
  {
    rc = false;
  }

  return (rc ? out__count : 0);
}

bool ON_CompressedBuffer::InflateHelper(
        ON_CompressedBufferHelper* helper,
        size_t sizeof___outbuffer,  // sizeof uncompressed data
        void* out___buffer          // buffer for uncompressed data
        ) const
{
  const size_t max_avail = 0x7FFFFFF0; // See max_avail comment in ON_CompressedBuffer::InflateHelper

  bool rc = true;

  int zrc = -1;

  // set up zlib in buffer
  unsigned char* my_next_in = (unsigned char*)m_buffer_compressed;
  size_t my_avail_in = m_sizeof_compressed;

  size_t d = my_avail_in;
  if ( d > max_avail )
    d = max_avail;

  struct ON_CompressedBufferHelper& m_zlib = *helper;

  m_zlib.strm.next_in  = my_next_in;
  m_zlib.strm.avail_in = (unsigned int)d;
  my_next_in  += d;
  my_avail_in -= d;

  // set up zlib out buffer
  unsigned char* my_next_out = (unsigned char*)out___buffer;
  size_t my_avail_out = sizeof___outbuffer;

  d = my_avail_out;
  if ( d > max_avail )
    d = max_avail;
  m_zlib.strm.next_out  = my_next_out;
  m_zlib.strm.avail_out = (unsigned int)d;
  my_next_out  += d;
  my_avail_out -= d;

  // counter guards against infinte loop if there are
  // bugs in zlib return codes
  int counter = 512;
  int flush = Z_NO_FLUSH;

  while ( rc && counter > 0 )
  {
    // Call zlib's inflate function.  It can either process
    // more input from m_zlib.strm.next_in[], create more
    // uncompressed output in m_zlib.strm.next_out[], or do both.
    if ( 0 == my_avail_in && 0 == m_zlib.strm.avail_in )
    {
      // no compressed input is left - switch to finish mode
      flush = Z_FINISH;
    }
    zrc = z_inflate( &m_zlib.strm, flush );
    if ( zrc < 0 )
    {
      // Something went haywire - bail out.
      ON_ERROR("ON_CompressedBuffer::InflateHelper - z_inflate failure");
      rc = false;
      break;
    }

    if ( Z_FINISH == flush && Z_STREAM_END == zrc )
    {
      // no input left, all pending decompression is finished,
      // and all decompressed output has been returned.
      break;
    }

    d = 0;
    if ( my_avail_in > 0 && m_zlib.strm.avail_in < max_avail )
    {
      if ( 0 == m_zlib.strm.avail_in || 0 == m_zlib.strm.next_in )
      {
        // The call to inflate() used up all the input
        // in m_zlib.strm.next_in[].  I can feed it another chunk
        // from inbuffer[]
        d = my_avail_in;
        if ( d > max_avail )
          d = max_avail;
        m_zlib.strm.next_in  = my_next_in;
        m_zlib.strm.avail_in = (unsigned int)d;
      }
      else
      {
        // The call to inflate() left some input in m_zlib.strm.next_in[],
        // but I can increase m_zlib.strm.avail_in.
        d =  max_avail - m_zlib.strm.avail_in;
        if ( d > my_avail_in )
          d = my_avail_in;
        m_zlib.strm.avail_in += (unsigned int)d;
      }
      my_next_in  += d;
      my_avail_in -= d;
    }

    if ( my_avail_out > 0 && m_zlib.strm.avail_out < max_avail )
    {
      // increase m_zlib.strm.next_out[] buffer
      if ( 0 == m_zlib.strm.avail_out || 0 == m_zlib.strm.next_out )
      {
        d = my_avail_out;
        if ( d > max_avail )
          d = max_avail;
        m_zlib.strm.next_out  = my_next_out;
        m_zlib.strm.avail_out = (unsigned int)d;
      }
      else
      {
        d = max_avail - m_zlib.strm.avail_out;
        if ( d > my_avail_out )
          d = my_avail_out;
        m_zlib.strm.avail_out += ((unsigned int)d);
      }
      my_next_out  += d;
      my_avail_out -= d;
    }
    else if ( 0 == d )
    {
      // no buffer changes
      counter--;
    }
  }

  if ( 0 == counter )
  {
    rc = false;
  }

  return rc;
}

bool ON_CompressedBuffer::CompressionInit( struct ON_CompressedBufferHelper* helper ) const
{
  bool rc = false;

  if ( helper )
  {
    // inflateInit() and deflateInit() are in zlib 1.3.3
    if ( 1 == helper->action )
    {
      // begin compression using zlib's deflate tool
      if ( Z_OK == deflateInit( &helper->strm, Z_BEST_COMPRESSION ) )
      {
        rc = true;
      }
      else
      {
        memset(&helper->strm,0,sizeof(helper->strm));
        helper->action = 0;
      }
    }
    else if ( 2 == helper->action )
    {
      // begin uncompression using zlib's inflate tool
      if ( Z_OK == inflateInit( &helper->strm ) )
      {
        rc = true;
      }
      else
      {
        memset(&helper->strm,0,sizeof(helper->strm));
        helper->action = 0;
      }
    }
  }

  return rc;
}

bool ON_CompressedBuffer::CompressionEnd( struct ON_CompressedBufferHelper* helper ) const
{
  bool rc = false;

  if ( helper )
  {
    // inflateEnd() and deflateEnd() are in zlib 1.3.3
    if ( 1 == helper->action )
    {
      // finish compression
      deflateEnd(&helper->strm);
      rc = true;
    }
    else if ( 2 == helper->action )
    {
      // finish decompression
      inflateEnd(&helper->strm);
      rc = true;
    }
    memset(&helper->strm,0,sizeof(helper->strm));
    helper->action = 0;
  }

  return rc;
}


text:
import React, { Component } from 'react'
import Tag from '../../../components/map/tag'
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { createNewEvent, updateEventTag } from '../../../actions/events_creation/events_creation'
import EventCreationFormComponent from '../../../components/map/event_creation/event_creation_form_component'
import * as firebase from 'firebase'

class EventCreationFormContainer extends Component {

  constructor(props) {
    super(props)
    this.state = {
      tags: null
    }
  }

  componentDidMount(){
    var self = this
    firebase.database().ref().child('tags').once('value', function(snapshot){
      var tags = []
      snapshot.forEach(data => {
        var tag = {}
        tag["name"] = data.val()
        tags.push(tag)
      })
      self.setState({ tags })
    })
  }

  render() {

    let p = this.props
    let s = this.state
    const Loading = require('react-loading-animation');
    if (!s.tags)
      return <Loading />
    const tags = s.tags.map((tag, index) => { return <Tag key={index} tag={tag} selected={p.new_event.tag == tag.name} onclick={p.updateEventTag}/>})
    return (<EventCreationFormComponent user = {p.user} createNewEvent={p.createNewEvent} tags={tags}/>)
  }
}

function mapStateToProps(state) {
    return {
      user: state.user,
      new_event: state.new_event
    }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(
    {
      createNewEvent: createNewEvent,
      updateEventTag: updateEventTag
    },
    dispatch
  )
}

export default connect(mapStateToProps, mapDispatchToProps)(EventCreationFormContainer)


text:
package ru.job4j;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by aleks on 21.08.2017.
 */
public class Convert {
    public Node convert(Node root) {
        for (int index = 0; index < 2; index++) {
            int tmp;
            if (root.valueOne > root.valueTwo) {
                tmp = root.valueOne;
                root.valueOne = root.valueTwo;
                root.valueTwo = tmp;
                if (root.valueTwo > root.valueThree) {
                    tmp = root.valueTwo;
                    root.valueTwo = root.valueThree;
                    root.valueThree = tmp;
                }
            }
        }
        return root;
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Azure.Identity;
using NUnit.Framework;
using System;
using System.IO;
using System.Threading;
using Azure.Security.KeyVault.Tests;

namespace Azure.Security.KeyVault.Keys.Samples
{
    /// <summary>
    /// This sample demonstrates how to back up and restore a Key from Azure Key Vault using synchronous methods of <see cref="KeyClient">.
    /// </summary>
    public partial class BackupAndRestore
    {
        [Test]
        [Ignore("https://github.com/Azure/azure-sdk-for-net/issues/6514")]
        public void BackupAndRestoreSync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = TestEnvironment.KeyVaultUrl;

            #region Snippet:KeysSample2KeyClient
            var client = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential());
            #endregion

            #region Snippet:KeysSample2CreateKey
            string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}";
            var rsaKey = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false)
            {
                KeySize = 2048,
                ExpiresOn = DateTimeOffset.Now.AddYears(1)
            };

            KeyVaultKey storedKey = client.CreateRsaKey(rsaKey);
            #endregion

            #region Snippet:KeysSample2BackupKey
            byte[] backupKey = client.BackupKey(rsaKeyName);
            #endregion

            using (var memoryStream = new MemoryStream())
            {
                memoryStream.Write(backupKey, 0, backupKey.Length);

                // The storage account key is no longer in use, so you delete it.
                DeleteKeyOperation operation = client.StartDeleteKey(rsaKeyName);

                // To ensure the key is deleted on server before we try to purge it.
                while (!operation.HasCompleted)
                {
                    Thread.Sleep(2000);

                    operation.UpdateStatus();
                }

                // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged.
                client.PurgeDeletedKey(rsaKeyName);

                #region Snippet:KeysSample2RestoreKey
                KeyVaultKey restoredKey = client.RestoreKeyBackup(memoryStream.ToArray());
                #endregion

                AssertKeysEqual(storedKey.Properties, restoredKey.Properties);

                // Delete and purge the restored key.
                operation = client.StartDeleteKey(rsaKeyName);

                // You only need to wait for completion if you want to purge or recover the key.
                while (!operation.HasCompleted)
                {
                    Thread.Sleep(2000);

                    operation.UpdateStatus();
                }

                client.PurgeDeletedKey(rsaKeyName);
            }
        }

        private void AssertKeysEqual(KeyProperties exp, KeyProperties act)
        {
            Assert.AreEqual(exp.Name, act.Name);
            Assert.AreEqual(exp.Version, act.Version);
            Assert.AreEqual(exp.Managed, act.Managed);
            Assert.AreEqual(exp.RecoveryLevel, act.RecoveryLevel);
            Assert.AreEqual(exp.ExpiresOn, act.ExpiresOn);
            Assert.AreEqual(exp.NotBefore, act.NotBefore);
        }
    }
}


text:
import Transform from 'ember-stickler/transform';

export default Transform.create({
  transform(value) {
    return value.trim();
  }
});


text:
"""
For testing with Firefox at command line. Example:
    python -m chartio {email} {password} {dashboard_url} "Filter Value 1,Filter Value 2"

Uses FireFox and will write PDF to `chartio_test.pdf`

Useful for debugging interactively:
  from IPython.core.debugger import Tracer
  Tracer()() # to break into ipdb
"""

import sys
from chartio import ChartioDashboardRetriever
username, password, dashboard_url, filter_values_str = sys.argv[1:5]
filter_values = filter_values_str.split(',')
chartio = ChartioDashboardRetriever(username, password, debug=True)
chartio.get_pdf_for_dashboard(dashboard_url, filter_values)
chartio.close()


text:
"""
Chapter 15: Binary Search Trees
"""
from sys import maxint

class BST(object):

    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

def check_bst(root):
    """
    Question 15.1: Test if a binary tree satisfies the BST property
    """
    INT_MAX = maxint
    INT_MIN = -maxint - 1
    return check_bst_helper(root, INT_MIN, INT_MAX)

def check_bst_helper(root, low, high):
    if not root:
        return True

    if root.val < low or root.val > high:
        return False

    return check_bst_helper(root.left, low, root.val - 1) \
        and check_bst_helper(root.right, root.val + 1, high)

def find_first_occurrence(root, target):
    """
    Question 15.2: Find first occurrence
    of key in binary search tree, with
    possible duplicate elements
    """
    if root is None:
        return None

    if root.val < target:
        return find_first_occurrence(root.right, target)

    left_res = find_first_occurrence(root.left, target)
    if left_res:
        return left_res

    if root.val == target:
        return root

def find_first_larger_key(root, key):
    """
    Question 15.3: Find the first key larger than given
    value in bst
    """
    larger = None
    while root:
        if root.val > key:
            # check if larger defined
            larger = root.val
            root = root.left
        else:
            root = root.right
    return larger

def find_largest_keys(root, k):
    """
    Question 15.4: Find k largest keys in bst
    """
    largest = []
    stack = []
    done = False

    while not done and len(largest) < k:
        if root:
            stack.append(root)
            root = root.right
        else:
            if len(stack):
                root = stack.pop()
                largest.insert(0, root.val)
                root = root.left
            else:
                done = True
    return largest

def find_lca(root, a, b):
    """
    Question 15.5: Compute the LCA in a BST
    """
    smaller = min(a, b)
    larger = max(a, b)

    cur_node = root

    while cur_node.val > larger or cur_node.val < smaller:
        while cur_node.val > larger:
            if cur_node.left:
                cur_node = cur_node.left
            else:
                return None
        while cur_node.val < smaller:
            if cur_node.right:
                cur_node = cur_node.right
            else:
                return None
    return cur_node.val