text:
var ffGrid = {
    selectedRowClassName: "state-selected",
    disabledButtonClassName: "k-state-disabled",

    showEditDialog: function (gridId, isNewRow, title, idfRow) {
        if (isNewRow) {
            idfRow = -1;
        }
        var index = gridId.indexOf("_");
        var idfsSection = gridId.substring(index + 1, gridId.length);
        var ffKey = $("#FFKey").val();
        var ffpresenterId = $("#FFpresenterId").val();
        var url = bvUrls.getEditFlexibleFormTableRowUrl() + "?idfsSection=" + idfsSection + "&isNew=" +
            isNewRow + "&idfRow=" + idfRow + "&key=" + ffKey + "&ffpresenterId=" + ffpresenterId;
        bvGrid.showEditWindow(url, 730, 460, title);
    },

    saveAndClosePopUp: function (parentGridName) {
        var contentData = bvPopup.getDefaultWindowData();
        var postUrl = bvPopup.getFormActionUrl(bvPopup.defaultName);
        $.ajax({
            url: postUrl,
            type: "POST",
            data: contentData,
            success: function (data) {
                if (parentGridName.length) {
                    if (data.indexOf("</div>") < 0)
                        bvDialog.showError(data);
                    else {
                        bvPopup.closeDefaultPopup();
                        ffGrid.reload(parentGridName, data);
                        return;
                    }
                }
                if (data == 'ok') {
                    bvPopup.closeDefaultPopup();
                } else {
                    bvDialog.showError(data);
                }
            },
            error: function (a, b, c) {
                bvDialog.showError("Error");
            }
        });
    },

    deleteRow: function (gridId, idfRow) {
        if ($("#btDelete_" + gridId).hasClass(ffGrid.disabledButtonClassName)) {
            return;
        }
        var index = gridId.indexOf("_");
        var idfsSection = gridId.substring(index + 1, gridId.length);
        var ffKey = $("#FFKey").val();
        var ffpresenterId = $("#FFpresenterId").val();
        var url = bvUrls.getDeleteFlexibleFormTableRowUrl() + "?idfsSection=" + idfsSection + "&idfRow=" + idfRow + "&key=" + ffKey + "&ffpresenterId=" + ffpresenterId;
        $.ajax({
            type: 'POST',
            url: url,
            success: function (data) {
                ffGrid.reload(gridId, data);
            }
        });
    },

    reload: function (gridId, data) {
        var idfRow = $("." + ffGrid.selectedRowClassName).attr('idfrow');
        // заменить html на результат запроса
        $("#" + gridId).html(data);

        if (idfRow === undefined) {
            ffGrid.disableOnRowButtons(gridId);
            return;
        }
        var selectedRow = $("#" + gridId + " tr[idfRow=" + idfRow + "]");
        if(selectedRow.size() === 0){
            ffGrid.disableOnRowButtons(gridId);
            return;
        }
        $("#" + gridId + " tr[idfRow=" + idfRow + "] input[type='radio']").prop('checked', true);
        ffGrid.selectRow(selectedRow);
    },

    copyRow: function (gridId) {
        var idfRow = $("." + ffGrid.selectedRowClassName).attr('idfrow');
        if (idfRow === undefined) {
            return;
        }
        var index = gridId.indexOf("_");
        var idfsSection = gridId.substring(index + 1, gridId.length);
        var ffKey = $("#FFKey").val();
        var ffpresenterId = $("#FFpresenterId").val();
        var url = bvUrls.getCopyFlexibleFormTableRowUrl() + "?idfsSection=" + idfsSection + "&idfRow=" + idfRow + "&key=" + ffKey + "&ffpresenterId=" + ffpresenterId;
        $.ajax({
            type: 'POST',
            url: url,
            success: function (data) {
                ffGrid.reload(gridId, data);
            }
        });
    },

    unSelectAllRows: function (gridId) {
        $("#" + gridId + " tr").removeClass(ffGrid.selectedRowClassName);
    },

    selectRow: function (row) {
        row.addClass(ffGrid.selectedRowClassName);
    },

    isRowSelected: function (row) {
        return row.hasClass(ffGrid.selectedRowClassName);
    },

    enableOnRowButtons: function (gridId) {
        var buttons = ffGrid.getOnRowButtons(gridId);
        ffGrid.enableButtons(buttons);
    },

    enableButtons: function (buttons) {
        if (buttons) {
            buttons.removeAttr('disabled');
            buttons.removeClass(ffGrid.disabledButtonClassName);
        }
    },

    disableOnRowButtons: function (gridId) {
        var buttons = ffGrid.getOnRowButtons(gridId);
        ffGrid.disableButtons(buttons);
    },

    disableButtons: function (buttons) {
        if (buttons) {
            buttons.attr('disabled', 'disabled');
            buttons.addClass(ffGrid.disabledButtonClassName);
        }
    },

    getOnRowButtons:function(gridId) {
        var buttons = $("#" + gridId).parent().find("button[data-role='grid-on-row-button']");
        return buttons;
    },

    onRowRadioButtonClick: function (gridName, button) {
        ffGrid.unSelectAllRows(gridName);
        var buttonData = $(button);
        var selectedRow = buttonData.closest("tr");
        if (ffGrid.isRowSelected(selectedRow)) {
            return;
        }
        ffGrid.selectRow(selectedRow);
        ffGrid.enableOnRowButtons(gridName);
    }
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPEyeTracking.Tools;

namespace WPEyeTracking.Matchers
{
    internal class BlobMatcher : Matcher<List<PixelBlob>>
    {

        internal override List<FaceEyesInfo> Match(List<PixelBlob> blobs)
        {
            List<Tuple<PixelBlob, PixelBlob>> matches = new List<Tuple<PixelBlob, PixelBlob>>();

            foreach (var item in blobs)
            {
                foreach (var item2 in blobs)
                {
                    if (item != item2)
                    {
                        if (Math.Abs(item.CenterY - item2.CenterY) < 10 && item.Count > 100)
                        {
                            matches.Add(new Tuple<PixelBlob, PixelBlob>(item, item2));
                        }
                    }
                }
            }

            List<PixelBlob> eyes = new List<PixelBlob>();

            foreach (var item in matches)
            {
                if (Math.Abs(item.Item1.MaxX - item.Item1.MinX) < 2.5 * Math.Abs(item.Item1.MaxY - item.Item1.MinY))
                {
                    if (Math.Abs(item.Item1.MaxY - item.Item1.MinY) < 2.5 * Math.Abs(item.Item1.MaxX - item.Item1.MinX))
                    {
                        eyes.Add(item.Item1);
                        eyes.Add(item.Item2);
                    }
                }
            }

            List<FaceEyesInfo> facesInfo = new List<FaceEyesInfo>();

            while (eyes.Count > 1)
            {
                PixelBlob eye1 = eyes[0];
                PixelBlob eye2 = eyes[1];

                EyeInfo leftEye = null;
                EyeInfo rightEye = null;

                if (eye1.CenterX < eye2.CenterX)
                {
                    leftEye = new EyeInfo { Side = Side.Left, X = (int)eye1.CenterX, Y = (int)eye1.CenterY, Width = eye1.MaxX - eye1.MinX, Height = eye1.MaxY - eye1.MinY };
                    rightEye = new EyeInfo { Side = Side.Right, X = (int)eye2.CenterX, Y = (int)eye2.CenterY, Width = eye2.MaxX - eye2.MinX, Height = eye2.MaxY - eye2.MinY };
                }
                else
                {
                    rightEye = new EyeInfo { Side = Side.Right, X = (int)eye1.CenterX, Y = (int)eye1.CenterY, Width = eye1.MaxX - eye1.MinX, Height = eye1.MaxY - eye1.MinY };
                    leftEye = new EyeInfo { Side = Side.Left, X = (int)eye2.CenterX, Y = (int)eye2.CenterY, Width = eye2.MaxX - eye2.MinX, Height = eye2.MaxY - eye2.MinY };
                }

                FaceEyesInfo f = new FaceEyesInfo { Eyes = new List<EyeInfo> { leftEye, rightEye } };
                facesInfo.Add(f);
            }

            return facesInfo;
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.bdgenomics.scheduling

import java.util.UUID

trait Stateful {
  def updateState(e : Event) : Stateful
}

abstract class Scheduler extends EventSource {
}

object Tracker {
  def apply[T <: EventSource](history : EventHistory) : Tracker[T] =
    history.foldStateful(new Tracker[T](Map()))
}

class Tracker[T <: EventSource](val events : Map[T, (InitialEvent[T], Option[TerminalEvent[T]])]) extends Stateful {
  override def updateState(e: Event): Tracker[T] = {
    e match {
      case startEvent : InitialEvent[T] =>
        events.get(startEvent.started) match {
          case None =>
            new Tracker[T]( events ++ Seq(startEvent.started -> (startEvent, None) ) )

          case Some((initial : InitialEvent[T], ended : Option[TerminalEvent[T]])) =>
            throw new IllegalStateException("%s had already started by time %d".format(startEvent.started, startEvent.time))
        }

      case endEvent : TerminalEvent[T] =>
        events.get(endEvent.terminated) match {
          case Some((initial : InitialEvent[T], None)) =>
            new Tracker[T](events.updated(endEvent.terminated, (initial, Some(endEvent))))

          case Some((initial : InitialEvent[T], Some(terminal : TerminalEvent[T]))) =>
            throw new IllegalStateException("%s had already had a terminal event by time %d".format(endEvent.terminated, endEvent.time))
          case None =>
            throw new IllegalStateException("%s had not started by time %d".format(endEvent.terminated, endEvent.time))
        }

      case _ => this
    }
  }

  def findOpen() : Seq[T] = events.filter( p => isOpenPair(p._2) ).map(_._1).toSeq

  def duration(value : T) : Option[Long] = events.get(value).flatMap {
    case (initialEvent, None) => None
    case (initialEvent, terminalEvent) => terminalEvent.map(evt => evt.time - initialEvent.time)
    case _ => None
  }

  def isOpenPair( eventPair : (InitialEvent[T], Option[TerminalEvent[T]]) ) : Boolean =
    eventPair match {
      case (initialEvent, None) => true
      case (initialEvent, terminalEvent) => false
      case _ => true
    }

  def isOpen(value : T) : Boolean = events.get(value).map(isOpenPair).getOrElse(true)

}

class PendingResources(val resourceRequests : Seq[ResourceRequest]) extends Stateful {
  override def updateState(e: Event): PendingResources = {
    e match {
      case RequestEvent(time, request: ResourceRequest) =>
        new PendingResources(request +: resourceRequests)
      case FulfillEvent(time, request: ResourceRequest) =>
        new PendingResources(resourceRequests.filter(_ != request))
      case _ => this
    }
  }
}

trait FlowChart[T <: Scheduler] {
  def findEvent( scheduler : T ) : Option[Event]
}

case class Choice[T <: Scheduler](option : T => Boolean,
                                  trueChoice : FlowChart[T],
                                  falseChoice : FlowChart[T]) extends FlowChart[T] {
  override def findEvent(scheduler: T): Option[Event] =
    if(option(scheduler)) trueChoice.findEvent(scheduler) else falseChoice.findEvent(scheduler)
}

case class Leaf[T <: Scheduler](event : Option[Event]) extends FlowChart[T] {
  override def findEvent(scheduler: T): Option[Event] = event
}


text:
import Dexie from 'dexie';
import {module, stop, start, asyncTest, equal, ok} from 'QUnit';
import {resetDatabase, spawnedTest} from './dexie-unittest-utils';

var db = new Dexie("TestDBException");
db.version(1).stores({ users: "id,first,last,&username,&*email,*pets" });
db.on("populate", function (trans) {
    db.users.add({ id: 1, first: "David", last: "Fahlander", username: "dfahlander", email: ["david@awarica.com", "daw@thridi.com"], pets: ["dog"] });
    db.users.add({ id: 2, first: "Karl", last: "Cedersköld", username: "kceder", email: ["karl@ceder.what"], pets: [] });
});

module("exception-handling", {
    setup: function () {
        stop();
        resetDatabase(db).catch(function (e) {
            ok(false, "Error resetting database: " + e.stack);
        }).finally(start);
    },
    teardown: function () {
    }
});

asyncTest("Uncaught promise should signal 'unhandledrejection'", function(){
    // We must not use finally or catch here because then we don't test what we should.
    var onErrorSignals = 0;
    function onerror(ev) {
        ++onErrorSignals;
        ev.preventDefault();
    }
    var prevUnhandledRejection = window.onunhandledrejection;
    window.onunhandledrejection = onerror;
    db.users.add({ id: 1 });
    setTimeout(()=> {
        equal(onErrorSignals, 1, "unhandledrejection should have been signaled");
        window.onunhandledrejection = prevUnhandledRejection;
        start();
    }, 100);
});

spawnedTest("transaction should abort on collection error", function*(){
    yield db.transaction("rw", db.users, function*() {
        let id = yield db.users.add({id: 3, first: "Foo", last: "Bar", username: "foobar"});
        equal (id, 3);
        yield db.users.where('id').equals(null).toArray();
        ok(false, "Should not come here");
    }).catch(e => {
        ok(true, "Got error because WhereClause.equals(null) should throw DataError: " + e);
    });
    equal (yield db.users.where('first').equals("Foo").count(), 0, "Should not have succeeded to add when transaction was aborted");

    yield db.transaction("rw", db.users, function() {
        db.users.add({id: 3, first: "Foo", last: "Bar", username: "foobar"});
        db.users.where('id').equals(null).toArray(res=> {
            ok(false, "Not possible to query null");
        });
    }).then(()=>{
        ok(false, "Transaction shouldnt commit");
    }).catch(e => {
        ok(true, "Got error because WhereClause.equals(null) should throw TypeError");
    });

    equal (yield db.users.where('first').equals("Foo").count(), 0, "Should not have succeeded to add when transaction was aborted");
});

asyncTest("eventError-transaction-catch", function () {
    db.transaction("rw", db.users, function () {
        db.users.add({ id: 100, username: "dfahlander" }).then(function () {
            ok(false, "Should not be able to add two users with same username");
        });
    }).then(function () {
        ok(false, "Transaction should not complete since an error should have occurred");
    }).catch(function (e) {
        ok(true, "Got transaction error: " + e);
    }).finally(start);
});

asyncTest("eventError-request-catch", function () {
    db.transaction("rw", db.users, function () {
        db.users.add({ id: 100, username: "dfahlander" }).then(function () {
            ok(false, "Should not be able to add two users with same username");
        }).catch(function (e) {
            ok(true, "Got request error: " + e);
        });
        db.users.add({ id: 101, first: "Trazan", last: "Apansson", username: "tapan", email: ["trazan@apansson.barnarne"], pets: ["monkey"] }).then(function (id) {
            ok(id > 2, "Could continue transaction and add Trazan since last error event was catched");
        });
    }).then(function () {
        ok(true, "Transaction should complete since the only error that occurred was catched");
    }).catch(function (e) {
        ok(false, "Should not get transaction error since we have catched the error. Got Transaction error: " + e);
    }).finally(start);
});

asyncTest("exceptionThrown-transaction-catch", function () {
    db.transaction("r", db.users, function () {
        throw new SyntaxError("Why not throw an exception for a change?");
    }).then(function () {
        ok(false, "Transaction should not complete since an error should have occurred");
    }).catch(TypeError, function (e) {
        ok(false, "Should not happen. The thrown error was not a TypeError");
    }).catch(SyntaxError, function (e) {
        ok(true, "Transaction got SyntaxError: " + e);
    }).catch(function (e) {
        ok(false, "Should not come here! The error should already have been catched above()");
    }).finally(start);
});

asyncTest("exceptionThrown-request-catch", function () {
    db.transaction("r", db.users, function () {
        db.users.where("username").equals("apa").toArray(function () {
            db.users.where("username").equals("kceder").toArray().then(function () {
                return "a";
            }).then(function () {
                NonExistingSymbol.EnotherIdioticError = "Why not make an exception for a change?";
            });
        });
    }).then(function () {
        ok(false, "Transaction should not complete since an error should have occurred");
    }).catch(function (e) {
        ok(true, "Transaction got error: " + e);
    }).finally(start);
});

asyncTest("exceptionThrown-iteration-should-abort-when-using-hook", function () {
    function deletingHook () {
        // Testing with
    };
    db.users.hook('deleting', deletingHook);
    db.transaction('rw', db.users, function () {

        function deleteKarls() {
            db.users.toCollection().modify(function (user) {
                delete this.value;
                throw "Throwing something";
            });
        }

        db.users.delete(1);
        deleteKarls();

    }).then(function () {
        ok(false, "Transaction should not complete!");
    }).catch(function (err) {
        ok(true, "Transaction aborted");
    }).finally(()=>{
        db.users.hook('deleting').unsubscribe(deletingHook);
        start();
    });
});

asyncTest("exceptionThrown-iteration-should-not-abort-when-using-hook", function () {
    db.users.hook('deleting', function () {
        // Testing with
    })
    db.transaction('rw', db.users, function () {

        function deleteKarls() {
            db.users.toCollection().modify(function (user) {
                delete this.value;
                throw "Throwing something";
            }).catch(function (err) {
                // Catching error should prevent transaction from aborting.
            });
        }

        db.users.delete(1);
        deleteKarls();

    }).then(function () {
        ok(true, "Transaction completed");
    }).catch(function (err) {
        ok(false, "Transaction should not abort!");
    }).finally(start);
});

/*asyncTest("promise-test", function () {
    var p = new Dexie.Promise(function (resolve, reject) {
        setTimeout(function () {
            reject("apa error");
        }, 0);
    });
    p.catch(function (err) {
        return Dexie.Promise.reject(err);
    });
    p.then(function(){}).catch(function (err) {
        return Dexie.Promise.reject(err);
    });
    p.onuncatched = function () {
        debugger;
    }
    p.finally(start);
});*/

asyncTest("exception in upgrader", function () {
    // Create a database:
    var db = new Dexie("TestUpgrader");
    db.version(1).stores({ cars: "++id,name,brand" });
    db.open().then(function(){
        // Once it opens, close it and create an upgraded version that will fail to upgrade.
        db.close();
        db = new Dexie("TestUpgrader");
        db.version(1).stores({ cars: "++id,name,brand" });
        db.version(2).upgrade(function () { db.cars.add({ name: "My car", brand: "Pegeut" }); });
        db.version(3).upgrade(function () {
            throw new Error("Oops. Failing in upgrade function");
        });
        return db.open();
    }).catch(function (err) {
        // Got error
        ok(err.toString().indexOf("Oops. Failing in upgrade function") != -1, "Got error: " + err);
        // Create 3rd instance of db that will only read from the existing DB.
        // What we want to check here is that the DB is there but is still
        // only on version 1.
        db = new Dexie("TestUpgrader");
        return db.open();
    }).then(function (){
        equal(db.verno, 1, "Database is still on version 1 since it failed to upgrade to version 2.");
    }).finally(function () {
        db.delete().then(start);
    });
});

asyncTest("exception in on('populate')", function () {
    // Create a database:
    var db = new Dexie("TestUpgrader");
    db.version(1).stores({ cars: "++id,name,brand" });
    db.on('populate', function () {
        throw new Error("Oops. Failing in upgrade function");
    });
    db.open().catch(function (err) {
        // Got error
        ok(err.toString().indexOf("Oops. Failing in upgrade function") != -1, "Got error: " + err.stack);
        // Create 3rd instance of db that will only read from the existing DB.
        // What we want to check here is that the DB is there but is still
        // only on version 1.
        db = new Dexie("TestUpgrader");
        return db.open();
    }).then(function () {
        ok(false, "The database should not have been created");
    }).catch(err => {
        ok(err instanceof Dexie.NoSuchDatabaseError, "The database doesnt exist");
    }).finally(function () {
        db.delete().then(start);
    });
});

asyncTest("Error in on('populate') should abort database creation", function () {
    var popufail = new Dexie("PopufailDB");
    popufail.version(1).stores({ users: "++id,first,last,&username,&*email,*pets" });
    popufail.on('populate', function () {
        popufail.users.add({ first: NaN, last: undefined, username: function () { } }).catch(function (e) {
            ok(true, "Got error when catching add() operation: " + e);
            return Dexie.Promise.reject(e);
        });
    });
    popufail.open().catch(function (err) {
        ok(true, "Got error (as expected):" + err);
    });
    popufail.users.count(function (count) {
        ok(false, "Could query database even though an error happened in the populate event!");
    }).catch(function (err) {
        ok(true, "Got error when trying to query: " + err);
    }).finally(function () {
        popufail.delete();
        start();
    });
});

asyncTest("Issue#73 Catching default error where specific error has already been declared in a previous catch clause(A)", function () {
    function CustomError() { }

    var wasCatched = false;
    new Dexie.Promise(function (resolve, reject) {
        setTimeout(function () {
            reject(new Error("apa"));
        }, 0);
    }).then(function () {
        ok(false, "Should not come here");
    }).catch(CustomError, function (e) {
        ok(false, "Should not come here");
    }).catch(function (e) {
        wasCatched = true;
    }).finally(function () {
        ok(wasCatched, "The error was catched in the generic catcher");
        start();
    });
});

asyncTest("Issue#73 Catching default error where specific error has already been declared in a previous catch clause(B)", function () {
    function CustomError() { }

    var wasCatched = false;
    Dexie.Promise.resolve(null).then(function () {
        throw new Error("apa");
    }).then(function () {
        ok(false, "Should not come here");
    }).catch(CustomError, function (e) {
        ok(false, "Should not come here");
    }).catch(function (e) {
        wasCatched = true;
    }).finally(function () {
        ok(wasCatched, "The error was catched in the generic catcher");
        start();
    });
});

asyncTest("Issue #67 - Exception can be thrown in WhereClause methods", function() {
    try {
        Dexie.Promise.all([
            // WhereClause.equals()
            db.users.where('first').equals(false) // Using a non-valid key (boolean) must fail but as a Promise rejection, not an exception.
            .toArray()
            .catch(function(err) {
                ok(true, "Invalid key passed to WhereClause.equals() returned as a failed Promise and not an exception.");
            }),
            // WhereClause.above()
            db.users.where('first').above(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception.
            .toArray()
            .catch(function(err) {
                ok(true, "Invalid key passed to WhereClause.above() returned as a failed Promise and not an exception.");
            }),
            // WhereClause.aboveOrEqual()
            db.users.where('first').aboveOrEqual(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception.
            .toArray()
            .catch(function(err) {
                ok(true, "Invalid key passed to WhereClause.aboveOrEqual() returned as a failed Promise and not an exception.");
            }),
            // WhereClause.below()
            db.users.where('first').below(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception.
            .toArray()
            .catch(function(err) {
                ok(true, "Invalid key passed to WhereClause.below() returned as a failed Promise and not an exception.");
            }),
            // WhereClause.belowOrEqual()
            db.users.where('first').belowOrEqual(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception.
            .toArray()
            .catch(function(err) {
                ok(true, "Invalid key passed to WhereClause.belowOrEqual() returned as a failed Promise and not an exception.");
            }),
            // WhereClause.anyOf()
            db.users.where('first').anyOf([undefined, null, false]) // Using a non-valid key (undefined, false) must fail but as a Promise rejection, not an exception.
            .toArray()
            .catch(function(err) {
                ok(true, "Invalid key passed to WhereClause.anyOf() returned as a failed Promise and not an exception.");
            }),
            // WhereClause.between()
            db.users.where('first').between(false, true) // Using a non-valid key (boolean) must fail but as a Promise rejection, not an exception.
            .toArray()
            .catch(function(err) {
                ok(true, "Invalid key passed to WhereClause.between() returned as a failed Promise and not an exception.");
            }),
            // WhereClause.equalsIgnoreCase()
            db.users.where('first').equalsIgnoreCase(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception.
            .toArray()
            .catch(function(err) {
                ok(true, "Invalid key passed to WhereClause.equalsIgnoreCase() returned as a failed Promise and not an exception.");
            }),
            // WhereClause.startsWith()
            db.users.where('first').startsWith(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception.
            .toArray()
            .catch(function(err) {
                ok(true, "Invalid key passed to WhereClause.startsWith() returned as a failed Promise and not an exception.");
            }),
            // WhereClause.startsWithIgnoreCase()
            db.users.where('first').startsWithIgnoreCase(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception.
            .toArray()
            .catch(function(err) {
                ok(true, "Invalid key passed to WhereClause.startsWithIgnoreCase() returned as a failed Promise and not an exception.");
            })
        ]).catch(function() {
            ok(false, "No promise should finally reject because we catch them all explicitely.")
        }).finally(start);
    } catch (ex) {
        ok(false, "Error was not encapsulated as a Promise failure: " + (ex.stack || ex));
        start();
    }
});

asyncTest("Issue #67 - Regression test - Transaction still fails if error in key", function () {
    db.transaction('rw', db.users, function () {
        db.users.where('first').above("").delete().then(function (num) {
            ok(true, num + " users deleted");
            db.users.where('first').above(undefined).delete();
        });
    }).then(function() {
        ok(false, "Transaction should not commit when we an unhandled error has happened");
    }).catch(function(err) {
        ok(true, "Good, transaction failed as expected");
    }).finally(start);
});

asyncTest("Issue #69 Global exception handler for promises", function () {
    var errorList = [];
    function globalRejectionHandler(ev) {
        console.log("Got error: " + ev.reason);
        if (errorList.indexOf(ev.reason) === -1) // Current implementation: accept multiple redundant triggers
            errorList.push(ev.reason);
        ev.preventDefault();
    }

    window.addEventListener('unhandledrejection', globalRejectionHandler);

    // The most simple case: Any Promise reject that is not catched should
    // be handled by the global error listener.
    new Dexie.Promise(function(resolve, reject) {
        reject("first error (by reject)");
    });

    // Also if the rejection was caused by a throw...
    new Dexie.Promise(function() {
        throw "second error (throw)";
    });

    // But when catched it should not trigger the global event:
    new Dexie.Promise(function(resolve, reject) {
        reject("third error (catched)");
    }).catch(function(e) {
        ok(true, "Catched error explicitely: " + e);
    });

    // If catching an explicit error type that was not thrown, it should be triggered
    new Dexie.Promise(function(resolve, reject) {
        reject("Simple error 1");
    }).catch(TypeError, function(e) {
        ok(false, "Error should not have been TypeError");
    });// Real error slip away... should be handled by global handler

    new Dexie.Promise(function(resolve, reject) {
        reject(new TypeError("Type Error 1"));
    }).catch(TypeError, function(e) {
        ok(true, "Catched the TypeError");
        // Now we have handled it. Not bubble to global handler!
    });

    Dexie.Promise.resolve(Promise.reject(new Error("Converting a rejected standard promise to Dexie.Promise but don't catch it")))
    .finally(()=>{
        // With finally, it should yet trigger the global event:
        return new Dexie.Promise(function(resolve, reject) {
            reject("forth error (uncatched but with finally)");
        });
    }).finally(function() {
        // From issue #43:
        // Prepare by cleaning up any unfinished previous run:
        Dexie.delete("testdb").then(function() {
            // Now just do some Dexie stuff...
            var db = new Dexie("testdb");
            db.version(1).stores({ table1: "id" });
            db.open().then(function() {
                console.log("before");
                throw new Error("FOO"); // Here a generic error is thrown (not a DB error)
                //console.log("after");
            });
            db.delete().finally(function() {
                equal(errorList.length, 6, "THere should be 6 global errors triggered");
                equal(errorList[0], "first error (by reject)", "first error (by reject)");
                equal(errorList[1], "second error (throw)", "second error (throw)");
                equal(errorList[2], "Simple error 1", "Simple error 1");
                equal(errorList[3].message, "Converting a rejected standard promise to Dexie.Promise but don't catch it", "Converting a rejected standard promise to Dexie.Promise but don't catch it");
                equal(errorList[4], "forth error (uncatched but with finally)", "forth error (uncatched but with finally)");
                equal(errorList[5].message, "FOO", "FOO");
                errorList.slice(6).map((e, i)=>`Unexpected error: ${(i+6) + ": " + e.stack}`).forEach(txt => {
                    console.error(txt);
                    ok(false, txt);
                });
                // cleanup:
                window.removeEventListener('unhandledrejection', globalRejectionHandler);
                start();
            });
        });
    });
});


text:
require 'gitolite'

module RedmineGitHosting
  module GitoliteWrapper
    extend self

    # Update the Gitolite Repository
    #
    # action: An API action defined in one of the gitolite/* classes.
    #
    def resync_gitolite(action, object, options = {})
      # Symbolize keys before using them
      action  = action.to_sym
      options = options.symbolize_keys

      # Flush cache if needed
      flush_cache(options)

      # Return if the action is only to flush cache on Sidekiq side
      if action == :flush_settings_cache
        logger.info('Settings cache flushed!')
        return
      else
        execute_action(action, object, options)
      end
    end

    private

      def flush_cache(options = {})
        if options.has_key?(:flush_cache) && options[:flush_cache] == true
          logger.info('Flush Settings Cache !')
          Setting.check_cache if Setting.respond_to?(:check_cache)
        end
      end

      # Be sure to have a Gitolite::GitoliteAdmin object.
      # Return if issues.
      #
      def execute_action(action, object, options = {})
        begin
          admin = gitolite_admin
        rescue Rugged::SshError => e
          logger.error 'Invalid Gitolite Admin SSH Keys'
          logger.error(e.message)
        rescue Rugged::NetworkError => e
          logger.error 'Access denied for Gitolite Admin SSH Keys'
          logger.error(e.message)
        rescue Rugged::RepositoryError => e
          logger.error "Gitolite couldn't write to its admin repo copy"
          logger.error "Try recreating '#{gitolite_admin_dir}'"
          logger.error(e.message)
        else
          call_gitolite_wrapper(action, admin, object, options)
        end
      end

      def gitolite_admin
        RedmineGitHosting::Config.create_temp_dir
        logger.debug("Accessing gitolite-admin.git at '#{gitolite_admin_dir}'")
        ::Gitolite::GitoliteAdmin.new(gitolite_admin_dir, gitolite_admin_settings)
      end

      def gitolite_admin_dir
        RedmineGitHosting::Config.gitolite_admin_dir
      end

      def call_gitolite_wrapper(action, admin, object, options = {})
        begin
          klass = GitoliteWrappers::Base.find_by_action_name(action)
        rescue RedmineGitHosting::Error::GitoliteWrapperException => e
          logger.error(e.message)
        else
          klass.call(admin, object, options)
        end
      end

      def gitolite_admin_settings
        {
          git_user:     RedmineGitHosting::Config.gitolite_user,
          host:         "#{RedmineGitHosting::Config.gitolite_server_host}:#{RedmineGitHosting::Config.gitolite_server_port}",
          author_name:  RedmineGitHosting::Config.git_config_username,
          author_email: RedmineGitHosting::Config.git_config_email,
          public_key:   RedmineGitHosting::Config.gitolite_ssh_public_key,
          private_key:  RedmineGitHosting::Config.gitolite_ssh_private_key,
          key_subdir:   RedmineGitHosting::Config.gitolite_key_subdir,
          config_file:  RedmineGitHosting::Config.gitolite_config_file,
          config_dir:   RedmineGitHosting::Config.gitolite_config_dir
        }
      end

      def logger
        RedmineGitHosting.logger
      end

  end
end


text:
package com.tale.controller.admin;

import com.blade.ioc.annotation.Inject;
import com.blade.jdbc.core.Take;
import com.blade.jdbc.model.Paginator;
import com.blade.kit.StringKit;
import com.blade.mvc.annotation.*;
import com.blade.mvc.http.HttpMethod;
import com.blade.mvc.http.Request;
import com.blade.mvc.view.RestResponse;
import com.tale.controller.BaseController;
import com.tale.dto.LogActions;
import com.tale.dto.Types;
import com.tale.exception.TipException;
import com.tale.model.Contents;
import com.tale.model.Metas;
import com.tale.model.Users;
import com.tale.service.ContentsService;
import com.tale.service.LogService;
import com.tale.service.MetasService;
import com.tale.service.SiteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 文章管理控制器
 * Created by biezhi on 2017/2/21.
 */
@Controller("admin/article")
public class ArticleController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ArticleController.class);

    @Inject
    private ContentsService contentsService;

    @Inject
    private MetasService metasService;

    @Inject
    private LogService logService;

    @Inject
    private SiteService siteService;

    /**
     * 文章管理首页
     * @param page
     * @param limit
     * @param request
     * @return
     */
    @Route(value = "", method = HttpMethod.GET)
    public String index(@QueryParam(value = "page", defaultValue = "1") int page,
                        @QueryParam(value = "limit", defaultValue = "15") int limit, Request request) {

        Paginator<Contents> contentsPaginator = contentsService.getArticles(new Take(Contents.class).eq("type", Types.ARTICLE).page(page, limit, "created desc"));
        request.attribute("articles", contentsPaginator);
        return "admin/article_list";
    }

    /**
     * 文章发布页面
     * @param request
     * @return
     */
    @Route(value = "publish", method = HttpMethod.GET)
    public String newArticle(Request request) {
        List<Metas> categories = metasService.getMetas(Types.CATEGORY);
        request.attribute("categories", categories);
        return "admin/article_edit";
    }

    /**
     * 文章编辑页面
     * @param cid
     * @param request
     * @return
     */
    @Route(value = "/:cid", method = HttpMethod.GET)
    public String editArticle(@PathParam String cid, Request request) {
        Contents contents = contentsService.getContents(cid);
        request.attribute("contents", contents);
        List<Metas> categories = metasService.getMetas(Types.CATEGORY);
        request.attribute("categories", categories);
        request.attribute("active", "article");
        return "admin/article_edit";
    }

    /**
     * 发布文章操作
     *
     * @param title
     * @param content
     * @param tags
     * @param categories
     * @param status
     * @param slug
     * @param allow_comment
     * @param allow_ping
     * @param allow_feed
     * @return
     */
    @Route(value = "publish", method = HttpMethod.POST)
    @JSON
    public RestResponse publishArticle(@QueryParam String title, @QueryParam String content,
                                       @QueryParam String tags, @QueryParam String categories,
                                       @QueryParam String status, @QueryParam String slug,
                                       @QueryParam Boolean allow_comment, @QueryParam Boolean allow_ping, @QueryParam Boolean allow_feed) {

        Users users = this.user();

        Contents contents = new Contents();
        contents.setTitle(title);
        contents.setContent(content);
        contents.setStatus(status);
        contents.setSlug(slug);
        contents.setType(Types.ARTICLE);
        if (null != allow_comment) {
            contents.setAllow_comment(allow_comment);
        }
        if (null != allow_ping) {
            contents.setAllow_ping(allow_ping);
        }
        if (null != allow_feed) {
            contents.setAllow_feed(allow_feed);
        }
        contents.setAuthor_id(users.getUid());
        contents.setTags(tags);
        if (StringKit.isBlank(categories)) {
            categories = "默认分类";
        }
        contents.setCategories(categories);

        try {
            contentsService.publish(contents);
            siteService.cleanCache(Types.C_STATISTICS);
        } catch (Exception e) {
            String msg = "文章发布失败";
            if (e instanceof TipException) {
                msg = e.getMessage();
            } else {
                LOGGER.error(msg, e);
            }
            return RestResponse.fail(msg);
        }
        return RestResponse.ok();
    }

    /**
     * 修改文章操作
     *
     * @param cid
     * @param title
     * @param content
     * @param tags
     * @param categories
     * @param status
     * @param slug
     * @param allow_comment
     * @param allow_ping
     * @param allow_feed
     * @return
     */
    @Route(value = "modify", method = HttpMethod.POST)
    @JSON
    public RestResponse modifyArticle(@QueryParam Integer cid, @QueryParam String title,
                                      @QueryParam String content,
                                      @QueryParam String tags, @QueryParam String categories,
                                      @QueryParam String status, @QueryParam String slug,
                                      @QueryParam Boolean allow_comment, @QueryParam Boolean allow_ping, @QueryParam Boolean allow_feed) {

        Users users = this.user();
        Contents contents = new Contents();
        contents.setCid(cid);
        contents.setTitle(title);
        contents.setContent(content);
        contents.setStatus(status);
        contents.setSlug(slug);
        if (null != allow_comment) {
            contents.setAllow_comment(allow_comment);
        }
        if (null != allow_ping) {
            contents.setAllow_ping(allow_ping);
        }
        if (null != allow_feed) {
            contents.setAllow_feed(allow_feed);
        }
        contents.setAuthor_id(users.getUid());
        contents.setTags(tags);
        contents.setCategories(categories);
        try {
            contentsService.updateArticle(contents);
        } catch (Exception e) {
            String msg = "文章编辑失败";
            if (e instanceof TipException) {
                msg = e.getMessage();
            } else {
                LOGGER.error(msg, e);
            }
            return RestResponse.fail(msg);
        }
        return RestResponse.ok();
    }

    /**
     * 删除文章操作
     *
     * @param cid
     * @param request
     * @return
     */
    @Route(value = "delete")
    @JSON
    public RestResponse delete(@QueryParam int cid, Request request) {
        try {
            contentsService.delete(cid);
            siteService.cleanCache(Types.C_STATISTICS);
            logService.save(LogActions.DEL_ARTICLE, cid+"", request.address(), this.getUid());
        } catch (Exception e) {
            String msg = "文章删除失败";
            if (e instanceof TipException) {
                msg = e.getMessage();
            } else {
                LOGGER.error(msg, e);
            }
            return RestResponse.fail(msg);
        }
        return RestResponse.ok();
    }
}


text:
#ifndef BOOST_FUSION_ADAPTED_ARRAY_AT_IMPL_HPP
#define BOOST_FUSION_ADAPTED_ARRAY_AT_IMPL_HPP

#include <boost/type_traits/add_reference.hpp>
#include <boost/type_traits/remove_extent.hpp>

namespace boost { namespace fusion { namespace extension
{
    template<typename>
    struct at_impl;

    template<>
    struct at_impl<po_array_tag>
    {
        template<typename Seq, typename N>
        struct apply
        {
            typedef typename
                add_reference<typename remove_extent<Seq>::type>::type
            type;

            static type
            call(Seq& seq)
            {
                return seq[N::value];
            }
        };
    };
}}}

#endif


text:
package pe.org.edustats.data.bean;

import java.io.Serializable;

public class OpcionBean implements Serializable {
  private Integer idOpcion;
  private String coOpcion;
  private String deOpcion;
  private String deRuta;
  private OpcionBean opcionPadre;

  public Integer getIdOpcion() {
    return idOpcion;
  }

  public void setIdOpcion(Integer idOpcion) {
    this.idOpcion = idOpcion;
  }

  public String getCoOpcion() {
    return coOpcion;
  }

  public void setCoOpcion(String coOpcion) {
    this.coOpcion = coOpcion;
  }

  public String getDeOpcion() {
    return deOpcion;
  }

  public void setDeOpcion(String deOpcion) {
    this.deOpcion = deOpcion;
  }

  public String getDeRuta() {
    return deRuta;
  }

  public void setDeRuta(String deRuta) {
    this.deRuta = deRuta;
  }

  public OpcionBean getOpcionPadre() {
    return opcionPadre;
  }

  public void setOpcionPadre(OpcionBean opcionPadre) {
    this.opcionPadre = opcionPadre;
  }
}


text:
module.exports = new DateTimeUtils();
function DateTimeUtils() {
    /**
     * Get timestamp of today (at 00:00:00.00)
     * @param {Date} dateTime
     * @returns {long}
     */
    this.dayTimestamp = function (dateTime) {
        dateTime.setHours(0);
        dateTime.setMinutes(0);
        dateTime.setSeconds(0);
        dateTime.setMilliseconds(0);
        return dateTime.getTime();
    };

    this.milisecondToString = function(time){
        var date = new Date(parseInt(time));
        return date.getDate() + "/"
            + (date.getMonth()+1)  + "/"
            + date.getFullYear();
    };
}


text:
class DRBG::HMAC

  def initialize(entropy, sec_level=256, personalization_string="")

    if sec_level > 256
      raise 'sec_level cannot exceed 256 bits'
    end

    if personalization_string.size * 8 > 256
      raise 'personalization_string cannot exceed 256 bits'
    end

    if sec_level <= 112
      @security_strength = 112
    elsif sec_level <= 128
      @sec_level = 128
    elsif sec_level <= 192
      @sec_level = 192
    else
      @sec_level = 256
    end

    if (entropy.size * 8 * 2) < (3 * @sec_level)
      raise 'entropy must be at least ' + (1.5 * @sec_level).to_s + ' bits'
    end

    if entropy.size * 8 > 1000
      raise 'entropy cannot exceed 1000 bits'
    end

    _instantiate(entropy, personalization_string)

  end

  def generate(num_bytes, sec_level=256)

    if num_bytes * 8 > 7500
      raise 'generate cannot generate more than 7500 bits in a single call'
    end

    if sec_level > @sec_level
      raise 'sec_level exceeds this instance\'s security_strength'
    end

    return if @reseed_counter >= 10000

    temp = ''

    while temp.size < num_bytes
      @V = hmac(@K, @V)
      temp += @V
    end

    self._update(nil)
    @reseed_counter += 1

    temp

  end

  protected

  def _instantiate(entropy, personalization_string)

    seed_material = entropy + personalization_string

    @K = "\x00" * 32
    @V = "\x01" * 32

    _update(seed_material)
    @reseed_counter = 1

  end

  def _update(provided_data = nil)

    @K = hmac(@K, @V + "\x00" + (provided_data || ''))
    @V = hmac(@K, @V)

    if provided_data
      @K = hmac(@K, @V + "\x01" + provided_data)
      @V = hmac(@K, @V)
    end

  end

  def reseed(entropy)

    if len(entropy) * 8 < @sec_level
      raise "entropy must be at least #{@sec_level} bits"
    end

    if len(entropy) * 8 > 1000
      raise 'entropy cannot exceed 1000 bits'
    end

    _update(entropy)
    @reseed_counter = 1

  end

  def hmac(key, data)

    @digest ||= OpenSSL::Digest::SHA256.new
    OpenSSL::HMAC.digest(@digest, key, data)

  end

end


text:
using Google.GData.Client;

namespace Google.GData.Contacts
{
    /// <summary>
    /// Entry API customization class for defining entries in an Group feed.
    /// </summary>
    public class GroupEntry : BaseContactEntry
    {
        /// <summary>
        /// default contact term string for the contact relationship link
        /// </summary>
        public static string GroupTerm = "http://schemas.google.com/contact/2008#group";

        /// <summary>
        /// Category used to label entries that contain contact extension data.
        /// </summary>
        public static AtomCategory GROUP_CATEGORY =
            new AtomCategory(GroupTerm, new AtomUri(BaseNameTable.gKind));

        /// <summary>
        /// Constructs a new ContactEntry instance with the appropriate category
        /// to indicate that it is an event.
        /// </summary>
        public GroupEntry()
        {
            Tracing.TraceMsg("Created Group Entry");
            AddExtension(new SystemGroup());
            Categories.Add(GROUP_CATEGORY);
        }

        /// <summary>
        /// returns the systemgroup id, if this groupentry represents
        /// a system group.
        /// The values of the system group ids corresponding to these
        /// groups can be found in the Reference Guide for the Contacts Data API.
        /// Currently the values can be Contacts, Friends, Family and Coworkers
        /// </summary>
        /// <returns></returns>
        public string SystemGroup
        {
            get
            {
                SystemGroup sg = FindExtension(ContactsNameTable.SystemGroupElement,
                    ContactsNameTable.NSContacts) as SystemGroup;

                if (sg != null)
                {
                    return sg.Id;
                }
                return null;
            }
        }

        /// <summary>
        /// typed override of the Update method
        /// </summary>
        /// <returns></returns>
        public new GroupEntry Update()
        {
            return base.Update() as GroupEntry;
        }
    }
}


text:
//// Copyright (c) Microsoft Corporation. All rights reserved

(function () {
    "use strict";

    var SecondaryTile = Windows.UI.StartScreen.SecondaryTile;
    var TileSize = Windows.UI.StartScreen.TileSize;
    var Uri = Windows.Foundation.Uri;

    var TileNotification = Windows.UI.Notifications.TileNotification;
    var TileUpdateManager = Windows.UI.Notifications.TileUpdateManager;
    var Notifications = Microsoft.Toolkit.Uwp.Notifications;

    var _tileId;

    // UI elements on the page
    var sendCommand;
    var pinCommand;

    var page = WinJS.UI.Pages.define("/html/scenario4-secondarytilenotifications.html", {
        ready: function (element, options) {

            pinCommand = element.querySelector("#pincommand");
            pinCommand.addEventListener("click", pinTile);

            sendCommand = element.querySelector("#sendcommand");
            sendCommand.addEventListener("click", sendNotification);
        }
    });

    function pinTile() {

        pinCommand.disabled = true;

        // Generate a unique tile ID for the purposes of the sample
        _tileId = new Date().getTime().toString();

        // Initialize and pin a new secondary tile.
        var tile = new SecondaryTile(_tileId, "Secondary notifications", "args", new Uri("ms-appx:///images/Square150x150Logo.png"), TileSize.default);
        tile.visualElements.wide310x150Logo = new Uri("ms-appx:///images/Wide310x150Logo.png");
        tile.visualElements.square310x310Logo = new Uri("ms-appx:///images/Square310x310Logo.png");
        tile.visualElements.showNameOnSquare150x150Logo = true;
        tile.visualElements.showNameOnSquare310x310Logo = true;
        tile.visualElements.showNameOnWide310x150Logo = true;

        tile.requestCreateAsync().then(function complete() {
            pinCommand.disabled = false;
        });
    }

    function sendNotification() {

        var nowTimeString = new Date().toLocaleString();

        var textConfigs = [
            { text: "New secondary tile notification", hintWrap: true },
            { text: nowTimeString, hintWrap: true, hintStyle: Notifications.AdaptiveTextStyle.captionSubtle }
        ];

        // Build and append content from textConfigs, line by line.
        var adaptiveContent = new Notifications.TileBindingContentAdaptive();
        textConfigs.forEach(function (lineConfig) {
            var lineOfText = new Notifications.AdaptiveText();
            for (var key in lineConfig) {
                lineOfText[key] = lineConfig[key];
            }
            adaptiveContent.children.push(lineOfText);
        });

        // Specify templates and send Notification.
        var tileContent = new Notifications.TileContent();
        tileContent.visual = new Notifications.TileVisual();
        tileContent.visual.branding = Notifications.TileBranding.nameAndLogo;
        tileContent.visual.tileMedium = new Notifications.TileBinding();
        tileContent.visual.tileMedium.content = adaptiveContent;
        tileContent.visual.tileWide = new Notifications.TileBinding();
        tileContent.visual.tileWide.content = adaptiveContent;
        tileContent.visual.tileLarge = new Notifications.TileBinding();
        tileContent.visual.tileLarge.content = adaptiveContent;

        var doc = tileContent.getXml();
        var notification = new TileNotification(doc);
        TileUpdateManager.createTileUpdaterForSecondaryTile(_tileId).update(notification);
    }

})();


text:
require 'json'
require_relative 'json/builder'
require_relative 'json/error_handler'
require_relative 'json/handler'
require_relative 'json/parser'

module Aws
  # @api private
  module Json

    class ParseError < StandardError

      def initialize(error)
        @error = error
        super(error.message)
      end

      attr_reader :error

    end

    class << self

      def load(json)
        ENGINE.load(json, *ENGINE_LOAD_OPTIONS)
      rescue ENGINE_ERROR => e
        raise ParseError.new(e)
      end

      def load_file(path)
        self.load(File.open(path, 'r', encoding: 'UTF-8') { |f| f.read })
      end

      def dump(value)
        ENGINE.dump(value, *ENGINE_DUMP_OPTIONS)
      end

      private

      def oj_engine
        require 'oj'
        [Oj, [{mode: :compat, symbol_keys: false}], [{ mode: :compat }], oj_parse_error]
      rescue LoadError
        false
      end

      def json_engine
        [JSON, [], [], JSON::ParserError]
      end

      def oj_parse_error
        if Oj.const_defined?('ParseError')
          Oj::ParseError
        else
          SyntaxError
        end
      end

    end

    # @api private
    ENGINE, ENGINE_LOAD_OPTIONS, ENGINE_DUMP_OPTIONS, ENGINE_ERROR =
      oj_engine || json_engine

  end
end


text:
Current Boards
        Show By User:
            <select class="form-control" data-ng-model="boardFilter.userFilter"
                data-ng-options="user.id as user.username for user in users">
                <option value="">Any User</option>
            </select>

        Filter By:
            <select class="form-control" data-ng-model="boardFilter.filter"
                data-ng-options="option.filter as option.name for option in boardFilter.options">
            </select>

        Sort By:
            <select class="form-control" data-ng-model="boardSort.sort"
                data-ng-options="option.sort as option.name for option in boardSort.options">
            </select>

                    Name	Columns	Categories	Users	Actions

                     Loading Boards...

                    You are not assigned to any boards. Contact an admin user to be added to a board.
                    There are no current boards. Use the Add Board button below to add one.

                    {{ board.name }}

{{ lane.name }}
                                {{ lane.ownItem.length || 0 }}

{{ category.name }}

{{ user.username }}

                                <input type="checkbox" data-ng-checked="board.active == 1" data-ng-click="toggleActiveState(board.id)" title="Active Status">
                                Active

                                <input type="checkbox" data-ng-checked="board.active == 1" data-ng-click="toggleActiveState(board.id)" title="Active Status">
                                Inactive

 Add Board


text:
/*
 *
 * COPYRIGHT NVIDIA CORPORATION 2003. ALL RIGHTS RESERVED.
 * BY ACCESSING OR USING THIS SOFTWARE, YOU AGREE TO:
 *
 *  1) ACKNOWLEDGE NVIDIA'S EXCLUSIVE OWNERSHIP OF ALL RIGHTS
 *     IN AND TO THE SOFTWARE;
 *
 *  2) NOT MAKE OR DISTRIBUTE COPIES OF THE SOFTWARE WITHOUT
 *     INCLUDING THIS NOTICE AND AGREEMENT;
 *
 *  3) ACKNOWLEDGE THAT TO THE MAXIMUM EXTENT PERMITTED BY
 *     APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS* AND
 *     THAT NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES,
 *     EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED
 *     TO, IMPLIED WARRANTIES OF MERCHANTABILITY  AND FITNESS
 *     FOR A PARTICULAR PURPOSE.
 *
 * IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
 * SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES
 * WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS
 * OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS
 * INFORMATION, OR ANY OTHER PECUNIARY LOSS), INCLUDING ATTORNEYS'
 * FEES, RELATING TO THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 */

package demos.hwShadowmapsSimple;

import gleem.BSphere;
import gleem.BSphereProvider;
import gleem.CameraParameters;
import gleem.ExaminerViewer;
import gleem.HandleBoxManip;
import gleem.ManipManager;
import gleem.linalg.Mat4f;
import gleem.linalg.Rotf;
import gleem.linalg.Vec3f;

import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.ArrayList;

import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLDrawableFactory;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.GLException;
import javax.media.opengl.GLPbuffer;
import javax.media.opengl.GLProfile;
import javax.media.opengl.awt.AWTGLAutoDrawable;
import javax.media.opengl.awt.GLCanvas;
import javax.media.opengl.glu.GLU;
import javax.swing.JOptionPane;

import com.jogamp.opengl.util.gl2.GLUT;
import com.jogamp.opengl.util.texture.Texture;
import com.jogamp.opengl.util.texture.TextureIO;

import demos.common.Demo;
import demos.common.DemoListener;

/** This demo is a simple illustration of ARB_shadow and ARB_depth_texture.

    Cass Everitt

    12-11-00

    hw_shadowmaps_simple (c) 2001 NVIDIA Corporation

    Ported to Java by Kenneth Russell
*/

public class HWShadowmapsSimple extends Demo {
  public static void main(String[] args) {
    // set argument 'NotFirstUIActionOnProcess' in the JNLP's application-desc tag for example
    // <application-desc main-class="demos.j2d.TextCube"/>
    //   <argument>NotFirstUIActionOnProcess</argument>
    // </application-desc>
    boolean firstUIActionOnProcess = 0==args.length || !args[0].equals("NotFirstUIActionOnProcess") ;
    GLProfile.initSingleton();

    final GLCanvas canvas = new GLCanvas();
    final HWShadowmapsSimple demo = new HWShadowmapsSimple();
    canvas.addGLEventListener(demo);

    canvas.addKeyListener(new KeyAdapter() {
        public void keyPressed(KeyEvent e) {
          demo.dispatchKey(e.getKeyChar());
          demo.demoListener.repaint();
        }
      });

    demo.setDemoListener(new DemoListener() {
        public void shutdownDemo() {
          runExit();
        }
        public void repaint() {
          canvas.repaint();
        }
      });

    Frame frame = new Frame("ARB_shadow Shadows");
    frame.setLayout(new BorderLayout());
    canvas.setSize(512, 512);
    frame.add(canvas, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
    canvas.requestFocus();

    frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
          runExit();
        }
      });
  }

  //----------------------------------------------------------------------
  // Internals only below this point
  //

  public void shutdownDemo() {
    ManipManager.getManipManager().unregisterWindow((AWTGLAutoDrawable) drawable);
    drawable.removeGLEventListener(this);
    super.shutdownDemo();
  }

  private GLPbuffer pbuffer;

  private GLU  glu;
  private GLUT glut;

  private float[] light_ambient   = { 0, 0, 0, 0 };
  private float[] light_intensity = { 1, 1, 1, 1 };
  private float[] light_pos       = { 0, 0, 0, 1 };

  static class Tweak {
    String name;
    float val;
    float incr;

    Tweak(String name, float val, float incr) {
      this.name = name;
      this.val = val;
      this.incr = incr;
    }
  };
  private java.util.List/*<Tweak>*/ tweaks = new ArrayList();
  private static final int R_COORDINATE_SCALE   = 0;
  private static final int R_COORDINATE_BIAS    = 1;
  private static final int POLYGON_OFFSET_SCALE = 2;
  private static final int POLYGON_OFFSET_BIAS  = 3;
  private int curr_tweak;

  // Texture objects
  private static final int TEX_SIZE = 1024;
  private Texture decal;
  private Texture light_image;
  private int light_view_depth;

  // Depth buffer format
  private int depth_format;

  private boolean fullyInitialized;

  // Display mode
  private static final int RENDER_SCENE_FROM_CAMERA_VIEW = 0;
  private static final int RENDER_SCENE_FROM_CAMERA_VIEW_SHADOWED = 1;
  private static final int RENDER_SCENE_FROM_LIGHT_VIEW = 2;
  private static final int NUM_DISPLAY_MODES = 3;
  private int displayMode = 1;

  // Display lists
  private int quad;
  private int wirecube;
  private int geometry;

  // Shadowing light
  private float lightshaper_fovy  = 60.0f;
  private float lightshaper_zNear = 0.5f;
  private float lightshaper_zFar  = 5.0f;

  // Manipulators
  private GLAutoDrawable drawable;
  private ExaminerViewer viewer;
  private boolean  doViewAll = true;
  //  private float    zNear = 0.5f;
  //  private float    zFar  = 5.0f;
  private float    zNear = 0.5f;
  private float    zFar  = 50.0f;
  private HandleBoxManip object;
  private HandleBoxManip spotlight;
  private Mat4f cameraPerspective = new Mat4f();
  private Mat4f cameraTransform = new Mat4f();
  private Mat4f cameraInverseTransform = new Mat4f();
  private Mat4f spotlightTransform = new Mat4f();
  private Mat4f spotlightInverseTransform = new Mat4f();
  private Mat4f objectTransform = new Mat4f();
  private int viewportX;
  private int viewportY;

  public void init(GLAutoDrawable drawable) {
    // Use debug/trace pipeline
    /**
    GL _gl = drawable.getGL();
    // Debug ..
    _gl = _gl.getContext().setGL( GLPipelineFactory.create("javax.media.opengl.Debug", GL2.class, _gl, null) );
    // Trace ..
    _gl = _gl.getContext().setGL( GLPipelineFactory.create("javax.media.opengl.Trace", GL2.class, _gl, new Object[] { System.err } ) );
    */

    GL2 gl = drawable.getGL().getGL2();
    glu = new GLU();
    glut = new GLUT();

    try {
      checkExtension(gl, "GL_VERSION_1_3"); // For multitexture
      checkExtension(gl, "GL_ARB_depth_texture");
      checkExtension(gl, "GL_ARB_shadow");
      checkExtension(gl, "GL_ARB_pbuffer");
      checkExtension(gl, "GL_ARB_pixel_format");
    } catch (GLException e) {
      e.printStackTrace();
      throw(e);
    }

    gl.glClearColor(.5f, .5f, .5f, .5f);

    try {
      decal = TextureIO.newTexture(getClass().getClassLoader().getResourceAsStream("demos/data/images/decal_image.png"),
                                   true,
                                   TextureIO.PNG);
      decal.setTexParameteri(GL2.GL_TEXTURE_WRAP_S, GL2.GL_REPEAT);
      decal.setTexParameteri(GL2.GL_TEXTURE_WRAP_T, GL2.GL_REPEAT);
      light_image = TextureIO.newTexture(getClass().getClassLoader().getResourceAsStream("demos/data/images/nvlogo_spot.png"),
                                         true,
                                         TextureIO.PNG);
    } catch (IOException e) {
      throw new GLException(e);
    }

    quad = gl.glGenLists(1);
    gl.glNewList(quad, GL2.GL_COMPILE);
    gl.glPushMatrix();
    gl.glRotatef(-90, 1, 0, 0);
    gl.glScalef(4,4,4);
    gl.glBegin(GL2.GL_QUADS);
    gl.glNormal3f(0, 0, 1);
    gl.glVertex2f(-1, -1);
    gl.glVertex2f(-1,  1);
    gl.glVertex2f( 1,  1);
    gl.glVertex2f( 1, -1);
    gl.glEnd();
    gl.glPopMatrix();
    gl.glEndList();

    wirecube = gl.glGenLists(1);
    gl.glNewList(wirecube, GL2.GL_COMPILE);
    glut.glutWireCube(2);
    gl.glEndList();

    geometry = gl.glGenLists(1);
    gl.glNewList(geometry, GL2.GL_COMPILE);
    gl.glPushMatrix();
    glut.glutSolidTeapot(0.8f);
    gl.glPopMatrix();
    gl.glEndList();

    gl.glEnable(GL2.GL_LIGHT0);
    gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_AMBIENT, light_ambient, 0);
    gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_DIFFUSE, light_intensity, 0);
    gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_SPECULAR, light_intensity, 0);

    gl.glEnable(GL2.GL_DEPTH_TEST);

    // init pbuffer
    GLCapabilities caps = new GLCapabilities(gl.getGLProfile());
    caps.setDoubleBuffered(false);

    if (!GLDrawableFactory.getFactory(gl.getGLProfile()).canCreateGLPbuffer(null)) {
      unavailableExtension("Can not create pbuffer");
    }
    if (pbuffer != null) {
      pbuffer.destroy();
      pbuffer = null;
    }
    pbuffer = GLDrawableFactory.getFactory(gl.getGLProfile()).createGLPbuffer(caps, null, TEX_SIZE, TEX_SIZE, drawable.getContext());
    pbuffer.addGLEventListener(new PbufferListener());

    doViewAll = true;

    // Register the window with the ManipManager
    ManipManager manager = ManipManager.getManipManager();
    manager.registerWindow((AWTGLAutoDrawable) drawable);
    this.drawable = drawable;

    object = new HandleBoxManip();
    object.setTranslation(new Vec3f(0, 0.7f, 1.8f));
    object.setGeometryScale(new Vec3f(0.7f, 0.7f, 0.7f));
    manager.showManipInWindow(object, (AWTGLAutoDrawable) drawable);

    spotlight = new HandleBoxManip();
    spotlight.setScale(new Vec3f(0.5f, 0.5f, 0.5f));
    spotlight.setTranslation(new Vec3f(-0.25f, 2.35f, 5.0f));
    spotlight.setRotation(new Rotf(Vec3f.X_AXIS, (float) Math.toRadians(-30.0f)));
    manager.showManipInWindow(spotlight, (AWTGLAutoDrawable) drawable);

    viewer = new ExaminerViewer();
    viewer.setUpVector(Vec3f.Y_AXIS);
    viewer.attach((AWTGLAutoDrawable) drawable, new BSphereProvider() {
        public BSphere getBoundingSphere() {
          return new BSphere(object.getTranslation(), 2.0f);
        }
      });
    viewer.setOrientation(new Rotf(Vec3f.Y_AXIS, (float) Math.toRadians(45.0f)).times
                          (new Rotf(Vec3f.X_AXIS, (float) Math.toRadians(-15.0f))));
    viewer.setVertFOV((float) Math.toRadians(lightshaper_fovy / 2.0f));
    viewer.setZNear(zNear);
    viewer.setZFar(zFar);

    float bias = 1/((float) Math.pow(2.0,16.0)-1);

    tweaks.add(new Tweak("r coordinate scale",    0.5f, bias));
    tweaks.add(new Tweak("r coordinate bias",     0.5f, bias));
    tweaks.add(new Tweak("polygon offset scale",  2.5f, 0.5f));
    tweaks.add(new Tweak("polygon offset bias",  10.0f, 1.0f));

  }

  public void dispose(GLAutoDrawable drawable) {
    glu = null;
    glut = null;
  }

  public void display(GLAutoDrawable drawable) {
    viewer.update();

    // Grab these values once per render to avoid multithreading
    // issues with their values being changed by manipulation from
    // the AWT thread during the render
    CameraParameters params = viewer.getCameraParameters();

    cameraPerspective.set(params.getProjectionMatrix());
    cameraInverseTransform.set(params.getModelviewMatrix());
    cameraTransform.set(cameraInverseTransform);
    cameraTransform.invertRigid();
    spotlightTransform.set(spotlight.getTransform());
    spotlightInverseTransform.set(spotlightTransform);
    spotlightInverseTransform.invertRigid();
    objectTransform.set(object.getTransform());

    if (displayMode == RENDER_SCENE_FROM_CAMERA_VIEW_SHADOWED || !fullyInitialized) {
      if (pbuffer != null) {
        pbuffer.display();
      }
    }

    if (!fullyInitialized) {
      // Repaint again later once everything is set up
      demoListener.repaint();
      return;
    }

    GL2 gl = drawable.getGL().getGL2();

    gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT);

    if (doViewAll) {
      viewer.viewAll(gl);
      doViewAll = false;
      // Immediately zap effects
      gl.glMatrixMode(GL2.GL_PROJECTION);
      gl.glLoadIdentity();
      gl.glMatrixMode(GL2.GL_MODELVIEW);
      gl.glLoadIdentity();
      // Schedule repaint to clean up first bogus frame
      demoListener.repaint();
    }

    switch (displayMode) {
    case RENDER_SCENE_FROM_CAMERA_VIEW:          render_scene_from_camera_view(gl, drawable, params); break;
    case RENDER_SCENE_FROM_CAMERA_VIEW_SHADOWED: render_scene_from_camera_view_shadowed(gl, drawable, params); break;
    case RENDER_SCENE_FROM_LIGHT_VIEW:           render_scene_from_light_view(gl, drawable, viewportX, viewportY); break;
    default: throw new RuntimeException("Illegal display mode " + displayMode);
    }
  }

  // Unused routines
  public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
    viewportX = x;
    viewportY = y;
  }
  public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) {}

  private void checkExtension(GL2 gl, String extensionName) {
    if (!gl.isExtensionAvailable(extensionName)) {
      String message = "Unable to initialize " + extensionName + " OpenGL extension";
      unavailableExtension(message);
    }
  }

  private void unavailableExtension(String message) {
    JOptionPane.showMessageDialog(null, message, "Unavailable extension", JOptionPane.ERROR_MESSAGE);
    throw new GLException(message);
  }

  private void dispatchKey(char k) {
    switch (k) {
    case 27:
    case 'q':
      shutdownDemo();
      break;

    case 'v':
      doViewAll = true;
      System.err.println("Forcing viewAll()");
      break;

    case ' ':
      displayMode = (displayMode + 1) % NUM_DISPLAY_MODES;
      System.err.println("Switching to display mode " + displayMode);
      break;

      // FIXME: add more key behaviors from original demo

    default:
      break;
    }
  }

  class PbufferListener implements GLEventListener {
    public void init(GLAutoDrawable drawable) {
      // Use debug pipeline
      // drawable.setGL(new DebugGL(drawable.getGL()));

      GL2 gl = drawable.getGL().getGL2();

      gl.glEnable(GL2.GL_DEPTH_TEST);

      int[] depth_bits = new int[1];
      gl.glGetIntegerv(GL2.GL_DEPTH_BITS, depth_bits, 0);

      if (depth_bits[0] == 16)  depth_format = GL2.GL_DEPTH_COMPONENT16;
      else                      depth_format = GL2.GL_DEPTH_COMPONENT24;

      light_view_depth = genTexture(gl);
      gl.glBindTexture(GL2.GL_TEXTURE_2D, light_view_depth);
      gl.glTexImage2D(GL2.GL_TEXTURE_2D, 0, depth_format, TEX_SIZE, TEX_SIZE, 0,
                      GL2.GL_DEPTH_COMPONENT, GL2.GL_UNSIGNED_INT, null);
      set_light_view_texture_parameters(gl);

      fullyInitialized = true;
    }

    public void dispose(GLAutoDrawable drawable) {
    }

    public void display(GLAutoDrawable drawable) {
      GL2 gl = drawable.getGL().getGL2();

      gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT);

      gl.glPolygonOffset(((Tweak) tweaks.get(POLYGON_OFFSET_SCALE)).val,
                         ((Tweak) tweaks.get(POLYGON_OFFSET_BIAS)).val);
      gl.glEnable(GL2.GL_POLYGON_OFFSET_FILL);

      render_scene_from_light_view(gl, drawable, 0, 0);

      gl.glDisable(GL2.GL_POLYGON_OFFSET_FILL);

      gl.glBindTexture(GL2.GL_TEXTURE_2D, light_view_depth);

      // trying different ways of getting the depth info over
      gl.glCopyTexSubImage2D(GL2.GL_TEXTURE_2D, 0,   0, 0,   0, 0,  TEX_SIZE, TEX_SIZE);
    }

    // Unused routines
    public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {}
    public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) {}
  }

  private void set_light_view_texture_parameters(GL2 gl) {
    gl.glBindTexture(GL2.GL_TEXTURE_2D, light_view_depth);
    gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MIN_FILTER, GL2.GL_LINEAR);
    gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR);
    gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_WRAP_S, GL2.GL_CLAMP_TO_EDGE);
    gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_WRAP_T, GL2.GL_CLAMP_TO_EDGE);
    gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_COMPARE_MODE, GL2.GL_COMPARE_R_TO_TEXTURE);
    gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_COMPARE_FUNC, GL2.GL_LEQUAL);
  }

  private int genTexture(GL2 gl) {
    int[] tmp = new int[1];
    gl.glGenTextures(1, tmp, 0);
    return tmp[0];
  }

  private void eye_linear_texgen(GL2 gl) {
    Mat4f m = new Mat4f();
    m.makeIdent();

    set_texgen_planes(gl, GL2.GL_EYE_PLANE, m);
    gl.glTexGeni(GL2.GL_S, GL2.GL_TEXTURE_GEN_MODE, GL2.GL_EYE_LINEAR);
    gl.glTexGeni(GL2.GL_T, GL2.GL_TEXTURE_GEN_MODE, GL2.GL_EYE_LINEAR);
    gl.glTexGeni(GL2.GL_R, GL2.GL_TEXTURE_GEN_MODE, GL2.GL_EYE_LINEAR);
    gl.glTexGeni(GL2.GL_Q, GL2.GL_TEXTURE_GEN_MODE, GL2.GL_EYE_LINEAR);
  }

  private void obj_linear_texgen(GL2 gl) {
    Mat4f m = new Mat4f();
    m.makeIdent();

    set_texgen_planes(gl, GL2.GL_OBJECT_PLANE, m);
    gl.glTexGeni(GL2.GL_S, GL2.GL_TEXTURE_GEN_MODE, GL2.GL_OBJECT_LINEAR);
    gl.glTexGeni(GL2.GL_T, GL2.GL_TEXTURE_GEN_MODE, GL2.GL_OBJECT_LINEAR);
    gl.glTexGeni(GL2.GL_R, GL2.GL_TEXTURE_GEN_MODE, GL2.GL_OBJECT_LINEAR);
    gl.glTexGeni(GL2.GL_Q, GL2.GL_TEXTURE_GEN_MODE, GL2.GL_OBJECT_LINEAR);
  }

  private void set_texgen_planes(GL2 gl, int plane_type, Mat4f m) {
    int[] coord = {GL2.GL_S, GL2.GL_T, GL2.GL_R, GL2.GL_Q};
    float[] row = new float[4];
    for(int i = 0; i < 4; i++) {
      getRow(m, i, row);
      gl.glTexGenfv(coord[i], plane_type, row, 0);
    }
  }

  private void texgen(GL2 gl, boolean enable) {
    if(enable) {
      gl.glEnable(GL2.GL_TEXTURE_GEN_S);
      gl.glEnable(GL2.GL_TEXTURE_GEN_T);
      gl.glEnable(GL2.GL_TEXTURE_GEN_R);
      gl.glEnable(GL2.GL_TEXTURE_GEN_Q);
    } else {
      gl.glDisable(GL2.GL_TEXTURE_GEN_S);
      gl.glDisable(GL2.GL_TEXTURE_GEN_T);
      gl.glDisable(GL2.GL_TEXTURE_GEN_R);
      gl.glDisable(GL2.GL_TEXTURE_GEN_Q);
    }
  }

  private void render_light_frustum(GL2 gl) {
    gl.glPushMatrix();
    applyTransform(gl, cameraInverseTransform);
    applyTransform(gl, spotlightTransform);
    applyTransform(gl, perspectiveInverse(lightshaper_fovy, 1, lightshaper_zNear, lightshaper_zFar));
    gl.glDisable(GL2.GL_LIGHTING);
    gl.glColor3f(1,1,0);
    gl.glCallList(wirecube);
    gl.glColor3f(1,1,1);
    gl.glEnable(GL2.GL_LIGHTING);
    gl.glPopMatrix();
  }

  private void render_quad(GL2 gl) {
    gl.glActiveTexture(GL2.GL_TEXTURE0);
    obj_linear_texgen(gl);
    texgen(gl, true);
    gl.glMatrixMode(GL2.GL_TEXTURE);
    gl.glLoadIdentity();
    gl.glScalef(4,4,1);
    gl.glMatrixMode(GL2.GL_MODELVIEW);

    gl.glDisable(GL2.GL_LIGHTING);
    decal.bind();
    decal.enable();
    gl.glCallList(quad);
    decal.disable();
    gl.glEnable(GL2.GL_LIGHTING);

    texgen(gl, false);
    gl.glMatrixMode(GL2.GL_TEXTURE);
    gl.glLoadIdentity();
    gl.glMatrixMode(GL2.GL_MODELVIEW);
  }

  private void render_scene(GL2 gl, Mat4f view, GLAutoDrawable drawable, CameraParameters params) {
    gl.glColor3f(1,1,1);
    gl.glPushMatrix();
    Mat4f inverseView = new Mat4f(view);
    inverseView.invertRigid();
    applyTransform(gl, inverseView);

    gl.glPushMatrix();
    render_quad(gl);

    applyTransform(gl, objectTransform);

    gl.glEnable(GL2.GL_LIGHTING);
    gl.glCallList(geometry);
    gl.glDisable(GL2.GL_LIGHTING);

    gl.glPopMatrix();

    gl.glPopMatrix();
  }

  private void render_manipulators(GL2 gl, Mat4f view, GLAutoDrawable drawable, CameraParameters params) {
    gl.glColor3f(1,1,1);
    gl.glPushMatrix();
    Mat4f inverseView = new Mat4f(view);
    inverseView.invertRigid();
    applyTransform(gl, inverseView);

    if (params != null) {
      ManipManager.getManipManager().updateCameraParameters((AWTGLAutoDrawable) drawable, params);
      ManipManager.getManipManager().render((AWTGLAutoDrawable) drawable, gl);
    }

    gl.glPopMatrix();
  }

  private void render_scene_from_camera_view(GL2 gl, GLAutoDrawable drawable, CameraParameters params) {
    // place light
    gl.glPushMatrix();
    gl.glLoadIdentity();
    applyTransform(gl, cameraInverseTransform);
    applyTransform(gl, spotlightTransform);
    gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_POSITION, light_pos, 0);
    gl.glPopMatrix();

    // spot image
    gl.glActiveTexture(GL2.GL_TEXTURE1);

    gl.glPushMatrix();
    applyTransform(gl, cameraInverseTransform);
    eye_linear_texgen(gl);
    texgen(gl, true);
    gl.glPopMatrix();

    gl.glMatrixMode(GL2.GL_TEXTURE);
    gl.glLoadIdentity();
    gl.glTranslatef(.5f, .5f, .5f);
    gl.glScalef(.5f, -.5f, .5f);
    glu.gluPerspective(lightshaper_fovy, 1, lightshaper_zNear, lightshaper_zFar);
    applyTransform(gl, spotlightInverseTransform);
    gl.glMatrixMode(GL2.GL_MODELVIEW);

    light_image.bind();
    light_image.enable();
    gl.glTexEnvi(GL2.GL_TEXTURE_ENV, GL2.GL_TEXTURE_ENV_MODE, GL2.GL_MODULATE);

    gl.glActiveTexture(GL2.GL_TEXTURE0);
    gl.glMatrixMode(GL2.GL_PROJECTION);
    gl.glLoadIdentity();
    gl.glViewport(viewportX, viewportY, drawable.getWidth(), drawable.getHeight());
    applyTransform(gl, cameraPerspective);
    gl.glMatrixMode(GL2.GL_MODELVIEW);
    render_scene(gl, cameraTransform, drawable, params);

    gl.glActiveTexture(GL2.GL_TEXTURE1);
    light_image.disable();
    gl.glActiveTexture(GL2.GL_TEXTURE0);

    render_manipulators(gl, cameraTransform, drawable, params);

    render_light_frustum(gl);
  }

  private void render_scene_from_camera_view_shadowed(GL2 gl, GLAutoDrawable drawable, CameraParameters params) {
    // place light
    gl.glPushMatrix();
    gl.glLoadIdentity();
    applyTransform(gl, cameraInverseTransform);
    applyTransform(gl, spotlightTransform);
    gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_POSITION, light_pos, 0);
    gl.glPopMatrix();

    // spot image
    gl.glActiveTexture(GL2.GL_TEXTURE1);

    gl.glPushMatrix();
    applyTransform(gl, cameraInverseTransform);
    eye_linear_texgen(gl);
    texgen(gl, true);
    gl.glPopMatrix();

    gl.glMatrixMode(GL2.GL_TEXTURE);
    gl.glLoadIdentity();
    gl.glTranslatef(.5f, .5f, .5f);
    gl.glScalef(.5f, -.5f, .5f);
    glu.gluPerspective(lightshaper_fovy, 1, lightshaper_zNear, lightshaper_zFar);
    applyTransform(gl, spotlightInverseTransform);
    gl.glMatrixMode(GL2.GL_MODELVIEW);

    light_image.bind();
    light_image.enable();
    gl.glTexEnvi(GL2.GL_TEXTURE_ENV, GL2.GL_TEXTURE_ENV_MODE, GL2.GL_MODULATE);

    // depth compare
    gl.glActiveTexture(GL2.GL_TEXTURE2);

    gl.glPushMatrix();
    applyTransform(gl, cameraInverseTransform);
    eye_linear_texgen(gl);
    texgen(gl, true);
    gl.glPopMatrix();

    gl.glMatrixMode(GL2.GL_TEXTURE);
    gl.glLoadIdentity();
    gl.glTranslatef(.5f, .5f, ((Tweak) tweaks.get(R_COORDINATE_SCALE)).val);
    gl.glScalef(.5f, .5f, ((Tweak) tweaks.get(R_COORDINATE_BIAS)).val);
    glu.gluPerspective(lightshaper_fovy, 1, lightshaper_zNear, lightshaper_zFar);
    applyTransform(gl, spotlightInverseTransform);
    gl.glMatrixMode(GL2.GL_MODELVIEW);

    gl.glBindTexture(GL2.GL_TEXTURE_2D, light_view_depth);
    gl.glEnable(GL2.GL_TEXTURE_2D);
    gl.glTexEnvi(GL2.GL_TEXTURE_ENV, GL2.GL_TEXTURE_ENV_MODE, GL2.GL_MODULATE);

    gl.glActiveTexture(GL2.GL_TEXTURE0);

    gl.glMatrixMode(GL2.GL_PROJECTION);
    gl.glLoadIdentity();
    gl.glViewport(viewportX, viewportY, drawable.getWidth(), drawable.getHeight());
    applyTransform(gl, cameraPerspective);
    gl.glMatrixMode(GL2.GL_MODELVIEW);
    render_scene(gl, cameraTransform, drawable, params);

    gl.glActiveTexture(GL2.GL_TEXTURE1);
    light_image.disable();
    gl.glActiveTexture(GL2.GL_TEXTURE2);
    gl.glDisable(GL2.GL_TEXTURE_2D);
    gl.glActiveTexture(GL2.GL_TEXTURE0);

    render_manipulators(gl, cameraTransform, drawable, params);

    render_light_frustum(gl);
  }

  private void largest_square_power_of_two_viewport(GL2 gl, GLAutoDrawable drawable, int viewportX, int viewportY) {
    float min = Math.min(drawable.getWidth(), drawable.getHeight());
    float log2min = (float) Math.log(min) / (float) Math.log(2.0);
    float pow2 = (float) Math.floor(log2min);
    int size = 1 << (int) pow2;
    gl.glViewport(viewportX, viewportY, size, size);
  }

  private void render_scene_from_light_view(GL2 gl, GLAutoDrawable drawable, int viewportX, int viewportY) {
    // place light
    gl.glPushMatrix();
    gl.glLoadIdentity();
    gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_POSITION, light_pos, 0);
    gl.glPopMatrix();

    // spot image
    gl.glActiveTexture(GL2.GL_TEXTURE1);

    gl.glPushMatrix();
    eye_linear_texgen(gl);
    texgen(gl, true);
    gl.glPopMatrix();

    gl.glMatrixMode(GL2.GL_TEXTURE);
    gl.glLoadIdentity();
    gl.glTranslatef(.5f, .5f, .5f);
    gl.glScalef(.5f, .5f, .5f);
    glu.gluPerspective(lightshaper_fovy, 1, lightshaper_zNear, lightshaper_zFar);
    gl.glMatrixMode(GL2.GL_MODELVIEW);

    light_image.bind();
    light_image.enable();
    gl.glTexEnvi(GL2.GL_TEXTURE_ENV, GL2.GL_TEXTURE_ENV_MODE, GL2.GL_MODULATE);

    gl.glActiveTexture(GL2.GL_TEXTURE0);

    gl.glViewport(0, 0, TEX_SIZE, TEX_SIZE);
    gl.glMatrixMode(GL2.GL_PROJECTION);
    gl.glLoadIdentity();
    glu.gluPerspective(lightshaper_fovy, 1, lightshaper_zNear, lightshaper_zFar);
    gl.glMatrixMode(GL2.GL_MODELVIEW);
    if (displayMode == RENDER_SCENE_FROM_LIGHT_VIEW)
      largest_square_power_of_two_viewport(gl, drawable, viewportX, viewportY);
    render_scene(gl, spotlightTransform, null, null);

    gl.glActiveTexture(GL2.GL_TEXTURE1);
    light_image.disable();
    gl.glActiveTexture(GL2.GL_TEXTURE0);
  }

  private static void getRow(Mat4f m, int row, float[] out) {
    out[0] = m.get(row, 0);
    out[1] = m.get(row, 1);
    out[2] = m.get(row, 2);
    out[3] = m.get(row, 3);
  }

  private static void applyTransform(GL2 gl, Mat4f xform) {
    float[] data = new float[16];
    xform.getColumnMajorData(data);
    gl.glMultMatrixf(data, 0);
  }

  private static Mat4f perspectiveInverse(float fovy, float aspect, float zNear, float zFar) {
    float tangent = (float) Math.tan(Math.toRadians(fovy / 2.0));
    float y = tangent * zNear;
    float x = aspect * y;
    return frustumInverse(-x, x, -y, y, zNear, zFar);
  }

  private static Mat4f frustumInverse(float left, float right,
                               float bottom, float top,
                               float zNear, float zFar) {
    Mat4f m = new Mat4f();
    m.makeIdent();

    m.set(0, 0, (right - left) / (2 * zNear));
    m.set(0, 3, (right + left) / (2 * zNear));

    m.set(1, 1, (top - bottom) / (2 * zNear));
    m.set(1, 3, (top + bottom) / (2 * zNear));

    m.set(2, 2,  0);
    m.set(2, 3, -1);

    m.set(3, 2, -(zFar - zNear) / (2 * zFar * zNear));
    m.set(3, 3,  (zFar + zNear) / (2 * zFar * zNear));

    return m;
  }

  private static void runExit() {
    // Note: calling System.exit() synchronously inside the draw,
    // reshape or init callbacks can lead to deadlocks on certain
    // platforms (in particular, X11) because the JAWT's locking
    // routines cause a global AWT lock to be grabbed. Run the
    // exit routine in another thread.
    new Thread(new Runnable() {
        public void run() {
          System.exit(0);
        }
      }).start();
  }
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use dektrium\user\widgets\Connect;

