text:
@interface CheckManager () <CheckfileCollectionDelegate, CheckfileDelegate>
@property (nonatomic, strong) CheckfileCollection *checkfiles;
@property (nonatomic, strong) MenuController *menuController;
@property (nonatomic, strong) StickiesController *stickiesController;
@property (nonatomic, strong) NotificationsController *notificationsController;
@property (nonatomic, strong) WebUI *webUI;
@property (nonatomic, strong) Settings *settings;
@end

@implementation CheckManager
@synthesize
    checkfiles = _checkfiles,
    menuController = _menuController,
    stickiesController = _stickiesController,
    notificationsController = _notificationsController,
    webUI = _webUI,
    settings = _settings;

- (id)initWithMenuController:(MenuController *)menuController
          stickiesController:(StickiesController *)stickiesController
     notificationsController:(NotificationsController *)notificationsController
                       webUI:(WebUI *)webUI
                    settings:(Settings *)settings {
    if (self = [super init]) {
        self.menuController = menuController;
        self.stickiesController = stickiesController;
        self.notificationsController = notificationsController;
        self.webUI = webUI;
        self.settings = settings;
    }
    return self;
}

- (void)loadCheckfiles {
    self.checkfiles = [CheckfileCollection collectionFromCheckmanUserDirectoryPath];
    self.checkfiles.delegate = self;
    [self.checkfiles trackChanges];
}

- (void)reloadCheckfiles {
    NSAssert(self.checkfiles, @"Checkfiles must first be loaded");
    [self.checkfiles reloadFiles];
}

#pragma mark - CheckfileCollectionDelegate

- (void)checkfileCollection:(CheckfileCollection *)collection didAddCheckfile:(Checkfile *)checkfile {
    NSUInteger index = [collection indexOfCheckfile:checkfile];
    [self.menuController insertSectionWithTag:checkfile.tag atIndex:index];
    [self _showCheckfileEntries:checkfile];

    checkfile.delegate = self;
    [checkfile trackChanges];
}

- (void)checkfileCollection:(CheckfileCollection *)collection willRemoveCheckfile:(Checkfile *)checkfile {
    checkfile.delegate = nil;
    [self _hideCheckfileEntries:checkfile];
    [self.menuController removeSectionWithTag:checkfile.tag];
}

#pragma mark - CheckfileDelegate

- (void)checkfile:(Checkfile *)checkfile didAddEntry:(CheckfileEntry *)entry {
    [self _showEntry:entry fromCheckfile:checkfile];
}

- (void)checkfile:(Checkfile *)checkfile willRemoveEntry:(CheckfileEntry *)entry {
    [self _hideEntry:entry fromCheckfile:checkfile];
}

#pragma mark - Showing entries

- (void)_showCheckfileEntries:(Checkfile *)checkfile {
    for (CheckfileEntry *entry in checkfile.entries) {
        [self _showEntry:entry fromCheckfile:checkfile];
    }
}

- (void)_showEntry:(CheckfileEntry *)entry fromCheckfile:(Checkfile *)checkfile {
    NSUInteger entryIndex = [checkfile indexOfEntry:entry];

    if (entry.isCommandEntry) {
        Check *check = [self _checkFromEntry:(id)entry checkfile:checkfile];
        [check startImmediately:YES];

        [self.menuController
            insertCheck:check
            atIndex:entryIndex
            inSectionWithTag:checkfile.tag];

        [self.stickiesController addCheck:check];
        [self.notificationsController addCheck:check];
        [self.webUI addCheck:check];
    }
    else if (entry.isSeparatorEntry) {
        [self.menuController
            insertSeparatorItemWithTag:entry.tag
            atIndex:entryIndex
            inSectionWithTag:checkfile.tag];
    }
    else if (entry.isTitledSeparatorEntry) {
        [self.menuController
            insertTitledSeparatorItemWithTag:entry.tag
            title:[(CheckfileTitledSeparatorEntry *)entry title]
            atIndex:entryIndex
            inSectionWithTag:checkfile.tag];
    }
    else NSAssert(NO, @"Unknown entry type cannot be shown.");
}

- (Check *)_checkFromEntry:(CheckfileCommandEntry *)entry checkfile:(Checkfile *)checkfile {
    Check *check =
        [[Check alloc]
            initWithName:entry.name
            command:entry.command
            directoryPath:checkfile.resolvedDirectoryPath];
    check.tag = entry.tag;

    check.primaryContextName = entry.primaryContextName;
    check.secondaryContextName = entry.secondaryContextName;
    check.runInterval = [self.settings
        runIntervalForCheckWithName:check.name
        inCheckfileWithName:checkfile.name];
    check.disabled = [self.settings
        isCheckWithNameDisabled:check.name
        inCheckfileWithName:checkfile.name];

    return check;
}

#pragma mark - Hiding entries

- (void)_hideCheckfileEntries:(Checkfile *)checkfile {
    for (CheckfileEntry *entry in checkfile.entries) {
        [self _hideEntry:entry fromCheckfile:checkfile];
    }
}

- (void)_hideEntry:(CheckfileEntry *)entry fromCheckfile:(Checkfile *)checkfile {
    if (entry.isCommandEntry) {
        Check *check = [self.menuController checkWithTag:entry.tag];
        [self.stickiesController removeCheck:check];
        [self.notificationsController removeCheck:check];
        [self.webUI removeCheck:check];
        [check stop];
    }

    [self.menuController
        removeItemWithTag:entry.tag
        inSectionWithTag:checkfile.tag];
}
@end


text:
import edu.neu.nutrons.ultimateascent.commands.CommandBase;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author NUTRONs
 */
public class ResetGyroCmd extends CommandBase {

    public ResetGyroCmd() {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
        dt.resetGyro();
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return true;
    }

    // Called once after isFinished returns true
    protected void end() {
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}

redpajama_set_name: RedPajamaGithub


text:
USE `appbase`;

INSERT INTO `groups` (id,title) VALUES
  (null, "user"),
  (null,"superuser");


text:
'use strict';
var winston = require('winston');

module.exports = {
    up: function (queryInterface, Sequelize) {
        return queryInterface.addColumn('vod_resume', 'reaction', {
            type: Sequelize.INTEGER,
            allowNull: false,
            defaultValue: 0,
            after: 'resume_position'
        }).catch(function (err) {
            winston.error('Adding column vod_resume.reaction failed with error message: ', err.message);
        });
    },
    down: function (queryInterface, Sequelize) {
        return queryInterface.removeColumn('vod_resume', 'reaction').catch(function (err) {
            winston.error('Dropping column vod_resume.reaction failed with error message: ', err.message);
        });
    }
};


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.trino.plugin.raptor.legacy.metadata;

import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.ResultSetMapper;

import java.sql.ResultSet;
import java.sql.SQLException;

import static java.util.Objects.requireNonNull;

public class TableStatsRow
{
    private final String schemaName;
    private final String tableName;
    private final long createTime;
    private final long updateTime;
    private final long tableVersion;
    private final long shardCount;
    private final long rowCount;
    private final long compressedSize;
    private final long uncompressedSize;

