text:
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Component, EventEmitter, Input, Output, ViewEncapsulation } from "@angular/core";
let DatetimePickerComponent = class DatetimePickerComponent {
    constructor() {
        this.allMonths = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
        this.showMonths = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
        this.allYears = [];
        this.pickerChange = new EventEmitter();
        this.rows = [0, 1, 2, 3, 4, 5];
        this.cols = [1, 2, 3, 4, 5, 6, 7];
        this.weekdays = [0, 1, 2, 3, 4, 5, 6];
        this.bind = {};
        this.lastDateSet = {
            year: this.year,
            month: this.month,
            day: this.day,
            hour: this.hour,
            minute: this.minute,
            second: this.second,
            date: new Date(),
            getDateWithoutTime() {
                let tempDate = new Date(this.date);
                tempDate.setHours(0, 0, 0, 0);
                return tempDate;
            },
        };
        this.monthLeftDisable = false;
        this.monthRightDisable = false;
        let currentYear = new Date().getFullYear();
        this.lastYear;
        for (var i = 0; i < 7; i++) {
            if (this.allYears.indexOf(currentYear + i) < 0) {
                this.allYears.push(currentYear + i);
            }
            if (i == 6) {
                this.lastYear = currentYear + i;
            }
        }
    }
    ngOnInit() {
        let currentMonth = new Date().getMonth();
        this.showMonths.splice(0, currentMonth);
        if (this.dateEnabled) {
            let today = new Date();
            this.today = {
                day: today.getDate(),
                month: today.getMonth(),
                year: today.getFullYear(),
            };
        }
        if (this.isMondayFirst) {
            this.weekdays = [1, 2, 3, 4, 5, 6, 0];
        }
        this.processModel();
    }
    getMonthDisplay() {
        let year = new Date().getFullYear();
        if (this.bind.year) {
            if (this.bind.year > year) {
                return this.allMonths;
            }
            else {
                return this.showMonths;
            }
        }
        else {
            return this.showMonths;
        }
    }
    getMonthNumber(index) {
        let year = new Date().getFullYear();
        if (this.bind.year) {
            if (this.bind.year > year) {
                return index;
            }
            else {
                return index + (new Date().getMonth());
            }
        }
        else {
            return index + (new Date().getMonth());
        }
    }
    cellDay(x, y) {
        return y * 7 + x - this.firstDay;
    }
    isDayHidden(x, y) {
        let cellDay = this.cellDay(x, y);
        return cellDay <= 0 || cellDay > this.daysInMonth;
    }
    processModel() {
        let date = this.modelDate instanceof Date ? this.modelDate : new Date();
        this.year = this.dateEnabled ? date.getFullYear() : 0;
        this.month = this.dateEnabled ? date.getMonth() : 0;
        this.day = this.dateEnabled ? date.getDate() : 0;
        this.hour = this.timeEnabled ? date.getHours() : 0;
        this.minute = this.timeEnabled ? date.getMinutes() : 0;
        this.second = this.secondsEnabled ? date.getSeconds() : 0;
        this.changeViewData();
    }
    changeBy(value, unit) {
        if ((unit === "month") && (((this.monthLeftDisable == true) && (value == -1)) || ((this.monthRightDisable == true) && (value == 1)))) {
            //month navigation disabled
        } else {
            if (+value) {
                // DST workaround
                if ((unit === "hour" || unit === "minute") && value === -1) {
                    let date = new Date(this.year, this.month, this.day, this.hour - 1, this.minute);
                    if ((this.minute === 0 || unit === "hour") && this.hour === date.getHours()) {
                        this.hour--;
                    }
                }
                this[unit] += +value;
                if (unit === "month" || unit === "year") {
                    if ((this.month == new Date().getMonth()) && (this.year == new Date().getFullYear())) {
                        this.day = Math.min(this.day, this.getDaysInMonth(this.year, this.month));
                    } else {
                        this.day = 1;
                    }
                }
                this.changeViewData();
            }
        }
    }
    change(unit) {
        let value = this.bind[unit];
        if (value && unit === "meridiem") {
            value = value.toUpperCase();
            if (value === "AM" && this.meridiem === "PM") {
                this.hour -= 12;
            }
            else if (value === "PM" && this.meridiem === "AM") {
                this.hour += 12;
            }
            this.changeViewData();
        }
        else if (+value || +value === 0) {
            this[unit] = +value;
            if (unit === "month" || unit === "year") {
                if ((this.month == new Date().getMonth()) && (this.year == new Date().getFullYear())) {
                    this.day = Math.min(this.day, this.getDaysInMonth(this.year, this.month));
                } else {
                    this.day = 1;
                }
            }
            this.changeViewData();
        }
    }
    changeDay(x, y) {
        this.day = this.cellDay(x, y);
        this.changeViewData();
    }
    isEnabled(day, computeNextValidDate) {
        if (!this.onlyValid) {
            return true;
        }
        let currentDate = new Date(this.year, this.month, day);
        let constraints = [].concat(this.onlyValid);
        return constraints.every((currentRule) => {
            let isValid = true;
            currentRule = JSON.parse(currentRule);
            // console.log(currentRule);
            // console.log(currentRule.after);
            if (currentRule.after) {
                let afterDate = this.createDate(currentRule.after);
                if (currentRule.inclusive) {
                    isValid = currentDate >= afterDate;
                    if (!isValid && computeNextValidDate) {
                        this.setNextValidDate(afterDate, 0);
                    }
                }
                else {
                    isValid = currentDate > afterDate;
                    if (!isValid && computeNextValidDate) {
                        this.setNextValidDate(afterDate, 1);
                    }
                }
            }
            else if (currentRule.before) {
                let beforeDate = this.createDate(currentRule.before);
                if (currentRule.inclusive) {
                    isValid = currentDate <= beforeDate;
                    if (!isValid && computeNextValidDate) {
                        this.setNextValidDate(beforeDate, 0);
                    }
                }
                else {
                    isValid = currentDate < beforeDate;
                    if (!isValid && computeNextValidDate) {
                        this.setNextValidDate(beforeDate, -1);
                    }
                }
            }
            else if (currentRule.between) {
                let initialDate = this.createDate(currentRule.between.initial);
                let finalDate = this.createDate(currentRule.between.final);
                if (currentRule.inclusive) {
                    isValid = currentDate >= initialDate && currentDate <= finalDate;
                    if (!isValid && computeNextValidDate) {
                        if (currentDate < initialDate) {
                            this.setNextValidDate(initialDate, 0);
                        }
                        else if (currentDate > finalDate) {
                            this.setNextValidDate(finalDate, 0);
                        }
                    }
                }
                else {
                    isValid = currentDate > initialDate && currentDate < finalDate;
                    if (!isValid && computeNextValidDate) {
                        if (currentDate <= initialDate) {
                            this.setNextValidDate(initialDate, 1);
                        }
                        else if (currentDate >= finalDate) {
                            this.setNextValidDate(finalDate, -1);
                        }
                    }
                }
            }
            else if (currentRule.outside) {
                let initialDate = this.createDate(currentRule.outside.initial);
                let finalDate = this.createDate(currentRule.outside.final);
                if (currentRule.inclusive) {
                    isValid = currentDate <= initialDate || currentDate >= finalDate;
                    if (!isValid && computeNextValidDate) {
                        let lastValidDate = this.lastDateSet.getDateWithoutTime();
                        if (lastValidDate <= initialDate) {
                            this.setNextValidDate(finalDate, 0);
                        }
                        else if (lastValidDate >= finalDate) {
                            this.setNextValidDate(initialDate, 0);
                        }
                    }
                }
                else {
                    isValid = currentDate < initialDate || currentDate > finalDate;
                    if (!isValid && computeNextValidDate) {
                        let lastValidDate = this.lastDateSet.getDateWithoutTime();
                        if (lastValidDate < initialDate) {
                            this.setNextValidDate(finalDate, 1);
                        }
                        else if (lastValidDate > finalDate) {
                            this.setNextValidDate(initialDate, -1);
                        }
                    }
                }
            }
            return isValid;
        });
    }
    changed() {
        this.changeViewData();
    }
    triggerChange() {
        this.pickerChange.emit(new Date(this.year, this.month, this.day, this.hour, this.minute, this.second));
    }
    setNextValidDate(date, dayToAdd) {
        dayToAdd = dayToAdd || 0;
        if (dayToAdd !== 0) {
            date.setDate(date.getDate() + dayToAdd);
        }
        this.lastDateSet.year = date.getFullYear();
        this.lastDateSet.month = date.getMonth();
        this.lastDateSet.day = date.getDate();
        this.lastDateSet.hour = date.getHours();
        this.lastDateSet.minute = date.getMinutes();
        this.lastDateSet.second = date.getSeconds();
        this.lastDateSet.date = date;
    }
    setLastValidDate() {
        let date = new Date(this.year, this.month, this.day, this.hour, this.minute, this.second);
        if (this.isEnabled(date.getDate(), true)) {
            this.setNextValidDate(date);
        }
        else {
            this.year = this.lastDateSet.year;
            this.month = this.lastDateSet.month;
            this.day = this.lastDateSet.day;
            this.hour = this.lastDateSet.hour;
            this.minute = this.lastDateSet.minute;
            this.second = this.lastDateSet.second;
        }
    }
    changeViewData() {
        this.setLastValidDate();
        let date = new Date(this.year, this.month, this.day, this.hour, this.minute, this.second);
        if (this.dateEnabled) {
            this.year = date.getFullYear();
            this.month = date.getMonth();
            this.day = date.getDate();
            this.bind.year = this.year;
            this.bind.month = this.month;
            this.firstDay = new Date(this.year, this.month, 1).getDay();
            if (this.isMondayFirst) {
                this.firstDay = (this.firstDay || 7) - 1;
            }
            this.daysInMonth = this.getDaysInMonth(this.year, this.month);
            //disabling month navigation
            let startMonth = new Date().getMonth();;
            let startYear = new Date().getFullYear();
            let validAfter;
            if (this.onlyValid) {
                validAfter = JSON.parse(this.onlyValid);
                if (validAfter.after != 'today') {
                    startMonth = Number.parseInt(validAfter.after.split('/')[0]) - 1;
                    startYear = Number.parseInt(validAfter.after.split('/')[2]);
                }
            }
            if ((this.month == startMonth) && (this.year == startYear)) {
                this.monthLeftDisable = true;
                if (document.getElementById('monthLeft')) {
                    document.getElementById('monthLeft').setAttribute('style', 'color: rgba(220, 105, 0, .4);');
                } else {
                    setTimeout(() => { document.getElementById('monthLeft').setAttribute('style', 'color: rgba(220, 105, 0, .4);'); }, 500);
                }
            } else if (this.monthLeftDisable == true) {
                this.monthLeftDisable = false;
                document.getElementById('monthLeft').removeAttribute('style');
            }
            if ((this.month == 11) && (this.year == this.lastYear)) {
                this.monthRightDisable = true;
                if (document.getElementById('monthRight')) {
                    document.getElementById('monthRight').setAttribute('style', 'color: rgba(220, 105, 0, .4);');
                } else {
                    setTimeout(() => { document.getElementById('monthRight').setAttribute('style', 'color: rgba(220, 105, 0, .4);'); }, 500);
                }
            } else if (this.monthRightDisable == true) {
                this.monthRightDisable = false;
                document.getElementById('monthRight').removeAttribute('style');
            }
        }
        if (this.timeEnabled) {
            this.hour = date.getHours();
            this.minute = date.getMinutes();
            this.second = date.getSeconds();
            this.meridiem = this.hour < 12 ? "AM" : "PM";
            this.bind.hour = this.meridiemEnabled ? (this.hour % 12 || 12).toString() : this.hour.toString();
            this.bind.minute = (this.minute < 10 ? "0" : "") + this.minute.toString();
            this.bind.second = (this.second < 10 ? "0" : "") + this.second.toString();
            this.bind.meridiem = this.meridiem;
        }
        this.triggerChange();
    }
    getDaysInMonth(year, month) {
        return new Date(year, month + 1, 0).getDate();
    }
    createDate(stringDate) {
        let date = new Date(stringDate);
        let isInvalidDate = isNaN(date.getTime());
        if (isInvalidDate) {
            date = new Date(); // today
        }
        date.setHours(0, 0, 0, 0);
        return date;
    }

    openMenu(unit) {
        let e = document.getElementsByClassName('alert-wrapper ion-datetime-picker-wrapper')[0];
        // let style = e.getAttribute('style');
        // e.setAttribute('style', style+' background-color: #dbdbdf;');
        var newe = document.createElement('div');
        newe.setAttribute('style', 'position: absolute; z-index: 1; background: rgba(0, 0, 0, 0.2); width:100%; height: 100%; top: 0px; left: 0px; border-radius: 13px;');
        newe.setAttribute('id', 'month-back');
        newe.onclick = function () {
            let alertElement = document.getElementsByClassName('alert-wrapper ion-datetime-picker-wrapper')[0];
            alertElement.removeChild(alertElement.children[3]);
            let menu = document.getElementsByClassName('menu-select')[0];
            menu.removeAttribute('style');
            menu = document.getElementsByClassName('menu-select')[1];
            menu.removeAttribute('style');
        }
        e.appendChild(newe);
        let menu;
        if(unit == 'month') {
            menu = document.getElementsByClassName('menu-select')[0];
            menu.setAttribute('style', 'display: initial; left: 0px; width: 97px;');
        } else {
            menu = document.getElementsByClassName('menu-select')[1];
            menu.setAttribute('style', 'display: initial; left: 0px; width: 60px;');
        }
    }

    clickMonth(index) {
        this.bind.month = this.getMonthNumber(index);
        let alertElement = document.getElementsByClassName('alert-wrapper ion-datetime-picker-wrapper')[0];
        alertElement.removeChild(alertElement.children[3]);
        let menu = document.getElementsByClassName('menu-select')[0];
        menu.removeAttribute('style');
        this.change('month');
    }

    monthSelected(index) {
        if(this.getMonthNumber(index) == this.bind.month) {
            return true;
        } else {
            return false;
        }
    }

    clickYear(year) {
        this.bind.year = year;
        let alertElement = document.getElementsByClassName('alert-wrapper ion-datetime-picker-wrapper')[0];
        alertElement.removeChild(alertElement.children[3]);
        let menu = document.getElementsByClassName('menu-select')[1];
        menu.removeAttribute('style');
        this.change('year');
    }

    yearSelected(year) {
        if(year == this.bind.year) {
            return true;
        } else {
            return false;
        }
    }

};
__decorate([
    Input(),
    __metadata("design:type", Date)
], DatetimePickerComponent.prototype, "modelDate", void 0);
__decorate([
    Input(),
    __metadata("design:type", Boolean)
], DatetimePickerComponent.prototype, "dateEnabled", void 0);
__decorate([
    Input(),
    __metadata("design:type", Boolean)
], DatetimePickerComponent.prototype, "timeEnabled", void 0);
__decorate([
    Input(),
    __metadata("design:type", Boolean)
], DatetimePickerComponent.prototype, "isMondayFirst", void 0);
__decorate([
    Input(),
    __metadata("design:type", Boolean)
], DatetimePickerComponent.prototype, "secondsEnabled", void 0);
__decorate([
    Input(),
    __metadata("design:type", Boolean)
], DatetimePickerComponent.prototype, "meridiemEnabled", void 0);
__decorate([
    Input(),
    __metadata("design:type", Object)
], DatetimePickerComponent.prototype, "onlyValid", void 0);
__decorate([
    Input(),
    __metadata("design:type", Array)
], DatetimePickerComponent.prototype, "monthNames", void 0);
__decorate([
    Input(),
    __metadata("design:type", Array)
], DatetimePickerComponent.prototype, "weekdayNames", void 0);
__decorate([
    Output(),
    __metadata("design:type", Object)
], DatetimePickerComponent.prototype, "pickerChange", void 0);
DatetimePickerComponent = __decorate([
    Component({
        selector: "ion-datetime-picker",
        template: `

        <button type="button" ion-button icon-only clear (click)="changeBy(-1, 'month')"><ion-icon id="monthLeft" class="pwcorange" name="arrow-back"></ion-icon></button>

            {{allMonths[bind.month]}}
            <ion-icon class="menu-arrow" name="md-arrow-dropdown"></ion-icon>

{{month}}

            {{bind.year}}
            <ion-icon class="menu-arrow" name="md-arrow-dropdown"></ion-icon>

{{year}}

        <button type="button" ion-button icon-only clear (click)="changeBy(+1, 'month')"><ion-icon id="monthRight" class="pwcorange" name="arrow-forward"></ion-icon></button>

{{weekdayNames[weekday]}}

            {{cellDay(x, y)}}

<button type="button" ion-button icon-only clear (click)="changeBy(+1, 'hour')"><ion-icon class="pwcorange" name="arrow-up"></ion-icon></button>

<button type="button" ion-button icon-only clear (click)="changeBy(+1, 'minute')"><ion-icon class="pwcorange" name="arrow-up"></ion-icon></button>

<button type="button" ion-button icon-only clear (click)="changeBy(+1, 'second')"><ion-icon class="pwcorange" name="arrow-up"></ion-icon></button>

<button type="button" ion-button icon-only clear (click)="changeBy(+12, 'hour')"><ion-icon class="pwcorange" name="arrow-up"></ion-icon></button>

{{bind.hour}}

:

{{bind.minute}}

:

{{bind.second}}

{{bind.meridiem}}

<button type="button" ion-button icon-only clear (click)="changeBy(-1, 'hour')"><ion-icon class="pwcorange" name="arrow-down"></ion-icon></button>

<button type="button" ion-button icon-only clear (click)="changeBy(-1, 'minute')"><ion-icon class="pwcorange" name="arrow-down"></ion-icon></button>

<button type="button" ion-button icon-only clear (click)="changeBy(-1, 'second')"><ion-icon class="pwcorange" name="arrow-down"></ion-icon></button>

<button type="button" ion-button icon-only clear (click)="changeBy(-12, 'hour')"><ion-icon class="pwcorange" name="arrow-down"></ion-icon></button>

  `,
        styles: [`

        .menu-select {
            position: absolute;
            //width: 96px;
            max-height: 180px;
            background: white;
            z-index: 2;
            border: 0.55px solid #9e9e9e;
            overflow-y: scroll;
            border-bottom: 1px solid #9e9e9e;
            display: none;
        }

        .menu-element {
            height: 30px;
            font-size: 16px;
            //width: 96px;
            border-bottom: 0.55px solid #9e9e9e;
            padding-top: 6px;
        }

        .menu-element-selected {
            font-weight: bold;
            color: #dc6900;
        }

        .menu-arrow {
            display: block;
            position: absolute;
            right: 0px;
            top: 11px;
        }

        .month-select {
            height: 40px;
            width: 96px;
            font-size: 16px;
            padding-top: 10px;
        }

        .year-select {
            height: 40px;
            width: 60px;
            font-size: 16px;
            padding-top: 10px;
        }

    :host {
      padding: 0 5px;
      overflow-x: hidden;
      overflow-y: auto;
    }

    input, select {
      width: 100%;
      height: 100%;
      max-width: none;
      text-align: center;
      padding: .1em 5px 0;

      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;

      background-color: #fff;
      border: 1px solid #999;
    }

    input::-webkit-outer-spin-button, input::-webkit-inner-spin-button {
      display: none;
    }

    .item-input {
      position: relative;
      width: 100%;
      height: 100%;
      padding: 0;
      margin: 0;
    }

    .calendar {
      text-align: center;
    }
    .calendar .col {
      padding: 0;
    }
    .calendar .day, .calendar .weekday {
      padding: 10px 5px;
    }
    .calendar .day:hover, .calendar .day.activated, .calendar .day.today:hover, .calendar .day.today.activated {
      //background-color: #bdf;
      color: black;
      cursor: pointer;
    }
    .calendar .day.today {
      background-color: #e4e4e4;
      //background-color: #ccc;
    }
    .calendar .day.selected, .calendar .day.selected:hover, .calendar .day.selected.activated {
      //background-color: #387ef5;
      background-color: #DC6900;
      color: white;
    }
    .calendar .day.disabled, .calendar .day.disabled:hover, .calendar .day.disabled.activated {
      //background-color: #ccc;
      color: #ccc;
    }
    .calendar .weekday {
      font-weight: bold;
    }

    .month-year {
      padding: 0;
      text-align: center;
    }
    .month-year .button {
      padding: 0;
      margin: 0;
      width: 1.5em;
      height: 1.7em;
      min-width: 0;
      min-height: 0;
    }
    .month-year input, .month-year select {
      font-size: 1em;
    }

    .time-buttons .col {
      padding: 0;
    }
    .time-buttons .button {
      padding: 0;
      margin: 0;
      width: 100%;
      height: 2em;
      min-width: 0;
      min-height: 0;
    }
    .time-buttons:first-child {
      padding-top: 0;
    }
    .time-buttons:last-child {
      padding-bottom: 0;
    }

    .time .col {
      padding: 0;
    }
    .time .colon {
      color: #999;
      font-size: 1.5em;
      padding: 0;
      text-align: center;
    }
    .time input {
      font-size: 1.2em;
    }
    .pwcorange {
        color: #DC6900;
    }
  `],
        encapsulation: ViewEncapsulation.Emulated,
    })
], DatetimePickerComponent);
export { DatetimePickerComponent };
//# sourceMappingURL=picker.component.js.map