/**
 * @var yii\web\View $this
 * @var yii\widgets\ActiveForm $form
 * @var dektrium\user\models\User $user
 */

$this->title = Yii::t('user', 'Sign up');
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

                <?php $form = ActiveForm::begin([
                    'id' => 'registration-form',
                ]); ?>

                <?= Connect::widget([
                    'baseAuthUrl' => ['/user/security/auth']
                ]) ?>

                <?= $form->field($model, 'username') ?>

                <?= $form->field($model, 'email') ?>

                <?php if (Yii::$app->getModule('user')->enableGeneratingPassword == false): ?>
                    <?= $form->field($model, 'password')->passwordInput() ?>
                <?php endif ?>

                <?= Html::submitButton(Yii::t('user', 'Sign up'), ['class' => 'btn btn-success btn-block']) ?>

                <?php ActiveForm::end(); ?>

            <?= Html::a(Yii::t('user', 'Already registered? Sign in!'), ['/user/security/login']) ?>


text:
#include <stdarg.h>

#include "windef.h"
#include "winbase.h"
#include "winerror.h"
#include "winreg.h"

#include "wingdi.h"
#include "winspool.h"
#include "ddk/winsplp.h"
#include "spoolss.h"

#include "wine/debug.h"

WINE_DEFAULT_DEBUG_CHANNEL(spoolss);

