text:
import React, { useCallback, useState } from 'react'
import { registerComponent, Components } from '../../lib/vulcan-core';
import { Link } from '../../lib/reactRouterWrapper';
import Button from '@material-ui/core/Button';
import Radio from '@material-ui/core/Radio';
import classNames from 'classnames';

const styles = (theme: ThemeType): JssStyles => ({
  revisionRow: {
    ...theme.typography.commentStyle,
    color: theme.palette.grey[600],
    marginBottom: 6
  },
  radio: {
    padding: 4,
    '& svg': {
      fontSize: 18,
      opacity: .4
    }
  },
  checked: {
    '& svg': {
      opacity: 1
    }
  },
  radioDisabled: {
    color: "rgba(0,0,0,0) !important",
  },
  charsAdded: {
    color: "#008800",
  },
  charsRemoved: {
    color: "#880000",
  },
  button: {
    marginBottom: 12,
    marginTop: 6
  }
});

const RevisionSelect = ({ revisions, getRevisionUrl, onPairSelected, loadMoreProps, classes }: {
  revisions: Array<RevisionMetadataWithChangeMetrics>,
  getRevisionUrl: (rev: RevisionMetadata) => React.ReactNode,
  onPairSelected: ({before, after}: {before: RevisionMetadata, after: RevisionMetadata}) => void,
  loadMoreProps: any,
  classes: ClassesType,
}) => {
  const { FormatDate, UsersName, LoadMore } = Components;

  const [beforeRevisionIndex, setBeforeRevisionIndex] = useState(1);
  const [afterRevisionIndex, setAfterRevisionIndex] = useState(0);

  const compareRevs = useCallback(() => {
    if (!revisions) return;
    onPairSelected({
      before: revisions[beforeRevisionIndex],
      after: revisions[afterRevisionIndex]
    });
  }, [beforeRevisionIndex, afterRevisionIndex, onPairSelected, revisions]);

  return <React.Fragment>
    {revisions.map((rev,i) => {
      const beforeDisabled = i<=afterRevisionIndex;
      const afterDisabled = i>=beforeRevisionIndex;
      const { added, removed } = rev.changeMetrics;

      return (

          <Radio
            className={classNames(classes.radio, {[classes.checked]: i===beforeRevisionIndex, [classes.radioDisabled]: beforeDisabled})}
            disabled={beforeDisabled}
            checked={i===beforeRevisionIndex}
            onChange={(ev, checked) => {
              if (checked) {
                setBeforeRevisionIndex(i);
              }
            }}
          />
          <Radio
            className={classNames(classes.radio, {[classes.checked]: i===afterRevisionIndex, [classes.radioDisabled]: afterDisabled})}
            disabled={afterDisabled}
            checked={i===afterRevisionIndex}
            onChange={(ev, checked) => {
              if (checked) {
                setAfterRevisionIndex(i);
              }
            }}
          />
          <Link to={getRevisionUrl(rev)}>
            {rev.version}{" "}
            <FormatDate format={"LLL z"} date={rev.editedAt}/>{" "}
          </Link>
          <UsersName documentId={rev.userId}/>{" "}
          <Link to={getRevisionUrl(rev)}>
            {(added>0 && removed>0)
              && <>(+{added}/-{removed})</>}
            {(added>0 && removed==0)
              && (+{added})}
            {(added==0 && removed>0)
              && (-{removed})}
            {" "}
            {rev.commitMessage}
          </Link>

      )
    })}

<LoadMore {...loadMoreProps}/>

    <Button className={classes.button} variant="outlined" onClick={compareRevs} >Compare selected revisions</Button>
  </React.Fragment>
}

const RevisionSelectComponent = registerComponent(
  'RevisionSelect', RevisionSelect, {styles}
);

declare global {
  interface ComponentTypes {
   RevisionSelect: typeof RevisionSelectComponent
  }
}


text:
/**
 * Created by korcky on 27/01/17.
 */
public interface Cruiser {
    String getDescription();
}

redpajama_set_name: RedPajamaGithub


text:
package no.ntnu.idi.chirp.rxtx;
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */

/*
  PSerial - class for serial port goodness
  Part of the Processing project - http://processing.org

  Copyright (c) 2004-05 Ben Fry & Casey Reas
  Reworked by Gottfried Haider as part of GSOC 2013

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General
  Public License along with this library; if not, write to the
  Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  Boston, MA  02111-1307  USA
*/

import java.lang.reflect.*;
import java.util.Map;

import jssc.*;

public class Serial implements SerialPortEventListener {
  public SerialPort port;
  Method serialAvailableMethod;
  Method serialEventMethod;

  byte[] buffer = new byte[32768];
  int inBuffer = 0;
  int readOffset = 0;

  int bufferUntilSize = 1;
  byte bufferUntilByte = 0;

  volatile boolean invokeSerialAvailable = false;

  // Things we are currently not exposing:
  // * hardware flow control
  // * state of the RING, RLSD line
  // * sending breaks

  public Serial() throws SerialPortException {
    this( "COM1", 9600, 'N', 8, 1);
  }

  public Serial(int baudRate) throws SerialPortException {
    this("COM1", baudRate, 'N', 8, 1);
  }

  public Serial(String portName) throws SerialPortException {
    this(portName, 9600, 'N', 8, 1);
  }

  public Serial( String portName, int baudRate) throws SerialPortException {
    this( portName, baudRate, 'N', 8, 1);
  }

  public Serial(String portName, int baudRate, char parity, int dataBits, float stopBits) throws SerialPortException {

    // setup parity
    if (parity == 'O') {
      parity = SerialPort.PARITY_ODD;
    } else if (parity == 'E') {
      parity = SerialPort.PARITY_EVEN;
    } else if (parity == 'M') {
      parity = SerialPort.PARITY_MARK;
    } else if (parity == 'S') {
      parity = SerialPort.PARITY_SPACE;
    } else {
      parity = SerialPort.PARITY_NONE;
    }

    // setup stop bits
    int stopBitsIdx = SerialPort.STOPBITS_1;
    if (stopBits == 1.5f) {
      stopBitsIdx = SerialPort.STOPBITS_1_5;
    } else if (stopBits == 2) {
      stopBitsIdx = SerialPort.STOPBITS_2;
    }

    port = new SerialPort(portName);
   // try {
      // the native open() call is not using O_NONBLOCK, so this might block for certain operations (see write())
      port.openPort();

      port.setParams(baudRate, dataBits, stopBitsIdx, parity);
      // we could register more events here
      port.addEventListener(this, SerialPort.MASK_RXCHAR);
   // } catch (SerialPortException e) {
      // this used to be a RuntimeException before, so stick with it
   //   throw new RuntimeException("Error opening serial port " + e.getPortName() + ": " + e.getExceptionType());
   // }

    //serialEventMethod = findCallback("serialEvent");
    //serialAvailableMethod = findCallback("serialAvailable");
  }

  /*private Method findCallback(final String name) {
    try {
      return parent.getClass().getMethod(name, this.getClass());
    } catch (Exception e) {
    }
    // Permit callback(Object) as alternative to callback(Serial).
    try {
      return parent.getClass().getMethod(name, Object.class);
    } catch (Exception e) {
    }
    return null;
  }*/

  public void dispose() {
    stop();
  }

  public void pre() {
    if (serialAvailableMethod != null && invokeSerialAvailable) {
      invokeSerialAvailable = false;
      try {
        serialAvailableMethod.invoke(this);
      } catch (Exception e) {
        System.err.println("Error, disabling serialAvailable() for "+port.getPortName());
        System.err.println(e.getLocalizedMessage());
        serialAvailableMethod = null;
      }
    }
  }

  public int available() {
    return (inBuffer-readOffset);
  }

  public void buffer(int size) {
    bufferUntilSize = size;
  }

  public void bufferUntil(int inByte) {
    bufferUntilSize = 0;
    bufferUntilByte = (byte)inByte;
  }

  public void clear() {
    synchronized (buffer) {
      inBuffer = 0;
      readOffset = 0;
    }
  }

  public boolean getCTS() {
    try {
      return port.isCTS();
    } catch (SerialPortException e) {
      throw new RuntimeException("Error reading the CTS line: " + e.getExceptionType());
    }
  }

  public boolean getDSR() {
    try {
      return port.isDSR();
    } catch (SerialPortException e) {
      throw new RuntimeException("Error reading the DSR line: " + e.getExceptionType());
    }
  }

  public static Map<String, String> getProperties(String portName) {
    return SerialPortList.getPortProperties(portName);
  }

  public int last() {
    if (inBuffer == readOffset) {
      return -1;
    }

    synchronized (buffer) {
      int ret = buffer[inBuffer-1] & 0xFF;
      inBuffer = 0;
      readOffset = 0;
      return ret;
    }
  }

  public char lastChar() {
    return (char)last();
  }

  public static String[] list() {
    // returns list sorted alphabetically, thus cu.* comes before tty.*
    // this was different with RXTX
    return SerialPortList.getPortNames();
  }

  public int read() {
    if (inBuffer == readOffset) {
      return -1;
    }

    synchronized (buffer) {
      int ret = buffer[readOffset++] & 0xFF;
      if (inBuffer == readOffset) {
        inBuffer = 0;
        readOffset = 0;
      }
      return ret;
    }
  }

  public byte[] readBytes() {
    if (inBuffer == readOffset) {
      return null;
    }

    synchronized (buffer) {
      byte[] ret = new byte[inBuffer-readOffset];
      System.arraycopy(buffer, readOffset, ret, 0, ret.length);
      inBuffer = 0;
      readOffset = 0;
      return ret;
    }
  }

  public int readBytes(byte[] dest) {
    if (inBuffer == readOffset) {
      return 0;
    }

    synchronized (buffer) {
      int toCopy = inBuffer-readOffset;
      if (dest.length < toCopy) {
        toCopy = dest.length;
      }
      System.arraycopy(buffer, readOffset, dest, 0, toCopy);
      readOffset += toCopy;
      if (inBuffer == readOffset) {
        inBuffer = 0;
        readOffset = 0;
      }
      return toCopy;
    }
  }

  public byte[] readBytesUntil(int inByte) {
    if (inBuffer == readOffset) {
      return null;
    }

    synchronized (buffer) {
      // look for needle in buffer
      int found = -1;
      for (int i=readOffset; i < inBuffer; i++) {
        if (buffer[i] == (byte)inByte) {
          found = i;
          break;
        }
      }
      if (found == -1) {
        return null;
      }

      int toCopy = found-readOffset+1;
      byte[] dest = new byte[toCopy];
      System.arraycopy(buffer, readOffset, dest, 0, toCopy);
      readOffset += toCopy;
      if (inBuffer == readOffset) {
        inBuffer = 0;
        readOffset = 0;
      }
      return dest;
    }
  }

  public int readBytesUntil(int inByte, byte[] dest) {
    if (inBuffer == readOffset) {
      return 0;
    }

    synchronized (buffer) {
      // look for needle in buffer
      int found = -1;
      for (int i=readOffset; i < inBuffer; i++) {
        if (buffer[i] == (byte)inByte) {
          found = i;
          break;
        }
      }
      if (found == -1) {
        return 0;
      }

      // check if bytes to copy fit in dest
      int toCopy = found-readOffset+1;
      if (dest.length < toCopy) {
        System.err.println( "The buffer passed to readBytesUntil() is to small " +
                  "to contain " + toCopy + " bytes up to and including " +
                  "char " + (byte)inByte);
        return -1;
      }
      System.arraycopy(buffer, readOffset, dest, 0, toCopy);
      readOffset += toCopy;
      if (inBuffer == readOffset) {
        inBuffer = 0;
        readOffset = 0;
      }
      return toCopy;
    }
  }

  public char readChar() {
    return (char) read();
  }

  public String readString() {
    if (inBuffer == readOffset) {
      return null;
    }
    return new String(readBytes());
  }

  public String readStringUntil(int inByte) {
    byte temp[] = readBytesUntil(inByte);
    if (temp == null) {
      return null;
    } else {
      return new String(temp);
    }
  }

