text:
'use strict';

angular.module('app', [
  'ngRoute',
  'ui.bootstrap',
  'uiGmapgoogle-maps',
  'angulartics',
  'angulartics.google.analytics'
]);

angular.module('app').config(['$routeProvider', '$locationProvider', '$analyticsProvider', 'uiGmapGoogleMapApiProvider', function($routeProvider, $locationProvider, $analyticsProvider, uiGmapGoogleMapApiProvider) {

  $routeProvider
    .when('/', {
      templateUrl: 'templates/home/index.html',
      title: 'benjaminGwilson',
      metaDescription: 'Benjamin G. Wilson is a web developer working in the NYC area'
    })
    .when('/bwca', {
      templateUrl: 'templates/bwca/index.html',
      controller: 'BwcaController',
      title: 'Geo Photo Galleries - benjaminGwilson',
      metaDescription: 'A project using AngularJS, Angular Google Maps and Angular Bootstrap.'
    })
    .otherwise({
      redirectTo: '/'
    });

  $locationProvider.html5Mode(true);

  $analyticsProvider.firstPageview(true);
  $analyticsProvider.withBase(true);

  uiGmapGoogleMapApiProvider.configure({
    key: '@@googleMapsApiBrowserKey'
  });
}]);

angular.module('app').run(['$rootScope', '$route', function($rootScope, $route) {

  $rootScope.$on('$routeChangeSuccess', function(event, current, previous) {
    $rootScope.pageTitle = $route.current.title;
    $rootScope.metaDescription = $route.current.metaDescription;
  });

}]);


text:
"""
Utilities for scraping data for html and csv files.  See the
enumerations_web module for example uses.
"""

from bs4 import BeautifulSoup
import csv, io
import typing

class Raw:
    """
    A tag indicating that raw HTML is being requested.

        >>> t=HTMLTable.from_data('''

        ...
text

''')
        >>> next(t.rows())[0]
        'text'
        >>> next(t.rows())[Raw(0)]
        text
    """

    def __init__(self,data):
        self.data=data

class Row:
    def __init__(self,nodes):
        self.nodes = nodes
        self.text = [node.text.strip() for node in nodes]

    def __getitem__(self,idx):
        if isinstance(idx, Raw):
            return self.nodes[idx.data]
        else:
            return self.text[idx]

    def __iter__(self):
        return iter(self.text)

    def __len__(self):
        return len(self.text)

class HTMLTable:
    def __init__(self,node):
        self.node = node

    def rows(self):
        for row in self.node.find_all('tr'):
            if not row.find('td'):
                continue
            cells = []
            for cell in row.find_all(['td','th']):
                colspan=int(cell.attrs.get('colspan',1))
                for _ in range(colspan):
                    cells.append(cell)
            yield Row(cells)

    @staticmethod
    def from_data(data,tablenum=0):
        if isinstance(data,bytes):
            data = data.decode()
        if not isinstance(data,BeautifulSoup):
            data = BeautifulSoup(data,'lxml')
        for t in data.find_all(attrs={'style':'display:none;speak:none'}):
            t.decompose()
        for t in data.find_all('sup',attrs={'class':'reference'}):
            t.decompose()
        node=data.find_all('table',class_='wikitable')[tablenum]
        return HTMLTable(node)

    @staticmethod
    def wikilink_list_format(cell):
        l = []
        for t in cell.find_all('a'):
            text=t.text.strip()
            if text:
                l.append(text)
        return l

def csv_rows(data,headers=False,enc='utf-8'):
    if isinstance(data,bytes):
        data = io.StringIO(data.decode(enc))
    elif isinstance(data,str):
        data = io.StringIO(data)
    elif isinstance(data,io.BufferedIOBase):
        data = io.TextIOWrapper(data,encoding=enc)
    reader=csv.reader(data)
    if headers:
        next(reader)
    yield from reader

def _view_item(row, idx):
    if isinstance(idx, typing.Sequence):
        idx, fn = idx
    else:
        fn = lambda x: x
    return fn(row[idx])

def view(rows, schema):
    for row in rows:
        yield [_view_item(row, idx) for idx in schema]

def allow_none(f):
    def apply(n):
        try:
            return f(n)
        except ValueError:
            return None
    return apply

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Galileo\SettingBundle\Lib\Model\ValueObject;

use Galileo\SettingBundle\Lib\Model\Exceptions\GuardException;
use Galileo\SettingBundle\Lib\Model\Specification\AlphaNumericSpecification;

class Section
{
    const EMPTY_SECTION = '___empty_section___';

    private $name;

    /**
     * @param string $name
     *
     * @throws GuardException
     */
    public function __construct($name)
    {
        $this->guard($name);
        $this->setName($name);
    }

    public static function blank()
    {
        return new Section(Section::EMPTY_SECTION);
    }

    public function name()
    {
        return $this->name;
    }

    /**
     * @param $name
     */
    private function setName($name)
    {
        $this->name = $name;
    }

    /**
     * @param $name
     */
    private function guard($name)
    {
        $alphaNumericSpecification = new AlphaNumericSpecification();
        $alphaNumericSpecification->guard($name);
    }
}


text:
<?php

/** @var \Magento\Catalog\Setup\CategorySetup $installer */
$installer = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\Catalog\Setup\CategorySetup');

/** @var $attribute \Magento\Catalog\Model\ResourceModel\Eav\Attribute */
$attribute = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
    'Magento\Catalog\Model\ResourceModel\Eav\Attribute'
);
$attribute->setData(
    [
        'attribute_code' => 'test_attribute',
        'entity_type_id' => $installer->getEntityTypeId('catalog_product'),
        'is_global' => 1,
        'is_user_defined' => 1,
        'frontend_input' => 'text',
        'is_used_for_promo_rules' => 1,
        'backend_type' => 'text',
    ]
);
$attribute->save();

/* Assign attribute to attribute set */
$installer->addAttributeToGroup('catalog_product', 'Default', 'General', $attribute->getId());

/** @var \Magento\Eav\Model\Config $eavConfig */
$eavConfig = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get('Magento\Eav\Model\Config');
$eavConfig->clear();


text:
using System;
using System.Globalization;
using MvvmCross.Converters;
using Xamarin.Forms;

namespace BLE.Client.Converters
{
    public class InverseBooleanValueConverter : MvxValueConverter<bool, bool>, IValueConverter
    {
        protected override bool Convert(bool value, Type targetType, object parameter, CultureInfo culture)
        {
            return !value;
        }

        protected override bool ConvertBack(bool value, Type targetType, object parameter, CultureInfo culture)
        {
            return !value;
        }
    }
}


text:
Register

                <form style="margin-top: 15px; margin-left: 15px;" class="ui form">

                        <input type="text" placeholder="Email Address">

                        <input type="text" placeholder="Full Name">

                        <input type="password" placeholder="Password">

                        <input type="password" placeholder="Password Repeat">

                            <input type="checkbox" tabindex="0">
                            I agree to the Terms and Conditions

                    <button class="ui button" type="submit">Register</button>
                </form>

            Or

Sign up with

                 Facebook

                 Google +

            Cancel


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@color/nice_toast_background" />
    <padding
        android:bottom="@dimen/nice_toast_icon_padding"
        android:left="@dimen/nice_toast_icon_padding"
        android:right="@dimen/nice_toast_icon_padding"
        android:top="@dimen/nice_toast_icon_padding" />
    <stroke
        android:width="@dimen/nice_toast_stroke_width"
        android:color="@color/nice_toast_error" />
    <corners android:radius="@dimen/nice_toast_corner_radius" />
</shape>


text:
ACCEPTED

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

#### Published in
Enchir. fung. (Paris) 44 (1886)

#### Original name
Agaricus demissus Fr., 1821

### Remarks
null


text:
using UnityEngine;
using System.Collections.Generic;

public class Main : MonoBehaviour {

	//Inheritance
	public Color[] EnemyType= {Color.red, Color.green, Color.yellow};// Enemy types(Colors) stored in array
	public static List <GameObject> EnemiesList= new List<GameObject>();

	public GameObject background; //2d Background image
	public static GameObject ParticleManager;// Used to clean up Hierarchy
	GameObject StarManager;//

	public float xPos;// These will be used to contain values for each methods constructor
	public float yPos;//
	public float xScale;//
	public float yScale;//
	public float speed;//
	public Color color;//
	public int Health;//

	public float EnemySpawnTime; // How long between each spawn.
	public float Enemyrotatespeed=40f;// Speed of lock on enemy rotation
	public float Zangle;

	int cooldown;//Weapon Cooldown
	int starCount=25; //set stars
	public int ScreenWidth = 7;
	public int ScreenHeight = 18;

	public static int mycooldown;//changes weapon cooldown across scripts
	public static int EnemyCount;
	public static GameObject ship;
	public static float Leveltime;
	public static int score;
	public static int Level;
	public bool debugmode=false;

	void Player(){
		ship = GameObject.CreatePrimitive (PrimitiveType.Cube);//assign Ship gameobject with a Cube
		ship.name = "Ship";
		ship.AddComponent<Ship> (); //Attach Ship script to ship GameObject
		ship.AddComponent<Movement> ();
		Ship myship = ship.GetComponent<Ship> (); // Create Instance of Enemies called myenemies
		myship.GetComponent<Ship>().SetShip (0, 0, 1.0f, 1.0f, 0.4f, new Color(100,0f,255f, 1f));
	}//End Player

	void CreateEnemies(){
		for (int i=1; i<=Level; i++) {
			GameObject enemy = GameObject.CreatePrimitive (PrimitiveType.Cube);
			enemy.name = "Enemy";
			enemy.AddComponent<Enemies> ();
			Enemies myenemies = enemy.GetComponent<Enemies> (); // Create Instance of Enemies called myenemies
			myenemies.SetEnemies (0, 0, 1, 1, 0.1f, EnemyType [0], 1);//_x, _y, _xScale, _yScale, _speed,  _color, _health
			EnemiesList.Add (enemy);
		}
	}//End CreateEnemies

	void CreateBullets(){
			GameObject bullet = GameObject.CreatePrimitive (PrimitiveType.Cube);
			bullet.name = "Bullet";
			float _xpos = ship.transform.position.x;// gives same position of ship
			float _ypos = ship.transform.position.y;//sets bullet at tip of ship
			bullet.AddComponent<ShipShoot> ();
			ShipShoot sbullet = bullet.GetComponent<ShipShoot> ();
			sbullet.SetBullet (_xpos, _ypos, 0.2f, 0.3f, 0.4f); //float _x, float _y, float _xScale, float _yScale, float _speed

	}//End CreateBullets

	void CreateStars(int _starCount){ //Takes in starCount from field above
		for (int i =0; i<=starCount; i++) {
			GameObject stars=GameObject.CreatePrimitive(PrimitiveType.Cube);
			stars.name = "Star";
			stars.collider.enabled = false;
			stars.AddComponent<Stars>();
			Stars sstars=stars.GetComponent<Stars>();
			sstars.SetStars(0, 0, 0.05f, 1.0f,Random.Range(-0.05f, -0.30f));
			stars.transform.parent=StarManager.transform;
		}
	}//End CreateStars