/* ################################ */

static HMODULE hwinspool;

static const WCHAR winspooldrvW[] = {'w','i','n','s','p','o','o','l','.','d','r','v',0};

/******************************************************************************
 *
 */
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
    TRACE("(%p, %d, %p)\n", hinstDLL, fdwReason, lpvReserved);

    switch (fdwReason) {
        case DLL_WINE_PREATTACH:
            return FALSE;  /* prefer native version */
        case DLL_PROCESS_ATTACH: {
            DisableThreadLibraryCalls(hinstDLL);
            break;

        case DLL_PROCESS_DETACH:
            if (lpvReserved) break;
            backend_unload_all();
            break;
        }
    }
    return TRUE;
}

/******************************************************************
 *   AllocSplStr   [SPOOLSS.@]
 *
 * Create a copy from the String on the Spooler-Heap
 *
 * PARAMS
 *  pwstr [I] PTR to the String to copy
 *
 * RETURNS
 *  Failure: NULL
 *  Success: PTR to the copied String
 *
 */
LPWSTR WINAPI AllocSplStr(LPCWSTR pwstr)
{
    LPWSTR  res = NULL;
    DWORD   len;

    TRACE("(%s)\n", debugstr_w(pwstr));
    if (!pwstr) return NULL;

    len = (lstrlenW(pwstr) + 1) * sizeof(WCHAR);
    res = HeapAlloc(GetProcessHeap(), 0, len);
    if (res) lstrcpyW(res, pwstr);

    TRACE("returning %p\n", res);
    return res;
}