  public void serialEvent(SerialPortEvent event) {
    if (event.getEventType() == SerialPortEvent.RXCHAR) {
      int toRead;
      try {
        while (0 < (toRead = port.getInputBufferBytesCount())) {
          // this method can be called from the context of another thread
          synchronized (buffer) {
            // read one byte at a time if the sketch is using serialEvent
            if (serialEventMethod != null) {
              toRead = 1;
            }
            // enlarge buffer if necessary
            if (buffer.length < inBuffer+toRead) {
              byte temp[] = new byte[buffer.length<<1];
              System.arraycopy(buffer, 0, temp, 0, inBuffer);
              buffer = temp;
            }
            // read an array of bytes and copy it into our buffer
            byte[] read = port.readBytes(toRead);
            System.arraycopy(read, 0, buffer, inBuffer, read.length);
            inBuffer += read.length;
          }
          if (serialEventMethod != null) {
            if ((0 < bufferUntilSize && bufferUntilSize <= inBuffer-readOffset) ||
              (0 == bufferUntilSize && bufferUntilByte == buffer[inBuffer-1])) {
              try {
                // serialEvent() is invoked in the context of the current (serial) thread
                // which means that serialization and atomic variables need to be used to
                // guarantee reliable operation (and better not draw() etc..)
                // serialAvailable() does not provide any real benefits over using
                // available() and read() inside draw - but this function has no
                // thread-safety issues since it's being invoked during pre in the context
                // of the Processing applet
                serialEventMethod.invoke(this);
              } catch (Exception e) {
                System.err.println("Error, disabling serialEvent() for "+port.getPortName());
                System.err.println(e.getLocalizedMessage());
                serialEventMethod = null;
              }
            }
          }
          invokeSerialAvailable = true;
        }
      } catch (SerialPortException e) {
        throw new RuntimeException("Error reading from serial port " + e.getPortName() + ": " + e.getExceptionType());
      }
    }
  }

  public void setDTR(boolean state) {
    // there is no way to influence the behavior of the DTR line when opening the serial port
    // this means that at least on Linux and OS X, Arduino devices are always reset
    try {
      port.setDTR(state);
    } catch (SerialPortException e) {
      throw new RuntimeException("Error setting the DTR line: " + e.getExceptionType());
    }
  }

  public void setRTS(boolean state) {
    try {
      port.setRTS(state);
    } catch (SerialPortException e) {
      throw new RuntimeException("Error setting the RTS line: " + e.getExceptionType());
    }
  }

  public void stop() {
    try {
      port.closePort();
    } catch (SerialPortException e) {
      // ignored
    	System.err.println("Serial port exception: " + e.getMessage());
    }
    inBuffer = 0;
    readOffset = 0;
  }

  public void write(byte[] src) {
    try {
      // this might block if the serial device is not yet ready (esp. tty devices under OS X)
      port.writeBytes(src);
      // we used to call flush() here
    } catch (SerialPortException e) {
      throw new RuntimeException("Error writing to serial port " + e.getPortName() + ": " + e.getExceptionType());
    }
  }

  public void write(int src) {
    try {
      port.writeInt(src);
    } catch (SerialPortException e) {
      throw new RuntimeException("Error writing to serial port " + e.getPortName() + ": " + e.getExceptionType());
    }
  }

  public void write(String src) {
    try {
      port.writeString(src);
    } catch (SerialPortException e) {
      throw new RuntimeException("Error writing to serial port " + e.getPortName() + ": " + e.getExceptionType());
    }
  }
}


text:
<?php

namespace PServerCore\Entity\Repository;

use Doctrine\ORM\EntityRepository;
use PServerCore\Entity\UserInterface;

class UserExtension extends EntityRepository
{
    /**
     * @param UserInterface $user
     * @param string $key
     */
    public function deleteExtension(UserInterface $user, $key = null)
    {
        $query = $this->createQueryBuilder('p')
            ->delete()
            ->where('p.user = :user')
            ->setParameter('user', $user);

        if ($key) {
            $query->andWhere('p.key = :key')
                ->setParameter('key', $key);
        }

        $query->getQuery()
            ->execute();
    }

}


text:
#ifndef __PROJECT_EULER_PROBLEM267_H__
#define __PROJECT_EULER_PROBLEM267_H__
/*
 * ProjectEuler/include/c/ProjectEuler/Problem267.h
 *
 * Billionaire
 * ===========
 * Published on Friday, 4th December 2009, 01:00 pm
 *
 * You are given a unique investment opportunity. Starting with £1 of capital,
 * you can choose a fixed proportion, f, of your capital to bet on a fair coin
 * toss repeatedly for 1000 tosses. Your return is double your bet for heads and
 * you lose your bet for tails. For example, if f = 1/4,  for the first toss you
 * bet £0.25, and if heads comes up you win £0.5 and so then have £1.5. You then
 * bet £0.375 and if the second toss is tails, you have £1.125. Choosing f to
 * maximize your chances of having at least £1,000,000,000 after 1,000 flips,
 * what is the chance that you become a billionaire? All computations are
 * assumed to be exact (no rounding), but give your answer rounded to 12 digits
 * behind the decimal point in the form 0.abcdefghijkl.
 */

#  ifdef __cplusplus
extern "C" {
#  endif

#  ifdef __cplusplus
}
#  endif

#endif  /* __PROJECT_EULER_PROBLEM267_H__ */


text:
/** @file
 * @brief CANBUS Sockets related functions
 */