    public TableStatsRow(
            String schemaName,
            String tableName,
            long createTime,
            long updateTime,
            long tableVersion,
            long shardCount,
            long rowCount,
            long compressedSize,
            long uncompressedSize)
    {
        this.schemaName = requireNonNull(schemaName, "schemaName is null");
        this.tableName = requireNonNull(tableName, "tableName is null");
        this.createTime = createTime;
        this.updateTime = updateTime;
        this.tableVersion = tableVersion;
        this.shardCount = shardCount;
        this.rowCount = rowCount;
        this.compressedSize = compressedSize;
        this.uncompressedSize = uncompressedSize;
    }

    public String getSchemaName()
    {
        return schemaName;
    }

    public String getTableName()
    {
        return tableName;
    }

    public long getCreateTime()
    {
        return createTime;
    }

    public long getUpdateTime()
    {
        return updateTime;
    }

    public long getTableVersion()
    {
        return tableVersion;
    }

    public long getShardCount()
    {
        return shardCount;
    }

    public long getRowCount()
    {
        return rowCount;
    }

    public long getCompressedSize()
    {
        return compressedSize;
    }

    public long getUncompressedSize()
    {
        return uncompressedSize;
    }

    public static class Mapper
            implements ResultSetMapper<TableStatsRow>
    {
        @Override
        public TableStatsRow map(int index, ResultSet rs, StatementContext context)
                throws SQLException
        {
            return new TableStatsRow(
                    rs.getString("schema_name"),
                    rs.getString("table_name"),
                    rs.getLong("create_time"),
                    rs.getLong("update_time"),
                    rs.getLong("table_version"),
                    rs.getLong("shard_count"),
                    rs.getLong("row_count"),
                    rs.getLong("compressed_size"),
                    rs.getLong("uncompressed_size"));
        }
    }
}


text:
package de.tblsoft.solr.pipeline.filter;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import de.tblsoft.solr.pipeline.AbstractFilter;
import de.tblsoft.solr.pipeline.bean.Document;

/**
 * Created by tblsoft on 30.06.16.
 *
 * Count the characters for a specific field.
 */
public class TokenCounterFilter extends AbstractFilter {

	private String fieldName;
	private String tokenCountFieldName;

    @Override
    public void init() {
        fieldName = getProperty("fieldName", null);
        verify(fieldName, "For the TokenCounterFilter a fieldName property must be defined.");

        tokenCountFieldName = getProperty("tokenCountFieldName", "tokenCount");
        super.init();
    }