/******************************************************************
 *   BuildOtherNamesFromMachineName   [SPOOLSS.@]
 */
BOOL WINAPI BuildOtherNamesFromMachineName(LPVOID * ptr1, LPVOID * ptr2)
{
    FIXME("(%p, %p) stub\n", ptr1, ptr2);

    *ptr1 = NULL;
    *ptr2 = NULL;
    return FALSE;
}

/******************************************************************
 *   DllAllocSplMem   [SPOOLSS.@]
 *
 * Allocate cleared memory from the spooler heap
 *
 * PARAMS
 *  size [I] Number of bytes to allocate
 *
 * RETURNS
 *  Failure: NULL
 *  Success: PTR to the allocated memory
 *
 * NOTES
 *  We use the process heap (Windows use a separate spooler heap)
 *
 */
LPVOID WINAPI DllAllocSplMem(DWORD size)
{
    LPVOID  res;

    res = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size);
    TRACE("(%d) => %p\n", size, res);
    return res;
}

/******************************************************************
 *   DllFreeSplMem   [SPOOLSS.@]
 *
 * Free the allocated spooler memory
 *
 * PARAMS
 *  memory [I] PTR to the memory allocated by DllAllocSplMem
 *
 * RETURNS
 *  Failure: FALSE
 *  Success: TRUE
 *
 * NOTES
 *  We use the process heap (Windows use a separate spooler heap)
 *
 */