	void Background(){
		background = GameObject.CreatePrimitive (PrimitiveType.Quad); //Flat plane
		if (background != null) {
			background.renderer.material.mainTexture = Resources.Load<Texture2D> ("Level_1");//Quad Texture
			background.name = "BackGround";// Texture Name
			background.transform.position = new Vector3 (0, 5, 5);
			background.transform.localScale = new Vector3 (15f, 30f, 0);
			background.renderer.material.shader = Shader.Find ("Unlit/Texture");// Removes light effect on texture
			if(Level==5){
				background.renderer.material.mainTexture = Resources.Load<Texture2D> ("Level_final");
			}
		}
	}//End Background

	public void ScoreM(){
		GameObject SM = new GameObject ();//assign Ship gameobject with a Cube
		SM.transform.position = new Vector3 (0, 0, -10f);
		SM.name = "ScoreM";
		SM.GetComponent<UI> ();
		SM.AddComponent<UI> ();
	}//End ScoreM

	public void CreateParticles(Vector3 pos, Color _col, float _spd, int part_amount){// Targets pos, Targets Color & Target speed
		for (int i = 0; i < part_amount; i++) {
			GameObject particle = GameObject.CreatePrimitive (PrimitiveType.Cube);
			particle.name = "Particle";
			particle.AddComponent<Particles> ();
			Particles party = particle.GetComponent<Particles> ();
			Vector3 Direction = new Vector3 (Random.Range (-1f, 1f), Random.Range (-1f, 1f), 0); //Random directions for particles
			party.SetupParticle (pos.x, pos.y, Random.Range (0.05f, 0.1f), Random.Range (0.05f, 0.1f), _spd, Direction, _col, 3);
			particle.transform.parent=ParticleManager.transform;
		}
	}

	void AdjustDifficulty(){
		//Refresh Invoke
		EnemyCount = 5; //resets EnemyCount, when 5 enemies are destroyed.
		CancelInvoke ("CreateEnemies");
		if (EnemySpawnTime != 0.50f) {
			EnemySpawnTime -= 0.25f; //Decrease EnemySpawnTime
		}
		InvokeRepeating ("CreateEnemies", 1f, EnemySpawnTime); //Re-intialize Invoke with new EnemySpawnTime value

	}

	public void GameOver(){
		Destroy (ship.gameObject);
		CreateParticles (transform.position, ship.renderer.material.color, speed, 100);
	}

	void NextLevel() {

		foreach (GameObject enemy in EnemiesList)//Clear Screen of enemies
		{
			EnemiesList.Remove(gameObject);
			Destroy (enemy.gameObject);
		}
		Leveltime = 60;
		if (Level!=6)
			Level++;
		if(Level==5){
			background.renderer.material.mainTexture = Resources.Load<Texture2D> ("Level_final");
		}
		if (Level == 6) {
			Level= 1;
			GameOver();
			InvokeRepeating("Partytime", 1f, 1f);
		}
	}

	public void ResetEnemies(){
		if (transform.position.y <= -3f) {// Resets position once it reachs -1
			Destroy(gameObject);
		}
	}

	void Partytime(){//No game is complete without some Confetti!
		Vector3 Party = new Vector3 (Random.Range (-ScreenWidth, ScreenWidth), Random.Range (0, ScreenHeight), 0.1f);
		CreateParticles(Party, new Color(Random.Range(0.1f, 1f),Random.Range(0.1f, 1f),Random.Range(0.1f, 1f),0), 0.1f, 20); // Feed in particles spawn area, color and take in speed for effects
	}

	void Start () {
		StarManager = new GameObject ();// Contains all stars in a scene
		StarManager.name="Stars";
		ParticleManager = new GameObject ();// Contains all particles in a scene
		ParticleManager.name="Particles";
		mycooldown = 15;
		cooldown = 0;
		EnemySpawnTime = 2.50f;
		Leveltime = 60;
		Level = 1;
		EnemyCount = 5;// Counter for use with Enemy difficulty
		score = 0;
		Player ();
		Background ();
		ScoreM ();
		CreateStars (starCount);
		InvokeRepeating ("CreateEnemies", 1f, EnemySpawnTime);
	}//End Start

	void Update () {
		if (ship) //Ship must exist or not be null for bullets to be fired
		{
			if (cooldown>0)
			{
				cooldown--;
			}
			if (Input.GetKey(KeyCode.Space)&& cooldown ==0)
			{
				CreateBullets(); //call the CreateBullet function
				cooldown=mycooldown;
				if (mycooldown<=3)
					mycooldown=3; //max speed of bullets after all bonus' are picked up
			}
			if (debugmode!=true) {
				if (Leveltime <= 0)
				{
					NextLevel();
					AdjustDifficulty();//Every new level, enemies will spawn quicker, regardless of player kills.
				}

				else
				{
					Leveltime -= Time.deltaTime;
				}
			}//end Debug
		}//end ship
		if (EnemyCount==0 && EnemySpawnTime>=0.50f)
			AdjustDifficulty();// Calls Method that adjusts enemies Difficulty
	}//End Update

}//End Main Class