    @Override
    public void document(Document document) {
        List<String> values = document.getFieldValues(fieldName, new ArrayList<String>());
        int tokenCount = 0;
        for(String value: values) {
            StringTokenizer tokenizer = new StringTokenizer(value);
            tokenCount = tokenCount + tokenizer.countTokens();
        }
        document.setField(tokenCountFieldName, String.valueOf(tokenCount));

        super.document(document);
    }

}


text:
define(["npm:aurelia-dependency-injection@1.3.1/aurelia-dependency-injection"], function(main) {
  return main;
});


text:
#include "psb_overlay.h"

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <math.h>
#include <psb_reg.h>
#include "xf86.h"
#include "i810_reg.h"
#include "psb_driver.h"
#include "xf86Modes.h"
#include "psb_lvds.h"

#include "libmm/mm_defines.h"
#include "libmm/mm_interface.h"
#include "xf86mm.h"
#include "xf86drm.h"
#include "xf86Crtc.h"
#include <assert.h>
#include <math.h>
#ifndef PI
#define PI                      3.1415926535897932384626433832795028841971f
#endif

/* Static functions, available for ILVDS downscale method of using overlay plane*/
/* downscale calculations use floating point math!*/
void PBDCOverlay_SetRegisters(float *fCoeff, uint16_t wMantSize, POV_COEFF pCoeff, uint16_t wPosition)
{
	uint16_t    maxVal, wCoeff, wRes;
	uint16_t    sign;
	float   coeff;

	sign = 0;
	maxVal = 1 << wMantSize;
	coeff = *fCoeff;
	if (coeff < 0) {
		sign = 1;
		coeff = - coeff;
	}

	wRes = 12 - wMantSize;

	if ( (wCoeff = (uint16_t)(coeff * 4 * maxVal + 0.5f)) < maxVal ) {
		pCoeff[wPosition].exponent = 3;
		pCoeff[wPosition].mantissa = wCoeff << wRes;
		*fCoeff = (float)wCoeff/(float)(4 * maxVal);
	} else if ( (wCoeff = (uint16_t)(coeff * 2 * maxVal + 0.5f)) < maxVal ) {
		pCoeff[wPosition].exponent = 2;
		pCoeff[wPosition].mantissa = wCoeff << wRes;
		*fCoeff = (float)wCoeff/(float)(2 * maxVal);
	} else if ( (wCoeff = (uint16_t)(coeff * maxVal + 0.5f)) < maxVal ) {
		pCoeff[wPosition].exponent = 1;
		pCoeff[wPosition].mantissa = (uint16_t)wCoeff << wRes;
		*fCoeff = (float)wCoeff/(float)maxVal;
	} else if ( (wCoeff = (uint16_t)(coeff * maxVal * 0.5f + 0.5f)) < maxVal ) {
		pCoeff[wPosition].exponent = 0;
		pCoeff[wPosition].mantissa = wCoeff << wRes;
		*fCoeff = (float)wCoeff/(float)(maxVal >> 1);
	} else {
		assert(0);  /*Coeff out of range!*/
	}

	pCoeff[wPosition].sign = sign;

	if (sign)
		*fCoeff = -(*fCoeff);
}

void PBDCOverlay_UpdateCoeff(uint16_t wTaps, float fCutoff, bool bHor, bool bY, POV_COEFF pCoeff)
{
	uint16_t    i, j, j1, num, pos, wMantSize;
	bool    bVandC;
	float   val, sinc, window, sum;
	float   fCoeff[5*32], ffCoeff[17][5];
	float   fDiff;
	uint16_t    wTapAdjust[5], wTap2Fix;

	if (wTaps == 2) {
		for (i = 0; i < 17; i++) {
			for (j = 0; j < 3; j++) {
				pos = j + i * 3;
				pCoeff[pos].exponent = 0;
				pCoeff[pos].mantissa = 0;
				pCoeff[pos].sign = 0;
			}
		}
		return;
	}

	if (bHor) /*H Scale*/
		wMantSize = 7;
	else
		wMantSize = 6;

	bVandC = (!bHor) & (!bY); /*vertal & Chroma*/

	num = wTaps * 16;
	for (i = 0; i < num*2; i++) {
		val = (1.0f/fCutoff) * wTaps * PI * (i - num)/(2 * num);
		if ( val == 0.0f )
			sinc = 1.0f;
		else
			sinc = (float)sin(val)/val;
		/* hanning window */
		window = (0.5f - 0.5f * (float)cos(i * PI/num));

		fCoeff[i] = sinc * window;
	}

	for (i = 0; i < 17; i++) {
		/* normalize the coefficient */
		sum = 0.0;
		for (j = 0; j < wTaps; j++) {
			pos = i + j * 32;
			sum += fCoeff[pos];
		}
		for (j = 0; j < wTaps; j++) {
			pos = i + j * 32;
			ffCoeff[i][j] = fCoeff[pos]/sum;
		}

		/* set the coefficient registers and get the data in floating point format */
		for (j = 0; j < wTaps; j++) {
			pos = j + i * wTaps;
			if ( (j == (wTaps - 1)/2) && (!bVandC) )
				PBDCOverlay_SetRegisters(&ffCoeff[i][j], (uint16_t)(wMantSize + 2), pCoeff, pos);
			else
				PBDCOverlay_SetRegisters(&ffCoeff[i][j], wMantSize, pCoeff, pos);
		}

		wTapAdjust[0] = (wTaps - 1)/2;
		for (j = 1, j1 = 1; j <= wTapAdjust[0]; j++, j1++) {
			wTapAdjust[j1] = wTapAdjust[0] - j;
			wTapAdjust[++j1] = wTapAdjust[0] + j;
		}

		/* adjust the coefficient */
		sum = 0.0;
		for (j = 0; j < wTaps; j++)
			sum += ffCoeff[i][j];

		if (sum != 1.0) {
			for (j1 = 0; j1 < wTaps; j1++) {
				wTap2Fix = wTapAdjust[j1];
				fDiff = 1.0f - sum;
				ffCoeff[i][wTap2Fix] += fDiff;
				pos = wTap2Fix + i * wTaps;
				if ( (wTap2Fix == (wTaps - 1)/2) && (!bVandC) )
					PBDCOverlay_SetRegisters(&ffCoeff[i][wTap2Fix], (uint16_t)(wMantSize + 2), pCoeff, pos);
				else
					PBDCOverlay_SetRegisters(&ffCoeff[i][wTap2Fix], wMantSize, pCoeff, pos);

				sum = 0.0f;
				for (j = 0; j < wTaps; j++)
					sum += ffCoeff[i][j];
				if (sum == 1.0f)
					break;
			}
		}
	}
}

void PBDCOverlay_SetOverlayCoefficients(POVERLAY_REGS pOverlayRegisters)
{
	uint16_t        wVTaps;
	float       fHYScale, fHUVScale, fVYScale, fVUVScale;
	uint32_t       dwHFYScale;
	/*    PVOID       pFloatStateBuf = NULL;*/

	uint32_t dwSrcW = pOverlayRegisters->SrcWidth.Y_Width;
	uint32_t dwSrcH = pOverlayRegisters->SrcHeight.Y_Height;
	uint32_t dwDstW = pOverlayRegisters->DestSize.Width;
	uint32_t dwDstH = pOverlayRegisters->DestSize.Height;

        wVTaps = 2;

	/*Save Floating point HW state before floating point operation and restore it after.*/
#if 0
	if  (!SaveFloatingPointState(&pFloatStateBuf))
		{
			DPF((DBG_CRITICAL,  "SetOverlayCoefficients: Error saving floating point state!\n"));
			DBG_ASSERT(FALSE);
		}
#endif
	/* Horizontal Y coefficients*/
	/* assume (DstW < SrcW)*/
	{
		dwHFYScale = ((pOverlayRegisters->FHDScale) >> 16) & 0x1f;
		fHYScale   = ((float)(dwSrcW >> dwHFYScale) / (float)dwDstW);
		if (fHYScale > 3.0f)
			{
				fHYScale = 3.0f; /*clamped to 3.0*/
			}
	}

	/* Vertical Y coefficients*/
	fVYScale = 1.0;

	/* UV coefficients*/
	fHUVScale = fHYScale;
	fVUVScale = fVYScale;

	PBDCOverlay_UpdateCoeff(5, fHYScale, 1, 1, pOverlayRegisters->HYCoeff);
	PBDCOverlay_UpdateCoeff(wVTaps, fVYScale, 0, 1, pOverlayRegisters->VYCoeff);
	PBDCOverlay_UpdateCoeff(3, fHUVScale, 1, 0, pOverlayRegisters->HUVCoeff);
	PBDCOverlay_UpdateCoeff(wVTaps, fVUVScale, 0, 0, pOverlayRegisters->VUVCoeff);

#if 0
	RestoreFloatingPointState(&pFloatStateBuf);
#endif

}

/********************************************************************
METHOD    : FractionToDword()
PURPOSE   : Convert fraction to Dword
ARGUMENTS : d, a double precision fraction 0 <= value < 1
            numbits, the number of bits to put in the fraction
RETURN    : ulResult, an numbits-bit representation of the fraction
*********************************************************************/
uint32_t FractionToDword(double d, int numbits)
{
        uint32_t ulResult;
        uint64_t mask;
        union Union_DoubleBitPattern {
                uint64_t ulBits;
                double dDouble;
        } Pattern;

        Pattern.dDouble = d + 1.0;

        mask = (1<<(numbits+1))-1;
        mask <<= (52-numbits-1);

        ulResult = (uint32_t)((Pattern.ulBits & mask) >> (52-numbits-1));
        ulResult += ulResult & 0x1;
        ulResult = ulResult >> 1;
        return ulResult;
}

static OVERLAY_REGS overlay_reglist;

void psb_overlay_setup_reglist(xf86CrtcPtr crtc, POVERLAY_REGS reglist, int turnon, uint16_t usSrcWidth, uint16_t usSrcHeight, uint16_t usDestWidth, uint16_t usDestHeight)
{
	PsbCrtcPrivatePtr pCrtc = psbCrtcPrivate(crtc);
	ScrnInfoPtr pScrn = crtc->scrn;
	PsbPtr pPsb = psbPTR(pScrn);
	/* this pDevice referenced by PSB_READ32() */
	PsbDevicePtr pDevice = psbDevicePTR(psbPTR(pScrn));

	/* we only support LVDS now */
	int dspcntr_reg =  DSPBCNTR;
	int dspbase_reg =  DSPBBASE;
	int pipeconf_reg = PIPEBCONF;
	int dspstride_reg =  DSPBSTRIDE;
	int dspsize_reg =  DSPBSIZE;

	CARD32 temp;
	int ret;
	int i;

	memset(reglist , 0, sizeof(OVERLAY_REGS)); /* clear reg list*/

	/* we only support LVDS now */
	reglist->Buffer0YPtr = PSB_READ32(dspbase_reg);

	reglist->Stride.Y_Stride = PSB_READ32(dspstride_reg);

	/* XXX possibly the position should be (0,0), or should be
	   read from crtc */
	/* reglist->DestPosition.Left = (uint16_t)(1024-640)/2; */
	/* reglist->DestPosition.Top = (uint16_t)(768-480)/2; */

	reglist->DestSize.Width = usDestWidth; /* DWINSZ*/
	reglist->DestSize.Height = usDestHeight; /* DWIMSZ*/

	reglist->SrcWidth.Y_Width = usSrcWidth; /* SWIDTH*/
	reglist->SrcSWORDWidth.Y_Width = (uint16_t)
		(((((	reglist->Buffer0YPtr +
			(reglist->SrcWidth.Y_Width * 32/8)	+ /* 32bpp = 4Bpp*/
			0x3F) >> 6) - (reglist->Buffer0YPtr >> 6)) << 1) - 1) << 2;
	reglist->SrcHeight.Y_Height = usSrcHeight; /* SHEIGHT*/

	double fRatio = (double)usSrcHeight/(double)usDestHeight;
	uint16_t usScaleFraction = (uint16_t)FractionToDword(fRatio - (int)fRatio, 12);
	reglist->YRGBScale =  usScaleFraction << 20; /* YRGB_VFRACT*/
	reglist->YRGBScale |= (usSrcWidth/usDestWidth) << 16; /* YRGB_HINT*/

	fRatio = (double)usSrcWidth/(double)usDestWidth;
	usScaleFraction = (uint16_t)FractionToDword(fRatio - (int)fRatio, 12);
	reglist->YRGBScale |= usScaleFraction << 3; /* YRGB_HFRACT*/

	/* UV scales the same as Y (and seems to be required even for
	   RGB surface) */
	reglist->UV_Scale = reglist->YRGBScale;
	reglist->VDScale = (usSrcHeight/usDestHeight) << 16; /* YRGB_VINT*/
	reglist->VDScale |= (usSrcHeight/usDestHeight); /* UV_VINT (B-Spec says not used for packed formats, but doesn't hurt*/

	reglist->CCorrection0 = (1<<6) << 18; /* OCLRC0 - Normal Contract (3.6 format) & Brightness*/
	reglist->CCorrection1 = 1<<7; /* OCLRC1 - Normal Contract & Brightness (3.7 format)*/

#if 0 /* alpha it over desktop (for test alpha'd w/ PlaneA)*/
	reglist->DestCMask = 1<<30; /* Constant Alpha On*/
	reglist->SrcCMask = 0xE0; /* const Alpha ~12%*/
#endif

	reglist->Command = (1 << 10); /* RGB 8:8:8 format*/

	reglist->Config |= (1 << 4); /* Disable YUV2RGB (not needed, so might as well not use it)*/
	reglist->Config |= (1 << 16); /* Use Pipe's Gamma (not just Overlay's)*/

	PBDCOverlay_SetOverlayCoefficients(reglist);

	/* direct the output to pipe B */
	reglist->Config |= (1 << 18);

	if (turnon)
		reglist->Command |= 1; /* Enable Overlay */
	else
		reglist->Command &= ~1; /* Disable Overlay */

	return;
}

void psb_overlay_write_reglist(xf86CrtcPtr crtc, POVERLAY_REGS reglist, int turnon)
{
	unsigned long offset;
	unsigned long buf_addr, buf_offset;
	CARD32 buf_user_start;
	unsigned long buf_virtual;
	unsigned long buf_size;

	PsbCrtcPrivatePtr pCrtc = psbCrtcPrivate(crtc);
	ScrnInfoPtr pScrn = crtc->scrn;
	PsbPtr pPsb = psbPTR(pScrn);
	PsbDevicePtr pDevice = psbDevicePTR(psbPTR(pScrn));
	MMManager *man = pDevice->man;
	struct _MMBuffer* buf;

	int ret;

	buf = man->createBuf(man, sizeof(OVERLAY_REGS), 0,
			     MM_FLAG_READ | MM_FLAG_MEM_VRAM |
			     MM_FLAG_NO_EVICT | MM_FLAG_MAPPABLE,
			     MM_HINT_DONT_FENCE);

	if (!buf) {
		over_msg( "Error: create buf failed\n");
		return;
	}

	ret = man->mapBuf(buf, MM_FLAG_READ | MM_FLAG_WRITE, 0);
	if (ret) {
		over_msg( "Error: mapBuf failed!\n");
		goto out_err;
	}
	/* XXX should unMap later? */
	man->unMapBuf(buf);

	/*  OVADD wants the offset relative to the aperture start. */
	offset = mmBufOffset(buf) & 0x0FFFFFFF;
	buf_addr = pDevice->stolenBase + offset;

	/* the userspace visible virtual address */
	buf_virtual = man->bufVirtual(buf);
	buf_size = man->bufSize(buf);

	if (turnon) {
		/* set the chicken bit */
		PSB_WRITE32(0x70400, PSB_READ32(0x70400) | 1<<30);
	}

	/* Tell DC Hardware to read in overlay reg list*/
	memcpy(buf_virtual, reglist, sizeof(OVERLAY_REGS));
	PSB_WRITE32(OVADD,  buf_addr | BIT0); //XXX why | BIT0?

	if (!turnon) {
		PSB_WRITE32(0x70400, PSB_READ32(0x70400) & ~(1<<30)); /* unset the chicken bit */
	}

	return;

 out_err:
	man->destroyBuf(buf);
	return;
}

/* This function handles the sophisticated decision making process on
   when to turn on/off the overlay plane, and then call proper
   functions to execute */
void psb_dpms_overlay(xf86CrtcPtr crtc, int turnon)
{
	PsbCrtcPrivatePtr pCrtc = psbCrtcPrivate(crtc);
	ScrnInfoPtr pScrn = crtc->scrn;
	PsbPtr pPsb = psbPTR(pScrn);
	PsbDevicePtr pDevice = psbDevicePTR(psbPTR(pScrn));
	xf86CrtcConfigPtr xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
	int pipe = pCrtc->pipe;

	uint16_t usSrcWidth;
	uint16_t usSrcHeight;
	uint16_t usDestWidth;
	uint16_t usDestHeight;

	int ret;
	uint32_t temp;
	int i;

	int overlay_on;

	/* to detect if the overlay plane is on or off */
	overlay_on = PSB_READ32(OVADD+0x168) & 1;

	/* figure out the LVDS physical resolution limit, i.e. the
	   overlay plane destination mode */
	/* XXX better to do this in LVDS initialize phase */
	for (i = 0; i < xf86_config->num_output; i++) {
	    xf86OutputPtr output = xf86_config->output[i];
	    PsbLVDSOutputPtr pLVDS = NULL;
	    DisplayModePtr pFixedMode = NULL;
	    pLVDS = containerOf(output->driver_private, PsbLVDSOutputRec, psbOutput);

	    if (pLVDS->psbOutput.type != PSB_OUTPUT_LVDS)
		continue;

	    pFixedMode = pLVDS->panelFixedMode;

	    /* Overlay plane only supports source smaller than
	       1024x768, therefore the destination should also smaller
	       than 1024x768 */
	    if (pFixedMode->HDisplay > 1024 || pFixedMode->VDisplay > 768) {
		    /* We should not just set destination resolution
		       as 1024x768, otherwise the overlay plane out
		       put will be mixed with the plane B output,
		       which is larger than 1024x768 and can not be
		       covered. */
		    /*In this case, actually the overlay plane should
		       never ever be turned on, so we don't need to
		       worry about turnning it off here. It's ok to
		       just return */
		    return;
	    } else {
		    usDestWidth = pFixedMode->HDisplay;
		    usDestHeight = pFixedMode->VDisplay;
	    }
	}

	/* figure out the source plane resolution, i.e. the source
	   buffer resolution */
	temp = PSB_READ32(DSPBSIZE);
	usSrcWidth = (uint16_t) ( temp & 0xffff);
	usSrcHeight = (uint16_t) (temp >> 16) & 0xffff;

	/* being called when SDVO is updating its stride */
	if (pipe == 0) {
		/* should update the stride */
		if (overlay_on)
			goto out_update;
		else
			return;
	}

	/* should not turn on/off if is already on/off */
	/* XXX what if Dpms forgets to turn the overlay plane off when
	   exiting the xserver, and forgets to turn it off when
	   entering the xserver? */
	if (turnon && overlay_on) {
		/* overlay plane is already turned on, don't do it
		   twice */
		return;
	} else if (!turnon && !overlay_on) {
		/* overlay plane is already turnon off, don't do it
		   twice */
		return;
	}

	if (!turnon)
		goto out_turnoff;

        /* shouldn't use overlay unless we need to downscale*/
	if (!(usSrcWidth > usDestWidth || usSrcHeight > usDestHeight)) {
		/* the LVDS mode will be set to equal or smaller than
		   the physical limite, in this case, we should
		   disable the overlay plane */
		if (overlay_on)
			goto out_turnoff;
		else
			return;
	}

 out_turnon:
 out_update:

	psb_overlay_setup_reglist(crtc, &overlay_reglist, TRUE,
				  usSrcWidth, usSrcHeight, usDestWidth, usDestHeight);
	psb_overlay_write_reglist(crtc, &overlay_reglist, TRUE);

	pCrtc->downscale = 1;
	pCrtc->scale_x = 1.0 * usSrcWidth / usDestWidth;
	pCrtc->scale_y = 1.0 * usSrcHeight / usDestHeight;

	return;

 out_turnoff:

	psb_overlay_setup_reglist(crtc, &overlay_reglist, FALSE,
				  usSrcWidth, usSrcHeight, usDestWidth, usDestHeight);
	psb_overlay_write_reglist(crtc, &overlay_reglist, FALSE);

	pCrtc->downscale = 0;
	pCrtc->scale_x = 1;
	pCrtc->scale_y = 1;

	return;
}


text:
module Note.Era where
import Control.Applicative hiding ( (<|>) )
import Control.DateTime.Absolute
import Data.Body ( event )
import Data.Utils
import Internal
import Note ( Note(..), Basic, parseBasic, prefixes, suffixes )
import Text.ParserCombinators.Parsec ( GenParser )
import Text.Utils
import qualified Control.Modifier as Mods

newtype Era = Era { base :: Basic } deriving (Eq, Ord, Show)
instance Note Era where basic = base

code :: Era -> String
code e = headOr (show e) (prefixes e)

codes :: Era -> [String]
codes = map slugify . prefixes

precodes :: Era -> [String]
precodes = map slugify . suffixes

instance Momented Era where
    when side e = case event "dawn" $ body e of
        Just ev -> when side ev
        Nothing -> pure Present

parseEra :: Int -> GenParser Char st Era
parseEra i = Era <$> parseBasic i Mods.anyMod


text:
const SourceNode = require('source-map').SourceNode;

const lineMatcher = /\n/gm;
const varMatcher = /\$({([\d]+)}|[\d]+)/gm;

// Handle a position in a file
function Position(file, line, column) {
  this.file = file;
  this.line = line || 1;
  this.column = column || 0;
}

// Advance in the file to move the cursor after content
Position.prototype.forward = function (content) {
  const lines = content.split(lineMatcher);

  if (lines.length <= 1) {
    this.column += content.length;
  } else {
    this.line += lines.length - 1;
    this.column = lines[lines.length - 1].length;
  }

  return this;
};

// Add content to a node (needs to be added line per line)
Position.prototype.add = function (node, content, autoForward = true) {
  const pos = autoForward ? this : new Position(this.file, this.line, this.column);

  let sub;

  let lastIndex = 0;
  lineMatcher.lastIndex = 0;
  while (lineMatcher.exec(content)) {
    sub = content.substring(lastIndex, lineMatcher.lastIndex);
    node.add(new SourceNode(pos.line, pos.column, pos.file, sub));
    pos.forward(sub);
    lastIndex = lineMatcher.lastIndex;
  }

  if (lastIndex < content.length) {
    sub = content.substring(lastIndex);
    node.add(new SourceNode(pos.line, pos.column, pos.file, sub));
    pos.forward(sub);
  }

  return this;
};

// Regexp replacer with sourcemap support
// eslint-disable-next-line
const Replacer = module.exports = function Replacer(regexp, replace, regexpName) {
  // Handle params
  if (typeof replace !== 'string') {
    if (typeof replace !== 'function') {
      throw new Error('replace parameter must be of type "string" or "function"');
    }
    if (typeof replace() !== 'string') {
      throw new Error('replace function must return a "string"');
    }
  }

  this.$regexp = regexp;
  this.$replace = replace;
  this.$regexpName = !regexpName ? null : `regexp/${regexpName}`;
};

// Create a replace node depending on the current pos & match
Replacer.prototype.createReplaceNode = function (pos, match) {
  const node = new SourceNode();
  let varMatch;
  const replacePos = new Position(this.$regexpName);
  const $replace = typeof this.$replace === 'function'
      ? this.$replace()
      : this.$replace;

  let lastIndex = 0;
  varMatcher.lastIndex = 0;
  // eslint-disable-next-line
  while ((varMatch = varMatcher.exec($replace))) {
    const parValue = match[varMatch[2] || varMatch[1]];
    if (varMatch.index > lastIndex) {
      replacePos.add(node, $replace.substring(lastIndex, varMatch.index));
    }

    pos.add(node, parValue, false);
    lastIndex = varMatcher.lastIndex;
  }
  if (lastIndex < $replace.length) {
    replacePos.add(node, $replace.substring(lastIndex));
  }

  return node;
};

// Replace the provided content
Replacer.prototype.replace = function (content, file = 'content') {
  const filePos = new Position(file);

  let match;
  // Create the base node & add sources
  const node = new SourceNode();
  node.setSourceContent(file, content);
  if (this.$regexpName) {
    node.setSourceContent(this.$regexpName, this.$replace);
  }

  let lastIndex = 0;
  this.$regexp.lastIndex = 0;

  // eslint-disable-next-line
  while ((match = this.$regexp.exec(content))) {
    if (match.index > lastIndex) {
      filePos.add(node, content.substring(lastIndex, match.index));
    }

    node.add(this.createReplaceNode(filePos, match));
    filePos.forward(match[0]);

    // Move
    lastIndex = this.$regexp.lastIndex || match.index + match[0].length;

    // Handle empty match
    if (!match[0].length) {
      ++this.$regexp.lastIndex;
    }

    // Handle global flag
    if (!this.$regexp.global) break;
  }

  if (lastIndex < content.length) {
    filePos.add(node, content.substring(lastIndex));
  }

  const res = node.toStringWithSourceMap({ file });
  res.map = res.map.toJSON();
  return res;
};


text:
package com.ifeng.servicesimpl;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ifeng.entitys.DmsDocument;
import com.ifeng.entitys.DmsDocumentExample;
import com.ifeng.mappers.DmsDocumentMapper;
import com.ifeng.services.DocumentService;
import com.ifeng.utils.Page;

@Service
public class DocumentServiceImpl implements DocumentService{
	@Autowired
	DmsDocumentMapper documentMapper;
	@Override
	public boolean addDocument(DmsDocument user) {
		// TODO Auto-generated method stub

		int result = documentMapper.insertSelective(user);

		if(result==1){
			return true;
		}
		else{
			return false;
		}
	}