BOOL WINAPI DllFreeSplMem(LPBYTE memory)
{
    TRACE("(%p)\n", memory);
    return HeapFree(GetProcessHeap(), 0, memory);
}

/******************************************************************
 *   DllFreeSplStr   [SPOOLSS.@]
 *
 * Free the allocated Spooler-String
 *
 * PARAMS
 *  pwstr [I] PTR to the WSTR, allocated by AllocSplStr
 *
 * RETURNS
 *  Failure: FALSE
 *  Success: TRUE
 *
 */

BOOL WINAPI DllFreeSplStr(LPWSTR pwstr)
{
    TRACE("(%s) PTR: %p\n", debugstr_w(pwstr), pwstr);
    return HeapFree(GetProcessHeap(), 0, pwstr);
}

/******************************************************************
 *   ImpersonatePrinterClient   [SPOOLSS.@]
 */
BOOL WINAPI ImpersonatePrinterClient(HANDLE hToken)
{
    FIXME("(%p) stub\n", hToken);
    return TRUE;
}

/******************************************************************
 *   InitializeRouter   [SPOOLSS.@]
 */
BOOL WINAPI InitializeRouter(void)
{
    TRACE("()\n");
    return backend_load_all();
}

/******************************************************************
 *   IsLocalCall    [SPOOLSS.@]
 */