text:
(function( $ ){

/**
 * @class Navigator
 * @classdesc The Navigator provides a small view of the current image as fixed
 * while representing the viewport as a moving box serving as a frame
 * of reference in the larger viewport as to which portion of the image
 * is currently being examined.  The navigator's viewport can be interacted
 * with using the keyboard or the mouse.
 *
 * @memberof OpenSeadragon
 * @extends OpenSeadragon.Viewer
 * @extends OpenSeadragon.EventSource
 * @param {Object} options - Navigator options
 * @param {Element} [options.element] - An element to use for the navigator.
 * @param {String} [options.id] - Id of the element to use for the navigator. However, this is ignored if {@link options.element} is provided.
 */
$.Navigator = function( options ){

    var viewer      = options.viewer,
        _this = this,
        viewerSize,
        navigatorSize;

    //We may need to create a new element and id if they did not
    //provide the id for the existing element or the element itself
    if( options.element || options.id ){
        if ( options.element ) {
            if ( options.id ){
                $.console.warn("Given option.id for Navigator was ignored since option.element was provided and is being used instead.");
            }

            // Don't overwrite the element's id if it has one already
            if ( options.element.id ) {
                options.id = options.element.id;
            } else {
                options.id = 'navigator-' + $.now();
            }

            this.element = options.element;
        } else {
            this.element = document.getElementById( options.id );
        }

        options.controlOptions  = {
            anchor:           $.ControlAnchor.NONE,
            attachToViewer:   false,
            autoFade:         false
        };
    } else {
        options.id              = 'navigator-' + $.now();
        this.element            = $.makeNeutralElement( "div" );
        options.controlOptions  = {
            anchor:           $.ControlAnchor.TOP_RIGHT,
            attachToViewer:   true,
            autoFade:         options.autoFade
        };

        if( options.position ){
            if( 'BOTTOM_RIGHT' === options.position ){
               options.controlOptions.anchor = $.ControlAnchor.BOTTOM_RIGHT;
            } else if( 'BOTTOM_LEFT' === options.position ){
               options.controlOptions.anchor = $.ControlAnchor.BOTTOM_LEFT;
            } else if( 'TOP_RIGHT' === options.position ){
               options.controlOptions.anchor = $.ControlAnchor.TOP_RIGHT;
            } else if( 'TOP_LEFT' === options.position ){
               options.controlOptions.anchor = $.ControlAnchor.TOP_LEFT;
            } else if( 'ABSOLUTE' === options.position ){
               options.controlOptions.anchor = $.ControlAnchor.ABSOLUTE;
               options.controlOptions.top = options.top;
               options.controlOptions.left = options.left;
               options.controlOptions.height = options.height;
               options.controlOptions.width = options.width;
            }
        }
    }
    this.element.id         = options.id;
    this.element.className  += ' navigator';

    options = $.extend( true, {
        sizeRatio:     $.DEFAULT_SETTINGS.navigatorSizeRatio
    }, options, {
        element:                this.element,
        tabIndex:               -1, // No keyboard navigation, omit from tab order
        //These need to be overridden to prevent recursion since
        //the navigator is a viewer and a viewer has a navigator
        showNavigator:          false,
        mouseNavEnabled:        false,
        showNavigationControl:  false,
        showSequenceControl:    false,
        immediateRender:        true,
        blendTime:              0,
        animationTime:          options.animationTime,
        autoResize:             options.autoResize,
        // prevent resizing the navigator from adding unwanted space around the image
        minZoomImageRatio:      1.0,
        background:             options.background,
        opacity:                options.opacity,
        borderColor:            options.borderColor,
        displayRegionColor:     options.displayRegionColor
    });

    options.minPixelRatio = this.minPixelRatio = viewer.minPixelRatio;

    $.setElementTouchActionNone( this.element );

    this.borderWidth = 2;
    //At some browser magnification levels the display regions lines up correctly, but at some there appears to
    //be a one pixel gap.
    this.fudge = new $.Point(1, 1);
    this.totalBorderWidths = new $.Point(this.borderWidth * 2, this.borderWidth * 2).minus(this.fudge);

    if ( options.controlOptions.anchor !== $.ControlAnchor.NONE ) {
        (function( style, borderWidth ){
            style.margin        = '0px';
            style.border        = borderWidth + 'px solid ' + options.borderColor;
            style.padding       = '0px';
            style.background    = options.background;
            style.opacity       = options.opacity;
            style.overflow      = 'hidden';
        }( this.element.style, this.borderWidth));
    }

    this.displayRegion           = $.makeNeutralElement( "div" );
    this.displayRegion.id        = this.element.id + '-displayregion';
    this.displayRegion.className = 'displayregion';

    (function( style, borderWidth ){
        style.position      = 'relative';
        style.top           = '0px';
        style.left          = '0px';
        style.fontSize      = '0px';
        style.overflow      = 'hidden';
        style.border        = borderWidth + 'px solid ' + options.displayRegionColor;
        style.margin        = '0px';
        style.padding       = '0px';
        //TODO: IE doesn't like this property being set
        //try{ style.outline  = '2px auto #909'; }catch(e){/*ignore*/}

        style.background    = 'transparent';

        // We use square bracket notation on the statement below, because float is a keyword.
        // This is important for the Google Closure compiler, if nothing else.
        /*jshint sub:true */
        style['float']      = 'left'; //Webkit

        style.cssFloat      = 'left'; //Firefox
        style.styleFloat    = 'left'; //IE
        style.zIndex        = 999999999;
        style.cursor        = 'default';
    }( this.displayRegion.style, this.borderWidth ));
    $.setElementPointerEventsNone( this.displayRegion );
    $.setElementTouchActionNone( this.displayRegion );

    this.displayRegionContainer = $.makeNeutralElement("div");
    this.displayRegionContainer.id = this.element.id + '-displayregioncontainer';
    this.displayRegionContainer.className = "displayregioncontainer";
    this.displayRegionContainer.style.width = "100%";
    this.displayRegionContainer.style.height = "100%";
    $.setElementPointerEventsNone( this.displayRegionContainer );
    $.setElementTouchActionNone( this.displayRegionContainer );

    viewer.addControl(
        this.element,
        options.controlOptions
    );

    this._resizeWithViewer = options.controlOptions.anchor !== $.ControlAnchor.ABSOLUTE &&
        options.controlOptions.anchor !== $.ControlAnchor.NONE;

    if (options.width && options.height) {
        this.setWidth(options.width);
        this.setHeight(options.height);
    } else if ( this._resizeWithViewer ) {
        viewerSize = $.getElementSize( viewer.element );
        this.element.style.height = Math.round( viewerSize.y * options.sizeRatio ) + 'px';
        this.element.style.width  = Math.round( viewerSize.x * options.sizeRatio ) + 'px';
        this.oldViewerSize = viewerSize;
        navigatorSize = $.getElementSize( this.element );
        this.elementArea = navigatorSize.x * navigatorSize.y;
    }

    this.oldContainerSize = new $.Point( 0, 0 );

    $.Viewer.apply( this, [ options ] );

    this.displayRegionContainer.appendChild(this.displayRegion);
    this.element.getElementsByTagName('div')[0].appendChild(this.displayRegionContainer);

    function rotate(degrees) {
        _setTransformRotate(_this.displayRegionContainer, degrees);
        _setTransformRotate(_this.displayRegion, -degrees);
        _this.viewport.setRotation(degrees);
    }
    if (options.navigatorRotate) {
        var degrees = options.viewer.viewport ?
            options.viewer.viewport.getRotation() :
            options.viewer.degrees || 0;

        rotate(degrees);
        options.viewer.addHandler("rotate", function (args) {
            rotate(args.degrees);
        });
    }

    // Remove the base class' (Viewer's) innerTracker and replace it with our own
    this.innerTracker.destroy();
    this.innerTracker = new $.MouseTracker({
        userData:        'Navigator.innerTracker',
        element:         this.element, //this.canvas,
        dragHandler:     $.delegate( this, onCanvasDrag ),
        clickHandler:    $.delegate( this, onCanvasClick ),
        releaseHandler:  $.delegate( this, onCanvasRelease ),
        scrollHandler:   $.delegate( this, onCanvasScroll ),
        preProcessEventHandler: function (eventInfo) {
            if (eventInfo.eventType === 'wheel') {
                //don't scroll the page up and down if the user is scrolling
                //in the navigator
                eventInfo.preventDefault = true;
            }
        }
    });
    this.outerTracker.userData = 'Navigator.outerTracker';

    // this.innerTracker is attached to this.element...we need to allow pointer
    //   events to pass through this Viewer's canvas/container elements so implicit
    //   pointer capture works on touch devices
    //TODO an alternative is to attach the new MouseTracker to this.canvas...not
    //   sure why it isn't already (see MouseTracker constructor call above)
    $.setElementPointerEventsNone( this.canvas );
    $.setElementPointerEventsNone( this.container );

    this.addHandler("reset-size", function() {
        if (_this.viewport) {
            _this.viewport.goHome(true);
        }
    });

    viewer.world.addHandler("item-index-change", function(event) {
        window.setTimeout(function(){
            var item = _this.world.getItemAt(event.previousIndex);
            _this.world.setItemIndex(item, event.newIndex);
        }, 1);
    });

    viewer.world.addHandler("remove-item", function(event) {
        var theirItem = event.item;
        var myItem = _this._getMatchingItem(theirItem);
        if (myItem) {
            _this.world.removeItem(myItem);
        }
    });

    this.update(viewer.viewport);
};

$.extend( $.Navigator.prototype, $.EventSource.prototype, $.Viewer.prototype, /** @lends OpenSeadragon.Navigator.prototype */{

    /**
     * Used to notify the navigator when its size has changed.
     * Especially useful when {@link OpenSeadragon.Options}.navigatorAutoResize is set to false and the navigator is resizable.
     * @function
     */
    updateSize: function () {
        if ( this.viewport ) {
            var containerSize = new $.Point(
                    (this.container.clientWidth === 0 ? 1 : this.container.clientWidth),
                    (this.container.clientHeight === 0 ? 1 : this.container.clientHeight)
                );

            if ( !containerSize.equals( this.oldContainerSize ) ) {
                this.viewport.resize( containerSize, true );
                this.viewport.goHome(true);
                this.oldContainerSize = containerSize;
                this.drawer.clear();
                this.world.draw();
            }
        }
    },

    /**
     * Explicitly sets the width of the navigator, in web coordinates. Disables automatic resizing.
     * @param {Number|String} width - the new width, either a number of pixels or a CSS string, such as "100%"
     */
    setWidth: function(width) {
        this.width = width;
        this.element.style.width = typeof (width) === "number" ? (width + 'px') : width;
        this._resizeWithViewer = false;
    },

    /**
     * Explicitly sets the height of the navigator, in web coordinates. Disables automatic resizing.
     * @param {Number|String} height - the new height, either a number of pixels or a CSS string, such as "100%"
     */
    setHeight: function(height) {
        this.height = height;
        this.element.style.height = typeof (height) === "number" ? (height + 'px') : height;
        this._resizeWithViewer = false;
    },

    /**
      * Flip navigator element
      * @param {Boolean} state - Flip state to set.
      */
    setFlip: function(state) {
      this.viewport.setFlip(state);

      this.setDisplayTransform(this.viewer.viewport.getFlip() ? "scale(-1,1)" : "scale(1,1)");
      return this;
    },

    setDisplayTransform: function(rule) {
      setElementTransform(this.displayRegion, rule);
      setElementTransform(this.canvas, rule);
      setElementTransform(this.element, rule);
    },

    /**
     * Used to update the navigator minimap's viewport rectangle when a change in the viewer's viewport occurs.
     * @function
     * @param {OpenSeadragon.Viewport} The viewport this navigator is tracking.
     */
    update: function( viewport ) {

        var viewerSize,
            newWidth,
            newHeight,
            bounds,
            topleft,
            bottomright;

        viewerSize = $.getElementSize( this.viewer.element );
        if ( this._resizeWithViewer && viewerSize.x && viewerSize.y && !viewerSize.equals( this.oldViewerSize ) ) {
            this.oldViewerSize = viewerSize;

            if ( this.maintainSizeRatio || !this.elementArea) {
                newWidth  = viewerSize.x * this.sizeRatio;
                newHeight = viewerSize.y * this.sizeRatio;
            } else {
                newWidth = Math.sqrt(this.elementArea * (viewerSize.x / viewerSize.y));
                newHeight = this.elementArea / newWidth;
            }

            this.element.style.width  = Math.round( newWidth ) + 'px';
            this.element.style.height = Math.round( newHeight ) + 'px';

            if (!this.elementArea) {
                this.elementArea = newWidth * newHeight;
            }

            this.updateSize();
        }

        if (viewport && this.viewport) {
            bounds      = viewport.getBoundsNoRotate(true);
            topleft     = this.viewport.pixelFromPointNoRotate(bounds.getTopLeft(), false);
            bottomright = this.viewport.pixelFromPointNoRotate(bounds.getBottomRight(), false)
                .minus( this.totalBorderWidths );

            //update style for navigator-box
            var style = this.displayRegion.style;
            style.display = this.world.getItemCount() ? 'block' : 'none';

            style.top    = Math.round( topleft.y ) + 'px';
            style.left   = Math.round( topleft.x ) + 'px';

            var width = Math.abs( topleft.x - bottomright.x );
            var height = Math.abs( topleft.y - bottomright.y );
            // make sure width and height are non-negative so IE doesn't throw
            style.width  = Math.round( Math.max( width, 0 ) ) + 'px';
            style.height = Math.round( Math.max( height, 0 ) ) + 'px';
        }

    },

    // overrides Viewer.addTiledImage
    addTiledImage: function(options) {
        var _this = this;

        var original = options.originalTiledImage;
        delete options.original;

        var optionsClone = $.extend({}, options, {
            success: function(event) {
                var myItem = event.item;
                myItem._originalForNavigator = original;
                _this._matchBounds(myItem, original, true);
                _this._matchOpacity(myItem, original);
                _this._matchCompositeOperation(myItem, original);

                function matchBounds() {
                    _this._matchBounds(myItem, original);
                }

                function matchOpacity() {
                    _this._matchOpacity(myItem, original);
                }

                function matchCompositeOperation() {
                    _this._matchCompositeOperation(myItem, original);
                }

                original.addHandler('bounds-change', matchBounds);
                original.addHandler('clip-change', matchBounds);
                original.addHandler('opacity-change', matchOpacity);
                original.addHandler('composite-operation-change', matchCompositeOperation);
            }
        });

        return $.Viewer.prototype.addTiledImage.apply(this, [optionsClone]);
    },

    destroy: function() {
        return $.Viewer.prototype.destroy.apply(this);
    },

    // private
    _getMatchingItem: function(theirItem) {
        var count = this.world.getItemCount();
        var item;
        for (var i = 0; i < count; i++) {
            item = this.world.getItemAt(i);
            if (item._originalForNavigator === theirItem) {
                return item;
            }
        }

        return null;
    },

    // private
    _matchBounds: function(myItem, theirItem, immediately) {
        var bounds = theirItem.getBoundsNoRotate();
        myItem.setPosition(bounds.getTopLeft(), immediately);
        myItem.setWidth(bounds.width, immediately);
        myItem.setRotation(theirItem.getRotation(), immediately);
        myItem.setClip(theirItem.getClip());
        myItem.setFlip(theirItem.getFlip());
    },

    // private
    _matchOpacity: function(myItem, theirItem) {
        myItem.setOpacity(theirItem.opacity);
    },

    // private
    _matchCompositeOperation: function(myItem, theirItem) {
        myItem.setCompositeOperation(theirItem.compositeOperation);
    }
});

/**
 * @private
 * @inner
 * @function
 */
function onCanvasClick( event ) {
  var canvasClickEventArgs = {
    tracker: event.eventSource,
    position: event.position,
    quick: event.quick,
    shift: event.shift,
    originalEvent: event.originalEvent,
    preventDefaultAction: false
  };
  /**
   * Raised when a click event occurs on the {@link OpenSeadragon.Viewer#navigator} element.
   *
   * @event navigator-click
   * @memberof OpenSeadragon.Viewer
   * @type {object}
   * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.
   * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.
   * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.
   * @property {Boolean} quick - True only if the clickDistThreshold and clickTimeThreshold are both passed. Useful for differentiating between clicks and drags.
   * @property {Boolean} shift - True if the shift key was pressed during this event.
   * @property {Object} originalEvent - The original DOM event.
   * @property {?Object} userData - Arbitrary subscriber-defined object.
   * @property {Boolean} preventDefaultAction - Set to true to prevent default click to zoom behaviour. Default: false.
   */

   this.viewer.raiseEvent('navigator-click', canvasClickEventArgs);

   if ( !canvasClickEventArgs.preventDefaultAction && event.quick && this.viewer.viewport && (this.panVertical || this.panHorizontal)) {
    if(this.viewer.viewport.flipped) {
      event.position.x = this.viewport.getContainerSize().x - event.position.x;
    }
    var target = this.viewport.pointFromPixel(event.position);
    if (!this.panVertical) {
      // perform only horizonal pan
      target.y = this.viewer.viewport.getCenter(true).y;
    } else if (!this.panHorizontal) {
      // perform only vertical pan
      target.x = this.viewer.viewport.getCenter(true).x;
    }
    this.viewer.viewport.panTo(target);
    this.viewer.viewport.applyConstraints();
  }

}

/**
 * @private
 * @inner
 * @function
 */
function onCanvasDrag( event ) {
    var canvasDragEventArgs = {
      tracker: event.eventSource,
      position: event.position,
      delta: event.delta,
      speed: event.speed,
      direction: event.direction,
      shift: event.shift,
      originalEvent: event.originalEvent,
      preventDefaultAction: false
    };
    /**
     * Raised when a drag event occurs on the {@link OpenSeadragon.Viewer#navigator} element.
     *
     * @event navigator-drag
     * @memberof OpenSeadragon.Viewer
     * @type {object}
     * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.
     * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.
     * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.
     * @property {OpenSeadragon.Point} delta - The x,y components of the difference between start drag and end drag.
     * @property {Number} speed - Current computed speed, in pixels per second.
     * @property {Number} direction - Current computed direction, expressed as an angle counterclockwise relative to the positive X axis (-pi to pi, in radians). Only valid if speed > 0.
     * @property {Boolean} shift - True if the shift key was pressed during this event.
     * @property {Object} originalEvent - The original DOM event.
     * @property {?Object} userData - Arbitrary subscriber-defined object.
     * @property {Boolean} preventDefaultAction - Set to true to prevent default drag to pan behaviour. Default: false.
     */
     this.viewer.raiseEvent('navigator-drag', canvasDragEventArgs);

     if ( !canvasDragEventArgs.preventDefaultAction && this.viewer.viewport ) {
       if( !this.panHorizontal ){
            event.delta.x = 0;
        }
        if( !this.panVertical ){
            event.delta.y = 0;
        }

        if(this.viewer.viewport.flipped){
            event.delta.x = -event.delta.x;
        }

        this.viewer.viewport.panBy(
            this.viewport.deltaPointsFromPixels(
                event.delta
            )
        );
        if( this.viewer.constrainDuringPan ){
            this.viewer.viewport.applyConstraints();
        }
    }
}

/**
 * @private
 * @inner
 * @function
 */
function onCanvasRelease( event ) {
    if ( event.insideElementPressed && this.viewer.viewport ) {
        this.viewer.viewport.applyConstraints();
    }
}

/**
 * @private
 * @inner
 * @function
 */
function onCanvasScroll( event ) {
    var eventArgs = {
        tracker: event.eventSource,
        position: event.position,
        scroll: event.scroll,
        shift: event.shift,
        originalEvent: event.originalEvent,
        preventDefault: event.preventDefault
    };

    /**
     * Raised when a scroll event occurs on the {@link OpenSeadragon.Viewer#navigator} element (mouse wheel, touch pinch, etc.).
     *
     * @event navigator-scroll
     * @memberof OpenSeadragon.Viewer
     * @type {object}
     * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.
     * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.
     * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.
     * @property {Number} scroll - The scroll delta for the event.
     * @property {Boolean} shift - True if the shift key was pressed during this event.
     * @property {Object} originalEvent - The original DOM event.
     * @property {Boolean} preventDefault - Set to true to prevent the default user-agent's handling of the wheel event.
     * @property {?Object} userData - Arbitrary subscriber-defined object.
     */
    this.viewer.raiseEvent( 'navigator-scroll', eventArgs );

    event.preventDefault = eventArgs.preventDefault;
}

/**
    * @function
    * @private
    * @param {Object} element
    * @param {Number} degrees
    */
function _setTransformRotate( element, degrees ) {
  setElementTransform(element, "rotate(" + degrees + "deg)");
}

function setElementTransform( element, rule ) {
  element.style.webkitTransform = rule;
  element.style.mozTransform = rule;
  element.style.msTransform = rule;
  element.style.oTransform = rule;
  element.style.transform = rule;
}

}( OpenSeadragon ));