	@Override
	public ArrayList<DmsDocument> showDocumentAll(Page page,String keyword) {
		// TODO Auto-generated method stub

		DmsDocumentExample example=new DmsDocumentExample();
		example.setLimit(page.getPageSize());//设置分页
		example.setStart(page.getStart(page.getPageNo()));
		DmsDocumentExample.Criteria criteria = example.createCriteria();
		return (ArrayList<DmsDocument>) documentMapper.selectByExample(example);
	}

	@Override
	public DmsDocument showDocument(String documentNo) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean deleteDocument(String documentName) {
		// TODO Auto-generated method stub
		DmsDocumentExample example=new DmsDocumentExample();
		DmsDocumentExample.Criteria criteria = example.createCriteria();
		criteria.andDocumentNameEqualTo(documentName);
		int result = documentMapper.deleteByExample(example);
		if(result==1){
			return true;
		}
		else{
			return false;
		}
	}

	@Override
	public long showDocumentNameCount(String keyWords) {
		// TODO Auto-generated method stub
		long count=0;
		DmsDocumentExample example=new DmsDocumentExample();
		DmsDocumentExample.Criteria criteria = example.createCriteria();
		criteria.andDocumentNameLike(keyWords);
		count = documentMapper.countByExample(example);
		example=new DmsDocumentExample();
		criteria = example.createCriteria();
		criteria.andAuthorNameLike(keyWords);
		count+=documentMapper.countByExample(example);
		System.out.println("数量:"+count);
		return count;
	}