BOOL WINAPI IsLocalCall(void)
{
    FIXME("() stub\n");
    return TRUE;
}

/******************************************************************
 *   RevertToPrinterSelf   [SPOOLSS.@]
 */
HANDLE WINAPI RevertToPrinterSelf(void)
{
    FIXME("() stub\n");
    return (HANDLE) 0xdead0947;
}

/******************************************************************
 *   SplInitializeWinSpoolDrv   [SPOOLSS.@]
 *
 * Dynamic load "winspool.drv" and fill an array with some function-pointer
 *
 * PARAMS
 *  table  [I] array of function-pointer to fill
 *
 * RETURNS
 *  Success: TRUE
 *  Failure: FALSE
 *
 * NOTES
 *  Native "spoolss.dll" from w2k fill the table with 11 Function-Pointer.
 *  We implement the XP-Version (The table has only 9 Pointer)
 *
 */
BOOL WINAPI SplInitializeWinSpoolDrv(LPVOID * table)
{
    DWORD res;

    TRACE("(%p)\n", table);

    hwinspool = LoadLibraryW(winspooldrvW);
    if (!hwinspool) return FALSE;

    table[0] = (void *) GetProcAddress(hwinspool, "OpenPrinterW");
    table[1] = (void *) GetProcAddress(hwinspool, "ClosePrinter");
    table[2] = (void *) GetProcAddress(hwinspool, "SpoolerDevQueryPrintW");
    table[3] = (void *) GetProcAddress(hwinspool, "SpoolerPrinterEvent");
    table[4] = (void *) GetProcAddress(hwinspool, "DocumentPropertiesW");
    table[5] = (void *) GetProcAddress(hwinspool, (LPSTR) 212);  /* LoadPrinterDriver */
    table[6] = (void *) GetProcAddress(hwinspool, (LPSTR) 213);  /* RefCntLoadDriver */
    table[7] = (void *) GetProcAddress(hwinspool, (LPSTR) 214);  /* RefCntUnloadDriver */
    table[8] = (void *) GetProcAddress(hwinspool, (LPSTR) 215);  /* ForceUnloadDriver */

    for (res = 0; res < 9; res++) {
        if (table[res] == NULL) return FALSE;
    }

    return TRUE;

}