text:
<?php /* vim: set expandtab : */
/**
 * Mysql abstraction which only uses mysql_* functions, but can use
 * Mysqli also.
 *
 * For information on binding placeholders, @see AMysql_Statement::execute()
 *
 * @todo Maybe remove automatic dot detection for identifier escaping.
 * @todo Allow fetch methods to auto execute the statement, or throw an
 *       exception if the query hasn't been executed yet.
 * @todo Delay the call of some mysql queries to execute right before a
 *       proper one. e.g. calling 'SET NAMES utf8' every time after setting
 *       the connection params won't give you much use for lazy connection.
 *
 * Visit https://github.com/amcsi/amysql
 * @author      Szerémi Attila
 * @license     MIT License; http://www.opensource.org/licenses/mit-license.php
 **/
abstract class AMysql_Abstract
{

    public $insertId; // last insert id
    public $lastStatement; // last AMysql_Statement
    public $link = null; // mysql link
    public $isMysqli; // mysql or mysqli
    public $error; // last error message
    public $errno; // last error number
    public $result; // last mysql result
    public $query; // last used query string
    public $affectedRows; // last affected rows count
    /**
     * What value to reset autocommit to after a rollback or commit when
     * using Mysqli.
     *
     * @var boolean
     * @access public
     */
    public $defaultAutoCommit = true;

    /**
     * Contains the number of total affected rows by the last multiple statement deploying
     * method, such as updateMultipleByData and updateMultipleByKey
     *
     * @var int
     */
    public $multipleAffectedRows;

    /**
     * Whether to throw AMysql_Exceptions on mysql errors. If false, trigger_error is called instead.
     * It is recommended to leave this on TRUE.
     *
     * @var boolean
     * @access public
     */
    public $throwExceptions = true;

    /**
     * Whether AMysql_Exceptions should trigger errors by default on construction.
     * This is for legacy behavior (before v1.1.0). It is recommended to keep
     * is at FALSE.
     *
     * @var int
     * @access public
     */
    public $triggerErrorOnException = false;

    /**
     * Whether backtraces should be added to each array for getQueriesData(). If true,
     * backtraces will be found under the 'backtrace' key.
     *
     * @var boolean
     */
    public $includeBacktrace = false;

    /**
     * Amount of seconds needed to pass by to automatically call mysql_ping before
     * any query. This helps prevent "2006: Server has gone away" errors that may
     * be caused by mysql queries being performed after other long, blocking requests.
     *
     * Mysql pinging isn't guaranteed to automatically reconnect if the connection
     * actually gets lost, so it is recommended to set the connection details with
     * setConnDetails even if you are using a preexisting mysql(i) resource.
     *
     * Can be set in the connection details array or $this->setAutoPingSeconds()
     *
     * @var int|FALSE
     * @access protected
     */
    protected $autoPingSeconds = false;

    /**
     * This is set automatically by the script. Do not change this value manually!
     *
     * @var mixed
     * @access public
     */
    public $autoPing;

    /**
     * If a "2006: Server has gone away" error would occur, attempt to reconnect
     * once, resending the same query before giving up.
     *
     * Mysql pinging isn't guaranteed to automatically reconnect if the connection
     * actually gets lost, so it is recommended to set the connection details with
     * setConnDetails even if you are using a preexisting mysql(i) resource.
     *
     * Can be set in the config with the "autoReconnect" key, or by using the
     * $this->setAutoReconnect() method.
     *
     * @var false
     * @access protected
     */
    protected $autoReconnect = false;

    /**
     * Last time a query has been executed or a mysql connection has been made.
     * No need to modify externally.
     *
     * @var int
     * @access public
     */
    public $lastPingTime;

    /**
     * Let AMysql_Statement::bindParam() and AMysql_Statement::bindValue()
     * use indexes starting from 1 instead of 0 in case of unnamed placeholders.
     * The same way PDO does it. The factory default is false.
     **/
    public $pdoIndexedBinding = false;
    /**
     * The fetch mode. Can be changed here or set at runtime with
     * setFetchMode.
     *
     * @var string
     * @access protected
     */
    protected $_fetchMode = self::FETCH_ASSOC;

    protected $connDetails = array();
    protected $profiler;
    protected $inTransaction = false;

    protected $isAnsi = false;
    protected $identifierQuoteChar = '`';

    /**
     * Whether Mysqli is considered able to use.
     * Do not change; it is automatically set.
     * To force a specific mysql driver to be used, use
     * $this->setConnDetails()
     * @var boolean
     */
    public static $useMysqli;

    const FETCH_ASSOC	= 'assoc';
    const FETCH_OBJECT	= 'object';
    const FETCH_ARRAY	= 'array';
    const FETCH_ROW	    = 'row';

    /**
     * @constructor
     * @param resource|mysqli|array|string $resOrArrayOrHost    (Optional) Either a valid mysql or mysqli connection
     *					            resource/object, or a connection details array
     *					            as according to setConnDetails() (doesn't auto connect),
     *					            or parameters you would normally pass to the mysql_connect()
     *					            function. (auto connects)
     *					            (NOTE that this last construction method is
     *					            discouraged and may be deprecated and removed in later versions)
     *					            (Also note that I mention the arguments mysql_connect(), but only
     *					            the arguments. This library will still connect to mysqli if it
     *					            is available)
     *
     * @see $this->setConnDetails()
     * @see $this->setConnDetails()
     *
     **/
    public function __construct(
        $resOrArrayOrHost = null,
        $username = null,
        $password = null,
        $newLink = false,
        $clientFlags = 0
    ) {
        if (!class_exists('AMysql_Statement')) {
            // Assume no autoloader, and load everything manually
            $dir = dirname(realpath(__FILE__));
            require_once $dir . '/Exception.php';
            require_once $dir . '/Expr.php';
            require_once $dir . '/Statement.php';
            require_once $dir . '/Iterator.php';
            require_once $dir . '/Select.php';
            require_once $dir . '/Profiler.php';
        }

        $this->setAutoPingSeconds($this->autoPingSeconds);

        // Use mysqli by default if available and PHP is at least of version 5.3.0 (required).
        // Can be overridden by connection details.
        self::$useMysqli = class_exists('Mysqli', false) && function_exists('mysqli_stmt_get_result');

        if (is_resource($resOrArrayOrHost) &&
            0 === strpos(get_resource_type($resOrArrayOrHost), 'mysql link')
        ) {
            $this->link = $resOrArrayOrHost;
            $this->isMysqli = false;
        } elseif ($resOrArrayOrHost instanceof Mysqli) {
            $this->link = $resOrArrayOrHost;
            $this->isMysqli = true;
        } elseif (is_array($resOrArrayOrHost)) {
            $this->setConnDetails($resOrArrayOrHost);
        } elseif (is_string($resOrArrayOrHost)) {
            $this->oldSetConnDetails($resOrArrayOrHost, $username, $password, $newLink, $clientFlags);
            $this->connect();
        }
    }

    /**
     * Sets the connection details
     *
     * @param array $connDetails        An array of details:
     *                                  host - hostname or ip
     *                                  username - username
     *                                  password - password
     *                                  db - db to auto connect to
     *                                  port - port
     *                                  driver - force 'mysql' or 'mysqli'
     *                                  socket - socket
     *                                  defaultAutoCommit - @see $this->defaultAutoCommit
     *                                  autoPingSeconds - @see $this->autoPingSeconds
     *                                  autoReconnect - @see $this->autoReconnect
     *
     *
     * @access public
     * @return AMysql_Abstract (chainable)
     */
    public function setConnDetails(array $cd)
    {
        $defaults = array (
            'socket' => ini_get('mysqli.default_socket'),
            'db' => null,
            'newLink' => false,
            'clientFlags' => 0,
        );
        $this->connDetails = array_merge($defaults, $cd);
        if (array_key_exists('autoPingSeconds', $cd)) {
            $this->setAutoPingSeconds($cd['autoPingSeconds']);
        }
        if (array_key_exists('autoReconnect', $cd)) {
            $this->setAutoReconnect($cd['autoReconnect']);
        }
        if (array_key_exists('defaultAutoCommit', $cd)) {
            $this->setDefaultAutoCommit($cd['defaultAutoCommit']);
        }
        return $this;
    }