text:
+++
hook = "Touring the ORM and Postgres landscape in Go, and why sqlc is today's top pick."
location = "San Francisco"
published_at = 2021-09-08T16:49:02Z
tags = ["postgres"]
title = "How We Went All In on sqlc/pgx for Postgres + Go"
+++

After a few months of research and experimentation with running a heavily DB-dependent Go app, we've arrived at the conclusion that [sqlc](https://github.com/kyleconroy/sqlc) is the figurative Correct Answer when it comes to using Postgres (and probably other databases too) in Go code beyond trivial uses. Let me walk you through how we got there.

First, let's take a broad tour of popular options in Go's ecosystem:

* `database/sql`: Go's built-in database package. Most people agree -- best to avoid it. It's database agnostic, which is kind of nice, but by extension that means it conforms to the lowest common denominator. No support for Postgres-specific features.

* [`lib/pq`](https://github.com/lib/pq): An early Postgres frontrunner in the Go ecosystem. It was good for its time and place, but has fallen behind, and is no longer actively maintained.

* [`pgx`](https://github.com/jackc/pgx): A very well-written and very thorough package for full-featured, performant connections to Postgres. However, it's opinionated about not offering any ORM-like features, and gets you very little beyond a basic query interface. Like with `database/sql`, hydrating database results into structs is painful -- not only do you have to list target fields off ad nauseam in a `SELECT` statement, but you also have to `Scan` them into a struct manually.
	* [`scany`](https://github.com/georgysavva/scany): Scany adds some quality-of-life improvement on top of pgx by eliminating the need to scan into every field of a struct. However, the desired field names must still be listed out in a `SELECT ...` statement, so it only reduces boilerplate by half.

* [`go-pg`](https://github.com/go-pg/pg): I've used this on projects before, and it's a pretty good little Postgres-specific ORM. A little more below on why ORMs in Go aren't particularly satisfying, but another downside with go-pg is that it implements its own driver, and isn't compatible with pgx.
	* [Bun](https://bun.uptrace.dev/guide/pg-migration.html#new-features): go-pg has also been put in maintenance mode in favor of Bun, which is a go-pg rewrite that works with non-Postgres databases.

* [`gorm`](https://gorm.io/): Similar to go-pg except not Postgres specific. It can use pgx as a driver, but misses a lot of Postgres features.

## Queries as strings (#strings)

A big downside of vanilla `database/sql` or pgx is that SQL queries are strings:

``` go
var name string
var weight int64
err := conn.QueryRow(ctx, "SELECT name, weight FROM widgets WHERE id = $1", 42).
	Scan(&name, &weight)
if err != nil {
	...
}
fmt.Println(name, weight)
```

This is fine for simple queries, but provides little in the way of confidence that queries actually work. The compiler just sees a string, so you need to write exhaustive test coverage to verify them.

And it gets worse. When you're writing a larger application that's trying to hydrate models, in an effort to reduce code duplication, you might start slicing and dicing those query strings -- gluing little pieces together to share code. e.g.

``` go
err := conn.QueryRow(ctx, `SELECT ` + scanTeamFields + ` ...)
```

You can make it work, and still verify what you have is right by way of tests, but it gets messy fast.

## ORMs (#orms)

ORMs like go-pg make this a little better by bringing some typing into the mix, which has some benefit for reducing mistakes:

``` go
story := new(Story)
err = db.Model(story).
    Relation("Author").
    Where("story.id = ?", story1.Id).
    Select()
if err != nil {
    panic(err)
}
```

However, without generics, Go's type system can only offer so much, and in practice, the compiler can't catch all that much more than when we were concatenating strings together. In the code above, `Model()` returns a `*Query` object. `Relation()` also returns a `*Query` object, and so does `Where()`. go-pq can  do some intelligent shuffling (e.g. putting a `LIMIT` before a `WHERE` wouldn't work in SQL, but go-pg will make it work because it's constructing the query lazily), but like with strings, there's a plethora of mistakes that will only be caught on runtime.

ORMs also have the problem of being an impedance mismatch compared to the raw SQL most people are used to, meaning you've got the reference documentation open all day looking up how to do accomplish things when the equivalent SQL would've been automatic. Easier queries are pretty straightforward, but imagine if you want to add an upsert or a [CTE](https://www.postgresql.org/docs/current/queries-with.html).

## sqlc (#sqlc)

And that's where [sqlc](https://github.com/kyleconroy/sqlc) comes in. With sqlc, you write `*.sql` files that contain table definitions along with queries annotated with a name and return type in a magic comment:

``` sql
CREATE TABLE authors (
  id   BIGSERIAL PRIMARY KEY,
  name text      NOT NULL,
  bio  text
);

-- name: CreateAuthor :one
INSERT INTO authors (
  name, bio
) VALUES (
  $1, $2
)
RETURNING *;
```

After running `sqlc generate` (which generates Go code from your SQL definitions) [1], you're now able to run this:

``` go
author, err = dbsqlc.New(tx).CreateAuthor(ctx, dbsqlc.CreateAuthor{
    Name: "Haruki Murakami",
    Bio:  "Author of _Killing Commendatore_. Running and jazz enthusiast.",
    ...
})

if err != nil {
    return nil, xerrors.Errorf("error creating author: %w", err)
}

fmt.Printf("Author name: %s\n", author.Name)
```

sqlc isn't an ORM, but it implements one of the most useful features of one -- mapping a query back into a struct without the need for boilerplate. If you have query with a `SELECT *` or `RETURNING *`, it knows which fields a table is supposed to have, and emits the result to a standard struct representing its records. All queries for a particular table that return its complete set of fields get to share the same output struct.

Rather than implement its own partially-complete SQL parser, sqlc uses PGAnalyze's [excellent `pg_query_go`](https://github.com/pganalyze/pg_query_go), which bakes in the same query parser that Postgres really uses. It's never given me trouble so far -- even complex queries with unusual Postgres embellishments work.

This query parsing also gives you some additional pre-runtime code verification. It won't protect you against logical bugs, but it won't compile invalid SQL queries, which is a far shot better than the guarantees you get with SQL-in-Go-strings. And thanks to SQL's declarative nature, it tends to produce fewer bugs than comparable procedural code. You'll still want to write tests, but you don't need to test every query and corner case as exhaustively.

### Codegen (#codegen)

I'm slightly allergic to the idea of codegen on a philosophical level, and that made me reluctant to look too deeply into sqlc, but after finally getting into it, it's won me over.

Go makes programs like sqlc easily installable in one command (`go get github.com/kyleconroy/sqlc/cmd/sqlc`), and quickly with minimal fuss. Go's lightning fast startup and runtime speed means that your codegen loop runs in the blink of an eye. Our project is sitting around 100 queries broken up across a dozen input files and its codegen runs in (much) less than a second on commodity hardware:

``` go
$ time sqlc generate

real    0.07s
user    0.08s
sys     0.01s
```

Even if we expand our number of queries by 100x to 10,000, I think we'll still be comfortable with the timing on that development loop.

A GitHub Action verifies generated output, and between checkout, pulling down an sqlc binary, and running it, the whole job takes a grand total of 4 seconds to run.

### pgx support appears (#pgx)

Previously, a major reason not to use sqlc is that it didn't support pgx, which we were already bought into pretty deeply. A recent [pull request](https://github.com/kyleconroy/sqlc/pull/1037) has addressed this problem by giving sqlc support for multiple drivers, and the feature's now available in the sqlc's latest release.

The authors also managed to write it in such a way that it's coupled very loosely -- our mature codebase was making heavy use of pgx already and had a number of custom abstractions built on top of it, and yet I was able to get sqlc slotted in alongside them and fully operational in less than an hour. We could even weave sqlc invocations in amongst raw pgx invocations as part of the same transaction, giving us an easy way to migrate over to it incrementally.

### Caveats and workarounds (#caveats)

A few things in sqlc are less convenient compared to a more traditional ORM, but there are workarounds that land pretty well. For example, a noticeable one is that sqlc queries can't take an arbitrary number of parameters, so doing a multi-row insert doesn't work as easily as you'd expect it to. However, you can get around this by sending batches as arrays which are unnested into distinct tuples in the SQL:

``` sql
-- Upsert many marketplaces, inserting or replacing data as necessary.
INSERT INTO marketplace (
    name,
    display_name
)
SELECT unnest(@names::text[]) AS name,
    unnest(@display_names::text[]) AS display_names
ON CONFLICT (name)
    DO UPDATE SET display_name = EXCLUDED.display_name
RETURNING *;
```

Another one is `UPDATE` where with a normal ORM you'd just add as many target fields and values (i.e. `UPDATE foo SET a = 1, b = 2, c = 3, ...`) through the query builder as you wanted. Queries in sqlc must be fully structured in advance, so this doesn't work. What you can do is something like this where each field is conditionally updated based on the presence of an associated boolean:

``` sql
-- Update a team.
-- name: TeamUpdate :one
UPDATE team
SET
    customer_id = CASE WHEN @customer_id_do_update::boolean
        THEN @customer_id::VARCHAR(200) ELSE customer_id END,

    has_payment_method = CASE WHEN @has_payment_method_do_update::boolean
        THEN @has_payment_method::bool ELSE has_payment_method END,

    name = CASE WHEN @name_do_update::boolean
        THEN @name::text ELSE name END
WHERE
    id = @id
RETURNING *;
```

The Go code to update a field ends up looking like this:

``` go
team, err = queries.TeamUpdate(ctx, dbsqlc.TeamUpdateParams{
    NameDoUpdate: true,
    Name:         req.Name,
})
```

sqlc doesn't have any built-in conventions around how queries are named or organized, so you'll want to make sure to come up with your own so that you can find things.

## Summary and future (#summary)

I've largely covered sqlc's objective benefits and features, but more subjectively, it just _feels_ good and fast to work with. Like Go itself, the tool's working for you instead of against you, and giving you an easy way to get work done without wrestling with the computer all day.

I won't go as far as to say that its the best answer across all ecosystems -- the feats that Rust's SQL drivers can achieve with its type system are borderline wizardry -- but sqlc's far and away my preferred solution when working in Go.

Lastly, generics are coming to Go, possibly [in beta form by the end of the year](https://go.dev/blog/generics-proposal), and that could change the landscape. I could imagine a world where they power a new generation of Go ORMs that can do better query checking and give you even better type completion. However, it's safe to say that's a good year or two out. Until then, we're happy with sqlc.

[1] There's a little configuration involved as well -- see [this quickstart](https://docs.sqlc.dev/en/stable/tutorials/getting-started-postgresql.html) in the official documentation.

redpajama_set_name: RedPajamaGithub


text:
// CG: This file was added by the Splash Screen component.
// Splash.cpp : implementation file
//

#include "stdafx.h"  // e. g. stdafx.h
#include "resource.h"  // e.g. resource.h
#include "CxDev.h"

#include "Splash.h"  // e.g. splash.h

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
//   Splash Screen class

BOOL CSplashWnd::c_bShowSplashWnd;
CSplashWnd* CSplashWnd::c_pSplashWnd;
CSplashWnd::CSplashWnd()
{
}

CSplashWnd::~CSplashWnd()
{
	// Clear the static window pointer.
	ASSERT(c_pSplashWnd == this);
	c_pSplashWnd = NULL;
}

BEGIN_MESSAGE_MAP(CSplashWnd, CWnd)
	//{{AFX_MSG_MAP(CSplashWnd)
	ON_WM_CREATE()
	ON_WM_PAINT()
	ON_WM_TIMER()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

void CSplashWnd::EnableSplashScreen(BOOL bEnable /*= TRUE*/)
{
	c_bShowSplashWnd = bEnable;
}

void CSplashWnd::ShowSplashScreen(CWnd* pParentWnd /*= NULL*/, BOOL bLimitTime /*= TRUE*/)
{
	if (!c_bShowSplashWnd || c_pSplashWnd != NULL)
		return;

	// Allocate a new splash screen, and create the window.
	c_pSplashWnd = new CSplashWnd;
	c_pSplashWnd->m_bLimitTime = bLimitTime;
	if (!c_pSplashWnd->Create(pParentWnd))
		delete c_pSplashWnd;
	else
		c_pSplashWnd->UpdateWindow();
}

BOOL CSplashWnd::PreTranslateAppMessage(MSG* pMsg)
{
	if (c_pSplashWnd == NULL)
		return FALSE;

	// If we get a keyboard or mouse message, hide the splash screen.
	if (pMsg->message == WM_KEYDOWN ||
	    pMsg->message == WM_SYSKEYDOWN ||
	    pMsg->message == WM_LBUTTONDOWN ||
	    pMsg->message == WM_RBUTTONDOWN ||
	    pMsg->message == WM_MBUTTONDOWN ||
	    pMsg->message == WM_NCLBUTTONDOWN ||
	    pMsg->message == WM_NCRBUTTONDOWN ||
	    pMsg->message == WM_NCMBUTTONDOWN)
	{
		c_pSplashWnd->HideSplashScreen();
		return TRUE;	// message handled here
	}

	return FALSE;	// message not handled
}

BOOL CSplashWnd::Create(CWnd* pParentWnd /*= NULL*/)
{
	if (!m_bitmap.LoadBitmap(IDB_SPLASH))
		return FALSE;

	BITMAP bm;
	m_bitmap.GetBitmap(&bm);

	return CreateEx(0,
		AfxRegisterWndClass(0, AfxGetApp()->LoadStandardCursor(IDC_ARROW)),
		NULL, WS_POPUP | WS_VISIBLE, 0, 0, bm.bmWidth, bm.bmHeight, pParentWnd->GetSafeHwnd(), NULL);
}

void CSplashWnd::HideSplashScreen()
{
	// Destroy the window, and update the mainframe.
	DestroyWindow();
	AfxGetMainWnd()->UpdateWindow();
}

void CSplashWnd::PostNcDestroy()
{
//	theApp.NotifySelectChanged();

	delete this;
}

int CSplashWnd::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CWnd::OnCreate(lpCreateStruct) == -1)
		return -1;

	// Center the window.
	CenterWindow();

	// Set a timer to destroy the splash screen.
	if (m_bLimitTime)
		SetTimer(1, 1200, NULL);

	return 0;
}

void CSplashWnd::OnPaint()
{
	CPaintDC dc(this);

	CDC dcImage;
	if (!dcImage.CreateCompatibleDC(&dc))
		return;

	BITMAP bm;
	m_bitmap.GetBitmap(&bm);

	// Paint the image.
	CBitmap* pOldBitmap = dcImage.SelectObject(&m_bitmap);
	dc.BitBlt(0, 0, bm.bmWidth, bm.bmHeight, &dcImage, 0, 0, SRCCOPY);

//	CFont* pOldFont = dc.SelectObject(CFont::FromHandle((HFONT)GetStockObject(DEFAULT_GUI_FONT)));
//	int nY = 150;
//	dc.TextOut(26, nY, theApp.m_strUserName);
//	dc.TextOut(26, nY + 16, theApp.m_strUserCompany);
//	dc.TextOut(26, nY + 32, theApp.m_strUserSerial);
//	dc.SelectObject(pOldFont);

	dcImage.SelectObject(pOldBitmap);
}

void CSplashWnd::OnTimer(UINT nIDEvent)
{
	// Destroy the splash screen window.
	HideSplashScreen();
}


text:
namespace AdList.Data.UnitOfWork
{
    using AdList.Data.Models;

    public interface IDataProvider
    {
        IRepository<User> Users { get; }

        IRepository<Ad> Ads { get; }

        IRepository<Category> Categories { get; }

        IRepository<Message> Messages { get; }

        int SaveChanges();
    }
}


text:
'use strict';

var Dispatcher = require('core/Dispatcher');
var Constants = require('player/Constants');

module.exports = {

  /**
   * after the player is mounted into the DOM
   * @param  {Object} $el jquery player element
   */
  placed: function($el) {
    Dispatcher.dispatch({
      type: Constants.PLAYER_PLACED,
      $el: $el
    });
  },

  /**
   * after the player died
   * @param  {Object} $el jquery player element
   */
  died: function($el) {
    Dispatcher.dispatch({
      type: Constants.PLAYER_DIED,
      $el: $el
    });
  }

}


text:
import { FrameAtom } from './frame-atom';
import { Context } from './meta-frame';
export declare class FrameComment extends FrameAtom {
    protected data: string;
    static readonly COMMENT_BEGIN = "#";
    static readonly COMMENT_END = "#";
    static readonly COMMENT_EOL = "\n";
    static readonly COMMENT_END_REGEX: RegExp;
    constructor(data: string, meta?: Context);
    string_prefix(): string;
    string_suffix(): string;
    canInclude(char: string): boolean;
    protected toData(): string;
}


text:
'use strict';

describe('spec 1', function () {
  afterEach(function (done) {
    console.log('after');
    process.nextTick(function () {
      throw new Error('after each hook error');
    });
  });
  it('should be called because error is in after each hook', function () {
    console.log('test 1');
  });
  it('should not be called', function () {
    console.log('test 2');
  });
});
describe('spec 2', function () {
  it('should be called, because hook error was in a sibling suite', function () {
    console.log('test 3');
  });
});


text:
namespace Castle.DynamicProxy
{
	using System;

	/// <summary>
	///
	/// </summary>
	public interface ICallable
	{
		/// <summary>
		///
		/// </summary>
		/// <param name="args"></param>
		/// <returns></returns>
		object Call(params object[] args);

		/// <summary>
		///
		/// </summary>
		object Target
		{
			get;
		}
	}
}


text:
#pragma once

#include "Statistics.h"

#include "CommonBeam.h"
#include "StratumBeam.h"

///////////////////////////////  GlobalShareBeam
///////////////////////////////////
// Used to detect duplicate share attacks on ETH mining.
struct GlobalShareBeam {
  uint64_t inputPrefix_;
  uint64_t nonce_;
  uint32_t outputHash_;

  GlobalShareBeam() = default;

  GlobalShareBeam(const ShareBeam &share)
    : inputPrefix_(share.inputprefix())
    , nonce_(share.nonce())
    , outputHash_(share.outputhash()) {}

  GlobalShareBeam &operator=(const GlobalShareBeam &r) = default;

  bool operator<(const GlobalShareBeam &r) const {
    if (inputPrefix_ < r.inputPrefix_ ||
        (inputPrefix_ == r.inputPrefix_ && nonce_ < r.nonce_) ||
        (inputPrefix_ == r.inputPrefix_ && nonce_ == r.nonce_ &&
         outputHash_ < r.outputHash_)) {
      return true;
    }
    return false;
  }
};

////////////////////////////  Alias  ////////////////////////////
using DuplicateShareCheckerBeam =
    DuplicateShareCheckerT<ShareBeam, GlobalShareBeam>;


text:
package com.wayneleo.quickstart.configcenter.app;

import org.springframework.data.jpa.repository.JpaRepository;
import com.wayneleo.quickstart.configcenter.model.Project;

public interface ProjectRepository extends JpaRepository<Project, String> {}


text:
#region Usings

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Extend.Internal;
using FluentAssertions;
using Xunit;

#endregion

namespace Extend.Testing.Internal
{
    [Collection( "InstanceCreator" )]
    public class ObjectValueProviderTest
    {
        [Fact]
        public void CtorNullRefrenceTest()
        {
            // ReSharper disable once ObjectCreationAsStatement
            // ReSharper disable once AssignNullToNotNullAttribute
            Action test = () => new ObjectValueProvider( null );

            Assert.Throws<ArgumentNullException>( test );
        }

        [Fact]
        public void CtorTest()
        {
            var actual = new ObjectValueProvider( new TestModel() );
            actual.Should()
                  .NotBeNull();
        }

        [Fact]
        public void GetValueInvalidExpressionTest()
        {
            var model = InstanceCreator.CreateInstance<TestModel>();
            var target = new ObjectValueProvider( model );

            Action test = () => target.GetValue( "DOESNotExist" );
            Assert.Throws<FormatException>( test );
        }

        [Fact]
        public void GetValueTest()
        {
            var model = InstanceCreator.CreateInstance<TestModel>();
            var target = new ObjectValueProvider( model );

            var actual = target.GetValue( "MyString" );
            actual.Should()
                  .Be( model.MyString );
        }

        [Fact]
        public void GetValueTest1()
        {
            var model = InstanceCreator.CreateInstance<TestModel>();
            var target = new ObjectValueProvider( model );

            var actual = target.GetValue( "MyInt32" );
            actual.Should()
                  .Be( model.MyInt32.ToString() );
        }

        [Fact]
        public void GetValueTest10()
        {
            var model = InstanceCreator.CreateInstance<TestModel>();
            var target = new ObjectValueProvider( model );

            var actual = target.GetValue( "SubModel.MyDictionaryStringSub[" + model.SubModel.MyDictionaryStringSub.First()
                                                                                .Key + "]" );
            actual.Should()
                  .Be( model.SubModel.MyDictionaryStringSub[model.SubModel.MyDictionaryStringSub.First()
                                                                 .Key] );
        }

        [Fact]
        public void GetValueTest2()
        {
            var model = InstanceCreator.CreateInstance<TestModel>();
            var target = new ObjectValueProvider( model );

            var actual = target.GetValue( "MyDouble" );
            actual.Should()
                  .Be( model.MyDouble.ToString( CultureInfo.InvariantCulture ) );
        }

        [Fact]
        public void GetValueTest3()
        {
            var model = InstanceCreator.CreateInstance<TestModel>();
            var target = new ObjectValueProvider( model );

            var actual = target.GetValue( "MyStringArray[0]" );
            actual.Should()
                  .Be( model.MyStringArray[0] );
        }

        [Fact]
        public void GetValueTest4()
        {
            var model = InstanceCreator.CreateInstance<TestModel>();
            var target = new ObjectValueProvider( model );

            var actual = target.GetValue( "MyInt32Array[0]" );
            actual.Should()
                  .Be( model.MyInt32Array[0]
                            .ToString() );
        }

        [Fact]
        public void GetValueTest5()
        {
            var model = InstanceCreator.CreateInstance<TestModel>();
            var target = new ObjectValueProvider( model );

            var actual = target.GetValue( "MyListString[0]" );
            actual.Should()
                  .Be( model.MyListString[0] );
        }

        [Fact]
        public void GetValueTest6()
        {
            var model = new TestModel
            {
                MyListInt = new List<Int32>
                {
                    RandomValueEx.GetRandomInt32(),
                    RandomValueEx.GetRandomInt32(),
                    RandomValueEx.GetRandomInt32()
                }
            };
            var target = new ObjectValueProvider( model );

            var actual = target.GetValue( "MyListInt[0]" );
            actual.Should()
                  .Be( model.MyListInt[0]
                            .ToString() );
        }

        [Fact]
        public void GetValueTest7()
        {
            var model = InstanceCreator.CreateInstance<TestModel>();
            var target = new ObjectValueProvider( model );

            var actual = target.GetValue( "MyDictionaryString[" + model.MyDictionaryString.First()
                                                                       .Key + "]" );
            actual.Should()
                  .Be( model.MyDictionaryString[model.MyDictionaryString.First()
                                                     .Key] );
        }

        [Fact]
        public void GetValueTest8()
        {
            var model = InstanceCreator.CreateInstance<TestModel>();
            var target = new ObjectValueProvider( model );

            var actual = target.GetValue( "SubModel.MyStringSub" );
            actual.Should()
                  .Be( model.SubModel.MyStringSub );
        }

        [Fact]
        public void GetValueTest9()
        {
            var model = InstanceCreator.CreateInstance<TestModel>();
            var target = new ObjectValueProvider( model );

            var actual = target.GetValue( "SubModel.MyStringArraySub[0]" );
            actual.Should()
                  .Be( model.SubModel.MyStringArraySub[0] );
        }

        #region Nested Types

        private class SubModel
        {
            // ReSharper disable UnusedAutoPropertyAccessor.Local
            // ReSharper disable CollectionNeverUpdated.Local
            // ReSharper disable UnusedMember.Local
            public String MyStringSub { get; set; }

            public Int32 MyInt32Sub { get; set; }

            public Double MyDoubleSub { get; set; }

            public String[] MyStringArraySub { get; set; }

            public Int32[] MyInt32ArraySub { get; set; }

            public List<String> MyListStringSub { get; set; }

            public List<Int32> MyListIntSub { get; set; }

            public Dictionary<String, String> MyDictionaryStringSub { get; set; }
            // ReSharper restore UnusedMember.Local
            // ReSharper restore CollectionNeverUpdated.Local
            // ReSharper restore UnusedAutoPropertyAccessor.Local
        }

        private class TestModel
        {
            // ReSharper disable UnusedAutoPropertyAccessor.Local
            // ReSharper disable CollectionNeverUpdated.Local
            // ReSharper disable UnusedMember.Local
            public String MyString { get; set; }

            public Int32 MyInt32 { get; set; }

            public Double MyDouble { get; set; }

            public String[] MyStringArray { get; set; }

            public Int32[] MyInt32Array { get; set; }

            public List<String> MyListString { get; set; }

            public List<Int32> MyListInt { get; set; }

            public SubModel SubModel { get; set; }

            public Dictionary<String, String> MyDictionaryString { get; set; }
            // ReSharper restore UnusedMember.Local
            // ReSharper restore CollectionNeverUpdated.Local
            // ReSharper restore UnusedAutoPropertyAccessor.Local
        }

        #endregion
    }
}


text:
package org.apache.beam.sdk.io.rabbitmq;

import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkArgument;

import com.google.auto.value.AutoValue;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.GetResponse;
import com.rabbitmq.client.MessageProperties;
import java.io.IOException;
import java.io.Serializable;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeoutException;
import javax.annotation.Nullable;
import org.apache.beam.sdk.annotations.Experimental;
import org.apache.beam.sdk.annotations.Experimental.Kind;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.coders.SerializableCoder;
import org.apache.beam.sdk.io.UnboundedSource;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.values.PBegin;
import org.apache.beam.sdk.values.PCollection;
import org.joda.time.Duration;
import org.joda.time.Instant;

/**
 * A IO to publish or consume messages with a RabbitMQ broker.
 *
 *
Documentation in this module tends to reference interacting with a "queue" vs interacting with
 * an "exchange". AMQP doesn't technically work this way. For readers, notes on reading from/writing
 * to a "queue" implies the "default exchange" is in use, operating as a "direct exchange". Notes on
 * interacting with an "exchange" are more flexible and are generally more applicable.
 *
 *
Consuming messages from RabbitMQ server

 *
 *
{@link RabbitMqIO} {@link Read} returns an unbounded {@link PCollection} containing RabbitMQ
 * messages body (as {@code byte[]}) wrapped as {@link RabbitMqMessage}.
 *
 *
To configure a RabbitMQ source, you have to provide a RabbitMQ {@code URI} to connect to a
 * RabbitMQ broker. The following example illustrates various options for configuring the source,
 * reading from a named queue on the default exchange:
 *
 *
{@code
 * PCollection<RabbitMqMessage> messages = pipeline.apply(
 *   RabbitMqIO.read().withUri("amqp://user:password@localhost:5672").withQueue("QUEUE"))
 *
 * }

 *
 *
Often one will want to read from an exchange. The exchange can be declared by Beam or can be
 * pre-existing. The supplied {@code routingKey} has variable functionality depending on the
 * exchange type. As examples:
 *
 *
{@code
 *  // reading from an fanout (pubsub) exchange, declared (non-durable) by RabbitMqIO.
 *  // Note the routingKey is 'null' as a fanout exchange publishes all messages to
 *  // all queues, and the specified binding will be ignored
 * 	PCollection<RabbitMqMessage> messages = pipeline.apply(RabbitMqIO.read()
 * 			.withUri("amqp://user:password@localhost:5672").withExchange("EXCHANGE", "fanout", null));
 *
 * 	// reading from an existing topic exchange named 'EVENTS'
 * 	// this will use a dynamically-created, non-durable queue subscribing to all
 * 	// messages with a routing key beginning with 'users.'
 * 	PCollection<RabbitMqMessage> messages = pipeline.apply(RabbitMqIO.read()
 * 			.withUri("amqp://user:password@localhost:5672").withExchange("EVENTS", "users.#"));
 * }

 *
 *
Publishing messages to RabbitMQ server

 *
 *
{@link RabbitMqIO} {@link Write} can send {@link RabbitMqMessage} to a RabbitMQ server queue
 * or exchange.
 *
 *
As for the {@link Read}, the {@link Write} is configured with a RabbitMQ URI.
 *
 *
Examples
 *
 *
{@code
 * // Publishing to a named, non-durable exchange, declared by Beam:
 * pipeline
 *   .apply(...) // provide PCollection<RabbitMqMessage>
 *   .apply(RabbitMqIO.write().withUri("amqp://user:password@localhost:5672").withExchange("EXCHANGE", "fanout"));
 *
 * // Publishing to an existing exchange
 * pipeline
 *   .apply(...) // provide PCollection<RabbitMqMessage>
 *   .apply(RabbitMqIO.write().withUri("amqp://user:password@localhost:5672").withExchange("EXCHANGE"));
 *
 * // Publishing to a named queue in the default exchange:
 * pipeline
 *   .apply(...) // provide PCollection<RabbitMqMessage>
 *   .apply(RabbitMqIO.write().withUri("amqp://user:password@localhost:5672").withQueue("QUEUE"));
 * }

 */
@Experimental(Kind.SOURCE_SINK)
public class RabbitMqIO {
  public static Read read() {
    return new AutoValue_RabbitMqIO_Read.Builder()
        .setQueueDeclare(false)
        .setExchangeDeclare(false)
        .setMaxReadTime(null)
        .setMaxNumRecords(Long.MAX_VALUE)
        .setUseCorrelationId(false)
        .build();
  }

  public static Write write() {
    return new AutoValue_RabbitMqIO_Write.Builder()
        .setExchangeDeclare(false)
        .setQueueDeclare(false)
        .build();
  }

  private RabbitMqIO() {}

  private static class ConnectionHandler {

    private final ConnectionFactory connectionFactory;
    private Connection connection;
    private Channel channel;

    public ConnectionHandler(String uri)
        throws URISyntaxException, NoSuchAlgorithmException, KeyManagementException {
      connectionFactory = new ConnectionFactory();
      connectionFactory.setUri(uri);
      connectionFactory.setAutomaticRecoveryEnabled(true);
      connectionFactory.setConnectionTimeout(60000);
      connectionFactory.setNetworkRecoveryInterval(5000);
      connectionFactory.setRequestedHeartbeat(60);
      connectionFactory.setTopologyRecoveryEnabled(true);
      connectionFactory.setRequestedChannelMax(0);
      connectionFactory.setRequestedFrameMax(0);
    }

    public void start() throws TimeoutException, IOException {
      connection = connectionFactory.newConnection();
      channel = connection.createChannel();
      if (channel == null) {
        throw new IOException("No RabbitMQ channel available");
      }
    }

    public Channel getChannel() {
      return this.channel;
    }

    public void stop() throws IOException {
      if (channel != null) {
        try {
          channel.close();
        } catch (Exception e) {
          // ignore
        }
      }
      if (connection != null) {
        connection.close();
      }
    }
  }

  /** A {@link PTransform} to consume messages from RabbitMQ server. */
  @AutoValue
  public abstract static class Read extends PTransform<PBegin, PCollection<RabbitMqMessage>> {
    @Nullable
    abstract String uri();

    @Nullable
    abstract String queue();

    abstract boolean queueDeclare();

    @Nullable
    abstract String exchange();

    @Nullable
    abstract String exchangeType();

    abstract boolean exchangeDeclare();

    @Nullable
    abstract String routingKey();

    abstract boolean useCorrelationId();

    abstract long maxNumRecords();

    @Nullable
    abstract Duration maxReadTime();

    abstract Builder builder();

    @AutoValue.Builder
    abstract static class Builder {
      abstract Builder setUri(String uri);

      abstract Builder setQueue(String queue);

      abstract Builder setQueueDeclare(boolean queueDeclare);

      abstract Builder setExchange(String exchange);

      abstract Builder setExchangeType(String exchangeType);

      abstract Builder setExchangeDeclare(boolean exchangeDeclare);

      abstract Builder setRoutingKey(String routingKey);

      abstract Builder setUseCorrelationId(boolean useCorrelationId);

      abstract Builder setMaxNumRecords(long maxNumRecords);

      abstract Builder setMaxReadTime(Duration maxReadTime);

      abstract Read build();
    }

    public Read withUri(String uri) {
      checkArgument(uri != null, "uri can not be null");
      return builder().setUri(uri).build();
    }

    /**
     * If you want to directly consume messages from a specific queue, you just have to specify the
     * queue name. Optionally, you can declare the queue using {@link
     * RabbitMqIO.Read#withQueueDeclare(boolean)}.
     */
    public Read withQueue(String queue) {
      checkArgument(queue != null, "queue can not be null");
      return builder().setQueue(queue).build();
    }

    /**
     * You can "force" the declaration of a queue on the RabbitMQ broker. Exchanges and queues are
     * the high-level building blocks of AMQP. These must be "declared" (created) before they can be
     * used. Declaring either type of object ensures that one of that name and of the specified
     * properties exists, creating it if necessary.
     *
     *
NOTE: When declaring a queue or exchange that already exists, the properties specified in
     * the declaration must match those of the existing queue or exchange. That is, if you declare a
     * queue to be non-durable but a durable queue already exists with the same name, the
     * declaration will fail. When declaring a queue, RabbitMqIO will declare it to be non-durable.
     *
     * @param queueDeclare If {@code true}, {@link RabbitMqIO} will declare a non-durable queue. If
     *     another application created the queue, this is not required and should be set to {@code
     *     false}
     */
    public Read withQueueDeclare(boolean queueDeclare) {
      return builder().setQueueDeclare(queueDeclare).build();
    }

    /**
     * In AMQP, messages are published to an exchange and routed to queues based on the exchange
     * type and a queue binding. Most exchange types utilize the routingKey to determine which
     * queues to deliver messages to. It is incumbent upon the developer to understand the paradigm
     * in place to determine whether to declare a queue, what the appropriate binding should be, and
     * what routingKey will be in use.
     *
     *
This function should be used if the Beam pipeline will be responsible for declaring the
     * exchange. As a result of calling this function, {@code exchangeDeclare} will be set to {@code
     * true} and the resulting exchange will be non-durable and of the supplied type. If an exchange
     * with the given name already exists but is durable or is of another type, exchange declaration
     * will fail.
     *
     *
To use an exchange without declaring it, especially for cases when the exchange is shared
     * with other applications or already exists, use {@link #withExchange(String, String)} instead.
     *
     * @see
     *     "https://www.cloudamqp.com/blog/2015-09-03-part4-rabbitmq-for-beginners-exchanges-routing-keys-bindings.html"
     *     for a write-up on exchange types and routing semantics
     */
    public Read withExchange(String name, String type, @Nullable String routingKey) {
      checkArgument(name != null, "exchange name can not be null");
      checkArgument(type != null, "exchange type can not be null");
      return builder()
          .setExchange(name)
          .setExchangeType(type)
          .setRoutingKey(routingKey)
          .setExchangeDeclare(true)
          .build();
    }

    /**
     * In AMQP, messages are published to an exchange and routed to queues based on the exchange
     * type and a queue binding. Most exchange types utilize the routingKey to determine which
     * queues to deliver messages to. It is incumbent upon the developer to understand the paradigm
     * in place to determine whether to declare a queue, with the appropriate binding should be, and
     * what routingKey will be in use.
     *
     *
This function should be used if the Beam pipeline will be using an exchange that has
     * already been declared or when using an exchange shared by other applications, such as an
     * events bus or pubsub. As a result of calling this function, {@code exchangeDeclare} will be
     * set to {@code false}.
     */
    public Read withExchange(String name, @Nullable String routingKey) {
      checkArgument(name != null, "exchange name can not be null");
      return builder()
          .setExchange(name)
          .setExchangeDeclare(false)
          .setRoutingKey(routingKey)
          .build();
    }

    /**
     * Define the max number of records received by the {@link Read}. When this max number of
     * records is lower than {@code Long.MAX_VALUE}, the {@link Read} will provide a bounded {@link
     * PCollection}.
     */
    public Read withMaxNumRecords(long maxNumRecords) {
      checkArgument(maxReadTime() == null, "maxNumRecord and maxReadTime are exclusive");
      return builder().setMaxNumRecords(maxNumRecords).build();
    }

    /**
     * Define the max read time (duration) while the {@link Read} will receive messages. When this
     * max read time is not null, the {@link Read} will provide a bounded {@link PCollection}.
     */
    public Read withMaxReadTime(Duration maxReadTime) {
      checkArgument(
          maxNumRecords() == Long.MAX_VALUE, "maxNumRecord and maxReadTime are exclusive");
      return builder().setMaxReadTime(maxReadTime).build();
    }

    /**
     * Toggles deduplication of messages based on the amqp correlation-id property on incoming
     * messages.
     *
     *
When set to {@code true} all read messages will require the amqp correlation-id property
     * to be set.
     *
     *
When set to {@code false} the correlation-id property will not be used by the Reader and
     * no automatic deduplication will occur.
     */
    public Read withUseCorrelationId(boolean useCorrelationId) {
      return builder().setUseCorrelationId(useCorrelationId).build();
    }

    @Override
    public PCollection<RabbitMqMessage> expand(PBegin input) {
      org.apache.beam.sdk.io.Read.Unbounded<RabbitMqMessage> unbounded =
          org.apache.beam.sdk.io.Read.from(new RabbitMQSource(this));

      PTransform<PBegin, PCollection<RabbitMqMessage>> transform = unbounded;

      if (maxNumRecords() < Long.MAX_VALUE || maxReadTime() != null) {
        transform = unbounded.withMaxReadTime(maxReadTime()).withMaxNumRecords(maxNumRecords());
      }

      return input.getPipeline().apply(transform);
    }
  }

  static class RabbitMQSource extends UnboundedSource<RabbitMqMessage, RabbitMQCheckpointMark> {
    final Read spec;

    RabbitMQSource(Read spec) {
      this.spec = spec;
    }

    @Override
    public Coder<RabbitMqMessage> getOutputCoder() {
      return SerializableCoder.of(RabbitMqMessage.class);
    }

    @Override
    public List<RabbitMQSource> split(int desiredNumSplits, PipelineOptions options) {
      // RabbitMQ uses queue, so, we can have several concurrent consumers as source
      List<RabbitMQSource> sources = new ArrayList<>();
      for (int i = 0; i < desiredNumSplits; i++) {
        sources.add(this);
      }
      return sources;
    }

    @Override
    public UnboundedReader<RabbitMqMessage> createReader(
        PipelineOptions options, RabbitMQCheckpointMark checkpointMark) throws IOException {
      return new UnboundedRabbitMqReader(this, checkpointMark);
    }

    @Override
    public Coder<RabbitMQCheckpointMark> getCheckpointMarkCoder() {
      return SerializableCoder.of(RabbitMQCheckpointMark.class);
    }

    @Override
    public boolean requiresDeduping() {
      return spec.useCorrelationId();
    }
  }

  private static class RabbitMQCheckpointMark
      implements UnboundedSource.CheckpointMark, Serializable {
    transient Channel channel;
    Instant latestTimestamp = Instant.now();
    final List<Long> sessionIds = new ArrayList<>();

    /**
     * Advances the watermark to the provided time, provided said time is after the current
     * watermark. If the provided time is before the latest, this function no-ops.
     *
     * @param time The time to advance the watermark to
     */
    public void advanceWatermark(Instant time) {
      if (time.isAfter(latestTimestamp)) {
        latestTimestamp = time;
      }
    }

    @Override
    public void finalizeCheckpoint() throws IOException {
      for (Long sessionId : sessionIds) {
        channel.basicAck(sessionId, false);
      }
      channel.txCommit();
      latestTimestamp = Instant.now();
      sessionIds.clear();
    }
  }

  private static class UnboundedRabbitMqReader
      extends UnboundedSource.UnboundedReader<RabbitMqMessage> {
    private final RabbitMQSource source;

    private RabbitMqMessage current;
    private byte[] currentRecordId;
    private ConnectionHandler connectionHandler;
    private String queueName;
    private Instant currentTimestamp;
    private final RabbitMQCheckpointMark checkpointMark;

    UnboundedRabbitMqReader(RabbitMQSource source, RabbitMQCheckpointMark checkpointMark)
        throws IOException {
      this.source = source;
      this.current = null;
      this.checkpointMark = checkpointMark != null ? checkpointMark : new RabbitMQCheckpointMark();
    }

    @Override
    public Instant getWatermark() {
      return checkpointMark.latestTimestamp;
    }

    @Override
    public UnboundedSource.CheckpointMark getCheckpointMark() {
      return checkpointMark;
    }

    @Override
    public RabbitMQSource getCurrentSource() {
      return source;
    }

    @Override
    public byte[] getCurrentRecordId() {
      if (current == null) {
        throw new NoSuchElementException();
      }
      if (currentRecordId != null) {
        return currentRecordId;
      } else {
        return "".getBytes(StandardCharsets.UTF_8);
      }
    }

    @Override
    public Instant getCurrentTimestamp() {
      if (currentTimestamp == null) {
        throw new NoSuchElementException();
      }
      return currentTimestamp;
    }

    @Override
    public RabbitMqMessage getCurrent() {
      if (current == null) {
        throw new NoSuchElementException();
      }
      return current;
    }

    @Override
    public boolean start() throws IOException {
      try {
        connectionHandler = new ConnectionHandler(source.spec.uri());
        connectionHandler.start();

        Channel channel = connectionHandler.getChannel();

        queueName = source.spec.queue();
        if (source.spec.queueDeclare()) {
          // declare the queue (if not done by another application)
          // channel.queueDeclare(queueName, durable, exclusive, autoDelete, arguments);
          channel.queueDeclare(queueName, false, false, false, null);
        }
        if (source.spec.exchange() != null) {
          if (source.spec.exchangeDeclare()) {
            channel.exchangeDeclare(source.spec.exchange(), source.spec.exchangeType());
          }
          if (queueName == null) {
            queueName = channel.queueDeclare().getQueue();
          }
          channel.queueBind(queueName, source.spec.exchange(), source.spec.routingKey());
        }
        checkpointMark.channel = channel;
        channel.txSelect();
      } catch (IOException e) {
        throw e;
      } catch (Exception e) {
        throw new IOException(e);
      }
      return advance();
    }

    @Override
    public boolean advance() throws IOException {
      try {
        Channel channel = connectionHandler.getChannel();
        // we consume message without autoAck (we want to do the ack ourselves)
        GetResponse delivery = channel.basicGet(queueName, false);
        if (delivery == null) {
          current = null;
          currentRecordId = null;
          currentTimestamp = null;
          checkpointMark.advanceWatermark(Instant.now());
          return false;
        }
        if (source.spec.useCorrelationId()) {
          String correlationId = delivery.getProps().getCorrelationId();
          if (correlationId == null) {
            throw new IOException(
                "RabbitMqIO.Read uses message correlation ID, but received "
                    + "message has a null correlation ID");
          }
          currentRecordId = correlationId.getBytes(StandardCharsets.UTF_8);
        }
        long deliveryTag = delivery.getEnvelope().getDeliveryTag();
        checkpointMark.sessionIds.add(deliveryTag);

        current = new RabbitMqMessage(source.spec.routingKey(), delivery);
        Date deliveryTimestamp = delivery.getProps().getTimestamp();
        currentTimestamp =
            (deliveryTimestamp != null) ? new Instant(deliveryTimestamp) : Instant.now();
        checkpointMark.advanceWatermark(currentTimestamp);
      } catch (IOException e) {
        throw e;
      } catch (Exception e) {
        throw new IOException(e);
      }
      return true;
    }

    @Override
    public void close() throws IOException {
      if (connectionHandler != null) {
        connectionHandler.stop();
      }
    }
  }

  /** A {@link PTransform} to publish messages to a RabbitMQ server. */
  @AutoValue
  public abstract static class Write
      extends PTransform<PCollection<RabbitMqMessage>, PCollection<?>> {

    @Nullable
    abstract String uri();

    @Nullable
    abstract String exchange();

    @Nullable
    abstract String exchangeType();

    abstract boolean exchangeDeclare();

    @Nullable
    abstract String queue();

    abstract boolean queueDeclare();

    abstract Builder builder();

    @AutoValue.Builder
    abstract static class Builder {
      abstract Builder setUri(String uri);

      abstract Builder setExchange(String exchange);

      abstract Builder setExchangeType(String exchangeType);

      abstract Builder setExchangeDeclare(boolean exchangeDeclare);

      abstract Builder setQueue(String queue);

      abstract Builder setQueueDeclare(boolean queueDeclare);

      abstract Write build();
    }

    public Write withUri(String uri) {
      checkArgument(uri != null, "uri can not be null");
      return builder().setUri(uri).build();
    }

    /**
     * Defines the to-be-declared exchange where the messages will be sent. By defining the exchange
     * via this function, RabbitMqIO will be responsible for declaring this exchange, and will
     * declare it as non-durable. If an exchange with this name already exists but is non-durable or
     * of a different type, the declaration will fail.
     *
     *
By calling this function {@code exchangeDeclare} will be set to {@code true}.
     *
     *
To publish to an existing exchange, use {@link #withExchange(String)}
     */
    public Write withExchange(String exchange, String exchangeType) {
      checkArgument(exchange != null, "exchange can not be null");
      checkArgument(exchangeType != null, "exchangeType can not be null");
      return builder()
          .setExchange(exchange)
          .setExchangeType(exchangeType)
          .setExchangeDeclare(true)
          .build();
    }

    /**
     * Defines the existing exchange where the messages will be sent.
     *
     *
By calling this function {@code exchangeDeclare} will be set to {@code false}
     */
    public Write withExchange(String exchange) {
      checkArgument(exchange != null, "exchange can not be null");
      return builder().setExchange(exchange).setExchangeDeclare(false).build();
    }

    /**
     * Defines the queue where the messages will be sent. The queue has to be declared. It can be
     * done by another application or by {@link RabbitMqIO} if you set {@link
     * Write#withQueueDeclare} to {@code true}.
     */
    public Write withQueue(String queue) {
      checkArgument(queue != null, "queue can not be null");
      return builder().setQueue(queue).build();
    }

    /**
     * If the queue is not declared by another application, {@link RabbitMqIO} can declare the queue
     * itself.
     *
     * @param queueDeclare {@code true} to declare the queue, {@code false} else.
     */
    public Write withQueueDeclare(boolean queueDeclare) {
      return builder().setQueueDeclare(queueDeclare).build();
    }

    @Override
    public PCollection<?> expand(PCollection<RabbitMqMessage> input) {
      checkArgument(
          exchange() != null || queue() != null, "Either exchange or queue has to be specified");
      if (exchange() != null) {
        checkArgument(queue() == null, "Queue can't be set in the same time as exchange");
      }
      if (queue() != null) {
        checkArgument(exchange() == null, "Exchange can't be set in the same time as queue");
      }
      if (queueDeclare()) {
        checkArgument(queue() != null, "Queue is required for the queue declare");
      }
      if (exchangeDeclare()) {
        checkArgument(exchange() != null, "Exchange is required for the exchange declare");
      }
      return input.apply(ParDo.of(new WriteFn(this)));
    }

    private static class WriteFn extends DoFn<RabbitMqMessage, Void> {
      private final Write spec;

      private transient ConnectionHandler connectionHandler;

      WriteFn(Write spec) {
        this.spec = spec;
      }

      @Setup
      public void setup() throws Exception {
        connectionHandler = new ConnectionHandler(spec.uri());
        connectionHandler.start();

        Channel channel = connectionHandler.getChannel();

        if (spec.exchange() != null && spec.exchangeDeclare()) {
          channel.exchangeDeclare(spec.exchange(), spec.exchangeType());
        }
        if (spec.queue() != null && spec.queueDeclare()) {
          channel.queueDeclare(spec.queue(), true, false, false, null);
        }
      }

      @ProcessElement
      public void processElement(ProcessContext c) throws IOException {
        RabbitMqMessage message = c.element();
        Channel channel = connectionHandler.getChannel();

        if (spec.exchange() != null) {
          channel.basicPublish(
              spec.exchange(),
              message.getRoutingKey(),
              message.createProperties(),
              message.getBody());
        }
        if (spec.queue() != null) {
          channel.basicPublish(
              "", spec.queue(), MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBody());
        }
      }

      @Teardown
      public void teardown() throws Exception {
        if (connectionHandler != null) {
          connectionHandler.stop();
        }
      }
    }
  }
}


text:
package org.apache.lucene.sandbox.queries;

import java.io.IOException;

import org.apache.lucene.index.SingleTermsEnum;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.search.BooleanQuery; // javadocs
import org.apache.lucene.search.FuzzyQuery; // javadocs
import org.apache.lucene.search.MultiTermQuery;
import org.apache.lucene.util.AttributeSource;
import org.apache.lucene.util.ToStringUtils;
import org.apache.lucene.util.automaton.LevenshteinAutomata;

/** Implements the classic fuzzy search query. The similarity measurement
 * is based on the Levenshtein (edit distance) algorithm.
 *

 * Note that, unlike {@link FuzzyQuery}, this query will silently allow
 * for a (possibly huge) number of edit distances in comparisons, and may
 * be extremely slow (comparing every term in the index).
 *
 * @deprecated Use {@link FuzzyQuery} instead.
 */
@Deprecated
public class SlowFuzzyQuery extends MultiTermQuery {

  public final static float defaultMinSimilarity = LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE;
  public final static int defaultPrefixLength = 0;
  public final static int defaultMaxExpansions = 50;

  private float minimumSimilarity;
  private int prefixLength;
  private boolean termLongEnough = false;

  protected Term term;

  /**
   * Create a new SlowFuzzyQuery that will match terms with a similarity
   * of at least minimumSimilarity to term.
   * If a prefixLength > 0 is specified, a common prefix
   * of that length is also required.
   *
   * @param term the term to search for
   * @param minimumSimilarity a value between 0 and 1 to set the required similarity
   *  between the query term and the matching terms. For example, for a
   *  minimumSimilarity of 0.5 a term of the same length
   *  as the query term is considered similar to the query term if the edit distance
   *  between both terms is less than length(term)*0.5
   *

   *  Alternatively, if minimumSimilarity is >= 1f, it is interpreted
   *  as a pure Levenshtein edit distance. For example, a value of 2f
   *  will match all terms within an edit distance of 2 from the
   *  query term. Edit distances specified in this way may not be fractional.
   *
   * @param prefixLength length of common (non-fuzzy) prefix
   * @param maxExpansions the maximum number of terms to match. If this number is
   *  greater than {@link BooleanQuery#getMaxClauseCount} when the query is rewritten,
   *  then the maxClauseCount will be used instead.
   * @throws IllegalArgumentException if minimumSimilarity is >= 1 or < 0
   * or if prefixLength < 0
   */
  public SlowFuzzyQuery(Term term, float minimumSimilarity, int prefixLength,
      int maxExpansions) {
    super(term.field());
    this.term = term;

    if (minimumSimilarity >= 1.0f && minimumSimilarity != (int)minimumSimilarity)
      throw new IllegalArgumentException("fractional edit distances are not allowed");
    if (minimumSimilarity < 0.0f)
      throw new IllegalArgumentException("minimumSimilarity < 0");
    if (prefixLength < 0)
      throw new IllegalArgumentException("prefixLength < 0");
    if (maxExpansions < 0)
      throw new IllegalArgumentException("maxExpansions < 0");

    setRewriteMethod(new MultiTermQuery.TopTermsScoringBooleanQueryRewrite(maxExpansions));

    String text = term.text();
    int len = text.codePointCount(0, text.length());
    if (len > 0 && (minimumSimilarity >= 1f || len > 1.0f / (1.0f - minimumSimilarity))) {
      this.termLongEnough = true;
    }

    this.minimumSimilarity = minimumSimilarity;
    this.prefixLength = prefixLength;
  }

  /**
   * Calls {@link #SlowFuzzyQuery(Term, float) SlowFuzzyQuery(term, minimumSimilarity, prefixLength, defaultMaxExpansions)}.
   */
  public SlowFuzzyQuery(Term term, float minimumSimilarity, int prefixLength) {
    this(term, minimumSimilarity, prefixLength, defaultMaxExpansions);
  }

  /**
   * Calls {@link #SlowFuzzyQuery(Term, float) SlowFuzzyQuery(term, minimumSimilarity, 0, defaultMaxExpansions)}.
   */
  public SlowFuzzyQuery(Term term, float minimumSimilarity) {
    this(term, minimumSimilarity, defaultPrefixLength, defaultMaxExpansions);
  }

  /**
   * Calls {@link #SlowFuzzyQuery(Term, float) SlowFuzzyQuery(term, defaultMinSimilarity, 0, defaultMaxExpansions)}.
   */
  public SlowFuzzyQuery(Term term) {
    this(term, defaultMinSimilarity, defaultPrefixLength, defaultMaxExpansions);
  }

  /**
   * Returns the minimum similarity that is required for this query to match.
   * @return float value between 0.0 and 1.0
   */
  public float getMinSimilarity() {
    return minimumSimilarity;
  }

  /**
   * Returns the non-fuzzy prefix length. This is the number of characters at the start
   * of a term that must be identical (not fuzzy) to the query term if the query
   * is to match that term.
   */
  public int getPrefixLength() {
    return prefixLength;
  }

  @Override
  protected TermsEnum getTermsEnum(Terms terms, AttributeSource atts) throws IOException {
    if (!termLongEnough) {  // can only match if it's exact
      return new SingleTermsEnum(terms.iterator(null), term.bytes());
    }
    return new SlowFuzzyTermsEnum(terms, atts, getTerm(), minimumSimilarity, prefixLength);
  }

  /**
   * Returns the pattern term.
   */
  public Term getTerm() {
    return term;
  }

  @Override
  public String toString(String field) {
    final StringBuilder buffer = new StringBuilder();
    if (!term.field().equals(field)) {
        buffer.append(term.field());
        buffer.append(":");
    }
    buffer.append(term.text());
    buffer.append('~');
    buffer.append(Float.toString(minimumSimilarity));
    buffer.append(ToStringUtils.boost(getBoost()));
    return buffer.toString();
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = super.hashCode();
    result = prime * result + Float.floatToIntBits(minimumSimilarity);
    result = prime * result + prefixLength;
    result = prime * result + ((term == null) ? 0 : term.hashCode());
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (!super.equals(obj))
      return false;
    if (getClass() != obj.getClass())
      return false;
    SlowFuzzyQuery other = (SlowFuzzyQuery) obj;
    if (Float.floatToIntBits(minimumSimilarity) != Float
        .floatToIntBits(other.minimumSimilarity))
      return false;
    if (prefixLength != other.prefixLength)
      return false;
    if (term == null) {
      if (other.term != null)
        return false;
    } else if (!term.equals(other.term))
      return false;
    return true;
  }
}


text:
namespace tracing {
namespace v2 {

struct ContiguousMemoryRange {
  uint8_t* begin;
  uint8_t* end;  // STL style: one byte past the end of the buffer.

  inline bool is_valid() const { return begin != nullptr; }
  inline void reset() { begin = nullptr; }
  inline size_t size() { return static_cast<size_t>(end - begin); }
};

// This class deals with the following problem: append-only proto messages want
// to write a stream of bytes, without caring about the implementation of the
// underlying buffer (which concretely will be either the trace ring buffer
// or a heap-allocated buffer). The main deal is: proto messages don't know in
// advance what their size will be.
// Due to the tracing buffer being split into fixed-size chunks, on some
// occasions, these writes need to be spread over two (or more) non-contiguous
// chunks of memory. Similarly, when the buffer is backed by the heap, we want
// to avoid realloc() calls, as they might cause a full copy of the contents
// of the buffer.
// The purpose of this class is to abtract away the non-contiguous write logic.
// This class knows how to deal with writes as long as they fall in the same
// ContiguousMemoryRange and defers the chunk-chaining logic to the Delegate.
class TRACING_EXPORT ScatteredStreamWriter {
 public:
  class TRACING_EXPORT Delegate {
   public:
    virtual ~Delegate();
    virtual ContiguousMemoryRange GetNewBuffer() = 0;
  };

  explicit ScatteredStreamWriter(Delegate* delegate);
  ~ScatteredStreamWriter();

  void WriteByte(uint8_t value);
  void WriteBytes(const uint8_t* src, size_t size);

  // Reserves a fixed amount of bytes to be backfilled later. The reserved range
  // is guaranteed to be contiguous and not span across chunks.
  ContiguousMemoryRange ReserveBytes(size_t size);

  // Fast (but unsafe) version of the above. The caller must have previously
  // checked that there are at least |size| contiguos bytes available.
  // Returns only the start pointer of the reservation.
  uint8_t* ReserveBytesUnsafe(size_t size) {
    uint8_t* begin = write_ptr_;
    write_ptr_ += size;
    DCHECK_LE(write_ptr_, cur_range_.end);
    return begin;
  }

  // Resets the buffer boundaries and the write pointer to the given |range|.
  // Subsequent WriteByte(s) will write into |range|.
  void Reset(ContiguousMemoryRange range);

  // Number of contiguous free bytes in |cur_range_| that can be written without
  // requesting a new buffer.
  size_t bytes_available() const {
    return static_cast<size_t>(cur_range_.end - write_ptr_);
  }

  uint8_t* write_ptr() const { return write_ptr_; }

 private:
  void Extend();

  Delegate* const delegate_;
  ContiguousMemoryRange cur_range_;
  uint8_t* write_ptr_;

  DISALLOW_COPY_AND_ASSIGN(ScatteredStreamWriter);
};

}  // namespace v2
}  // namespace tracing

#endif  // COMPONENTS_TRACING_CORE_SCATTERED_STREAM_WRITER_H_


text:
var lsutigers = require(__dirname + '/../models/team');
var express = require('express');
var jsonParser = require('body-parser').json();
var handleError = require(__dirname + '/../lib/handle_error');
var eatAuth = require(__dirname + '/../lib/eat_auth');

var teamRouter = module.exports = exports = express.Router();

teamRouter.get('/', function(req, res){
    lsutigers.find({author: req.user.username}, function(err, data){
        if(err) return handleError(err, res);
        res.json(data);
    });
});

teamRouter.post('/', jsonParser, function(req, res){
    var newlsutigers = new lsutigers();
    newlsutigers.name = req.body.name;
    newlsutigers.position = req.body.position;
    newlsutigers.high_school = req.body.high_school;
    newlsutigers.author = req.user.username;
    if(newlsutigers.name)
        newlsutigers.save(function(err, data){
            if(err) return handleError(err, res);
            res.json(data);
        });
});

teamRouter.put('/:id', jsonParser, function(req, res){
    var newlsutigersBody = req.body;
    delete newlsutigersBody._id;
    lsutigers.update({_id: req.params.id}, newlsutigersBody, function(err, data){
        if(err) return handleError(err, res);
        res.json({msg: 'your update was a success'});
    });
});

teamRouter.delete('/:id', jsonParser, function(req, res){
    lsutigers.find({_id: req.params.id}, function(err, data){
        if(err) return handleError(err, res);

        if(data.length){
            lsutigers.remove({_id: req.params.id}, function(err){
                if(err) return handleError(err, res);
                res.json({msg: 'your delete went through'});
            });
        } else {
            res.json({msg: 'this player is not in our database'});
        }
    });
});


text:
/**
 * Created by hgeorgiev on 8/19/16.
 */
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var core_1 = require('@angular/core');
var http_1 = require('@angular/http');
var listing_model_1 = require('../listing.model');
var queryconstructor_1 = require('../queryconstructor');
require('rxjs/add/operator/toPromise');
var Rx_1 = require('rxjs/Rx');
var ClubsService = (function () {
    function ClubsService(http, api) {
        this.http = http;
        this.api = api;
        this.authToken = localStorage.getItem('auth_token');
        this.clubsUrl = this.api + '/clubs';
    }
    ClubsService.prototype.query = function (page, itemsPerPage) {
        return this.http.get(this.clubsUrl, { search: queryconstructor_1.QueryConstructor(page, itemsPerPage) })
            .toPromise()
            .then(function (res) {
            var body = res.json();
            var listing = new listing_model_1.Listing();
            listing.collection = body.Items;
            listing.count = body.Count;
            return listing;
        })
            .catch(this.handleError);
    };
    ClubsService.prototype.get = function (id) {
        return this.http.get(this.clubsUrl + ("/" + id))
            .toPromise()
            .then(function (res) { return res.json(); })
            .catch(this.handleError);
    };
    ClubsService.prototype.deleteClub = function (id) {
        var headers = new http_1.Headers({ 'Content-Type': 'application/json', 'Authorization': this.authToken });
        var url = this.clubsUrl + "/" + id;
        return this.http.delete(url, { headers: headers })
            .toPromise()
            .then(function () { return null; });
    };
    ClubsService.prototype.addClub = function (club, file, professor_id) {
        var _this = this;
        return Rx_1.Observable.create(function (observer) {
            var formData = new FormData();
            var xhr = new XMLHttpRequest();
            formData.append("club[logo]", file);
            formData.append("club[name]", club.name);
            formData.append("club[president]", club.president);
            formData.append("club[professor_id]", professor_id);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200 || xhr.status === 201) {
                        observer.next(JSON.parse(xhr.response));
                        observer.complete();
                    }
                    else {
                        observer.error(xhr.response);
                    }
                }
            };
            xhr.open("POST", _this.clubsUrl, true);
            xhr.setRequestHeader('Authorization', _this.authToken);
            xhr.send(formData);
        });
    };
    ClubsService.prototype.updateClub = function (club, file, id) {
        var _this = this;
        var url = this.clubsUrl + "/" + id;
        return Rx_1.Observable.create(function (observer) {
            var formData = new FormData();
            var xhr = new XMLHttpRequest();
            if (file !== undefined) {
                formData.append("club[logo]", file);
            }
            formData.append("club[name]", club.name);
            formData.append("club[president]", club.president);
            formData.append("club[professor_id]", club.professor_id);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200 || xhr.status === 201) {
                        observer.next(JSON.parse(xhr.response));
                        observer.complete();
                    }
                    else {
                        observer.error(xhr.response);
                    }
                }
            };
            xhr.open("PUT", url, true);
            xhr.setRequestHeader('Authorization', _this.authToken);
            xhr.send(formData);
        });
    };
    ClubsService = __decorate([
        core_1.Injectable(),
        __param(1, core_1.Inject('ApiEndpoint'))
    ], ClubsService);
    return ClubsService;
}());
exports.ClubsService = ClubsService;


text:
package components

import (
	"regexp"
	"testing"

	"github.com/google/go-cmp/cmp"
)

func TestFindMatchingStrings(t *testing.T) {
	args := []string{
		"LineCard1",
		"Supervisor1",
		"LineCard2",
		"Supervisor2",
		"Supervisor3",
		"LineCard2",
	}
	r := regexp.MustCompile(`^Supervisor[0-9]$`)
	want := []string{
		"Supervisor1",
		"Supervisor2",
		"Supervisor3",
	}
	got := FindMatchingStrings(args, r)
	if diff := cmp.Diff(want, got); diff != "" {
		t.Errorf("FindMatchingStrings(%s) returned unexpected diff (-want +got):\n%s", args, diff)
	}
}


text:
/* @flow */

import {sortAlpha} from '../util/misc.js';
import {LOCKFILE_VERSION} from '../constants.js';

function shouldWrapKey(str: string): boolean {
  return str.indexOf('true') === 0 || str.indexOf('false') === 0 ||
         /[:\s\n\\",\[\]]/g.test(str) || /^[0-9]/g.test(str) || !/^[a-zA-Z]/g.test(str);
}

function maybeWrap(str: string | boolean | number): string {
  if (typeof str === 'boolean' || typeof str === 'number' || shouldWrapKey(str)) {
    return JSON.stringify(str);
  } else {
    return str;
  }
}

const priorities: { [key: string]: ?number } = {
  name: 1,
  version: 2,
  uid: 3,
  resolved: 4,
  registry: 5,
  dependencies: 6,
};

function priorityThenAlphaSort(a: string, b: string): number {
  if (priorities[a] || priorities[b]) {
    return (priorities[a] || 100) > (priorities[b] || 100) ? 1 : -1;
  } else {
    return sortAlpha(a, b);
  }
}

type Options = {
  indent: string,
  topLevel?: boolean,
};

function _stringify(obj: { [key: string]: mixed }, options: Options): string {
  if (typeof obj !== 'object') {
    throw new TypeError();
  }

  const indent = options.indent;
  const lines = [];

  // Sorting order needs to be consistent between runs, we run native sort by name because there are no
  // problems with it being unstable because there are no to keys the same
  // However priorities can be duplicated and native sort can shuffle things from run to run
  const keys = Object.keys(obj).sort(priorityThenAlphaSort);

  let addedKeys = [];

  for (let i = 0; i < keys.length; i++) {
    const key = keys[i];
    const val = obj[key];
    if (val == null || addedKeys.indexOf(key) >= 0) {
      continue;
    }

    //
    const valKeys = [key];

    // get all keys that have the same value equality, we only want this for objects
    if (typeof val === 'object') {
      for (let j = i + 1; j < keys.length; j++) {
        const key = keys[j];
        if (val === obj[key]) {
          valKeys.push(key);
        }
      }
    }

    //
    const keyLine = valKeys.sort(sortAlpha).map(maybeWrap).join(', ');

    if (typeof val === 'string' || typeof val === 'boolean' || typeof val === 'number') {
      lines.push(`${keyLine} ${maybeWrap(val)}`);
    } else if (typeof val === 'object') {
      lines.push(
        `${keyLine}:\n${_stringify(val, {indent: indent + '  '})}` +
        (options.topLevel ? '\n' : ''),
      );
    } else {
      throw new TypeError();
    }

    addedKeys = addedKeys.concat(valKeys);
  }

  return indent + lines.join(`\n${indent}`);
}

export default function stringify(obj: Object, noHeader?: boolean): string {
  const val = _stringify(obj, {
    indent: '',
    topLevel: true,
  });
  if (noHeader) {
    return val;
  }

  return [
    '# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.',
    `# yarn lockfile v${LOCKFILE_VERSION}`,
    '\n',
    val,
  ].join('\n');
}