/*
 * Copyright (c) 2019 Intel Corporation
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#include <logging/log.h>
LOG_MODULE_REGISTER(net_sockets_can, CONFIG_NET_SOCKETS_LOG_LEVEL);

#include <errno.h>
#include <net/net_pkt.h>
#include <net/net_context.h>
#include <net/socket_can.h>

#include "connection.h"

enum net_verdict net_canbus_socket_input(struct net_pkt *pkt)
{
	if (net_pkt_family(pkt) == AF_CAN &&
	    net_if_l2(net_pkt_iface(pkt)) == &NET_L2_GET_NAME(CANBUS)) {
		return net_conn_input(pkt, NULL, CAN_RAW, NULL);
	}

	return NET_CONTINUE;
}


text:
<!DOCTYPE html>

    <title>Pause Play Test</title>

Pause Play Test

Status: not-started


text:
"""
(c) RIKEN 2017. All rights reserved.
Author: Keitaro Yamashita

This software is released under the new BSD License; see LICENSE.
"""
from __future__ import print_function
from __future__ import unicode_literals

from builtins import range
from yamtbx.dataproc.auto.multi_merging.resolve_reindex import KabschSelectiveBreeding
from yamtbx.util import read_path_list
from libtbx.utils import multi_out
import iotbx.phil
import libtbx.phil
from cctbx import sgtbx
from cctbx import crystal
import os
import sys
import copy
import numpy

master_params_str = """\
lstin = None
 .type = path
 .help = list of XDS_ASCII.HKL
method = pointless *selective_breeding
 .type = choice(multi=False)
 .help = method
from_p1 = False
 .type = bool
 .help = Start from P1 whatever the symmetry of input files.
logfile = "multi_determine_symmetry.log"
 .type = path
 .help = logfile name
nproc = 1
 .type = int
 .help = number of processors

d_min = 3
 .type = float
 .help = high resolution cutoff used in the method
min_ios = None
 .type = float
 .help = minimum I/sigma(I) cutoff used in the method
max_delta = 5
 .type = float
 .help = maximum obliquity used in determining the lattice symmetry, using a modified Le-Page algorithm.

max_cycles = 100
 .type = int(value_min=1)
 .help = Maximum number of cycles for selective_breeding algorithm.

"""

def run(params):
    log_out = multi_out()
    log_out.register("log", open(params.logfile, "w"), atexit_send_to=None)
    log_out.register("stdout", sys.stdout)

    libtbx.phil.parse(master_params_str).format(params).show(out=log_out, prefix=" ")

    xac_files = read_path_list(params.lstin, only_exists=True, err_out=log_out)
    if len(xac_files) == 0:
        print("No (existing) files in the list: %s" % params.lstin, file=log_out)
        return

    if params.method == "selective_breeding":
        rb = KabschSelectiveBreeding(xac_files, max_delta=params.max_delta,
                                     d_min=params.d_min, min_ios=params.min_ios,
                                     nproc=params.nproc, log_out=log_out,
                                     from_p1=params.from_p1)
        xs = rb.representative_crystal_symmetry()

        log_out.write("Starting from:\n")
        xs.show_summary(log_out, "  ")
        log_out.write("\n")

        rb.assign_operators(max_cycle=params.max_cycles)
        rb.show_assign_summary()
        final_cc_means = rb.final_cc_means()
        assert len(final_cc_means) == len(xac_files)
        reidx_ops = rb.reindex_operators()
        sg = copy.copy(xs.space_group())
        unit_cell = xs.unit_cell()

        cc0 = [x[0][1] for x in final_cc_means]
        log_out.write("Analyzing KabschSelectiveBreeding result..\n")

        accepted_ops = []

        for iop in range(1, len(reidx_ops)):
            cci = [x[iop][1] for x in final_cc_means]
            corr = numpy.corrcoef(cc0, cci)[0,1]
            log_out.write("  h,k,l vs %s: corr= %.4f\n" % (reidx_ops[iop].as_hkl(), corr))
            if corr > 0.5:
                accepted_ops.append(reidx_ops[iop])
                sg.expand_smx(reidx_ops[iop].as_hkl())
                unit_cell = unit_cell.change_basis(reidx_ops[iop])
                log_out.write("    this operator accepted. sg= %s\n" % sg.info())

        log_out.write("Solution:\n")
        new_xs = crystal.symmetry(unit_cell, space_group=sg)
        new_xs.show_summary(log_out, "  ")
        log_out.write("As reference setting:\n")
        new_xs.as_reference_setting().show_summary(log_out, "  ")

        log_out.write("Initial:\n")
        xs.show_summary(log_out, "  ")

        log_out.write("""
* Notice *
Here the space group is deduced from the similarity of reflection intensities under the constraint of lattice symmetry.
This could be wrong especially when the crystal is twineed.
Please note that space group is only determined when the structure is solved.
""")

    else:
        raise "invalid method choice (method=%s)" % params.method

# run()

def show_help():
    print("""
""")
    iotbx.phil.parse(master_params_str).show(prefix="  ", attributes_level=1)
    print()
# show_help()

def run_from_args(argv):
    if "-h" in argv or "--help" in argv:
        show_help()
        return

    cmdline = iotbx.phil.process_command_line(args=argv,
                                              master_string=master_params_str)
    params = cmdline.work.extract()
    args = cmdline.remaining_args

    for arg in args:
        if os.path.isfile(arg) and params.lstin is None:
            params.lstin = arg

    if params.lstin is None:
        show_help()
        print("Error: Give .lst of XDS_ASCII files")
        quit()

    run(params)
# run_from_args()

if __name__ == "__main__":
    import sys
    run_from_args(sys.argv[1:])


text:
require File.join(File.dirname(__FILE__), 'spec_helper')

context "A new Database" do
  before do
    @db = Sequel::Database.new(1 => 2, :logger => 3)
  end
  after do
    Sequel.quote_identifiers = false
    Sequel.identifier_input_method = nil
    Sequel.identifier_output_method = nil
  end

  specify "should receive options" do
    @db.opts.should == {1 => 2, :logger => 3}
  end

  specify "should set the logger from opts[:logger] and opts[:loggers]" do
    @db.loggers.should == [3]
    Sequel::Database.new(1 => 2, :loggers => 3).loggers.should == [3]
    Sequel::Database.new(1 => 2, :loggers => [3]).loggers.should == [3]
    Sequel::Database.new(1 => 2, :logger => 4, :loggers => 3).loggers.should == [4,3]
    Sequel::Database.new(1 => 2, :logger => [4], :loggers => [3]).loggers.should == [4,3]
  end

  specify "should create a connection pool" do
    @db.pool.should be_a_kind_of(Sequel::ConnectionPool)
    @db.pool.max_size.should == 4

    Sequel::Database.new(:max_connections => 10).pool.max_size.should == 10
  end

  specify "should pass the supplied block to the connection pool" do
    cc = nil
    d = Sequel::Database.new {1234}
    d.synchronize {|c| cc = c}
    cc.should == 1234
  end

  specify "should respect the :single_threaded option" do
    db = Sequel::Database.new(:single_threaded=>true)
    db.pool.should be_a_kind_of(Sequel::SingleThreadedPool)
    db = Sequel::Database.new(:single_threaded=>false)
    db.pool.should be_a_kind_of(Sequel::ConnectionPool)
  end

  specify "should respect the :quote_identifiers option" do
    db = Sequel::Database.new(:quote_identifiers=>false)
    db.quote_identifiers?.should == false
    db = Sequel::Database.new(:quote_identifiers=>true)
    db.quote_identifiers?.should == true
  end

  specify "should upcase on input and downcase on output by default" do
    db = Sequel::Database.new
    db.send(:identifier_input_method_default).should == :upcase
    db.send(:identifier_output_method_default).should == :downcase
  end

  deprec_specify "should respect the :upcase_identifiers option" do
    Sequel.upcase_identifiers = false
    db = Sequel::Database.new(:upcase_identifiers=>false)
    db.upcase_identifiers?.should == false
    db.upcase_identifiers = true
    db.upcase_identifiers?.should == true
    db = Sequel::Database.new(:upcase_identifiers=>true)
    db.upcase_identifiers?.should == true
    db.upcase_identifiers = false
    db.upcase_identifiers?.should == false
    Sequel.upcase_identifiers = true
    db = Sequel::Database.new(:upcase_identifiers=>false)
    db.upcase_identifiers?.should == false
    db.upcase_identifiers = true
    db.upcase_identifiers?.should == true
    db = Sequel::Database.new(:upcase_identifiers=>true)
    db.upcase_identifiers?.should == true
    db.upcase_identifiers = false
    db.upcase_identifiers?.should == false
  end

  specify "should respect the :identifier_input_method option" do
    Sequel.identifier_input_method = nil
    Sequel::Database.identifier_input_method.should == ""
    db = Sequel::Database.new(:identifier_input_method=>nil)
    db.identifier_input_method.should == nil
    db.identifier_input_method = :downcase
    db.identifier_input_method.should == :downcase
    db = Sequel::Database.new(:identifier_input_method=>:upcase)
    db.identifier_input_method.should == :upcase
    db.identifier_input_method = nil
    db.identifier_input_method.should == nil
    Sequel.identifier_input_method = :downcase
    Sequel::Database.identifier_input_method.should == :downcase
    db = Sequel::Database.new(:identifier_input_method=>nil)
    db.identifier_input_method.should == nil
    db.identifier_input_method = :upcase
    db.identifier_input_method.should == :upcase
    db = Sequel::Database.new(:identifier_input_method=>:upcase)
    db.identifier_input_method.should == :upcase
    db.identifier_input_method = nil
    db.identifier_input_method.should == nil
  end

  specify "should respect the :identifier_output_method option" do
    Sequel.identifier_output_method = nil
    Sequel::Database.identifier_output_method.should == ""
    db = Sequel::Database.new(:identifier_output_method=>nil)
    db.identifier_output_method.should == nil
    db.identifier_output_method = :downcase
    db.identifier_output_method.should == :downcase
    db = Sequel::Database.new(:identifier_output_method=>:upcase)
    db.identifier_output_method.should == :upcase
    db.identifier_output_method = nil
    db.identifier_output_method.should == nil
    Sequel.identifier_output_method = :downcase
    Sequel::Database.identifier_output_method.should == :downcase
    db = Sequel::Database.new(:identifier_output_method=>nil)
    db.identifier_output_method.should == nil
    db.identifier_output_method = :upcase
    db.identifier_output_method.should == :upcase
    db = Sequel::Database.new(:identifier_output_method=>:upcase)
    db.identifier_output_method.should == :upcase
    db.identifier_output_method = nil
    db.identifier_output_method.should == nil
  end

  specify "should use the default Sequel.quote_identifiers value" do
    Sequel.quote_identifiers = true
    Sequel::Database.new({}).quote_identifiers?.should == true
    Sequel.quote_identifiers = false
    Sequel::Database.new({}).quote_identifiers?.should == false
    Sequel::Database.quote_identifiers = true
    Sequel::Database.new({}).quote_identifiers?.should == true
    Sequel::Database.quote_identifiers = false
    Sequel::Database.new({}).quote_identifiers?.should == false
  end

  deprec_specify "should use the default Sequel.upcase_identifiers value" do
    Sequel.upcase_identifiers = true
    Sequel::Database.new({}).upcase_identifiers?.should == true
    Sequel.upcase_identifiers = false
    Sequel::Database.new({}).upcase_identifiers?.should == false
    Sequel::Database.upcase_identifiers = true
    Sequel::Database.new({}).upcase_identifiers?.should == true
    Sequel::Database.upcase_identifiers = false
    Sequel::Database.new({}).upcase_identifiers?.should == false
  end

  specify "should use the default Sequel.identifier_input_method value" do
    Sequel.identifier_input_method = :downcase
    Sequel::Database.new({}).identifier_input_method.should == :downcase
    Sequel.identifier_input_method = :upcase
    Sequel::Database.new({}).identifier_input_method.should == :upcase
    Sequel::Database.identifier_input_method = :downcase
    Sequel::Database.new({}).identifier_input_method.should == :downcase
    Sequel::Database.identifier_input_method = :upcase
    Sequel::Database.new({}).identifier_input_method.should == :upcase
  end

  specify "should use the default Sequel.identifier_output_method value" do
    Sequel.identifier_output_method = :downcase
    Sequel::Database.new({}).identifier_output_method.should == :downcase
    Sequel.identifier_output_method = :upcase
    Sequel::Database.new({}).identifier_output_method.should == :upcase
    Sequel::Database.identifier_output_method = :downcase
    Sequel::Database.new({}).identifier_output_method.should == :downcase
    Sequel::Database.identifier_output_method = :upcase
    Sequel::Database.new({}).identifier_output_method.should == :upcase
  end

  specify "should respect the quote_indentifiers_default method if Sequel.quote_identifiers = nil" do
    Sequel.quote_identifiers = nil
    Sequel::Database.new({}).quote_identifiers?.should == true
    x = Class.new(Sequel::Database){def quote_identifiers_default; false end}
    x.new({}).quote_identifiers?.should == false
    y = Class.new(Sequel::Database){def quote_identifiers_default; true end}
    y.new({}).quote_identifiers?.should == true
  end

  specify "should respect the identifier_input_method_default method" do
    class Sequel::Database
      @@identifier_input_method = nil
    end
    x = Class.new(Sequel::Database){def identifier_input_method_default; :downcase end}
    x.new({}).identifier_input_method.should == :downcase
    y = Class.new(Sequel::Database){def identifier_input_method_default; :camelize end}
    y.new({}).identifier_input_method.should == :camelize
  end

  specify "should respect the identifier_output_method_default method if Sequel.identifier_output_method is not called" do
    class Sequel::Database
      @@identifier_output_method = nil
    end
    x = Class.new(Sequel::Database){def identifier_output_method_default; :upcase end}
    x.new({}).identifier_output_method.should == :upcase
    y = Class.new(Sequel::Database){def identifier_output_method_default; :underscore end}
    y.new({}).identifier_output_method.should == :underscore
  end

  specify "should just use a :uri option for jdbc with the full connection string" do
    Sequel::Database.should_receive(:adapter_class).once.with(:jdbc).and_return(Sequel::Database)
    db = Sequel.connect('jdbc:test://host/db_name')
    db.should be_a_kind_of(Sequel::Database)
    db.opts[:uri].should == 'jdbc:test://host/db_name'
  end

  specify "should just use a :uri option for do with the full connection string" do
    Sequel::Database.should_receive(:adapter_class).once.with(:do).and_return(Sequel::Database)
    db = Sequel.connect('do:test://host/db_name')
    db.should be_a_kind_of(Sequel::Database)
    db.opts[:uri].should == 'do:test://host/db_name'
  end
end

context "Database#disconnect" do
  specify "should call pool.disconnect" do
    d = Sequel::Database.new
    p = d.pool
    p.should_receive(:disconnect).once.and_return(2)
    d.disconnect.should == 2
  end
end

context "Database#connect" do
  specify "should raise NotImplementedError" do
    proc {Sequel::Database.new.connect}.should raise_error(NotImplementedError)
  end
end

context "Database#uri" do
  before do
    @c = Class.new(Sequel::Database) do
      set_adapter_scheme :mau
    end

    @db = Sequel.connect('mau://user:pass@localhost:9876/maumau')
  end

  specify "should return the connection URI for the database" do
    @db.uri.should == 'mau://user:pass@localhost:9876/maumau'
  end

  specify "should be aliased as #url" do
    @db.url.should == 'mau://user:pass@localhost:9876/maumau'
  end
end

context "Database.adapter_scheme" do
  specify "should return the database schema" do
    Sequel::Database.adapter_scheme.should be_nil

    @c = Class.new(Sequel::Database) do
      set_adapter_scheme :mau
    end

    @c.adapter_scheme.should == :mau
  end
end

context "Database#dataset" do
  before do
    @db = Sequel::Database.new
    @ds = @db.dataset
  end

  specify "should provide a blank dataset through #dataset" do
    @ds.should be_a_kind_of(Sequel::Dataset)
    @ds.opts.should == {}
    @ds.db.should be(@db)
  end

  specify "should provide a #from dataset" do
    d = @db.from(:mau)
    d.should be_a_kind_of(Sequel::Dataset)
    d.sql.should == 'SELECT * FROM mau'

    e = @db[:miu]
    e.should be_a_kind_of(Sequel::Dataset)
    e.sql.should == 'SELECT * FROM miu'
  end

  specify "should provide a filtered #from dataset if a block is given" do
    d = @db.from(:mau) {:x.sql_number > 100}
    d.should be_a_kind_of(Sequel::Dataset)
    d.sql.should == 'SELECT * FROM mau WHERE (x > 100)'
  end

  specify "should provide a #select dataset" do
    d = @db.select(:a, :b, :c).from(:mau)
    d.should be_a_kind_of(Sequel::Dataset)
    d.sql.should == 'SELECT a, b, c FROM mau'
  end

  specify "should allow #select to take a block" do
    d = @db.select(:a, :b){c}.from(:mau)
    d.should be_a_kind_of(Sequel::Dataset)
    d.sql.should == 'SELECT a, b, c FROM mau'
  end
end

context "Database#execute" do
  specify "should raise NotImplementedError" do
    proc {Sequel::Database.new.execute('blah blah')}.should raise_error(NotImplementedError)
    proc {Sequel::Database.new << 'blah blah'}.should raise_error(NotImplementedError)
  end
end

context "Database#<<" do
  before do
    @c = Class.new(Sequel::Database) do
      define_method(:execute) {|sql, opts| sql}
    end
    @db = @c.new({})
  end

  specify "should pass the supplied sql to #execute" do
    (@db << "DELETE FROM items").should == "DELETE FROM items"
  end

  deprec_specify "should accept an array and convert it to SQL" do
    a = %[
      --
      CREATE TABLE items (a integer, /*b integer*/
        b text, c integer);
      DROP TABLE old_items;
    ].split($/)
    (@db << a).should ==
      "CREATE TABLE items (a integer, b text, c integer); DROP TABLE old_items;"
  end

  deprec_specify "should remove comments and whitespace from arrays" do
    s = %[
      --
      CREATE TABLE items (a integer, /*b integer*/
        b text, c integer); \r\n
      DROP TABLE old_items;
    ].split($/)
    (@db << s).should ==
      "CREATE TABLE items (a integer, b text, c integer); DROP TABLE old_items;"
  end

  specify "should not remove comments and whitespace from strings" do
    s = "INSERT INTO items VALUES ('---abc')"
    (@db << s).should == s
  end
end

context "Database#synchronize" do
  before do
    @db = Sequel::Database.new(:max_connections => 1)
    @db.pool.connection_proc = proc {12345}
  end

  specify "should wrap the supplied block in pool.hold" do
    stop = false
    c1, c2 = nil
    t1 = Thread.new {@db.synchronize {|c| c1 = c; while !stop;sleep 0.1;end}}
    while !c1;end
    c1.should == 12345
    t2 = Thread.new {@db.synchronize {|c| c2 = c}}
    sleep 0.2
    @db.pool.available_connections.should be_empty
    c2.should be_nil
    stop = true
    t1.join
    sleep 0.1
    c2.should == 12345
    t2.join
  end
end

context "Database#test_connection" do
  before do
    @db = Sequel::Database.new
    @test = nil
    @db.pool.connection_proc = proc {@test = rand(100)}
  end

  specify "should call pool#hold" do
    @db.test_connection
    @test.should_not be_nil
  end

  specify "should return true if successful" do
    @db.test_connection.should be_true
  end
end

class DummyDataset < Sequel::Dataset
  def first
    raise if @opts[:from] == [:a]
    true
  end
end

class DummyDatabase < Sequel::Database
  attr_reader :sqls

  def execute(sql, opts={})
    @sqls ||= []
    @sqls << sql
  end

  def transaction; yield; end

  def dataset
    DummyDataset.new(self)
  end
end

context "Database#create_table" do
  before do
    @db = DummyDatabase.new
  end

  specify "should construct proper SQL" do
    @db.create_table :test do
      primary_key :id, :integer, :null => false
      column :name, :text
      index :name, :unique => true
    end
    @db.sqls.should == [
      'CREATE TABLE test (id integer NOT NULL PRIMARY KEY AUTOINCREMENT, name text)',
      'CREATE UNIQUE INDEX test_name_index ON test (name)'
    ]
  end
end