/******************************************************************
 *   SplIsUpgrade   [SPOOLSS.@]
 */
BOOL WINAPI SplIsUpgrade(void)
{
    FIXME("() stub\n");
    return FALSE;
}

/******************************************************************
 *   SpoolerHasInitialized  [SPOOLSS.@]
 */
BOOL WINAPI SpoolerHasInitialized(void)
{
    FIXME("() stub\n");
    return TRUE;
}

/******************************************************************
 *   SpoolerInit   [SPOOLSS.@]
 */
BOOL WINAPI SpoolerInit(void)
{
    FIXME("() stub\n");
    return TRUE;
}

/******************************************************************
 *   WaitForSpoolerInitialization   [SPOOLSS.@]
 */
BOOL WINAPI WaitForSpoolerInitialization(void)
{
    FIXME("() stub\n");
    return TRUE;
}


text:
namespace open {
	class FileSource;
	class ThreadPool;

	class TerrainSource {
	public:
		using TileResponse = Response<TerrainData>::Ptr;
		using GetTerrainDataCallback = std::function<void(TileResponse)>;

	public:
		TerrainSource(FileSource& fileSource, ThreadPool& threadPool);
		~TerrainSource();

		virtual void getTerrainData(const TileID&, GetTerrainDataCallback&&);
	private:
		class Imp;
		Imp* _imp;
	};
}

