text:
// Based on Code by JeeLabs http://news.jeelabs.org/code/
// Released to the public domain! Enjoy!
//
// Modified and expanded by Red Byer 7/24/2013 to work with 3231 better
//     www.redstoyland.com      Find the code under "mizraith" on github
//
//  See .h file for the additions

#if ARDUINO < 100
#include <WProgram.h>
#else
#include <Arduino.h>
#endif

#include <avr/pgmspace.h>
#include <Wire.h>
#include "RTClib.h"
#include "RTC_DS3231.h"

#if ARDUINO < 100
#define SEND(x) send(x)
#define RECEIVE(x) receive(x)
#else
#define SEND(x) write(static_cast<uint8_t>(x))
#define RECEIVE(x) read(x)
#endif

////////////////////////////////////////////////////////////////////////////////
// RTC_DS3231 implementation

uint8_t RTC_DS3231::begin(void)
{
    return 1;
}

uint8_t RTC_DS3231::isrunning(void)
{
    Wire.beginTransmission(DS3231_ADDRESS);
    Wire.SEND(DS3231_REG_STATUS_CTL);
    Wire.endTransmission();

    Wire.requestFrom(DS3231_ADDRESS, 1);
    uint8_t ss = Wire.RECEIVE();
    return !(ss>>7);
}

/**
 * Set the datetime of the RTC
**/
void RTC_DS3231::adjust(const DateTime& dt)
{
	//set the address pointer and then start writing
    Wire.beginTransmission(DS3231_ADDRESS);
    Wire.SEND( DS3231_REG_SECONDS );           // was just '0'
    Wire.SEND(bin2bcd(dt.second()));
    Wire.SEND(bin2bcd(dt.minute()));
    Wire.SEND(bin2bcd(dt.hour()));
    Wire.SEND(bin2bcd(0));
    Wire.SEND(bin2bcd(dt.day()));
    Wire.SEND(bin2bcd(dt.month()));
    Wire.SEND(bin2bcd(dt.year() - 2000));
    Wire.SEND(0);
    Wire.endTransmission();
}

/**
 * Get the datetime from the RTC
 **/
DateTime RTC_DS3231::now()
{
	//set the address pointer in preparation for read
    Wire.beginTransmission(DS3231_ADDRESS);
    Wire.SEND( DS3231_REG_SECONDS );           // was just '0'
    Wire.endTransmission();

    Wire.requestFrom(DS3231_ADDRESS, 7);
    uint8_t ss = bcd2bin(Wire.RECEIVE() & 0x7F);
    uint8_t mm = bcd2bin(Wire.RECEIVE());
    uint8_t hh = bcd2bin(Wire.RECEIVE());
    Wire.RECEIVE();
    uint8_t d = bcd2bin(Wire.RECEIVE());
    uint8_t m = bcd2bin(Wire.RECEIVE());
    uint16_t y = bcd2bin(Wire.RECEIVE()) + 2000;

    return DateTime (y, m, d, hh, mm, ss);
}

/**
 * Return temperature as a float in degrees C
 * Data is 10bits provided in 2 bytes (11h and and 2bits in 12h)
 * Resolution of 0.25C
 * e.g.  00011001 01     =    25.25C
 *       00011001 = 25
 *             01 = 0.25 * 1 = .25
 *
 *  This function has not been tested
 */
float RTC_DS3231::getTempAsFloat()
{
	//set the address pointer in preparation for read
    Wire.beginTransmission(DS3231_ADDRESS);
    Wire.SEND( DS3231_REG_TEMP_MSB );           // was just '0'
    Wire.endTransmission();

	Wire.requestFrom(DS3231_ADDRESS, 2);
    int8_t sig   = Wire.RECEIVE();                  //signed MSB
    uint8_t fract = Wire.RECEIVE() & 0b11000000;    //rest should be zeroes anyway.

    fract = fract >> 6;                // now in 2 lsb's
    float temp = (float)fract * 0.25;  // total up,  .00, .25, .50
    if(sig < 0) {
    	temp = sig - temp;             // calculate the fract correctly
    } else {
	    temp = sig + temp;             // add    25 + .25 = 25.25
    }
    return temp;
}

/**
 * Return temperature as a 2 bytes in degrees C
 *    MSB is the significant  00011001 = 25
 *    LSB is the mantissa     00011001 = .25
 *  Display by writing them out to the display   MSB . LSB
 *
 * Data from the 3231 10bits provided in 2 bytes (11h and and 2bits in 12h)
 * Resolution of 0.25C
 * e.g.  00011001 01     =    25.25C
 *       00011001 = 25
 *             01 = 0.25 * 1 = .25
 *
 *  This function has not been tested
 */
int16_t RTC_DS3231::getTempAsWord()
{
	//set the address pointer in preparation for read
    Wire.beginTransmission(DS3231_ADDRESS);
    Wire.SEND( DS3231_REG_TEMP_MSB );           // was just '0'
    Wire.endTransmission();

	Wire.requestFrom(DS3231_ADDRESS, 2);
    int8_t sig   = Wire.RECEIVE();                  //signed MSB
    uint8_t fract = Wire.RECEIVE() & 0b11000000;    //rest should be zeroes anyway.

    int16_t temp = sig;           //put into lower byte
    temp = temp << 8 ;            //shift to upper byte

    fract = fract >> 6;                // shift upper 2 bits to lowest 2
    fract = fract * 25;                // multiply up

    temp = temp + fract;

    return temp;
}

/**
 *  Enable or disable the 32kHz pin.  When 1 it
 * will output 32768kHz.
 *
 */
void RTC_DS3231::enable32kHz(uint8_t enable)
{
	Wire.beginTransmission(DS3231_ADDRESS);
	Wire.SEND( DS3231_REG_STATUS_CTL );
	Wire.endTransmission();

	// status register
	Wire.requestFrom(DS3231_ADDRESS, 1);

	uint8_t sreg = bcd2bin(Wire.RECEIVE());    // do we need to wrap in bcd2bin?

	if (enable == true) {
		sreg |=  0b00001000; // Enable EN32KHZ bit
	} else {
		sreg &= ~0b00001000; // else set EN32KHZ bit to 0
	}

	Wire.beginTransmission(DS3231_ADDRESS);
	Wire.SEND( DS3231_REG_STATUS_CTL );
	Wire.SEND(sreg);
	Wire.endTransmission();
}

/**
 * Force the temp sensor to convert the temp
 * into digital code and execute the TCXO
 * algorithm.  The DS3231 normally does
 * this every 64 seconds anyway.
 *
 * NOTE: This is a BLOCKING method.  You have been warned.
 *
 * This method has not been fully debugged.
 */
void RTC_DS3231::forceTempConv(uint8_t block)
{
	Wire.beginTransmission(DS3231_ADDRESS);
	Wire.SEND( DS3231_REG_CONTROL );
	Wire.endTransmission();

	// control register
	Wire.requestFrom(DS3231_ADDRESS, 1);

	uint8_t creg = Wire.RECEIVE();  // do we need the bcd2bin

	creg |= 0b00100000; // Write CONV bit

	Wire.beginTransmission(DS3231_ADDRESS);
	Wire.SEND(DS3231_REG_CONTROL);
	Wire.SEND(creg);
	Wire.endTransmission();

	do
	{
		// Block until CONV is 0
		Wire.beginTransmission(DS3231_ADDRESS);
		Wire.SEND(DS3231_REG_CONTROL);
		Wire.endTransmission();
		Wire.requestFrom(DS3231_ADDRESS, 1);
	} while ((block && (Wire.RECEIVE() & 0b00100000) != 0));
}

/**
 * Enable or disable the output to the SQW pin.
 *  Send 1 or true to enable.
 *  This function does _not_ enable battery backed output
 * which helps conserve battery life.
 *
 */
void RTC_DS3231::SQWEnable(uint8_t enable)
{
	Wire.beginTransmission(DS3231_ADDRESS);
	Wire.SEND(DS3231_REG_CONTROL);
	Wire.endTransmission();

	// control register
	Wire.requestFrom(DS3231_ADDRESS, 1);

	uint8_t creg = Wire.RECEIVE();     //do we need the bcd2bin

	if (enable == true) {
		creg &= ~0b00000100; // Clear INTCN bit to output the square wave
	} else {
		creg |= 0b00000100;      // Set INTCN to 1 -- disables SQW
	}

	Wire.beginTransmission(DS3231_ADDRESS);
	Wire.SEND(DS3231_REG_CONTROL);
	Wire.SEND(creg);
	Wire.endTransmission();
}

/**
 * Enable or disable the output to the SQW pin.
 *  Send 1 or true to enable.
 * This method enables BOTH the square wave
 * and the battery backed output.
 *
 */
void RTC_DS3231::BBSQWEnable(uint8_t enable)
{
	Wire.beginTransmission(DS3231_ADDRESS);
	Wire.SEND(DS3231_REG_CONTROL);
	Wire.endTransmission();

	// control register
	Wire.requestFrom(DS3231_ADDRESS, 1);

	uint8_t creg = Wire.RECEIVE();     //do we need the bcd2bin

	if (enable == true) {
		creg |=  0b01000000; // Enable BBSQW if required so SQW continues to output (battery life reduction).
		creg &= ~0b00000100; // Clear INTCN bit to output the square wave
	} else {
		creg &= ~0b01000000;    // Set BBSQW 0 to disable battery back
		//creg |=  0b00000100;      // Set INTCN to 1 -- disables SQW
	}

	Wire.beginTransmission(DS3231_ADDRESS);
	Wire.SEND(DS3231_REG_CONTROL);
	Wire.SEND(creg);
	Wire.endTransmission();
}

/**
 *  Set the output frequence of the squarewave SQW pin
 *
 *  HINT:  Use the defined frequencies in the .h file
 *
 */
void RTC_DS3231::SQWFrequency(uint8_t freq)
{
	Wire.beginTransmission(DS3231_ADDRESS);
	Wire.SEND(DS3231_REG_CONTROL);
	Wire.endTransmission();

	// control register
	Wire.requestFrom(DS3231_ADDRESS, 1);

	uint8_t creg = Wire.RECEIVE();

	creg &= ~0b00011000; // Set to 0
	creg |= freq; // Set freq bits

	Wire.beginTransmission(DS3231_ADDRESS);
	Wire.SEND(DS3231_REG_CONTROL);
	Wire.SEND(creg);
	Wire.endTransmission();
}

void RTC_DS3231::getControlRegisterData(char &datastr) {

	Wire.beginTransmission(DS3231_ADDRESS);
    Wire.write( DS3231_REG_CONTROL );
    Wire.endTransmission();

    // control registers
    Wire.requestFrom(DS3231_ADDRESS, 2);
    uint8_t creg = Wire.RECEIVE();  // do we need the bcd2bin
    uint8_t sreg = Wire.RECEIVE();

    char cregstr[] = "00000000";
    char sregstr[] = "00000000";
    getBinaryString(creg, cregstr);
    getBinaryString(sreg, sregstr);

    strcpy(&datastr, "\n----- DS3231 Information -----\ncreg: ");
    strcat(&datastr, cregstr);
    strcat(&datastr, "\nsreg: ");
    strcat(&datastr, sregstr);
    strcat(&datastr, "\n------------------------------\n");

    return;
}

/********************************************************
* UTILITY and WORKER METHODS
*********************************************************/

/**
 * Takes one byte and loads up bytestr[8] with the value
 *  eg  "8" loads bytestr with "00000111"
 */
void RTC_DS3231::getBinaryString(uint8_t byteval, char bytestr[])
{
	uint8_t bitv;
	int i = 0;

    for (i = 0; i < 8; i++) {
           bitv = (byteval >> i) & 1;
           if (bitv == 0) {
               bytestr[7-i] = '0';
           } else {
               bytestr[7-i] = '1';
           }
    }
}

// vim:ci:sw=4 sts=4 ft=cpp


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