context "Database#alter_table" do
  before do
    @db = DummyDatabase.new
  end

  specify "should construct proper SQL" do
    @db.alter_table :xyz do
      add_column :aaa, :text, :null => false, :unique => true
      drop_column :bbb
      rename_column :ccc, :ddd
      set_column_type :eee, :integer
      set_column_default :hhh, 'abcd'

      add_index :fff, :unique => true
      drop_index :ggg
    end

    @db.sqls.should == [
      'ALTER TABLE xyz ADD COLUMN aaa text UNIQUE NOT NULL',
      'ALTER TABLE xyz DROP COLUMN bbb',
      'ALTER TABLE xyz RENAME COLUMN ccc TO ddd',
      'ALTER TABLE xyz ALTER COLUMN eee TYPE integer',
      "ALTER TABLE xyz ALTER COLUMN hhh SET DEFAULT 'abcd'",

      'CREATE UNIQUE INDEX xyz_fff_index ON xyz (fff)',
      'DROP INDEX xyz_ggg_index'
    ]
  end
end

context "Database#add_column" do
  before do
    @db = DummyDatabase.new
  end

  specify "should construct proper SQL" do
    @db.add_column :test, :name, :text, :unique => true
    @db.sqls.should == [
      'ALTER TABLE test ADD COLUMN name text UNIQUE'
    ]
  end
end

context "Database#drop_column" do
  before do
    @db = DummyDatabase.new
  end

  specify "should construct proper SQL" do
    @db.drop_column :test, :name
    @db.sqls.should == [
      'ALTER TABLE test DROP COLUMN name'
    ]
  end
end

context "Database#rename_column" do
  before do
    @db = DummyDatabase.new
  end

  specify "should construct proper SQL" do
    @db.rename_column :test, :abc, :def
    @db.sqls.should == [
      'ALTER TABLE test RENAME COLUMN abc TO def'
    ]
  end
end

context "Database#set_column_type" do
  before do
    @db = DummyDatabase.new
  end

  specify "should construct proper SQL" do
    @db.set_column_type :test, :name, :integer
    @db.sqls.should == [
      'ALTER TABLE test ALTER COLUMN name TYPE integer'
    ]
  end
end

context "Database#set_column_default" do
  before do
    @db = DummyDatabase.new
  end

  specify "should construct proper SQL" do
    @db.set_column_default :test, :name, 'zyx'
    @db.sqls.should == [
      "ALTER TABLE test ALTER COLUMN name SET DEFAULT 'zyx'"
    ]
  end
end

context "Database#add_index" do
  before do
    @db = DummyDatabase.new
  end

  specify "should construct proper SQL" do
    @db.add_index :test, :name, :unique => true
    @db.sqls.should == [
      'CREATE UNIQUE INDEX test_name_index ON test (name)'
    ]
  end

  specify "should accept multiple columns" do
    @db.add_index :test, [:one, :two]
    @db.sqls.should == [
      'CREATE INDEX test_one_two_index ON test (one, two)'
    ]
  end
end

context "Database#drop_index" do
  before do
    @db = DummyDatabase.new
  end

  specify "should construct proper SQL" do
    @db.drop_index :test, :name
    @db.sqls.should == [
      'DROP INDEX test_name_index'
    ]
  end

end

class Dummy2Database < Sequel::Database
  attr_reader :sql
  def execute(sql); @sql = sql; end
  def transaction; yield; end
end

context "Database#drop_table" do
  before do
    @db = DummyDatabase.new
  end

  specify "should construct proper SQL" do
    @db.drop_table :test
    @db.sqls.should == ['DROP TABLE test']
  end

  specify "should accept multiple table names" do
    @db.drop_table :a, :bb, :ccc
    @db.sqls.should == [
      'DROP TABLE a',
      'DROP TABLE bb',
      'DROP TABLE ccc'
    ]
  end
end

context "Database#rename_table" do
  before do
    @db = DummyDatabase.new
  end

  specify "should construct proper SQL" do
    @db.rename_table :abc, :xyz
    @db.sqls.should == ['ALTER TABLE abc RENAME TO xyz']
  end
end

context "Database#table_exists?" do
  before do
    @db = DummyDatabase.new
    @db.instance_variable_set(:@schemas, {:a=>[]})
    @db2 = DummyDatabase.new
  end

  specify "should use schema information if available" do
    @db.table_exists?(:a).should be_true
  end

  specify "should otherwise try to select the first record from the table's dataset" do
    @db2.table_exists?(:a).should be_false
    @db2.table_exists?(:b).should be_true
  end
end

class Dummy3Database < Sequel::Database
  attr_reader :sql, :transactions
  def execute(sql, opts={}); @sql ||= []; @sql << sql; end

  class DummyConnection
    def initialize(db); @db = db; end
    def execute(sql); @db.execute(sql); end
  end
end

context "Database#transaction" do
  before do
    @db = Dummy3Database.new
    @db.pool.connection_proc = proc {Dummy3Database::DummyConnection.new(@db)}
  end

  specify "should wrap the supplied block with BEGIN + COMMIT statements" do
    @db.transaction {@db.execute 'DROP TABLE test;'}
    @db.sql.should == ['BEGIN', 'DROP TABLE test;', 'COMMIT']
  end

  specify "should handle returning inside of the block by committing" do
    def @db.ret_commit
      transaction do
        execute 'DROP TABLE test;'
        return
        execute 'DROP TABLE test2;';
      end
    end
    @db.ret_commit
    @db.sql.should == ['BEGIN', 'DROP TABLE test;', 'COMMIT']
  end

  specify "should issue ROLLBACK if an exception is raised, and re-raise" do
    @db.transaction {@db.execute 'DROP TABLE test'; raise RuntimeError} rescue nil
    @db.sql.should == ['BEGIN', 'DROP TABLE test', 'ROLLBACK']

    proc {@db.transaction {raise RuntimeError}}.should raise_error(RuntimeError)
  end

  specify "should issue ROLLBACK if Sequel::Rollback is called in the transaction" do
    @db.transaction do
      @db.drop_table(:a)
      raise Sequel::Rollback
      @db.drop_table(:b)
    end

    @db.sql.should == ['BEGIN', 'DROP TABLE a', 'ROLLBACK']
  end

  specify "should be re-entrant" do
    stop = false
    cc = nil
    t = Thread.new do
      @db.transaction {@db.transaction {@db.transaction {|c|
        cc = c
        while !stop; sleep 0.1; end
      }}}
    end
    while cc.nil?; sleep 0.1; end
    cc.should be_a_kind_of(Dummy3Database::DummyConnection)
    @db.transactions.should == [t]
    stop = true
    t.join
    @db.transactions.should be_empty
  end
end

context "A Database adapter with a scheme" do
  before do
    class CCC < Sequel::Database
      if defined?(DISCONNECTS)
        DISCONNECTS.clear
      else
        DISCONNECTS = []
      end
      set_adapter_scheme :ccc
      def disconnect
        DISCONNECTS << self
      end
    end
  end

  specify "should be registered in the ADAPTER_MAP" do
    Sequel::ADAPTER_MAP[:ccc].should == CCC
  end

  specify "should be instantiated when its scheme is specified" do
    c = Sequel::Database.connect('ccc://localhost/db')
    c.should be_a_kind_of(CCC)
    c.opts[:host].should == 'localhost'
    c.opts[:database].should == 'db'
  end

  specify "should be accessible through Sequel.connect" do
    c = Sequel.connect 'ccc://localhost/db'
    c.should be_a_kind_of(CCC)
    c.opts[:host].should == 'localhost'
    c.opts[:database].should == 'db'
  end

  specify "should be accessible through Sequel.connect via a block" do
    x = nil
    y = nil
    z = nil

    p = proc do |c|
      c.should be_a_kind_of(CCC)
      c.opts[:host].should == 'localhost'
      c.opts[:database].should == 'db'
      z = y
      y = x
      x = c
    end
    Sequel::Database.connect('ccc://localhost/db', &p).should == nil
    CCC::DISCONNECTS.should == [x]

    Sequel.connect('ccc://localhost/db', &p).should == nil
    CCC::DISCONNECTS.should == [y, x]

    Sequel.send(:def_adapter_method, :ccc)
    Sequel.ccc('db', :host=>'localhost', &p).should == nil
    CCC::DISCONNECTS.should == [z, y, x]
  end

  deprec_specify "should be accessible through Sequel.open" do
    c = Sequel.open 'ccc://localhost/db'
    c.should be_a_kind_of(CCC)
    c.opts[:host].should == 'localhost'
    c.opts[:database].should == 'db'
  end

  specify "should be accessible through Sequel.<adapter>" do
    Sequel.send(:def_adapter_method, :ccc)

    # invalid parameters
    proc {Sequel.ccc('abc', 'def')}.should raise_error(Sequel::Error)

    c = Sequel.ccc('mydb')
    c.should be_a_kind_of(CCC)
    c.opts.should == {:adapter=>:ccc, :database => 'mydb'}

    c = Sequel.ccc('mydb', :host => 'localhost')
    c.should be_a_kind_of(CCC)
    c.opts.should == {:adapter=>:ccc, :database => 'mydb', :host => 'localhost'}

    c = Sequel.ccc
    c.should be_a_kind_of(CCC)
    c.opts.should == {:adapter=>:ccc}

    c = Sequel.ccc(:database => 'mydb', :host => 'localhost')
    c.should be_a_kind_of(CCC)
    c.opts.should == {:adapter=>:ccc, :database => 'mydb', :host => 'localhost'}
  end

  specify "should be accessible through Sequel.connect with options" do
    c = Sequel.connect(:adapter => :ccc, :database => 'mydb')
    c.should be_a_kind_of(CCC)
    c.opts.should == {:adapter => :ccc, :database => 'mydb'}
  end

  specify "should be accessible through Sequel.connect with URL parameters" do
    c = Sequel.connect 'ccc://localhost/db?host=/tmp&user=test'
    c.should be_a_kind_of(CCC)
    c.opts[:host].should == '/tmp'
    c.opts[:database].should == 'db'
    c.opts[:user].should == 'test'
  end

end

context "An unknown database scheme" do
  specify "should raise an error in Sequel::Database.connect" do
    proc {Sequel::Database.connect('ddd://localhost/db')}.should raise_error(Sequel::AdapterNotFound)
  end

  specify "should raise an error in Sequel.connect" do
    proc {Sequel.connect('ddd://localhost/db')}.should raise_error(Sequel::AdapterNotFound)
  end
end

context "A broken adapter (lib is there but the class is not)" do
  before do
    @fn = File.join(File.dirname(__FILE__), '../../lib/sequel/adapters/blah.rb')
    File.open(@fn,'a'){}
  end

  after do
    File.delete(@fn)
  end

  specify "should raise an error" do
    proc {Sequel.connect('blah://blow')}.should raise_error(Sequel::AdapterNotFound)
  end
end

context "A single threaded database" do
  after do
    Sequel::Database.single_threaded = false
  end

  specify "should use a SingleThreadedPool instead of a ConnectionPool" do
    db = Sequel::Database.new(:single_threaded => true)
    db.pool.should be_a_kind_of(Sequel::SingleThreadedPool)
  end

  specify "should be constructable using :single_threaded => true option" do
    db = Sequel::Database.new(:single_threaded => true)
    db.pool.should be_a_kind_of(Sequel::SingleThreadedPool)
  end

  specify "should be constructable using Database.single_threaded = true" do
    Sequel::Database.single_threaded = true
    db = Sequel::Database.new
    db.pool.should be_a_kind_of(Sequel::SingleThreadedPool)
  end

  specify "should be constructable using Sequel.single_threaded = true" do
    Sequel.single_threaded = true
    db = Sequel::Database.new
    db.pool.should be_a_kind_of(Sequel::SingleThreadedPool)
  end
end

context "A single threaded database" do
  before do
    conn = 1234567
    @db = Sequel::Database.new(:single_threaded => true) do
      conn += 1
    end
  end

  specify "should invoke connection_proc only once" do
    @db.pool.hold {|c| c.should == 1234568}
    @db.pool.hold {|c| c.should == 1234568}
  end

  specify "should convert an Exception into a RuntimeError" do
    db = Sequel::Database.new(:single_threaded => true) do
      raise Exception
    end

    proc {db.pool.hold {|c|}}.should raise_error(RuntimeError)
  end
end

