text:
static NSString * const PMCellReuseIdentifier = @"PMCellReuseIdentifier";

@interface PMViewController () <UICollectionViewDelegate, UICollectionViewDataSource>
@end

@implementation PMViewController
{
	PMCenteredCircularCollectionView *_collectionView;
	NSArray *_images;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    _images = @[[UIImage imageNamed:@"stock_photo1.jpg"],
				[UIImage imageNamed:@"stock_photo2.jpg"],
				[UIImage imageNamed:@"stock_photo3.jpg"],
				[UIImage imageNamed:@"stock_photo4.jpg"],
				[UIImage imageNamed:@"stock_photo5.jpg"]];

    CGRect frame = self.view.bounds;

    PMCenteredCollectionViewFlowLayout *layout = [PMCenteredCollectionViewFlowLayout new];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumLineSpacing = 10.0f;
    layout.minimumInteritemSpacing = 50.0f;
	CGFloat minDimension = fmin(self.view.bounds.size.width, self.view.bounds.size.height);
    layout.itemSize = CGSizeMake(minDimension, minDimension);

    _collectionView = [[PMCenteredCircularCollectionView alloc] initWithFrame:frame
                                                             collectionViewLayout:layout];

    _collectionView.backgroundColor = [UIColor whiteColor];
	_collectionView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    _collectionView.shadowRadius = 10.0f;
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:PMCellReuseIdentifier];
    [_collectionView setDataSource:self];

    [self.view addSubview:_collectionView];
}

- (void) viewDidAppear:(BOOL)animated
{
    [_collectionView setCenteredIndex:2 animated:YES];
}

#pragma mark - PMCircularCollectionViewDataSource Methods

- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return (NSInteger)_images.count;
}

- (UICollectionViewCell *) collectionView:(PMCenteredCircularCollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:PMCellReuseIdentifier forIndexPath:indexPath];
    NSInteger normalizedIndex = [collectionView normalizeIndex:indexPath.item];
    if (!cell.contentView.subviews.count) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:cell.contentView.bounds];
        imageView.contentMode = UIViewContentModeCenter;
        imageView.clipsToBounds = YES;
        [cell.contentView addSubview:imageView];
    }

    UIImageView *imageView = cell.contentView.subviews.lastObject;
    imageView.image = _images[(NSUInteger)normalizedIndex];
    return cell;
}

@end


text:
/**
 * Created by sebastian on 5/8/15.
 */

"use strict";

var ownsheetApp = angular.module("ownsheetApp");

ownsheetApp.controller('viewController', ["$scope", "$window", "$routeParams", "$sce",
    "chromeStorageService", "mdParserService", "previewContentService", "localStorageService",
    "$anchorScroll", "$location",
    function ($scope, $window, $routeParams, $sce, chromeStorageService, mdParserService,
              previewContentService, localStorageService, $anchorScroll, $location) {

        var mdContent, sheetPromise;
        var sheetNameParam = $routeParams.sheetName;
        $scope.sheet = {};

        var spinner = startSpinner();

        $scope.scrollTo = function (id) {
            var old = $location.hash();
            $location.hash(id);
            $anchorScroll();
            $location.hash(old);
        };
        // case: preview
        if (!sheetNameParam && $window.location.href.endsWith('main.html#/preview')) {
            $scope.sheet.name = "preview";
            $scope.mode = "preview";
            $scope.sheet.message = "";
            // get content from previewService
            var mdContentPromise = previewContentService.get();
            mdContentPromise.then(function (value) {
                $scope.mdContent = value;
                if ($scope.mdContent) {
                    renderContent($scope.mdContent, mdParserService);
                    customizePage(localStorageService, $scope);
                    $scope.buttonType = "edit";
                } else {
                    spinner.stop();
                    $scope.sheet.message = "No preview here";
                    $scope.buttonType = "new";
                }
            });
            // ask before unloading, because changed content will
            // be lost

            window.onbeforeunload = function (event) {
                return "If you leave this page, " +
                    "changes on your sheet you were just editing, " +
                    "will be lost."
            };
        } else {
            $scope.sheet.name = sheetNameParam;
            $scope.sheet.message = "";
            // get content from storage
            sheetPromise = chromeStorageService.getFromStorage(sheetNameParam);
            sheetPromise.then(function (value) {
                if (value[sheetNameParam]) {
                    // if there is content in storage
                    renderContent(value[sheetNameParam].content, mdParserService);
                    customizePage(localStorageService, $scope);

                    $scope.buttonType = "edit";
                } else {
                    // if there isn't
                    spinner.stop();
                    // check for error first
                    if (value === "Error") {
                        $scope.sheet.message = "Storage error! Please open ownsheet again. " +
                            "If this problem persists, consider contacting the developer."
                    } else {
                        $scope.sheet.name = "";
                        $scope.sheet.message = "No sheet here. Do you want to add one?";
                        $scope.buttonType = "new"
                    }
                }
            });

        }
        document.title = $scope.sheet.name + " cheat sheet";

        this.goToEdit = function () {
            if ($scope.mode !== "preview") {
                $window.open('main.html#/edit/' + $scope.sheet.name, "_self");
            } else {
                previewContentService.buffer($scope.mdContent);
                $window.history.back();
            }
        };

        this.new = function () {
            $window.open('main.html#/edit', "_self");
        };

    }]);

function initializeMasonry() {
    var container = document.querySelector('#masonry-container');
    var msnry = new Masonry(container, {
        // options
        columnWidth: 50,
        itemSelector: '.box'
    });
}

function customizePage(localStorageService, $scope) {
    makeTableOfContent($scope);
    var colorList = [];
    // get custom page parameters from local storage
    // set default value, if not customized.

    var colorsFromStorage = localStorageService.get('colors');
    if (!colorsFromStorage) {
        // default
        colorList = ["#4b65c3", "#2d9f34", "#48456a", "#4f7a4e",
            "#d61115", "#59582f"];
    } else {
        for (var indx in colorsFromStorage) {
            colorList.push(colorsFromStorage[indx].code);
        }
    }

    var boxSizeFromStorage = localStorageService.get('box-size') || 250;

    // set width and color of boxes
    $('.box').each(function (index) {
        $(this).css("width", boxSizeFromStorage + "px");
        $(this).css("background-color", colorList[index % colorList.length]);
    });

    // remove images
    $('img').each(function () {
        $(this).remove();
    });

    // add "toogle code block" button
    $('pre').before("\<button class=\"pre-button\" \>Show/Hide code block\<\/button\>");
    $(".pre-button").click(function () {
        $(this).next().find("code").toggle();
        // initialize Masonry again so there is no overlapping of boxes
        initializeMasonry();
    });

    var backgroundColorFromStorage = localStorageService.get('background-color');
    // set overall background color
    if (backgroundColorFromStorage) {
        $('html, body').css('background-color', backgroundColorFromStorage);
    }
    setTimeout(function () {
        initializeMasonry()
    }, 200);

}

function renderContent(mdContent, mdParserService) {
    // parse Content and insert it in 'ms.content' div
    var content = document.getElementById('ms-content');
    content.innerHTML = mdParserService.parse(mdContent) + "\
\
";
}