namespace Nums1To20
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("1");
            Console.WriteLine("2");
            Console.WriteLine("3");
            Console.WriteLine("4");
            Console.WriteLine("5");
            Console.WriteLine("6");
            Console.WriteLine("7");
            Console.WriteLine("8");
            Console.WriteLine("9");
            Console.WriteLine("10");
            Console.WriteLine("11");
            Console.WriteLine("12");
            Console.WriteLine("13");
            Console.WriteLine("14");
            Console.WriteLine("15");
            Console.WriteLine("16");
            Console.WriteLine("17");
            Console.WriteLine("18");
            Console.WriteLine("19");
            Console.WriteLine("20");
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.liuawei.web.controller.ExceptionHandling;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptaion {
	/*
	 * 定义异常处理方法
	 */
	@ExceptionHandler(LiuaweiException.class)
	public @ResponseBody String liuaweiException(){
		return "LiuaweiException--全部处理";
	}
}


text:
<?php

declare(strict_types=1);

namespace GeneaLabs\LaravelGovernor;

use GeneaLabs\LaravelGovernor\Traits\Governing;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Governing;
}


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

describe MIDIator::Driver do
  it "automatically registers subclasses" do
    SomeCoolDriver = Class.new
    SomeCoolDriver.should_receive( :< ).with( MIDIator::Driver ).and_return( true )

    # call inherited directly since we can't set up expectations ahead of
    # time with Class.new( MIDIator::Driver )
    MIDIator::Driver.inherited( SomeCoolDriver )
    MIDIator::DriverRegistry.instance[ SomeCoolDriver.to_s.underscore ].should be( SomeCoolDriver )
  end
end


text:
@interface ConstantLong : Constant {
 @public
  long Value_;
}

@property(nonatomic,assign)long Value_;

- (id)initWithLong:(long)l;
@end

#endif // _ConstantLong_H_


text:
/* Private definitions for libsepol. */

/* Endian conversion for reading and writing binary policies */

#include <sepol/policydb/policydb.h>

#include <byteswap.h>
#include <endian.h>
#include <errno.h>
#include <dso.h>

#if __BYTE_ORDER == __LITTLE_ENDIAN
#define cpu_to_le16(x) (x)
#define le16_to_cpu(x) (x)
#define cpu_to_le32(x) (x)
#define le32_to_cpu(x) (x)
#define cpu_to_le64(x) (x)
#define le64_to_cpu(x) (x)
#else
#define cpu_to_le16(x) bswap_16(x)
#define le16_to_cpu(x) bswap_16(x)
#define cpu_to_le32(x) bswap_32(x)
#define le32_to_cpu(x) bswap_32(x)
#define cpu_to_le64(x) bswap_64(x)
#define le64_to_cpu(x) bswap_64(x)
#endif

#undef min
#define min(a,b) (((a) < (b)) ? (a) : (b))

#define ARRAY_SIZE(x) (sizeof(x)/sizeof((x)[0]))

/* Policy compatibility information. */
struct policydb_compat_info {
	unsigned int type;
	unsigned int version;
	unsigned int sym_num;
	unsigned int ocon_num;
	unsigned int target_platform;
};

extern struct policydb_compat_info *policydb_lookup_compat(unsigned int version,
							   unsigned int type,
						unsigned int target_platform);

/* Reading from a policy "file". */
extern int next_entry(void *buf, struct policy_file *fp, size_t bytes) hidden;
extern size_t put_entry(const void *ptr, size_t size, size_t n,
		        struct policy_file *fp) hidden;


text:
@interface SegmentedControl : HMSegmentedControl

@property(nonatomic) IBInspectable float fontSize;
@property(nonatomic) IBInspectable float fontSizePad;
@property(nonatomic) IBInspectable NSString* fontName;
@property(nonatomic) IBInspectable UIColor* fontColor;

@property(nonatomic) IBInspectable BOOL verticalDivider;
@property(nonatomic) IBInspectable float vDividerWidth;
@property(nonatomic) IBInspectable UIColor* vDividerColor;

@property(nonatomic) IBInspectable UIColor* selectionColor;
@property(nonatomic) IBInspectable UIColor* background;

-(void)viewControllerDidLoad;

@end


text:
static CGFloat const kAKButtonSeparatorWidth = 1.0;

@interface AKSegmentedControl ()

@property (nonatomic, strong) NSMutableArray *separatorsArray;
@property (nonatomic, strong) UIImageView *backgroundImageView;

// Init
- (void)commonInitializer;

@end

@implementation AKSegmentedControl

#pragma mark - Init and Dealloc

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (!self) return nil;

    [self commonInitializer];

    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (!self) return nil;

    [self commonInitializer];

    return self;
}

- (void)commonInitializer {
    _separatorsArray = [NSMutableArray array];
    self.selectedIndexes = [NSIndexSet indexSet];
    self.contentEdgeInsets = UIEdgeInsetsZero;
    self.segmentedControlMode = AKSegmentedControlModeSticky;
    self.buttonsArray = [[NSArray alloc] init];

    [self addSubview:self.backgroundImageView];
}

#pragma mark - Layout

- (void)layoutSubviews {
    [super layoutSubviews];
    CGRect contentRect = UIEdgeInsetsInsetRect(self.bounds, _contentEdgeInsets);

    NSUInteger buttonsCount    = _buttonsArray.count;
    NSUInteger separtorsNumber = buttonsCount - 1;
    CGFloat separatorWidth     = (_separatorImage != nil) ? _separatorImage.size.width : kAKButtonSeparatorWidth;
    CGFloat buttonWidth        = floorf((CGRectGetWidth(contentRect) - (separtorsNumber * separatorWidth)) / buttonsCount);
    CGFloat buttonHeight       = CGRectGetHeight(contentRect);
    CGSize buttonSize          = CGSizeMake(buttonWidth, buttonHeight);

    __block CGFloat offsetX      = CGRectGetMinX(contentRect);
    __block CGFloat offsetY      = CGRectGetMinY(contentRect);
    __block CGFloat spaceLeft    = CGRectGetWidth(contentRect) - (buttonsCount * buttonSize.width) - (separtorsNumber * separatorWidth);
    __block CGFloat dButtonWidth = 0;
    __block NSUInteger increment = 0;

    [_buttonsArray enumerateObjectsUsingBlock:^(UIButton *button, NSUInteger idx, BOOL *stop) {
        if (![button isKindOfClass:UIButton.class]) {
            return;
        }

        dButtonWidth = buttonSize.width;

        if (spaceLeft != 0) {
            dButtonWidth++;
            spaceLeft--;
        }

        if (increment != 0) {
            offsetX += separatorWidth;
        }

        button.frame = CGRectMake(offsetX, offsetY, dButtonWidth, buttonSize.height);

        if (increment < separtorsNumber) {
            UIImageView *separatorImageView = _separatorsArray[increment];
            [separatorImageView setFrame:CGRectMake(CGRectGetMaxX(button.frame),
                                                    offsetY,
                                                    separatorWidth,
                                                    CGRectGetHeight(self.bounds) - _contentEdgeInsets.top - _contentEdgeInsets.bottom)];
        }

        increment++;
        offsetX = CGRectGetMaxX(button.frame);
    }];

    [_backgroundImageView setFrame:self.bounds];
}

#pragma mark - Button Actions

- (void)segmentButtonPressed:(id)sender {
    UIButton *button = (UIButton *)sender;

    if (![button isKindOfClass:UIButton.class]) {
        return;
    }

    NSUInteger selectedIndex = button.tag;
    NSIndexSet *set = _selectedIndexes;

    if (_segmentedControlMode == AKSegmentedControlModeMultipleSelectionable) {

        NSMutableIndexSet *mutableSet = [set mutableCopy];
        if ([_selectedIndexes containsIndex:selectedIndex]) {
            [mutableSet removeIndex:selectedIndex];
        }

        else {
            [mutableSet addIndex:selectedIndex];
        }

        [self setSelectedIndexes:[mutableSet copy]];
    }

    else {
        [self setSelectedIndex:selectedIndex];
    }

    BOOL willSendAction = (![_selectedIndexes isEqualToIndexSet:set] || _segmentedControlMode == AKSegmentedControlModeButton);

    if (willSendAction) {
        [self sendActionsForControlEvents:UIControlEventValueChanged];
    }

}

#pragma mark - Setters

- (void)setBackgroundImage:(UIImage *)backgroundImage {
    _backgroundImage = backgroundImage;
    [_backgroundImageView setImage:_backgroundImage];
}

- (void)setButtonsArray:(NSArray *)buttonsArray {
    [_buttonsArray makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [_separatorsArray removeAllObjects];

    _buttonsArray = buttonsArray;

    [_buttonsArray enumerateObjectsUsingBlock:^(UIButton *button, NSUInteger idx, BOOL *stop) {
        [self addSubview:button];
        [button addTarget:self action:@selector(segmentButtonPressed:) forControlEvents:UIControlEventTouchDown];
        [button setTag:idx];
    }];

    [self rebuildSeparators];
    [self updateButtons];
}

- (void)setSeparatorImage:(UIImage *)separatorImage {
    _separatorImage = separatorImage;
    [self rebuildSeparators];
}

- (void)setSegmentedControlMode:(AKSegmentedControlMode)segmentedControlMode {
    _segmentedControlMode = segmentedControlMode;
    [self updateButtons];
}

- (void)setSelectedIndex:(NSUInteger)index {
    _selectedIndexes = [NSIndexSet indexSetWithIndex:index];
    [self updateButtons];
}

- (void)setSelectedIndexes:(NSIndexSet *)indexSet byExpandingSelection:(BOOL)expandSelection {

    if (_segmentedControlMode != AKSegmentedControlModeMultipleSelectionable) {
        return;
    }

    if (!expandSelection) {
        _selectedIndexes = [NSIndexSet indexSet];
    }

    NSMutableIndexSet *mutableIndexSet = [_selectedIndexes mutableCopy];
    [mutableIndexSet addIndexes:indexSet];
    [self setSelectedIndexes:mutableIndexSet];
}

- (void)setSelectedIndexes:(NSIndexSet *)selectedIndexes {
    _selectedIndexes = [selectedIndexes copy];
    [self updateButtons];
}

#pragma mark - Rearranging

- (void)rebuildSeparators {
    [_separatorsArray makeObjectsPerformSelector:@selector(removeFromSuperview)];

    NSUInteger separatorsNumber = [_buttonsArray count] - 1;

    [_separatorsArray removeAllObjects];
    [_buttonsArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if (idx < separatorsNumber) {
            UIImageView *separatorImageView = [[UIImageView alloc] initWithImage:_separatorImage];
            [self addSubview:separatorImageView];
            [_separatorsArray addObject:separatorImageView];
        }
    }];
}