	@Override
	public long showAuthorNameCount(String keyWords) {
		// TODO Auto-generated method stub
		DmsDocumentExample example=new DmsDocumentExample();
		DmsDocumentExample.Criteria criteria = example.createCriteria();
		criteria.andAuthorNameLike(keyWords);
		return documentMapper.countByExample(example);
	}

	@Override
	public ArrayList<DmsDocument> showDocumentNameDocument(Page page, String keyword) {
		// TODO Auto-generated method stub

		if(page==null){
			DmsDocumentExample example=new DmsDocumentExample();
			DmsDocumentExample.Criteria criteria = example.createCriteria();
			criteria.andDocumentNameLike(keyword);
			return (ArrayList<DmsDocument>) documentMapper.selectByExample(example);
		}
		ArrayList<DmsDocument> list;
		ArrayList<DmsDocument> list1;
		DmsDocumentExample example = new DmsDocumentExample();
		DmsDocumentExample.Criteria criteria = example.createCriteria();
		criteria.andDocumentNameLike(keyword);
		list=(ArrayList<DmsDocument>) documentMapper.selectByExample(example);
		example = new DmsDocumentExample();
		criteria = example.createCriteria();
		criteria.andAuthorNameLike(keyword);
		list1=(ArrayList<DmsDocument>) documentMapper.selectByExample(example);
		list.addAll(list1);
		return list;
	}