// Jquery I love you <3
function makeTableOfContent($scope) {

    //make links except contentTable ones open in new tab
    $('a').each(function () {
        (this).target = "_blank";
    });

    var tableOfContent = [];
    var content = "";
    var allBoxes = $('.box');

    $.each(allBoxes.find('h2'), function (index, value) {
        var text = $(value).text();
        $(value).after("\");
        tableOfContent.push(text);
        content += "\
" + text + "\" + "\
"
    });
    var tableOfContentHTML = "\

TABLE OF CONTENTS

" + content + "\

";

    $(allBoxes).first().before(tableOfContentHTML);

    $(".contentTable a").click(function (event) {
        event.preventDefault();
        var id = $(event.target).text();
        $scope.scrollTo(id);
    });

    $("a").click(function (event) {
        var goToTopExpressions = ['Back to top', 'Go to top', 'top', 'Scroll to top', 'Scroll up'];
        var id = $(event.target).text();

        if (goToTopExpressions.indexOf(id) > -1) {
            event.preventDefault();
            $scope.scrollTo("___tableOfcontent___");
        }
    });
}

String.prototype.endsWith = function (suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

function startSpinner() {
    var opts = {
        lines: 13, // The number of lines to draw
        length: 20, // The length of each line
        width: 10, // The line thickness
        radius: 30, // The radius of the inner circle
        corners: 1, // Corner roundness (0..1)
        rotate: 0, // The rotation offset
        direction: 1, // 1: clockwise, -1: counterclockwise
        color: '#000', // #rgb or #rrggbb or array of colors
        speed: 1, // Rounds per second
        trail: 60, // Afterglow percentage
        shadow: false, // Whether to render a shadow
        hwaccel: false, // Whether to use hardware acceleration
        className: 'spinner', // The CSS class to assign to the spinner
        zIndex: 2e9, // The z-index (defaults to 2000000000)
        top: '50%', // Top position relative to parent
        left: '50%' // Left position relative to parent
    };
    var target = document.getElementById('ms-content');
    var spinner = new Spinner(opts).spin(target);
    return spinner;
}

redpajama_set_name: RedPajamaGithub


text:
require 'rails_helper'

RSpec.describe ContributionDecorator do
  before do
    I18n.locale = :pt
  end

  describe "#display_date" do
    [:confirmed_at, :refunded_at, :requested_refund_at].each do |field|
      context "displaying #{field.to_s}" do
        subject { contribution.decorate.display_date(field)}

        let(:contribution) do
          c = build(:contribution)
          c[field] = Time.now
          c
        end

        it{ is_expected.to eq(I18n.l(contribution.send(field).to_date)) }
      end
    end
  end

  describe "#display_confirmed_at" do
    subject{ contribution.display_confirmed_at }
    context "when confirmet_at is not nil" do
      let(:contribution){ build(:contribution, confirmed_at: Time.now) }
      it{ is_expected.to eq(I18n.l(contribution.confirmed_at.to_date)) }
    end

    context "when confirmet_at is nil" do
      let(:contribution){ build(:contribution, confirmed_at: nil) }
      it{ is_expected.to be_nil }
    end
  end

  describe "#display_value" do

    context "when the value has decimal places" do
      subject{ build(:contribution, value: 99.99).display_value }
      it{ is_expected.to eq("R$ 99,99") }
    end

    context "when the value does not have decimal places" do
      subject{ build(:contribution, value: 1).display_value }
      it{ is_expected.to eq("R$ 1,00") }
    end
  end

  describe "#display_slip_url" do
    context "when slip_url is filled" do
      subject { build(:contribution, slip_url: 'http://foo.bar/').display_slip_url }
      it{ is_expected.to eq('http://foo.bar/')}
    end

    context "when slip_url is not filled" do
      subject { build(:contribution).display_slip_url }
      it{ is_expected.to match(/www\.moip\.com\.br/) }
    end
  end
end


text:
#ifndef	_FNMATCH_H_
#define	_FNMATCH_H_

#define	FNM_NOMATCH	1	/* Match failed. */

#define	FNM_NOESCAPE	0x01	/* Disable backslash escaping. */
#define	FNM_PATHNAME	0x02	/* Slash must be matched by slash. */
#define	FNM_PERIOD	0x04	/* Period must be matched by period. */
#define	FNM_LEADING_DIR	0x08	/* Ignore /<tail> after Imatch. */
#define	FNM_CASEFOLD	0x10	/* Case insensitive search. */
#define FNM_PREFIX_DIRS	0x20	/* Directory prefixes of pattern match too. */

/* Make this compile successfully with "gcc -traditional" */
#ifndef __STDC__
#define const	/* empty */
#endif

int	 fnmatch(const char *, const char *, int);

#endif /* !_FNMATCH_H_ */


text:
// Copyright (c) 2020 Shivaram Lingamneni
// released under the MIT license

package mysql

import (
	"context"
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"runtime/debug"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	"github.com/ergochat/ergo/irc/history"
	"github.com/ergochat/ergo/irc/logger"
	"github.com/ergochat/ergo/irc/utils"
	_ "github.com/go-sql-driver/mysql"
)

var (
	ErrDisallowed = errors.New("disallowed")
)

const (
	// maximum length in bytes of any message target (nickname or channel name) in its
	// canonicalized (i.e., casefolded) state:
	MaxTargetLength = 64

	// latest schema of the db
	latestDbSchema   = "2"
	keySchemaVersion = "db.version"
	// minor version indicates rollback-safe upgrades, i.e.,
	// you can downgrade oragono and everything will work
	latestDbMinorVersion  = "2"
	keySchemaMinorVersion = "db.minorversion"
	cleanupRowLimit       = 50
	cleanupPauseTime      = 10 * time.Minute
)

type e struct{}

type MySQL struct {
	timeout              int64
	trackAccountMessages uint32
	db                   *sql.DB
	logger               *logger.Manager

	insertHistory        *sql.Stmt
	insertSequence       *sql.Stmt
	insertConversation   *sql.Stmt
	insertCorrespondent  *sql.Stmt
	insertAccountMessage *sql.Stmt

	stateMutex sync.Mutex
	config     Config

	wakeForgetter chan e
}

func (mysql *MySQL) Initialize(logger *logger.Manager, config Config) {
	mysql.logger = logger
	mysql.wakeForgetter = make(chan e, 1)
	mysql.SetConfig(config)
}

func (mysql *MySQL) SetConfig(config Config) {
	atomic.StoreInt64(&mysql.timeout, int64(config.Timeout))
	var trackAccountMessages uint32
	if config.TrackAccountMessages {
		trackAccountMessages = 1
	}
	atomic.StoreUint32(&mysql.trackAccountMessages, trackAccountMessages)
	mysql.stateMutex.Lock()
	mysql.config = config
	mysql.stateMutex.Unlock()
}

func (mysql *MySQL) getExpireTime() (expireTime time.Duration) {
	mysql.stateMutex.Lock()
	expireTime = mysql.config.ExpireTime
	mysql.stateMutex.Unlock()
	return
}

func (m *MySQL) Open() (err error) {
	var address string
	if m.config.SocketPath != "" {
		address = fmt.Sprintf("unix(%s)", m.config.SocketPath)
	} else if m.config.Port != 0 {
		address = fmt.Sprintf("tcp(%s:%d)", m.config.Host, m.config.Port)
	}

	m.db, err = sql.Open("mysql", fmt.Sprintf("%s:%s@%s/%s", m.config.User, m.config.Password, address, m.config.HistoryDatabase))
	if err != nil {
		return err
	}

	if m.config.MaxConns != 0 {
		m.db.SetMaxOpenConns(m.config.MaxConns)
		m.db.SetMaxIdleConns(m.config.MaxConns)
	}
	if m.config.ConnMaxLifetime != 0 {
		m.db.SetConnMaxLifetime(m.config.ConnMaxLifetime)
	}

	err = m.fixSchemas()
	if err != nil {
		return err
	}

	err = m.prepareStatements()
	if err != nil {
		return err
	}

	go m.cleanupLoop()
	go m.forgetLoop()

	return nil
}

func (mysql *MySQL) fixSchemas() (err error) {
	_, err = mysql.db.Exec(`CREATE TABLE IF NOT EXISTS metadata (
		key_name VARCHAR(32) primary key,
		value VARCHAR(32) NOT NULL
	) CHARSET=ascii COLLATE=ascii_bin;`)
	if err != nil {
		return err
	}

	var schema string
	err = mysql.db.QueryRow(`select value from metadata where key_name = ?;`, keySchemaVersion).Scan(&schema)
	if err == sql.ErrNoRows {
		err = mysql.createTables()
		if err != nil {
			return
		}
		_, err = mysql.db.Exec(`insert into metadata (key_name, value) values (?, ?);`, keySchemaVersion, latestDbSchema)
		if err != nil {
			return
		}
		_, err = mysql.db.Exec(`insert into metadata (key_name, value) values (?, ?);`, keySchemaMinorVersion, latestDbMinorVersion)
		if err != nil {
			return
		}
		return
	} else if err == nil && schema != latestDbSchema {
		// TODO figure out what to do about schema changes
		return fmt.Errorf("incompatible schema: got %s, expected %s", schema, latestDbSchema)
	} else if err != nil {
		return err
	}

	var minorVersion string
	err = mysql.db.QueryRow(`select value from metadata where key_name = ?;`, keySchemaMinorVersion).Scan(&minorVersion)
	if err == sql.ErrNoRows {
		// XXX for now, the only minor version upgrade is the account tracking tables
		err = mysql.createComplianceTables()
		if err != nil {
			return
		}
		err = mysql.createCorrespondentsTable()
		if err != nil {
			return
		}
		_, err = mysql.db.Exec(`insert into metadata (key_name, value) values (?, ?);`, keySchemaMinorVersion, latestDbMinorVersion)
		if err != nil {
			return
		}
	} else if err == nil && minorVersion == "1" {
		// upgrade from 2.1 to 2.2: create the correspondents table
		err = mysql.createCorrespondentsTable()
		if err != nil {
			return
		}
		_, err = mysql.db.Exec(`update metadata set value = ? where key_name = ?;`, latestDbMinorVersion, keySchemaMinorVersion)
		if err != nil {
			return
		}
	} else if err == nil && minorVersion != latestDbMinorVersion {
		// TODO: if minorVersion < latestDbMinorVersion, upgrade,
		// if latestDbMinorVersion < minorVersion, ignore because backwards compatible
	}
	return
}

func (mysql *MySQL) createTables() (err error) {
	_, err = mysql.db.Exec(`CREATE TABLE history (
		id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
		data BLOB NOT NULL,
		msgid BINARY(16) NOT NULL,
		KEY (msgid(4))
	) CHARSET=ascii COLLATE=ascii_bin;`)
	if err != nil {
		return err
	}

	_, err = mysql.db.Exec(fmt.Sprintf(`CREATE TABLE sequence (
		history_id BIGINT UNSIGNED NOT NULL PRIMARY KEY,
		target VARBINARY(%[1]d) NOT NULL,
		nanotime BIGINT UNSIGNED NOT NULL,
		KEY (target, nanotime)
	) CHARSET=ascii COLLATE=ascii_bin;`, MaxTargetLength))
	if err != nil {
		return err
	}
	/* XXX: this table used to be:
	CREATE TABLE sequence (
		id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
		target VARBINARY(%[1]d) NOT NULL,
		nanotime BIGINT UNSIGNED NOT NULL,
		history_id BIGINT NOT NULL,
		KEY (target, nanotime),
		KEY (history_id)
	) CHARSET=ascii COLLATE=ascii_bin;
	Some users may still be using the old schema.
	*/

	_, err = mysql.db.Exec(fmt.Sprintf(`CREATE TABLE conversations (
		id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
		target VARBINARY(%[1]d) NOT NULL,
		correspondent VARBINARY(%[1]d) NOT NULL,
		nanotime BIGINT UNSIGNED NOT NULL,
		history_id BIGINT NOT NULL,
		KEY (target, correspondent, nanotime),
		KEY (history_id)
	) CHARSET=ascii COLLATE=ascii_bin;`, MaxTargetLength))
	if err != nil {
		return err
	}

	err = mysql.createCorrespondentsTable()
	if err != nil {
		return err
	}

	err = mysql.createComplianceTables()
	if err != nil {
		return err
	}

	return nil
}

func (mysql *MySQL) createCorrespondentsTable() (err error) {
	_, err = mysql.db.Exec(fmt.Sprintf(`CREATE TABLE correspondents (
		id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
		target VARBINARY(%[1]d) NOT NULL,
		correspondent VARBINARY(%[1]d) NOT NULL,
		nanotime BIGINT UNSIGNED NOT NULL,
		UNIQUE KEY (target, correspondent),
		KEY (target, nanotime),
		KEY (nanotime)
	) CHARSET=ascii COLLATE=ascii_bin;`, MaxTargetLength))
	return
}

func (mysql *MySQL) createComplianceTables() (err error) {
	_, err = mysql.db.Exec(fmt.Sprintf(`CREATE TABLE account_messages (
		history_id BIGINT UNSIGNED NOT NULL PRIMARY KEY,
		account VARBINARY(%[1]d) NOT NULL,
		KEY (account, history_id)
	) CHARSET=ascii COLLATE=ascii_bin;`, MaxTargetLength))
	if err != nil {
		return err
	}

	_, err = mysql.db.Exec(fmt.Sprintf(`CREATE TABLE forget (
		id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
		account VARBINARY(%[1]d) NOT NULL
	) CHARSET=ascii COLLATE=ascii_bin;`, MaxTargetLength))
	if err != nil {
		return err
	}

	return nil
}

func (mysql *MySQL) cleanupLoop() {
	defer func() {
		if r := recover(); r != nil {
			mysql.logger.Error("mysql",
				fmt.Sprintf("Panic in cleanup routine: %v\n%s", r, debug.Stack()))
			time.Sleep(cleanupPauseTime)
			go mysql.cleanupLoop()
		}
	}()

	for {
		expireTime := mysql.getExpireTime()
		if expireTime != 0 {
			for {
				startTime := time.Now()
				rowsDeleted, err := mysql.doCleanup(expireTime)
				elapsed := time.Now().Sub(startTime)
				mysql.logError("error during row cleanup", err)
				// keep going as long as we're accomplishing significant work
				// (don't busy-wait on small numbers of rows expiring):
				if rowsDeleted < (cleanupRowLimit / 10) {
					break
				}
				// crude backpressure mechanism: if the database is slow,
				// give it time to process other queries
				time.Sleep(elapsed)
			}
		}
		time.Sleep(cleanupPauseTime)
	}
}

func (mysql *MySQL) doCleanup(age time.Duration) (count int, err error) {
	ctx, cancel := context.WithTimeout(context.Background(), cleanupPauseTime)
	defer cancel()

	ids, maxNanotime, err := mysql.selectCleanupIDs(ctx, age)
	if len(ids) == 0 {
		mysql.logger.Debug("mysql", "found no rows to clean up")
		return
	}

	mysql.logger.Debug("mysql", fmt.Sprintf("deleting %d history rows, max age %s", len(ids), utils.NanoToTimestamp(maxNanotime)))

	if maxNanotime != 0 {
		mysql.deleteCorrespondents(ctx, maxNanotime)
	}

	return len(ids), mysql.deleteHistoryIDs(ctx, ids)
}

func (mysql *MySQL) deleteHistoryIDs(ctx context.Context, ids []uint64) (err error) {
	// can't use ? binding for a variable number of arguments, build the IN clause manually
	var inBuf strings.Builder
	inBuf.WriteByte('(')
	for i, id := range ids {
		if i != 0 {
			inBuf.WriteRune(',')
		}
		fmt.Fprintf(&inBuf, "%d", id)
	}
	inBuf.WriteRune(')')
	inClause := inBuf.String()

	_, err = mysql.db.ExecContext(ctx, fmt.Sprintf(`DELETE FROM conversations WHERE history_id in %s;`, inClause))
	if err != nil {
		return
	}
	_, err = mysql.db.ExecContext(ctx, fmt.Sprintf(`DELETE FROM sequence WHERE history_id in %s;`, inClause))
	if err != nil {
		return
	}
	if mysql.isTrackingAccountMessages() {
		_, err = mysql.db.ExecContext(ctx, fmt.Sprintf(`DELETE FROM account_messages WHERE history_id in %s;`, inClause))
		if err != nil {
			return
		}
	}
	_, err = mysql.db.ExecContext(ctx, fmt.Sprintf(`DELETE FROM history WHERE id in %s;`, inClause))
	if err != nil {
		return
	}

	return
}

func (mysql *MySQL) selectCleanupIDs(ctx context.Context, age time.Duration) (ids []uint64, maxNanotime int64, err error) {
	rows, err := mysql.db.QueryContext(ctx, `
		SELECT history.id, sequence.nanotime, conversations.nanotime
		FROM history
		LEFT JOIN sequence ON history.id = sequence.history_id
		LEFT JOIN conversations on history.id = conversations.history_id
		ORDER BY history.id LIMIT ?;`, cleanupRowLimit)
	if err != nil {
		return
	}
	defer rows.Close()

	idset := make(map[uint64]struct{}, cleanupRowLimit)
	threshold := time.Now().Add(-age).UnixNano()
	for rows.Next() {
		var id uint64
		var seqNano, convNano sql.NullInt64
		err = rows.Scan(&id, &seqNano, &convNano)
		if err != nil {
			return
		}
		nanotime := extractNanotime(seqNano, convNano)
		// returns 0 if not found; in that case the data is inconsistent
		// and we should delete the entry
		if nanotime < threshold {
			idset[id] = struct{}{}
			if nanotime > maxNanotime {
				maxNanotime = nanotime
			}
		}
	}
	ids = make([]uint64, len(idset))
	i := 0
	for id := range idset {
		ids[i] = id
		i++
	}
	return
}

func (mysql *MySQL) deleteCorrespondents(ctx context.Context, threshold int64) {
	result, err := mysql.db.ExecContext(ctx, `DELETE FROM correspondents WHERE nanotime <= (?);`, threshold)
	if err != nil {
		mysql.logError("error deleting correspondents", err)
	} else {
		count, err := result.RowsAffected()
		if !mysql.logError("error deleting correspondents", err) {
			mysql.logger.Debug(fmt.Sprintf("deleted %d correspondents entries", count))
		}
	}
}

// wait for forget queue items and process them one by one
func (mysql *MySQL) forgetLoop() {
	defer func() {
		if r := recover(); r != nil {
			mysql.logger.Error("mysql",
				fmt.Sprintf("Panic in forget routine: %v\n%s", r, debug.Stack()))
			time.Sleep(cleanupPauseTime)
			go mysql.forgetLoop()
		}
	}()

	for {
		for {
			found, err := mysql.doForget()
			mysql.logError("error processing forget", err)
			if err != nil {
				time.Sleep(cleanupPauseTime)
			}
			if !found {
				break
			}
		}

		<-mysql.wakeForgetter
	}
}

// dequeue an item from the forget queue and process it
func (mysql *MySQL) doForget() (found bool, err error) {
	id, account, err := func() (id int64, account string, err error) {
		ctx, cancel := context.WithTimeout(context.Background(), cleanupPauseTime)
		defer cancel()

		row := mysql.db.QueryRowContext(ctx,
			`SELECT forget.id, forget.account FROM forget LIMIT 1;`)
		err = row.Scan(&id, &account)
		if err == sql.ErrNoRows {
			return 0, "", nil
		}
		return
	}()

	if err != nil || account == "" {
		return false, err
	}

	found = true

	var count int
	for {
		start := time.Now()
		count, err = mysql.doForgetIteration(account)
		elapsed := time.Since(start)
		if err != nil {
			return true, err
		}
		if count == 0 {
			break
		}
		time.Sleep(elapsed)
	}

	mysql.logger.Debug("mysql", "forget complete for account", account)

	ctx, cancel := context.WithTimeout(context.Background(), cleanupPauseTime)
	defer cancel()
	_, err = mysql.db.ExecContext(ctx, `DELETE FROM forget where id = ?;`, id)
	return
}

func (mysql *MySQL) doForgetIteration(account string) (count int, err error) {
	ctx, cancel := context.WithTimeout(context.Background(), cleanupPauseTime)
	defer cancel()

	rows, err := mysql.db.QueryContext(ctx, `
		SELECT account_messages.history_id
		FROM account_messages
		WHERE account_messages.account = ?
		LIMIT ?;`, account, cleanupRowLimit)
	if err != nil {
		return
	}
	defer rows.Close()

	var ids []uint64
	for rows.Next() {
		var id uint64
		err = rows.Scan(&id)
		if err != nil {
			return
		}
		ids = append(ids, id)
	}

	if len(ids) == 0 {
		return
	}

	mysql.logger.Debug("mysql", fmt.Sprintf("deleting %d history rows from account %s", len(ids), account))
	err = mysql.deleteHistoryIDs(ctx, ids)
	return len(ids), err
}

func (mysql *MySQL) prepareStatements() (err error) {
	mysql.insertHistory, err = mysql.db.Prepare(`INSERT INTO history
		(data, msgid) VALUES (?, ?);`)
	if err != nil {
		return
	}
	mysql.insertSequence, err = mysql.db.Prepare(`INSERT INTO sequence
		(target, nanotime, history_id) VALUES (?, ?, ?);`)
	if err != nil {
		return
	}
	mysql.insertConversation, err = mysql.db.Prepare(`INSERT INTO conversations
		(target, correspondent, nanotime, history_id) VALUES (?, ?, ?, ?);`)
	if err != nil {
		return
	}
	mysql.insertCorrespondent, err = mysql.db.Prepare(`INSERT INTO correspondents
		(target, correspondent, nanotime) VALUES (?, ?, ?)
		ON DUPLICATE KEY UPDATE nanotime = GREATEST(nanotime, ?);`)
	if err != nil {
		return
	}
	mysql.insertAccountMessage, err = mysql.db.Prepare(`INSERT INTO account_messages
		(history_id, account) VALUES (?, ?);`)
	if err != nil {
		return
	}

	return
}

func (mysql *MySQL) getTimeout() time.Duration {
	return time.Duration(atomic.LoadInt64(&mysql.timeout))
}

func (mysql *MySQL) isTrackingAccountMessages() bool {
	return atomic.LoadUint32(&mysql.trackAccountMessages) != 0
}

func (mysql *MySQL) logError(context string, err error) (quit bool) {
	if err != nil {
		mysql.logger.Error("mysql", context, err.Error())
		return true
	}
	return false
}

func (mysql *MySQL) Forget(account string) {
	if mysql.db == nil || account == "" {
		return
	}

	ctx, cancel := context.WithTimeout(context.Background(), mysql.getTimeout())
	defer cancel()

	_, err := mysql.db.ExecContext(ctx, `INSERT INTO forget (account) VALUES (?);`, account)
	if mysql.logError("can't insert into forget table", err) {
		return
	}

	// wake up the forget goroutine if it's blocked:
	select {
	case mysql.wakeForgetter <- e{}:
	default:
	}
}

func (mysql *MySQL) AddChannelItem(target string, item history.Item, account string) (err error) {
	if mysql.db == nil {
		return
	}

	if target == "" {
		return utils.ErrInvalidParams
	}

	ctx, cancel := context.WithTimeout(context.Background(), mysql.getTimeout())
	defer cancel()

	id, err := mysql.insertBase(ctx, item)
	if err != nil {
		return
	}

	err = mysql.insertSequenceEntry(ctx, target, item.Message.Time.UnixNano(), id)
	if err != nil {
		return
	}

	err = mysql.insertAccountMessageEntry(ctx, id, account)
	if err != nil {
		return
	}

	return
}

func (mysql *MySQL) insertSequenceEntry(ctx context.Context, target string, messageTime int64, id int64) (err error) {
	_, err = mysql.insertSequence.ExecContext(ctx, target, messageTime, id)
	mysql.logError("could not insert sequence entry", err)
	return
}

func (mysql *MySQL) insertConversationEntry(ctx context.Context, target, correspondent string, messageTime int64, id int64) (err error) {
	_, err = mysql.insertConversation.ExecContext(ctx, target, correspondent, messageTime, id)
	mysql.logError("could not insert conversations entry", err)
	return
}

func (mysql *MySQL) insertCorrespondentsEntry(ctx context.Context, target, correspondent string, messageTime int64, historyId int64) (err error) {
	_, err = mysql.insertCorrespondent.ExecContext(ctx, target, correspondent, messageTime, messageTime)
	mysql.logError("could not insert conversations entry", err)
	return
}

func (mysql *MySQL) insertBase(ctx context.Context, item history.Item) (id int64, err error) {
	value, err := marshalItem(&item)
	if mysql.logError("could not marshal item", err) {
		return
	}

	msgidBytes, err := decodeMsgid(item.Message.Msgid)
	if mysql.logError("could not decode msgid", err) {
		return
	}

	result, err := mysql.insertHistory.ExecContext(ctx, value, msgidBytes)
	if mysql.logError("could not insert item", err) {
		return
	}
	id, err = result.LastInsertId()
	if mysql.logError("could not insert item", err) {
		return
	}

	return
}

func (mysql *MySQL) insertAccountMessageEntry(ctx context.Context, id int64, account string) (err error) {
	if account == "" || !mysql.isTrackingAccountMessages() {
		return
	}
	_, err = mysql.insertAccountMessage.ExecContext(ctx, id, account)
	mysql.logError("could not insert account-message entry", err)
	return
}

func (mysql *MySQL) AddDirectMessage(sender, senderAccount, recipient, recipientAccount string, item history.Item) (err error) {
	if mysql.db == nil {
		return
	}

	if senderAccount == "" && recipientAccount == "" {
		return
	}

	if sender == "" || recipient == "" {
		return utils.ErrInvalidParams
	}

	ctx, cancel := context.WithTimeout(context.Background(), mysql.getTimeout())
	defer cancel()

	id, err := mysql.insertBase(ctx, item)
	if err != nil {
		return
	}

	nanotime := item.Message.Time.UnixNano()

	if senderAccount != "" {
		err = mysql.insertConversationEntry(ctx, senderAccount, recipient, nanotime, id)
		if err != nil {
			return
		}
		err = mysql.insertCorrespondentsEntry(ctx, senderAccount, recipient, nanotime, id)
		if err != nil {
			return
		}
	}

	if recipientAccount != "" && sender != recipient {
		err = mysql.insertConversationEntry(ctx, recipientAccount, sender, nanotime, id)
		if err != nil {
			return
		}
		err = mysql.insertCorrespondentsEntry(ctx, recipientAccount, sender, nanotime, id)
		if err != nil {
			return
		}
	}

	err = mysql.insertAccountMessageEntry(ctx, id, senderAccount)
	if err != nil {
		return
	}

	return
}

// note that accountName is the unfolded name
func (mysql *MySQL) DeleteMsgid(msgid, accountName string) (err error) {
	if mysql.db == nil {
		return nil
	}

	ctx, cancel := context.WithTimeout(context.Background(), mysql.getTimeout())
	defer cancel()

	_, id, data, err := mysql.lookupMsgid(ctx, msgid, true)
	if err != nil {
		return
	}

	if accountName != "*" {
		var item history.Item
		err = unmarshalItem(data, &item)
		// delete if the entry is corrupt
		if err == nil && item.AccountName != accountName {
			return ErrDisallowed
		}
	}

	err = mysql.deleteHistoryIDs(ctx, []uint64{id})
	mysql.logError("couldn't delete msgid", err)
	return
}

func (mysql *MySQL) Export(account string, writer io.Writer) {
	if mysql.db == nil {
		return
	}

	var err error
	var lastSeen uint64
	for {
		rows := func() (count int) {
			ctx, cancel := context.WithTimeout(context.Background(), cleanupPauseTime)
			defer cancel()

			rows, rowsErr := mysql.db.QueryContext(ctx, `
				SELECT account_messages.history_id, history.data, sequence.target FROM account_messages
				INNER JOIN history ON history.id = account_messages.history_id
				INNER JOIN sequence ON account_messages.history_id = sequence.history_id
				WHERE account_messages.account = ? AND account_messages.history_id > ?
				LIMIT ?`, account, lastSeen, cleanupRowLimit)
			if rowsErr != nil {
				err = rowsErr
				return
			}
			defer rows.Close()
			for rows.Next() {
				var id uint64
				var blob, jsonBlob []byte
				var target string
				var item history.Item
				err = rows.Scan(&id, &blob, &target)
				if err != nil {
					return
				}
				err = unmarshalItem(blob, &item)
				if err != nil {
					return
				}
				item.CfCorrespondent = target
				jsonBlob, err = json.Marshal(item)
				if err != nil {
					return
				}
				count++
				if lastSeen < id {
					lastSeen = id
				}
				writer.Write(jsonBlob)
				writer.Write([]byte{'\n'})
			}
			return
		}()
		if rows == 0 || err != nil {
			break
		}
	}

	mysql.logError("could not export history", err)
	return
}

func (mysql *MySQL) lookupMsgid(ctx context.Context, msgid string, includeData bool) (result time.Time, id uint64, data []byte, err error) {
	decoded, err := decodeMsgid(msgid)
	if err != nil {
		return
	}
	cols := `sequence.nanotime, conversations.nanotime`
	if includeData {
		cols = `sequence.nanotime, conversations.nanotime, history.id, history.data`
	}
	row := mysql.db.QueryRowContext(ctx, fmt.Sprintf(`
		SELECT %s FROM history
		LEFT JOIN sequence ON history.id = sequence.history_id
		LEFT JOIN conversations ON history.id = conversations.history_id
		WHERE history.msgid = ? LIMIT 1;`, cols), decoded)
	var nanoSeq, nanoConv sql.NullInt64
	if !includeData {
		err = row.Scan(&nanoSeq, &nanoConv)
	} else {
		err = row.Scan(&nanoSeq, &nanoConv, &id, &data)
	}
	if err != sql.ErrNoRows {
		mysql.logError("could not resolve msgid to time", err)
	}
	if err != nil {
		return
	}
	nanotime := extractNanotime(nanoSeq, nanoConv)
	if nanotime == 0 {
		err = sql.ErrNoRows
		return
	}
	result = time.Unix(0, nanotime).UTC()
	return
}

func extractNanotime(seq, conv sql.NullInt64) (result int64) {
	if seq.Valid {
		return seq.Int64
	} else if conv.Valid {
		return conv.Int64
	}
	return
}

func (mysql *MySQL) selectItems(ctx context.Context, query string, args ...interface{}) (results []history.Item, err error) {
	rows, err := mysql.db.QueryContext(ctx, query, args...)
	if mysql.logError("could not select history items", err) {
		return
	}

	defer rows.Close()

	for rows.Next() {
		var blob []byte
		var item history.Item
		err = rows.Scan(&blob)
		if mysql.logError("could not scan history item", err) {
			return
		}
		err = unmarshalItem(blob, &item)
		if mysql.logError("could not unmarshal history item", err) {
			return
		}
		results = append(results, item)
	}
	return
}

func (mysql *MySQL) betweenTimestamps(ctx context.Context, target, correspondent string, after, before, cutoff time.Time, limit int) (results []history.Item, err error) {
	useSequence := correspondent == ""
	table := "sequence"
	if !useSequence {
		table = "conversations"
	}

	after, before, ascending := history.MinMaxAsc(after, before, cutoff)
	direction := "ASC"
	if !ascending {
		direction = "DESC"
	}

	var queryBuf strings.Builder

	args := make([]interface{}, 0, 6)
	fmt.Fprintf(&queryBuf,
		"SELECT history.data from history INNER JOIN %[1]s ON history.id = %[1]s.history_id WHERE", table)
	if useSequence {
		fmt.Fprintf(&queryBuf, " sequence.target = ?")
		args = append(args, target)
	} else {
		fmt.Fprintf(&queryBuf, " conversations.target = ? AND conversations.correspondent = ?")
		args = append(args, target)
		args = append(args, correspondent)
	}
	if !after.IsZero() {
		fmt.Fprintf(&queryBuf, " AND %s.nanotime > ?", table)
		args = append(args, after.UnixNano())
	}
	if !before.IsZero() {
		fmt.Fprintf(&queryBuf, " AND %s.nanotime < ?", table)
		args = append(args, before.UnixNano())
	}
	fmt.Fprintf(&queryBuf, " ORDER BY %[1]s.nanotime %[2]s LIMIT ?;", table, direction)
	args = append(args, limit)

	results, err = mysql.selectItems(ctx, queryBuf.String(), args...)
	if err == nil && !ascending {
		history.Reverse(results)
	}
	return
}

func (mysql *MySQL) listCorrespondentsInternal(ctx context.Context, target string, after, before, cutoff time.Time, limit int) (results []history.TargetListing, err error) {
	after, before, ascending := history.MinMaxAsc(after, before, cutoff)
	direction := "ASC"
	if !ascending {
		direction = "DESC"
	}

	var queryBuf strings.Builder
	args := make([]interface{}, 0, 4)
	queryBuf.WriteString(`SELECT correspondents.correspondent, correspondents.nanotime from correspondents
		WHERE target = ?`)
	args = append(args, target)
	if !after.IsZero() {
		queryBuf.WriteString(" AND correspondents.nanotime > ?")
		args = append(args, after.UnixNano())
	}
	if !before.IsZero() {
		queryBuf.WriteString(" AND correspondents.nanotime < ?")
		args = append(args, before.UnixNano())
	}
	fmt.Fprintf(&queryBuf, " ORDER BY correspondents.nanotime %s LIMIT ?;", direction)
	args = append(args, limit)
	query := queryBuf.String()

	rows, err := mysql.db.QueryContext(ctx, query, args...)
	if err != nil {
		return
	}
	defer rows.Close()
	var correspondent string
	var nanotime int64
	for rows.Next() {
		err = rows.Scan(&correspondent, &nanotime)
		if err != nil {
			return
		}
		results = append(results, history.TargetListing{
			CfName: correspondent,
			Time:   time.Unix(0, nanotime),
		})
	}

	if !ascending {
		history.ReverseCorrespondents(results)
	}

	return
}

func (mysql *MySQL) ListChannels(cfchannels []string) (results []history.TargetListing, err error) {
	if mysql.db == nil {
		return
	}

	if len(cfchannels) == 0 {
		return
	}

	ctx, cancel := context.WithTimeout(context.Background(), mysql.getTimeout())
	defer cancel()

	var queryBuf strings.Builder
	args := make([]interface{}, 0, len(results))
	// https://dev.mysql.com/doc/refman/8.0/en/group-by-optimization.html
	// this should be a "loose index scan"
	queryBuf.WriteString(`SELECT sequence.target, MAX(sequence.nanotime) FROM sequence
		WHERE sequence.target IN (`)
	for i, chname := range cfchannels {
		if i != 0 {
			queryBuf.WriteString(", ")
		}
		queryBuf.WriteByte('?')
		args = append(args, chname)
	}
	queryBuf.WriteString(") GROUP BY sequence.target;")

	rows, err := mysql.db.QueryContext(ctx, queryBuf.String(), args...)
	if mysql.logError("could not query channel listings", err) {
		return
	}
	defer rows.Close()

	var target string
	var nanotime int64
	for rows.Next() {
		err = rows.Scan(&target, &nanotime)
		if mysql.logError("could not scan channel listings", err) {
			return
		}
		results = append(results, history.TargetListing{
			CfName: target,
			Time:   time.Unix(0, nanotime),
		})
	}
	return
}

func (mysql *MySQL) Close() {
	// closing the database will close our prepared statements as well
	if mysql.db != nil {
		mysql.db.Close()
	}
	mysql.db = nil
}

// implements history.Sequence, emulating a single history buffer (for a channel,
// a single user's DMs, or a DM conversation)
type mySQLHistorySequence struct {
	mysql         *MySQL
	target        string
	correspondent string
	cutoff        time.Time
}

func (s *mySQLHistorySequence) Between(start, end history.Selector, limit int) (results []history.Item, err error) {
	ctx, cancel := context.WithTimeout(context.Background(), s.mysql.getTimeout())
	defer cancel()

	startTime := start.Time
	if start.Msgid != "" {
		startTime, _, _, err = s.mysql.lookupMsgid(ctx, start.Msgid, false)
		if err != nil {
			return nil, err
		}
	}
	endTime := end.Time
	if end.Msgid != "" {
		endTime, _, _, err = s.mysql.lookupMsgid(ctx, end.Msgid, false)
		if err != nil {
			return nil, err
		}
	}

	results, err = s.mysql.betweenTimestamps(ctx, s.target, s.correspondent, startTime, endTime, s.cutoff, limit)
	return results, err
}

func (s *mySQLHistorySequence) Around(start history.Selector, limit int) (results []history.Item, err error) {
	return history.GenericAround(s, start, limit)
}

func (seq *mySQLHistorySequence) ListCorrespondents(start, end history.Selector, limit int) (results []history.TargetListing, err error) {
	ctx, cancel := context.WithTimeout(context.Background(), seq.mysql.getTimeout())
	defer cancel()

	// TODO accept msgids here?
	startTime := start.Time
	endTime := end.Time

	results, err = seq.mysql.listCorrespondentsInternal(ctx, seq.target, startTime, endTime, seq.cutoff, limit)
	seq.mysql.logError("could not read correspondents", err)
	return
}

func (seq *mySQLHistorySequence) Cutoff() time.Time {
	return seq.cutoff
}

func (seq *mySQLHistorySequence) Ephemeral() bool {
	return false
}

func (mysql *MySQL) MakeSequence(target, correspondent string, cutoff time.Time) history.Sequence {
	return &mySQLHistorySequence{
		target:        target,
		correspondent: correspondent,
		mysql:         mysql,
		cutoff:        cutoff,
	}
}


text:
using ClosedXML.Excel;
using NUnit.Framework;

namespace ClosedXML.Tests.Excel.Ranges
{
    public class RangeShiftingTests
    {
        [Test]
        public void CellReferenceRemainAfterColumnDeleted()
        {
            using (var wb = new XLWorkbook())
            {
                var ws = wb.AddWorksheet();
                var d4 = ws.Cell("D4");

                ws.Column("C").Delete();

                Assert.AreSame(d4, ws.Cell("C4"));
            }
        }

        [Test]
        public void CellReferenceRemainAfterRowDeleted()
        {
            using (var wb = new XLWorkbook())
            {
                var ws = wb.AddWorksheet();
                var d4 = ws.Cell("D4");

                ws.Row(3).Delete();

                Assert.AreSame(d4, ws.Cell("D3"));
            }
        }

        [Test]
        public void CellReferenceRemainAfterColumnInserted()
        {
            using (var wb = new XLWorkbook())
            {
                var ws = wb.AddWorksheet();
                var d4 = ws.Cell("D4");

                ws.Column("C").InsertColumnsBefore(1);

                Assert.AreSame(d4, ws.Cell("E4"));
            }
        }

        [Test]
        public void CellReferenceRemainAfterRowInserted()
        {
            using (var wb = new XLWorkbook())
            {
                var ws = wb.AddWorksheet();
                var d4 = ws.Cell("D4");

                ws.Row(3).InsertRowsAbove(1);

                Assert.AreSame(d4, ws.Cell("D5"));
            }
        }

        [Test]
        public void CellReferenceRemainAfterRangeDeleted()
        {
            using (var wb = new XLWorkbook())
            {
                var ws = wb.AddWorksheet();
                var d4 = ws.Cell("D4");
                var f8 = ws.Cell("F8");

                ws.Range("B2:C5").Delete(XLShiftDeletedCells.ShiftCellsLeft);
                ws.Range("E5:F7").Delete(XLShiftDeletedCells.ShiftCellsUp);

                Assert.AreSame(d4, ws.Cell("B4"));
                Assert.AreSame(f8, ws.Cell("F5"));
            }
        }
    }
}


text:
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2013-2017 The Anoncoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifndef ANONCOIN_TXDB_LEVELDB_H
#define ANONCOIN_TXDB_LEVELDB_H

#include "leveldbwrapper.h"
#include "main.h"

#include <map>
#include <string>
#include <utility>
#include <vector>

class CCoins;
class uint256;

//! -dbcache default (MiB)
extern const int64_t nDefaultDbCache;
//! max. -dbcache in (MiB)
extern const int64_t nMaxDbCache;
//! min. -dbcache in (MiB)
extern const int64_t nMinDbCache;

/** CCoinsView backed by the LevelDB coin database (chainstate/) */
class CCoinsViewDB : public CCoinsView
{
protected:
    CLevelDBWrapper db;
public:
    CCoinsViewDB(size_t nCacheSize, bool fMemory = false, bool fWipe = false);

    bool GetCoins(const uint256 &txid, CCoins &coins) const;
    bool HaveCoins(const uint256 &txid) const;
    uint256 GetBestBlock() const;
    bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock);
    bool GetStats(CCoinsStats &stats) const;
};

//! We now return and sort the following structure of details during a LoadBlockIndexGuts() call.
//! This allows us to give a faster load time than could otherwise be done during initialization.
//! Using this we do not need to calculate every Scrypt hash, for every block in order to build
//! the cross-reference map, that information is already available as the 'key' field in the LevelDB
//! database.
struct BlockTreeEntry
{
    int nHeight;
    CBlockIndex* pBlockIndex;
    uint256 uintRealHash;
    bool operator <(const BlockTreeEntry& s2) const { return nHeight < s2.nHeight; }
};

/** Access to the block database (blocks/index/) */
class CBlockTreeDB : public CLevelDBWrapper
{
public:
    CBlockTreeDB(size_t nCacheSize, bool fMemory = false, bool fWipe = false);
private:
    CBlockTreeDB(const CBlockTreeDB&);
    void operator=(const CBlockTreeDB&);
public:
    bool WriteBlockIndex(const CDiskBlockIndex& blockindex);
    bool ReadBlockFileInfo(int nFile, CBlockFileInfo &fileinfo);
    bool WriteBlockFileInfo(int nFile, const CBlockFileInfo &fileinfo);
    bool ReadLastBlockFile(int &nFile);
    bool WriteLastBlockFile(int nFile);
    bool WriteReindexing(bool fReindex);
    bool ReadReindexing(bool &fReindex);
    bool ReadTxIndex(const uint256 &txid, CDiskTxPos &pos);
    bool WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> > &list);
    bool WriteFlag(const std::string &name, bool fValue);
    bool ReadFlag(const std::string &name, bool &fValue);
    bool LoadBlockIndexGuts( std::vector<BlockTreeEntry>& vSortedByHeight );
};