    /**
     * @see mysql_connect()
     *
     * @param string $host (optional)
     * @param string $username (optional)
     * @param string $password (optional)
     * @param boolean $newLink (optional)
     * @param int $clientFlags (optional)
     * @access public
     * @return AMysql_Abstract (chainable)
     */
    public function oldSetConnDetails(
        $host = null,
        $username = null,
        $password = null,
        $newLink = false,
        $clientFlags = 0
    ) {
        $port = null;
        $cd = array ();
        if ($host && false !== strpos($host, ':')) {
            list ($host, $port) = explode(':', $host, 2);
        }
        $cd['host'] = $host;
        $cd['port'] = $port;
        $cd['username'] = $username;
        $cd['password'] = $password;
        $cd['newLink'] = $newLink;
        $cd['clientFlags'] = $clientFlags;
        $this->setConnDetails($cd);
        return $this;
    }

    /**
     * Connects to the database with the configured settings.
     * Sets $this->link and $this->isMysqli
     *
     * @access public
     * @return AMysql_Abstract (chainable)
     */
    public function connect()
    {
        $this->error = null;
        $this->errno = null;

        $cd = $this->connDetails;
        if (!$cd) {
            throw new LogicException("No connection details set. Could not connect.");
        }
        if (isset($cd['driver'])) {
            switch ($cd['driver']) {
                case 'mysqli':
                    $isMysqli = true;
                    break;
                case 'mysql':
                    $isMysqli = false;
                    break;
                default:
                    throw new LogicException ("Unknown driver: `$cd[driver]`");
                    break;
            }
        } else {
            $isMysqli = self::$useMysqli;
        }
        $this->isMysqli = $isMysqli;
        $newLink = !empty($cd['newLink']);
        $res = null;
        if (isset($cd['host'], $cd['username'], $cd['password'])) {
            if ($isMysqli) {
                $port = isset($cd['port']) ? $cd['port'] : ini_get('mysqli.default_port');
                $res = mysqli_connect(
                    $cd['host'],
                    $cd['username'],
                    $cd['password'],
                    $cd['db'],
                    $port,
                    $cd['socket']
                );
            } else {
                $host = isset($cd['port']) ? "$cd[host]:$cd[port]" : $cd['host'];
                $res = mysql_connect(
                    $host,
                    $cd['username'],
                    $cd['password'],
                    $newLink,
                    $cd['clientFlags']
                );
            }
        }
        if ($res) {
            $this->lastPingTime = time(); // otherwise can cause infinite recursion.
            $this->link = $res;

            if (!$isMysqli && !empty($cd['db'])) {
                $this->selectDb($cd['db']);
            }
        } else {
            if ($this->isMysqli) {
                $this->handleError(
                    mysqli_connect_error(),
                    mysqli_connect_errno(),
                    '(connection to mysql)'
                );
            } else {
                $this->handleError(
                    mysql_error(),
                    mysql_errno(),
                    '(connection to mysql)'
                );
            }
        }
        return $this;
    }

    /**
     * Closes the connection and unsets its link.
     *
     * @access public
     * @return AMysql_Abstract (chainable)
     */
    public function close()
    {
        if ($this->link instanceof Mysqli) {
            $this->link->close();
        }
        else if (is_resource($this->link)) {
            mysql_close($this->link);
        }
        $this->link = null;
        return $this;
    }

    /**
     * Returns the DB connection link. Connects to the DB if not connected.
     * Does not check if the connection has since been broken.
     *
     * @access public
     * @return resource|mysqli            Connection resource or object
     */
    public function autoConnect()
    {
        if (!$this->link) {
            $this->connect();
        }
        return $this->link;
    }

    /**
     * Reconnects to the database with the last saved connection details.
     *
     * @access public
     * @return void
     */
    public function forceReconnect()
    {
        $oldConnDetails = (array) $this->connDetails;
        $this->connDetails['newLink'] = true;
        $this->connect();
        $this->connDetails = $oldConnDetails;
    }

    /**
     * Sets the amount of seconds needed to pass - since last communicating
     * with the database - before communicating again, to ping the
     * database server beforehand and also reconnect if the connection has
     * been since lost.
     *
     * @param int|FALSE $autoPingSeconds        The amount of seconds, or
     *                                          FALSE if it should be disabled
     * @access public
     * @return AMysql_Statement (chainable)
     */
    public function setAutoPingSeconds($autoPingSeconds)
    {
        $this->autoPingSeconds = $autoPingSeconds;
        $this->autoPing = is_numeric($this->autoPingSeconds);
        return $this;
    }

    /**
     * @see $this->autoReconnect
     *
     * @param boolean
     * @access public
     * @return AMysql_Abstract (chainable)
     */
    public function setAutoReconnect($autoReconnect)
    {
        $this->autoReconnect = $autoReconnect == true;
        return $this;
    }

    /**
     * getAutoReconnect
     *
     * @access public
     * @return boolean
     */
    public function getAutoReconnect()
    {
        return $this->autoReconnect;
    }

    /**
     * @see $this->defaultAutoCommit
     *
     * @param boolean
     * @access public
     * @return AMysql_Abstract (chainable)
     */
    public function setDefaultAutoCommit($defaultAutoCommit)
    {
        $this->defaultAutoCommit = $defaultAutoCommit == true;
        return $this;
    }

    /**
     * Returns the default fetch mode. See the FETCH_ class constants.
     *
     * @access public
     * @return string
     */
    public function getFetchMode()
    {
        return $this->_fetchMode;
    }

    /**
     * Selects the given database.
     *
     * @param string $db
     * @return AMysql_Abstract (chainable)
     */
    public function selectDb($db)
    {
        $this->connDetails['db'] = $db; // for reconnecting later
        $isMysqli = $this->isMysqli;
        $link = $this->autoPingConnect();
        $result = $isMysqli ? $link->select_db($db) : mysql_select_db($db, $link);
        if (!$result) {
            $error = $isMysqli ? $link->error : mysql_error($link);
            $errno = $isMysqli ? $link->errno : mysql_errno($link);
            $this->handleError($error, $errno, 'USE ' . $db);
        }
        return $this;
    }

    /**
     * Takes care of setting everything to utf-8
     *
     * @access public
     * @return AMysql_Abstract (chainable)
     */
    public function setUtf8()
    {
        return $this->setCharset('utf8')->setNames('utf8');
    }

    /**
     * Changes the character set of the connection.
     *
     * @param string $charset Example: utf8
     * @return AMysql_Abstract (chainable)
     */
    public function setCharset($charset)
    {
        $this->autoConnect();
        $isMysqli = $this->isMysqli;
        if ($isMysqli) {
            $result = $this->link->set_charset($charset);
        } else {
            if (!function_exists('mysql_set_charset')) {
                function mysql_set_charset($charset, $link = null)
                {
                    return mysql_query("SET CHARACTER SET '$charset'", $link);
                }
            }
            $result = mysql_set_charset($charset, $this->link);
        }
        if (!$result) {
            $error = $isMysqli ? $this->link->error : mysql_error($this->link);
            $errno = $isMysqli ? $this->link->errno : mysql_errno($this->link);
            $this->handleError($error, $errno, "(setting charset)");
        }
        return $this;
    }

    /**
     * Performs SET NAMES <charset> to change the character set. It may be
     * enough to use $this->setCharset().
     *
     * @param string $names Example: utf8
     * @return AMysql_Abstract (chainable)
     */
    public function setNames($names)
    {
        $stmt = $this->query("SET NAMES $names");
        return $this;
    }

    /**
     * Sets whether ANSI mode is on. Does not change the database's mode,
     * you just have to call this method when you know ANSI mode is being
     * used in the mysql connection, so that escaping is done according
     * to the correct mode.
     * ANSI mode is off my default on most mysql installations.
     *
     * @param boolean $isAnsi
     * @access public
     * @return AMysql_Abstract (chainable)
     */
    public function setAnsi($isAnsi)
    {
        $this->isAnsi = $isAnsi;
        $this->identifierQuoteChar = $isAnsi ? '"' : '`';
        return $this;
    }

    /**
     * Returns whether ANSI mode is being used by this instance (not the database)
     *
     * @return boolean
     **/
    public function isAnsi()
    {
        return $this->isAnsi;
    }

    /**
     * Does a simple identifier escape. It should be fail proof for that literal identifier.
     *
     * @param string $identifier    The identifier
     * @param string $qc            The quote character. Default: `
     *
     * @return string               The escaped identifier.
     **/
    public static function escapeIdentifierSimple($identifier, $qc = '`')
    {
        return $qc . addcslashes($identifier, "$qc\\") . $qc;
    }

    /**
     * Escapes an identifier. If there's a dot in it, it is split
     * into two identifiers, each escaped, and joined with a dot.
     *
     * @param string $identifier    The identifier
     * @param string $qc            The quote character. Default: `
     *
     * @return string               The escaped identifier.
     **/
    protected static function _escapeIdentifier($identifier, $qc)
    {
        $exploded = explode('.', $identifier);
        $count = count($exploded);
        $identifier = $exploded[$count-1] == '*' ?
            '*' :
            self::escapeIdentifierSimple($exploded[$count-1], $qc);
        if (1 < $count) {
            $identifier = "$qc$exploded[0]$qc.$identifier";
        }
        $ret = $identifier;
        return $ret;
    }

    /**
     * Escapes an identifier, such as a column or table name.
     * Includes functionality for making an AS syntax.
     *
     * @deprecated Do not rely on this static method. Its public visibility or name may be changed
     *  in the future. Use the non-static escapeTable() method instead.
     *
     * @param string $identifierName    The identifier name. If it has a dot in
     *                                  it, it'll automatically split the
     *                                  identifier name into the
     *                                  `tableName`.`columnName` syntax.
     *
     * @param string $as                (Optional) adds an AS syntax, but only
     *                                  if it's a string. The value is the alias
     *                                  the identifier should have for the query.
     *
     * @param $qc                       The quote character. Default: `
     *
     * @todo Possibly change the functionality to remove the automatic dot
     * detection,
     * 	and ask for an array instead?
     *
     * e.g.
     *  echo $amysql->escapeIdentifier('table.order', 'ot');
     *  // `table`.`order` AS ot
     **/
    public static function escapeIdentifier($identifierName, $as = null, $qc = '`')
    {
        $asString = '';
        $escapeIdentifierName = true;
        if ($as and !is_numeric($as)) {
            $asString = ' AS ' . $as;
        } elseif (is_string($identifierName) and (false !==
            strpos($identifierName, ' AS '))
        ) {
            $exploded = explode(' AS ', $identifierName);
            $identifierName = $exploded[0];
            $asString = ' AS ' . $exploded[1];
        }
        if ($identifierName instanceof AMysql_Expr) {
            $ret = $identifierName->__toString() . $asString;
        } else {
            $ret = self::_escapeIdentifier($identifierName, $qc) . $asString;
        }
        return $ret;
    }