	@Override
	public long showCount(String keyWords) {
		// TODO Auto-generated method stub
		DmsDocumentExample example=new DmsDocumentExample();
		DmsDocumentExample.Criteria criteria = example.createCriteria();
		return documentMapper.countByExample(example);
	}

	@Override
	public boolean updateDocument(String documentSn,DmsDocument dmsDocument) {
		// TODO Auto-generated method stub
		DmsDocumentExample example=new DmsDocumentExample();
		DmsDocumentExample.Criteria criteria = example.createCriteria();
		criteria.andDocumentSnEqualTo(documentSn);
		int result=documentMapper.updateByExampleSelective(dmsDocument, example);
		if(result==1){
			return true;
		}
		else{
			return false;
		}
	}

}


text:
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="simple_search_padding_left">40dp</dimen>
</resources>


text:
license: Licensed to the Apache Software Foundation (ASF) under one
         or more contributor license agreements.  See the NOTICE file
         distributed with this work for additional information
         regarding copyright ownership.  The ASF licenses this file
         to you under the Apache License, Version 2.0 (the
         "License"); you may not use this file except in compliance
         with the License.  You may obtain a copy of the License at

           http://www.apache.org/licenses/LICENSE-2.0

         Unless required by applicable law or agreed to in writing,
         software distributed under the License is distributed on an
         "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
         KIND, either express or implied.  See the License for the
         specific language governing permissions and limitations
         under the License.
---

Developing a Plugin on Bada
===========================

プラグインは Bada 2.0 以上のみサポートしています。 Bada 1.2 はサポートしていません。

Bada の実装はすべて JavaScript の実装です。そのため、カスタムプラグインを追加することは、プラグインコードによって CordovaJS を更新することになります。以下は、シンプルな _Hello World_ プラグインを追加するステップです:

1. CordovaJS リポジトリーを clone します

        git clone https://git-wip-us.apache.org/repos/asf/incubuator-cordova-js.git

2. __lib/bada/plugin/bada/__ 以下に新しい JavaScript ファイルを作成し、 _HelloWorld.js_ と名前をつけます。以下の内容を追加します:

        function HelloWorld() {
        }

        HelloWorld.prototype.printHello = function(success, fail, arg) {
            alert(Osp.Core.StringHelper('Hello %1', arg[0]));
        }