#endif // ANONCOIN_TXDB_LEVELDB_H


text:
layout: post
comments: true
title: "Blogging with Jupyter Notebooks"
date: 2020-04-12
tags: blogs
---

> With Notebooks, we can easily share prose, code, tables, charts, and more!

{: class="table-of-content"}
* TOC
{:toc}

Jupyter Notebooks is a great environment for creating blog posts. Or maybe you didn't even plan to write a blog post, but you've done some interesting experiments and you realize afterwards that you have results worth sharing. Either way, you'll want some way to get your Notebook onto your blog.

[fast_template](https://www.fast.ai/2020/01/16/fast_template/) and [nbdev](http://nbdev.fast.ai/) are set up to handle Jupyter Notebooks nicely, so there's not much you have to do to get this working. I'll walk you through the steps here. Note that Jupyter Notebooks and GitHub Pages already have some support for exporting notebooks to markdown; but I suggest you use `fast_template` and `nbdev`, with the process described in this post, because otherwise you won't get useful features such as:

- Support for pasting images directly into your notebook
- Input and output cells clearly displayed with appropriate styles
- The ability to hide some cells from the markdown output.

This whole post was created using this method. You can see the source notebook here:

## Writing your notebook

Your markdown cells, code cells, and all outputs will appear in your exported blog post. The only thing that won't be shown is interactive outputs (e.g. `ipywidgets`, bokeh plots, etc), or cells you explicitly hide using the `#hide` marker discussed below.

When you write your notebook, just write whatever you want your audience to see. Since most writing platforms make it much harder to include code and outputs, many of us are in a habit of including less real examples than we should. So try to get into a new habit of including lots of examples as you write.

Often you'll want to hide boilerplate such as import statements. Add `#hide` to the top of any cell to make it not show up in output.

Jupyter displays the result of the last line of a cell, so there's no need to include `print()`. (And including extra code that isn't needed means there's more cognitive overhead for the reader; so don't include code that you don't really need!)

```python
1+1
```

    2

It works not just for text, but also for images:

```python
Image.open('../fast.ai/images/fast_template/image2.png').flip_lr()
```

![png](/assets/images/blog_test_files/output_6_0.png)

...and plots:

```python
plt.plot([1,2]);
```

![png](/assets/images/blog_test_files/output_8_0.png)

...and Pandas DataFrames, and much more!

```python
pd.DataFrame({'a':[1,2], 'b':[3,4]})
```

      a
      b

      0
      1
      3

      1
      2
      4

You can also paste images, such as screenshots, directly into a markdown cell in Jupyter. This creates a file embedded in the notebook that Jupyter calls an "attachment". Or you can use Markdown to refer to an image on the internet by its URL.

![](https://upload.wikimedia.org/wikipedia/commons/1/1b/Creative-Tail-Animal-dog.svg)

## Exporting to markdown

Before you export to markdown, you first need to make sure your notebook is saved, so press `s` or click `File`➡`Save`. Then close the browser tab with the open notebook. This is important, because when we export to markdown any attachments will be exported to files, and the notebook will be updated to refer to those external files. Therefore, the notebook itself will change; if you leave it open, you may accidentally end up overwriting the updated notebook.

You'll need `nbdev` installed; if you haven't already, then install it with:

    pip install nbdev

Then, in your terminal, cd to the folder containing your notebook, and type (assuming your notebook is called `name.ipynb`):

    nbdev_nb2md name.ipynb

You'll see that a file `name.md` and folder `name_files` have been created (where "name" is replaced by your notebook file name). One problem is that the markdown exporter assumes your images will be in `name_files`, but on your blog they'll be in `/images/name_files`. So we need to do a search and replace to fix this in the markdown file. We can do this automatically with python. Create a file called `upd_md.py` with the following contents:

```python
import fileinput,re
for f in fileinput.input(inplace=True):
    print(re.sub(r'^(!.*]\()(\w+_files/)', r'\1/images/\2', f), end='')
```

Then, in the terminal, run (assuming that `upd_md.py` and your markdown doc are in the same folder):

    python upd_md.py name.md

This will modify your markdown doc inplace, so it will have the correct `/images/` prefix on each image reference.

Finally, copy `name_files` to the `images` folder in your blog repo, and `name.md` to your `_posts` folder, and rename `name.md` to have the required `YEAR-MONTH-DAY-name.md` format. Commit and push this to GitHub, and you should see your post!


text:
package io.vertigo.quarto.services.publisher;

/**
 * Formats de sortie supportés.
 *
 * @author pchretien, npiedeloup
 */
public enum PublisherFormat {
	/** OpenOffice Text. */
	ODT,
	/** DOCX Text. */
	DOCX;

	/**
	 * Mimetypes des différents formats gérés.
	 *
	 * @return Type Mime
	 */
	public String getMimeType() {
		switch (this) {
			case ODT:
				return "application/vnd.oasis.opendocument.text";
			case DOCX:
				return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
			default:
				throw new IllegalArgumentException("Format " + this + "non reconnu");
		}
	}
}


text:
require 'cap_git_tools/tasks'

module CapistranoNvieGitWorkflow::TaskHelpers
  include CapGitTools::TaskHelpers

  def changed_files(ref_start, ref_end)
    raw = `git log --name-status --oneline #{ref_start}...#{ref_end} | grep -e ^[MAD][[:space:]]`
    files = raw.split("\n")
    files.map {|f| f.sub(/^[MAD]\t/, '')}.uniq
  end

  def checkout_and_pull_branch(deployment_branch)
    if has_branch_locally?(deployment_branch)
      local_sh "git checkout #{deployment_branch}"
      local_sh "git pull #{upstream_remote} #{deployment_branch}"
    else
      local_sh "git checkout -b #{deployment_branch}  #{upstream_remote}/#{deployment_branch} -t"
    end
  end

  def choose_deployment_branch
    deployable_branches = get_deployable_branches
    Capistrano::CLI.ui.say "What branch do you want to deploy?"
    Capistrano::CLI.ui.choose *deployable_branches
  end

  def choose_deployment_tag
    tags = `git tag -l '#{previous_stage}-*'`.split("\n")
    Capistrano::CLI.ui.say "What tag do you want to deploy?"
    Capistrano::CLI.ui.choose *tags
  end

  def create_deployment_tag(version)
    timestamp = Time.now.localtime.strftime('%Y%m%d%H%M%S')
    deployment_tag = "#{fetch(:stage)}-#{version}-#{timestamp}"
    Capistrano::CLI.ui.say "    New deployment tag will be: #{deployment_tag}"
    return deployment_tag
  end

  def create_deployment_tag_from_branch(deploy_branch)
    version = deploy_branch.gsub /^(release|hotfix)-/, ''
    create_deployment_tag version
  end

  def deployment_file_paths
    paths = fetch(:deployment_file_paths) || []
    paths += fetch(:additional_deployment_file_paths) if exists?(:additional_deployment_file_paths)
    paths
  end

  def deployment_files_changed?(files)
    deployment_file_paths.each do |path|
      return true if files.any? {|f| f =~ /^#{path}/}
    end
    false
  end

  def filter_remote_branches
    rem_branches = local_sh("git branch -r --no-color").split "\n"
    rem_branches.reject! {|b| b =~ /HEAD/}
    rem_branches.map do |b|
      b = b.strip
      b.gsub!(/#{upstream_remote}\//, '')
      b.gsub!(/ .*/, '')
      b.strip
    end
  end

  def final_stage
    workflow_stages.last
  end

  def final_stage?
    final_stage == fetch(:stage).to_s
  end

  def guard_deployment_file_changes(files)
    return unless deployment_files_changed?(files)
    abort(<<-EOF)
  failed: deployment files have changed

    One or more deployment files have changed since the last time
    this branch was pulled. To ensure that all deployment files are
    loaded properly the process will now end, and must be restarted.
    EOF
  end

  def get_deployable_branches
    rem_branches = filter_remote_branches
    releases = rem_branches.map {|b| b if b =~ /^release-/}
    hotfixes = rem_branches.map {|b| b if b =~ /^hotfix-/}
    (releases + hotfixes).compact
  end

  def get_local_branches
    loc_branches = local_sh("git for-each-ref --format='%(refname:short)' refs/heads/*").chomp.split("\n")
    loc_branches
  end

  def get_version_from_tag(tag)
    tag.gsub(/(^\w+-)|(-\d+$)/, '')
  end

  def has_branch_locally?(target_branch)
    get_local_branches.include? target_branch
  end

  def initial_stage
    workflow_stages.first
  end

  def initial_stage?
    initial_stage == fetch(:stage).to_s
  end

  def local_sh(cmd)
    Capistrano::CLI.ui.say "    Executing locally: #{cmd}"
    r = `#{cmd}`
    abort("failed: #{cmd}") unless $? == 0
    r
  end

  def merge_tag_to_production(deploy_tag, version)
    `git checkout #{production_branch}`
    local_sh "git merge --no-ff --no-edit -m 'Release #{version} to #{fetch :stage}' #{deploy_tag}"
    local_sh "git push #{upstream_remote} #{production_branch}"
  end

  def next_stage
    next_idx = workflow_stages.index(fetch(:stage).to_s) + 1
    next_idx >= workflow_stages.size ? nil : workflow_stages[next_idx]
  end

  def previous_stage
    previous_idx = workflow_stages.index(fetch(:stage).to_s) - 1
    previous_idx < 0 ? nil : workflow_stages[previous_idx]
  end

  def production_branch
    fetch(:production_branch, 'master')
  end

  def setup_tagged_workflow_stage
    deploy_tag = choose_deployment_tag
    version = get_version_from_tag deploy_tag

    changed = changed_files current_branch, deploy_tag
    local_sh "git checkout #{deploy_tag}"
    guard_deployment_file_changes changed

    if final_stage?
      checkout_and_pull_branch fetch(:production_branch, 'master')
      merge_tag_to_production(deploy_tag, version) if final_stage?
    end

    _cset :tag, create_deployment_tag(version)
    _cset :from_tag, deploy_tag
  end

  def setup_initial_workflow_stage
    deployment_branch = choose_deployment_branch
    # use the current branch because the importance is on where the script starts
    # running from, not specific differences between revisions on the deployment
    # branch.
    changed = changed_files current_branch, "#{upstream_remote}/#{deployment_branch}"
    checkout_and_pull_branch deployment_branch
    guard_deployment_file_changes changed
    set :branch, deployment_branch
    _cset :tag, create_deployment_tag_from_branch(deployment_branch)
  end

  def workflow_stages
    @workflow_stages ||= if exists?(:workflow_stages)
      fetch :workflow_stages
    elsif fetch(:stages).size == 2
      stages = fetch(:stages).dup
      abort(<<-EOF) unless stages.delete('production')
  failed: No 'production' stage found

    You do not have a stage named 'production'. Please specify the proper
    stage deployment order by setting the :workflow_stages variable with
    the final production stage last.
    EOF

      stages << 'production'
      stages
    else
      abort(<<-EOF)
  failed: Unable to identify workflow stages

    You must either have only two stages defined in the :stages variable
    or you must set the :workflow_stages variable to the stages you want
    to deploy to, and their proper sequence.
      EOF
    end
  end
end


text:
service sputnik stop
service sputnik start
sleep 2
tail -f /var/log/sputnik.log


text:
"""Vendor: HP."""
from compass.hdsdiscovery import base

# Vendor_loader will load vendor instance by CLASS_NAME
CLASS_NAME = 'Hp'

class Hp(base.BaseSnmpVendor):
    """Hp switch object."""

    def __init__(self):
        base.BaseSnmpVendor.__init__(self, ['hp', 'procurve'])
        self.names = ['hp', 'procurve']

    @property
    def name(self):
        """Get 'name' proptery."""
        return self.names[0]


text:
// Copyright 2020 Oath Inc.
// Licensed under the terms of the Apache license. Please see LICENSE.md file distributed with this work for terms.
package com.yahoo.bard.webservice.data.metric.protocol.protocols;

import com.yahoo.bard.webservice.data.metric.protocol.Protocol;

import java.util.Collection;

/**
 * Define and implement a Reaggregation Protocol.
 */
public class ReaggregationProtocol {
    public static final String REAGGREGATION_CONTRACT_NAME = "reaggregation";
    public static final String REAGG_CORE_PARAMETER = "reagg";

    public static final Protocol INSTANCE = new Protocol(
            REAGGREGATION_CONTRACT_NAME,
            REAGG_CORE_PARAMETER,
            new TimeAverageMetricTransformer()
    );

    public static final Collection<String> acceptedValues() {
        return TimeAverageMetricTransformer.acceptedValues();
    }

    /**
     * Private constructor to keep singleton.
     */
    private ReaggregationProtocol() {

    }
}


text:
package edu.utah.sci.cyclist.neup.ui.views.flow;

import javafx.scene.Node;
import javafx.scene.layout.Pane;

public class ToggleIcon extends Pane {
	private boolean _selected = false;

	public ToggleIcon(Node first, Node second) {
		super();

		getChildren().addAll(first, second);
		select(false);
	}

	public void select(boolean value) {
		_selected = value;
		getChildren().get(0).setVisible(!value);
		getChildren().get(1).setVisible(value);
	}

	public boolean getSelected() {
		return _selected;
	}
}


text:
<?php
namespace Titon\Db\Mysql;

use Titon\Common\Config;
use Titon\Db\Driver\Dialect;
use Titon\Db\Driver\Schema;
use Titon\Db\Query;
use Titon\Test\Stub\Repository\User;

/**
 * @property \Titon\Db\Mysql\MysqlDialect $object
 */
class DialectTest extends \Titon\Db\Driver\DialectTest {

    protected function setUp() {
        $this->driver = new MysqlDriver(Config::get('db'));
        $this->driver->connect();

        $this->object = $this->driver->getDialect();
    }

    public function testBuildCreateIndex() {
        parent::testBuildCreateIndex();

        $query = new Query(Query::CREATE_INDEX, new User());
        $query->data(['profile_id'])->from('users', 'idx')
            ->attribute([
                'type' => MysqlDialect::FULLTEXT,
                'using' => function(Dialect $dialect) {
                    return sprintf($dialect->getClause(MysqlDialect::USING), $dialect->getKeyword(MysqlDialect::BTREE));
                }
            ]);

        $this->assertRegExp('/CREATE FULLTEXT INDEX (`|\")idx(`|\") ON (`|\")users(`|\") \((`|\")profile_id(`|\")\) USING BTREE/', $this->object->buildCreateIndex($query));
    }

    public function testBuildCreateTable() {
        $schema = new Schema('foobar');
        $schema->addColumn('column', [
            'type' => 'int',
            'ai' => true
        ]);

        $query = new Query(Query::CREATE_TABLE, new User());
        $query->schema($schema);

        $this->assertEquals("CREATE  TABLE IF NOT EXISTS `foobar` (\n`column` INT NOT NULL AUTO_INCREMENT\n);", $this->object->buildCreateTable($query));

        $schema->addColumn('column', [
            'type' => 'int',
            'ai' => true,
            'primary' => true
        ]);

        $this->assertEquals("CREATE  TABLE IF NOT EXISTS `foobar` (\n`column` INT NOT NULL AUTO_INCREMENT,\nPRIMARY KEY (`column`)\n);", $this->object->buildCreateTable($query));

        $schema->addColumn('column2', [
            'type' => 'int',
            'null' => true,
            'index' => true
        ]);

        $this->assertEquals("CREATE  TABLE IF NOT EXISTS `foobar` (\n`column` INT NOT NULL AUTO_INCREMENT,\n`column2` INT NULL,\nPRIMARY KEY (`column`)\n);", $this->object->buildCreateTable($query));

        $schema->addOption('engine', 'InnoDB');

        $this->assertEquals("CREATE  TABLE IF NOT EXISTS `foobar` (\n`column` INT NOT NULL AUTO_INCREMENT,\n`column2` INT NULL,\nPRIMARY KEY (`column`)\n) ENGINE InnoDB;", $this->object->buildCreateTable($query));

        $schema = new Schema('foobar');
        $schema->addColumn('column', [
            'type' => 'int',
            'ai' => true
        ]);

        $query = new Query(Query::CREATE_TABLE, new User());
        $query->schema($schema)->attribute('temporary', true);

        $this->assertEquals("CREATE TEMPORARY TABLE IF NOT EXISTS `foobar` (\n`column` INT NOT NULL AUTO_INCREMENT\n);", $this->object->buildCreateTable($query));
    }

    public function testBuildDeleteQuick() {
        $query = new Query(Query::DELETE, new User());
        $query->from('foobar')->attribute('quick', true);

        $this->assertRegExp('/DELETE\s+QUICK\s+FROM `foobar`;/', $this->object->buildDelete($query));
    }

    public function testBuildDeleteIgnore() {
        $query = new Query(Query::DELETE, new User());
        $query->from('foobar')->attribute('ignore', true);

        $this->assertRegExp('/DELETE\s+IGNORE\s+FROM `foobar`;/', $this->object->buildDelete($query));
    }

    public function testBuildDropTableTemporary() {
        $query = new Query(Query::DROP_TABLE, new User());
        $query->from('foobar')->attribute('temporary', true);

        $this->assertRegExp('/DROP TEMPORARY TABLE IF EXISTS `foobar`;/', $this->object->buildDropTable($query));
    }

    public function testBuildInsertIgnore() {
        $query = new Query(Query::INSERT, new User());
        $query->from('foobar')->data([
            'email' => 'email@domain.com',
            'website' => 'http://titon.io'
        ]);

        $query->attribute('ignore', true);
        $this->assertRegExp('/INSERT\s+IGNORE\s+INTO `foobar` \(`email`, `website`\) VALUES \(\?, \?\);/', $this->object->buildInsert($query));
    }

    public function testBuildInsertPriority() {
        $query = new Query(Query::INSERT, new User());
        $query->from('foobar')->data([
            'email' => 'email@domain.com',
            'website' => 'http://titon.io'
        ]);

        $query->attribute('priority', 'highPriority');
        $this->assertRegExp('/INSERT HIGH_PRIORITY  INTO `foobar` \(`email`, `website`\) VALUES \(\?, \?\);/', $this->object->buildInsert($query));
    }

    public function testBuildSelectDistinct() {
        $query = new Query(Query::SELECT, new User());
        $query->from('foobar')->attribute('distinct', true);

        $this->assertRegExp('/SELECT\s+DISTINCT\s+\* FROM `foobar`;/', $this->object->buildSelect($query));

        $query->attribute('distinct', 'all');
        $this->assertRegExp('/SELECT\s+ALL\s+\* FROM `foobar`;/', $this->object->buildSelect($query));
    }

    public function testBuildSelectOptimize() {
        $query = new Query(Query::SELECT, new User());
        $query->from('foobar')->attribute('optimize', 'sqlBufferResult');

        $this->assertRegExp('/SELECT\s+SQL_BUFFER_RESULT\s+\* FROM `foobar`;/', $this->object->buildSelect($query));
    }

    public function testBuildSelectCache() {
        $query = new Query(Query::SELECT, new User());
        $query->from('foobar')->attribute('cache', 'sqlCache');

        $this->assertRegExp('/SELECT\s+SQL_CACHE\s+\* FROM `foobar`;/', $this->object->buildSelect($query));
    }

    public function testBuildSelectUnions() {
        $user = new User();
        $query = $user->select('id');
        $query->union($query->subQuery('id')->from('u1'));

        $this->assertRegExp('/\(SELECT\s+(`|\")?id(`|\")? FROM (`|\")?users(`|\")?\s+\) UNION  \(SELECT\s+(`|\")?id(`|\")? FROM (`|\")?u1(`|\")?\);/', $this->object->buildSelect($query));

        // more joins
        $query->union($query->subQuery('id')->from('u2'), 'all');

        $this->assertRegExp('/\(SELECT\s+(`|\")?id(`|\")? FROM (`|\")?users(`|\")?\s+\) UNION  \(SELECT\s+(`|\")?id(`|\")? FROM (`|\")?u1(`|\")?\) UNION ALL \(SELECT\s+(`|\")?id(`|\")? FROM (`|\")?u2(`|\")?\);/', $this->object->buildSelect($query));

        // order by limit
        $query->orderBy('id', 'DESC')->limit(10);

        $this->assertRegExp('/\(SELECT\s+(`|\")?id(`|\")? FROM (`|\")?users(`|\")?\s+\) UNION  \(SELECT\s+(`|\")?id(`|\")? FROM (`|\")?u1(`|\")?\) UNION ALL \(SELECT\s+(`|\")?id(`|\")? FROM (`|\")?u2(`|\")?\) ORDER BY (`|\")?id(`|\")? DESC LIMIT 10;/', $this->object->buildSelect($query));
    }

    public function testBuildSelectLocking() {
        $query = new MysqlQuery(Query::SELECT, new User());
        $query->from('users')->where('name', 'like', '%miles%');

        $query->lockForShare();
        $this->assertRegExp('/SELECT\s+\* FROM\s+`users`\s+WHERE `name` LIKE \?\s+LOCK IN SHARE MODE;/', $this->object->buildSelect($query));

        $query->lockForUpdate();
        $this->assertRegExp('/SELECT\s+\* FROM\s+`users`\s+WHERE `name` LIKE \?\s+FOR UPDATE;/', $this->object->buildSelect($query));
    }

    public function testBuildUpdateIgnore() {
        $query = new Query(Query::UPDATE, new User());
        $query->from('foobar')->data(['username' => 'miles'])->attribute('ignore', true);

        $this->assertRegExp('/UPDATE\s+IGNORE\s+`foobar`\s+SET `username` = \?;/', $this->object->buildUpdate($query));
    }

    public function testBuildUpdatePriority() {
        $query = new Query(Query::UPDATE, new User());
        $query->from('foobar')->data(['username' => 'miles'])->attribute('priority', 'lowPriority');

        $this->assertRegExp('/UPDATE LOW_PRIORITY  `foobar`\s+SET `username` = \?;/', $this->object->buildUpdate($query));
    }

    public function testFormatCompounds() {
        $query = new Query(Query::INSERT, new User());

        $query->union($query->subQuery('id')->from('u1'));
        $this->assertRegExp('/\) UNION\s+\(SELECT\s+(`|\")?id(`|\")? FROM (`|\")?u1(`|\")?\)/', $this->object->formatCompounds($query->getCompounds()));

        // all
        $query->union($query->subQuery('id')->from('u2'), 'all');
        $this->assertRegExp('/\) UNION\s+\(SELECT\s+(`|\")?id(`|\")? FROM (`|\")?u1(`|\")?\) UNION ALL \(SELECT\s+(`|\")?id(`|\")? FROM (`|\")?u2(`|\")?\)/', $this->object->formatCompounds($query->getCompounds()));

        // distinct
        $query = new Query(Query::INSERT, new User());
        $query->union($query->subQuery('id')->from('u1'), 'distinct');
        $this->assertRegExp('/\) UNION DISTINCT \(SELECT\s+(`|\")?id(`|\")? FROM (`|\")?u1(`|\")?\)/', $this->object->formatCompounds($query->getCompounds()));
    }

    public function testGetStatement() {
        $this->assertEquals(new Dialect\Statement('INSERT {priority} {ignore} INTO {table} {fields} VALUES {values}'), $this->object->getStatement('insert'));
    }

    public function testRenderStatement() {
        $this->assertEquals('SELECT     * FROM tableName;', $this->object->renderStatement(Query::SELECT, [
            'table' => 'tableName',
            'fields' => '*'
        ]));
    }

}


text:
package nl.conspect.eventboot.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author arnoutvw
 * @since 29/10/14
 */
@Controller
public class IndexController {

    @RequestMapping("/")
    public String index() {
        return "forward:/index.html";
    }
}


text:
import * as React from 'react';
import {Fragment, useContext, useMemo} from 'react';
import {StoreContext} from 'react-devtools-shared/src/devtools/views/context';
import {useSubscription} from 'react-devtools-shared/src/devtools/views/hooks';
import {NativeStyleContext} from './context';
import LayoutViewer from './LayoutViewer';
import StyleEditor from './StyleEditor';
import {TreeStateContext} from '../TreeContext';

type Props = {};

export default function NativeStyleEditorWrapper(_: Props): React.Node {
  const store = useContext(StoreContext);

  const subscription = useMemo(
    () => ({
      getCurrentValue: () => store.supportsNativeStyleEditor,
      subscribe: (callback: Function) => {
        store.addListener('supportsNativeStyleEditor', callback);
        return () => {
          store.removeListener('supportsNativeStyleEditor', callback);
        };
      },
    }),
    [store],
  );
  const supportsNativeStyleEditor = useSubscription<boolean>(subscription);

  if (!supportsNativeStyleEditor) {
    return null;
  }

  return <NativeStyleEditor />;
}

function NativeStyleEditor(_: Props) {
  const {getStyleAndLayout} = useContext(NativeStyleContext);

  const {inspectedElementID} = useContext(TreeStateContext);
  if (inspectedElementID === null) {
    return null;
  }

  const maybeStyleAndLayout = getStyleAndLayout(inspectedElementID);
  if (maybeStyleAndLayout === null) {
    return null;
  }

  const {layout, style} = maybeStyleAndLayout;

  return (
    <Fragment>
      {layout !== null && (
        <LayoutViewer id={inspectedElementID} layout={layout} />
      )}
      {style !== null && (
        <StyleEditor
          id={inspectedElementID}
          style={style !== null ? style : {}}
        />
      )}
    </Fragment>
  );
}


text:
require 'test_helper'

class ShortUrlHitsHelperTest < ActionView::TestCase
  # def setup
  #   @short_url = short_urls(:google)
  # end

  # test 'records root hits' do
  #   assert_difference 'ShortUrlHit.count' do
  #     record_hit('root')
  #   end
  # end

  # test 'records non-root hits' do
  #   assert_difference 'ShortUrlHit.count' do
  #     record_hit
  #   end
  # end

end


text:
package com.verifalia.api.rest;

/**
 * HTTP REST request methods used by the Verifalia SDK.
 */
public enum HttpRequestMethod {
    GET,
    POST,
    DELETE
}


text:
package com.thoughtworks.go.agent.service;

import com.thoughtworks.go.util.URLService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean;
import org.springframework.stereotype.Component;

@Component
public class HttpInvokerProxyFactoryWrapper extends HttpInvokerProxyFactoryBean {

    @Autowired
    public void setUrlService(URLService urlService) {
        super.setServiceUrl(urlService.getBuildRepositoryURL());
    }

}


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel app\models\search\NotificationSubscriptionSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = Yii::t('app', 'Notification Subscriptions');
$this->params['breadcrumbs'][] = $this->title;
?>

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

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

        <?= Html::a(Yii::t('app', 'Create Notification Subscription'), ['create'], ['class' => 'btn btn-success']) ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'id',
            'user_id',
            'county_id',
            'title',
            'lat',
            // 'lng',
            // 'created_at',
            // 'updated_at',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"

    default-init-method="initialize" default-destroy-method="destroy">

    <!--
    By default, the Duo flow will use a statically-defined integration defined with the
    duo.properties file. If you need more flexibility, you can define a function bean
    called "shibboleth.authn.Duo.DuoIntegrationStrategy" to return an instance of
    net.shibboleth.idp.authn.duo.DuoIntegration based on the state of the request.

    The Duo flow is designed to operate in conjunction with some other login flow,
    usually orchestrated by the MFA login flow. It obtains the username to send to
    Duo based on the output of the other login flow or a previous session with the
    user. You can override that approach using a function bean called
    "shibboleth.authn.Duo.UsernameLookupStrategy" to supply the username from a
    different source.
    -->

</beans>


text:
package com.connexta.arbitro.cond.cluster.xacml3;

import com.connexta.arbitro.cond.Function;
import com.connexta.arbitro.cond.cluster.FunctionCluster;
import com.connexta.arbitro.cond.xacml3.StringConversionFunction;

import java.util.HashSet;
import java.util.Set;

/**
 * Clusters all the functions supported by StringConversionFunction
 */
public class StringConversionFunctionCluster implements FunctionCluster {

    public Set<Function> getSupportedFunctions() {
        Set<Function> set = new HashSet<Function>();
        for (String identifier : StringConversionFunction.getSupportedIdentifiers()){
            set.add(new StringConversionFunction(identifier));
        }
        return set;
    }
}


text:
'use strict';

// Declare app level module which depends on views, and components
var app = angular.module('myApp', [
    'ngRoute',
    'myApp.view1',
    'myApp.view2',
    'myApp.version',
    'angular.filter',
    'ngMaterial',
    'ngMessages'
]).
config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
  $locationProvider.hashPrefix('!');

  $routeProvider.otherwise({redirectTo: '/view1'});
}]);

app.constant('config', {
    gw2AccessToken: "3FDA2B03-EC05-EA4B-9901-7E7854D18CA48A682A20-2E8C-4205-B584-CB32EC4B744D",
});

app.constant('gw2ApiUrls', {
    Root: "https://api.guildwars2.com",
    QueryString: "?access_token=",
    Account: '/v2/account',
    AccountAchievements: '/v2/account/achievements',
    Bank: '/v2/account/bank',
    Dyes: '/v2/account/dyes',
    Finishers: '/v2/account/finishers',
    Inventory: '/v2/account/inventory',
    Masteries: '/v2/account/masteries',
    Materials: '/v2/account/materials',
    Minis: '/v2/account/minis',
    Outfits: '/v2/account/outfits',
    Recipies: '/v2/account/recipes',
    Skins: '/v2/account/skins',
    Titles: '/v2/account/titles',
    Wallet: '/v2/account/wallet',
    AllAchievements: '/v2/achievements/',
    AchievementCategories: '/v2/achievements/categories',
    DailyAchievements: '/v2/achievements/daily',
    TomorrowsDailyAchievements: '/v2/achievements/daily/tomorrow',
    AchievementGroups: '/v2/achievements/groups',
    BackstoryAnswers: '/v2/backstory/answers',
    BackstoryQuestions: '/v2/backstory/questions',
    Build: '/v2/build',
    Characters: '/v2/characters',
    Colors: '/v2/colors',
    Exchange: '/v2/commerce/exchange',
    Coins: '/v2/commerce/exchange/coins',
    Gems: '/v2/commerce/exchange/gems',
    Listings: '/v2/commerce/listings',
    Prices: '/v2/commerce/prices',
    Transactions: '/v2/commerce/transactions',
    Continents: '/v2/continents',
    Currencies: '/v2/currencies',
    Emblems: '/v2/emblem',
    Files: '/v2/files',
    AllFinishers: '/v2/finishers',
    Guild: '/v2/guild/: id',
    GuildLog: '/v2/guild/: id/log',
    GuildMembers: '/v2/guild/:id/members',
    GuildRanks: '/v2/guild/:id/ranks',
    GuildStash: '/v2/guild/:id/stash',
    GuildTeams: '/v2/guild/:id/teams',
    GuildTreasury: '/v2/guild/:id/treasury',
    GuildUpgrades: '/v2/guild/:id/upgrades',
    GuildPermissions: '/v2/guild/permissions',
    GuildSearch: '/v2/guild/search',
    GuildAllUpgrades: '/v2/guild/upgrades',
    Items: '/v2/items',
    ItemStats: '/v2/itemstats',
    Legends: '/v2/legends',
    Maps: '/v2/maps',
    AllMasteries: '/v2/masteries',
    AllMaterials: '/v2/materials',
    AllMinis: '/v2/minis',
    AllOutfits: '/v2/outfits',
    AllPets: '/v2/pets',
    AllProfessions: '/v2/professions',
    Pvp: '/v2/pvp',
    PvpAmulets: '/v2/pvp/amulets',
    PvpGames: '/v2/pvp/games',
    PvpRanks: '/v2/pvp/ranks',
    PvpSeasons: '/v2/pvp/seasons',
    PvpLeaderboards: '/v2/pvp/seasons/leaderboards',
    PvpStandings: '/v2/pvp/standings',
    PvpStats: '/v2/pvp/stats',
    Quaggans: '/v2/quaggans',
    AllRecipes: '/v2/recipes',
    SearchRecipies: '/v2/recipes/search',
    Skills: '/v2/skills',
    AllSkins: '/v2/skins',
    Specializations: '/v2/specializations',
    Stories: '/v2/stories',
    StorySeasons: '/v2/stories/seasons',
    AllTitles: '/v2/titles',
    TokenInfo: '/v2/tokeninfo',
    Traits: '/v2/traits',
    Worlds: '/v2/worlds',
    Wvw: '/v2/wvw',
    WvwAbilities: '/v2/wvw/abilities',
    WvwMatches: '/v2/wvw/matches',
    WvwObjectives: '/v2/wvw/objectives',
    WvwRanks: '/v2/wvw/ranks',
});


text:
pikabin
=======

Paste tool with inline commenting support.

Installation
------------

```bash
# Cloning repo
git clone git@github.com:tunglam14/pikabin.git
cd pikabin/

# Setup
export RAILS_ENV=production
bundle install

# Config db
vim config/database.yml
cat config/database.yml
#production:
#  adapter: sqlite3
#  pool: 5
#  timeout: 5000
#  database: /var/run/pikabin_production.sqlite3

bundle exec rake db:migrate
bundle exec rake assets:precompile

# Start service with puma
SECRET_KEY_BASE=$(bundle exec rake secret) bundle exec puma
# Listening on tcp://127.0.0.1:8080
```

API
---

```bash
curl -X POST -H "content-type: application/json" -d '{ "document": { "content": "asdasdsd" } }' "http://localhost:3000"

# Response
{"message":"","uri":"http://localhost:3000/31037f223195e451e0ebe56e8e041d0c756bc"}
```

### Request

Header:

    * Conten-type: application/json

Body:

```json
{
  "document": {
    "content": "Paste content",
    "title": "Paste title | can be empty | Default: empty",
    "expired_at": "Expiration time in minute | 0: delete after reading | -1: No expire | Default: 0",
    "syntax": "Paste color syntax | See more: https://github.com/tunglam14/pikabin/blob/master/config/initializers/00contants.rb#L1 | Default: plain"
  }
}
```

### Response

#### Success

Code: `201`

Body:

```json
{
  "message": "",
  "uri": "https://pikab.in/e90e9f9ff807091bb589b0e4db203bc3e92c4"
}
```

#### Error

Code: `400`

Body:

```json
{
  "message": [
    "Content can't be blank"
  ],
  "uri": ""
}
```

### Show document

raw:

```bash
curl https://pikab.in/936279c6f3.raw
assasasss
```

json:

```bash
curl https://pikab.in/936279c6f3.json
{"content_decrypted":"assasasss ","title":"","expired_at":"-1","syntax":"plain"}
```

Client
------

* Python: [pikapy](https://github.com/tunglam14/pikapy) by [@kinhvan017](https://github.com/kinhvan017)
* Golang: [pikago](https://github.com/Gnouc/pikago) by [@Gnouc](https://github.com/Gnouc)

Star point
----------

* Security:

    - Encrypt content with random password: [[...]](https://github.com/tunglam14/pikabin/blob/master/lib/cryptor.rb#L12)
    - [Don't log password](https://github.com/tunglam14/pikabin/blob/master/config/initializers/filter_parameter_logging.rb#L4), [request URI](https://github.com/tunglam14/pikabin/blob/master/config/environments/production.rb#L49) in production environment
    - Remove expired document immediately [[...]](https://github.com/tunglam14/pikabin/blob/master/app/models/document.rb#L114)
    - Remove document after reading

* UI:

    - Front-end framework: Semantic-UI
    - Editor: ACE Editor
    - Syntax highlighting: SyntaxHighlighter

Wanna contribute?
-----------------

Your contribution are welcome, desired features are in [TODO.md](https://github.com/tunglam14/pikabin/blob/master/TODO.md)


text:
namespace enterprise_connectors {
namespace test {

class MockDeviceTrustService : public DeviceTrustService {
 public:
  MockDeviceTrustService();
  ~MockDeviceTrustService() override;

  MOCK_METHOD(bool, IsEnabled, (), (const, override));
  MOCK_METHOD(void,
              BuildChallengeResponse,
              (const std::string&, AttestationCallback),
              (override));
  MOCK_METHOD(bool, Watches, (const GURL&), (const, override));
};

}  // namespace test
}  // namespace enterprise_connectors

#endif  // CHROME_BROWSER_ENTERPRISE_CONNECTORS_DEVICE_TRUST_MOCK_DEVICE_TRUST_SERVICE_H_