- (UIImageView *)backgroundImageView {
    if (_backgroundImageView == nil) {
        _backgroundImageView = [[UIImageView alloc] initWithFrame:self.bounds];
        [_backgroundImageView setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
    }

    return _backgroundImageView;
}

- (void)updateButtons {

    if ([_buttonsArray count] == 0) {
        return;
    }

    [_buttonsArray makeObjectsPerformSelector:@selector(setSelected:) withObject:nil];

    [_selectedIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {

        if (_segmentedControlMode != AKSegmentedControlModeButton) {
            if (idx >= [_buttonsArray count]) return;

            UIButton *button = _buttonsArray[idx];
            button.selected = YES;
        }
    }];
}

@end


text:
from django.utils.importlib import import_module
from django.conf import settings

# Managers
mkdocs = import_module(getattr(settings, 'MKDOCS_BACKEND', 'doc_builder.backends.mkdocs'))
sphinx = import_module(getattr(settings, 'SPHINX_BACKEND', 'doc_builder.backends.sphinx'))

BUILDER_BY_NAME = {
    # Possible HTML Builders
    'sphinx': sphinx.HtmlBuilder,
    'sphinx_htmldir': sphinx.HtmlDirBuilder,
    'sphinx_singlehtml': sphinx.SingleHtmlBuilder,
    # Other Sphinx Builders
    'sphinx_pdf': sphinx.PdfBuilder,
    'sphinx_epub': sphinx.EpubBuilder,
    'sphinx_search': sphinx.SearchBuilder,
    'sphinx_singlehtmllocalmedia': sphinx.LocalMediaBuilder,
    # Other markup
    'mkdocs': mkdocs.MkdocsHTML,
    'mkdocs_json': mkdocs.MkdocsJSON,
}

def get_builder_class(name):
    return BUILDER_BY_NAME[name]


text:
package org.springframework.vault.core;

import java.time.Instant;
import java.util.Collections;
import java.util.Map;
import java.util.UUID;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.vault.VaultException;
import org.springframework.vault.domain.Person;
import org.springframework.vault.support.Versioned;
import org.springframework.vault.support.Versioned.Metadata;
import org.springframework.vault.support.Versioned.Version;
import org.springframework.vault.util.IntegrationTestSupport;
import org.springframework.vault.util.RequiresVaultVersion;
import org.springframework.vault.util.VaultInitializer;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

/**
 * Integration tests for {@link VaultVersionedKeyValueTemplate}.
 *
 * @author Mark Paluch
 */
@ExtendWith(SpringExtension.class)
@RequiresVaultVersion(VaultInitializer.VERSIONING_INTRODUCED_WITH_VALUE)
@ContextConfiguration(classes = VaultIntegrationTestConfiguration.class)
class VaultVersionedKeyValueTemplateIntegrationTests extends IntegrationTestSupport {

	@Autowired
	VaultOperations vaultOperations;

	VaultVersionedKeyValueOperations versionedOperations;

	@BeforeEach
	void before() {
		versionedOperations = vaultOperations.opsForVersionedKeyValue("versioned");
	}

	@Test
	void shouldCreateVersionedSecret() {

		Map<String, String> secret = Collections.singletonMap("key", "value");

		String key = UUID.randomUUID().toString();

		Metadata metadata = versionedOperations.put(key, Versioned.create(secret));

		assertThat(metadata.isDestroyed()).isFalse();
		assertThat(metadata.getCreatedAt()).isBetween(Instant.now().minusSeconds(60),
				Instant.now().plusSeconds(60));
		assertThat(metadata.getDeletedAt()).isNull();
	}

	@Test
	void shouldCreateComplexVersionedSecret() {

		Person person = new Person();
		person.setFirstname("Walter");
		person.setLastname("White");

		String key = UUID.randomUUID().toString();
		versionedOperations.put(key, Versioned.create(person));

		Versioned<Person> versioned = versionedOperations.get(key, Person.class);

		assertThat(versioned.getRequiredData()).isEqualTo(person);
	}

	@Test
	void shouldCreateVersionedWithCAS() {

		Map<String, String> secret = Collections.singletonMap("key", "value");

		String key = UUID.randomUUID().toString();

		versionedOperations.put(key, Versioned.create(secret, Version.unversioned()));

		// this should fail
		assertThatThrownBy(() -> versionedOperations.put(key,
				Versioned.create(secret, Version.unversioned())))
						.isExactlyInstanceOf(VaultException.class).hasMessageContaining(
								"check-and-set parameter did not match the current version");
	}

	@Test
	void shouldReadAndWriteVersionedSecret() {

		Map<String, String> secret = Collections.singletonMap("key", "value");

		String key = UUID.randomUUID().toString();

		versionedOperations.put(key, Versioned.create(secret));

		Versioned<Map<String, Object>> loaded = versionedOperations.get(key);

		assertThat(loaded.getRequiredData()).isEqualTo(secret);
		assertThat(loaded.getRequiredMetadata()).isNotNull();
		assertThat(loaded.getVersion()).isEqualTo(Version.from(1));
	}

	@Test
	void shouldListExistingSecrets() {

		Map<String, String> secret = Collections.singletonMap("key", "value");
		String key = UUID.randomUUID().toString();

		versionedOperations.put(key, secret);

		assertThat(versionedOperations.list("")).contains(key);
	}

	@Test
	void shouldReadDifferentVersions() {

		String key = UUID.randomUUID().toString();

		versionedOperations.put(key, Collections.singletonMap("key", "v1"));
		versionedOperations.put(key, Collections.singletonMap("key", "v2"));

		assertThat(versionedOperations.get(key, Version.from(1)).getRequiredData())
				.isEqualTo(Collections.singletonMap("key", "v1"));
		assertThat(versionedOperations.get(key, Version.from(2)).getRequiredData())
				.isEqualTo(Collections.singletonMap("key", "v2"));
	}

	@Test
	void shouldDeleteMostRecentVersion() {

		String key = UUID.randomUUID().toString();

		versionedOperations.put(key, Collections.singletonMap("key", "v1"));
		versionedOperations.put(key, Collections.singletonMap("key", "v2"));

		versionedOperations.delete(key);

		Versioned<Map<String, Object>> versioned = versionedOperations.get(key);

		assertThat(versioned.getData()).isNull();
		assertThat(versioned.getVersion()).isEqualTo(Version.from(2));
		assertThat(versioned.getRequiredMetadata().isDestroyed()).isFalse();
		assertThat(versioned.getRequiredMetadata().getDeletedAt())
				.isBetween(Instant.now().minusSeconds(60), Instant.now().plusSeconds(60));
	}

	@Test
	void shouldUndeleteVersion() {

		String key = UUID.randomUUID().toString();

		versionedOperations.put(key, Collections.singletonMap("key", "v1"));
		versionedOperations.put(key, Collections.singletonMap("key", "v2"));

		versionedOperations.delete(key, Version.from(2));
		versionedOperations.undelete(key, Version.from(2));

		Versioned<Map<String, Object>> versioned = versionedOperations.get(key);

		assertThat(versioned.getRequiredData())
				.isEqualTo(Collections.singletonMap("key", "v2"));
		assertThat(versioned.getVersion()).isEqualTo(Version.from(2));
		assertThat(versioned.getRequiredMetadata().isDestroyed()).isFalse();
		assertThat(versioned.getRequiredMetadata().getDeletedAt()).isNull();
	}

	@Test
	void shouldDeleteIntermediateRecentVersion() {

		String key = UUID.randomUUID().toString();

		versionedOperations.put(key, Collections.singletonMap("key", "v1"));
		versionedOperations.put(key, Collections.singletonMap("key", "v2"));

		versionedOperations.delete(key, Version.from(1));

		Versioned<Map<String, Object>> versioned = versionedOperations.get(key,
				Version.from(1));

		assertThat(versioned.getData()).isNull();
		assertThat(versioned.getVersion()).isEqualTo(Version.from(1));
		assertThat(versioned.getRequiredMetadata().isDestroyed()).isFalse();
		assertThat(versioned.getRequiredMetadata().getDeletedAt())
				.isBetween(Instant.now().minusSeconds(60), Instant.now().plusSeconds(60));
	}

	@Test
	void shouldDestroyVersion() {

		String key = UUID.randomUUID().toString();

		versionedOperations.put(key, Collections.singletonMap("key", "v1"));
		versionedOperations.put(key, Collections.singletonMap("key", "v2"));

		versionedOperations.destroy(key, Version.from(2));

		Versioned<Map<String, Object>> versioned = versionedOperations.get(key);

		assertThat(versioned.getData()).isNull();
		assertThat(versioned.getVersion()).isEqualTo(Version.from(2));
		assertThat(versioned.getRequiredMetadata().isDestroyed()).isTrue();
		assertThat(versioned.getRequiredMetadata().getDeletedAt()).isNull();
	}
}


text:
package pt.up.fe.comp.fsa;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

@SuppressWarnings("unused") //methods are used through reflection
public class Operations {

    /**
     * Creates a new FSA with a single state.
     *
     * @param name name of the automaton
     * @return returns a new automaton with just an initial state.
     */
    public static FSA empty_fsa(String name) {
        try {
            return new FSA(name, "q0", new HashSet<String>());
        } catch (FSAException e) {
            throw new Error(e);
        }
    }

    /**
     * Creates a new FSA from a regex.
     *
     * @param name   name of the automaton
     * @param regExp regular expression that determines the language of the automaton
     * @return returns a new automaton that accepts the language specified by the regular expression
     */
    public static FSA loadr(String name, String regExp) {
        try {
            return new FSA(name, regExp);

        } catch (IllegalArgumentException e) {
            throw new Error(e);
        }
    }

    /**
     * Concatenates all the specified automata in the order in which they are supplied to the function.
     *
     * @param args array of automata to operate with
     * @return returns a new eNFA that is the concatenation of all the given automata
     */
    public static FSA concat(FSA arg1, FSA arg2, FSA... args) {
        FSA result = new FSA(arg1);
        result.concat(arg2);
        for (FSA automaton : args) {
            result.concat(automaton);
        }
        return result;
    }

    /**
     * Computes the union between several automata. (Minimum of two).
     *
     * @param args array of automata to unite
     * @return returns a new eNFA that is the union of all the supplied automata.
     */
    public static FSA union(FSA arg1, FSA arg2, FSA... args) {
        FSA result = arg1.union(arg2);
        for (FSA automaton : args) {
            result = result.union(automaton);
        }
        return result;
    }

    /**
     * Computes the intersection between several automata. (Minimum of two).
     *
     * @param args array of automata to intersect
     * @return returns a new eNFA that is the intersection of all the supplied automata.
     */
    public static FSA intersect(FSA arg1, FSA arg2, FSA... args) {
        FSA result = arg1.intersect(arg2);
        for (FSA automaton : args) {
            result = result.intersect(automaton);
        }
        return result;
    }

    /**
     * Computes the cartesian product of the automata (minimum of two).
     * The resulting automaton will either have no final states or be the union, intersection, difference or XOR of the automata,
     * deppending on the specified type for the operation.
     *

     * After the cartesian product is calculated, the resulting automaton will have a state for every combination of states of the supplied automata.
     *

     * Operation types:
     * UNION - Computes the union of the languages accepted by the automata
     * INTERSECTION - Computes the intersection of the languages accepted by the automata
     * XOR - Computes the exclusive or of the languages accepted by the automata
     * DIFF - Computes the difference between the languages accepted by the automata, in the same order as they are supplied
     * NONE - Resulting automaton will have no final states
     *
     * @param opType indicates the desired operation type and must have one of the following values: "union", "intersection", "xor", "diff", "none".
     * @param args   array of automata to operate with
     * @return returns a new automaton that is the cartesian product of all the supplied automata
     */
    public static FSA cartesian(String opType, FSA arg1, FSA arg2, FSA... args) {
        try {
            FSA.CartesianType _opType = FSA.CartesianType.valueOf(opType.toUpperCase());
            FSA result = arg1.cartesian(arg2, _opType);

            for (FSA automaton : args) {
                result = result.cartesian(automaton, _opType);
            }
            return result;
        } catch (IllegalArgumentException e) {
            throw new Error("No such operation type: " + opType);
        }
    }

    /**
     * Computes the difference between several automata. (Minimum of two).
     *
     * @param args array of automata to operate with
     * @return returns a new eNFA that is the difference between the automata
     */
    public static FSA diff(FSA arg1, FSA arg2, FSA... args) {
        FSA result = arg1.diff(arg2);
        for (FSA automaton : args) {
            result = result.diff(automaton);
        }
        return result;
    }

    /**
     * Loads an automatons from dot file.
     *
     * @param fileName path to the dot file
     * @return returns a new automaton built from the information in the dot file
     */
    public static FSA loadf(String fileName) {
        File f = new File(fileName);
        if (!f.exists())
            throw new Error("No such file '"  + f.getAbsolutePath() + "'");

        try {
            return FSALoader.LoadFromFile(fileName);
        } catch (IOException e) {
            throw new Error(e);
        }
    }

    /**
     * Creates a new automaton from the given one and complements it.
     * I.e. it will accept strings iff they were not accepted by the original automaton.
     *
     * @param lhs FSA to complement
     * @return returns a new automaton that is the complement of lhs
     */
    public static FSA complement(FSA lhs) {
        FSA result = new FSA(lhs);
        result.complement();
        return result;
    }

    /**
     * Creates a new automaton from the given one and makes it minimal.
     * If automaton is not deterministic, it will be determinized first.
     *
     * @param lhs FSA to minimize
     * @return returns a new deterministic automaton equivalent to lhs but minimal
     */
    public static FSA minimize(FSA lhs) {
        FSA result = new FSA(lhs);
        result.minimize();
        return result;
    }

    /**
     * Creates a new automaton from the given one and makes it deterministic.
     *
     * @param lhs FSA to determinize
     * @return returns a new automaton equivalent to lhs but deterministic
     */
    public static FSA to_dfa(FSA lhs) {
        FSA result = new FSA(lhs);
        result.makeDeterministic();
        return result;
    }

    /**
     * Test if automaton in first argument is equal to or included in automaton passed as second argument.
     *
     * @param lhs automaton to operate with
     * @param rhs automaton to operate with
     * @return returns true if lhs is equal to or included in rhs, false otherwise
     */
    public static Boolean in(FSA lhs, FSA rhs) {
        return lhs.isIncludedIn(rhs);
    }

    /**
     * Tests if two automata accept the same language. The automata are not modified by this operation.
     *
     * @param lhs automaton to use for comparison
     * @param rhs automaton to use for comparison
     * @return returns true if the automata accept the same language, false otherwise
     */
    public static Boolean equivalent(FSA lhs, FSA rhs) {
        return lhs.equals(rhs);
    }

    /**
     * Changes the name of an automaton.
     *
     * @param lhs     automaton to rename
     * @param newName new name of the automaton
     * @return returns a new automaton with altered name
     */
    public static FSA change_name(FSA lhs, String newName) {
        FSA copy = new FSA(lhs);
        copy.setName(newName);
        return copy;
    }

    /**
     * Adds a state to the automaton as well as all associated edges.
     *
     * @param lhs     automaton to operate on
     * @param newNode state to add
     * @return returns a new automaton with altered node set
     */
    public static FSA add_state(FSA lhs, String newNode) {
        FSA copy = new FSA(lhs);
        try {
            copy.addNode(newNode);
        } catch (DuplicateElementException e) {
            throw new Error("State already exists in FSA.");
        }
        return copy;
    }

    /**
     * Adds an edge to the automaton.
     *
     * @param lhs         automaton to operate on
     * @param origin      origin state of the edge
     * @param label       edge label, if empty string, an empty transition is added
     * @param destination destination state of the edge
     * @return returns a new automaton with altered edge set
     */
    public static FSA add_edge(FSA lhs, String origin, String label, String destination) {
        FSA copy = new FSA(lhs);
        try {
            copy.addEdges(origin, label, destination);
        } catch (DuplicateElementException e) {
            throw new Error("Edge already exists in FSA.");
        } catch (NoSuchNodeException e) {
            throw new Error("Origin state does not exist in FSA.");
        }
        return copy;
    }

    /**
     * Inserts an automaton in another automaton.
     *  i.e. to get from the specified origin state to the destination state must traverse the whole automaton to be inserted.
     *

     * Will rename states of the resulting automaton if there is a name conflict between the nodes of both automata.
     *
     * @param lhs           original automaton
     * @param origin        name of the source state
     * @param transition    automaton that specifies the language for the state transition
     * @param destination   name of the destination state
     * @return returns a new automaton with the new transitions
     */
    public static FSA insert_automaton(FSA lhs, String origin, FSA transition, String destination) {
        FSA copy = new FSA(lhs);
        try {
            copy.insertFSA(origin, transition, destination);
            return copy;
        } catch (NoSuchNodeException e) {
            throw new Error("Origin state does not exist in FSA.");
        }
    }

    /**
     * Changes the initial state of an automaton as long as it exists.
     *
     * @param lhs             automaton to operate on
     * @param newInitialState state to be the new initial state
     * @return returns a new automaton with altered initial state
     */
    public static FSA change_initial_state(FSA lhs, String newInitialState) {
        FSA copy = new FSA(lhs);
        try {
            copy.setInitialState(newInitialState);
        } catch (NoSuchNodeException e) {
            throw new Error("Specified initial state does not exist in FSA: " + newInitialState);
        }
        return copy;
    }

    /**
     * Removes a state from the automaton as well as all associated edges.
     *
     * @param lhs     automaton to operate on
     * @param oldNode state to remove
     * @return returns a new automaton with altered node set
     */
    public static FSA remove_state(FSA lhs, String oldNode) {
        if (lhs.getInitialState().equals(oldNode)) {
            throw new Error("Cannot remove initial state.");
        }
        FSA copy = new FSA(lhs);
        try {
            copy.removeNode(oldNode);
        } catch (NoSuchNodeException e) {
            throw new Error("State to remove does not exist in FSA.");
        }
        return copy;
    }

    /**
     * Removes an edge from the automaton.
     *
     * @param lhs         automaton to operate on
     * @param origin      origin state of the edge
     * @param label       edge label
     * @param destination destination state of the edge
     * @return returns a new automaton with altered edge set
     */
    public static FSA remove_edge(FSA lhs, String origin, String label, String destination) {
        FSA copy = new FSA(lhs);
        if (label.length() != 1)
            throw new Error("Edge to remove can only contain one character");
        try {
            copy.removeEdge(origin, label.charAt(0), destination);
        } catch (NoSuchNodeException e) {
            throw new Error("Origin state does not exist in FSA.");
        } catch (NoSuchEdgeException e) {
            throw new Error("Origin state does not have the specified edge.");
        }
        return copy;
    }

    /**
     * Adds a state to the set of final states of automaton. If it does not exist in the set of ndoes, it is created.
     *
     * @param lhs       automaton to operate on
     * @param stateName name of state to add to final states set
     * @return returns a new automaton with altered final states
     */
    public static FSA add_final_state(FSA lhs, String stateName) {
        FSA copy = new FSA(lhs);
        copy.addFinalState(stateName);
        return copy;
    }

    /**
     * Removes a state from the set of final states of automaton.
     *
     * @param lhs       automaton to operate on
     * @param stateName name of state to remove from final states set
     * @return returns a new automaton with altered final states
     */
    public static FSA remove_final_state(FSA lhs, String stateName) {
        if (!lhs.getFinalStates().contains(stateName))
            throw new Error("Specified state is not final in FSA.");
        FSA copy = new FSA(lhs);
        copy.removeFinalState(stateName);
        return copy;
    }

    /**
     * Adds the empty string to the alphabet. (Null character)
     *
     * @param lhs automaton to operate on
     * @return returns a new automaton with modified alphabet
     */
    public static FSA add_empty_to_alphabet(FSA lhs) {
        FSA copy = new FSA(lhs);
        Set<Character> c = new HashSet<>();

        copy.addToAlphabet(c);
        return copy;
    }

    /**
     * Adds the double quote character to the alphabet. (Null character)
     *
     * @param lhs automaton to operate on
     * @return returns a new automaton with modified alphabet
     */
    public static FSA add_doublequote_to_alphabet(FSA lhs) {
        FSA copy = new FSA(lhs);
        copy.addToAlphabet('"');
        return copy;
    }

    /**
     * Adds all specified characters to an FSA's alphabet.
     *
     * @param lhs       automaton to operate on
     * @param newTokens string of characters to add to alphabet
     * @return returns a new automaton with modified alphabet
     */
    public static FSA add_to_alphabet(FSA lhs, String newTokens) {
        FSA copy = new FSA(lhs);
        for (int i = 0; i < newTokens.length(); i++) {
            copy.addToAlphabet(newTokens.charAt(i));
        }
        return copy;
    }

    /**
     * Removes all specified characters from an FSA's alphabet as long as they are currently not in use.
     * If any of them are in use, the method fails.
     *
     * @param lhs       automaton to operate on
     * @param oldTokens string of characters to remove from alphabet
     * @return returns a new automaton with modified alphabet
     */
    public static FSA remove_from_alphabet(FSA lhs, String oldTokens) {
        FSA copy = new FSA(lhs);
        Set<Character> toRemove = new HashSet<>();
        for (char c : oldTokens.toCharArray())
            toRemove.add(c);
        if (copy.removeFromAlphabet(toRemove))
            return copy;
        else
            throw new Error("Cannot remove characters from fsa's alphabet as one or more are currently in use.");
    }

    /**
     * Removes all characters from an FSA's alphabet that are currently not in use.
     *
     * @param lhs automaton to operate on
     * @return returns a new automaton with modified alphabet
     */
    public static FSA strip_alphabet(FSA lhs) {
        FSA copy = new FSA(lhs);
        copy.stripAlphabet();
        return copy;
    }

    /**
     * Tests if a given automaton is deterministic
     *
     * @param lhs automaton to test
     * @return returns true if lhs is deterministic, false otherwise
     */
    public static Boolean is_deterministic(FSA lhs) {
        return lhs.isDeterministic();
    }

    /**
     * Determines whether an automaton's accepted language only contains the empty string.
     *
     * @param lhs automaton to test
     * @return returns true if lhs only accepts the empty string, false otherwise
     */
    public static Boolean only_accepts_empty_string(FSA lhs) {
        return lhs.onlyAcceptsEmptyString();
    }

    /**
     * Determines whether an automaton's accepted language is the empty set.
     *
     * @param lhs automaton to test
     * @return returns true if lhs does not accept any string, false otherwise
     */
    public static Boolean empty_language(FSA lhs) {
        return lhs.doesNotAcceptAnything();
    }

    /**
     * Determines whether an automaton's accepts every string in it's alphabet AND the empty set
     *
     * @param lhs automaton to test
     * @return returns true if lhs accepts the kleene star closure of it's alphabet
     */
    public static Boolean accepts_alphabet_star_closure(FSA lhs) {
        return lhs.acceptsAlphabetKleeneStar();
    }

    /**
     * Determines whether an automaton's accepts every string in it's alphabet
     *
     * @param lhs automaton to test
     * @return returns true if lhs accepts the kleene plus closure of it's alphabet
     */
    public static Boolean accepts_alphabet_plus_closure(FSA lhs) {
        return lhs.acceptsAlphabetKleeneStar();
    }

    /**
     * Determines whether an automaton accepts a given string.
     *
     * @param lhs automaton to test
     * @param rhs string of inputs for the automaton
     * @return returns true if lhs does not accept any string, false otherwise
     */
    public static Boolean accepts(FSA lhs, String rhs) {
        return lhs.accepts(rhs);
    }

    /**
     * Creates a new automaton from the given one and removes all empty transitions from it. (eNFA to NFA)
     *
     * @param lhs eNFA to convert
     * @return returns a new automaton equivalent to lhs but without empty transitions
     */
    public static FSA remove_e(FSA lhs) {
        FSA result = new FSA(lhs);
        result.removeEmptyTransitions();
        return result;
    }

    /**
     * Creates a new automaton from the given one and makes it total.
     *

     * I.e. Every state will have at least one transition for every character in the automaton's alphabet.
     * Previously undefined transitions will lead to a new trap state.
     *
     * @param lhs FSA to totalize
     * @return returns a new automaton equivalent to lhs but total
     */
    public static FSA totalize(FSA lhs) {
        FSA result = new FSA(lhs);
        result.makeTotal();
        return result;
    }

    /**
     * Creates a new automaton from the given one and removes all it's unreachable states.
     *
     * @param lhs FSA to convert
     * @return returns a new automaton equivalent to lhs but without unreachable states
     */
    public static FSA remove_unreachable(FSA lhs) {
        FSA result = new FSA(lhs);
        result.removeUnreachableStates();
        return result;
    }

    /**
     * Creates a new automaton from the given one and removes all it's useless states.
     * A state is useless if it is a trap state (cannot reach a final state).
     *

     * However, the initial state is always kept.
     *
     * @param lhs FSA to convert
     * @return returns a new automaton equivalent to lhs but without useless states
     */
    public static FSA remove_useless(FSA lhs) {
        FSA result = new FSA(lhs);
        result.removeUselessStates();
        return result;
    }

    /**
     * Generates and writes dot output for a given automaton.
     *
     * @param lhs      automaton to write as dot
     * @param fileName path where to write the output
     * @return always returns null
     * @throws FileNotFoundException if it fails to open a PrintStream for fileName
     */
    public static Object write_dot(FSA lhs, String fileName) throws FileNotFoundException {
        PrintStream stream = new PrintStream(fileName);
        lhs.writeDot(stream);
        return null;
    }

    /**
     * Generates and prints dot output for a given automaton to System.out.
     *
     * @param lhs automaton to write as dot
     * @return always returns null
     */
    public static Object print_dot(FSA lhs) {
        lhs.writeDot(System.out);
        return null;
    }

    /**
     * Computes a regex from the given automaton. Empty parenthesis (i.e. "()") indicade empty strings (from epsilon transitions and such).
     *
     * @param lhs automaton to convert to regex
     * @return returns a string containing the regex for the given automaton
     */
    public static String to_regex(FSA lhs) {
        return lhs.toRegex();
    }

    private static String string_encode(String str) {
        return str.replace("#", "sharp").replace("++", "pp");
    }

    /**
     * Generates and writes code output for the implementation of a given automaton in the specified language.
     * The generated code exports an acceptance method which allows to test whether a given string is accepted by the automaton or not.
     *
     * @param language language in which to generate the code
     * @param lhs      automaton for which to generate code implementation
     * @param fileName path where to write the output
     * @return returns an invocation for the write method associated with the specified language
     * @throws InvocationTargetException     if the underlying method throws an exception
     * @throws IllegalAccessException        if this Method object is enforcing Java language access control and the underlying method is inaccessible
     * @throws FileNotFoundException         if it fails to open a PrintStream for fileName
     * @throws UnsupportedOperationException if there is no method to generate the implementation in the specified language
     */
    public static Object write_code(String language, FSA lhs, String fileName) throws InvocationTargetException, IllegalAccessException, FileNotFoundException {
        try {
            language = string_encode(language);

            File f = new File(fileName);
            String moduleName = f.getName().substring(0, f.getName().indexOf('.') > 0 ? f.getName().indexOf('.') : f.getName().length());
            PrintStream stream = new PrintStream(f);

            Method m = FSA.class.getMethod("write_" + language.toLowerCase(), String.class, PrintStream.class);
            Object result = m.invoke(lhs, moduleName, stream);
            stream.close();
            return result;
        } catch (NoSuchMethodException e) {
            throw new UnsupportedOperationException("No output to language '" + language + "' defined.");
        }
    }

    /**
     * Generates and prints code output for the implementation of a given automaton in the specified language to System.out.
     * The generated code exports an acceptance method which allows to test whether a given string is accepted by the automaton or not.
     *
     * @param language language in which to generate the code
     * @param lhs      automaton for which to generate code implementation
     * @return returns an invocation for the write method associated with the specified language
     * @throws InvocationTargetException     if the underlying method throws an exception
     * @throws IllegalAccessException        if this Method object is enforcing Java language access control and the underlying method is inaccessible
     * @throws UnsupportedOperationException if there is no method to generate the implementation in the specified language
     */
    public static Object print_code(String language, FSA lhs) throws InvocationTargetException, IllegalAccessException {
        try {
            language = string_encode(language);

            Method m = FSA.class.getMethod("write_" + language.toLowerCase(), String.class, PrintStream.class);
            return m.invoke(lhs, "Automaton", System.out);
        } catch (NoSuchMethodException e) {
            throw new UnsupportedOperationException("No output to language '" + language + "' defined.");
        }
    }

    /**
     * Creates a temporary dot file for the automaton and uses ZGRViewer to visualize it.
     *  Must have Graphviz installed.
     *

     * Additionally, it supports the command line options for ZGRViewer, which can be of types:
     *   opengl                    ZVTM will run in OpenGL accelerated mode");
     *                              (requires JDK 1.5 or later)\n");
     *   Pxxx                      where xxx={dot, neato, svg} to specify what program");
     *                              to use to compute the [file]'s layout\n");
     *   pluginDir=<path>          where <path> is the relative of full path to");
     *                              the directory where to look for plugins");
     *   pluginList=<paths>        where <path> is a list of comma-separated relative");
     *                              to the JAR files that contain plugins");
     *   pluginList                takes precedence over -pluginDir\n");
     *   pluginMode=<PluginClass>  plugin mode enabled by default in tool palette\n");
     *
     * @param lhs automaton to visualize
     * @param options options for ZGRViewer, must be enclosed by double quotes (see description)
     * @return returns null
     */
    public static Object show(FSA lhs, String... options) {
        try {
            final File temp = File.createTempFile("dlmr", ".dot");
            PrintStream stream = new PrintStream(temp);
            lhs.writeDot(stream);
            stream.close();

            final String[] ops = options;
            new Thread(new Runnable() {
                @Override
                public void run() {

                    try {
                        ArrayList<String> cmdArray = new ArrayList<>();
                        cmdArray.add("java");

                        String path = Operations.class.getProtectionDomain().getCodeSource().getLocation().getPath();

                        if (path.endsWith(".jar")) {
                            cmdArray.add("-cp");
                            cmdArray.add(path);
                            cmdArray.add("net.claribole.zgrviewer.ZGRViewer");
                            // path = path.substring(0, path.lastIndexOf(File.separator));
                        } else {
                            cmdArray.add("-jar");
                            cmdArray.add("deps/zgrviewer-target/zgrviewer-0.9.0.jar");
                        }

                        for (String o: ops)
                            cmdArray.add(" -" + o);
                        String absPath = temp.getAbsolutePath().replace(" ", "\\ ");
                        cmdArray.add(temp.getAbsolutePath());

                        Process proc = Runtime.getRuntime().exec(cmdArray.toArray(new String[cmdArray.size()]));
                        proc.waitFor();
                    } catch (InterruptedException | IOException e) {
                        e.printStackTrace();
                    }
                    if (!temp.delete())
                        temp.deleteOnExit();

                }
            }).start();

        } catch (IOException e) {
            throw new Error("Could not run ZGRViewer.");
        }

        return null;
    }

    /**
     * Prints a new line character to System.out.
     */
    public static void nl() {
        System.out.println();
    }

    /**
     * Prints an object to System.out.
     *
     * @param lhs object to print
     */
    public static void print(Object lhs) {
        System.out.print(lhs);
    }

    /**
     * Prints an object to System.out, followed by a newline.
     *
     * @param lhs object to print
     */
    public static void println(Object lhs) {
        System.out.println(lhs);
    }

    /**
     * 'Not' operator, used to negate boolean values.
     *
     * @param val value to negate
     * @return returns false if val is true, false otherwise
     */
    public static Boolean not(Boolean val) {
        return !val;
    }

    /**
     * 'AND' operator, used to check if all arguments evaluate to true.
     *
     * @param vals values to check
     * @return returns true if all arguments are true, false otherwise
     */
    public static Boolean and(Boolean val1, Boolean val2, Boolean... vals) {
        Boolean res = val1 && val2;

        for (int i=0; i < vals.length && res; i++) {
            res = vals[i];
        }

        return res;
    }

    /**
     * 'OR' operator, used to check if all arguments evaluate to true.
     *
     * @param vals values to check
     * @return returns true if all arguments are true, false otherwise
     */
    public static Boolean or(Boolean val1, Boolean val2, Boolean... vals) {
        Boolean res = val1 || val2;

        for (int i=0; i < vals.length && !res; i++) {
            res = vals[i];
        }

        return res;
    }

    /**
     * 'XOR' operator, used to check if all arguments evaluate to true.
     *
     * @param val1 value to check
     * @param val2 value to check
     * @return returns true if all arguments are true, false otherwise
     */
    public static Boolean xor(Boolean val1, Boolean val2) {
        int res = (val1 ? 1 : 0) + (val2 ? 1 : 0);

        return res == 1;
    }
}


text:
{% extends "base_generic.html" %}

{% block title %}Local login{% endblock %}

{% block heading %}Local login{% endblock %}

{% block content %}

    <form method="POST" action="#">
      {% csrf_token %}

              User ID

              <input type="text" name="userid" value="{{userid}}" />

              Password

              <input type="password" name="password" />

              <input type="submit" value="Login"  name="login" />
              <input type="submit" value="Cancel" name="cancel" />

      <input type="hidden" name="user_profile_url"  value="{{user_profile_url}}"/>
      <input type="hidden" name="continuation_url"  value="{{continuation_url}}"/>
    </form>

{% endblock %}


text:
title: rei miyasaka
firstName: rei
position: conductor
image: rei.jpg
status: active
order: 7
layout: profile
---
Rei was among the first members of the orchestra, having joined since the first rehearsal in the fall of 2007, when he was a computing science student at SFU. Since then, though he was tempted by somewhat antiquated promises of glory as a software developer and researcher, he stuck stubbornly to music, participating in any capacity possible. He briefly studied violin performance at UBC before family circumstances made it impossible to continue, and now serves as Publisher for Fraser Monthly Japanese community magazine and as a translator for Crunchyroll. He hopes to someday dust himself off and pick up the violin again, and is grateful to the orchestra for providing a place to keep the music alive.


text:
<?php

namespace Database\Exceptions;

/**
 * FatalException
 */
class FatalException extends \Exception
{

}


text:
package org.apache.tools.zip;

import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import java.util.zip.ZipException;

import static org.apache.tools.zip.ZipConstants.DWORD;
import static org.apache.tools.zip.ZipConstants.SHORT;
import static org.apache.tools.zip.ZipConstants.WORD;
import static org.apache.tools.zip.ZipConstants.ZIP64_MAGIC;
import static org.apache.tools.zip.ZipConstants.ZIP64_MAGIC_SHORT;

/**
 * Replacement for java.util.ZipFile.
 *
 *

 * This class adds support for file name encodings other than UTF-8 (which is
 * required to work on ZIP files created by native zip tools and is able to skip
 * a preamble like the one found in self extracting archives. Furthermore it
 * returns instances of org.apache.tools.zip.ZipEntry instead of
 * java.util.zip.ZipEntry.
 *

 *
 *

 * It doesn't extend java.util.zip.ZipFile as it would have to
 * reimplement all methods anyway. Like java.util.ZipFile, it uses
 * RandomAccessFile under the covers and supports compressed and uncompressed
 * entries. As of Apache Ant 1.9.0 it also transparently supports Zip64
 * extensions and thus individual entries and archives larger than 4 GB or with
 * more than 65536 entries.
 *

 *
 *

 * The method signatures mimic the ones of java.util.zip.ZipFile,
 * with a couple of exceptions:
 *
 *

 *
There is no getName method.

 *
entries has been renamed to getEntries.

 *
getEntries and getEntry return org.apache.tools.zip.ZipEntry
 * instances.

 *
close is allowed to throw IOException.

 *

 *
 */
public class ZipFile
{
	private static final int HASH_SIZE = 509;
	static final int NIBLET_MASK = 0x0f;
	static final int BYTE_SHIFT = 8;
	private static final int POS_0 = 0;
	private static final int POS_1 = 1;
	private static final int POS_2 = 2;
	private static final int POS_3 = 3;

	/**
	 * List of entries in the order they appear inside the central directory.
	 */
	private final List<ZipEntry> entries = new LinkedList<ZipEntry>();

	/**
	 * Maps String to list of ZipEntrys, name -> actual entries.
	 */
	private final Map<String, LinkedList<ZipEntry>> nameMap = new HashMap<String, LinkedList<ZipEntry>>(HASH_SIZE);

	private static final class OffsetEntry
	{
		private long headerOffset = -1;
		private long dataOffset = -1;
	}

	/**
	 * The encoding to use for filenames and the file comment.
	 *
	 *

	 * For a list of possible values see http://java.sun.com/j2se/1.5.0/docs/guide/intl/encoding.doc.html.
	 * Defaults to the platform's default character encoding.
	 *

	 */
	private final String encoding;

	/**
	 * The zip encoding to use for filenames and the file comment.
	 */
	private final ZipEncoding zipEncoding;

	/**
	 * File name of actual source.
	 */
	private final String archiveName;

	/**
	 * The actual data source.
	 */
	private final RandomAccessFile archive;

	/**
	 * Whether to look for and use Unicode extra fields.
	 */
	private final boolean useUnicodeExtraFields;

	/**
	 * Whether the file is closed.
	 */
	private boolean closed;

	// cached buffers
	private final byte[] DWORD_BUF = new byte[DWORD];
	private final byte[] WORD_BUF = new byte[WORD];
	private final byte[] CFH_BUF = new byte[CFH_LEN];
	private final byte[] SHORT_BUF = new byte[SHORT];

	/**
	 * Opens the given file for reading, assuming the platform's native encoding
	 * for file names.
	 *
	 * @param f
	 *            the archive.
	 *
	 * @throws IOException
	 *             if an error occurs while reading the file.
	 */
	public ZipFile(File f) throws IOException
	{
		this(f, null);
	}

	/**
	 * Opens the given file for reading, assuming the platform's native encoding
	 * for file names.
	 *
	 * @param name
	 *            name of the archive.
	 *
	 * @throws IOException
	 *             if an error occurs while reading the file.
	 */
	public ZipFile(String name) throws IOException
	{
		this(new File(name), null);
	}

	/**
	 * Opens the given file for reading, assuming the specified encoding for
	 * file names, scanning unicode extra fields.
	 *
	 * @param name
	 *            name of the archive.
	 * @param encoding
	 *            the encoding to use for file names, use null for the
	 *            platform's default encoding
	 *
	 * @throws IOException
	 *             if an error occurs while reading the file.
	 */
	public ZipFile(String name, String encoding) throws IOException
	{
		this(new File(name), encoding, true);
	}

	/**
	 * Opens the given file for reading, assuming the specified encoding for
	 * file names and scanning for unicode extra fields.
	 *
	 * @param f
	 *            the archive.
	 * @param encoding
	 *            the encoding to use for file names, use null for the
	 *            platform's default encoding
	 *
	 * @throws IOException
	 *             if an error occurs while reading the file.
	 */
	public ZipFile(File f, String encoding) throws IOException
	{
		this(f, encoding, true);
	}

	/**
	 * Opens the given file for reading, assuming the specified encoding for
	 * file names.
	 *
	 * @param f
	 *            the archive.
	 * @param encoding
	 *            the encoding to use for file names, use null for the
	 *            platform's default encoding
	 * @param useUnicodeExtraFields
	 *            whether to use InfoZIP Unicode Extra Fields (if present) to
	 *            set the file names.
	 *
	 * @throws IOException
	 *             if an error occurs while reading the file.
	 */
	public ZipFile(File f, String encoding, boolean useUnicodeExtraFields) throws IOException
	{
		this.archiveName = f.getAbsolutePath();
		this.encoding = encoding;
		this.zipEncoding = ZipEncodingHelper.getZipEncoding(encoding);
		this.useUnicodeExtraFields = useUnicodeExtraFields;
		archive = new RandomAccessFile(f, "r");
		boolean success = false;
		try
		{
			Map<ZipEntry, NameAndComment> entriesWithoutUTF8Flag = populateFromCentralDirectory();
			resolveLocalFileHeaderData(entriesWithoutUTF8Flag);
			success = true;
		}
		finally
		{
			if (!success)
			{
				try
				{
					closed = true;
					archive.close();
				}
				catch (IOException e2)
				{
					// swallow, throw the original exception instead
				}
			}
		}
	}

	/**
	 * The encoding to use for filenames and the file comment.
	 *
	 * @return null if using the platform's default character encoding.
	 */
	public String getEncoding()
	{
		return encoding;
	}

	/**
	 * Closes the archive.
	 *
	 * @throws IOException
	 *             if an error occurs closing the archive.
	 */
	public void close() throws IOException
	{
		// this flag is only written here and read in finalize() which
		// can never be run in parallel.
		// no synchronization needed.
		closed = true;

		archive.close();
	}

	/**
	 * close a zipfile quietly; throw no io fault, do nothing on a null
	 * parameter
	 *
	 * @param zipfile
	 *            file to close, can be null
	 */
	public static void closeQuietly(ZipFile zipfile)
	{
		if (zipfile != null)
		{
			try
			{
				zipfile.close();
			}
			catch (IOException e)
			{
				// ignore
			}
		}
	}

	/**
	 * Returns all entries.
	 *
	 *

	 * Entries will be returned in the same order they appear within the
	 * archive's central directory.
	 *

	 *
	 * @return all entries as {@link ZipEntry} instances
	 */
	public Enumeration<ZipEntry> getEntries()
	{
		return Collections.enumeration(entries);
	}

	/**
	 * Returns all entries in physical order.
	 *
	 *

	 * Entries will be returned in the same order their contents appear within
	 * the archive.
	 *

	 *
	 * @return all entries as {@link ZipEntry} instances
	 *
	 * @since Ant 1.9.0
	 */
	public Enumeration<ZipEntry> getEntriesInPhysicalOrder()
	{
		ZipEntry[] allEntries = entries.toArray(new ZipEntry[0]);
		Arrays.sort(allEntries, OFFSET_COMPARATOR);
		return Collections.enumeration(Arrays.asList(allEntries));
	}

	/**
	 * Returns a named entry - or {@code null} if no entry by that name exists.
	 *
	 *

	 * If multiple entries with the same name exist the first entry in the
	 * archive's central directory by that name is returned.
	 *

	 *
	 * @param name
	 *            name of the entry.
	 * @return the ZipEntry corresponding to the given name - or {@code null} if
	 *         not present.
	 */
	public ZipEntry getEntry(String name)
	{
		LinkedList<ZipEntry> entriesOfThatName = nameMap.get(name);
		return entriesOfThatName != null ? entriesOfThatName.getFirst() : null;
	}

	/**
	 * Returns all named entries in the same order they appear within the
	 * archive's central directory.
	 *
	 * @param name
	 *            name of the entry.
	 * @return the Iterable<ZipEntry> corresponding to the given name
	 * @since 1.9.2
	 */
	public Iterable<ZipEntry> getEntries(String name)
	{
		List<ZipEntry> entriesOfThatName = nameMap.get(name);
		return entriesOfThatName != null ? entriesOfThatName : Collections.<ZipEntry> emptyList();
	}

	/**
	 * Returns all named entries in the same order their contents appear within
	 * the archive.
	 *
	 * @param name
	 *            name of the entry.
	 * @return the Iterable<ZipEntry> corresponding to the given name
	 * @since 1.9.2
	 */
	public Iterable<ZipEntry> getEntriesInPhysicalOrder(String name)
	{
		ZipEntry[] entriesOfThatName = new ZipEntry[0];
		if (nameMap.containsKey(name))
		{
			entriesOfThatName = nameMap.get(name).toArray(entriesOfThatName);
			Arrays.sort(entriesOfThatName, OFFSET_COMPARATOR);
		}
		return Arrays.asList(entriesOfThatName);
	}

	/**
	 * Whether this class is able to read the given entry.
	 *
	 *

	 * May return false if it is set up to use encryption or a compression
	 * method that hasn't been implemented yet.
	 *

	 */
	public boolean canReadEntryData(ZipEntry ze)
	{
		return ZipUtil.canHandleEntryData(ze);
	}

	/**
	 * Returns an InputStream for reading the contents of the given entry.
	 *
	 * @param ze
	 *            the entry to get the stream for.
	 * @return a stream to read the entry from.
	 * @throws IOException
	 *             if unable to create an input stream from the zipentry
	 * @throws ZipException
	 *             if the zipentry uses an unsupported feature
	 */
	public InputStream getInputStream(ZipEntry ze) throws IOException, ZipException
	{
		if (!(ze instanceof Entry))
		{
			return null;
		}
		// cast valididty is checked just above
		OffsetEntry offsetEntry = ((Entry) ze).getOffsetEntry();
		ZipUtil.checkRequestedFeatures(ze);
		long start = offsetEntry.dataOffset;
		BoundedInputStream bis = new BoundedInputStream(start, ze.getCompressedSize());
		switch (ze.getMethod())
		{
		case ZipEntry.STORED:
			return bis;
		case ZipEntry.DEFLATED:
			bis.addDummy();
			final Inflater inflater = new Inflater(true);
			return new InflaterInputStream(bis, inflater)
			{
				@Override
				public void close() throws IOException
				{
					super.close();
					inflater.end();
				}
			};
		default:
			throw new ZipException("Found unsupported compression method " + ze.getMethod());
		}
	}

	/**
	 * Ensures that the close method of this zipfile is called when there are no
	 * more references to it.
	 *
	 * @see #close()
	 */
	@Override
	protected void finalize() throws Throwable
	{
		try
		{
			if (!closed)
			{
				System.err.println("Cleaning up unclosed ZipFile for archive " + archiveName);
				close();
			}
		}
		finally
		{
			super.finalize();
		}
	}

	/**
	 * Length of a "central directory" entry structure without file name, extra
	 * fields or comment.
	 */
	private static final int CFH_LEN =
	/* version made by */SHORT
	/* version needed to extract */+ SHORT
	/* general purpose bit flag */+ SHORT
	/* compression method */+ SHORT
	/* last mod file time */+ SHORT
	/* last mod file date */+ SHORT
	/* crc-32 */+ WORD
	/* compressed size */+ WORD
	/* uncompressed size */+ WORD
	/* filename length */+ SHORT
	/* extra field length */+ SHORT
	/* file comment length */+ SHORT
	/* disk number start */+ SHORT
	/* internal file attributes */+ SHORT
	/* external file attributes */+ WORD
	/* relative offset of local header */+ WORD;

	private static final long CFH_SIG = ZipLong.getValue(ZipOutputStream.CFH_SIG);

	/**
	 * Reads the central directory of the given archive and populates the
	 * internal tables with ZipEntry instances.
	 *
	 *

	 * The ZipEntrys will know all data that can be obtained from the central
	 * directory alone, but not the data that requires the local file header or
	 * additional data to be read.
	 *

	 *
	 * @return a map of zipentries that didn't have the language encoding flag
	 *         set when read.
	 */
	private Map<ZipEntry, NameAndComment> populateFromCentralDirectory() throws IOException
	{
		HashMap<ZipEntry, NameAndComment> noUTF8Flag = new HashMap<ZipEntry, NameAndComment>();

		positionAtCentralDirectory();

		archive.readFully(WORD_BUF);
		long sig = ZipLong.getValue(WORD_BUF);

		if (sig != CFH_SIG && startsWithLocalFileHeader())
		{
			throw new IOException("central directory is empty, can't expand" + " corrupt archive.");
		}

		while (sig == CFH_SIG)
		{
			readCentralDirectoryEntry(noUTF8Flag);
			archive.readFully(WORD_BUF);
			sig = ZipLong.getValue(WORD_BUF);
		}
		return noUTF8Flag;
	}

	/**
	 * Reads an individual entry of the central directory, creats an ZipEntry
	 * from it and adds it to the global maps.
	 *
	 * @param noUTF8Flag
	 *            map used to collect entries that don't have their UTF-8 flag
	 *            set and whose name will be set by data read from the local
	 *            file header later. The current entry may be added to this map.
	 */
	private void readCentralDirectoryEntry(Map<ZipEntry, NameAndComment> noUTF8Flag) throws IOException
	{
		archive.readFully(CFH_BUF);
		int off = 0;
		OffsetEntry offset = new OffsetEntry();
		Entry ze = new Entry(offset);

		int versionMadeBy = ZipShort.getValue(CFH_BUF, off);
		off += SHORT;
		ze.setPlatform((versionMadeBy >> BYTE_SHIFT) & NIBLET_MASK);

		off += SHORT; // skip version info

		final GeneralPurposeBit gpFlag = GeneralPurposeBit.parse(CFH_BUF, off);
		final boolean hasUTF8Flag = gpFlag.usesUTF8ForNames();
		final ZipEncoding entryEncoding = hasUTF8Flag ? ZipEncodingHelper.UTF8_ZIP_ENCODING : zipEncoding;
		ze.setGeneralPurposeBit(gpFlag);

		off += SHORT;

		ze.setMethod(ZipShort.getValue(CFH_BUF, off));
		off += SHORT;

		long time = ZipUtil.dosToJavaTime(ZipLong.getValue(CFH_BUF, off));
		ze.setTime(time);
		off += WORD;

		ze.setCrc(ZipLong.getValue(CFH_BUF, off));
		off += WORD;

		ze.setCompressedSize(ZipLong.getValue(CFH_BUF, off));
		off += WORD;

		ze.setSize(ZipLong.getValue(CFH_BUF, off));
		off += WORD;

		int fileNameLen = ZipShort.getValue(CFH_BUF, off);
		off += SHORT;

		int extraLen = ZipShort.getValue(CFH_BUF, off);
		off += SHORT;

		int commentLen = ZipShort.getValue(CFH_BUF, off);
		off += SHORT;

		int diskStart = ZipShort.getValue(CFH_BUF, off);
		off += SHORT;

		ze.setInternalAttributes(ZipShort.getValue(CFH_BUF, off));
		off += SHORT;

		ze.setExternalAttributes(ZipLong.getValue(CFH_BUF, off));
		off += WORD;

		byte[] fileName = new byte[fileNameLen];
		archive.readFully(fileName);
		ze.setName(entryEncoding.decode(fileName), fileName);

		// LFH offset,
		offset.headerOffset = ZipLong.getValue(CFH_BUF, off);
		// data offset will be filled later
		entries.add(ze);

		byte[] cdExtraData = new byte[extraLen];
		archive.readFully(cdExtraData);
		ze.setCentralDirectoryExtra(cdExtraData);

		setSizesAndOffsetFromZip64Extra(ze, offset, diskStart);

		byte[] comment = new byte[commentLen];
		archive.readFully(comment);
		ze.setComment(entryEncoding.decode(comment));

		if (!hasUTF8Flag && useUnicodeExtraFields)
		{
			noUTF8Flag.put(ze, new NameAndComment(fileName, comment));
		}
	}

	/**
	 * If the entry holds a Zip64 extended information extra field, read sizes
	 * from there if the entry's sizes are set to 0xFFFFFFFFF, do the same for
	 * the offset of the local file header.
	 *
	 *

	 * Ensures the Zip64 extra either knows both compressed and uncompressed
	 * size or neither of both as the internal logic in ExtraFieldUtils forces
	 * the field to create local header data even if they are never used - and
	 * here a field with only one size would be invalid.
	 *

	 */
	private void setSizesAndOffsetFromZip64Extra(ZipEntry ze, OffsetEntry offset, int diskStart) throws IOException
	{
		Zip64ExtendedInformationExtraField z64 = (Zip64ExtendedInformationExtraField) ze
				.getExtraField(Zip64ExtendedInformationExtraField.HEADER_ID);
		if (z64 != null)
		{
			boolean hasUncompressedSize = ze.getSize() == ZIP64_MAGIC;
			boolean hasCompressedSize = ze.getCompressedSize() == ZIP64_MAGIC;
			boolean hasRelativeHeaderOffset = offset.headerOffset == ZIP64_MAGIC;
			z64.reparseCentralDirectoryData(hasUncompressedSize, hasCompressedSize, hasRelativeHeaderOffset,
					diskStart == ZIP64_MAGIC_SHORT);

			if (hasUncompressedSize)
			{
				ze.setSize(z64.getSize().getLongValue());
			}
			else if (hasCompressedSize)
			{
				z64.setSize(new ZipEightByteInteger(ze.getSize()));
			}

			if (hasCompressedSize)
			{
				ze.setCompressedSize(z64.getCompressedSize().getLongValue());
			}
			else if (hasUncompressedSize)
			{
				z64.setCompressedSize(new ZipEightByteInteger(ze.getCompressedSize()));
			}

			if (hasRelativeHeaderOffset)
			{
				offset.headerOffset = z64.getRelativeHeaderOffset().getLongValue();
			}
		}
	}

	/**
	 * Length of the "End of central directory record" - which is supposed to be
	 * the last structure of the archive - without file comment.
	 */
	private static final int MIN_EOCD_SIZE =
	/* end of central dir signature */WORD
	/* number of this disk */+ SHORT
	/* number of the disk with the */
	/* start of the central directory */+ SHORT
	/* total number of entries in */
	/* the central dir on this disk */+ SHORT
	/* total number of entries in */
	/* the central dir */+ SHORT
	/* size of the central directory */+ WORD
	/* offset of start of central */
	/* directory with respect to */
	/* the starting disk number */+ WORD
	/* zipfile comment length */+ SHORT;

	/**
	 * Maximum length of the "End of central directory record" with a file
	 * comment.
	 */
	private static final int MAX_EOCD_SIZE = MIN_EOCD_SIZE
	/* maximum length of zipfile comment */+ ZIP64_MAGIC_SHORT;

	/**
	 * Offset of the field that holds the location of the first central
	 * directory entry inside the "End of central directory
	 * record" relative to the start of the "End of central directory record".
	 */
	private static final int CFD_LOCATOR_OFFSET =
	/* end of central dir signature */WORD
	/* number of this disk */+ SHORT
	/* number of the disk with the */
	/* start of the central directory */+ SHORT
	/* total number of entries in */
	/* the central dir on this disk */+ SHORT
	/* total number of entries in */
	/* the central dir */+ SHORT
	/* size of the central directory */+ WORD;

	/**
	 * Length of the "Zip64 end of central directory locator" - which should be
	 * right in front of the "end of central directory record" if one is present
	 * at all.
	 */
	private static final int ZIP64_EOCDL_LENGTH =
	/* zip64 end of central dir locator sig */WORD
	/* number of the disk with the start */
	/* start of the zip64 end of */
	/* central directory */+ WORD
	/* relative offset of the zip64 */
	/* end of central directory record */+ DWORD
	/* total number of disks */+ WORD;

	/**
	 * Offset of the field that holds the location of the "Zip64 end of central
	 * directory record" inside the "Zip64 end of central directory
	 * locator" relative to the start of the "Zip64 end of central directory
	 * locator".
	 */
	private static final int ZIP64_EOCDL_LOCATOR_OFFSET =
	/* zip64 end of central dir locator sig */WORD
	/* number of the disk with the start */
	/* start of the zip64 end of */
	/* central directory */+ WORD;

	/**
	 * Offset of the field that holds the location of the first central
	 * directory entry inside the "Zip64 end of central directory
	 * record" relative to the start of the "Zip64 end of central directory
	 * record".
	 */
	private static final int ZIP64_EOCD_CFD_LOCATOR_OFFSET =
	/* zip64 end of central dir */
	/* signature */WORD
	/* size of zip64 end of central */
	/* directory record */+ DWORD
	/* version made by */+ SHORT
	/* version needed to extract */+ SHORT
	/* number of this disk */+ WORD
	/* number of the disk with the */
	/* start of the central directory */+ WORD
	/* total number of entries in the */
	/* central directory on this disk */+ DWORD
	/* total number of entries in the */
	/* central directory */+ DWORD
	/* size of the central directory */+ DWORD;

	/**
	 * Searches for either the "Zip64 end of central directory
	 * locator" or the "End of central dir record", parses it and
	 * positions the stream at the first central directory record.
	 */
	private void positionAtCentralDirectory() throws IOException
	{
		positionAtEndOfCentralDirectoryRecord();
		boolean found = false;
		boolean searchedForZip64EOCD = archive.getFilePointer() > ZIP64_EOCDL_LENGTH;
		if (searchedForZip64EOCD)
		{
			archive.seek(archive.getFilePointer() - ZIP64_EOCDL_LENGTH);
			archive.readFully(WORD_BUF);
			found = Arrays.equals(ZipOutputStream.ZIP64_EOCD_LOC_SIG, WORD_BUF);
		}
		if (!found)
		{
			// not a ZIP64 archive
			if (searchedForZip64EOCD)
			{
				skipBytes(ZIP64_EOCDL_LENGTH - WORD);
			}
			positionAtCentralDirectory32();
		}
		else
		{
			positionAtCentralDirectory64();
		}
	}

	/**
	 * Parses the "Zip64 end of central directory locator", finds the
	 * "Zip64 end of central directory record" using the parsed
	 * information, parses that and positions the stream at the first central
	 * directory record.
	 */
	private void positionAtCentralDirectory64() throws IOException
	{
		skipBytes(ZIP64_EOCDL_LOCATOR_OFFSET - WORD /*
													 * signature has already
													 * been read
													 */);
		archive.readFully(DWORD_BUF);
		archive.seek(ZipEightByteInteger.getLongValue(DWORD_BUF));
		archive.readFully(WORD_BUF);
		if (!Arrays.equals(WORD_BUF, ZipOutputStream.ZIP64_EOCD_SIG))
		{
			throw new ZipException("archive's ZIP64 end of central " + "directory locator is corrupt.");
		}
		skipBytes(ZIP64_EOCD_CFD_LOCATOR_OFFSET - WORD /*
														 * signature has already
														 * been read
														 */);
		archive.readFully(DWORD_BUF);
		archive.seek(ZipEightByteInteger.getLongValue(DWORD_BUF));
	}

	/**
	 * Searches for the "End of central dir record", parses it and
	 * positions the stream at the first central directory record.
	 */
	private void positionAtCentralDirectory32() throws IOException
	{
		skipBytes(CFD_LOCATOR_OFFSET);
		archive.readFully(WORD_BUF);
		archive.seek(ZipLong.getValue(WORD_BUF));
	}

	/**
	 * Searches for the and positions the stream at the start of the "End
	 * of central dir record".
	 */
	private void positionAtEndOfCentralDirectoryRecord() throws IOException
	{
		boolean found = tryToLocateSignature(MIN_EOCD_SIZE, MAX_EOCD_SIZE, ZipOutputStream.EOCD_SIG);
		if (!found)
		{
			throw new ZipException("archive is not a ZIP archive");
		}
	}

	/**
	 * Searches the archive backwards from minDistance to maxDistance for the
	 * given signature, positions the RandomaccessFile right at the signature if
	 * it has been found.
	 */
	private boolean tryToLocateSignature(long minDistanceFromEnd, long maxDistanceFromEnd, byte[] sig) throws IOException
	{
		boolean found = false;
		long off = archive.length() - minDistanceFromEnd;
		final long stopSearching = Math.max(0L, archive.length() - maxDistanceFromEnd);
		if (off >= 0)
		{
			for (; off >= stopSearching; off--)
			{
				archive.seek(off);
				int curr = archive.read();
				if (curr == -1)
				{
					break;
				}
				if (curr == sig[POS_0])
				{
					curr = archive.read();
					if (curr == sig[POS_1])
					{
						curr = archive.read();
						if (curr == sig[POS_2])
						{
							curr = archive.read();
							if (curr == sig[POS_3])
							{
								found = true;
								break;
							}
						}
					}
				}
			}
		}
		if (found)
		{
			archive.seek(off);
		}
		return found;
	}

	/**
	 * Skips the given number of bytes or throws an EOFException if skipping
	 * failed.
	 */
	private void skipBytes(final int count) throws IOException
	{
		int totalSkipped = 0;
		while (totalSkipped < count)
		{
			int skippedNow = archive.skipBytes(count - totalSkipped);
			if (skippedNow <= 0)
			{
				throw new EOFException();
			}
			totalSkipped += skippedNow;
		}
	}

	/**
	 * Number of bytes in local file header up to the "length of
	 * filename" entry.
	 */
	private static final long LFH_OFFSET_FOR_FILENAME_LENGTH =
	/* local file header signature */WORD
	/* version needed to extract */+ SHORT
	/* general purpose bit flag */+ SHORT
	/* compression method */+ SHORT
	/* last mod file time */+ SHORT
	/* last mod file date */+ SHORT
	/* crc-32 */+ WORD
	/* compressed size */+ WORD
	/* uncompressed size */+ WORD;

	/**
	 * Walks through all recorded entries and adds the data available from the
	 * local file header.
	 *
	 *

	 * Also records the offsets for the data to read from the entries.
	 *

	 */
	private void resolveLocalFileHeaderData(Map<ZipEntry, NameAndComment> entriesWithoutUTF8Flag) throws IOException
	{
		for (Iterator<ZipEntry> it = entries.iterator(); it.hasNext();)
		{
			// entries is filled in populateFromCentralDirectory and
			// never modified
			Entry ze = (Entry) it.next();
			OffsetEntry offsetEntry = ze.getOffsetEntry();
			long offset = offsetEntry.headerOffset;
			archive.seek(offset + LFH_OFFSET_FOR_FILENAME_LENGTH);
			archive.readFully(SHORT_BUF);
			int fileNameLen = ZipShort.getValue(SHORT_BUF);
			archive.readFully(SHORT_BUF);
			int extraFieldLen = ZipShort.getValue(SHORT_BUF);
			int lenToSkip = fileNameLen;
			while (lenToSkip > 0)
			{
				int skipped = archive.skipBytes(lenToSkip);
				if (skipped <= 0)
				{
					throw new IOException("failed to skip file name in" + " local file header");
				}
				lenToSkip -= skipped;
			}
			byte[] localExtraData = new byte[extraFieldLen];
			archive.readFully(localExtraData);
			ze.setExtra(localExtraData);
			offsetEntry.dataOffset = offset + LFH_OFFSET_FOR_FILENAME_LENGTH + SHORT + SHORT + fileNameLen + extraFieldLen;

			if (entriesWithoutUTF8Flag.containsKey(ze))
			{
				NameAndComment nc = entriesWithoutUTF8Flag.get(ze);
				ZipUtil.setNameAndCommentFromExtraFields(ze, nc.name, nc.comment);
			}

			String name = ze.getName();
			LinkedList<ZipEntry> entriesOfThatName = nameMap.get(name);
			if (entriesOfThatName == null)
			{
				entriesOfThatName = new LinkedList<ZipEntry>();
				nameMap.put(name, entriesOfThatName);
			}
			entriesOfThatName.addLast(ze);
		}
	}

	/**
	 * Checks whether the archive starts with a LFH. If it doesn't, it may be an
	 * empty archive.
	 */
	private boolean startsWithLocalFileHeader() throws IOException
	{
		archive.seek(0);
		archive.readFully(WORD_BUF);
		return Arrays.equals(WORD_BUF, ZipOutputStream.LFH_SIG);
	}

	/**
	 * InputStream that delegates requests to the underlying RandomAccessFile,
	 * making sure that only bytes from a certain range can be read.
	 */
	private class BoundedInputStream extends InputStream
	{
		private long remaining;
		private long loc;
		private boolean addDummyByte = false;

		BoundedInputStream(long start, long remaining)
		{
			this.remaining = remaining;
			loc = start;
		}

		@Override
		public int read() throws IOException
		{
			if (remaining-- <= 0)
			{
				if (addDummyByte)
				{
					addDummyByte = false;
					return 0;
				}
				return -1;
			}
			synchronized (archive)
			{
				archive.seek(loc++);
				return archive.read();
			}
		}

		@Override
		public int read(byte[] b, int off, int len) throws IOException
		{
			if (remaining <= 0)
			{
				if (addDummyByte)
				{
					addDummyByte = false;
					b[off] = 0;
					return 1;
				}
				return -1;
			}

			if (len <= 0)
			{
				return 0;
			}

			if (len > remaining)
			{
				len = (int) remaining;
			}
			int ret = -1;
			synchronized (archive)
			{
				archive.seek(loc);
				ret = archive.read(b, off, len);
			}
			if (ret > 0)
			{
				loc += ret;
				remaining -= ret;
			}
			return ret;
		}

		/**
		 * Inflater needs an extra dummy byte for nowrap - see Inflater's
		 * javadocs.
		 */
		void addDummy()
		{
			addDummyByte = true;
		}
	}

	private static final class NameAndComment
	{
		private final byte[] name;
		private final byte[] comment;

		private NameAndComment(byte[] name, byte[] comment)
		{
			this.name = name;
			this.comment = comment;
		}
	}

	/**
	 * Compares two ZipEntries based on their offset within the archive.
	 *
	 *

	 * Won't return any meaningful results if one of the entries isn't part of
	 * the archive at all.
	 *

	 *
	 * @since Ant 1.9.0
	 */
	private final Comparator<ZipEntry> OFFSET_COMPARATOR = new Comparator<ZipEntry>()
	{
		public int compare(ZipEntry e1, ZipEntry e2)
		{
			if (e1 == e2)
			{
				return 0;
			}

			Entry ent1 = e1 instanceof Entry ? (Entry) e1 : null;
			Entry ent2 = e2 instanceof Entry ? (Entry) e2 : null;
			if (ent1 == null)
			{
				return 1;
			}
			if (ent2 == null)
			{
				return -1;
			}
			long val = (ent1.getOffsetEntry().headerOffset - ent2.getOffsetEntry().headerOffset);
			return val == 0 ? 0 : val < 0 ? -1 : +1;
		}
	};

	/**
	 * Extends ZipEntry to store the offset within the archive.
	 */
	private static class Entry extends ZipEntry
	{

		private final OffsetEntry offsetEntry;

		Entry(OffsetEntry offset)
		{
			this.offsetEntry = offset;
		}

		OffsetEntry getOffsetEntry()
		{
			return offsetEntry;
		}

		@Override
		public int hashCode()
		{
			return 3 * super.hashCode() + (int) (offsetEntry.headerOffset % Integer.MAX_VALUE);
		}

		@Override
		public boolean equals(Object other)
		{
			if (super.equals(other))
			{
				// super.equals would return false if other were not an Entry
				Entry otherEntry = (Entry) other;
				return offsetEntry.headerOffset == otherEntry.offsetEntry.headerOffset
						&& offsetEntry.dataOffset == otherEntry.offsetEntry.dataOffset;
			}
			return false;
		}
	}
}


text:
#include <osquery/config.h>
#include <osquery/flags.h>
#include <osquery/logger.h>

namespace pt = boost::property_tree;

namespace osquery {

/**
 * @brief A simple ConfigParserPlugin for an "options" dictionary key.
 */
class OptionsConfigParserPlugin : public ConfigParserPlugin {
 public:
  std::vector<std::string> keys() { return {"options"}; }

  Status setUp() {
    data_.put_child("options", pt::ptree());
    return Status(0, "OK");
  }

  Status update(const std::map<std::string, pt::ptree>& config) {
    if (config.count("options") > 0) {
      data_ = pt::ptree();
      data_.put_child("options", config.at("options"));
    }

    const auto& options = data_.get_child("options");
    for (const auto& option : options) {
      std::string value = options.get<std::string>(option.first, "");
      if (value.empty()) {
        continue;
      }

      Flag::updateValue(option.first, value);
      // There is a special case for supported Gflags-reserved switches.
      if (option.first == "verbose" || option.first == "verbose_debug" ||
          option.first == "debug") {
        setVerboseLevel();
        if (Flag::getValue("verbose") == "true") {
          VLOG(1) << "Verbose logging enabled by config option";
        }
      }
    }

    return Status(0, "OK");
  }
};

REGISTER_INTERNAL(OptionsConfigParserPlugin, "config_parser", "options");
}


text:
class AddUnknownSetlistToShows < ActiveRecord::Migration
  def change
    add_column :shows, :unknown_setlist, :boolean, default: false, null: false
  end
end


text:
* https://www.haskell.org/haskellwiki/All_About_Monads#Example_8
* https://raw.githubusercontent.com/dag/all-about-monads/master/examples/example17.hs

```Haskell
{- Author:     Jeff Newbern
   Maintainer: Jeff Newbern <jnewbern@nomaware.com>
   Time-stamp: <Mon Aug 18 15:47:36 2003>
   License:    GPL
-}

{- DESCRIPTION

Example 17 - Using the Writer monad

Usage: Compile the code to produce a simple firewall simulator.

       The first argument is a file (look at rules.txt) that contains
       a list of firewall rules.

       The second argument is a file (look at packets.txt) that contains
       a list of packets.

       Running the program with the two arguments will cause the
       program to load the rule set and then use the rules to filter all
       of the packets in the packet file.  The program will display all
       of the allowed packets followed by a log of the simulated
       firewall activity.

Try: ./ex17 rules.txt packets.txt
-}

import System.IO
import System.Environment (getArgs)
import Data.Maybe
import Data.List
import Control.Monad.Writer

-- this is the definition of our simple packet format
data Data   = AnyData | Data String deriving (Show,Read)
data Addr   = AnyHost | Host Int    deriving (Show,Read)
data Packet = Packet {from::Addr, to::Addr, payload::Data} deriving (Eq,Show,Read)

-- these Eq definitions allow for pattern matching
instance Eq Data where
  AnyData   == _         = True
  _         == AnyData   = True
  (Data s1) == (Data s2) = s1 == s2

instance Eq Addr where
  AnyHost   == _         = True
  _         == AnyHost   = True
  (Host h1) == (Host h2) = h1 == h2

-- this is the format of our rules
data Disposition = Accept | Reject deriving (Eq,Show,Read)
data Rule = Rule {disposition::Disposition, pattern::Packet, logIt::Bool} deriving (Eq,Show,Read)

-- match a packet against a single rule
matchPacket :: Packet -> Rule -> Maybe Rule
matchPacket packet rule = if pattern rule == packet then Just rule else Nothing

-- match a packet against a list of rules
match :: [Rule] -> Packet -> Maybe Rule
match rules packet = foldl mplus Nothing (map (matchPacket packet) rules)

-- this is the format of our log entries
data Entry = Log {count::Int, msg::String} deriving Eq

instance Show Entry where
  show (Log 1 s) = s
  show (Log n s) = (show n) ++ " X " ++ s

-- add a message to the log
logMsg :: String -> Writer [Entry] ()
logMsg s = tell [Log 1 s]

-- merge identical entries at the end of the log
-- This function uses [Entry] as both the log type and the result type.
-- When two identical messages are merged, the result is just the message
-- with an incremented count.  When two different messages are merged,
-- the first message is logged and the second is returned as the result.
mergeEntries :: [Entry] -> [Entry] -> Writer [Entry] [Entry]
mergeEntries []   x    = return x
mergeEntries x    []   = return x
mergeEntries [e1] [e2] = let (Log n msg)   = e1
                             (Log n' msg') = e2
                         in if msg == msg' then
                              return [(Log (n+n') msg)]
                            else
                              do tell [e1]
                                 return [e2]

-- this handles one packet
filterOne :: [Rule] -> Packet -> Writer [Entry] (Maybe Packet)
filterOne rules packet = do rule <- return (match rules packet)
                            case rule of
                              Nothing  -> do logMsg ("DROPPING UNMATCHED PACKET: " ++ (show packet))
                                             return Nothing
                              (Just r) -> do when (logIt r) (logMsg ("MATCH: " ++ (show r) ++ " <=> " ++ (show packet)))
                                             case r of
                                               (Rule Accept _ _) -> return (Just packet)
                                               (Rule Reject _ _) -> return Nothing

-- This is a complex-looking function but it is actually pretty simple.
-- It maps a function over a list of values to get a list of Writers,
-- then runs each writer and combines the results.  The result of the function
-- is a writer whose value is a list of all the values from the writers and whose
-- log output is the result of folding the merge operator into the individual
-- log entries (using 'initial' as the initial log value).
groupSame :: (Monoid a) => a -> (a -> a -> Writer a a) -> [b] -> (b -> Writer a c) -> Writer a [c]
groupSame initial merge []     _  = do tell initial
                                       return []
groupSame initial merge (x:xs) fn = do (result,output) <- return (runWriter (fn x))
                                       new             <- merge initial output
                                       rest            <- groupSame new merge xs fn
                                       return (result:rest)

-- this filters a list of packets, producing a filtered packet list and a log of
-- the activity in which consecutive messages are merged
filterAll :: [Rule] -> [Packet] -> Writer [Entry] [Packet]
filterAll rules packets = do tell [Log 1 "STARTING PACKET FILTER"]
                             out <- groupSame [] mergeEntries packets (filterOne rules)
                             tell [Log 1 "STOPPING PACKET FILTER"]
                             return (catMaybes out)

-- read the rule data from the file named in the first argument, and the packet data from
-- the file named in the second argument, and then print the accepted packets followed by
-- a log generated during the computation.
main :: IO ()
main = do args       <- getArgs
	  ruleData   <- readFile (args!!0)
	  packetData <- readFile (args!!1)
	  let rules     = (read ruleData)::[Rule]
	      packets   = (read packetData)::[Packet]
	      (out,log) = runWriter (filterAll rules packets)
	  putStrLn "ACCEPTED PACKETS"
	  putStr (unlines (map show out))
	  putStrLn "\n\nFIREWALL LOG"
	  putStr (unlines (map show log))

-- END OF FILE
```

## Screenshot

![Screenshot](https://raw.githubusercontent.com/taylorjg/Monads/master/Images/WriterAllAboutMonadsExample.png "Screenshot")


text:
package com.netflix.governator.guice.servlet;

import java.io.IOException;

import javax.inject.Singleton;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

/**
 * This service is a hack to solve a bug in Guice's serving of jsp files.
 *
 * To enable add this line to your ServletModule
 * <pre>
 * {@code
 * serveRegex("/.*\\.jsp").with(JspDispatchServlet.class);
 * bind(JspDispatchServlet.class).asEagerSingleton();
 * }
 * </pre>
 *
 * @author elandau
 */
@Singleton
public class JspDispatchServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        RequestDispatcher rd = getServletContext().getRequestDispatcher(req.getRequestURI());
        req.setAttribute("org.apache.catalina.jsp_file", req.getRequestURI());

        // Wrap ServletPath with an empty value to avoid Guice's null getServletPath() bug from within a filter/servlet chain
        HttpServletRequest wrapped = new HttpServletRequestWrapper(req) {
            public String getServletPath() {
                return "";
            }
        };

        rd.include(wrapped, resp);
    }
}