text:
package com.tommytony.war.structure;

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

import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Player;

import com.tommytony.war.War;
import com.tommytony.war.Warzone;
import com.tommytony.war.utility.Direction;

/**
 *
 * @author tommytony
 *
 */
public class ZoneWallGuard {
	private Player player;
	private Warzone warzone;
	private Location playerLocation;
	private BlockFace wall;
	private List<BlockState> glassified = new ArrayList<BlockState>();
	public static final Material[] glassifyBlocks = {
		Material.AIR,
		Material.WATER,
		Material.TALL_GRASS,
		Material.VINE,
		Material.LILY_PAD,
		Material.DANDELION_YELLOW,
		Material.ROSE_RED,
		Material.RED_MUSHROOM,
		Material.BROWN_MUSHROOM,
		Material.DEAD_BUSH,
		Material.SUGAR_CANE
	};

	public ZoneWallGuard(Player player, War war, Warzone warzone, BlockFace wall) {
		this.player = player;
		this.wall = wall;
		this.playerLocation = player.getLocation();
		this.warzone = warzone;
		this.activate();
	}

	private void activate() {
		List<Block> nearestWallBlocks = this.warzone.getNearestWallBlocks(this.playerLocation);

		// add wall guard blocks
		for (Block block : nearestWallBlocks) {
			this.glassify(block, this.wall);
			if (this.wall != BlockFace.UP && this.wall != BlockFace.DOWN) {
				this.glassify(block.getRelative(BlockFace.UP), this.wall);
				this.glassify(block.getRelative(BlockFace.UP, 2), this.wall);
				this.glassify(block.getRelative(BlockFace.DOWN), this.wall);
				this.glassify(block.getRelative(BlockFace.DOWN, 2), this.wall);
			}
			if (this.wall == Direction.NORTH() && this.warzone.getVolume().isNorthWallBlock(block)) {
				this.glassify(block.getRelative(Direction.EAST()), Direction.NORTH());
				this.glassify(block.getRelative(Direction.EAST()).getRelative(BlockFace.UP), Direction.NORTH());
				this.glassify(block.getRelative(Direction.EAST()).getRelative(BlockFace.DOWN), Direction.NORTH());
				this.glassify(block.getRelative(Direction.EAST(), 2), Direction.NORTH());
				this.glassify(block.getRelative(Direction.EAST(), 2).getRelative(BlockFace.UP), Direction.NORTH());
				this.glassify(block.getRelative(Direction.EAST(), 2).getRelative(BlockFace.DOWN), Direction.NORTH());
				this.glassify(block.getRelative(Direction.EAST()).getRelative(BlockFace.UP, 2), Direction.NORTH());
				this.glassify(block.getRelative(Direction.EAST()).getRelative(BlockFace.DOWN, 2), Direction.NORTH());
				this.glassify(block.getRelative(Direction.WEST()), Direction.NORTH());
				this.glassify(block.getRelative(Direction.WEST()).getRelative(BlockFace.UP), Direction.NORTH());
				this.glassify(block.getRelative(Direction.WEST()).getRelative(BlockFace.DOWN), Direction.NORTH());
				this.glassify(block.getRelative(Direction.WEST(), 2), Direction.NORTH());
				this.glassify(block.getRelative(Direction.WEST(), 2).getRelative(BlockFace.UP), Direction.NORTH());
				this.glassify(block.getRelative(Direction.WEST(), 2).getRelative(BlockFace.DOWN), Direction.NORTH());
				this.glassify(block.getRelative(Direction.WEST()).getRelative(BlockFace.UP, 2), Direction.NORTH());
				this.glassify(block.getRelative(Direction.WEST()).getRelative(BlockFace.DOWN, 2), Direction.NORTH());
			} else if (this.wall == Direction.SOUTH() && this.warzone.getVolume().isSouthWallBlock(block)) {
				this.glassify(block.getRelative(Direction.EAST()), Direction.SOUTH());
				this.glassify(block.getRelative(Direction.EAST()).getRelative(BlockFace.UP), Direction.SOUTH());
				this.glassify(block.getRelative(Direction.EAST()).getRelative(BlockFace.DOWN), Direction.SOUTH());
				this.glassify(block.getRelative(Direction.EAST(), 2), Direction.SOUTH());
				this.glassify(block.getRelative(Direction.EAST(), 2).getRelative(BlockFace.UP), Direction.SOUTH());
				this.glassify(block.getRelative(Direction.EAST(), 2).getRelative(BlockFace.DOWN), Direction.SOUTH());
				this.glassify(block.getRelative(Direction.EAST()).getRelative(BlockFace.UP, 2), Direction.SOUTH());
				this.glassify(block.getRelative(Direction.EAST()).getRelative(BlockFace.DOWN, 2), Direction.SOUTH());
				this.glassify(block.getRelative(Direction.WEST()), Direction.SOUTH());
				this.glassify(block.getRelative(Direction.WEST()).getRelative(BlockFace.UP), Direction.SOUTH());
				this.glassify(block.getRelative(Direction.WEST()).getRelative(BlockFace.DOWN), Direction.SOUTH());
				this.glassify(block.getRelative(Direction.WEST(), 2), Direction.SOUTH());
				this.glassify(block.getRelative(Direction.WEST(), 2).getRelative(BlockFace.UP), Direction.SOUTH());
				this.glassify(block.getRelative(Direction.WEST(), 2).getRelative(BlockFace.DOWN), Direction.SOUTH());
				this.glassify(block.getRelative(Direction.WEST()).getRelative(BlockFace.UP, 2), Direction.SOUTH());
				this.glassify(block.getRelative(Direction.WEST()).getRelative(BlockFace.DOWN, 2), Direction.SOUTH());
			} else if (this.wall == Direction.EAST() && this.warzone.getVolume().isEastWallBlock(block)) {
				this.glassify(block.getRelative(Direction.NORTH()), Direction.EAST());
				this.glassify(block.getRelative(Direction.NORTH()).getRelative(BlockFace.UP), Direction.EAST());
				this.glassify(block.getRelative(Direction.NORTH()).getRelative(BlockFace.DOWN), Direction.EAST());
				this.glassify(block.getRelative(Direction.NORTH(), 2), Direction.EAST());
				this.glassify(block.getRelative(Direction.NORTH(), 2).getRelative(BlockFace.UP), Direction.EAST());
				this.glassify(block.getRelative(Direction.NORTH(), 2).getRelative(BlockFace.DOWN), Direction.EAST());
				this.glassify(block.getRelative(Direction.NORTH()).getRelative(BlockFace.UP, 2), Direction.EAST());
				this.glassify(block.getRelative(Direction.NORTH()).getRelative(BlockFace.DOWN, 2), Direction.EAST());
				this.glassify(block.getRelative(Direction.SOUTH()), Direction.EAST());
				this.glassify(block.getRelative(Direction.SOUTH()).getRelative(BlockFace.UP), Direction.EAST());
				this.glassify(block.getRelative(Direction.SOUTH()).getRelative(BlockFace.DOWN), Direction.EAST());
				this.glassify(block.getRelative(Direction.SOUTH(), 2), Direction.EAST());
				this.glassify(block.getRelative(Direction.SOUTH(), 2).getRelative(BlockFace.UP), Direction.EAST());
				this.glassify(block.getRelative(Direction.SOUTH(), 2).getRelative(BlockFace.DOWN), Direction.EAST());
				this.glassify(block.getRelative(Direction.SOUTH()).getRelative(BlockFace.UP, 2), Direction.EAST());
				this.glassify(block.getRelative(Direction.SOUTH()).getRelative(BlockFace.DOWN, 2), Direction.EAST());
			} else if (this.wall == Direction.WEST() && this.warzone.getVolume().isWestWallBlock(block)) {
				this.glassify(block.getRelative(Direction.NORTH()), Direction.WEST());
				this.glassify(block.getRelative(Direction.NORTH()).getRelative(BlockFace.UP), Direction.WEST());
				this.glassify(block.getRelative(Direction.NORTH()).getRelative(BlockFace.DOWN), Direction.WEST());
				this.glassify(block.getRelative(Direction.NORTH(), 2), Direction.WEST());
				this.glassify(block.getRelative(Direction.NORTH(), 2).getRelative(BlockFace.UP), Direction.WEST());
				this.glassify(block.getRelative(Direction.NORTH(), 2).getRelative(BlockFace.DOWN), Direction.WEST());
				this.glassify(block.getRelative(Direction.NORTH()).getRelative(BlockFace.UP, 2), Direction.WEST());
				this.glassify(block.getRelative(Direction.NORTH()).getRelative(BlockFace.DOWN, 2), Direction.WEST());
				this.glassify(block.getRelative(Direction.SOUTH()), Direction.WEST());
				this.glassify(block.getRelative(Direction.SOUTH()).getRelative(BlockFace.UP), Direction.WEST());
				this.glassify(block.getRelative(Direction.SOUTH()).getRelative(BlockFace.DOWN), Direction.WEST());
				this.glassify(block.getRelative(Direction.SOUTH(), 2), Direction.WEST());
				this.glassify(block.getRelative(Direction.SOUTH(), 2).getRelative(BlockFace.UP), Direction.WEST());
				this.glassify(block.getRelative(Direction.SOUTH(), 2).getRelative(BlockFace.DOWN), Direction.WEST());
				this.glassify(block.getRelative(Direction.SOUTH()).getRelative(BlockFace.UP, 2), Direction.WEST());
				this.glassify(block.getRelative(Direction.SOUTH()).getRelative(BlockFace.DOWN, 2), Direction.WEST());
			} else if (this.wall == BlockFace.UP && this.warzone.getVolume().isUpWallBlock(block)) {
				this.glassify(block.getRelative(Direction.EAST()), BlockFace.UP);
				this.glassify(block.getRelative(Direction.EAST(), 2), BlockFace.UP);
				this.glassify(block.getRelative(Direction.WEST()), BlockFace.UP);
				this.glassify(block.getRelative(Direction.WEST(), 2), BlockFace.UP);
				this.glassify(block.getRelative(Direction.NORTH()), BlockFace.UP);
				this.glassify(block.getRelative(Direction.NORTH()).getRelative(Direction.EAST()), BlockFace.UP);
				this.glassify(block.getRelative(Direction.NORTH()).getRelative(Direction.WEST()), BlockFace.UP);
				this.glassify(block.getRelative(Direction.NORTH(), 2), BlockFace.UP);
				this.glassify(block.getRelative(Direction.NORTH(), 2).getRelative(Direction.EAST()), BlockFace.UP);
				this.glassify(block.getRelative(Direction.NORTH(), 2).getRelative(Direction.WEST()), BlockFace.UP);
				this.glassify(block.getRelative(Direction.NORTH()).getRelative(Direction.EAST(), 2), BlockFace.UP);
				this.glassify(block.getRelative(Direction.NORTH()).getRelative(Direction.WEST(), 2), BlockFace.UP);
				this.glassify(block.getRelative(Direction.SOUTH()), BlockFace.UP);
				this.glassify(block.getRelative(Direction.SOUTH()).getRelative(Direction.EAST()), BlockFace.UP);
				this.glassify(block.getRelative(Direction.SOUTH()).getRelative(Direction.WEST()), BlockFace.UP);
				this.glassify(block.getRelative(Direction.SOUTH(), 2), BlockFace.UP);
				this.glassify(block.getRelative(Direction.SOUTH(), 2).getRelative(Direction.EAST()), BlockFace.UP);
				this.glassify(block.getRelative(Direction.SOUTH(), 2).getRelative(Direction.WEST()), BlockFace.UP);
				this.glassify(block.getRelative(Direction.SOUTH()).getRelative(BlockFace.UP, 2), BlockFace.UP);
				this.glassify(block.getRelative(Direction.SOUTH()).getRelative(BlockFace.DOWN, 2), BlockFace.UP);
			} else if (this.wall == BlockFace.DOWN && this.warzone.getVolume().isDownWallBlock(block)) {
				this.glassify(block.getRelative(Direction.EAST()), BlockFace.DOWN);
				this.glassify(block.getRelative(Direction.EAST(), 2), BlockFace.DOWN);
				this.glassify(block.getRelative(Direction.WEST()), BlockFace.DOWN);
				this.glassify(block.getRelative(Direction.WEST(), 2), BlockFace.DOWN);
				this.glassify(block.getRelative(Direction.NORTH()), BlockFace.DOWN);
				this.glassify(block.getRelative(Direction.NORTH()).getRelative(Direction.EAST()), BlockFace.DOWN);
				this.glassify(block.getRelative(Direction.NORTH()).getRelative(Direction.WEST()), BlockFace.DOWN);
				this.glassify(block.getRelative(Direction.NORTH(), 2), BlockFace.DOWN);
				this.glassify(block.getRelative(Direction.NORTH(), 2).getRelative(Direction.EAST()), BlockFace.DOWN);
				this.glassify(block.getRelative(Direction.NORTH(), 2).getRelative(Direction.WEST()), BlockFace.DOWN);
				this.glassify(block.getRelative(Direction.NORTH()).getRelative(Direction.EAST(), 2), BlockFace.DOWN);
				this.glassify(block.getRelative(Direction.NORTH()).getRelative(Direction.WEST(), 2), BlockFace.DOWN);
				this.glassify(block.getRelative(Direction.SOUTH()), BlockFace.DOWN);
				this.glassify(block.getRelative(Direction.SOUTH()).getRelative(Direction.EAST()), BlockFace.DOWN);
				this.glassify(block.getRelative(Direction.SOUTH()).getRelative(Direction.WEST()), BlockFace.DOWN);
				this.glassify(block.getRelative(Direction.SOUTH(), 2), BlockFace.DOWN);
				this.glassify(block.getRelative(Direction.SOUTH(), 2).getRelative(Direction.EAST()), BlockFace.DOWN);
				this.glassify(block.getRelative(Direction.SOUTH(), 2).getRelative(Direction.WEST()), BlockFace.DOWN);
				this.glassify(block.getRelative(Direction.SOUTH()).getRelative(BlockFace.DOWN, 2), BlockFace.DOWN);
				this.glassify(block.getRelative(Direction.SOUTH()).getRelative(BlockFace.DOWN, 2), BlockFace.DOWN);
			}
		}
	}