context "A database" do
  before do
    Sequel::Database.single_threaded = false
  end

  after do
    Sequel::Database.single_threaded = false
  end

  deprec_specify "should have a multi_threaded? method" do
    db = Sequel::Database.new(:single_threaded => true)
    db.should_not be_multi_threaded

    db = Sequel::Database.new(:max_options => 1)
    db.should be_multi_threaded

    db = Sequel::Database.new
    db.should be_multi_threaded

    Sequel::Database.single_threaded = true

    db = Sequel::Database.new
    db.should_not be_multi_threaded

    db = Sequel::Database.new(:max_options => 4)
    db.should_not be_multi_threaded
  end

  specify "should have single_threaded? respond to true if in single threaded mode" do
    db = Sequel::Database.new(:single_threaded => true)
    db.should be_single_threaded

    db = Sequel::Database.new(:max_options => 1)
    db.should_not be_single_threaded

    db = Sequel::Database.new
    db.should_not be_single_threaded

    Sequel::Database.single_threaded = true

    db = Sequel::Database.new
    db.should be_single_threaded

    db = Sequel::Database.new(:max_options => 4)
    db.should be_single_threaded
  end

  deprec_specify "should have a logger method" do
    db = Sequel::Database.new
    s = "I'm a logger"
    db.logger = s
    db.logger.should == s
    db.logger = nil
    db.logger.should == nil
    db.loggers = []
    db.logger.should == nil
    t = "I'm also a logger"
    db.loggers = [s, t]
    db.logger.should == s
  end

  specify "should be able to set loggers via the logger= and loggers= methods" do
    db = Sequel::Database.new
    s = "I'm a logger"
    db.logger = s
    db.loggers.should == [s]
    db.logger = nil
    db.loggers.should == []

    db.loggers = [s]
    db.loggers.should == [s]
    db.loggers = []
    db.loggers.should == []

    t = "I'm also a logger"
    db.loggers = [s, t]
    db.loggers.should == [s,t]
  end
end

context "Database#dataset" do
  before do
    @db = Sequel::Database.new
  end

  deprec_specify "should delegate to Dataset#query if block is provided" do
    @d = @db.query {select :x; from :y}
    @d.should be_a_kind_of(Sequel::Dataset)
    @d.sql.should == "SELECT x FROM y"
  end
end

context "Database#fetch" do
  before do
    @db = Sequel::Database.new
    c = Class.new(Sequel::Dataset) do
      def fetch_rows(sql); yield({:sql => sql}); end
    end
    @db.meta_def(:dataset) {c.new(self)}
  end

  specify "should create a dataset and invoke its fetch_rows method with the given sql" do
    sql = nil
    @db.fetch('select * from xyz') {|r| sql = r[:sql]}
    sql.should == 'select * from xyz'
  end

  specify "should format the given sql with any additional arguments" do
    sql = nil
    @db.fetch('select * from xyz where x = ? and y = ?', 15, 'abc') {|r| sql = r[:sql]}
    sql.should == "select * from xyz where x = 15 and y = 'abc'"

    # and Aman Gupta's example
    @db.fetch('select name from table where name = ? or id in ?',
    'aman', [3,4,7]) {|r| sql = r[:sql]}
    sql.should == "select name from table where name = 'aman' or id in (3, 4, 7)"
  end

  specify "should return the dataset if no block is given" do
    @db.fetch('select * from xyz').should be_a_kind_of(Sequel::Dataset)

    @db.fetch('select a from b').map {|r| r[:sql]}.should == ['select a from b']

    @db.fetch('select c from d').inject([]) {|m, r| m << r; m}.should == \
      [{:sql => 'select c from d'}]
  end

  specify "should return a dataset that always uses the given sql for SELECTs" do
    ds = @db.fetch('select * from xyz')
    ds.select_sql.should == 'select * from xyz'
    ds.sql.should == 'select * from xyz'

    ds.filter!(:price.sql_number < 100)
    ds.select_sql.should == 'select * from xyz'
    ds.sql.should == 'select * from xyz'
  end
end

context "Database#[]" do
  before do
    @db = Sequel::Database.new
  end

  specify "should return a dataset when symbols are given" do
    ds = @db[:items]
    ds.class.should == Sequel::Dataset
    ds.opts[:from].should == [:items]
  end

  specify "should return an enumerator when a string is given" do
    c = Class.new(Sequel::Dataset) do
      def fetch_rows(sql); yield({:sql => sql}); end
    end
    @db.meta_def(:dataset) {c.new(self)}

    sql = nil
    @db['select * from xyz where x = ? and y = ?', 15, 'abc'].each {|r| sql = r[:sql]}
    sql.should == "select * from xyz where x = 15 and y = 'abc'"
  end
end

context "Database#create_view" do
  before do
    @db = DummyDatabase.new
  end

  specify "should construct proper SQL with raw SQL" do
    @db.create_view :test, "SELECT * FROM xyz"
    @db.sqls.should == ['CREATE VIEW test AS SELECT * FROM xyz']
    @db.sqls.clear
    @db.create_view :test.identifier, "SELECT * FROM xyz"
    @db.sqls.should == ['CREATE VIEW test AS SELECT * FROM xyz']
  end

  specify "should construct proper SQL with dataset" do
    @db.create_view :test, @db[:items].select(:a, :b).order(:c)
    @db.sqls.should == ['CREATE VIEW test AS SELECT a, b FROM items ORDER BY c']
    @db.sqls.clear
    @db.create_view :test.qualify(:sch), @db[:items].select(:a, :b).order(:c)
    @db.sqls.should == ['CREATE VIEW sch.test AS SELECT a, b FROM items ORDER BY c']
  end
end

context "Database#create_or_replace_view" do
  before do
    @db = DummyDatabase.new
  end

  specify "should construct proper SQL with raw SQL" do
    @db.create_or_replace_view :test, "SELECT * FROM xyz"
    @db.sqls.should == ['CREATE OR REPLACE VIEW test AS SELECT * FROM xyz']
    @db.sqls.clear
    @db.create_or_replace_view :sch__test, "SELECT * FROM xyz"
    @db.sqls.should == ['CREATE OR REPLACE VIEW sch.test AS SELECT * FROM xyz']
  end

  specify "should construct proper SQL with dataset" do
    @db.create_or_replace_view :test, @db[:items].select(:a, :b).order(:c)
    @db.sqls.should == ['CREATE OR REPLACE VIEW test AS SELECT a, b FROM items ORDER BY c']
    @db.sqls.clear
    @db.create_or_replace_view :test.identifier, @db[:items].select(:a, :b).order(:c)
    @db.sqls.should == ['CREATE OR REPLACE VIEW test AS SELECT a, b FROM items ORDER BY c']
  end
end

context "Database#drop_view" do
  before do
    @db = DummyDatabase.new
  end

  specify "should construct proper SQL" do
    @db.drop_view :test
    @db.drop_view :test.identifier
    @db.drop_view :sch__test
    @db.drop_view :test.qualify(:sch)
    @db.sqls.should == ['DROP VIEW test', 'DROP VIEW test', 'DROP VIEW sch.test', 'DROP VIEW sch.test']
  end
end

context "Database#alter_table_sql" do
  before do
    @db = DummyDatabase.new
  end

  specify "should raise error for an invalid op" do
    proc {@db.send(:alter_table_sql, :mau, :op => :blah)}.should raise_error(Sequel::Error)
  end
end

context "Database.connect" do
  EEE_YAML = "development:\r\n  adapter: eee\r\n  username: mau\r\n  password: tau\r\n  host: alfonso\r\n  database: mydb\r\n"

  before do
    class EEE < Sequel::Database
      set_adapter_scheme :eee
    end

    @fn = File.join(File.dirname(__FILE__), 'eee.yaml')
    File.open(@fn, 'wb') {|f| f << EEE_YAML}
  end

  after do
    File.delete(@fn)
  end

  specify "should accept hashes loaded from YAML files" do
    db = Sequel.connect(YAML.load_file(@fn)['development'])
    db.class.should == EEE
    db.opts[:database].should == 'mydb'
    db.opts[:user].should == 'mau'
    db.opts[:password].should == 'tau'
    db.opts[:host].should == 'alfonso'
  end
end

context "Database#inspect" do
  before do
    @db = DummyDatabase.new

    @db.meta_def(:uri) {'blah://blahblah/blah'}
  end

  specify "should include the class name and the connection url" do
    @db.inspect.should == '#<DummyDatabase: "blah://blahblah/blah">'
  end
end

context "Database#get" do
  before do
    @c = Class.new(DummyDatabase) do
      def dataset
        ds = super
        def ds.get(*args, &block)
          @db.execute select(*args, &block).sql
          args
        end
        ds
      end
    end

    @db = @c.new
  end

  specify "should use Dataset#get to get a single value" do
    @db.get(1).should == [1]
    @db.sqls.last.should == 'SELECT 1'

    @db.get(:version.sql_function)
    @db.sqls.last.should == 'SELECT version()'
  end

  specify "should accept a block" do
    @db.get{1}
    @db.sqls.last.should == 'SELECT 1'

    @db.get{version(1)}
    @db.sqls.last.should == 'SELECT version(1)'
  end
end

context "Database#call" do
  specify "should call the prepared statement with the given name" do
    db = MockDatabase.new
    db[:items].prepare(:select, :select_all)
    db.call(:select_all).should == [{:id => 1, :x => 1}]
    db[:items].filter(:n=>:$n).prepare(:select, :select_n)
    db.call(:select_n, :n=>1).should == [{:id => 1, :x => 1}]
    db.sqls.should == ['SELECT * FROM items', 'SELECT * FROM items WHERE (n = 1)']
  end
end

context "Database#server_opts" do
  specify "should return the general opts if no :servers option is used" do
    opts = {:host=>1, :database=>2}
    MockDatabase.new(opts).send(:server_opts, :server1).should == {:host=>1, :database=>2}
  end

  specify "should return the general opts if entry for the server is present in the :servers option" do
    opts = {:host=>1, :database=>2, :servers=>{}}
    MockDatabase.new(opts).send(:server_opts, :server1).should == {:host=>1, :database=>2}
  end

  specify "should return the general opts merged with the specific opts if given as a hash" do
    opts = {:host=>1, :database=>2, :servers=>{:server1=>{:host=>3}}}
    MockDatabase.new(opts).send(:server_opts, :server1).should == {:host=>3, :database=>2}
  end

  specify "should return the sgeneral opts merged with the specific opts if given as a proc" do
    opts = {:host=>1, :database=>2, :servers=>{:server1=>proc{|db| {:host=>4}}}}
    MockDatabase.new(opts).send(:server_opts, :server1).should == {:host=>4, :database=>2}
  end

  specify "should raise an error if the specific opts is not a proc or hash" do
    opts = {:host=>1, :database=>2, :servers=>{:server1=>2}}
    proc{MockDatabase.new(opts).send(:server_opts, :server1)}.should raise_error(Sequel::Error)
  end
end

context "Database#raise_error" do
  specify "should reraise if the exception class is not in opts[:classes]" do
    e = Class.new(StandardError)
    proc{MockDatabase.new.send(:raise_error, e.new(''), :classes=>[])}.should raise_error(e)
  end

  specify "should convert the exception to a DatabaseError if the exception class is not in opts[:classes]" do
    proc{MockDatabase.new.send(:raise_error, Interrupt.new(''), :classes=>[Interrupt])}.should raise_error(Sequel::DatabaseError)
  end

  specify "should convert the exception to a DatabaseError if opts[:classes] if not present" do
    proc{MockDatabase.new.send(:raise_error, Interrupt.new(''))}.should raise_error(Sequel::DatabaseError)
  end
end

context "Database#typecast_value" do
  before do
    @db = Sequel::Database.new
  end
  specify "should raise an InvalidValue when given an invalid value" do
    proc{@db.typecast_value(:integer, "13a")}.should raise_error(Sequel::InvalidValue)
    proc{@db.typecast_value(:float, "4.e2")}.should raise_error(Sequel::InvalidValue)
    proc{@db.typecast_value(:decimal, :invalid_value)}.should raise_error(Sequel::InvalidValue)
    proc{@db.typecast_value(:date, Object.new)}.should raise_error(Sequel::InvalidValue)
    proc{@db.typecast_value(:date, 'a')}.should raise_error(Sequel::InvalidValue)
    proc{@db.typecast_value(:time, Date.new)}.should raise_error(Sequel::InvalidValue)
    proc{@db.typecast_value(:datetime, 4)}.should raise_error(Sequel::InvalidValue)
  end
end


text:
<?php

namespace Framework\Headers;

use Framework\MVC\View;

/**
 * Download a file.
 * @author Jordi Jolink <mail@jordijolink.nl>
 * @since  18-3-2015
 */
class Download
{
    /**
     * Redirect to a given URL.
     * @param string $filename
     * @param View $view
     */
    public function __construct($filename, View $view)
    {
        $quoted = sprintf('"%s"', addcslashes(basename($filename), '"\\'));

        header('Content-Description: File Transfer');
        header('Content-Disposition: attachment; filename=' . $quoted);
        header('Content-Transfer-Encoding: binary');
        header('Connection: Keep-Alive');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');

        $contents = $view->render();
        $size = strlen($contents);
        header('Content-Length: ' . $size);
        echo $contents;
    }
}