    /**
     * Escapes a table name.
     *
     * @param string $identifierName    The identifier name. If it has a dot in
     *                                  it, it'll automatically split the
     *                                  identifier name into the
     *                                  `tableName`.`columnName` syntax.
     *
     * @param string $as                (Optional) adds an AS syntax, but only
     *                                  if it's a string. The value is the alias
     *                                  the identifier should have for the query.
     *
     * @return string
     */
    public function escapeTable($tableName, $as = null)
    {
        return self::escapeIdentifier($tableName, $as, $this->identifierQuoteChar);
    }

    /**
     * Escapes a column name.
     *
     * @param string $identifierName    The identifier name. If it has a dot in
     *                                  it, it'll automatically split the
     *                                  identifier name into the
     *                                  `tableName`.`columnName` syntax.
     *
     * @param string $as                (Optional) adds an AS syntax, but only
     *                                  if it's a string. The value is the alias
     *                                  the identifier should have for the query.
     *
     * @return string
     */
    public function escapeColumn($columnName, $as = null)
    {
        return $this->escapeTable($columnName, $as, $this->identifierQuoteChar);
    }

    /**
     * Returns whether a MySQL TRANSACTION is in progress,
     * based off method calls.
     *
     * @access public
     * @return boolean
     */
    public function inTransaction()
    {
        return $this->inTransaction;
    }

    /**
     * Performs a mysql ROLLBACK.
     *
     * @todo checks
     * @return mixed        Do not rely on this return value; it may change in
     *                      the future.
     **/
    public function startTransaction()
    {
        $link = $this->autoConnect();
        if ($link instanceof Mysqli) {
            $link->autocommit(false);
            $ret = true;
        } else {
            $ret = $this->query('START TRANSACTION');
        }
        $this->inTransaction = true;
        return $ret;
    }

    /**
     * Performs a mysql COMMIT.
     *
     * @todo checks
     * @return mixed        Do not rely on this return value; it may change in
     *                      the future.
     **/
    public function commit()
    {
        $link = $this->autoConnect();
        $ret = $this->query('COMMIT');
        if ($link instanceof Mysqli) {
            $link->autocommit($this->defaultAutoCommit);
        }

        $this->inTransaction = false;
        return $ret;
    }

    /**
     * Performs a mysql ROLLBACK.
     *
     * @todo checks
     * @return mixed        Do not rely on this return value; it may change in
     *                      the future.
     **/
    public function rollback()
    {
        $link = $this->autoConnect();
        $ret = $this->query('ROLLBACK');
        if ($link instanceof Mysqli) {
            $link->autocommit($this->defaultAutoCommit);
        }

        $this->inTransaction = false;
        return $ret;
    }

    /**
     * Executes a query by an sql string and binds.
     *
     * @param string $sql The SQL string.
     * @param mixed $binds The binds or a single bind.
     *
     * @return AMysql_Statement
     **/
    public function query($sql, $binds = array ())
    {
        $stmt = new AMysql_Statement($this);
        $result = $stmt->query($sql, $binds);
        return $stmt;
    }

    /**
     * Executes a query, and returns the first found row's first column's value.
     * Throws a warning if no rows were found.
     *
     * @param string $sql   The SQL string.
     * @param mixed $binds  The binds or a single bind.
     *
     * @return string|int
     **/
    public function getOne($sql, $binds = array ())
    {
        $stmt = new AMysql_Statement($this);
        $stmt->query($sql, $binds);
        return $stmt->result(0, 0);
    }

    /**
     * Like $this->getOne(), except returns a null when no result is found,
     * without throwing an error.
     *
     * @param string $sql   The SQL string.
     * @param mixed $binds  The binds or a single bind.
     *
     * @see AMysql_Abstract::getOne()
     *
     * @return string|int|NULL
     **/
    public function getOneNull($sql, $binds = array ())
    {
        $stmt = new AMysql_Statement($this);
        $stmt->query($sql, $binds);
        return $stmt->resultNull(0, 0);
    }

    /**
     * Like $this->getOne(), but casts the result to an int. No exception is
     * thrown when there is no result.
     *
     * @param string $sql The SQL string.
     * @param mixed $binds The binds or a single bind.
     *
     * @see AMysql_Abstract::getOne()
     *
     * @return int
     **/
    public function getOneInt($sql, $binds = array ())
    {
        $stmt = new AMysql_Statement($this);
        $stmt->query($sql, $binds);
        return $stmt->resultInt(0, 0);
    }

    /**
     * Prepares a mysql statement. It is to be executed.
     *
     * @param string $sql               The unbound SQL string.
     *
     * @return AMysql_Statement         A new statement instance.
     **/
    public function prepare($sql)
    {
        $stmt = new AMysql_Statement($this);
        $stmt->prepare($sql);
        return $stmt;
    }

    /**
     * Returns a new instance of AMysql_Select.
     * By passing parameters, you can now have $select->column() invoked
     * straight away (e.g. $amysql->select('*')->...)
     *
     * @param mixed $columns            (Optional)
     *
     * @see AMysql_Select::column()
     *
     * @return AMysql_Select            A new instance of this class
     **/
    public function select($columns = null)
    {
        $select = new AMysql_Select($this);
        if ($columns) {
            $select->column($columns);
        }
        return $select;
    }

    /**
     * Creates a new AMysql_Statement instance and returns it.
     *
     * @return AMysql_Statement
     **/
    public function newStatement()
    {
        return new AMysql_Statement($this);
    }

    /**
     * Performs an instant UPDATE returning the statement.
     *
     * @param string $tableName 	The table name.
     * @param array $data 		    The array of data changes. A
     *					            one-dimensional array
     * 					            with keys as column names and values
     *					            as their values.
     * @param string $where		    An SQL substring of the WHERE clause.
     * @param mixed $binds		    (Optional) The binds or a single bind for the WHERE clause.
     *
     * @return AMysql_Statement
     **/
    public function upd($tableName, array $data, $where, $binds = array())
    {
        $stmt = new AMysql_Statement($this);
        $stmt->update($tableName, $data, $where);
        $stmt->execute($binds);
        return $stmt;
    }

    /**
     * Performs an instant UPDATE returning its success.
     *
     * @param string $tableName 	The table name.
     * @param array $data 		    The array of data changes. A
     *					            one-dimensional array
     * 					            with keys as column names and values
     *					            as their values.
     * @param string $where		    An SQL substring of the WHERE clause.
     * @param mixed $binds		    (Optional) The binds or a single bind for the WHERE clause.
     *
     * @return boolean              Whether the update was successful.
     **/
    public function update($tableName, array $data, $where, $binds = array())
    {
        return $this->upd($tableName, $data, $where, $binds)->result;
    }

    /**
     * Updates multiple rows.
     * The number of total affected rows can be found in
     * $this->multipleAffectedRows.
     *
     * @param string $tableName 	The table name.
     * @param array[] $data 	    The array of data changes. An array of
     *                              an array of column-value pairs to update
     *                              for that row.
     *					            One of the column keys should be the one
     *					            with the value to search for for updating
     *					            (typically the primary key)
     *					            e.g.
     *					            [
     *					                [
     *					                    'id' => 1,
     *					                    'col1' => 'newStringValue',
     *					                    'col2' => 'newStringValue2'
     *					                ],
     *					                [
     *					                    'id' => 2,
     *					                    'col1' => 'anotherNewStringValue',
     *					                    'col2' => 'anotherNewStringValue2'
     *					                ],
     *					                ...
     *					            ]
     * @param string $column		(Options) the name of the column to search
     *                              for, and key to use among the data.
     *					            The default is 'id'.
     * @return boolean              Whether there was an equal amount of
     *                              successful updates (whether a row was
     *                              affected or not) as the size of the
     *                              inputted data array.
     **/
    public function updateMultipleByData(
        $tableName,
        array $data,
        $column = 'id'
    ) {
        $successesNeeded = count($data);
        $where = self::escapeIdentifier($column) . " = ?";
        $affectedRows = 0;
        foreach ($data as $row) {
            $by = $row[$column];
            unset($row[$column]);
            $stmt = new AMysql_Statement($this);
            $stmt->update($tableName, $row, $where)->execute(array ($by));
            $affectedRows += $stmt->affectedRows;
            if ($stmt->result) {
                $successesNeeded--;
            }
        }
        $this->multipleAffectedRows = $affectedRows;
        return 0 === $successesNeeded;
    }

    /**
     * Updates multiple rows. The values for the column to search for is the
     * key of each row.
     * The number of total affected rows can be found in
     * $this->multipleAffectedRows.
     *
     * @param string $tableName 	The table name.
     * @param array[] $data 	    The array of data changes. An array
     *                              indexed by the value of the column to
     *                              apply the update to (typically the primary)
     *                              key containing
     *                              an array of column-value pairs to update
     *                              for that row.
     *					            e.g.
     *					            [
     *					                1 => [
     *					                    'col1' => 'newStringValue',
     *					                    'col2' => 'newStringValue2'
     *					                ],
     *					                2 => [
     *					                    'id' => 2,
     *					                    'col1' => 'anotherNewStringValue',
     *					                    'col2' => 'anotherNewStringValue2'
     *					                ],
     *					                ...
     *					            ]
     * @param string $column		(Options) the name of the column and
     *					            key to search for. The default is
     *					            'id'.
     * @param boolean $updateSameColumn	(Optional) If the column being searched
     *					                for is within the a data row,
     *					                if this is false, that key should
     *					                be removed before updating the data.
     *					                This is the default.
     *
     * @return boolean
     **/
    public function updateMultipleByKey(
        $tableName,
        array $data,
        $column = 'id',
        $updateSameColumn = false
    ) {
        $successesNeeded = count($data);
        $where = $this->escapeColumn($column) . " = ?";
        $affectedRows = 0;
        foreach ($data as $by => $row) {
            if (!$updateSameColumn) {
                unset($row[$column]);
            }
            $stmt = new AMysql_Statement($this);
            $stmt->update($tableName, $row, $where)->execute(array ($by));
            $affectedRows += $stmt->affectedRows;
            if ($stmt->result) {
                $successesNeeded--;
            }
        }
        $this->multipleAffectedRows = $affectedRows;
        return 0 === $successesNeeded;
    }

    /**
     * Performs an instant INSERT, returning the statement.
     *
     * @param string $tableName 	The table name.
     * @param array $data		    A one or two-dimensional array.
     * 					            1D:
     * 					            an associative array of keys as column names and values
     * 					            as their values. This inserts one row.
     * 					            2D numeric:
     * 					            A numeric array where each value is an associative array
     * 					            with column-value pairs. Each outer, numeric value represents
     * 					            a row of data.
     * 					            2D associative:
     * 					            An associative array where the keys are the columns, the
     * 					            values are numerical arrays, where each value represents the
     * 					            value for the new row of that key.
     *
     * @return AMysql_Statement
     **/
    public function ins($tableName, array $data)
    {
        $stmt = new AMysql_Statement($this);
        $stmt->insert($tableName, $data);
        $stmt->execute();
        return $stmt;
    }