        module.exports = new HelloWorld();

3. __lib/bada/platform.js__ の objects プロパティーの下に、新しく作ったプラグインへのリンクを追加します:

        objects: {
            ...
            HelloWorld: {
                'cordova/plugin/bada/HelloWorld'
            },
            ...
        }
        ...
4. __lib/bada/exec.js__ のプラグインリストを、作ったプラグインを含むように更新します

        var plugins = {
            ...
            "HelloWorld": require('cordova/plugin/bada/HelloWorld')
        };
5. これで、好きなようにユーザー向けの JavaScript を書くことができます。しかし、プラグインを実行するためには、以下のメソッドを呼び出す必要があることを忘れないで下さい

        exec(succes, fail, 'HelloWorld', 'printHello', ['Jackson!']);

    success はプラグインが正常に終了したときに実行される成功コールバック関数です
    fail はプラグインが正常に終了しなかったときに実行されるエラーコールバック関数です
    'HelloWorld' はあなたのプラグインの名前です
    'printHello' はあなたのプラグインのアクション名です
    最後のパラメーターは、プラグインへの引数です

6. 以下のコマンドを実行し、新しい共通 JavaScript を生成します (npm モジュールの jake がインストールされていることを確認して下さい)

        jake

7. 新しく生成された __pkg/cordova.bada.js__ を、 Bada プロジェクトの __Res/js__ 以下にコピーします

6. 以上です!これで、あなたは新しい Bada プラグインを追加することができ、現在は Cordova Bada でサポートされていないたくさんの機能を実装できるようになりました。


text:
/**
 * This file is generated by tifstoc. Do not edit!
 * Generated from tifs for tool 'lower-rstore' (prefix='')
 */

#ifndef _LOWER_RSTORE_H
#define _LOWER_RSTORE_H

#include <atb-tool.h>

/* Prototypes for functions called from the event handler */
void rec_terminate(int conn, ATerm);
ATerm lower_rstore(int conn, ATerm);
extern ATerm lower_rstore_handler(int conn, ATerm term);
extern ATerm lower_rstore_checker(int conn, ATerm sigs);

#endif


text:
<?php

namespace Symfony\Contracts\EventDispatcher;

use Psr\EventDispatcher\EventDispatcherInterface as PsrEventDispatcherInterface;

/**
 * Allows providing hooks on domain-specific lifecycles by dispatching events.
 */
interface EventDispatcherInterface extends PsrEventDispatcherInterface
{
    /**
     * Dispatches an event to all registered listeners.
     *
     * For BC with Symfony 4, the $eventName argument is not declared explicitly on the
     * signature of the method. Implementations that are not bound by this BC constraint
     * MUST declare it explicitly, as allowed by PHP.
     *
     * @param object      $event     The event to pass to the event handlers/listeners
     * @param string|null $eventName The name of the event to dispatch. If not supplied,
     *                               the class of $event should be used instead.
     *
     * @return object The passed $event MUST be returned
     */
    public function dispatch($event/*, string $eventName = null*/);
}


text:
<!DOCTYPE html>

  <title> Gulp with Foundation and SASS</title>
  <link href="css/main.css" rel="stylesheet" type="text/css">

      Welcome to the bestest, Simplest, Prototype ever!!!
      Gulp, double Gulp

    <canvas id="canvas" width="150" height="150"></canvas>


text:
"""Node Server Example

This example demonstrates how to create a very simple node server
that supports bi-diractional messaging between server and connected
clients forming a cluster of nodes.
"""

from __future__ import print_function

from os import getpid
from optparse import OptionParser

from circuits.node import Node
from circuits import Component, Debugger

__version__ = "0.0.1"

USAGE = "%prog [options]"
VERSION = "%prog v" + __version__

def parse_options():
    parser = OptionParser(usage=USAGE, version=VERSION)

    parser.add_option(
        "-b", "--bind",
        action="store", type="string",
        default="0.0.0.0:8000", dest="bind",
        help="Bind to address:[port]"
    )

    parser.add_option(
        "-d", "--debug",
        action="store_true",
        default=False, dest="debug",
        help="Enable debug mode"
    )

    opts, args = parser.parse_args()

    return opts, args

class NodeServer(Component):

    def init(self, args, opts):
        """Initialize our ``ChatServer`` Component.

        This uses the convenience ``init`` method which is called after the
        component is proeprly constructed and initialized and passed the
        same args and kwargs that were passed during construction.
        """

        self.args = args
        self.opts = opts

        self.clients = {}

        if opts.debug:
            Debugger().register(self)

        if ":" in opts.bind:
            address, port = opts.bind.split(":")
            port = int(port)
        else:
            address, port = opts.bind, 8000

        Node(port=port, server_ip=address).register(self)

    def connect(self, sock, host, port):
        """Connect Event -- Triggered for new connecting clients"""

        self.clients[sock] = {
            "host": sock,
            "port": port,
        }

    def disconnect(self, sock):
        """Disconnect Event -- Triggered for disconnecting clients"""

        if sock not in self.clients:
            return

        del self.clients[sock]

    def ready(self, server, bind):
        print("Ready! Listening on {}:{}".format(*bind))
        print("Waiting for remote events...")

    def hello(self):
        return "Hello World! ({0:d})".format(getpid())

def main():
    opts, args = parse_options()

    # Configure and "run" the System.
    NodeServer(args, opts).run()

if __name__ == "__main__":
    main()


text:
require 'test_helper'

class EventChangeRegistrationPolicyServiceTest < ActiveSupport::TestCase
  include ActiveJob::TestHelper

  let(:convention) { create(:convention, :with_notification_templates) }
  let(:event) { create :event, convention: convention }
  let(:the_run) { create :run, event: event }
  let(:new_registration_policy) do
    RegistrationPolicy.new(
      buckets: [
        { key: 'dogs', slots_limited: true, total_slots: 1 },
        { key: 'cats', slots_limited: true, total_slots: 1 },
        { key: 'anything', slots_limited: true, total_slots: 1, anything: true }
      ]
    )
  end
  let(:whodunit) { create :user_con_profile, convention: convention }
  let(:team_member) { create :team_member, event: event, receive_signup_email: 'all_signups' }

  subject { EventChangeRegistrationPolicyService.new(event, new_registration_policy, whodunit) }

  before do
    the_run
    team_member
  end

  it 'changes the registration policy' do
    result = subject.call

    assert result.success?
    assert_equal new_registration_policy, event.reload.registration_policy
  end

  it 'does not email the team members if nobody moved' do
    perform_enqueued_jobs do
      subject.call!
      assert_equal 0, ActionMailer::Base.deliveries.size
    end
  end

  describe 'with existing signups in buckets that will be removed' do
    let(:user_con_profile) { create :user_con_profile, convention: convention }
    let(:signup) do
      create(
        :signup,
        user_con_profile: user_con_profile,
        requested_bucket_key: 'unlimited',
        bucket_key: 'unlimited',
        run: the_run
      )
    end