text:
STR_INFO_TITLE

STR_HELP_MENU_HDR

STR_HELP_SIDEMENU

STR_HELP_VIEWMODE

STR_INFO_VIEW_VERT

STR_INFO_VIEW_HORIZ

STR_HELP_MTG_STATES_HDR

{{s.stringId}}

STR_HELP_MTG_STATES_BODY

STR_INFO_MTG_BAD_STATUS

STR_HELP_TOPIC_STATES_HDR

                    {{t.stringId}}

                    STR_MTG_STATUS_PUBLISHED_PROPOSALS

                    STR_INFO_CONFIDENTIAL

STR_HELP_BELL

STR_INFO_MTG_INACTIVE

STR_INFO_TOPIC_STATUS_CHANGE_DISABLED

        <button class="btn btn-success db-btn-dyna" type="button" ng-click="closeThisDialog()">
            STR_CLOSE
        </button>


text:
package ed.mslib;

public class MzInt {

	public MzInt(double mz, float intensity){
		this.mz = mz;
		this.intensity = intensity;
	}

	private double mz;
	private float intensity;

	public double getmz(){return mz;}
	public float getint(){return intensity;}

	public void setmz(double m){mz = m;}
	public void setint(float i){intensity = i;}
}


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>particle</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

Module particle

Classes

    Color
    ExceptionNoEmptyParticle
    ParticleSystem

Functions

    PointerToNumpy
    point_sprites_available
    rand

Variables

    __package__
    forced_point_sprites


text:
package com.github.jmnarloch.spring.cloud.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.util.Assert;

/**
 * The base request interceptor.
 *
 * @author Jakub Narloch
 */
public abstract class BaseRequestInterceptor implements RequestInterceptor {

    /**
     * The encoding properties.
     */
    private final FeignClientEncodingProperties properties;

    /**
     * Creates new instance of {@link BaseRequestInterceptor}.
     *
     * @param properties the encoding properties
     */
    protected BaseRequestInterceptor(FeignClientEncodingProperties properties) {
        Assert.notNull(properties, "Properties can not be null");
        this.properties = properties;
    }

    /**
     * Retrieves the properties.
     *
     * @return the properties
     */
    protected FeignClientEncodingProperties getProperties() {
        return properties;
    }