    /**
     * Performs an instant INSERT, but tries to return the last insert
     * id straight away.
     *
     * @param string $tableName 	The table name.
     * @param array $data		    A one or two-dimensional array.
     * 					            1D:
     * 					            an associative array of keys as column names and values
     * 					            as their values. This inserts one row.
     * 					            2D numeric:
     * 					            A numeric array where each value is an associative array
     * 					            with column-value pairs. Each outer, numeric value represents
     * 					            a row of data.
     * 					            2D associative:
     * 					            An associative array where the keys are the columns, the
     * 					            values are numerical arrays, where each value represents the
     * 					            value for the new row of that key.
     * @access public
     *
     * @return int|boolean          The mysql_insert_id(), if the query
     *                              succeeded and there exists a primary key.
     *                              Otherwise the boolean of whether the insert
     *                              was successful.
     */
    public function insert($tableName, array $data)
    {
        $stmt = $this->ins($tableName, $data);
        $success = $stmt->result;
        if ($success) {
            return $stmt->insertId ? $stmt->insertId : true;
        } else {
            return false;
        }
    }

    /**
     * Performs an instant REPLACE, returning the statement.
     *
     * @param string $tableName 	The table name.
     * @param array $data		    A one or two-dimensional array.
     * 					            1D:
     * 					            an associative array of keys as column names and values
     * 					            as their values. This inserts one row.
     * 					            2D numeric:
     * 					            A numeric array where each value is an associative array
     * 					            with column-value pairs. Each outer, numeric value represents
     * 					            a row of data.
     * 					            2D associative:
     * 					            An associative array where the keys are the columns, the
     * 					            values are numerical arrays, where each value represents the
     * 					            value for the new row of that key.
     *
     * @return AMysql_Statement
     **/
    public function rep($tableName, array $data)
    {
        $stmt = new AMysql_Statement($this);
        $stmt->replace($tableName, $data);
        $stmt->execute();
        return $stmt;
    }

    /**
     * Performs an instant REPLACE, returning its success.
     *
     * @param string $tableName 	The table name.
     * @param array $data		    A one or two-dimensional array.
     * 					            1D:
     * 					            an associative array of keys as column
     * 					            names and values
     * 					            as their values. This inserts one row.
     * 					            2D numeric:
     * 					            A numeric array where each value is an
     * 					            associative array
     * 					            with column-value pairs. Each outer,
     * 					            numeric value represents
     * 					            a row of data.
     * 					            2D associative:
     * 					            An associative array where the keys are the
     * 					            columns, the
     * 					            values are numerical arrays, where each
     * 					            value represents the
     * 					            value for the new row of that key.
     *
     * @return boolean              Success.
     **/
    public function replace($tableName, array $data)
    {
        $success = $this->rep($tableName, $data)->result;
        return $success;
    }

    /**
     * Performs an INSERT or an UPDATE; if the $value parameter is not falsy,
     * an UPDATE is performed with the given column name and value, otherwise
     * an insert. It is recommended that this is used for tables with a primary
     * key, and use the primary key as the column to look at. Also, this would
     * keep the return value consistent.
     *
     * @param mixed $tableName		The table name to INSERT or UPDATE to
     * @param mixed $data		    The data to change
     * @param mixed $columnName		The column to search by. It should be
     *					            a primary key.
     * @param mixed $value		    (Optional) The value to look for in
     *					            case you want
     *					            to UPDATE. Keep this at null, 0,
     *					            or anything else falsy for INSERT.
     *
     * @return int			        If the $value is not falsy, it returns
     *					            $value after UPDATING. Otherwise the
     *					            mysql_insert_id() of the newly
     *					            INSERTED row.
     */
    public function save($tableName, $data, $columnName, $value = null)
    {
        if ($value) {
            $where = AMysql_Abstract::escapeIdentifier($columnName) . ' = ?';
            $this->update($tableName, $data, $where, array ($value));
            return $value;
        } else {
            $id = $this->insert($tableName, $data);
            return $id;
        }
    }

    /**
     * Performs an instant DELETE, returning the statement.
     *
     * @param string $tableName 	The table name.
     * @param string $where		    An SQL substring of the WHERE clause.
     * @param mixed $binds		    (Optional) The binds or a single bind for
     *                              the WHERE clause.
     *
     * @return AMysql_Statement
     **/
    public function del($tableName, $where, $binds = array ())
    {
        $stmt = new AMysql_Statement($this);
        $stmt->delete($tableName, $where);
        $stmt->execute($binds);
        return $stmt;
    }

    /**
     * Performs an instant DELETE, returning whether it succeeded.
     *
     * @param string $tableName 	The table name.
     * @param string $where		    An SQL substring of the WHERE clause.
     * @param mixed $binds		    (Optional) The binds or a single bind for
     *                              the WHERE clause.
     *
     * @return resource|FALSE       The mysql resource if the delete was
     *                              successful, otherwise false.
     **/
    public function delete($tableName, $where, $binds = array ())
    {
        return $this->del($tableName, $where, $binds)->result;
    }

    /**
     * If the last mysql query was a SELECT with the SQL_CALC_FOUND_ROWS
     * options, this returns the number of found rows from that last
     * query with LIMIT and OFFSET ignored.
     *
     * @access public
     * @return int              Number of found rows.
     */
    public function foundRows()
    {
        $stmt = new AMysql_Statement($this);
        $sql = 'SELECT FOUND_ROWS()';
        $stmt->query($sql);
        return $stmt->resultInt();
    }

    /**
     * Returns an AMysql_Expr for using in prepared statements as values.
     * See the AMysql_Expr class for details.
     * To bind a literal value without apostrophes, here is an example of
     * how you can execute a prepared statement with the help of placeholders:
     *	$amysql->prepare('SELECT ? AS time')->execute(array (
     *	    $amysql->expr('CURRENT_TIMESTAMP')
     *	))
     *
     * @see AMysql_Expr
     * @param ...$variadic      see AMysql_Expr
     *
     * @return AMysql_Expr
     **/
    public function expr(/* args */)
    {
        $args = func_get_args();
        $expr = new AMysql_Expr($this);
        call_user_func_array(array ($expr, 'set'), $args);
        return $expr;
    }

    /**
     * Escapes LIKE. The after the LIKE <string> syntax, you must place
     * an ESCAPE statement with '=' or whatever you pass here as
     * $escapeStr
     * It is not recommended to call this static method externally;
     * please use {@link AMysql_Expr} instead.
     *
     * @param string $s                 The string to LIKE escape
     * @param string $escapeChar        (Optional) The escape character
     **/
    public static function escapeLike($s, $escapeStr = '=')
    {
        return str_replace(
            array($escapeStr, '_', '%'),
            array($escapeStr.$escapeStr, $escapeStr.'_', $escapeStr.'%'),
            $s
        );
    }

    /**
     * Escapes a value. The method depends on the passed value's type, but
     * unless the passed type is an AMysql_Expr, the safety is almost
     * guaranteed. Do not put apostrophes around bind marks!  Those are handled
     * by this escaping method.
     *
     * @param mixed         The value to escape
     *
     * @return string|int               The value safe to put into a query,
     *                                  including surrounding apostrophes if
     *                                  the value is string-like, not including
     *                                  apostrophes if it's an int or an
     *                                  {@link AMysql_Expr} or
     *                                  {@link AMysql_Select}
     *                                  (for selectception)
     *
     **/
    public function escape($value)
    {
        $res = $this->autoConnect();
        $isValidLink =
            $res instanceof Mysqli ||
            0 === strpos(get_resource_type($res), 'mysql link');
        if (!$isValidLink) {
            throw new RuntimeException('Resource is not a mysql resource.', 0);
        }
        $isMysqli = $this->isMysqli;
        // If it's an int, place it there literally
        if (is_int($value)) {
            return $value;
        }
        // If it's a NULL, use the literal string, NULL
        if (null === $value) {
            return 'NULL';
        }
        // Literal TRUE or FALSE in case of a boolean
        if (is_bool($value)) {
            return $value ? 'TRUE' : 'FALSE';
        }
        // for selectception ;)
        if ($value instanceof AMysql_Statement) {
            return $value->getSql();
        }
        // In case of an AMysql_Expr, use its __toString() methods return value.
        if ($value instanceof AMysql_Expr) {
            return $value->__toString();
        }
        // In the case of a string or anything else, let's escape it and
        // put it between apostrophes.
        return
            "'" .
                ($isMysqli ?
                    $this->link->real_escape_string($value) :
                    mysql_real_escape_string($value, $res))
                .
            "'"
        ;
    }

    /**
     * Transposes a 2 dimensional array.
     * Every inner array must contain the same keys as the other inner arrays,
     * otherwise unexpected results may occur.
     *
     * Example:
     *   $input = array (
     *       3 => array (
     *           'col1' => 'bla',
     *           'col2' => 'yo'
     *       ),
     *       9 => array (
     *           'col1' => 'ney',
     *           'col2' => 'lol'
     *       )
     *   );
     *   $output = $amysql->transpose($input);
     *
     *   $output: array (
     *       'col1' => array (
     *           3 => 'bla',
     *           9 => 'ney'
     *       ),
     *       'col2' => array (
     *           3 => 'yo',
     *           9 => 'lol'
     *       )
     *   );
     *
     * @param array $array      The 2 dimensional array to transpose
     * @return array
     */
    public static function transpose(array $array)
    {
        $ret = array ();
        if (!$array) {
            return $ret;
        }
        foreach ($array as $key1 => $arraySub) {
            if (!$ret) {
                foreach ($arraySub as $key2 => $value) {
                    $ret[$key2] = array ($key1 => $value);
                }
            } else {
                foreach ($arraySub as $key2 => $value) {
                    $ret[$key2][$key1] = $value;
                }
            }
        }
        return $ret;
    }

    /**
     * Adds a query and a profile for it to the list of queries.
     * Used by AMysql_Statement. Do not call externally!
     *
     * @param string $query         The SQL query.
     * @param float $queryTime      The time the query took.
     * @access public
     * @return AMysql_Abstract (chainable)
     */
    public function addQuery($query, $queryTime)
    {
        $this->getProfiler()->addQuery($query, $queryTime);
        return $this;
    }

    /**
     * Pings the mysql server to see if it's still alive;
     * attempts to reconnect otherwise.
     *
     * @param boolean $handleError      (Optional) If TRUE, on failure, this will
     *                                  be handled as any other AMysql error.
     *                                  Defaults to FALSE (no errors or
     *                                  exceptions).
     * @access public
     * @return boolean                  TRUE if the connection is still there
     *                                  or reconnection was successful.
     *                                  FALSE if reconnection wasn't successful.
     */
    public function pingReconnect()
    {
        $isMysqli = $this->isMysqli;
        if ($isMysqli) {
            $success = @mysqli_ping($this->link);
        } else {
            $success = @mysql_ping($this->link);
        }
        if (!$success) {
            try {
                $this->forceReconnect();
                if (!$this->error) {
                    $success = true;
                }
            } catch (Exception $e) {
                // do nothing
            }
        }
        return $success;
    }