	public static boolean shouldGlassify(Material material) {
		for (Material glassify : glassifyBlocks) {
			if (glassify == material) {
				return true;
			}
		}
		return false;
	}

	private void glassify(Block block, BlockFace wall) {
		// face here means which wall we are working on

		if (shouldGlassify(block.getType())
				&& (this.warzone.getLobby() == null || (this.warzone.getLobby() != null && !this.warzone
						.getLobby().blockIsAGateBlock(block, wall)))) {
			if (wall == Direction.NORTH()) {
				if (this.warzone.getVolume().isNorthWallBlock(block)) {
					this.glassified.add(block.getState());
					block.setType(Material.GLASS);
				}
			} else if (wall == Direction.SOUTH()) {
				if (this.warzone.getVolume().isSouthWallBlock(block)) {
					this.glassified.add(block.getState());
					block.setType(Material.GLASS);
				}
			} else if (wall == Direction.EAST()) {
				if (this.warzone.getVolume().isEastWallBlock(block)) {
					this.glassified.add(block.getState());
					block.setType(Material.GLASS);
				}
			} else if (wall == Direction.WEST()) {
				if (this.warzone.getVolume().isWestWallBlock(block)) {
					this.glassified.add(block.getState());
					block.setType(Material.GLASS);
				}
			} else if (wall == BlockFace.UP) {
				if (this.warzone.getVolume().isUpWallBlock(block)) {
					this.glassified.add(block.getState());
					block.setType(Material.GLASS);
				}
			} else if (wall == BlockFace.DOWN) {
				if (this.warzone.getVolume().isDownWallBlock(block)) {
					this.glassified.add(block.getState());
					block.setType(Material.GLASS);
				}
			}
		}
	}

	public void updatePlayerPosition(Location location) {
		if (this.warzone.isNearWall(location)) {
			this.playerLocation = location;
			this.deactivate();
			this.activate();
		}
	}

	public void deactivate() {
		for (BlockState oldBlock : this.glassified) {
			// return to original
			oldBlock.update(true);
		}
	}

	public Player getPlayer() {
		return this.player;
	}

	public BlockFace getWall() {
		return this.wall;
	}
}


text:
IF EXIST zrus.to del zrus.to

:START

IF EXIST zrus.to GOTO END
IF EXIST dijkstraheapgeomFLAT_MINEDGECONN_NEAREST1.log GOTO SKIPTESTdijkstraheapgeomFLAT_MINEDGECONN_NEAREST1
PathFinding.exe dijkstraheapgeomFLAT_MINEDGECONN_NEAREST1.txt > dijkstraheapgeomFLAT_MINEDGECONN_NEAREST1.log
:SKIPTESTdijkstraheapgeomFLAT_MINEDGECONN_NEAREST1

IF EXIST zrus.to GOTO END
IF EXIST dijkstraheapgeomFLAT_MINEDGECONN1.log GOTO SKIPTESTdijkstraheapgeomFLAT_MINEDGECONN1
PathFinding.exe dijkstraheapgeomFLAT_MINEDGECONN1.txt > dijkstraheapgeomFLAT_MINEDGECONN1.log
:SKIPTESTdijkstraheapgeomFLAT_MINEDGECONN1

IF EXIST zrus.to GOTO END
IF EXIST dijkstraheapgeomFLAT_PEREDGECONN_NEAREST1.log GOTO SKIPTESTdijkstraheapgeomFLAT_PEREDGECONN_NEAREST1
PathFinding.exe dijkstraheapgeomFLAT_PEREDGECONN_NEAREST1.txt > dijkstraheapgeomFLAT_PEREDGECONN_NEAREST1.log
:SKIPTESTdijkstraheapgeomFLAT_PEREDGECONN_NEAREST1

IF EXIST zrus.to GOTO END
IF EXIST dijkstraheapgeomFLAT_PEREDGECONN1.log GOTO SKIPTESTdijkstraheapgeomFLAT_PEREDGECONN1
PathFinding.exe dijkstraheapgeomFLAT_PEREDGECONN1.txt > dijkstraheapgeomFLAT_PEREDGECONN1.log
:SKIPTESTdijkstraheapgeomFLAT_PEREDGECONN1

IF EXIST zrus.to GOTO END
IF EXIST dijkstraheapgeomSPACE_MINEDGECONN_NEAREST1.log GOTO SKIPTESTdijkstraheapgeomSPACE_MINEDGECONN_NEAREST1
PathFinding.exe dijkstraheapgeomSPACE_MINEDGECONN_NEAREST1.txt > dijkstraheapgeomSPACE_MINEDGECONN_NEAREST1.log
:SKIPTESTdijkstraheapgeomSPACE_MINEDGECONN_NEAREST1

IF EXIST zrus.to GOTO END
IF EXIST dijkstraheapgeomSPACE_MINEDGECONN1.log GOTO SKIPTESTdijkstraheapgeomSPACE_MINEDGECONN1
PathFinding.exe dijkstraheapgeomSPACE_MINEDGECONN1.txt > dijkstraheapgeomSPACE_MINEDGECONN1.log
:SKIPTESTdijkstraheapgeomSPACE_MINEDGECONN1

IF EXIST zrus.to GOTO END
IF EXIST dijkstraheapgeomSPACE_PEREDGECONN_NEAREST1.log GOTO SKIPTESTdijkstraheapgeomSPACE_PEREDGECONN_NEAREST1
PathFinding.exe dijkstraheapgeomSPACE_PEREDGECONN_NEAREST1.txt > dijkstraheapgeomSPACE_PEREDGECONN_NEAREST1.log
:SKIPTESTdijkstraheapgeomSPACE_PEREDGECONN_NEAREST1

IF EXIST zrus.to GOTO END
IF EXIST dijkstraheapgeomSPACE_PEREDGECONN1.log GOTO SKIPTESTdijkstraheapgeomSPACE_PEREDGECONN1
PathFinding.exe dijkstraheapgeomSPACE_PEREDGECONN1.txt > dijkstraheapgeomSPACE_PEREDGECONN1.log
:SKIPTESTdijkstraheapgeomSPACE_PEREDGECONN1

:END

redpajama_set_name: RedPajamaGithub


text:
#include "stdafx.h"

#ifndef UNITTEST_NO_EXCEPTIONS

namespace UnitTest {

AssertException::AssertException()
{
}

AssertException::~AssertException() throw()
{
}

}

#endif


text:
@implementation XWAssetsViewControllerTransition