    /**
     * Adds the header if it wasn't yet specified.
     *
     * @param requestTemplate the request
     * @param name            the header name
     * @param values          the header values
     */
    protected void addHeader(RequestTemplate requestTemplate, String name, String... values) {

        if (!requestTemplate.headers().containsKey(name)) {
            requestTemplate.header(name, values);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>

<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:id="@+id/coordinator_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <include layout="@layout/app_bar_layout" />

        <FrameLayout
            android:id="@+id/frame_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/navigation_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/navigation_view_header"
        app:itemBackground="@drawable/selector_empty"
        app:menu="@menu/drawer" />

</androidx.drawerlayout.widget.DrawerLayout>


text:
httpsocket::httpsocket(QObject *parent) :
    QObject(parent)
{
    response = "";
    useProxy = false;
}

void httpsocket::getUrl(QString url)
{
    if(this->useProxy==true){
        QNetworkProxy proxy;
        proxy.setType(QNetworkProxy::HttpProxy);
        proxy.setHostName(this->proxyAddress);
        proxy.setPort(this->proxyPort);
        //proxy.setUser("username");
        //proxy.setPassword("password");
        QNetworkProxy::setApplicationProxy(proxy);
    }

    qDebug()<< "Connecting...";
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(replyFinished(QNetworkReply*)));

    manager->get(QNetworkRequest(QUrl(url)));
}

void httpsocket::replyFinished(QNetworkReply *reply)
{
    if(reply->error()==QNetworkReply::NoError){
        qDebug() << "Response";
        if(reply->isOpen()){
            QString response = reply->readAll();
            this->response = response;//the contents of response = response.
            reply->close();
            //qDebug()<<"Finished With Socket Data...";
        }
    }else{
        qDebug()<<"Error Occured";
        this->response = "Error";
        this->error = reply->errorString();
    }
    emit finished();
}


text:
<!DOCTYPE html>

		<title>RPo Dynamics</title>

		<meta charset="utf-8">
    	<meta http-equiv="X-UA-Compatible" content="IE=edge">
    	<meta name="viewport" content="width=device-width, initial-scale=1">
    	<meta name="description" content="RNA polymerase open complex dynamics.">
    	<meta name="author" content="Athan Reines">

		<link rel="stylesheet" type="text/css" href="/css/reset.css">
		<link rel='stylesheet' type='text/css' href="/css/fonts.css">
		<link rel="stylesheet" type="text/css" href="/css/bootstrap/bootstrap.min.css">
		<link rel="stylesheet" type="text/css" href="/css/bootstrap/bootstrap-dashboard.css">
		<link rel="stylesheet" type="text/css" href="/css/styles.css">

					<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
						Toggle navigation

					</button>
					RPo Dynamics

Conditions

									ID
									<% var header; %>
									<% for ( var i = 0; i < headers.length; i++ ) { %>
									<% header = headers[ i ]; %>
									<%= header %>
									<% } %>

								<% var row, datum; %>
								<% for ( var j = 0; j < rows.length; j++ ) { %>
								<% row = rows[ j ]; %>
								<tr class="condition" data-id="<%= row[ 0 ] %>" >
									<% for ( var k = 0; k < row.length; k++ ) { %>
									<% datum = row[ k ]; %>
									<%= datum %>
									<% } %>

								<% } %>


text:
class Exhibit::Presenter
  # You can extend Exhibit::Presenter by changing this file.
  # Remember to restart your server after changing it.
end


text:
from PyQt5.QtWidgets import QSizePolicy
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from .content import Content

class LearningCurveBase(Content):
    def __init__(self, parent=None, title='', params=None):
        super().__init__(parent, title, params)

    def plot_curve(self, algo_results):
        ylim = self.__get_ylim(algo_results)
        for name, val in algo_results.items():
            self.set_paragraph(h2=name)

            x = val['learning_curve']['x']
            y_train = val['learning_curve']['y_train']
            y_cv = val['learning_curve']['y_cv']
            fig = PlotLearningCurve(x, y_train, y_cv, ylim, name, self.inner)
            self.vbox.addWidget(fig)

    def __get_ylim(self, algorithms):
        ymin = float('Inf')
        ymax = -float('Inf')

        for name, val in algorithms.items():
            ymin = min([ymin, min(val['learning_curve']['y_cv'])])
            ymax = max([ymax, max(val['learning_curve']['y_train'])])
        margin = 0.05 * (ymax - ymin)

        return (ymin - margin, ymax + margin)

class PlotLearningCurve(FigureCanvas):
    def __init__(self, x, y_train, y_cv, ylim, title, parent=None,
                 width=5, height=4, dpi=100):
        self.fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = self.fig.add_subplot(111)

        FigureCanvas.__init__(self, self.fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self,
                                   QSizePolicy.Fixed, QSizePolicy.Fixed)
        FigureCanvas.updateGeometry(self)
        self.plot(x, y_train, y_cv, ylim, title)

    def plot(self, x, y_train, y_cv, ylim, title):
        self.axes.set_title(title)
        self.axes.set_xlabel('Training examples')
        self.axes.set_ylabel('Score')
        self.axes.grid(True)

        self.axes.plot(x, y_train, 'o-', color='dodgerblue', label='Training score')
        self.axes.plot(x, y_cv, 'o-', color='darkorange',
                       label='Cross-validation score')
        self.axes.set_ylim(ylim)
        self.axes.legend(loc="lower right")

        self.draw()


text:
    <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
    <META NAME="Generator" CONTENT="Microsoft Word 97">
    <TITLE>PassThrough</TITLE>
    <META NAME="Template" CONTENT="C:\PROGRAM FILES\MICROSOFT OFFICE\OFFICE\html.dot">

PassThrough

    <LARGE>Author : Ian Taylor

    <LARGE>Version : 2.0

        Input Types : TrianaType

        Output Types : TrianaType

        Date : 27 Feb 2001</LARGE>

Contents

Description of PassThrough

Using PassThrough

Description of PassThrough

The unit called PassThrough ......

Using PassThrough

PassThrough's parameter window (double-click on the unit while holding down the Control key) is used to ....


text:
package spyglass

import (
	"bytes"
	"compress/gzip"
	"context"
	"fmt"
	"io"
	"testing"

	pkgio "k8s.io/test-infra/prow/io"
)

type ByteReadCloser struct {
	io.Reader
	incompleteRead bool
}

func (rc *ByteReadCloser) Close() error {
	return nil
}

func (rc *ByteReadCloser) Read(p []byte) (int, error) {
	if rc.incompleteRead {
		p = p[:len(p)/2]
		rc.incompleteRead = false
	}
	read, err := rc.Reader.Read(p)
	if err != nil {
		return 0, err
	}
	if bytes.Equal(p[:read], []byte("deeper unreadable contents")) {
		return 0, fmt.Errorf("it's just turtes all the way down")
	}
	return read, nil
}

type fakeArtifactHandle struct {
	oAttrs         pkgio.Attributes
	contents       []byte
	incompleteRead bool
}

func (h *fakeArtifactHandle) Attrs(ctx context.Context) (pkgio.Attributes, error) {
	if bytes.Equal(h.contents, []byte("no attrs")) {
		return pkgio.Attributes{}, fmt.Errorf("error getting attrs")
	}
	return h.oAttrs, nil
}

func (h *fakeArtifactHandle) NewRangeReader(ctx context.Context, offset, length int64) (io.ReadCloser, error) {
	if bytes.Equal(h.contents, []byte("unreadable contents")) {
		return nil, fmt.Errorf("cannot read unreadable contents")
	}
	lenContents := int64(len(h.contents))
	var err error
	var toRead int64
	if length < 0 {
		toRead = lenContents - offset
		err = io.EOF
	} else {
		toRead = length
		if offset+length > lenContents {
			toRead = lenContents - offset
			err = io.EOF
		}
	}
	return &ByteReadCloser{bytes.NewReader(h.contents[offset : offset+toRead]), h.incompleteRead}, err
}

func (h *fakeArtifactHandle) NewReader(ctx context.Context) (io.ReadCloser, error) {
	var buf bytes.Buffer
	zw := gzip.NewWriter(&buf)
	_, err := zw.Write([]byte("unreadable contents"))
	if err != nil {
		return nil, fmt.Errorf("Failed to gzip log text, err: %v", err)
	}
	if err := zw.Close(); err != nil {
		return nil, fmt.Errorf("Failed to close gzip writer, err: %v", err)
	}
	if bytes.Equal(h.contents, buf.Bytes()) {
		return nil, fmt.Errorf("cannot read unreadable contents, even if they're gzipped")
	}
	if bytes.Equal(h.contents, []byte("unreadable contents")) {
		return nil, fmt.Errorf("cannot read unreadable contents")
	}
	return &ByteReadCloser{bytes.NewReader(h.contents), false}, nil
}

// Tests reading the tail n bytes of data from an artifact
func TestReadTail(t *testing.T) {
	var buf bytes.Buffer
	zw := gzip.NewWriter(&buf)
	_, err := zw.Write([]byte("Oh wow\nlogs\nthis is\ncrazy"))
	if err != nil {
		t.Fatalf("Failed to gzip log text, err: %v", err)
	}
	if err := zw.Close(); err != nil {
		t.Fatalf("Failed to close gzip writer, err: %v", err)
	}
	gzippedLog := buf.Bytes()
	testCases := []struct {
		name      string
		n         int64
		contents  []byte
		encoding  string
		expected  []byte
		expectErr bool
	}{
		{
			name:      "ReadTail example build log",
			n:         4,
			contents:  []byte("Oh wow\nlogs\nthis is\ncrazy"),
			expected:  []byte("razy"),
			expectErr: false,
		},
		{
			name:      "ReadTail build log, gzipped",
			n:         23,
			contents:  gzippedLog,
			encoding:  "gzip",
			expectErr: true,
		},
		{
			name:      "ReadTail build log, claimed gzipped but not actually gzipped",
			n:         2333,
			contents:  []byte("Oh wow\nlogs\nthis is\ncrazy"),
			encoding:  "gzip",
			expectErr: true,
		},
		{
			name:      "ReadTail N>size of build log",
			n:         2222,
			contents:  []byte("Oh wow\nlogs\nthis is\ncrazy"),
			expected:  []byte("Oh wow\nlogs\nthis is\ncrazy"),
			expectErr: false,
		},
	}
	for _, tc := range testCases {
		artifact := NewGCSArtifact(context.Background(), &fakeArtifactHandle{
			contents: tc.contents,
			oAttrs: pkgio.Attributes{
				Size:            int64(len(tc.contents)),
				ContentEncoding: tc.encoding,
			},
		}, "", "build-log.txt", 500e6)
		actualBytes, err := artifact.ReadTail(tc.n)
		if err != nil && !tc.expectErr {
			t.Fatalf("Test %s failed with err: %v", tc.name, err)
		}
		if err == nil && tc.expectErr {
			t.Errorf("Test %s did not produce error when expected", tc.name)
		}
		if !bytes.Equal(actualBytes, tc.expected) {
			t.Errorf("Test %s failed.\nExpected: %s\nActual: %s", tc.name, tc.expected, actualBytes)
		}
	}
}

// Tests reading at most n bytes of data from files in GCS
func TestReadAtMost(t *testing.T) {
	var buf bytes.Buffer
	zw := gzip.NewWriter(&buf)
	_, err := zw.Write([]byte("Oh wow\nlogs\nthis is\ncrazy"))
	if err != nil {
		t.Fatalf("Failed to gzip log text, err: %v", err)
	}
	if err := zw.Close(); err != nil {
		t.Fatalf("Failed to close gzip writer, err: %v", err)
	}
	testCases := []struct {
		name      string
		n         int64
		contents  []byte
		encoding  string
		expected  []byte
		expectErr bool
		expectEOF bool
	}{
		{
			name:      "ReadAtMost example build log",
			n:         4,
			contents:  []byte("Oh wow\nlogs\nthis is\ncrazy"),
			expected:  []byte("Oh w"),
			expectErr: false,
		},
		{
			name:      "ReadAtMost build log, transparently gzipped",
			n:         8,
			contents:  []byte("Oh wow\nlogs\nthis is\ncrazy"),
			expected:  []byte("Oh wow\nl"),
			encoding:  "gzip",
			expectErr: false,
		},
		{
			name:      "ReadAtMost unreadable contents",
			n:         2,
			contents:  []byte("unreadable contents"),
			expectErr: true,
		},
		{
			name:      "ReadAtMost unreadable contents",
			n:         45,
			contents:  []byte("deeper unreadable contents"),
			expectErr: true,
		},
		{
			name:      "ReadAtMost N>size of build log",
			n:         2222,
			contents:  []byte("Oh wow\nlogs\nthis is\ncrazy"),
			expected:  []byte("Oh wow\nlogs\nthis is\ncrazy"),
			expectErr: true,
			expectEOF: true,
		},
	}
	for _, tc := range testCases {
		artifact := NewGCSArtifact(context.Background(), &fakeArtifactHandle{
			contents: tc.contents,
			oAttrs: pkgio.Attributes{
				Size:            int64(len(tc.contents)),
				ContentEncoding: tc.encoding,
			},
		}, "", "build-log.txt", 500e6)
		actualBytes, err := artifact.ReadAtMost(tc.n)
		if err != nil && !tc.expectErr {
			if tc.expectEOF && err != io.EOF {
				t.Fatalf("Test %s failed with err: %v, expected EOF", tc.name, err)
			}
			t.Fatalf("Test %s failed with err: %v", tc.name, err)
		}
		if err != nil && tc.expectEOF && err != io.EOF {
			t.Fatalf("Test %s failed with err: %v, expected EOF", tc.name, err)
		}
		if err == nil && tc.expectErr {
			t.Errorf("Test %s did not produce error when expected", tc.name)
		}
		if !bytes.Equal(actualBytes, tc.expected) {
			t.Errorf("Test %s failed.\nExpected: %s\nActual: %s", tc.name, tc.expected, actualBytes)
		}
	}
}

// Tests reading at offset from files in GCS
func TestReadAt(t *testing.T) {
	var buf bytes.Buffer
	zw := gzip.NewWriter(&buf)
	_, err := zw.Write([]byte("Oh wow\nlogs\nthis is\ncrazy"))
	if err != nil {
		t.Fatalf("Failed to gzip log text, err: %v", err)
	}
	if err := zw.Close(); err != nil {
		t.Fatalf("Failed to close gzip writer, err: %v", err)
	}
	gzippedLog := buf.Bytes()
	testCases := []struct {
		name           string
		n              int64
		offset         int64
		contents       []byte
		encoding       string
		expected       []byte
		expectErr      bool
		incompleteRead bool
	}{
		{
			name:      "ReadAt example build log",
			n:         4,
			offset:    6,
			contents:  []byte("Oh wow\nlogs\nthis is\ncrazy"),
			expected:  []byte("\nlog"),
			expectErr: false,
		},
		{
			name:      "ReadAt offset past file size",
			n:         4,
			offset:    400,
			contents:  []byte("Oh wow\nlogs\nthis is\ncrazy"),
			expectErr: true,
		},
		{
			name:           "ReadAt needs multiple internal Reads",
			n:              4,
			offset:         6,
			contents:       []byte("Oh wow\nlogs\nthis is\ncrazy"),
			expected:       []byte("\nlog"),
			incompleteRead: true,
		},
		{
			name:      "ReadAt build log, gzipped",
			n:         23,
			contents:  gzippedLog,
			encoding:  "gzip",
			expectErr: true,
		},
		{
			name:      "ReadAt, claimed gzipped but not actually gzipped",
			n:         2333,
			contents:  []byte("Oh wow\nlogs\nthis is\ncrazy"),
			encoding:  "gzip",
			expectErr: true,
		},
		{
			name:      "ReadAt offset negative",
			offset:    -3,
			n:         32,
			contents:  []byte("Oh wow\nlogs\nthis is\ncrazy"),
			expectErr: true,
		},
	}
	for _, tc := range testCases {
		artifact := NewGCSArtifact(context.Background(), &fakeArtifactHandle{
			contents: tc.contents,
			oAttrs: pkgio.Attributes{
				Size:            int64(len(tc.contents)),
				ContentEncoding: tc.encoding,
			},
			incompleteRead: tc.incompleteRead,
		}, "", "build-log.txt", 500e6)
		p := make([]byte, tc.n)
		bytesRead, err := artifact.ReadAt(p, tc.offset)
		if err != nil && !tc.expectErr {
			t.Fatalf("Test %s failed with err: %v", tc.name, err)
		}
		if err == nil && tc.expectErr {
			t.Errorf("Test %s did not produce error when expected", tc.name)
		}
		readBytes := p[:bytesRead]
		if !bytes.Equal(readBytes, tc.expected) {
			t.Errorf("Test %s failed.\nExpected: %s\nActual: %s", tc.name, tc.expected, readBytes)
		}
	}

}

// Tests reading all data from files in GCS
func TestReadAll(t *testing.T) {
	testCases := []struct {
		name      string
		sizeLimit int64
		contents  []byte
		expectErr bool
		expected  []byte
	}{
		{
			name:      "ReadAll example build log",
			contents:  []byte("Oh wow\nlogs\nthis is\ncrazy"),
			sizeLimit: 500e6,
			expected:  []byte("Oh wow\nlogs\nthis is\ncrazy"),
		},
		{
			name:      "ReadAll example too large build log",
			sizeLimit: 20,
			contents:  []byte("Oh wow\nlogs\nthis is\ncrazy"),
			expectErr: true,
			expected:  nil,
		},
		{
			name:      "ReadAll unable to get reader",
			sizeLimit: 500e6,
			contents:  []byte("unreadable contents"),
			expectErr: true,
			expected:  nil,
		},
		{
			name:      "ReadAll unable to read contents",
			sizeLimit: 500e6,
			contents:  []byte("deeper unreadable contents"),
			expectErr: true,
			expected:  nil,
		},
	}
	for _, tc := range testCases {
		artifact := NewGCSArtifact(context.Background(), &fakeArtifactHandle{
			contents: tc.contents,
			oAttrs: pkgio.Attributes{
				Size: int64(len(tc.contents)),
			},
		}, "", "build-log.txt", tc.sizeLimit)

		actualBytes, err := artifact.ReadAll()
		if err != nil && !tc.expectErr {
			t.Fatalf("Test %s failed with err: %v", tc.name, err)
		}
		if err == nil && tc.expectErr {
			t.Errorf("Test %s did not produce error when expected", tc.name)
		}
		if !bytes.Equal(actualBytes, tc.expected) {
			t.Errorf("Test %s failed.\nExpected: %s\nActual: %s", tc.name, tc.expected, actualBytes)
		}
	}
}

func TestSize_GCS(t *testing.T) {
	fakeGCSClient := fakeGCSServer.Client()
	fakeOpener := pkgio.NewGCSOpener(fakeGCSClient)
	startedContent := []byte("hi jason, im started")
	testCases := []struct {
		name      string
		handle    artifactHandle
		expected  int64
		expectErr string
	}{
		{
			name: "Test size simple",
			handle: &fakeArtifactHandle{
				contents: startedContent,
				oAttrs: pkgio.Attributes{
					Size: int64(len(startedContent)),
				},
			},
			expected: int64(len(startedContent)),
		},
		{
			name: "Test size from attrs error",
			handle: &fakeArtifactHandle{
				contents: []byte("no attrs"),
				oAttrs: pkgio.Attributes{
					Size: 8,
				},
			},
			expectErr: "error getting gcs attributes for artifact: error getting attrs",
		},
		{
			name: "Size of nonexistentArtifact",
			handle: &gcsArtifactHandle{
				Opener: fakeOpener,
				Name:   "gs://test-bucket/logs/example-ci-run/404/started.json",
			},
			expectErr: "error getting gcs attributes for artifact: storage: object doesn't exist",
		},
	}
	for _, tc := range testCases {
		artifact := NewGCSArtifact(context.Background(), tc.handle, "", "started.json", 500e6)
		actual, err := artifact.Size()
		var actualErr string
		if err != nil {
			actualErr = err.Error()
		}
		if actualErr != tc.expectErr {
			t.Fatalf("%s failed getting size for artifact %s, error = %v, expectErr %v", tc.name, artifact.JobPath(), actualErr, tc.expectErr)
		}
		if tc.expected != actual {
			t.Errorf("Test %s failed.\nExpected:\n%d\nActual:\n%d", tc.name, tc.expected, actual)
		}
	}
}


text:
<?php

namespace Psy\CodeCleaner;

use PhpParser\Node\Expr;
use PhpParser\Node\Stmt\Return_ as ReturnStmt;

/**
 * Add an implicit "return" to the last statement, provided it can be returned.
 */
class ImplicitReturnPass extends CodeCleanerPass
{
    /**
     * @param array $nodes
     */
    public function beforeTraverse(array $nodes)
    {
        $last = end($nodes);

        if ($last instanceof Expr) {
            $nodes[count($nodes) - 1] = new ReturnStmt($last, array(
                'startLine' => $last->getLine(),
                'endLine'   => $last->getLine(),
            ));
        }

        return $nodes;
    }
}


text:
package com.matthewtamlin.android_utilities.library.helpers;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
import static android.net.ConnectivityManager.TYPE_DUMMY;
import static android.net.ConnectivityManager.TYPE_ETHERNET;
import static android.net.ConnectivityManager.TYPE_MOBILE;
import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
import static android.net.ConnectivityManager.TYPE_VPN;
import static android.net.ConnectivityManager.TYPE_WIFI;
import static com.matthewtamlin.android_utilities.library.helpers.InternetHelper.ConnectionType.BLUETOOTH;
import static com.matthewtamlin.android_utilities.library.helpers.InternetHelper.ConnectionType.ETHERNET;
import static com.matthewtamlin.android_utilities.library.helpers.InternetHelper.ConnectionType.MOBILE;
import static com.matthewtamlin.android_utilities.library.helpers.InternetHelper.ConnectionType.MOBILE_DUN;
import static com.matthewtamlin.android_utilities.library.helpers.InternetHelper.ConnectionType.MOCK;
import static com.matthewtamlin.android_utilities.library.helpers.InternetHelper.ConnectionType.UNKNOWN;
import static com.matthewtamlin.android_utilities.library.helpers.InternetHelper.ConnectionType.VPN;
import static com.matthewtamlin.android_utilities.library.helpers.InternetHelper.ConnectionType.WIFI;
import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull;

/**
 * Provides information about the current internet connection.
 */
public class InternetHelper {
	/**
	 * Checks if an internet connection is currently available and returns the type.
	 *
	 * @param context
	 * 		the querying context, not null
	 *
	 * @return the type of the current internet connection, null if there is none
	 */
	public static ConnectionType getInternetConnectionType(final Context context) {
		checkNotNull(context, "context cannot be null.");

		final NetworkInfo info = getNetworkInfo(context);

		if (info == null) {
			return null;
		} else {
			switch (info.getType()) {
				case TYPE_MOBILE:
					return MOBILE;
				case TYPE_WIFI:
					return WIFI;
				case TYPE_BLUETOOTH:
					return BLUETOOTH;
				case TYPE_DUMMY:
					return MOCK;
				case TYPE_ETHERNET:
					return ETHERNET;
				case TYPE_MOBILE_DUN:
					return MOBILE_DUN;
				case TYPE_VPN:
					return VPN;

				default:
					return UNKNOWN;
			}
		}
	}

	/**
	 * @param context
	 * 		a context, not null
	 *
	 * @return the NetworkInfo for the supplied context
	 */
	private static NetworkInfo getNetworkInfo(final Context context) {
		final ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		return connectivityManager.getActiveNetworkInfo();
	}

	/**
	 * The different internet connection types available to an Android device.
	 */
	public enum ConnectionType {
		/**
		 * The device is routing all traffic through a WIFI network.
		 */
		WIFI,

		/**
		 * The device is routing all traffic through the mobile data connection.
		 */
		MOBILE,

		/**
		 * The device is routing all traffic through a bluetooth connection.
		 */
		BLUETOOTH,

		/**
		 * The device is routing all traffic through an ethernet connection.
		 */
		ETHERNET,

		/**
		 * The internet connection is being mocked at a low level. <b>Not for use in production.</b>
		 */
		MOCK,

		/**
		 * The device is routing all traffic through a dial up mobile data connection.
		 */
		MOBILE_DUN,

		/**
		 * The device is routing all traffic through a VPN. The actual nature of the connection is
		 * obscured.
		 */
		VPN,

		/**
		 * The device has an active internet connection, but its nature is unknown.
		 */
		UNKNOWN,
	}
}


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace AppBundle\Controller;

/**
 * Description of LuckyController
 *
 * @author tankosic.branislav
 */

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class LuckyController extends Controller
{
  //put your code here
  /**
     * @Route("/lucky/number", name="lucky_number")
     *
     */
    public function numberAction()
    {
        $number = mt_rand(0, 100);

//       return new Response(
//            'Lucky number: '.$number.''
//        );

        return $this->render('lucky/number.html.twig', array(
            'number' => $number,
        ));
    }
}


text:
bool Filedata::valid(void) const
{
  // A valid fuzzy hash has the form
  // [blocksize]:[sig1]:[sig2]
  // with no filename at the end

  // First find the block size
  const char * sig = m_signature.c_str();
  unsigned int block_size;
  if (-1 == sscanf(sig, "%u:", &block_size))
    return false;

  // Move past the blocksize
  sig = strchr(sig,':');
  if (!sig)
    return false;

  // Move past the first colon and Look for the second colon
  ++sig;
  sig = strchr(sig,':');
  if (!sig)
    return false;

  // Finally, a valid signature does *not* have a filename at the end of it
  sig = strchr(sig,',');
  if (sig)
    return false;

  return true;
}

void Filedata::clear_cluster(void)
{
  if (NULL == m_cluster)
    return;

  // We don't want to call the destructors on the individual elements
  // so we have to clear the set first.
  m_cluster->clear();
  m_cluster = NULL;
}

Filedata::Filedata(const TCHAR *fn, const char * sig, const char * match_file)
{
  m_signature = std::string(sig);
  if (not valid())
    throw std::bad_alloc();

  m_filename = _tcsdup(fn);
  m_cluster  = NULL;

  if (NULL == match_file)
    m_has_match_file = false;
  else
  {
    m_has_match_file = true;
    m_match_file = std::string(match_file);
  }
}

Filedata::Filedata(const std::string sig, const char * match_file)
{
  // Set the easy stuff first
  m_cluster = NULL;

  if (NULL == match_file)
    m_has_match_file = false;
  else
  {
    m_has_match_file = true;
    m_match_file = std::string(match_file);
  }

  // If we don't have a filename included with the sig, that's ok,
  // but we should find out now.
  // If there is a filename, it should be immediately after the
  // first comma and enclosed in quotation marks.
  size_t start, stop;
  start = sig.find_first_of(",\"");
  if (std::string::npos == start)
  {
    // There is no filename. Ok. We still have a valid Filedata.
    m_filename  = _tcsdup(_TEXT("[NO FILENAME]"));
    m_signature = std::string(sig);

    // We still have to check the validity of the signature
    if (not valid())
      throw std::bad_alloc();

    return;
  }

  // There is a filename. Ok.
  // Advance past the comma and quotation mark.
  start += 2;

  // Look for the second quotation mark, which should be at the end
  // of the string.
  stop = sig.find_last_of('"');
  if (stop != sig.size() - 1)
    throw std::bad_alloc();

  // Strip off the final quotation mark and record the filename
  std::string tmp = sig.substr(start,(stop - start));

  // Strip off the filename from the signature. Remember that "start"
  // now points to two characters ahead of the comma
  m_signature = sig.substr(0,start-2);

  // Unescape any quotation marks in the filename
  while (tmp.find(std::string("\\\"")) != std::string::npos)
    tmp.replace(tmp.find(std::string("\\\"")),2,std::string("\""));

#ifndef _WIN32
  m_filename = strdup(tmp.c_str());
#else
  char * tmp2 = strdup(tmp.c_str());

  // On Win32 we have to do a kludgy cast from ordinary char
  // values to the TCHAR values we use internally. Because we may have
  // reset the string length, get it again.
  // The extra +1 is for the terminating newline
  size_t i, sz = strlen(tmp2);
  m_filename = (TCHAR *)malloc(sizeof(TCHAR) * (sz + 1));
  if (NULL == m_filename)
    throw std::bad_alloc();

  for (i = 0 ; i < sz ; i++)
    m_filename[i] = (TCHAR)(tmp2[i]);
  m_filename[i] = 0;
#endif
}

std::ostream& operator<<(std::ostream& o, const Filedata& f)
{
  return o << f.get_signature() << "," << f.get_filename() << ",";
}

bool operator==(const Filedata& a, const Filedata& b)
{
  if (a.get_signature() != b.get_signature())
    return false;
  if (a.has_match_file() and not b.has_match_file())
    return false;
  if (not a.has_match_file() and b.has_match_file())
    return false;
  if (a.has_match_file() and b.has_match_file())
  {
    if (a.get_match_file() != b.get_match_file())
      return false;
  }

  return true;
}


text:
import { CanActivate, Component, ChangeDetectionStrategy } from "../core";
import { TagActionCreator } from "./tag.actions";

@Component({
    templateUrl: "wwwroot/tag/tag.component.html",
	styleUrls: ["wwwroot/tag/tag.component.css"],
    selector: "tag",
    viewProviders: ["tagActionCreator"]
})
export class TagComponent {
    constructor(private tagActionCreator: TagActionCreator) { }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bot. Gaz. 69: 3 (1920)

#### Original name
Cantharosphaeria chilensis Thaxt.

### Remarks
null


text:
Gallery.register(
  'annotations-gviz',
  {
    name: 'Annotation Gviz (broken)',
    title: 'Comparison of Gviz and Dygraphs annotated timelines',
    setup : function(parent) {
      parent.innerHTML =
          "
Google AnnotatedTimeline:
" +
          "

" +
          "
Dygraph.GVizChart:
" +
          "

";
    },
    run: function() {
      drawChart = function() {
        var data = new google.visualization.DataTable();
        data.addColumn('date', 'Date');
        data.addColumn('number', 'Sold Pencils');
        data.addColumn('string', 'title1');
        data.addColumn('string', 'text1');
        data.addColumn('number', 'Sold Pens');
        data.addColumn('string', 'title2');
        data.addColumn('string', 'text2');
        data.addRows([
          [new Date(2008, 1 ,1), 30000, undefined, undefined, 40645, undefined, undefined],
          [new Date(2008, 1 ,2), 14045, undefined, undefined, 20374, undefined, undefined],
          [new Date(2008, 1 ,3), 55022, undefined, undefined, 50766, undefined, undefined],
          [new Date(2008, 1 ,4), 75284, undefined, undefined, 14334, 'Out of Stock','Ran out of stock on pens at 4pm'],
          [new Date(2008, 1 ,5), 41476, 'Bought Pens','Bought 200k pens', 66467, undefined, undefined],
          [new Date(2008, 1 ,6), 33322, undefined, undefined, 39463, undefined, undefined]
        ]);

        var chart = new google.visualization.AnnotatedTimeLine(document.getElementById('gviz_div'));
        chart.draw(data, {displayAnnotations: true});

      };
      google.setOnLoadCallback(drawChart);
      var f = function() { alert("!"); };
      google.setOnLoadCallback(f);
      var g = new Dygraph.GVizChart(document.getElementById("dg_div"));
      g.draw(data, {displayAnnotations: true, labelsKMB: true});
    }
  });


text:
class CefContentUtilityClient : public content::ContentUtilityClient {
 public:
  virtual ~CefContentUtilityClient();
  virtual void UtilityThreadStarted() OVERRIDE;
  virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
};

#endif  // CEF_LIBCEF_UTILITY_CONTENT_UTILITY_CLIENT_H_


text:
package org.apache.shardingsphere.example.cluster.mode.raw.jdbc.config.local;

import org.apache.shardingsphere.driver.api.ShardingSphereDataSourceFactory;
import org.apache.shardingsphere.example.config.ExampleConfiguration;
import org.apache.shardingsphere.example.core.api.DataSourceUtil;
import org.apache.shardingsphere.infra.config.algorithm.ShardingSphereAlgorithmConfiguration;
import org.apache.shardingsphere.infra.config.mode.ModeConfiguration;
import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration;
import org.apache.shardingsphere.sharding.api.config.rule.ShardingTableRuleConfiguration;
import org.apache.shardingsphere.sharding.api.config.strategy.keygen.KeyGenerateStrategyConfiguration;
import org.apache.shardingsphere.sharding.api.config.strategy.sharding.StandardShardingStrategyConfiguration;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public final class LocalShardingDatabasesAndTablesConfiguration implements ExampleConfiguration {

    private final ModeConfiguration modeConfig;

    public LocalShardingDatabasesAndTablesConfiguration(final ModeConfiguration modeConfig) {
        this.modeConfig = modeConfig;
    }

    private static KeyGenerateStrategyConfiguration getKeyGeneratorConfiguration() {
        return new KeyGenerateStrategyConfiguration("order_id", "snowflake");
    }

    @Override
    public DataSource getDataSource() throws SQLException {
        return ShardingSphereDataSourceFactory.createDataSource(modeConfig, createDataSourceMap(), Collections.singleton(createShardingRuleConfiguration()), new Properties());
    }

    private ShardingRuleConfiguration createShardingRuleConfiguration() {
        ShardingRuleConfiguration result = new ShardingRuleConfiguration();
        result.getTables().add(getOrderTableRuleConfiguration());
        result.getTables().add(getOrderItemTableRuleConfiguration());
        result.getBindingTableGroups().add("t_order, t_order_item");
        result.getBroadcastTables().add("t_address");
        result.setDefaultDatabaseShardingStrategy(new StandardShardingStrategyConfiguration("user_id", "inline"));
        result.setDefaultTableShardingStrategy(new StandardShardingStrategyConfiguration("order_id", "standard_test_tbl"));
        Properties props = new Properties();
        props.setProperty("algorithm-expression", "demo_ds_${user_id % 2}");
        result.getShardingAlgorithms() .put("inline", new ShardingSphereAlgorithmConfiguration("INLINE", props));
        result.getShardingAlgorithms() .put("standard_test_tbl", new ShardingSphereAlgorithmConfiguration("STANDARD_TEST_TBL", new Properties()));
        result.getKeyGenerators().put("snowflake", new ShardingSphereAlgorithmConfiguration("SNOWFLAKE", new Properties()));
        return result;
    }

    private ShardingTableRuleConfiguration getOrderTableRuleConfiguration() {
        ShardingTableRuleConfiguration result = new ShardingTableRuleConfiguration("t_order", "demo_ds_${0..1}.t_order_${[0, 1]}");
        result.setKeyGenerateStrategy(getKeyGeneratorConfiguration());
        return result;
    }

    private ShardingTableRuleConfiguration getOrderItemTableRuleConfiguration() {
        return new ShardingTableRuleConfiguration("t_order_item", "demo_ds_${0..1}.t_order_item_${[0, 1]}");
    }

    private Map<String, DataSource> createDataSourceMap() {
        Map<String, DataSource> result = new HashMap<>();
        result.put("demo_ds_0", DataSourceUtil.createDataSource("demo_ds_0"));
        result.put("demo_ds_1", DataSourceUtil.createDataSource("demo_ds_1"));
        return result;
    }
}