    /**
     * Pings if the set amount of auto ping time has passed.
     *
     * @access public
     * @return AMysql_Abstract (chainable)
     */
    public function autoPing()
    {
        if ($this->autoPing) {
            if (!$this->link) {
                $this->connect();
            } elseif (
                !$this->lastPingTime ||
                $this->autoPingSeconds <= (time() - $this->lastPingTime)
            ) {
                $this->pingReconnect();
                $this->lastPingTime = time();
            }
        }
        return $this;
    }

    /**
     * Auto connects and auto pings (if on), returning the mysql link.
     *
     * @access public
     * @return Mysqli|resource
     */
    public function autoPingConnect()
    {
        $link = $this->autoConnect();
        $this->autoPing();
        return $link;
    }

    /**
     * Gets the list of SQL queries performed so far by AMysql_Statement
     * objects connected by this object.
     *
     * @access public
     * @return array
     */
    public function getQueries()
    {
        return $this->getProfiler()->getQueries();
    }

    /**
     * Returns an arrays of profiled query data. Each value is an array that
     * consists of:
     *  - query - The SQL query performed
     *  - time - The amount of seconds the query took (float)
     *
     * If profileQueries wss off at any query, its time value will be null.
     *
     * @return array[]
     */
    public function getQueriesData()
    {
        return $this->getProfiler()->getQueriesData();
    }

    /**
     * Returns the profiler object. Pass it to your templates
     * to retrieve the profiler results.
     *
     * @access public
     * @return AMysql_Profiler
     */
    public function getProfiler()
    {
        if (!$this->profiler) {
            $this->profiler = new AMysql_Profiler($this);
        }
        return $this->profiler;
    }

    /**
     * Force using a new profiler.
     *
     * @access public
     * @return AMysql_Abstract (chainable)
     */
    public function useNewProfiler()
    {
        $this->profiler = new AMysql_Profiler($this);
        return $this;
    }

    /**
     * For internal use.
     *
     * @param mixed $msg
     * @param mixed $code
     * @param mixed $query
     * @access public
     * @throws AMysql_Exception
     * @return void
     */
    public function handleError($msg, $code, $query)
    {
        $this->error = $msg;
        $this->errno = $code;
        $ex = new AMysql_Exception($msg, $code, $query);
        if ($this->triggerErrorOnException) {
            $ex->triggerErrorOnce();
        }
        if ($this->throwExceptions) {
            throw $ex;
        }
        $ex->triggerErrorOnce();
    }

    /**
     * For internal use.
     *
     * @param mixed $msg
     * @param mixed $code
     * @param mixed $query
     * @access public
     * @throws AMysql_Exception
     * @return void
     */
    public function handleException(AMysql_Exception $ex)
    {
        $this->error = $ex->getMessage();
        $this->errno = $ex->getCode();
        if ($this->triggerErrorOnException) {
            $ex->triggerErrorOnce();
        }
        if ($this->throwExceptions) {
            throw $ex;
        }
        $ex->triggerErrorOnce();
    }

    public function __get($name)
    {
        switch ($name) {
            case 'totalTime':
                $profiler = $this->getProfiler();
                return $profiler->totalTime;
        }
        trigger_error("Undefined property: `$name`");
    }
}


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "usrp_source.h"
#include "circular_buffer.h"
#include "fcch_detector.h"
#include "arfcn_freq.h"
#include "util.h"

extern int g_verbosity;

static const float ERROR_DETECT_OFFSET_MAX = 40e3;

#ifdef _WIN32
#define BUFSIZ 1024
#endif

static double vectornorm2(const complex *v, const unsigned int len) {

	unsigned int i;
	double e = 0.0;

	for(i = 0; i < len; i++)
		e += norm(v[i]);

	return e;
}

int c0_detect(usrp_source *u, int bi) {

#define GSM_RATE (1625000.0 / 6.0)
#define  NOTFOUND_MAX 10

	int i, chan_count;
	unsigned int overruns, b_len, frames_len, found_count, notfound_count, r;
	float offset, spower[BUFSIZ], effective_offset, min_offset, max_offset;
	double freq, sps, n, power[BUFSIZ], sum = 0, a;
	complex *b;
	circular_buffer *ub;
	fcch_detector *detector = new fcch_detector(u->sample_rate());

	if(bi == BI_NOT_DEFINED) {
		fprintf(stderr, "error: c0_detect: band not defined\n");
		return -1;
	}

	sps = u->sample_rate() / GSM_RATE;
	frames_len = (unsigned int)ceil((12 * 8 * 156.25 + 156.25) * sps);
	ub = u->get_buffer();

	// first, we calculate the power in each channel
	if(g_verbosity > 2) {
		fprintf(stderr, "calculate power in each channel:\n");
	}
	u->start();
	u->flush();
	for(i = first_chan(bi); i >= 0; i = next_chan(i, bi)) {
		freq = arfcn_to_freq(i, &bi);
		if(!u->tune(freq)) {
			fprintf(stderr, "error: usrp_source::tune\n");
			return -1;
		}

		do {
			u->flush();
			if(u->fill(frames_len, &overruns)) {
				fprintf(stderr, "error: usrp_source::fill\n");
				return -1;
			}
		} while(overruns);

		b = (complex *)ub->peek(&b_len);
		n = sqrt(vectornorm2(b, frames_len));
		power[i] = n;
		if(g_verbosity > 2) {
			fprintf(stderr, "\tchan %d (%.1fMHz):\tpower: %lf\n",
			   i, freq / 1e6, n);
		}
	}

	/*
	 * We want to use the average to determine which channels have
	 * power, and hence a possibility of being channel 0 on a BTS.
	 * However, some channels in the band can be extremely noisy.  (E.g.,
	 * CDMA traffic in GSM-850.)  Hence we won't consider the noisiest
	 * channels when we construct the average.
	 */
	chan_count = 0;
	for(i = first_chan(bi); i >= 0; i = next_chan(i, bi)) {
		spower[chan_count++] = power[i];
	}
	sort(spower, chan_count);

	// average the lowest %60
	a = avg(spower, chan_count - 4 * chan_count / 10, 0);

	if(g_verbosity > 0) {
		fprintf(stderr, "channel detect threshold: %lf\n", a);
	}

	// then we look for fcch bursts
	printf("%s:\n", bi_to_str(bi));
	found_count = 0;
	notfound_count = 0;
	sum = 0;
	i = first_chan(bi);
	do {
		if(power[i] <= a) {
			i = next_chan(i, bi);
			continue;
		}
		if (isatty(1)) {
			printf("...chan %i\r", i);
			fflush(stdout);
		}

		freq = arfcn_to_freq(i, &bi);
		if(!u->tune(freq)) {
			fprintf(stderr, "error: usrp_source::tune\n");
			return -1;
		}

		do {
			u->flush();
			if(u->fill(frames_len, &overruns)) {
				fprintf(stderr, "error: usrp_source::fill\n");
				return -1;
			}
		} while(overruns);

		b = (complex *)ub->peek(&b_len);
		r = detector->scan(b, b_len, &offset, 0);
		effective_offset = offset - GSM_RATE / 4;
		if(r && (fabsf(effective_offset) < ERROR_DETECT_OFFSET_MAX)) {
			// found
			if (found_count) {
				min_offset = fmin(min_offset, effective_offset);
				max_offset = fmax(max_offset, effective_offset);
			} else {
				min_offset = max_offset = effective_offset;
			}
			found_count++;
			printf("    chan: %4d (%.1fMHz ", i, freq / 1e6);
			display_freq(effective_offset);
			printf(")    power: %10.2f\n", power[i]);
			notfound_count = 0;
			i = next_chan(i, bi);
		} else {
			// not found
			notfound_count += 1;
			if(notfound_count >= NOTFOUND_MAX) {
				notfound_count = 0;
				i = next_chan(i, bi);
			}
		}
	} while(i >= 0);

	if (found_count == 1) {
		printf("\n");
		printf("Only one channel was found. This is unlikely and may "
			"indicate you need to provide a rough estimate of the initial "
			"PPM. It can be provided with the '-e' option. Try tuning against "
			"a local FM radio or other known frequency first.\n");
	}
	/*
	 * If the difference in offsets found is strangely large
	 */
	if (found_count > 1 && max_offset - min_offset > 1000) {
		printf("\n");
		printf("Difference of offsets between channels is >1kHz. This likely "
			"means that the correct PPM is too far away and you need to provide "
			"a rough estimate using the '-e' option. Try tuning against "
			"a local FM radio or other known frequency first.\n");
	}
	return 0;
}


text:
package chapter4.section4;

import pump.*;
import nz.sodium.*;
import java.util.Optional;

public class LifeCycle {
    public final Stream<Fuel> sStart;
    public final Cell<Optional<Fuel>> fillActive;
    public final Stream<End> sEnd;

    public enum End { END }

    private static Stream<Fuel> whenLifted(Stream<UpDown> sNozzle,
                                          Fuel nozzleFuel) {
        return sNozzle.filter(u -> u == UpDown.UP)
                      .map(u -> nozzleFuel);
    }

    private static Stream<End> whenSetDown(Stream<UpDown> sNozzle,
                Fuel nozzleFuel,
                Cell<Optional<Fuel>> fillActive) {
        return Stream.<End>filterOptional(
            sNozzle.snapshot(fillActive,
                (u,f) -> u == UpDown.DOWN &&
                         f.equals(Optional.of(nozzleFuel))
                                       ? Optional.of(End.END)
                                       : Optional.empty()));
    }

    public LifeCycle(Stream<UpDown> sNozzle1,
                     Stream<UpDown> sNozzle2,
                     Stream<UpDown> sNozzle3) {
        Stream<Fuel> sLiftNozzle =
            whenLifted(sNozzle1, Fuel.ONE).orElse(
            whenLifted(sNozzle2, Fuel.TWO).orElse(
            whenLifted(sNozzle3, Fuel.THREE)));
        CellLoop<Optional<Fuel>> fillActive = new CellLoop<>();
        this.fillActive = fillActive;
        this.sStart = Stream.filterOptional(
            sLiftNozzle.snapshot(fillActive, (newFuel, fillActive_) ->
                fillActive_.isPresent() ? Optional.empty()
                                        : Optional.of(newFuel)));
        this.sEnd = whenSetDown(sNozzle1, Fuel.ONE, fillActive).orElse(
                    whenSetDown(sNozzle2, Fuel.TWO, fillActive).orElse(
                    whenSetDown(sNozzle3, Fuel.THREE, fillActive)));
        fillActive.loop(
            sEnd.map(e -> Optional.<Fuel>empty())
                .orElse(sStart.map(f -> Optional.of(f)))
                .hold(Optional.empty())
        );
    }
}


text:
package com.spotify.docker.client;

import java.net.URI;

public class DockerTimeoutException extends DockerException {

  private final String method;
  private final URI uri;

  public DockerTimeoutException(final String method, final URI uri, final Throwable cause) {
    super("Timeout: " + method + " " + uri, cause);
    this.method = method;
    this.uri = uri;
  }

  public String method() {
    return method;
  }

  public URI uri() {
    return uri;
  }
}


text:
HANDLER_NAME="vim"
EXCLUDED_FILES=(.vitest)

function dotfiles::vim::init() {
  dotfiles::log info "Bootstrapping ${HANDLER_NAME} files..."
}