#endif


text:
require_relative '../helper'

require_relative '../../lib/sidekiq-spy'

def start_and_stop_app(app)
  app_thread = Thread.new { app.start }

  sleep 1 # patience, patience; give app time to start

  app.stop

  app_thread.join(2)

  Thread.kill(app_thread)
end

describe SidekiqSpy::App do

  before do
    @screen = stub(
      :close     => nil,
      :refresh   => nil,
      :next_key  => nil,
      :missized? => nil
    )

    SidekiqSpy::Display::Screen.stubs(:new).returns(@screen)

    @app = SidekiqSpy::App.new
  end

  it "sets status not-running" do
    @app.running.must_equal false
  end

  it "sets status not-restarting" do
    @app.restarting.must_equal false
  end

  describe "#configure" do
    it "configures Sidekiq" do
      Sidekiq.expects(:configure_client)

      @app.configure {  }
    end
  end

  describe "configure block main" do
    before do
      @app.configure do |c|
        c.namespace = 'resque'
        c.interval  = 1
      end

      @config = @app.config
    end

    it "configures namespace" do
      @config.namespace.must_equal 'resque'
    end

    it "configures interval" do
      @config.interval.must_equal 1
    end
  end

  describe "configure block url" do
    before do
      @app.configure do |c|
        c.url = 'redis://da.example.com:237/42'
      end

      @config = @app.config
    end

    it "configures host" do
      @config.host.must_equal 'da.example.com'
    end

    it "configures port" do
      @config.port.must_equal 237
    end

    it "configures database" do
      @config.database.must_equal 42
    end
  end

  describe "configure block url-brief" do
    before do
      @app.configure do |c|
        c.url = 'redis://da.example.com'
      end

      @config = @app.config
    end

    it "configures host" do
      @config.host.must_equal 'da.example.com'
    end

    it "configures port" do
      @config.port.must_equal 6379
    end

    it "configures database" do
      @config.database.must_equal 0
    end
  end

  describe "configure block non-url" do
    before do
      @app.configure do |c|
        c.host      = 'da.example.com'
        c.port      = 237
        c.database  = 42
      end

      @config = @app.config
    end

    it "configures host" do
      @config.host.must_equal 'da.example.com'
    end

    it "configures port" do
      @config.port.must_equal 237
    end

    it "configures database" do
      @config.database.must_equal 42
    end
  end

  describe "#start" do
    before do
      @app.configure do |c|
        c.interval = 10
      end
    end

    it "sets status running within 1s" do
      thread_app = Thread.new { @app.start }

      sleep 1 # patience, patience; give app time to start

      @app.running.must_equal true

      Thread.kill(thread_app)
    end

    it "stops running within 1s" do
      thread_app = Thread.new { @app.start }

      sleep 1 # patience, patience; give app time to start

      @app.stop; t0 = Time.now

      thread_app.join(2)

      Thread.kill(thread_app)

      assert_operator (Time.now - t0), :<=, 1
    end

    it "calls #setup hook" do
      @app.expects(:setup)

      start_and_stop_app(@app)
    end

    it "calls #refresh on screen" do
      @screen.expects(:refresh)

      start_and_stop_app(@app)
    end

    it "calls #next_key on screen" do
      @screen.expects(:next_key).at_least_once

      start_and_stop_app(@app)
    end

    it "calls #cleanup hook" do
      @app.expects(:cleanup)

      start_and_stop_app(@app)
    end
  end

  describe "#stop" do
    before do
      @app.instance_variable_set(:@running, true)
    end

    it "sets status not-running" do
      @app.stop

      @app.running.must_equal false
    end
  end

  describe "#restart" do
    before do
      @app.instance_variable_set(:@restarting, false)
    end

    it "sets status restarting" do
      @app.restart

      @app.restarting.must_equal true
    end
  end

  describe "#do_command" do
    before do
      @app.instance_variable_set(:@running, true)
      @app.instance_variable_set(:@screen, @screen)
    end

    it "<q> sets status not-running" do
      @app.do_command('q')

      @app.running.must_equal false
    end

    it "<w> switches to Workers panel" do
      @screen.expects(:panel_main=).with(:workers)

      @app.do_command('w')
    end

    it "<u> switches to Queues panel" do
      @screen.expects(:panel_main=).with(:queues)

      @app.do_command('u')
    end
  end

end


text:
package jp.gr.java_conf.a_kura.chatter.message;

public class HashTagSegment extends MessageSegment {

	private String type = "Hashtag";
	private String tag;

	public HashTagSegment() {
		this.tag = "";
	}

	public HashTagSegment(String tag) {
		this.tag = tag;
	}

	public String getTag() {
		return tag;
	}

	@Override
	public String getType() {
		return type;
	}

}


text:
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(_dereq_,module,exports){
'use strict';

mejs.i18n.en['mejs.time-skip-back'] = ['Skip back 1 second', 'Skip back %1 seconds'];

Object.assign(mejs.MepDefaults, {
	skipBackInterval: 30,

	skipBackText: null
});

Object.assign(MediaElementPlayer.prototype, {
	buildskipback: function buildskipback(player, controls, layers, media) {
		var t = this,
		    defaultTitle = mejs.i18n.t('mejs.time-skip-back', t.options.skipBackInterval),
		    skipTitle = mejs.Utils.isString(t.options.skipBackText) ? t.options.skipBackText.replace('%1', t.options.skipBackInterval) : defaultTitle,
		    button = document.createElement('div');

		button.className = t.options.classPrefix + 'button ' + t.options.classPrefix + 'skip-back-button';
		button.innerHTML = '<button type="button" aria-controls="' + t.id + '" title="' + skipTitle + '" aria-label="' + skipTitle + '" tabindex="0">' + t.options.skipBackInterval + '</button>';

		t.addControlElement(button, 'skipback');

		button.addEventListener('click', function () {
			var duration = !isNaN(media.duration) ? media.duration : t.options.skipBackInterval;
			if (duration) {
				var current = media.currentTime === Infinity ? 0 : media.currentTime;
				media.setCurrentTime(Math.max(current - t.options.skipBackInterval, 0));
				this.querySelector('button').blur();
			}
		});
	}
});

},{}]},{},[1]);