    before { signup }

    it 'moves the signup' do
      result = subject.call

      assert result.success?
      assert_equal 1, result.move_results.size
      assert_equal signup.id, result.move_results.first.signup_id
      assert_equal 'anything', result.move_results.first.bucket_key
      assert_equal 'unlimited', result.move_results.first.prev_bucket_key
      assert_equal 'confirmed', result.move_results.first.state
      assert_equal 'confirmed', result.move_results.first.prev_state
      assert_equal 'anything', signup.reload.bucket_key
    end

    it 'emails the team members' do
      perform_enqueued_jobs do
        subject.call!

        assert_equal 1, ActionMailer::Base.deliveries.size
        recipients = ActionMailer::Base.deliveries.map(&:to)
        assert_equal [[team_member.user_con_profile.email]], recipients
      end
    end
  end

  describe 'with existing signups in buckets that will shrink' do
    let(:event) do
      create(
        :event,
        convention: convention,
        registration_policy:
          RegistrationPolicy.new(
            buckets: [
              { key: 'dogs', slots_limited: true, total_slots: 2 },
              { key: 'cats', slots_limited: true, total_slots: 1 },
              { key: 'anything', slots_limited: true, total_slots: 1, anything: true }
            ]
          )
      )
    end

    let(:user_con_profile1) { create :user_con_profile, convention: convention }
    let(:user_con_profile2) { create :user_con_profile, convention: convention }

    let(:signup1) do
      create(
        :signup,
        user_con_profile: user_con_profile1,
        requested_bucket_key: 'dogs',
        bucket_key: 'dogs',
        run: the_run
      )
    end
    let(:signup2) do
      create(
        :signup,
        user_con_profile: user_con_profile2,
        requested_bucket_key: 'dogs',
        bucket_key: 'dogs',
        run: the_run
      )
    end

    before do
      signup1
      signup2
    end

    it 'moves the overflow signups' do
      result = subject.call

      assert result.success?
      assert_equal 1, result.move_results.size
      assert_equal signup2.id, result.move_results.first.signup_id
      assert_equal 'anything', result.move_results.first.bucket_key
      assert_equal 'dogs', result.move_results.first.prev_bucket_key
      assert_equal 'confirmed', result.move_results.first.state
      assert_equal 'confirmed', result.move_results.first.prev_state

      assert_equal 'dogs', signup1.reload.bucket_key
      assert_equal 'anything', signup2.reload.bucket_key
    end

    it 'emails the team members' do
      perform_enqueued_jobs do
        subject.call!

        assert_equal 1, ActionMailer::Base.deliveries.size
        recipients = ActionMailer::Base.deliveries.map(&:to)
        assert_equal [[team_member.user_con_profile.email]], recipients
      end
    end

    describe 'with no-preference signups' do
      let(:signup2) do
        create(
          :signup,
          user_con_profile: user_con_profile2,
          requested_bucket_key: nil,
          bucket_key: 'anything',
          run: the_run
        )
      end

      let(:user_con_profile3) { create :user_con_profile, convention: convention }
      let(:signup3) do
        create(
          :signup,
          user_con_profile: user_con_profile3,
          requested_bucket_key: nil,
          bucket_key: 'dogs',
          run: the_run
        )
      end

      before do
        signup1
        signup2
        signup3
      end

      it 'moves them wherever it can' do
        result = subject.call

        assert result.success?
        assert_equal 1, result.move_results.size
        assert_equal signup3.id, result.move_results.first.signup_id
        assert_equal 'cats', result.move_results.first.bucket_key
        assert_equal 'dogs', result.move_results.first.prev_bucket_key
        assert_equal 'confirmed', result.move_results.first.state
        assert_equal 'confirmed', result.move_results.first.prev_state

        assert_equal 'dogs', signup1.reload.bucket_key
        assert_equal 'anything', signup2.reload.bucket_key
        assert_equal 'cats', signup3.reload.bucket_key
      end

      it 'emails the team members' do
        perform_enqueued_jobs do
          subject.call!

          assert_equal 1, ActionMailer::Base.deliveries.size
          recipients = ActionMailer::Base.deliveries.map(&:to)
          assert_equal [[team_member.user_con_profile.email]], recipients
        end
      end
    end

    describe 'with an impossible situation' do
      let(:user_con_profile3) { create :user_con_profile, convention: convention }
      let(:signup3) do
        create(
          :signup,
          user_con_profile: user_con_profile3,
          requested_bucket_key: 'dogs',
          bucket_key: 'anything',
          run: the_run
        )
      end

      before do
        signup1
        signup2
        signup3
      end

      it 'fails' do
        result = subject.call

        assert result.failure?
        assert_match(
          /\ASignup for #{user_con_profile3.name_without_nickname} would no longer fit/,
          result.errors.full_messages.join("\n")
        )
        assert_equal 'dogs', signup1.reload.bucket_key
        assert_equal 'dogs', signup2.reload.bucket_key
        assert_equal 'anything', signup3.reload.bucket_key
        refute_equal new_registration_policy, event.reload.registration_policy
      end
    end
  end

  describe 'with existing signups in buckets that will grow' do
    let(:event) do
      create(
        :event,
        convention: convention,
        registration_policy:
          RegistrationPolicy.new(
            buckets: [
              { key: 'dogs', slots_limited: true, total_slots: 0 },
              { key: 'cats', slots_limited: true, total_slots: 1 },
              { key: 'anything', slots_limited: true, total_slots: 1, anything: true }
            ]
          )
      )
    end

    let(:user_con_profile1) { create :user_con_profile, convention: convention }
    let(:user_con_profile2) { create :user_con_profile, convention: convention }

    let(:signup1) do
      create(
        :signup,
        user_con_profile: user_con_profile1,
        requested_bucket_key: 'dogs',
        bucket_key: 'anything',
        run: the_run
      )
    end
    let(:signup2) do
      create(
        :signup,
        user_con_profile: user_con_profile2,
        state: 'waitlisted',
        requested_bucket_key: 'dogs',
        bucket_key: nil,
        run: the_run
      )
    end

    before do
      signup1
      signup2
    end

    it 'tries not to move confirmed signups' do
      result = subject.call

      assert result.success?
      assert_equal 'anything', signup1.reload.bucket_key
    end

    it 'pulls in waitlisted signups' do
      result = subject.call

      assert result.success?
      assert_equal 'dogs', signup2.reload.bucket_key
      assert_equal 'confirmed', signup2.reload.state
    end

    it 'emails the team members and the attendees who got pulled in' do
      perform_enqueued_jobs do
        subject.call!

        assert_equal 2, ActionMailer::Base.deliveries.size
        recipients = ActionMailer::Base.deliveries.map(&:to)
        assert_equal [[user_con_profile2.email], [team_member.user_con_profile.email]], recipients
      end
    end
  end
end