#pragma mark - UIViewControllerAnimatedTransitioning

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext
{
    return 0.35f;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{

    UIView *containerView           = [transitionContext containerView];
    containerView.backgroundColor   = [UIColor whiteColor];

    if (self.operation == UINavigationControllerOperationPush)
    {
        XWAssetsGroupViewController *fromVC      = (XWAssetsGroupViewController *)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
        XWAssetsPageViewController *toVC    = (XWAssetsPageViewController *)[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];

        UIView *cellView = nil;

        if (!toVC.isPreview) {
            NSIndexPath *indexPath              = toVC.indexPath;
            cellView        = [fromVC.pickerCollectionView cellForItemAtIndexPath:indexPath];
        }
        else {

            cellView        = fromVC.assetToolBar.previewBtn;
        }

        UIImageView *imageView  = (UIImageView *)[((UIViewController *)toVC.viewControllers[0]).view viewWithTag:1];;
        CGSize size = imageView.frame.size;

        UIView *snapshot        = [self resizedSnapshot:imageView size:size];

        CGPoint cellCenter  = [fromVC.view convertPoint:cellView.center fromView:cellView.superview];
//        cellCenter = cellView.center;
        CGPoint snapCenter  = toVC.view.center;

        // Find the scales of snapshot
        float startScale    = MAX(cellView.frame.size.width / snapshot.frame.size.width,
                                  cellView.frame.size.height / snapshot.frame.size.height);

        float endScale      = MIN(toVC.view.frame.size.width / snapshot.frame.size.width,
                                  toVC.view.frame.size.height / snapshot.frame.size.height);

        // Find the bounds of the snapshot mask
        float width         = snapshot.bounds.size.width;
        float height        = snapshot.bounds.size.height;
        float length        = MIN(width, height);

        CGRect startBounds  = CGRectMake((width-length)/2, (height-length)/2, length, length);

        // Create the mask
        UIView *mask            = [[UIView alloc] initWithFrame:startBounds];
        mask.backgroundColor    = [UIColor blackColor];

        // Prepare transition
        snapshot.transform  = CGAffineTransformMakeScale(startScale, startScale);;
        snapshot.layer.mask = mask.layer;
        snapshot.center     = cellCenter;

        toVC.view.frame     = [transitionContext finalFrameForViewController:toVC];
        toVC.view.alpha     = 0;

        // Add to container view
        [containerView addSubview:toVC.view];
        [containerView addSubview:snapshot];

        // Animate
        [UIView animateWithDuration:[self transitionDuration:transitionContext]
                              delay:0
             usingSpringWithDamping:0.75
              initialSpringVelocity:0
                            options:UIViewAnimationOptionCurveLinear
                         animations:^{
                             fromVC.view.alpha          = 0;
                             snapshot.transform         = CGAffineTransformMakeScale(endScale, endScale);
                             snapshot.layer.mask.bounds = snapshot.bounds;
                             snapshot.center            = snapCenter;
                         }
                         completion:^(BOOL finished){
                             toVC.view.alpha   = 1;
                             [snapshot removeFromSuperview];
                             [transitionContext completeTransition:YES];
                         }];
    }

    else
    {
        XWAssetsPageViewController *fromVC  = (XWAssetsPageViewController *)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
        XWAssetsGroupViewController *toVC        = (XWAssetsGroupViewController *)[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];

        UIView *cellView        = nil;

        if (!fromVC.isPreview) {
            NSIndexPath *indexPath              = fromVC.indexPath;

            // Scroll to index path
            [toVC.pickerCollectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
            [toVC.pickerCollectionView layoutIfNeeded];

            cellView        = [toVC.pickerCollectionView cellForItemAtIndexPath:indexPath];
        }
        else {
            cellView       =   toVC.assetToolBar.previewBtn;
        }

        UIImageView *imageView  = (UIImageView *)[((UIViewController *)fromVC.viewControllers[0]).view viewWithTag:1];
         CGSize size = imageView.frame.size;

        UIView *snapshot        = [self resizedSnapshot:imageView size:size];

        CGPoint cellCenter  = [toVC.view convertPoint:cellView.center fromView:cellView.superview];
        CGPoint snapCenter  = fromVC.view.center;

        // Find the scales of snapshot
        float startScale    = MIN(fromVC.view.frame.size.width / snapshot.frame.size.width,
                                  fromVC.view.frame.size.height / snapshot.frame.size.height);

        float endScale      = MAX(cellView.frame.size.width / snapshot.frame.size.width,
                                  cellView.frame.size.height / snapshot.frame.size.height);

        // Find the bounds of the snapshot mask
        float width         = snapshot.bounds.size.width;
        float height        = snapshot.bounds.size.height;
        float length        = MIN(width, height);
        CGRect endBounds    = CGRectMake((width-length)/2, (height-length)/2, length, length);

        UIView *mask            = [[UIView alloc] initWithFrame:snapshot.bounds];
        mask.backgroundColor    = [UIColor whiteColor];

        // Prepare transition
        snapshot.transform      = CGAffineTransformMakeScale(startScale, startScale);
        snapshot.layer.mask     = mask.layer;
        snapshot.center         = snapCenter;

        toVC.view.frame         = [transitionContext finalFrameForViewController:toVC];
        toVC.view.alpha         = 0;
        fromVC.view.alpha       = 0;

        // Add to container view
        [containerView addSubview:toVC.view];
        [containerView addSubview:snapshot];

        // Animate
        [UIView animateWithDuration:[self transitionDuration:transitionContext]
                              delay:0
             usingSpringWithDamping:1
              initialSpringVelocity:0
                            options:UIViewAnimationOptionCurveLinear
                         animations:^{
                             toVC.view.alpha            = 1;
                             snapshot.transform         = CGAffineTransformMakeScale(endScale, endScale);
                             snapshot.layer.mask.bounds = endBounds;
                             snapshot.center            = cellCenter;
                         }
                         completion:^(BOOL finished){
                             fromVC.view.alpha = 0;
                             [snapshot removeFromSuperview];
                             [transitionContext completeTransition:YES];
                         }];
    }
}

#pragma mark - Snapshot

- (UIView *)resizedSnapshot:(UIImageView *)imageView size:(CGSize)size
{
//    CGSize size = imageView.frame.size;

    UIGraphicsBeginImageContextWithOptions(size, YES, 0);

    [[UIColor whiteColor] set];
    UIRectFill(CGRectMake(0, 0, size.width, size.height));

    [imageView.image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *resized = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return (UIView *)[[UIImageView alloc] initWithImage:resized];
}

@end

@implementation XWAssetsViewControllerTransition2

#pragma mark - UIViewControllerAnimatedTransitioning

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext
{
    return 0.35f;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{

    UIView *containerView           = [transitionContext containerView];
    containerView.backgroundColor   = [UIColor whiteColor];

    if (self.operation == UINavigationControllerOperationPush)
    {
        XWAssetsGroupViewController *fromVC      = (XWAssetsGroupViewController *)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
        XWAssetsPikerEditViewController *toVC    = (XWAssetsPikerEditViewController *)[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];

        NSIndexPath *indexPath              = toVC.indexPath;
        UIView *cellView        = [fromVC.pickerCollectionView cellForItemAtIndexPath:indexPath];

        UIImageView *imageView  = [[toVC.view viewWithTag:100] viewWithTag:100];
        CGSize size = toVC.photoView.originalSize;

        UIView *snapshot        = [self resizedSnapshot:imageView size:size];

        CGPoint cellCenter  = [fromVC.view convertPoint:cellView.center fromView:cellView.superview];
        //        cellCenter = cellView.center;
        CGPoint snapCenter  = toVC.photoView.originalPoint;

        // Find the bounds of the snapshot mask
        float width         = snapshot.bounds.size.width;
        float height        = snapshot.bounds.size.height;
//        float length        = MIN(width, height);

        float scale_x       = width/cellView.frame.size.width;
        float scale_y       = height/cellView.frame.size.height;
        // Find the scales of snapshot
        CGRect startBounds  = [fromVC.view convertRect:cellView.frame fromView:fromVC.pickerCollectionView];
//        CGRect endBounds  = snapshot.frame;

        snapshot.center     = cellCenter;
        snapshot.frame = startBounds;

        toVC.view.frame     = [transitionContext finalFrameForViewController:toVC];
        toVC.view.alpha     = 0;

        // Add to container view
        [containerView addSubview:toVC.view];
        [containerView addSubview:snapshot];

        containerView.backgroundColor = [UIColor blackColor];

        // Animate
        [UIView animateWithDuration:[self transitionDuration:transitionContext]
                              delay:0
             usingSpringWithDamping:0.75
              initialSpringVelocity:0
                            options:UIViewAnimationOptionCurveLinear
                         animations:^{
                             fromVC.view.alpha          = 0;
                             snapshot.transform         = CGAffineTransformMakeScale(scale_x, scale_y);
//                             snapshot.layer.mask.bounds = endBounds;
                             snapshot.center            = snapCenter;
                         }
                         completion:^(BOOL finished){
                             toVC.view.alpha   = 1;
                             [snapshot removeFromSuperview];
                             [transitionContext completeTransition:YES];
                         }];
    }

    else
    {
        XWAssetsPikerEditViewController *fromVC  = (XWAssetsPikerEditViewController *)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
        XWAssetsGroupViewController *toVC        = (XWAssetsGroupViewController *)[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];

        NSIndexPath *indexPath              = fromVC.indexPath;

        // Scroll to index path
        [toVC.pickerCollectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        [toVC.pickerCollectionView layoutIfNeeded];

        UIView *cellView        = [toVC.pickerCollectionView cellForItemAtIndexPath:indexPath];
        cellView.backgroundColor = [UIColor blackColor];

        UIImageView *imageView  = [[fromVC.view viewWithTag:100] viewWithTag:100];
        CGSize size = fromVC.photoView.originalSize;

        UIView *snapshot        = [self resizedSnapshot:imageView size:size];

        CGPoint cellCenter  = [toVC.view convertPoint:cellView.center fromView:cellView.superview];
//        CGPoint snapCenter  = fromVC.view.center;

        // Find the bounds of the snapshot mask
        float width         = snapshot.bounds.size.width;
        float height        = snapshot.bounds.size.height;
        //        float length        = MIN(width, height);

        float scale_x       = cellView.frame.size.width*1.0/width;
        float scale_y       = cellView.frame.size.height*1.0/height;
        // Find the scales of snapshot
        CGRect startBounds  = snapshot.frame;
//        CGRect endBounds  = [toVC.view convertRect:cellView.frame fromView:toVC.pickerCollectionView];

        snapshot.center     = cellCenter;
        snapshot.frame = startBounds;

        toVC.view.frame     = [transitionContext finalFrameForViewController:toVC];
        toVC.view.alpha     = 0;

        // Add to container view
        [containerView addSubview:toVC.view];
        [containerView addSubview:snapshot];

        // Animate
        [UIView animateWithDuration:[self transitionDuration:transitionContext]
                              delay:0
             usingSpringWithDamping:1
              initialSpringVelocity:0
                            options:UIViewAnimationOptionCurveLinear
                         animations:^{
                             toVC.view.alpha            = 1;
                             snapshot.transform         = CGAffineTransformMakeScale(scale_x, scale_y);
//                             snapshot.layer.mask.bounds = endBounds;
                             snapshot.center            = cellCenter;
                         }
                         completion:^(BOOL finished){
                             fromVC.view.alpha = 0;
                             [snapshot removeFromSuperview];
                             [transitionContext completeTransition:YES];
                         }];
    }
}

#pragma mark - Snapshot

- (UIView *)resizedSnapshot:(UIImageView *)imageView size:(CGSize)size
{
    //    CGSize size = imageView.frame.size;

    UIGraphicsBeginImageContextWithOptions(size, YES, 0);

    [[UIColor blackColor] set];
    UIRectFill(CGRectMake(0, 0, size.width, size.height));

    [imageView.image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *resized = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return (UIView *)[[UIImageView alloc] initWithImage:resized];
}

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Arch. Mikrobiol. 18(2): 200 (1953)

#### Original name
Pericystis apis var. minor Prökschl & Zobl

### Remarks
null


text:
(function($, litepubl) {
  'use strict';

  $.BootstrapDialog = Class.extend({
    dialog: false,
    footer: false,
    style: false,
    options: false,
    padwidth: 32,
    padheight: 0,
    removeOnclose: true,

    tml: '
' +
      '
' +
      '
' +
      '
' +
      '<button type="button" class="close" data-dismiss="modal" aria-label="%%close%%">×%%close%%</button>' +
      '
%%title%%
' +
      '
' +
      '
%%body%%
' +
      '
%%buttons%%
' +
      '

',

    button: '<button type="button" class="btn btn-default" id="button-%%id%%-%%index%%" data-index="%%index%%">%%icon%%%%title%%</button>',

    init: function() {
      var close = $.proxy(this.close, this);
      $.closedialog = close;
      $.litedialog = $.proxy(this.open, this);

      this.default_options = {
        title: "",
        html: "",
        css: "",
        width: false,
        height: false,
        open: $.noop,
        close: $.noop,
        buttons: [{
          title: "Ok",
          click: close
        }]
      };
    },

    close: function(callback) {
      if (!this.dialog) return false;
      if ($.isFunction(callback)) {
        this.dialog.on("hidden.bs.modal", function() {
          setTimeout(function() {
            callback();
          }, 20);
        });
      }

      this.dialog.modal("hide");
    },

    doclose: function() {
      if (this.dialog && $.isFunction(this.options.close)) {
        this.options.close(this.dialog);
      }

      if (this.removeOnclose) {
        this.remove();
      }
    },

    remove: function() {
      if (!this.dialog) return false;

      this.trigger('remove');
      this.options = false;
      this.footer = false;
      this.dialog.find(".tooltip-toggle, .tooltip-ready").tooltip("destroy");
      this.dialog.find(".popover-toggle").popover("destroy");
      this.dialog.remove();
      this.dialog = false;

      if (this.style) {
        this.style.remove();
        this.style = false;
      }
    },

    closetips: function() {
      if ("closetooltips" in $) $.closetooltips();
      if ("closepopovers" in $) $.closepopovers();
    },

    addstyle: function() {
      var options = this.options;
      var css = options.css;
      if (options.width) css = css + ".modal-dialog{width:" + (options.width + this.padwidth) + "px}";
      if (options.height) css = css + ".modal-dialog{height:" + (options.height + this.padheight) + "px}";
      if (!options.buttons.length) css = css + '.modal-footer{display:none}';
      if (css) this.style = $('').appendTo("head:first");
    },

    open: function(o) {
      if (this.dialog) {
        //one chanse to wait close
        var self = this;
        setTimeout(function() {
          if (self.dialog) {
            alert('Dialog already opened');
          } else {
            self.open(o);
          }
        }, 300);

        return;
      }

      this.closetips();

      var id = litepubl.guid++;
      this.options = $.extend({}, this.default_options, o);

      var buttons = this.options.buttons;
      var html_buttons = '';
      for (var i = 0, l = buttons.length; i < l; i++) {
        var btnitem = buttons[i];
        html_buttons += $.simpletml(this.button, {
          index: i,
          id: id,
          title: btnitem.title,
          icon: "icon" in btnitem ? btnitem.icon : ""
        });
      }

      //single button change class to "btn-primary"
      if (buttons.length == 1) html_buttons = html_buttons.replace(/btn-default/g, "btn-primary");

      var html = $.simpletml(this.tml, {
        id: id,
        title: this.options.title,
        close: lang.dialog.close,
        body: this.options.html,
        buttons: html_buttons
      });

      this.addstyle();
      var dialog = this.dialog = $(html).appendTo("body");
      //dialog.settooltip();
      this.footer = $(".modal-footer:first", dialog);
      for (var i = 0, l = buttons.length; i < l; i++) {
        this.getbutton(i).on("click.dialog", buttons[i].click);
      }

      return dialog
        .fixAndroid()
        .on("shown.bs.modal.dialog", $.proxy(this.opened, this))
        .on("hidden.bs.modal.dialog", $.proxy(this.doclose, this))
        .modal();
    },

    opened: function() {
      if ($.isFunction(this.options.open)) {
        this.options.open(this.dialog);
      }

      this.trigger('opened');
    },

    trigger: function(name) {
      this.dialog.trigger($.Event(name + '.dialog.litepubl', {
        target: this.dialog[0],
        dialog: this
      }));
    },

    getbutton: function(index) {
      if (!this.footer) return false;
      return this.footer.find("button[data-index=" + index + "]");
    },

    geticon: function(name) {
      if (!name) return '';

      var icons = {
        info: "info-circle",
        success: "check",
        //warning: "warning",
        danger: "times-circle",
        error: "times-circle"
      };

      if (name in icons) name = icons[name];
      return '';
    }

  });

  $.ready2(function() {
    if ("modal" in $.fn) {
      $.bootstrapDialog = new $.BootstrapDialog();
    }
  });

})(jQuery, litepubl);


text:
<?php

namespace AppBundle\Form\Model;

use Symfony\Component\Validator\Constraints as Assert;

/**
 * UserFormModel.
 */
class GradeSessionFormModel
{
    /**
     * @Assert\NotNull()
     * @Assert\DateTime()
     *
     * @var string
     */
    protected $start_date;

    /**
     * @Assert\DateTime()
     *
     * @var string
     */
    protected $end_date;

    /**
     * GradeSessionFormModel constructor.
     *
     * @param \DateTime|null $start_date
     * @param \DateTime|null $end_date
     */
    public function __construct(\DateTime $start_date = null, \DateTime $end_date = null)
    {
        $this->start_date = $start_date;
        $this->end_date = $end_date;
    }

    public function setStartDate($start_date)
    {
        if ($this->validateDate($start_date)) {
            $this->start_date = new \DateTime($start_date);
        } else {
            $this->start_date = $start_date;
        }
    }

    public function getStartDate()
    {
        return $this->start_date;
    }

    public function setEndDate($end_date)
    {
        if ($this->validateDate($end_date)) {
            $this->start_date = new \DateTime($end_date);
        } else {
            $this->end_date = $end_date;
        }
    }

    public function getEndDate()
    {
        return $this->end_date;
    }

    /**
     * @param string $date_string
     *
     * @return string
     */
    public function validateDate($date_string)
    {
        return (bool) strtotime($date_string);
    }
}


text:
// app.init = function(){
//   if(is_professional) {
//     app.professional.resize();
//   }else if(is_root){
//     app.frontPage.elHeightToScreenHeight($one, height);
//     app.frontPage.elHeightToScreenHeight($three, height);
//     app.frontPage.sectionTwo();
//   }
// };

// app.bind = function(){

//   if(is_root){// if the page is the home page

//     $(document).on('click', '#orderNow', function() { // If order now is clicked scroll to the product secition
//       $('html, body').animate({scrollTop: $five.offset().top}, 1000);
//     });

//   }

//   if(is_professional){// if the page is the professional page

//     $(document).on('click', '#orderNow', function() { // If order now is clicked scroll to the product secition
//       $('html, body').animate({scrollTop: $('#three-prof').offset().top}, 1000);
//     });

//   }

//   if(is_root || is_professional){// if the page is the professional page or the professional page

//     $(document).on('click', '.icon-circle', function(){// when the icon circle if clicked
//       if($(window).width() > 791 ){// if the width is less than the medium query size
//         app.frontPage.animateSectionTwo($(this)); // show the coresponding text to the icon
//       }
//     });
//   }

//   $(document).on('click', '#closeCart', function() { // If The cart is open close the art
//     app.cart.close();
//   });

//   $(document).on('click', '#openCart', function() {  // If The cart is closed open the art
//     app.cart.open();
//   });
// };

// app.header = {

//   showHeader: function(){

//     var isOpen = $nav.hasClass('showHiddenNav');

//     if(isOpen && $nav.hasClass('navHidden')){

//       app.header.hideHeader();
//       app.header.showHeader();

//     }else if($nav.hasClass('navHidden')){

//       $nav.addClass('showHiddenNav');

//     }
//   },

//   hideHeader: function(){
//     $nav.removeClass('showHiddenNav');
//   }

// };

// app.frontPage = {

//   scrollEffects:  function(scrollY ,trigger){

//     var bottom = scrollY + height;

//     if(scrollY > position){

//       if( scrollY > (trigger - (height / 4)) && scrolled === false ){
//         app.frontPage.animateSectionThree('add', 'move');
//         scrolled = true;
//       }

//     }else if(scrollY < position){

//       if(scrollY < (trigger - (height / 4) - 10) && scrolled === true ){
//         app.frontPage.animateSectionThree('remove', 'move');
//         scrolled = false;
//       }
//     }

//     // if the bottom of the window is below the switch
//     if(bottom > $five.offset().top + $five.outerHeight() + 50){
//       // open the div if it isn't open allready
//       if(!$six.hasClass('open')){
//         window.setTimeout(function(){
//           $six.addClass('open');
//         }, 300);

//       }

//     // reset the footer animation after scoll up
//     }else if(bottom < $footer.offset().top + 50 ){

//       if($six.hasClass('open')){
//         $six.removeClass('open');
//       }
//     }
//   },

//   elHeightToScreenHeight: function(el, screenHeight){
//       // resize the first div
//     if(screenHeight > el.height()){
//       el.css('height', screenHeight);
//     }

//   },

//    // this is actually the second block
//   animateSectionThree: function(call, arg){

//     var animations = [
//         $('.perioTop'),
//         $('.perioBottom'),
//         $('.perioHandle')
//       ];

//     function applyAll(arg1){
//       animations.forEach( function(x){
//         if( call === 'add' ){
//           x.addClass(arg1);
//         }else{
//           x.removeClass(arg1);
//         }
//       });
//     }

//     return applyAll(arg);

//   }

// };

// app.professional = {

//   resize: function(){
//     var secOne = $('#one-prof');
//     var grid = secOne.children('.grid');
//     var screenH = $(window).height();

//     if(grid.height() < screenH ){
//       grid.css('height', screenH);
//     }
//   }

// };

// $(document).ready(function(){

//   app.init();

//   $(window).on('resize', function(){
//     app.frontPage.sectionTwo();
//     contactSwitch = $footer.offset().top + $footer.height();
//     width = $(window).width();
//     height = $(window).height();

//     if(is_root){
//       app.frontpage.elHeightToScreenHeight($one, height);
//       app.frontpage.elHeightToScreenHeight($two, height);
//     }

//     // if the page is the front page
//       // change the height of #one #two to fit the screen

//   });

//   if(is_root){
//     $trigger = $three.offset().top;
//   }

//   if(is_professional){
//     $trigger = $('.two-prof').offset().top;
//   }

//   $(this).scroll(function(){

//     var scrollY = $(window).scrollTop();

//     if(is_root || is_professional){

//       if(is_root){
//         // trigger effects
//         app.frontPage.scrollEffects(scrollY, $trigger);

//       }

//       if (scrollY < $trigger){
//         if($nav.hasClass('blue')){
//           $nav.removeClass('blue');
//         }
//       }else{
//         if(!$nav.hasClass('blue')){
//           $nav.addClass('blue');
//         }
//       }

//       if(scrollY > 200){
//         $nav.addClass('navHidden');
//         if(scrollY < position){
//           if(scrollY < (position - 20)){
//             app.header.showHeader();
//           }
//         }else{
//           app.header.hideHeader();
//         }
//       }else if(scrollY === 0){
//         app.header.hideHeader();
//         $nav.removeClass('navHidden');
//       }
//     }

//     position = scrollY;

//   });
// });


text:
<!DOCTYPE html>
<body>Hello world


text:
title: "Made in 2019"
date: 2020-01-02
related: [
  "Made in 2018",
  "Made in 2017",
  "Made in 2016",
]
---

Things I made in 2019:

* [PowerpointKaraoke.com redesign](https://www.powerpointkaraoke.com/) (including new decks and new pricing)
* [Connect Four redesign]({{site.url}}/2019/05/13/connect-four-invisible-interface-design/)
* [Alt React Demo](https://github.com/bryanbraun/alt-react-demo) ([A Password Generator]({{site.url}}/alt-react-demo/))
* [21 blog posts]({{site.url}}/archives/#y2019)
* [23 spreadsheet tips](https://us11.campaign-archive.com/home/?u=c6aa5d99b8059f1aba3005443&id=cf722f27b0)
* [Commit Colors Video](https://seesparkbox.com/foundry/css_colors_from_git_commit_ids)
* Two lightning talks
* [Tic Tac Term](https://gist.github.com/bryanbraun/9292bb57dab2e01aa59d02c5300d775f)
* [Music Box Fun](https://musicboxfun.com/) (an online editor for [DIY music boxes](https://musicboxfun.com/guides/diy-music-box))

There's a lot that I'm proud of here, but at the same time, I fell short of some milestones I was hoping to reach. It's easy to feel a bit disappointed, but I've been trying to remind myself of an idea [recently expressed by James Clear](https://twitter.com/JamesClear/status/1212459953195233280):

> Focus on your current trajectory, not your current results.

My trajectory in 2019 was good. As long as I keep that trajectory strong, then I know that, eventually, the results will come.


text:
const keystone	= require( 'keystone' ),
	  _			= require( 'underscore' );

exports.getAllRegions = () => {

	return new Promise( ( resolve, reject ) => {
		// query the database for all region models
		keystone.list( 'Region' ).model
			.find()
			.exec()
			.then( regions => {
				// if no regions could not be found
				if( regions.length === 0 ) {
					// log an error for debugging purposes
					console.error( `no regions could be found` );
					// reject the promise
					return reject();
				}
				// if regions were successfully returned, resolve with the array
				resolve( regions );
			// if an error was encountered fetching from the database
			}, err => {
				// log the error for debugging purposes
				console.error( `error fetching the list of all regions - ${ err }` );
				// reject the promise
				reject();
			});
	});
};

exports.getRegionByName = name => {

	return new Promise( ( resolve, reject ) => {
		// query the database for the region with the matching name
		keystone.list( 'Region' ).model
			.findOne()
			.where( 'region', name )
			.exec()
			.then( region => {
				// if no region could not be found
				if( !region ) {
					// reject the promise with an error message
					return reject( `region could not be found by name: ${ name }` );
				}
				// if the region was successfully returned, resolve with the model
				resolve( region );
			// if an error was encountered fetching from the database
			}, err => {
				// reject the promise
				reject( err );
			});
	});
};

exports.getAllSocialWorkerPositions = () => {

	return new Promise( ( resolve, reject ) => {
		// query the database for all social worker position models
		keystone.list( 'Social Worker Position' ).model
			.find()
			.exec()
			.then( positions => {
				// if no social worker positions could not be found
				if( positions.length === 0 ) {
					// log an error for debugging purposes
					console.error( `no social worker positions could be found` );
					// reject the promise
					return reject();
				}
				// if positions were successfully returned, resolve with the array
				resolve( positions );
			// if an error was encountered fetching from the database
			}, err => {
				// log the error for debugging putposes
				console.error( `error fetching the list of all social worker positions - ${ err }` );
				// reject the promise
				reject();
			});
	});
};

exports.getAllRaces = options => {

	return new Promise( ( resolve, reject ) => {
		// query the database for all race models
		keystone.list( 'Race' ).model
			.find()
			.exec()
			.then( races => {
				// if no races could not be found
				if( races.length === 0 ) {
					// log an error for debugging purposes
					console.error( `no races could be found` );
					// reject the promise
					return reject();
				}
				// if there is a value of 'other' in the list, which should appear at the bottom of any
				// dropdown lists on the site, add an appropriate attribute
				if( options && options.other ) {
					// loop through the returned races array
					for( let race of races ) {
						// and if a value of 'other' is encountered
						if( race.race === 'other' ) {
							// add an attribute to the model object showing that it represents the 'other' value
							race.other = true;
						}
					};
				}
				// resolve with the returned array of races
				resolve( races );
			// if an error was encountered fetching from the database
			}, err => {
				// log the error for debugging purposes
				console.error( `error fetching the list of races - ${ err }` );
				// reject the promise
				reject();
			});
	});
};

exports.getAllStates = options => {

	return new Promise( ( resolve, reject ) => {
		// query the database for all states models
		keystone.list( 'State' ).model
			.find()
			.exec()
			.then( states => {
				// if no states could not be found
				if( states.length === 0 ) {
					// log an error for debugging purposes
					console.error( `no states could be found` );
					// reject the promise
					return reject();
				}
				// if there is a default value which should appear selected when a dropdown menu is first rendered add an appropriate attribute
				if( options && options.default ) {
					// loop through the returned states array
					for( let state of states ) {
						// and if one matches the text of the default option
						if( state.state === options.default ) {
							// add an attribute to the model object showing that it represents the default option
							state.defaultSelection = true;
						}
					};

				}
				// resolve with the returned array of states
				resolve( states );
			// if an error was encountered fetching from the database
			}, err => {
				// log the error for debugging purposes
				console.error( `error fetching the list of all states - ${ err }` );
				// reject the promise
				reject();
			});
	});
};

exports.getStateById = id => {

	return new Promise( ( resolve, reject ) => {
		// if no id value was passed into the function
		if ( !id ) {
			// reject the promise with a description of the error
			return reject( 'getStateById cannot execute - no state ID provided' );
		}
		// query the database for the state with the matching _id
		keystone.list( 'State' ).model
			.findById( id )
			.exec()
			.then( state => {
				// if no state could not be found
				if( !state ) {
					// reject the promise with an error message
					return reject( `state could not be found` );
				}
				// if the state was successfully returned, resolve with the model
				resolve( state );
			// if an error was encountered fetching from the database
			}, err => {
				// reject the promise
				reject( err );
			});
	});
};

exports.getAllGenders = () => {

	return new Promise( ( resolve, reject ) => {
		// query the database for all gender models
		keystone.list( 'Gender' ).model
			.find()
			.exec()
			.then( genders => {
				// if no genders could not be found
				if( genders.length === 0 ) {
					// log an error for debugging purposes
					console.error( `no genders could be found` );
					// reject the promise
					return reject();
				}
				// if genders were successfully returned, resolve with the array
				resolve( genders );
			// if an error was encountered fetching from the database
			}, err => {
				// log the error for debugging purposes
				console.error( `error fetching the list of all genders - ${ err }` );
				// reject the promise
				reject();
			});
	});
};

exports.getAllLegalStatuses = () => {

	return new Promise( ( resolve, reject ) => {
		// query the database for all legal status models
		keystone.list( 'Legal Status' ).model
			.find()
			.exec()
			.then( legalStatuses => {
				// if no legal statuses could not be found
				if( legalStatuses.length === 0 ) {
					// log an error for debugging purposes
					console.error( `no legal statuses could be found` );
					// reject the promise
					return reject();
				}
				// if legal statuses were successfully returned, resolve with the array
				resolve( legalStatuses );
			// if an error was encountered fetching from the database
			}, err => {
				// log the error for debugging purposes
				console.error( `error fetching the list of all legal statuses - ${ err }` );
				// reject the promise
				reject();
			});
	});
};

exports.getAllLanguages = () => {

	return new Promise( ( resolve, reject ) => {
		// query the database for all language models
		keystone.list( 'Language' ).model
			.find()
			.exec()
			.then( languages => {
				// if no languages could not be found
				if( languages.length === 0 ) {
					// log an error for debugging purposes
					console.error( `no languages could be found` );
					// reject the promise
					return reject();
				}
				// if languages were successfully returned, resolve with the array
				resolve( languages );
			// if an error was encountered fetching from the database
			}, err => {
				// log the error for debugging purposes
				console.error( `error fetching the list of all languages - ${ err }` );
				// reject the promise
				reject();
			});
	});
};

exports.getAllFamilyConstellations = () => {

	return new Promise( ( resolve, reject ) => {
		// query the database for all family constellation models
		keystone.list( 'Family Constellation' ).model
			.find()
			.exec()
			.then( familyConstellations => {
				// if no family constellations could not be found
				if( familyConstellations.length === 0 ) {
					// log an error for debugging purposes
					console.error( `no family constellations could be found` );
					// reject the promise
					return reject();
				}
				// if family constellations were successfully returned, resolve with the array
				resolve( familyConstellations );
			// if an error was encountered fetching from the database
			}, err => {
				// log the error for debugging purposes
				console.error( `error fetching the list of all family constellations - ${ err }` );
				// reject the promise
				reject();
			});
	});
};

exports.getAllDisabilities = () => {

	return new Promise( ( resolve, reject ) => {
		// query the database for all disability models
		keystone.list( 'Disability' ).model
			.find()
			.exec()
			.then( disabilities => {
				// if no disabilities could not be found
				if( disabilities.length === 0 ) {
					// log an error for debugging purposes
					console.error( `no disabilities could be found` );
					// reject the promise
					return reject();
				}
				// if disabilities were successfully returned, resolve with the array
				resolve( disabilities );
			// if an error was encountered fetching from the database
			}, err => {
				// log the error for debugging purposes
				console.error( `error fetching the list of all disabilities - ${ err }` );
				// reject the promise
				reject();
			});
	});
};

exports.getAllOtherConsiderations = () => {

	return new Promise( ( resolve, reject ) => {
		// query the database for all other consideration models
		keystone.list( 'Other Consideration' ).model
			.find()
			.exec()
			.then( otherConsiderations => {
				// if no other considerations could not be found
				if( otherConsiderations.length === 0 ) {
					// log an error for debugging purposes
					console.error( `no other considerations could be found` );
					// reject the promise
					return reject();
				}
				// if other considerations were successfully returned, resolve with the array
				resolve( otherConsiderations );
			// if an error was encountered fetching from the database
			}, err => {
				// log the error for debugging purposes
				console.error( `error fetching the list of all other considerations - ${ err }` );
				// reject the promise
				reject();

			});
	});
};

exports.getChildTypesForWebsite = () => {

	return new Promise( ( resolve, reject ) => {
		// query the database for all child types marked for display on the website
		keystone.list( 'Child Type' ).model
			.find()
			.where( 'availableOnWebsite', true )
			.exec()
			.then( childTypes => {
				// if no child types could not be found
				if( childTypes.length === 0 ) {
					// log an error for debugging purposes
					console.error( `no child types could be found` );
					// reject the promise
					return reject();
				}
				// if child types were successfully returned, resolve with the array
				resolve( childTypes );
			// if an error was encountered fetching from the database
			}, err => {
				// log the error for debugging purposes
				console.error( `error fetching the list of all child types meant for website display - ${ err }` );
				// reject the promise
				reject();

			});
	});
};

exports.getEventTypesForWebsite = () => {

	return new Promise( ( resolve, reject ) => {
		// query the database for all event types marked for display on the website
		keystone.list( 'Event Type' ).model
			.find()
			.where( 'availableOnWebsite', true )
			.exec()
			.then( eventTypes => {
				// if no event types meant for the website could not be found
				if( eventTypes.length === 0 ) {
					// log an error for debugging purposes
					console.error( `no event types meant for website display could be found` );
					// reject the promise
					return reject();
				}
				// if event types were successfully returned, resolve with the array
				resolve( eventTypes );
			// if an error was encountered fetching from the database
			}, err => {
				// log the error for debugging purposes
				console.error( `error fetching the list of all event types meant for website display - ${ err }` );
				// reject the promise
				reject();
			});
	});
};

exports.getAllWaysToHearAboutMARE = options => {

	return new Promise( ( resolve, reject ) => {
	// query the database for all ways to hear about MARE
	keystone.list( 'Way To Hear About MARE' ).model
		.find()
		.exec()
		.then( waysToHearAboutMARE => {
			// if no ways to hear about MARE could not be found
			if( waysToHearAboutMARE.length === 0 ) {
				// log an error for debugging purposes
				console.error( `no ways to hear about MARE could be found` );
				// reject the promise
				return reject();
			}
			// if there is a value of 'other' in the list, which should appear at the bottom of any
			// dropdown lists on the site, add an appropriate attribute
			if( options && options.other ) {
				// loop through the returned ways to hear about MARE array
				for( let wayToHearAboutMARE of waysToHearAboutMARE ) {
					// and if a value of 'other' is encountered
					if( wayToHearAboutMARE.wayToHearAboutMARE === 'other' ) {
						// add an attribute to the model object showing that it represents the 'other' value
						wayToHearAboutMARE.other = true;
					}
				};
			}
			// resolve with the returned array of ways to hear about MARE
			resolve( waysToHearAboutMARE );
		// if an error was encountered fetching from the database
		}, err => {
			// log the error for debugging purposes
			console.error( `error fetching the list of ways to hear about MARE - ${ err }` );
			// reject the promise
			reject();
		});
	});
};

exports.getAllResidences = () => {

	return new Promise( ( resolve, reject ) => {
		// query the database for all residences
		keystone.list( 'Residence' ).model
			.find()
			.exec()
			.then( residences => {
				// if no residences could not be found
				if( residences.length === 0 ) {
					// log an error for debugging purposes
					console.error( `no residences could be found` );
					// reject the promise
					return reject();
				}
				// if residences were successfully returned, resolve with the array
				resolve( residences );
			// if an error was encountered fetching from the database
			}, err => {
				// log the error for debugging purposes
				console.error( `error fetching the list of residences - ${ err }` );
				// reject the promise
				reject();
			});
	});
};

exports.getAllOtherFamilyConstellationConsiderations = () => {

	return new Promise( ( resolve, reject ) => {
		// query the database for all other family constellation considerations
		keystone.list( 'Other Family Constellation Consideration' ).model
			.find()
			.exec()
			.then( otherFamilyConstellationConsiderations => {
				// if no other family constellation considerations could not be found
				if( otherFamilyConstellationConsiderations.length === 0 ) {
					// log an error for debugging purposes
					console.error( `no other family constellation considerations could be found` );
					// reject the promise
					return reject();
				}
				// if other family constellation considerations were successfully returned, resolve with the array
				resolve( otherFamilyConstellationConsiderations );
			// if an error was encountered fetching from the database
			}, err => {
				// log the error for debugging purposes
				console.error( `error fetching the list of other family constellation considerations - ${ err }` );
				// reject the promise
				reject();
			});
	});
};

exports.getAllCitiesAndTowns = () => {

	return new Promise( ( resolve, reject ) => {
		// query the database for all cities and towns
		keystone.list( 'City or Town' ).model
			.find()
			.sort( { cityOrTown: 1 } ) // TODO: should this be handled in the model?
			.exec()
			.then( citiesAndTowns => {
				// if no cities or towns could not be found
				if( citiesAndTowns.length === 0 ) {
					// log an error for debugging purposes
					console.error( `no cities or towns could be found` );
					// reject the promise
					return reject();
				}
				// if cities and towns were successfully returned, resolve with the array
				resolve( citiesAndTowns );
			// if an error was encountered fetching from the database
			}, err => {
				// log the error for debugging purposes
				console.error( `error fetching the list of cities and towns - ${ err }` );
				// reject the promise
				reject();
			});
	});
};

exports.getCityOrTownById = id => {

	return new Promise( ( resolve, reject ) => {
		// query the database for the city or town with the matching _id
		keystone.list( 'City or Town' ).model
			.findById( id )
			.exec()
			.then( city => {
				// if no city or town could not be found
				if( !city ) {
					// reject the promise with an error message
					return reject( `city or town could not be found` );
				}
				// if the city or town was successfully returned, resolve with the model
				resolve( city );
			// if an error was encountered fetching from the database
			}, err => {
				// reject the promise
				reject( err );
			});
	});
};

// TODO: this needs to be un-async'ed
exports.getChildStatusIdByName = ( req, res, done, name ) => {

	let locals = res.locals;

	keystone.list( 'Child Status' ).model
		.findOne()
		.where( 'childStatus' ).equals( name )
		.lean()
		.exec()
		.then( status => {

			locals.activeChildStatusId = status._id;
			// execute done function if async is used to continue the flow of execution
			done()

		}, err => {

			console.log( err );
			done();

		});
};

exports.getInquiryMethodByName = name => {

	return new Promise( ( resolve, reject ) => {
		// attempt to find a single inquiry method matching the passed in name
		keystone.list( 'Inquiry Method' ).model
			.findOne()
			.where( 'inquiryMethod' ).equals( name )
			.exec()
			.then( inquiryMethod => {
				// if the target inquiry method could not be found
				if( !inquiryMethod ) {
					// log an error for debugging purposes
					console.error( `no inquiry method matching '${ name } could be found` );
					// reject the promise
					return reject();
				}
				// if the target inquiry method was found, resolve the promise with the lean version of the object
				resolve( inquiryMethod );
			// if there was an error fetching from the database
			}, err => {
				// log an error for debugging purposes
				console.error( `error fetching inquiry method matching ${ name } - ${ err }` );
				// and reject the promise
				reject();
			});
	});
};

exports.getSourceByName = name => {

		return new Promise( ( resolve, reject ) => {
			// attempt to find a single source matching the passed in name
			keystone.list( 'Source' ).model
				.findOne()
				.where( 'source' ).equals( name )
				.exec()
				.then( source => {
					// if the target source could not be found
					if( !source ) {
						// log an error for debugging purposes
						console.error( `no source matching name '${ name } could be found` );
						// reject the promise
						return reject();
					}
					// if the target source was found, resolve the promise with the lean version of the object
					resolve( source );
				// if there was an error fetching from the database
				}, err => {
					// log an error for debugging purposes
					console.error( `error fetching source matching ${ name } - ${ err }` );
					// and reject the promise
					reject();
				});
		});
	};


text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Transaction;
use yii\helpers\BaseVarDumper;

/**
 * TransactionSearch represents the model behind the search form about `app\models\Transaction`.
 */
class TransactionSearch extends Transaction {

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['Id', 'EnvelopeId', 'UseInStats', 'IsRefund', 'CreatedBy', 'ModifiedBy', 'IsDeleted'], 'integer'],
            [['Name', 'PostedDate', 'CreatedOn', 'ModifiedOn'], 'safe'],
            [['Amount', 'Pending'], 'number'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios() {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params, $envelopeIds, $days) {

        $query = Transaction::find();
        $query->where([
                    'transaction.IsDeleted' => 0,
                    'EnvelopeId' => $envelopeIds,
                ])
                ->joinWith('envelope')
                ->all();

        if ($days !== null) {
            $date = date('Y-m-d H:i:s', strtotime("-" . $days . " days"));

            $query->andWhere(['>=', 'PostedDate', $date]);
        }

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => ['defaultOrder' => ['PostedDate' => SORT_DESC]]
        ]);

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $query->andFilterWhere([
            'Id' => $this->Id,
            'EnvelopeId' => $this->EnvelopeId,
            'Amount' => $this->Amount,
            'Pending' => $this->Pending,
            'UseInStats' => $this->UseInStats,
            'IsRefund' => $this->IsRefund,
        ]);

        $query->andFilterWhere(['like', 'Name', $this->Name]);
        $query->andFilterWhere(['like', 'PostedDate', $this->PostedDate]);

        return $dataProvider;
    }

    public function findByDate($accountId) {
        $query = Transaction::find();

        $query->select(['T.PostedDate As PostedDate', 'SUM(T.Pending) As Pending'])
                ->from('transaction T')
                ->innerJoin('envelope E', 'T.EnvelopeId = E.Id')
                ->where([
                    'E.IsDeleted' => 0,
                    'E.IsClosed' => 0,
                    'T.IsDeleted' => 0,
                    'E.AccountId' => $accountId
                ])
                ->groupBy(['T.PostedDate'])
                ->having(['>', 'COUNT(T.PostedDate)', '1'])
                ->orderBy('T.PostedDate')
                ->limit(20);

        $query->andWhere(['!=', 'T.Pending', 0]);

        return $query->all();
    }

    public function findByName($accountId) {
        $query = Transaction::find();

        $query->select(['T.Name As Name', 'SUM(T.Pending) As Pending'])
                ->from('transaction T')
                ->innerJoin('envelope E', 'T.EnvelopeId = E.Id')
                ->where([
                    'E.IsDeleted' => 0,
                    'E.IsClosed' => 0,
                    'T.IsDeleted' => 0,
                    'E.AccountId' => $accountId
                ])
                ->groupBy('T.Name')
                ->having(['>', 'COUNT(T.Name)', '1'])
                ->orderBy('T.Name')
                ->limit(20);

        $query->andWhere(['!=', 'T.Pending', 0]);

        return $query->all();
    }

    public function findForBulkPending($accountId, $column, $value) {
        $envelopeIds = EnvelopeSearch::GetEnvelopeIdsByAccount($accountId);
        $query = Transaction::find();

        $query->where([
                    'IsDeleted' => 0,
                    'EnvelopeId' => $envelopeIds,
                    $column => $value
                ])
                ->limit(20);

        $query->andWhere(['!=', 'Pending', 0]);

        return $query->all();
    }

    public function findByEnvelope($envelopeId) {
        $query = Transaction::find();

        $query->where(['EnvelopeId' => $envelopeId, 'IsDeleted' => 0]);

        return $query->all();
    }

}


text:
require 'zip/filesystem'
require 'nokogiri'

module RubyPowerpoint
  class RubyPowerpoint::Slide

    attr_reader :presentation,
                :slide_number,
                :slide_number,
                :slide_file_name

    def initialize presentation, slide_xml_path
      @presentation = presentation
      @slide_xml_path = slide_xml_path
      @slide_number = extract_slide_number_from_path slide_xml_path
      @slide_notes_xml_path = "ppt/notesSlides/notesSlide#{@slide_number}.xml"
      @slide_file_name = extract_slide_file_name_from_path slide_xml_path

      parse_slide
      parse_slide_notes
      parse_relation
    end

    def parse_slide
      slide_doc = @presentation.files.file.open @slide_xml_path
      @slide_xml = Nokogiri::XML::Document.parse slide_doc
    end

    def parse_slide_notes
      slide_notes_doc = @presentation.files.file.open @slide_notes_xml_path rescue nil
      @slide_notes_xml = Nokogiri::XML::Document.parse(slide_notes_doc) if slide_notes_doc
    end

    def parse_relation
      @relation_xml_path = "ppt/slides/_rels/#{@slide_file_name}.rels"
      if @presentation.files.file.exist? @relation_xml_path
        relation_doc = @presentation.files.file.open @relation_xml_path
        @relation_xml = Nokogiri::XML::Document.parse relation_doc
      end
    end

    def content
      content_elements @slide_xml
    end

    def notes_content
      content_elements @slide_notes_xml
    end

    def title
      title_elements = title_elements(@slide_xml)
      title_elements.join(" ") if title_elements.length > 0
    end

    def images
      image_elements(@relation_xml)
        .map.each do |node|
          @presentation.files.file.open(
            node['Target'].gsub('..', 'ppt'))
        end
    end

    def slide_num
      @slide_xml_path.match(/slide([0-9]*)\.xml$/)[1].to_i
    end

    def paragraphs
      paragraph_element @slide_xml
    end

    private

    def extract_slide_number_from_path path
      path.gsub('ppt/slides/slide', '').gsub('.xml', '').to_i
    end

    def extract_slide_file_name_from_path path
      path.gsub('ppt/slides/', '')
    end

    def title_elements(xml)
      shape_elements(xml).select{ |shape| element_is_title(shape) }
    end

    def content_elements(xml)
      xml.xpath('//a:t').collect{ |node| node.text }
    end

    def image_elements(xml)
      xml.css('Relationship').select{ |node| element_is_image(node) }
    end

    def shape_elements(xml)
      xml.xpath('//p:sp')
    end

    def paragraph_element(xml)
      xml.xpath('//a:p').collect{ |node| RubyPowerpoint::Paragraph.new(self, node) }
    end

    def element_is_title(shape)
      shape.xpath('.//p:nvSpPr/p:nvPr/p:ph').select{ |prop| prop['type'] == 'title' || prop['type'] == 'ctrTitle' }.length > 0
    end

    def element_is_image(node)
      node['Type'].include? 'image'
    end
  end
end


text:
define([
  'underscore',
  'underscore.string',
  'backbone',
  'backbone.paginator',
  'models/site'
  ], function(_, _s, Backbone, BackbonePaginator, Site){

  var SitesCollection = Backbone.PageableCollection.extend({
    mode: 'client',

    service: 'gato', //default. override in constructor.

    url: function() { return '/' + this.service + '/sites'; },

    title: function() { return _s.titleize(this.service) + ' Sites'; },

    // Reference to this collection's model.
    model: Site,

    state: {
      pageSize: 10
    },

    // Sites are sorted by their name.
    comparator: function(site) {
      return site.get('name');
    },

    initialize: function(models, options) {
      if (options && options['service']) {
        this.service = options['service'];
      }
    }

  });
  return SitesCollection;
});


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="20dp"
    android:textSize="16sp" android:background="#FF9900" android:textColor="#660000">
</TextView>


text:
{% extends 'django_mailjet/base.html' %}

{% load i18n %}

{% block body %}
<p>{% trans 'Thanks for subscribing to our mailing list.' %}</p>
{% endblock %}


text:
"""
Test script for scheduled_tasks/dataset_monitor
"""

import logging
logger = logging.getLogger('scheduled_tasks_dataset_monitor_test')

import os
import sys
import shutil
import tempfile
import unittest
from functools import partial
from unittest.mock import patch, MagicMock
from collections import defaultdict

from tornado.testing import AsyncTestCase

from statsd import TCPStatsClient as StatsClient
from rest_tools.client import RestClient

from tests.util import unittest_reporter, glob_tests

from iceprod.server.modules.schedule import schedule
from iceprod.server.scheduled_tasks import dataset_monitor

class dataset_monitor_test(AsyncTestCase):
    def setUp(self):
        super(dataset_monitor_test,self).setUp()
        self.test_dir = tempfile.mkdtemp(dir=os.getcwd())
        def cleanup():
            shutil.rmtree(self.test_dir)
        self.addCleanup(cleanup)

        self.cfg = {
            'queue':{
                'init_queue_interval':0.1,
                'submit_dir':self.test_dir,
                '*':{'type':'Test1','description':'d'},
            },
            'master':{
                'url':False,
            },
            'site_id':'abcd',
        }

    @unittest_reporter
    def test_100_dataset_monitor(self):
        s = schedule(self.cfg,None,None,None)
        dataset_monitor.dataset_monitor(s)

    @unittest_reporter
    async def test_200_run(self):
        rc = MagicMock(spec=RestClient)
        pilots = {}
        jobs = {}
        tasks = defaultdict(dict)
        stats = {}
        async def client(method, url, args=None):
            logger.info('REST: %s, %s', method, url)
            if url.startswith('/dataset_summaries/status'):
                return {'processing':['foo']}
            elif url.startswith('/datasets/foo/job_counts/status'):
                return jobs
            elif url.startswith('/datasets/foo/task_counts/name_status'):
                client.called = True
                return tasks
            elif url.startswith('/datasets/foo/task_stats'):
                return stats
            if url.startswith('/datasets/foo'):
                return {'dataset':123,'status':'processing','jobs_submitted':1,'tasks_submitted':1}
            else:
                raise Exception()
        client.called = False
        rc.request = client
        mon = MagicMock(spec=StatsClient)

        await dataset_monitor.run(rc, mon, debug=True)
        self.assertTrue(client.called)
        self.assertTrue(mon.gauge.called)

        jobs['processing'] = 1
        mon.reset_mock()
        await dataset_monitor.run(rc, mon, debug=True)
        self.assertTrue(mon.gauge.called)

        tasks['generate']['queued'] = 1
        mon.reset_mock()
        await dataset_monitor.run(rc, mon, debug=True)
        self.assertTrue(mon.gauge.called)

    @unittest_reporter(name='run() - error')
    async def test_201_run(self):
        rc = MagicMock(spec=RestClient)
        async def client(method, url, args=None):
            logger.info('REST: %s, %s', method, url)
            raise Exception()
        rc.request = client
        mon = MagicMock(spec=StatsClient)
        with self.assertRaises(Exception):
            await dataset_monitor.run(rc, mon, debug=True)

        # check it normally hides the error
        await dataset_monitor.run(rc, mon, debug=False)

def load_tests(loader, tests, pattern):
    suite = unittest.TestSuite()
    alltests = glob_tests(loader.getTestCaseNames(dataset_monitor_test))
    suite.addTests(loader.loadTestsFromNames(alltests,dataset_monitor_test))
    return suite


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core.Pipeline;
using Azure.Messaging.ServiceBus.Diagnostics;

namespace Azure.Messaging.ServiceBus
{
    /// <summary>
    /// Represents a single receiver instance that multiple tasks spawned by the
    /// <see cref="ServiceBusProcessor"/> may be using to receive and process messages.
    /// The manager will delegate to the user provided callbacks and handle automatic
    /// locking of messages.
    /// </summary>
    internal class ReceiverManager
    {
        internal virtual ServiceBusReceiver Receiver { get; private set; }

        protected readonly ServiceBusProcessor Processor;
        protected readonly TimeSpan? _maxReceiveWaitTime;
        private readonly ServiceBusReceiverOptions _receiverOptions;
        protected readonly ServiceBusProcessorOptions ProcessorOptions;
        private readonly EntityScopeFactory _scopeFactory;

        protected bool AutoRenewLock => ProcessorOptions.MaxAutoLockRenewalDuration > TimeSpan.Zero;

        public ReceiverManager(
            ServiceBusProcessor processor,
            EntityScopeFactory scopeFactory,
            bool isSession)
        {
            Processor = processor;
            ProcessorOptions = processor.Options;
            _receiverOptions = new ServiceBusReceiverOptions
            {
                ReceiveMode = ProcessorOptions.ReceiveMode,
                PrefetchCount = ProcessorOptions.PrefetchCount,
                // Pass None for subqueue since the subqueue has already
                // been taken into account when computing the EntityPath of the processor.
                SubQueue = SubQueue.None,
                Identifier = $"{processor.Identifier}-Receiver"
            };
            _maxReceiveWaitTime = ProcessorOptions.MaxReceiveWaitTime;
            if (!isSession)
            {
                Receiver = new ServiceBusReceiver(
                    connection: Processor.Connection,
                    entityPath: Processor.EntityPath,
                    isSessionEntity: false,
                    isProcessor: true,
                    options: _receiverOptions);
            }

            _scopeFactory = scopeFactory;
        }

        public virtual async Task CloseReceiverIfNeeded(CancellationToken cancellationToken)
        {
            var capturedReceiver = Receiver;
            if (capturedReceiver != null)
            {
                try
                {
                    await capturedReceiver.DisposeAsync().ConfigureAwait(false);
                }
                finally
                {
                    Receiver = null;
                }
            }
        }

        public virtual async Task ReceiveAndProcessMessagesAsync(CancellationToken cancellationToken)
        {
            ServiceBusErrorSource errorSource = ServiceBusErrorSource.Receive;
            try
            {
                // loop within the context of this thread
                while (!cancellationToken.IsCancellationRequested && !Processor.Connection.IsClosed)
                {
                    errorSource = ServiceBusErrorSource.Receive;
                    IReadOnlyList<ServiceBusReceivedMessage> messages = await Receiver.ReceiveMessagesAsync(
                        maxMessages: 1,
                        maxWaitTime: _maxReceiveWaitTime,
                        isProcessor: true,
                        cancellationToken: cancellationToken).ConfigureAwait(false);
                    ServiceBusReceivedMessage message = messages.Count == 0 ? null : messages[0];
                    if (message == null)
                    {
                        continue;
                    }
                    await ProcessOneMessageWithinScopeAsync(
                        message,
                        DiagnosticProperty.ProcessMessageActivityName,
                        cancellationToken).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            // If the user manually throws a TCE, then we should log it.
            when (!(ex is TaskCanceledException) ||
                  !cancellationToken.IsCancellationRequested)
            {
                if (ex is ServiceBusException sbException && sbException.ProcessorErrorSource.HasValue)
                {
                    errorSource = sbException.ProcessorErrorSource.Value;
                }
                await RaiseExceptionReceived(
                    new ProcessErrorEventArgs(
                        ex,
                        errorSource,
                        Processor.FullyQualifiedNamespace,
                        Processor.EntityPath,
                        Processor.Identifier,
                        cancellationToken))
                    .ConfigureAwait(false);
            }
        }

        public virtual Task CancelAsync() => Task.CompletedTask;

        protected async Task ProcessOneMessageWithinScopeAsync(ServiceBusReceivedMessage message, string activityName, CancellationToken cancellationToken)
        {
            using DiagnosticScope scope = _scopeFactory.CreateScope(activityName, DiagnosticScope.ActivityKind.Consumer);
            scope.SetMessageAsParent(message);
            scope.Start();

            try
            {
                await ProcessOneMessage(
                    message,
                    cancellationToken)
                    .ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                scope.Failed(ex);
                throw;
            }
        }

        private async Task ProcessOneMessage(
            ServiceBusReceivedMessage triggerMessage,
            CancellationToken cancellationToken)
        {
            ServiceBusErrorSource errorSource = ServiceBusErrorSource.Receive;
            EventArgs args = ConstructEventArgs(triggerMessage, cancellationToken);

            try
            {
                errorSource = ServiceBusErrorSource.ProcessMessageCallback;
                try
                {
                    ServiceBusEventSource.Log.ProcessorMessageHandlerStart(Processor.Identifier, triggerMessage.SequenceNumber, triggerMessage.LockTokenGuid);
                    await OnMessageHandler(args).ConfigureAwait(false);
                    ServiceBusEventSource.Log.ProcessorMessageHandlerComplete(Processor.Identifier, triggerMessage.SequenceNumber, triggerMessage.LockTokenGuid);
                }
                catch (Exception ex)
                {
                    ServiceBusEventSource.Log.ProcessorMessageHandlerException(Processor.Identifier, triggerMessage.SequenceNumber, ex.ToString(), triggerMessage.LockTokenGuid);
                    throw;
                }

                if (Receiver.ReceiveMode == ServiceBusReceiveMode.PeekLock && ProcessorOptions.AutoCompleteMessages)
                {
                    foreach (ServiceBusReceivedMessage message in GetProcessedMessages(args))
                    {
                        if (!message.IsSettled)
                        {
                            errorSource = ServiceBusErrorSource.Complete;
                            // Don't pass the processor cancellation token as we want in flight auto-completion to be able
                            // to finish.
                            await Receiver.CompleteMessageAsync(
                                    message,
                                    CancellationToken.None)
                                .ConfigureAwait(false);
                            message.IsSettled = true;
                        }
                    }
                }
            }
            catch (Exception ex)
                // This prevents exceptions relating to processing a message from bubbling up all
                // the way to the main thread when calling StopProcessingAsync, which we don't want
                // as it isn't actionable.
                when (!(ex is TaskCanceledException) || !cancellationToken.IsCancellationRequested)
            {
                ThrowIfSessionLockLost(ex, errorSource);
                await RaiseExceptionReceived(
                        new ProcessErrorEventArgs(
                            ex,
                            errorSource,
                            Processor.FullyQualifiedNamespace,
                            Processor.EntityPath,
                            Processor.Identifier,
                            cancellationToken))
                    .ConfigureAwait(false);

                // If we got a message or session lock lost error, do not attempt to abandon the message, or any of the additional received
                // messages in the handler, as we have no way of knowing which message caused the error.
                ServiceBusFailureReason? failureReason = (ex as ServiceBusException)?.Reason;
                if (_receiverOptions.ReceiveMode == ServiceBusReceiveMode.PeekLock &&
                    failureReason != ServiceBusFailureReason.SessionLockLost &&
                    failureReason != ServiceBusFailureReason.MessageLockLost)
                {
                    foreach (ServiceBusReceivedMessage message in GetProcessedMessages(args))
                    {
                        // If the user already settled the message, do not abandon.
                        if (message.IsSettled)
                        {
                            continue;
                        }
                        try
                        {
                            // Don't pass the processor cancellation token as we want in flight abandon to be able
                            // to finish even if user stopped processing.
                            await Receiver.AbandonMessageAsync(message, cancellationToken: CancellationToken.None).ConfigureAwait(false);
                        }
                        catch (Exception exception)
                        {
                            ThrowIfSessionLockLost(exception, ServiceBusErrorSource.Abandon);
                            await RaiseExceptionReceived(
                                    new ProcessErrorEventArgs(
                                        exception,
                                        ServiceBusErrorSource.Abandon,
                                        Processor.FullyQualifiedNamespace,
                                        Processor.EntityPath,
                                        Processor.Identifier,
                                        cancellationToken))
                                .ConfigureAwait(false);
                        }
                    }
                }
            }
            finally
            {
                if (args is ProcessMessageEventArgs processMessageEventArgs)
                {
                    await processMessageEventArgs.CancelMessageLockRenewalAsync().ConfigureAwait(false);
                }
            }
        }

        private static ICollection<ServiceBusReceivedMessage> GetProcessedMessages(EventArgs args) =>
            args is ProcessMessageEventArgs processMessageEventArgs ? processMessageEventArgs.Messages.Keys
                : ((ProcessSessionMessageEventArgs)args).Messages.Keys;

        internal bool ShouldAutoRenewMessageLock()
        {
            return !Receiver.IsSessionReceiver &&
                   Receiver.ReceiveMode == ServiceBusReceiveMode.PeekLock &&
                   AutoRenewLock;
        }

        protected virtual EventArgs ConstructEventArgs(ServiceBusReceivedMessage message, CancellationToken cancellationToken) =>
            new ProcessMessageEventArgs(
            message,
            this,
            Processor.Identifier,
            cancellationToken);

        protected virtual async Task OnMessageHandler(EventArgs args) =>
            await Processor.OnProcessMessageAsync((ProcessMessageEventArgs) args).ConfigureAwait(false);

        internal async Task RenewMessageLockAsync(
            ServiceBusReceivedMessage message,
            CancellationTokenSource cancellationTokenSource)
        {
            cancellationTokenSource.CancelAfter(ProcessorOptions.MaxAutoLockRenewalDuration);
            CancellationToken cancellationToken = cancellationTokenSource.Token;
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    ServiceBusEventSource.Log.ProcessorRenewMessageLockStart(Processor.Identifier, 1, message.LockTokenGuid);
                    TimeSpan delay = CalculateRenewDelay(message.LockedUntil);

                    // We're awaiting the task created by 'ContinueWith' to avoid awaiting the Delay task which may be canceled
                    // by the renewLockCancellationToken. This way we prevent a TaskCanceledException.
                    Task delayTask = await Task.Delay(delay, cancellationToken)
                        .ContinueWith(
                            t => t,
                            CancellationToken.None,
                            TaskContinuationOptions.ExecuteSynchronously,
                            TaskScheduler.Default)
                        .ConfigureAwait(false);
                    if (Receiver.IsClosed || delayTask.IsCanceled || message.IsSettled)
                    {
                        break;
                    }

                    await Receiver.RenewMessageLockAsync(message, cancellationToken).ConfigureAwait(false);
                    ServiceBusEventSource.Log.ProcessorRenewMessageLockComplete(Processor.Identifier, message.LockTokenGuid);
                }
                catch (Exception ex) when (!(ex is TaskCanceledException))
                {
                    ServiceBusEventSource.Log.ProcessorRenewMessageLockException(Processor.Identifier, ex.ToString(), message.LockTokenGuid);

                    // If the message has already been settled there is no need to raise the lock lost exception to user error handler.
                    if (!message.IsSettled)
                    {
                        await HandleRenewLockException(ex, cancellationToken).ConfigureAwait(false);
                    }

                    // if the error was not transient, break out of the loop
                    if (!(ex as ServiceBusException)?.IsTransient == true)
                    {
                        break;
                    }
                }
            }
        }

        private static void ThrowIfSessionLockLost(
            Exception exception,
            ServiceBusErrorSource errorSource)
        {
            // we need to propagate this in order to dispose the session receiver
            // in the same place where we are creating them.
            var sbException = exception as ServiceBusException;
            if (sbException?.Reason == ServiceBusFailureReason.SessionLockLost)
            {
                sbException.ProcessorErrorSource = errorSource;
                throw sbException;
            }
        }

        protected async Task HandleRenewLockException(Exception ex, CancellationToken cancellationToken)
        {
            // ObjectDisposedException should only happen here because the CancellationToken was disposed at which point
            // this renew exception is not relevant anymore. Lets not bother user with this exception.
            if (!(ex is ObjectDisposedException) && !cancellationToken.IsCancellationRequested)
            {
                await RaiseExceptionReceived(
                    new ProcessErrorEventArgs(
                        ex,
                        ServiceBusErrorSource.RenewLock,
                        Processor.FullyQualifiedNamespace,
                        Processor.EntityPath,
                        Processor.Identifier,
                        cancellationToken)).ConfigureAwait(false);
            }
        }

        protected virtual async Task RaiseExceptionReceived(ProcessErrorEventArgs eventArgs)
        {
            try
            {
                await Processor.OnProcessErrorAsync(eventArgs).ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                // don't bubble up exceptions raised from customer exception handler
                ServiceBusEventSource.Log.ProcessorErrorHandlerThrewException(exception.ToString(), Processor.Identifier);
            }
        }

        protected static TimeSpan CalculateRenewDelay(DateTimeOffset lockedUntil)
        {
            var remainingTime = lockedUntil - DateTimeOffset.UtcNow;

            if (remainingTime < TimeSpan.FromMilliseconds(400))
            {
                return TimeSpan.Zero;
            }

            var buffer = TimeSpan.FromTicks(Math.Min(remainingTime.Ticks / 2, Constants.MaximumRenewBufferDuration.Ticks));
            var renewAfter = remainingTime - buffer;

            return renewAfter;
        }
    }
}


text:
package e_frame
import skidbladnir.{Assembly,Base,Compo,Handle,Interface,Mono,Multi},
       javax.swing.{JFrame,JPanel,WindowConstants,JLabel},
       java.awt.{BorderLayout,Component,Dimension},
       java.awt.event.{WindowAdapter,WindowEvent},
       applet.AbstractApplet

object Test {def main(args: Array[String]): Unit = {val a = new TestAssembly}}

object IFrame extends Interface {
  class Am extends Mono {val imports:Pm = null
    def setTitle(s:String) = {}
    def show() = {}
    def hide() = {}}
  class Pm extends Mono {val imports:Am = null
    def closing () = {}}
}

object IWidget extends Interface {
  class Am extends Mono {val imports:Pm = null
    val widget:Compo = null}
  class Pm extends Multi {val imports = Map[Handle, Am]()
    def pack () = {}}
}

object IWindow extends Interface {
  class Am extends Multi {val imports = Map[Handle, Pm]()
    def getSize():(Int,Int) = {(0,0)}
    def getLocation():(Int,Int) = {(0,0)}}
  class Pm extends Mono {val imports:Am = null}
}

class TestAssembly extends Assembly {
  visualization
  new Main named "main"
  new BorderFrame connected "iFrame" from "main" named "frame"
  new Hello connected "iCenter" from "frame" named "hello"
  gowait()
  end
}

class TestApplet extends AbstractApplet {
  def construct() ={
    new Main named "main"
    new BorderFrame connected "iFrame" from "main" named "frame"
    new Hello connected "iCenter" from "frame" named "hello"
  }
}

class Main extends Base {
  //Interfaces
  protected val iFrame:IFrame.Pm = jack(new IFrame.Pm{
    override def closing () = {selfdestruction}})
  //Main
  main(()=>{
    iFrame.imports.setTitle("GUI Hello")
    iFrame.imports.show()
  })
}

class BorderFrame extends JFrame with Compo {
  //Self-assembly
  setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE)
  private val panel = new JPanel
  panel setLayout new BorderLayout
  add(panel)
  val frame = this
  //Interfaces
  protected val iFrame = root(new IFrame.Am{
    override def setTitle(s:String) = {frame.setTitle(s)}
    override def show() = {frame.setVisible(true)}
    override def hide() = {frame.setVisible(false)}})
  protected val iNorth:IWidget.Pm = multijack(new IWidget.Pm{
    override def pack () = {frame.pack()}},
    connection = (h)=>{addWidget(iNorth.imports(h), BorderLayout.NORTH)},
    disconnection = (h,i)=>{delWidget(iNorth.imports(h))})
  protected val iSouth:IWidget.Pm = multijack(new IWidget.Pm{
    override def pack () = {frame.pack()}},
    connection = (h)=>{addWidget(iSouth.imports(h), BorderLayout.SOUTH)},
    disconnection = (h,i)=>{delWidget(iSouth.imports(h))})
  protected val iEast:IWidget.Pm = multijack(new IWidget.Pm{
    override def pack () = {frame.pack()}},
    connection = (h)=>{addWidget(iEast.imports(h), BorderLayout.EAST)},
    disconnection = (h,i)=>{delWidget(iEast.imports(h))})
  protected val iWest:IWidget.Pm = multijack(new IWidget.Pm{
    override def pack () = {frame.pack()}},
    connection = (h)=>{addWidget(iWest.imports(h), BorderLayout.WEST)},
    disconnection = (h,i)=>{delWidget(iWest.imports(h))})
  protected val iCenter:IWidget.Pm = multijack(new IWidget.Pm{
    override def pack () = {frame.pack()}},
    connection = (h)=>{addWidget(iCenter.imports(h), BorderLayout.CENTER)},
    disconnection = (h,i)=>{delWidget(iCenter.imports(h))})
  protected val iWindow:IWindow.Am = multijack(new IWindow.Am{
    override def getSize():(Int,Int) = {val d = frame.getSize(); (d.width, d.height)}
    override def getLocation():(Int,Int) = {val p = frame.getLocation(); (p.x, p.y)}})
  //Deconstructor
  deconstructor((h,i)=>{setVisible(false)})
  //Listeners
  addWindowListener(new WindowAdapter{
    override def windowClosing(e:WindowEvent) = {iFrame.imports.closing()}
  })
  //Functions
  private def addWidget(i:IWidget.Am, p:String) = {
    panel.add(i.widget.asInstanceOf[Component], p)
    pack()
  }
  private def delWidget(i:IWidget.Am) = {
    panel.remove(i.widget.asInstanceOf[Component])
    pack()
  }
}

class Hello extends JLabel with Compo {
  //Self-assembly
  setText("Hello world!")
  setPreferredSize(new Dimension(200,20))
  //Interfaces
  protected val iWidget = root(new IWidget.Am{override val widget:Compo = compo})
}