text:
package org.jboss.resteasy.spi;

import org.jboss.resteasy.plugins.delegates.LinkHeaderDelegate;

import javax.ws.rs.core.Link;
import javax.ws.rs.core.MultivaluedMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Abstraction for LInk headers.  Also uses JAXRS classes rather than deprecated old resteasy ones.
 *
 * @author Bill Burke
 * @version $Revision: 1 $
 */
public class LinkHeaders
{
   private Map<String, Link> linksByRelationship = new HashMap<String, Link>();
   private Map<String, Link> linksByTitle = new HashMap<String, Link>();
   private List<Link> links = new ArrayList<Link>();

   public LinkHeaders addLinks(MultivaluedMap<String, String> headers)
   {
      List<String> values = headers.get("Link");
      if (values == null) return this;
      for (String val : values)
      {
         LinkHeader linkHeader = new LinkHeaderDelegate().fromString(val);
         for (Link link : linkHeader.getLinks())
         {
            addLink(link);
         }
      }
      return this;
   }

   public LinkHeaders addLinkObjects(MultivaluedMap<String, Object> headers, HeaderValueProcessor factory)
   {
      List<Object> values = headers.get("Link");
      if (values == null) return this;
      for (Object val : values)
      {
         if (val instanceof Link) addLink((Link)val);
         else
         {
            String str = factory.toHeaderString(val);
            addLink(Link.valueOf(str));
         }
      }
      return this;
   }

   public LinkHeaders addLink(final Link link)
   {
      links.add(link);
      for (String rel : link.getRels())
      {
         linksByRelationship.put(rel, link);
      }
      if (link.getTitle() != null) linksByTitle.put(link.getTitle(), link);
      return this;
   }

   public Link getLinkByTitle(String title)
   {
      return linksByTitle.get(title);
   }

   public Link getLinkByRelationship(String rel)
   {
      return linksByRelationship.get(rel);
   }

   /**
    * Index of links by relationship "rel" or "rev"
    *
    * @return
    */
   public Map<String, Link> getLinksByRelationship()
   {
      return linksByRelationship;
   }

   /**
    * Index of links by title
    *
    * @return
    */
   public Map<String, Link> getLinksByTitle()
   {
      return linksByTitle;
   }

   /**
    * All the links defined
    *
    * @return
    */
   public List<Link> getLinks()
   {
      return links;
   }

}


text:
package com.gemstone.gemfire.internal.cache.wan.offheap;

import com.gemstone.gemfire.internal.cache.wan.parallel.ParallelWANPersistenceEnabledGatewaySenderDUnitTest;

@SuppressWarnings("serial")
public class ParallelWANPersistenceEnabledGatewaySenderOffHeapDUnitTest extends
    ParallelWANPersistenceEnabledGatewaySenderDUnitTest {

  public ParallelWANPersistenceEnabledGatewaySenderOffHeapDUnitTest(String name) {
    super(name);
  }

  @Override
  public boolean isOffHeap() {
    return true;
  }

}

redpajama_set_name: RedPajamaGithub


text:
VAGRANT_CORE_FOLDER=$(echo "$1")
export "DEBIAN_FRONTEND=noninteractive"
# Making a world a bit more perfect in order to continue provision due to possible locks...
sudo killall apt-get
sudo killall dpkg
sudo dpkg --configure -a

# CIBox ad.
cat "${VAGRANT_CORE_FOLDER}/shell/self-promotion.txt"

OS=$(/bin/bash "${VAGRANT_CORE_FOLDER}/shell/os-detect.sh" ID)
CODENAME=$(/bin/bash "${VAGRANT_CORE_FOLDER}/shell/os-detect.sh" CODENAME)

if [[ ! -d /.puphpet-stuff ]]; then
    mkdir /.puphpet-stuff

    echo "${VAGRANT_CORE_FOLDER}" > "/.puphpet-stuff/vagrant-core-folder.txt"

    echo "Created directory /.puphpet-stuff"
fi

if [[ ! -f /.puphpet-stuff/initial-setup-repo-update ]]; then
    if [ "${OS}" == 'debian' ] || [ "${OS}" == 'ubuntu' ]; then
        echo "Running initial-setup apt-get update"
        apt-get update >/dev/null
        touch /.puphpet-stuff/initial-setup-repo-update
        echo "Finished running initial-setup apt-get update"
    fi
fi

if [[ "${OS}" == 'ubuntu' && ("${CODENAME}" == 'lucid' || "${CODENAME}" == 'precise') && ! -f /.puphpet-stuff/ubuntu-required-libraries ]]; then
    echo 'Installing basic curl packages (Ubuntu only)'
    apt-get install -y libcurl3 libcurl4-gnutls-dev curl >/dev/null
    echo 'Finished installing basic curl packages (Ubuntu only)'

    touch /.puphpet-stuff/ubuntu-required-libraries
fi


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>jQuery Flip Image</title>

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">

jQuery Flip Image

transform: rotateY(90deg)

								<button type="button" class="btn btn-primary btn-lg" id="btn-flip-1">Flip!</button>

transform: rotateX(90deg)

								<button type="button" class="btn btn-primary btn-lg" id="btn-flip-2">Flip!</button>

transform: rotateY(90deg) rotateX(90deg)

								<button type="button" class="btn btn-primary btn-lg" id="btn-flip-3">Flip!</button>

See in action: Leodis Lager

Github homepage: https://github.com/project53/jquery-flip-image

© 2014 Project 53 Ltd, Code licensed under MIT


text:
package com.speedment.generator.standard.manager;

import com.speedment.common.codegen.model.Class;
import com.speedment.common.codegen.model.File;
import com.speedment.common.injector.Injector;
import com.speedment.generator.translator.AbstractEntityAndManagerTranslator;
import com.speedment.runtime.config.Table;

/**
 *
 * @author Emil Forslund
 */
public final class SqlAdapterTranslator extends AbstractEntityAndManagerTranslator<Class> {

    public SqlAdapterTranslator(Injector injector, Table table) {
        super(injector, table, Class::of);
    }

    @Override
    protected Class makeCodeGenModel(File file) {
        return newBuilder(file, getClassOrInterfaceName())
            .forEveryProject((intf, project) ->
                intf.public_()
                    .setSupertype(getSupport().generatedSqlAdapterType())
            )
            .build();
    }

    @Override
    protected String getJavadocRepresentText() {
        return "The SqlAdapter for every {@link " +
            getSupport().entityType().getTypeName() + "} entity.";
    }

    @Override
    protected String getClassOrInterfaceName() {
        return getSupport().sqlAdapterName();
    }
}


text:
NSString * const DekoButtonGalleryNotSaved = @"button-galle-";
NSString * const DekoButtonGallerySaved = @"button-gallf-";
NSString * const DekoButtonSave = @"button-save-";
NSString * const DekoButtonShareFront = @"button-sharer-";
NSString * const DekoButtonShareBack = @"button-sharel-";

NSString * const DekoSaveButtonSaveLabel = @"Save to Gallery";
NSString * const DekoSaveButtonRemoveLabel = @"Remove from Gallery";

const NSTimeInterval DekoAnimationDuration = 0.2;

@interface DekoMenuView () <DekoMenuButtonDelegate>
@property (nonatomic) UIView *baseContainer;
@property (nonatomic) UIView *shareContainer;
@property (nonatomic) DekoMenuButton *plusButton;
@property (nonatomic) DekoMenuButton *galleryButton;
@property (nonatomic) DekoMenuButton *shareButton;
@property (nonatomic) DekoMenuButton *twitterButton;
@property (nonatomic) DekoMenuButton *facebookButton;
@property (nonatomic) DekoMenuButton *emailButton;
@property (nonatomic) DekoMenuButton *photosButton;
@property (nonatomic) DekoMenuButton *imageCopyButton;
@property (nonatomic) NSString *deviceType;
@property (nonatomic, assign) BOOL shareMenuVisible;
@property (nonatomic) UILabel *tutorialGalleryLabel;
@property (nonatomic) UILabel *tutorialSaveLabel;
@property (nonatomic) UILabel *tutorialShareLabel;
@property (nonatomic) DekoCircleMenuView *baseMenuCircles;
@property (nonatomic) DekoCircleMenuView *shareMenuCircles;
@end

@implementation DekoMenuView

#pragma mark - Private

- (void)_plusButtonTouched:(id)sender
{
	[self.delegate menuViewPlusButtonTouched:self];
}

- (void)_galleryButtonTouched:(id)sender
{
	[self.delegate menuViewGalleryButtonTouched:self];
}

- (void)_shareButtonTouched:(id)sender
{
	[self.delegate menuViewShareButtonTouched:self];
}

- (void)_twitterButtonTouched:(id)sender
{
	[self.delegate menuView:self shareWithType:DekoShareTwitter];
}

- (void)_facebookButtonTouched:(id)sender
{
	[self.delegate menuView:self shareWithType:DekoShareFacebook];
}

- (void)_emailButtonTouched:(id)sender
{
	[self.delegate menuView:self shareWithType:DekoShareEmail];
}

- (void)_photosButtonTouched:(id)sender
{
	[self.delegate menuView:self shareWithType:DekoSharePhotos];
}

- (void)_copyButtonTouched:(id)sender
{
	[self.delegate menuView:self shareWithType:DekoShareCopy];
}

- (void)_IAPButtonTouched:(id)sender
{
	[self.delegate menuViewIAPButtonTouched:self];
}

- (void)_removeAllSubviewsFromView:(UIView *)view
{
	for (id subview in view.subviews)
	{
		[subview removeFromSuperview];
	}
}

#pragma mark - UIView

- (instancetype)initWithFrame:(CGRect)frame containerWidth:(CGFloat)containerWidth
{
    if ((self = [super initWithFrame:frame]))
	{
		self.backgroundColor = [UIColor clearColor];

		CGFloat length = MAX(frame.size.width, frame.size.height);
		CGRect rect = CGRectMake(CGRectGetMidX(frame) - (containerWidth / 2.0),
								 CGRectGetMidY(frame) - (length / 2.0),
								 containerWidth,
								 length);
		_baseContainer = [[UIView alloc] initWithFrame:rect];
		_baseContainer.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
		_baseContainer.backgroundColor = [UIColor clearColor];
		[self addSubview:_baseContainer];

		_shareContainer = [[UIView alloc] initWithFrame:AECGRectPlaceY(rect, rect.origin.y)];
		_shareContainer.autoresizingMask = _baseContainer.autoresizingMask;
		_shareContainer.backgroundColor = [UIColor clearColor];
    }

	return self;
}

- (void)_populateMenuWithProStatus:(BOOL)proPurchased tutorial:(BOOL)tutorial
{
	CGFloat circleSize = 0;
	CGFloat overlap = 0;
	CGFloat fontSize = 0;
	CGFloat circleAlpha = 0.8;
	CGFloat tutorialLabelHeight = 0;

	if (DekoGetCurrentDeviceType() == DekoDeviceTypeiPad)
	{
		circleSize = 120.0;
		overlap = 8.0;
		fontSize = 22;
		tutorialLabelHeight = fontSize * 3.0;
		self.deviceType = @"ipad";
	}
	else
	{
		circleSize = 90.0;
		overlap = 6.0;
		fontSize = 16;
		tutorialLabelHeight = floor(fontSize * 2.5);
		self.deviceType = @"iphone";
	}

	DekoCircleMenuView *baseCircles = [[DekoCircleMenuView alloc] initWithFrame:self.baseContainer.bounds];
	baseCircles.backgroundColor = [UIColor clearColor];
	baseCircles.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
	baseCircles.circleSize = circleSize;
	baseCircles.overlap = overlap;
	baseCircles.items = 3;
	baseCircles.alpha = circleAlpha;
	[self.baseContainer addSubview:baseCircles];
	self.baseMenuCircles = baseCircles;

	CGFloat landscapeOffset = (DekoGetCurrentDeviceType() == DekoDeviceTypeiPhone6Plus && !proPurchased) ? -20.0 : 0;

	DekoCircleMenuView *shareCircles = [[DekoCircleMenuView alloc] initWithFrame:AECGRectPlaceY(self.shareContainer.bounds, self.shareContainer.bounds.origin.y + landscapeOffset)];
	shareCircles.backgroundColor = baseCircles.backgroundColor;
	shareCircles.autoresizingMask = baseCircles.autoresizingMask;
	shareCircles.circleSize = circleSize;
	shareCircles.overlap = overlap;
	shareCircles.items = proPurchased ? 6 : 7;
	shareCircles.alpha = circleAlpha;
	[self.shareContainer addSubview:shareCircles];
	self.shareMenuCircles = shareCircles;

	UIFont *font = [self.localizationManager localizedFontWithSize:fontSize];

	DekoMenuButton *galleryButton = [DekoMenuButton buttonWithType:UIButtonTypeCustom];
	UIImage *galleryButtonImage = [UIImage imageNamed:[NSString stringWithFormat:@"%@%@", DekoButtonGalleryNotSaved, self.deviceType]];
	[galleryButton setImage:galleryButtonImage forState:UIControlStateNormal];
	galleryButton.frame = CGRectMake((self.baseContainer.bounds.size.width / 2.0) - ((galleryButtonImage.size.width / 2.0) - (overlap / 2.0)),
									 (self.baseContainer.bounds.size.height / 2.0) - (galleryButtonImage.size.height / 2.0),
									 galleryButtonImage.size.width - overlap,
									 galleryButtonImage.size.height);
	galleryButton.autoresizingMask = baseCircles.autoresizingMask;
	galleryButton.imageView.contentMode = UIViewContentModeCenter;
	galleryButton.tag = 2;
	galleryButton.delegate = self;
	[galleryButton addTarget:self action:@selector(_galleryButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
	[self.baseContainer addSubview:galleryButton];
	self.galleryButton = galleryButton;

	CGFloat offset = 10.0;
	CGRect tutorialGalleryLabelRect = CGRectMake(galleryButton.frame.origin.x,
												 galleryButton.frame.origin.y + galleryButton.bounds.size.height + offset,
												 galleryButton.bounds.size.width,
												 tutorialLabelHeight);
	self.tutorialGalleryLabel = [[UILabel alloc] initWithFrame:tutorialGalleryLabelRect];
	self.tutorialGalleryLabel.font = font;
	self.tutorialGalleryLabel.backgroundColor = [UIColor clearColor];
	self.tutorialGalleryLabel.textAlignment = NSTextAlignmentCenter;
	self.tutorialGalleryLabel.text = NSLocalizedString(@"Gallery", @"Tutorial, gallery button");
	self.tutorialGalleryLabel.textColor = [UIColor colorWithWhite:DekoBackgroundColor alpha:1.0];
	self.tutorialGalleryLabel.shadowColor = [UIColor colorWithWhite:0 alpha:0.8];
	self.tutorialGalleryLabel.shadowOffset = CGSizeMake(1.0, 1.0);
	self.tutorialGalleryLabel.hidden = !tutorial;
	[self.baseContainer addSubview:self.tutorialGalleryLabel];

	DekoMenuButton *plusButton = [DekoMenuButton buttonWithType:UIButtonTypeCustom];
	UIImage *plusButtonImage = [UIImage imageNamed:[NSString stringWithFormat:@"%@%@", DekoButtonSave, self.deviceType]];
	[plusButton setImage:plusButtonImage forState:UIControlStateNormal];
	plusButton.frame = CGRectMake(galleryButton.frame.origin.x - plusButtonImage.size.width + overlap,
								  galleryButton.frame.origin.y,
								  plusButtonImage.size.width - overlap,
								  plusButtonImage.size.height);
	plusButton.autoresizingMask = baseCircles.autoresizingMask;
	plusButton.imageView.contentMode = galleryButton.imageView.contentMode;
	plusButton.tag = 1;
	plusButton.delegate = self;
	[plusButton addTarget:self action:@selector(_plusButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
	[self.baseContainer addSubview:plusButton];
	self.plusButton = plusButton;

	CGRect tutorialSaveLabelRect = CGRectMake(plusButton.frame.origin.x,
											  tutorialGalleryLabelRect.origin.y,
											  plusButton.bounds.size.width,
											  tutorialGalleryLabelRect.size.height);
	self.tutorialSaveLabel = [[UILabel alloc] initWithFrame:tutorialSaveLabelRect];
	self.tutorialSaveLabel.font = font;
	self.tutorialSaveLabel.backgroundColor = self.tutorialGalleryLabel.backgroundColor;
	self.tutorialSaveLabel.textAlignment = self.tutorialGalleryLabel.textAlignment;
	self.tutorialSaveLabel.textColor = self.tutorialGalleryLabel.textColor;
	self.tutorialSaveLabel.numberOfLines = 0;
	self.tutorialSaveLabel.lineBreakMode = NSLineBreakByWordWrapping;
	self.tutorialSaveLabel.shadowColor = self.tutorialGalleryLabel.shadowColor;
	self.tutorialSaveLabel.shadowOffset = self.tutorialGalleryLabel.shadowOffset;
	self.tutorialSaveLabel.hidden = self.tutorialGalleryLabel.hidden;
	[self.baseContainer addSubview:self.tutorialSaveLabel];
	[self _updateTutorialSaveLabelWithSaveStatus:NO];

	DekoMenuButton *shareButton = [DekoMenuButton buttonWithType:UIButtonTypeCustom];
	UIImage *shareButtonImage = [UIImage imageNamed:[NSString stringWithFormat:@"%@%@", DekoButtonShareFront, self.deviceType]];
	[shareButton setImage:shareButtonImage forState:UIControlStateNormal];
	shareButton.frame = CGRectMake(galleryButton.frame.origin.x + galleryButton.frame.size.width,
								   galleryButton.frame.origin.y,
								   shareButtonImage.size.width - overlap,
								   shareButtonImage.size.height);
	shareButton.autoresizingMask = baseCircles.autoresizingMask;
	shareButton.imageView.contentMode = galleryButton.imageView.contentMode;
	shareButton.tag = 3;
	shareButton.delegate = self;
	[shareButton addTarget:self action:@selector(_shareButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
	[self.baseContainer addSubview:shareButton];
	self.shareButton = shareButton;

	CGRect tutorialShareLabelRect = CGRectMake(shareButton.frame.origin.x,
											   tutorialGalleryLabelRect.origin.y,
											   shareButton.bounds.size.width,
											   tutorialGalleryLabelRect.size.height);
	self.tutorialShareLabel = [[UILabel alloc] initWithFrame:tutorialShareLabelRect];
	self.tutorialShareLabel.font = font;
	self.tutorialShareLabel.backgroundColor = self.tutorialGalleryLabel.backgroundColor;
	self.tutorialShareLabel.textAlignment = self.tutorialGalleryLabel.textAlignment;
	self.tutorialShareLabel.text = NSLocalizedString(@"Share and Export", @"Tutorial, share and export");
	self.tutorialShareLabel.textColor = self.tutorialGalleryLabel.textColor;
	self.tutorialShareLabel.shadowColor = self.tutorialGalleryLabel.shadowColor;
	self.tutorialShareLabel.shadowOffset = self.tutorialGalleryLabel.shadowOffset;
	self.tutorialShareLabel.numberOfLines = self.tutorialSaveLabel.numberOfLines;
	self.tutorialShareLabel.lineBreakMode = self.tutorialSaveLabel.lineBreakMode;
	self.tutorialShareLabel.hidden = self.tutorialGalleryLabel.hidden;
	[self.baseContainer addSubview:self.tutorialShareLabel];

	DekoMenuButton *backButton = [DekoMenuButton buttonWithType:UIButtonTypeCustom];
	UIImage *backButtonImage = [UIImage imageNamed:[NSString stringWithFormat:@"%@%@", DekoButtonShareBack, self.deviceType]];
	[backButton setImage:backButtonImage forState:UIControlStateNormal];
	backButton.frame = AECGRectPlaceY(plusButton.frame, plusButton.frame.origin.y + landscapeOffset);
	backButton.autoresizingMask = plusButton.autoresizingMask;
	backButton.imageView.contentMode = galleryButton.imageView.contentMode;
	backButton.tag = 1;
	backButton.delegate = self;
	[backButton addTarget:self action:@selector(_shareButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
	[self.shareContainer addSubview:backButton];

	DekoMenuButton *twitterButton = [DekoMenuButton buttonWithType:UIButtonTypeCustom];
	[twitterButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
	[twitterButton setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
	twitterButton.titleLabel.font = font;
	twitterButton.titleLabel.numberOfLines = 0;
	twitterButton.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
	twitterButton.titleLabel.textAlignment = NSTextAlignmentCenter;
	twitterButton.frame = AECGRectPlaceY(galleryButton.frame, galleryButton.frame.origin.y + landscapeOffset);
	twitterButton.autoresizingMask = shareCircles.autoresizingMask;
	twitterButton.tag = 2;
	twitterButton.delegate = self;
	[twitterButton addTarget:self action:@selector(_twitterButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
	[self.shareContainer addSubview:twitterButton];
	self.twitterButton = twitterButton;

	DekoMenuButton *facebookButton = [DekoMenuButton buttonWithType:UIButtonTypeCustom];
	[facebookButton setTitleColor:[twitterButton titleColorForState:UIControlStateNormal] forState:UIControlStateNormal];
	[facebookButton setTitleColor:[twitterButton titleColorForState:UIControlStateHighlighted] forState:UIControlStateHighlighted];
	facebookButton.titleLabel.font = twitterButton.titleLabel.font;
	facebookButton.titleLabel.numberOfLines = twitterButton.titleLabel.numberOfLines;
	facebookButton.titleLabel.lineBreakMode = twitterButton.titleLabel.lineBreakMode;
	facebookButton.titleLabel.textAlignment = twitterButton.titleLabel.textAlignment;
	facebookButton.frame = AECGRectPlaceY(shareButton.frame, shareButton.frame.origin.y + landscapeOffset);
	facebookButton.autoresizingMask = shareButton.autoresizingMask;
	facebookButton.tag = 3;
	facebookButton.delegate = self;
	[facebookButton addTarget:self action:@selector(_facebookButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
	[self.shareContainer addSubview:facebookButton];
	self.facebookButton = facebookButton;

	DekoMenuButton *emailButton = [DekoMenuButton buttonWithType:UIButtonTypeCustom];
	[emailButton setTitleColor:[twitterButton titleColorForState:UIControlStateNormal] forState:UIControlStateNormal];
	[emailButton setTitleColor:[twitterButton titleColorForState:UIControlStateHighlighted] forState:UIControlStateHighlighted];
	emailButton.titleLabel.font = twitterButton.titleLabel.font;
	emailButton.titleLabel.numberOfLines = twitterButton.titleLabel.numberOfLines;
	emailButton.titleLabel.lineBreakMode = twitterButton.titleLabel.lineBreakMode;
	emailButton.titleLabel.textAlignment = twitterButton.titleLabel.textAlignment;
	emailButton.frame = CGRectMake(backButton.frame.origin.x,
								   backButton.frame.origin.y + backButton.frame.size.height - (overlap / 2.0),
								   backButton.frame.size.width,
								   backButton.frame.size.height - overlap);
	emailButton.autoresizingMask = backButton.autoresizingMask;
	emailButton.tag = 4;
	emailButton.delegate = self;
	[emailButton addTarget:self action:@selector(_emailButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
	[self.shareContainer addSubview:emailButton];
	self.emailButton = emailButton;

	DekoMenuButton *photosButton = [DekoMenuButton buttonWithType:UIButtonTypeCustom];
	[photosButton setTitleColor:[twitterButton titleColorForState:UIControlStateNormal] forState:UIControlStateNormal];
	[photosButton setTitleColor:[twitterButton titleColorForState:UIControlStateHighlighted] forState:UIControlStateHighlighted];
	photosButton.titleLabel.font = twitterButton.titleLabel.font;
	photosButton.titleLabel.numberOfLines = twitterButton.titleLabel.numberOfLines;
	photosButton.titleLabel.lineBreakMode = twitterButton.titleLabel.lineBreakMode;
	photosButton.titleLabel.textAlignment = twitterButton.titleLabel.textAlignment;
	photosButton.frame = CGRectMake(galleryButton.frame.origin.x,
									emailButton.frame.origin.y,
									galleryButton.frame.size.width,
									emailButton.frame.size.height);
	photosButton.autoresizingMask = backButton.autoresizingMask;
	photosButton.tag = 5;
	photosButton.delegate = self;
	[photosButton addTarget:self action:@selector(_photosButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
	[self.shareContainer addSubview:photosButton];
	self.photosButton = photosButton;

	DekoMenuButton *copyButton = [DekoMenuButton buttonWithType:UIButtonTypeCustom];
	[copyButton setTitleColor:[twitterButton titleColorForState:UIControlStateNormal] forState:UIControlStateNormal];
	[copyButton setTitleColor:[twitterButton titleColorForState:UIControlStateHighlighted] forState:UIControlStateHighlighted];
	copyButton.titleLabel.font = twitterButton.titleLabel.font;
	copyButton.titleLabel.numberOfLines = twitterButton.titleLabel.numberOfLines;
	copyButton.titleLabel.lineBreakMode = twitterButton.titleLabel.lineBreakMode;
	copyButton.titleLabel.textAlignment = twitterButton.titleLabel.textAlignment;
	copyButton.frame = CGRectMake(shareButton.frame.origin.x,
								  emailButton.frame.origin.y,
								  shareButton.frame.size.width,
								  emailButton.frame.size.height);
	copyButton.autoresizingMask = backButton.autoresizingMask;
	copyButton.tag = 6;
	copyButton.delegate = self;
	[copyButton addTarget:self action:@selector(_copyButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
	[self.shareContainer addSubview:copyButton];
	self.imageCopyButton = copyButton;

	if (!proPurchased)
	{
		DekoMenuButton *unlockHighQualityButton = [DekoMenuButton buttonWithType:UIButtonTypeCustom];
		[unlockHighQualityButton setTitle:NSLocalizedString(@"High\nquality export", @"Unlock high quality export button title") forState:UIControlStateNormal];
		[unlockHighQualityButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
		unlockHighQualityButton.titleLabel.font = twitterButton.titleLabel.font;
		unlockHighQualityButton.titleLabel.numberOfLines = twitterButton.titleLabel.numberOfLines;
		unlockHighQualityButton.titleLabel.lineBreakMode = twitterButton.titleLabel.lineBreakMode;
		unlockHighQualityButton.titleLabel.textAlignment = twitterButton.titleLabel.textAlignment;
		unlockHighQualityButton.frame = CGRectMake(photosButton.frame.origin.x,
												   photosButton.frame.origin.y + photosButton.frame.size.height,
												   photosButton.frame.size.width,
												   photosButton.frame.size.height);
		unlockHighQualityButton.autoresizingMask = photosButton.autoresizingMask;
		unlockHighQualityButton.tag = 7;
		unlockHighQualityButton.delegate = self;
		[unlockHighQualityButton addTarget:self action:@selector(_IAPButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
		[self.shareContainer addSubview:unlockHighQualityButton];
	}

	[self updateShareButtonsWithBusyStateForShareType:DekoShareNone];
}

- (void)_updateTutorialSaveLabelWithSaveStatus:(BOOL)saved
{
	if (saved)
	{
		self.tutorialSaveLabel.text = NSLocalizedString(@"Remove from Gallery", @"Tutorial, remove from gallery");
	}
	else
	{
		self.tutorialSaveLabel.text = NSLocalizedString(@"Save to Gallery", @"Tutorial, save to gallery");
	}
}

- (NSString *)_busyStringForShareType:(DekoShareType)shareType
{
	if (shareType == DekoSharePhotos)
	{
		return NSLocalizedString(@"Saving", @"Save to photos button title, busy state");
	}
	else if (shareType == DekoShareCopy)
	{
		return NSLocalizedString(@"Copying", @"Copy button title, busy state");
	}
	else
	{
		return NSLocalizedString(@"Preparing", @"Generic share button title, busy state");
	}
}

#pragma mark - Public

- (void)setupWithDelegate:(id)delegate purchased:(BOOL)purchased tutorial:(BOOL)tutorial
{
	AEAssert(delegate != nil);

	self.delegate = delegate;

	[self _populateMenuWithProStatus:purchased tutorial:tutorial];
}

- (void)updateMenuWithSaveStatus:(BOOL)saved tutorial:(BOOL)tutorial animated:(BOOL)animated
{
	self.tutorialGalleryLabel.hidden = !tutorial;
	self.tutorialSaveLabel.hidden = !tutorial;
	self.tutorialShareLabel.hidden = !tutorial;

	void (^animationBlock)(void) = ^{
		if (saved)
		{
			self.plusButton.transform = CGAffineTransformRotate(CGAffineTransformIdentity, M_PI_4);
		}
		else
		{
			self.plusButton.transform = CGAffineTransformIdentity;
		}
	};

	void (^animationCompletionBlock)(BOOL) = ^(BOOL finished) {
		if (saved)
		{
			[self.galleryButton setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@%@", DekoButtonGallerySaved, self.deviceType]] forState:UIControlStateNormal];
		}
		else
		{
			[self.galleryButton setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@%@", DekoButtonGalleryNotSaved, self.deviceType]] forState:UIControlStateNormal];
		}

		[self _updateTutorialSaveLabelWithSaveStatus:saved];
	};

	if (animated)
	{
		[UIView animateWithDuration:DekoAnimationDuration animations:animationBlock completion:animationCompletionBlock];
	}
	else
	{
		animationBlock();
		animationCompletionBlock(YES);
	}
}

- (void)refreshShareMenuWithPurchaseStatus:(BOOL)purchased tutorial:(BOOL)tutorial
{
	[self _removeAllSubviewsFromView:self.baseContainer];
	[self _removeAllSubviewsFromView:self.shareContainer];
	[self _populateMenuWithProStatus:purchased tutorial:tutorial];
}

- (void)flipMenu
{
	if (self.shareMenuVisible)
	{
		self.baseContainer.frame = self.shareContainer.frame;

		[UIView transitionFromView:self.shareContainer toView:self.baseContainer duration:UINavigationControllerHideShowBarDuration * 2.0 options:UIViewAnimationOptionTransitionFlipFromRight completion:^(BOOL finished) {
			self.shareMenuVisible = NO;
		}];
	}
	else
	{
		self.shareContainer.frame = self.baseContainer.frame;

		[UIView transitionFromView:self.baseContainer toView:self.shareContainer duration:UINavigationControllerHideShowBarDuration * 2.0 options:UIViewAnimationOptionTransitionFlipFromRight completion:^(BOOL finished) {
			self.shareMenuVisible = YES;
		}];
	}
}

- (void)updateShareButtonsWithBusyStateForShareType:(DekoShareType)shareType
{
	if (self.localizationManager.useSinaWeibo)
	{
		[self.twitterButton setTitle:@"新浪微博" forState:UIControlStateNormal];
	}
	else
	{
		[self.twitterButton setTitle:NSLocalizedString(@"Twitter", @"Share to Twitter button title") forState:UIControlStateNormal];
	}

	[self.facebookButton setTitle:NSLocalizedString(@"Facebook", @"Share to Facebook button title") forState:UIControlStateNormal];
	[self.emailButton setTitle:NSLocalizedString(@"Email", @"Share by email button title") forState:UIControlStateNormal];
	[self.photosButton setTitle:NSLocalizedString(@"Save to photos", @"Save to photos button title") forState:UIControlStateNormal];
	[self.imageCopyButton setTitle:NSLocalizedString(@"Copy", @"Copy button title") forState:UIControlStateNormal];

	if (shareType == DekoShareTwitter)
	{
		[self.twitterButton setTitle:[self _busyStringForShareType:shareType] forState:UIControlStateNormal];
	}
	else if (shareType == DekoShareFacebook)
	{
		[self.facebookButton setTitle:[self _busyStringForShareType:shareType] forState:UIControlStateNormal];
	}
	else if (shareType == DekoShareEmail)
	{
		[self.emailButton setTitle:[self _busyStringForShareType:shareType] forState:UIControlStateNormal];
	}
	else if (shareType == DekoSharePhotos)
	{
		[self.photosButton setTitle:[self _busyStringForShareType:shareType] forState:UIControlStateNormal];
	}
	else if (shareType == DekoShareCopy)
	{
		[self.imageCopyButton setTitle:[self _busyStringForShareType:shareType] forState:UIControlStateNormal];
	}
}

#pragma mark - DekoMenuButtonDelegate

- (void)menuButton:(DekoMenuButton *)menuButton highlighted:(BOOL)highlighted
{
	NSInteger selected = -1;
	if (highlighted)
	{
		selected = menuButton.tag;
	}

	if (self.shareMenuVisible)
	{
		self.shareMenuCircles.selected = selected;
	}
	else
	{
		self.baseMenuCircles.selected = selected;
	}
}

@end


text: The code for the Django base http://debian.org.il website


text:
require "active_model"
require "active_support/core_ext/module/attribute_accessors"
require "cgi"
require "rotp"
require "active_model/one_time_password"

ActiveSupport.on_load(:active_record) do
  include ActiveModel::OneTimePassword
end


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using AIT.Taskboard.Application.Controls;
using Microsoft.Reporting.WinForms;

namespace AIT.Taskboard.Application.UIInteraction
{
    /// <summary>
    /// Handles multitouch events performed on the taskboard and on workitems.
    /// </summary>
    /// <remarks>
    /// CLASS IS DEPRECATED. DO NOT USE!
    /// </remarks>
    [Obsolete("Not used anymore",true)]
    public class MultiTouchManager
    {
        #region Fields

        // Represents a touch point on the screen.
        // The key identifies the finger and the value the position of the finger on the screen.
        // Must be static because any listening multitouch manager may receive TouchUp calls,
        // depending on the position of the fingers on the UI.
        // The multitouch manager who registers the first TouchDown event is granted exclusive
        // write privileges of touch points until end of all active touch operations.
        private static DictionaryEntry _firstPoint = new DictionaryEntry(null, null);
        private static DictionaryEntry _secondPoint = new DictionaryEntry(null, null);

        // These points are the last points captured by touch move events. They are necessary
        // to calculate if an event will be processed or if its data delta is to low and
        // therefore would only cost cpu time.
        private TouchPoint _lastCapturedFirstPoint;
        private TouchPoint _lastCapturedSecondPoint;

        // Holds the event arguments while a move event is processed since a lot of
        // methods require these arguments.
        private TouchEventArgs _currentMoveEventArgs;

        // Minimum distance a touch point (finger) has to be moved before performing any
        // calculations or updating the UI.
        private const int UiUpdateOffset = 3;

        // Sets the distance a touch point has to move to double the size of a workitem.
        // private const int AbsoluteZoomMultiplier = 100;

        // Sets the distance a touch point has to move before a drag and drop action is
        // initialized.
        private const int DragAndDropOffset = 50;

        // Is true while a drag and drop and drop action of a workitem is in process.
        private bool _isDragAndDropAction;

        // max capacitiy of queue
        private const int MaxQueueLength = 10;

        // store last x-values of first finger in queue
        private readonly Queue _fingerOnePositions = new Queue(MaxQueueLength);

        // store last x-values of second finger in separate queue
        private readonly Queue _fingerTwoPositions = new Queue(MaxQueueLength);

        // store delta values in queue
        private Queue _deltaQueue = new Queue(MaxQueueLength);

        // use min max values to supress speeding or jumping zoom
        private const double MinimumDelta = 0.8;
        private const double MaximumDelta = 1.2;

        // Percentage of necessary valid delta values in queue
        private const double ValidityTresholdValue = 0.7;

        // Owner of all multitouch events.
        private readonly IInputElement _owner;

        // Holds the multitouch manager currently performing any actions.
        private static MultiTouchManager _operator;

        /// <summary>
        /// Returns the state of multitouch zoom.
        /// </summary>
        /// <remarks>
        /// Returns true while a multitouch zoom operation is in process and false if
        /// such an operation is performing. Can be used to prevent common UI update
        /// procedures to cease while zooming.
        /// </remarks>
        public static bool IsZooming { get; private set; }

        #endregion

        #region Events

        public static event EventHandler TaskboardZoomEnded;
        public static event EventHandler WorkitemZoomended;

        public static void InvokeWorkitemZoomended(EventArgs e)
        {
            EventHandler handler = WorkitemZoomended;
            if (handler != null) handler(null, e);
        }

        public void InvokeTaskboardZoomEnded(EventArgs e)
        {
            EventHandler handler = TaskboardZoomEnded;
            if (handler != null) handler(this, e);
        }

        #endregion

        /// <summary>
        /// Creates a new instance of the <see cref="MultiTouchManager"/> class.
        /// </summary>
        /// <param name="owner">Owner of all multi touch events.</param>
        public MultiTouchManager(IInputElement owner)
        {
            _owner = owner;
            _isDragAndDropAction = false;
            _lastCapturedFirstPoint = null;
            _lastCapturedSecondPoint = null;
            _currentMoveEventArgs = null;
        }

        #region TouchDown

        /// <summary>
        /// Processes touchdown events.
        /// </summary>
        /// <param name="e">Touch down event arguments.</param>
        /// <returns>State of event handling.</returns>
        public bool ProcessTouchDown(TouchEventArgs e)
        {
            // If more than two touchpoints are active ignore any additional touch points.
            if (_firstPoint.Key != null && _secondPoint.Key != null)
            {
                return true;
            }

            // If no other multitouch manager is currently working or we are the working one continue.
            if(_operator == null || _operator == this)
            {
                // If there is no current working multitouch manager assign ourself as the working one.
                if (_operator == null)
                {
                    _operator = this;
                }

                // Register touchpoints and store them.
                if (RegisterTouchPoints(e)) return false;
            }
            else
            {
                return e.Handled;
            }

            // This case should never happen if called correctly:
            // We are working and the touch point we get from the agruments is neither the first
            // nor the second of two maximal touch points. So we ignore this event.
            return true;
        }

        /// <summary>
        /// Registers the touchpoints and stores them in the key fields.
        /// </summary>
        /// <param name="e">Returns value for the handled parameter of the event arguments.</param>
        /// <returns>Event handled sate.</returns>
        private bool RegisterTouchPoints(TouchEventArgs e)
        {
            // Register second finger down and save it.
            if (_firstPoint.Key != null && e.TouchDevice.Id != (int)_firstPoint.Key && _secondPoint.Key == null && !_isDragAndDropAction)
            {
                //Disable Scrolling
                DisableTasboardScrolling();

                _secondPoint = new DictionaryEntry(e.TouchDevice.Id, e.GetTouchPoint(_owner));
                AddPositionToQueue(_fingerTwoPositions, ((TouchPoint)_secondPoint.Value).Position.X);

                // Two finger operations are always zoom operations.
                IsZooming = true;

                // This event cannot be a click and therefor is considered handled.
                return true;
            }

            // Register first finger down an save it.
            if (_firstPoint.Key == null)
            {
                //Enable Scrolling
                EnableTasboardScrolling();

                _firstPoint = new DictionaryEntry(e.TouchDevice.Id, e.GetTouchPoint(_owner));
                AddPositionToQueue(_fingerOnePositions, ((TouchPoint)_firstPoint.Value).Position.X);

                // This event cannot be a click and therefor is considered handled.
                return true;
            }

            return false;
        }

        #region TasboardScrolling

        /// <summary>
        /// Enables TaskboardsScrolling if current owner is Taskboardcontrol
        /// </summary>
        private void EnableTasboardScrolling()
        {
            if (OwnerIsTasbboardControl)
            {
                (_owner as TaskboardControl).EnableTaskboardScrolling();
            }
        }

        /// <summary>
        /// Disables TaskboardsScrolling if current owner is Taskboardcontrol
        /// </summary>
        private void DisableTasboardScrolling()
        {
            if (OwnerIsTasbboardControl)
            {
                (_owner as TaskboardControl).DisableTaskboardScrolling();
            }
        }

        #endregion

        #endregion

        #region TouchUp

        /// <summary>
        /// Processes touchup events.
        /// </summary>
        /// <param name="e">Touch up event arguments.</param>
        /// <returns>State of event handling.</returns>
        public bool ProcessTouchUp(TouchEventArgs e)
        {
            // If no valid touch point is stored mark the event as handled and return.
            // This case should never occur but better be save than sorry.
            if (_firstPoint.Key == null && _secondPoint.Key == null) return true;

            // If no operator exists return.
            // This event should never occur, too. But then again ...
            if (_operator == null) return e.Handled;

            // Unregister any released touch points from the storage.
            return UnregisterTouchPoints(e);
        }

        /// <summary>
        /// Unregisters touchpoints from the storage.
        /// </summary>
        /// <param name="e">Touch event arguments.</param>
        /// <returns>Handled state of the event arguments.</returns>
        private bool UnregisterTouchPoints(TouchEventArgs e)
        {
            bool handledState = false;

            // Register release of first finger and kill touch point.
            if (_firstPoint.Key != null && e.TouchDevice.Id == (int)_firstPoint.Key)
            {
                _firstPoint = new DictionaryEntry(null, null);
                _isDragAndDropAction = false;
                _fingerOnePositions.Clear();
            }

            // Register release of second finger and kill touch point.
            if (_secondPoint.Key != null && e.TouchDevice.Id == (int)_secondPoint.Key)
            {
                _secondPoint = new DictionaryEntry(null, null);
                _fingerTwoPositions.Clear();
                handledState = true;
                IsZooming = false;
                if(OwnerIsTasbboardControl) InvokeTaskboardZoomEnded(null);
                else if(OwnerIsWorkItemControl) InvokeWorkitemZoomended(null);
            }

            // If we do not have any active touch points we are done working and unregister as
            // currently working multitouch manager to enable the processing of further touch events.
            if (_firstPoint.Key == null && _secondPoint.Key == null)
            {
                _operator = null;
            }

            // Clear queue for delta values, it is only relevant for 2fingergestures, so it is obsolete
            // if a finger, no matter which one, is released
            _deltaQueue.Clear();

            return handledState;
        }

        #endregion

        #region TouchMove

        /// <summary>
        /// Processes touch move events.
        /// </summary>
        /// <param name="e">Touch move event arguments.</param>
        /// <returns>State of event handling.</returns>
        public bool ProcessTouchMove(TouchEventArgs e)
        {
            // This touch move event is related to a drag and drop action we already have identified, we can quit here
            // since drag and drop is handled somewhere else.
            if (_isDragAndDropAction) return PerformSaveReturn();

            // Store event arguments for fast access by processing methods.
            _currentMoveEventArgs = e;

            // TouchMove events are fired as long as a finger is on the touchpanel, even while not moving at all.
            // If there is no actual movement ignore the event.
            // Not filtering this will cause massive performance losses since this event is fired over 100 times a second.
            if(CatchInvalidMoveEvents()) return PerformSaveReturn(); // true

            // If we are not responsible for the move event ignore it.)
            if (_operator == null || _operator != this) return PerformSaveReturn(); // true

            // If there is only one finger on the touch panel it might be a drag and drop action.
            // However drag and drop is only fired if an offset of movement is exceeded.
            if(RegisterDragAndDropAction()) return PerformSaveReturn();

            // Do the actual zoom.
            PerformZoomOperation();

            // This case should never happen. All events should have been handled by now.
            return true;
        }

        /// <summary>
        /// Returns true if two touchpoints are active, otherwise false.
        /// This is used to prevent any kind of drag and drop action
        /// while a zoom action is active.
        /// </summary>
        /// <returns>Returns true if two touch poins are active.</returns>
        private static bool  PerformSaveReturn()
        {
            if (_firstPoint.Key != null && _secondPoint.Key != null) return true;

            return false;
        }

        /// <summary>
        /// Performs the zooming operation on workitems or the taskboard pane.
        /// </summary>
        private void PerformZoomOperation()
        {
            // Only perform any actions if we have a two finger touch event.
            if (_firstPoint.Key == null || _secondPoint.Key == null) return;

            // If we are not the currently working multitouch manager
            // do not do anything.
            if (_operator != this) return;

            double delta = 0;
            bool hasChanged = false;

            // If the first finger has been moved save it after delta calculation.
            // and finger has moved
            if ((_currentMoveEventArgs.TouchDevice.Id == (int)_firstPoint.Key) && (!_firstPoint.Value.Equals(_currentMoveEventArgs.GetTouchPoint(_owner))))
            {
                AddPositionToQueue(_fingerTwoPositions, ((TouchPoint) _firstPoint.Value).Position.X);

                //remember previous position of current finger
                var prev = (TouchPoint)_firstPoint.Value;

                //refresh current position
                _firstPoint.Value = _currentMoveEventArgs.GetTouchPoint(_owner);

                if (!QueueMismatch(_fingerOnePositions))
                {
                    //calculate delta for position change
                    delta = GetTouchPositionDelta(_secondPoint.Value as TouchPoint, prev, _firstPoint.Value as TouchPoint);
                    //add delta to delta queue
                    if (delta > 0) AddPositionToQueue(_deltaQueue, delta);

                    //report change
                    hasChanged = true;
                }
            }

            // if the second finger has been moved save it after delta calculation.
            if ((_currentMoveEventArgs.TouchDevice.Id == (int)_secondPoint.Key) && (!_firstPoint.Value.Equals(_currentMoveEventArgs.GetTouchPoint(_owner))))
            {
               AddPositionToQueue(_fingerTwoPositions, ((TouchPoint) _secondPoint.Value).Position.X);

                //remember previous position of current finger
                var prev = (TouchPoint)_secondPoint.Value;

                //refresh current position
                _secondPoint.Value = _currentMoveEventArgs.GetTouchPoint(_owner);

                if (!QueueMismatch(_fingerTwoPositions))
                {
                    //calculate delta for position change
                    delta = GetTouchPositionDelta(_firstPoint.Value as TouchPoint, prev, _secondPoint.Value as TouchPoint);
                    if (delta > 0) AddPositionToQueue(_deltaQueue, delta);

                    //report change
                    hasChanged = true;
                }
            }

            // If we have a valid delta, use it to change the scale of the workitem.
            if (hasChanged && delta > 0)
            {
                //supress errors by using average values from delta queue
                delta = GetCumulativeDelta();
                if (delta > 0) ScaleUiElement(delta);
            }
        }

        /// <summary>
        /// Returns the average delta of growing values (>1) and shrinking values (smaller than 1 and greater than 0)
        /// if the percentage of deltas in queue is greater or equal the ValidityTresholdValue.
        ///
        /// Returns 0 if ValidityTresholdValue is exceeded or queue is empty
        /// </summary>
        /// <returns>cumulative delta</returns>
        private double GetCumulativeDelta()
        {
            IList growingValues = new List<double>();
            IList shrinkingValues = new List<double>();
            double avg = 0;

            //sort deltas for growing and shrinking values
            foreach (double queuedValue in _deltaQueue)
            {
                if (queuedValue > 1) growingValues.Add(queuedValue);
                else shrinkingValues.Add(queuedValue);
            }

            // if more growing values than necessary by ValidityTresholdValue
            // calculate average growing value
            if (growingValues.Count > _deltaQueue.Count * ValidityTresholdValue)
            {
                foreach (double growingValue in growingValues)
                {
                    avg += growingValue;
                }
                return avg / growingValues.Count;
            }

            // if more shrinking values than necessary by ValidityTresholdValue
            // calculate average shrinking value
            if (shrinkingValues.Count > _deltaQueue.Count * ValidityTresholdValue)
            {
                foreach (double shrinkingValue in shrinkingValues)
                {
                    avg += shrinkingValue;
                }
                return avg / shrinkingValues.Count;
            }

            return 0;
        }

        /// <summary>
        /// Register drag and drop actions.
        /// </summary>
        /// <returns>Returns true if the event initializes a drag and drop action.</returns>
        private bool RegisterDragAndDropAction()
        {
            // If there is only one finger on the touch panel it might be a drag and drop action.
            // However drag and drop is only fired if an offset of movement is exceeded.
            if (_firstPoint.Key != null && _secondPoint.Key == null)
            {
                // Only recognize the move action as a drag and drop event
                // if the touch point exceeds the dragdropoffset.
                if (ChangeIsRelevant(_firstPoint.Value as TouchPoint, _currentMoveEventArgs.GetTouchPoint(_owner), DragAndDropOffset))
                {
                    _isDragAndDropAction = true;
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// Identifies any invalid move events.
        /// </summary>
        /// <remarks>
        /// TouchMove events are fired continuously. To prevent performance peaks this method
        /// may identify movement event agruments which hold no new event data. These events
        /// can be dismissed without any further analysis.
        /// </remarks>
        /// <returns>Returns true if the event is invalid.</returns>
        private bool CatchInvalidMoveEvents()
        {
            TouchPoint p = _currentMoveEventArgs.GetTouchPoint(_owner);

            // Catches events which hold no new data.
            if (CatchMatchingEventArguments()) return true;

            // Calculate the actual delta between the current an the previous valid touch point.
            // If the delta does not match the defined offset for UI updates, dismiss the event.
            if (_firstPoint.Key != null && _currentMoveEventArgs.TouchDevice.Id == (int)_firstPoint.Key &&
                !ChangeIsRelevant(_firstPoint.Value as TouchPoint, p, UiUpdateOffset)) return true;

            if (_secondPoint.Key != null && _currentMoveEventArgs.TouchDevice.Id == (int)_secondPoint.Key &&
                !ChangeIsRelevant(_secondPoint.Value as TouchPoint, p, UiUpdateOffset)) return true;

            return false;
        }

        /// <summary>
        /// Catches event that have the same position as the previous catched event.
        /// </summary>
        /// <returns>Returns true if the current event position matches the previous event position.</returns>
        private bool CatchMatchingEventArguments()
        {
            if (_firstPoint.Key != null && _currentMoveEventArgs.TouchDevice.Id == (int)_firstPoint.Key)
            {
                if (_lastCapturedFirstPoint == null)
                {
                    _lastCapturedFirstPoint = _currentMoveEventArgs.GetTouchPoint(_owner);
                }
                else
                {
                    if (_lastCapturedFirstPoint.Position.Equals(_currentMoveEventArgs.GetTouchPoint(_owner).Position))
                    {
                        return true;
                    }
                    _lastCapturedFirstPoint = _currentMoveEventArgs.GetTouchPoint(_owner);
                }
            }

            if (_secondPoint.Key != null && _currentMoveEventArgs.TouchDevice.Id == (int)_secondPoint.Key)
            {
                if (_lastCapturedSecondPoint == null)
                {
                    _lastCapturedSecondPoint = _currentMoveEventArgs.GetTouchPoint(_owner);
                }
                else
                {
                    if (_lastCapturedSecondPoint.Position.Equals(_currentMoveEventArgs.GetTouchPoint(_owner).Position))
                    {
                        return true;
                    }
                    _lastCapturedSecondPoint = _currentMoveEventArgs.GetTouchPoint(_owner);
                }
            }

            return FilterInvalidTouchMoves();
        }

        /// <summary>
        /// Returns true if current _owner is of type TaskboardControl
        /// </summary>
        private bool OwnerIsTasbboardControl
        {
            get
            {
                if (_owner.GetType() == typeof(TaskboardControl))
                {
                    return true;
                }

                return false;
            }
        }

        /// <summary>
        /// Returns true if current _owner is of type ReportControl
        /// </summary>
        private bool OwnerIsReportControl
        {
            get
            {
                if (_owner.GetType() == typeof(ReportControl))
                {
                    return true;
                }

                return false;
            }
        }

        /// <summary>
        /// Returns true if current _owner is of type WorkItemControl
        /// </summary>
        private bool OwnerIsWorkItemControl
        {

            get
            {
                if (_owner.GetType() == typeof(WorkItemControl))
                {
                    return true;
                }

                return false;
            }

        }

        /// <summary>
        /// Check if an occuring touch event does have a delta in its
        /// coordinates.
        /// </summary>
        /// <returns>Returns true if the touch event does not contain any new information and
        /// false if the touch event has a valid delta.</returns>
        private bool FilterInvalidTouchMoves()
        {
            bool firstPoint = false;
            bool secondPoint = false;

            if (_firstPoint.Value != null)
            {
                if (((TouchPoint)(_firstPoint.Value)).Position == (_currentMoveEventArgs.GetTouchPoint(_owner).Position)) firstPoint = true;
            }
            else
            {
                firstPoint = true;
            }

            if (_secondPoint.Value != null)
            {
                if (((TouchPoint)(_secondPoint.Value)).Position == (_currentMoveEventArgs.GetTouchPoint(_owner).Position)) secondPoint = true;
            }
            else
            {
                secondPoint = true;
            }

            return (firstPoint && secondPoint);
        }

        /// <summary>
        /// Returns true if x or y values of current touchpoint related to old touchpoint
        /// exceed the given offset value.
        /// </summary>
        /// <param name="old">former touchpoint</param>
        /// <param name="curr">current touchpoint</param>
        /// <param name="offset">offset</param>
        /// <returns>true if offset exceeded</returns>
        private static bool ChangeIsRelevant(TouchPoint old, TouchPoint curr, int offset)
        {
            // absolute difference of x values
            double x = Math.Abs(old.Position.X - curr.Position.X);
            // absolute difference of x values
            double y = Math.Abs(old.Position.Y - curr.Position.Y);

            // compare with offset
            if (x > offset)
                return true;

            if (y > offset)
                return true;

            // current touchpoint is irrelavant
            return false;
        }

        /// <summary>
        /// Calculate the delta value using a reference point and the previous point
        /// depending on changes on x-axis and y-axis
        /// </summary>
        /// <param name="reference">referencePoint</param>
        /// <param name="previous">previousPoint</param>
        /// <param name="current">currentPoint</param>
        /// <returns>delta</returns>
        private static double GetTouchPositionDelta(TouchPoint reference, TouchPoint previous, TouchPoint current)
        {
            // calculate distance of points before movement
            double previousDistance = GetDistance(previous, reference);
            // calculate distance of points after movement
            double currentDistance = GetDistance(current, reference);

            //return value of changement, so called delta
            return currentDistance / previousDistance;
        }

        /// <summary>
        /// Returns the distance between Point 1 and Point 2.
        /// Calculated with pythagoras.
        /// </summary>
        /// <param name="p1">Point 1</param>
        /// <param name="p2">Point 2</param>
        /// <returns>distance between Point 1 and Point 2</returns>
        private static double GetDistance(TouchPoint p1, TouchPoint p2)
        {
            double x = p2.Position.X - p1.Position.X;
            double y = p2.Position.Y - p1.Position.Y;
            double hypothenuse = Math.Sqrt((x * x) + (y * y));
            return hypothenuse;
        }

        /// <summary>
        /// Scales the target UI element.
        /// </summary>
        /// <param name="delta">Scaling factor.</param>
        private void ScaleUiElement(double delta)
        {
            if (delta == 0) return;

            // exceeding minvalue?
            if (delta < MinimumDelta)
                delta = MinimumDelta;
            // exceeding maxvalue
            if (delta > MaximumDelta)
                delta = MaximumDelta;

            if (OwnerIsWorkItemControl)
            {
                ScaleWorkItem(delta);
                return;
            }

            if (OwnerIsTasbboardControl)
            {
                ((TaskboardControl)_owner).ZoomFactor *= delta;
                return;
            }

            if (OwnerIsReportControl)
            {
                ScaleReportItem(delta);
                return;
            }

            throw new ArgumentException(
                "This method only supports WorkItemControl and TaskBoardControl touch events.");
        }

        /// <summary>
        /// Rescales the workitems RenderTransform matrix to change its size.
        /// </summary>
        /// <param name="delta">Delta for transformation.</param>
        private void ScaleWorkItem(double delta)
        {
            if (delta == 0) return;

            var convertedOwner = _owner as WorkItemControl;

            if (convertedOwner == null)
            {
                throw new NullReferenceException("This method may only be called for scaling WorkItemControl objects.");
            }

            // Perform workitem zoom.

            // Use LayoutTransform instead of RenderTransform to automatically
            // align space between single workitems
            MatrixTransform renderTransformObject = convertedOwner.LayoutTransform as MatrixTransform;

            if (renderTransformObject != null)
            {
                Matrix matrix = renderTransformObject.Matrix;

                matrix.Scale(delta, delta);
                MatrixTransform newTransformObject = new MatrixTransform(matrix);
                ((WorkItemControl)_owner).LayoutTransform = newTransformObject;

            }
        }

        /// <summary>
        /// Rescales the reportitems RenderTransform matrix to change its size.
        /// </summary>
        /// <param name="delta">Delta for transformation.</param>
        private void ScaleReportItem(double delta)
        {
            if (delta == 0 || delta == 1) return;

            var convertedOwner = _owner as ReportControl;
            if(convertedOwner!=null)
            {
                ReportViewer rv = convertedOwner.viewerInstance;
                rv.ZoomMode = ZoomMode.Percent;
                int currZoomValue = rv.ZoomPercent;
                double newZoomValue = currZoomValue * delta;
                rv.ZoomPercent = (int) newZoomValue;

            }
            else
            {
                throw new NullReferenceException("This method may only be called for scaling ReportControl objects.");
            }
        }

        #region Store previous finger positions in queue to prevent flickering of workitems

        /// <summary>
        /// add current position as last item to given queue. if queue capacity is
        /// reached first item is automaticly removed.
        /// </summary>
        /// <param name="q">queue</param>
        /// <param name="position">position</param>
        private static void AddPositionToQueue(Queue q, double position)
        {
            //if max_capacity is reached remove first item
            if (q.Count.Equals(MaxQueueLength)) q.Dequeue();

            //append item
            q.Enqueue(position);
        }

        /// <summary>
        /// check given queue for mismatch. contained values must be
        /// constantly increasing or decreasing to be valid. mismatch
        /// is intepreted as invalid.
        /// </summary>
        /// <param name="q">queue to be checked for mismatch</param>
        /// <returns>true if no mismatch found</returns>
        private static bool QueueMismatch(Queue q)
        {
            bool incr = false;
            bool decr = false;

            //convert queue to array
            var arr = q.ToArray();
            //store first value as prev
            double prev = (double)arr[0];

            //if queue has more than one item
            for (int i = 1; i < q.Count; i++)
            {
                //compare current value with previous
                double curr = (double)arr[i];
                //if it is the first comparision, notice
                //if values are increasing or decreasing
                if (i == 1)
                {
                    if (prev < curr)
                    {
                        incr = true;
                    }
                    else
                    {
                        decr = true;
                    }
                }

                //if values in queue are increasing but current value
                //is smaller than previous -> report mismatch
                if ((incr) && (prev > curr))
                {
                    return true;
                }

                //if values in queue are decreasing but current value
                //is greater than previous -> report mismatch
                if ((decr) && (prev < curr))
                {
                    return true;
                }

                //no errors so far, store current value as prevoius and
                //go to next value in the queue
                prev = curr;
            }

            return false;
        }

        #endregion

        #endregion

        #region Gestures

        private bool panningInProgress = false;
        private long initialPanValue;
        private long currentPanningValue;

        private bool ZoomingInProgress = false;
        private long initialZoomValue;
        private long currentZoomValue;

        /// <summary>
        /// Process GestureZoomMessage
        /// </summary>
        /// <param name="gestureEventArgs"></param>
        public void ProcessGestureZoom(GestureEventArgs gestureEventArgs)
        {
            /*
             The first GID_ZOOM command message begins a zoom
             but does not cause any zooming. The second GID_ZOOM
             command triggers a zoom relative to the state
             contained in the first GID_ZOOM.
             */

            if (ZoomingInProgress)
            {
                // Process changing ZoomValue relative to first zoomvalue
                currentZoomValue = gestureEventArgs.Arguments;

            }
            else
            {
                // Notify 1st Zoom Message has been processed
                // and remember first zoomvalue
                ZoomingInProgress = true;
                initialZoomValue = gestureEventArgs.Arguments;
            }
        }

        /// <summary>
        /// Process GesturePanMessage
        /// </summary>
        /// <param name="gestureEventArgs"></param>
        public void ProcessGesturePan(GestureEventArgs gestureEventArgs)
        {
            if (panningInProgress)
            {

                /* TODO: implement panning
                 * */
            }
            else
            {
                // Notify 1st Zoom Message has been processed
                // and remember first zoomvalue
                panningInProgress = true;
                initialPanValue = gestureEventArgs.Arguments;
            }
        }

        /// <summary>
        /// Process GestureEndMessage, Finish Gesture, reset temporary values
        /// </summary>
        /// <param name="gestureEventArgs"></param>
        public void ProcessGestureEnd(GestureEventArgs gestureEventArgs)
        {
            if(ZoomingInProgress)
            {
                double val = (currentZoomValue - initialZoomValue);

                try
                {
                    ScaleReportItem(Math.Abs(val / initialZoomValue));
                }
                catch (Exception e)
                {
                    Debug.Print(e.Message + ", " + e.StackTrace);
                }

                ZoomingInProgress = false;
            }

            if(panningInProgress)
            {
                panningInProgress = false;
            }
        }

        /// <summary>
        /// Process GestureBeginMessage
        /// </summary>
        /// <param name="gestureEventArgs"></param>
        public void ProcessGestureBegin(GestureEventArgs gestureEventArgs)
        {
            // empty on purpose
        }

      #endregion
    }
}


text:
package org.tyrannyofheaven.bukkit.util.command;

import org.bukkit.ChatColor;

/**
 * Default UsageOptions for my plugins.
 *
 * @author zerothangel
 */
public class DefaultUsageOptions implements UsageOptions {

    /* (non-Javadoc)
     * @see org.tyrannyofheaven.bukkit.util.command.UsageOptions#getPrefix()
     */
    @Override
    public String getPreamble() {
        return ChatColor.GREEN.toString();
    }

    /* (non-Javadoc)
     * @see org.tyrannyofheaven.bukkit.util.command.UsageOptions#getPostamble()
     */
    @Override
    public String getPostamble() {
        return "";
    }

    /* (non-Javadoc)
     * @see org.tyrannyofheaven.bukkit.util.command.UsageOptions#getFlagEnd()
     */
    @Override
    public String getFlagEnd() {
        return ChatColor.AQUA + "]" + ChatColor.GREEN;
    }

    /* (non-Javadoc)
     * @see org.tyrannyofheaven.bukkit.util.command.UsageOptions#getFlagStart()
     */
    @Override
    public String getFlagStart() {
        return ChatColor.AQUA + "[" + ChatColor.GOLD;
    }

    /* (non-Javadoc)
     * @see org.tyrannyofheaven.bukkit.util.command.UsageOptions#getFlagValueEnd()
     */
    @Override
    public String getFlagValueEnd() {
        return ">";
    }

    /* (non-Javadoc)
     * @see org.tyrannyofheaven.bukkit.util.command.UsageOptions#getFlagValueStart()
     */
    @Override
    public String getFlagValueStart() {
        return " " + ChatColor.LIGHT_PURPLE + "<";
    }

    /* (non-Javadoc)
     * @see org.tyrannyofheaven.bukkit.util.command.UsageOptions#getParameterEnd(boolean)
     */
    @Override
    public String getParameterEnd(boolean optional) {
        if (optional)
            return "]" + ChatColor.GREEN;
        else
            return ">" + ChatColor.GREEN;
    }

    /* (non-Javadoc)
     * @see org.tyrannyofheaven.bukkit.util.command.UsageOptions#getParameterStart(boolean)
     */
    @Override
    public String getParameterStart(boolean optional) {
        if (optional)
            return ChatColor.AQUA + "[";
        else
            return ChatColor.LIGHT_PURPLE + "<";
    }

    /* (non-Javadoc)
     * @see org.tyrannyofheaven.bukkit.util.command.UsageOptions#getDescriptionDelimiter()
     */
    @Override
    public String getDescriptionDelimiter() {
        return " " + ChatColor.WHITE + "- ";
    }

    /* (non-Javadoc)
     * @see org.tyrannyofheaven.bukkit.util.command.UsageOptions#getVarargsEnd()
     */
    @Override
    public String getVarargsEnd() {
        return "]" + ChatColor.GREEN;
    }

    /* (non-Javadoc)
     * @see org.tyrannyofheaven.bukkit.util.command.UsageOptions#getVarargsStart()
     */
    @Override
    public String getVarargsStart() {
        return " " + ChatColor.AQUA + "[";
    }

}


text:
/*
* OID Registry
* (C) 1999-2007 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/

#ifndef BOTAN_OIDS_H__
#define BOTAN_OIDS_H__

#include <botan/asn1_oid.h>

namespace Botan {

namespace OIDS {

/**
* Register an OID to string mapping.
* @param oid the oid to register
* @param name the name to be associated with the oid
*/
BOTAN_DLL void add_oid(const OID& oid, const std::string& name);

/**
* See if an OID exists in the internal table.
* @param oid the oid to check for
* @return true if the oid is registered
*/
BOTAN_DLL bool have_oid(const std::string& oid);

/**
* Resolve an OID
* @param oid the OID to look up
* @return name associated with this OID
*/
BOTAN_DLL std::string lookup(const OID& oid);

/**
* Find the OID to a name. The lookup will be performed in the
* general OID section of the configuration.
* @param name the name to resolve
* @return OID associated with the specified name
*/
BOTAN_DLL OID lookup(const std::string& name);

/**
* Tests whether the specified OID stands for the specified name.
* @param oid the OID to check
* @param name the name to check
* @return true if the specified OID stands for the specified name
*/
BOTAN_DLL bool name_of(const OID& oid, const std::string& name);

}

}

#endif


text:
Order:

- pre.sh
- gui.sh
- applications.sh
- config.sh

remember to remove the fonts from the applications file and put it in its own


text:
<?php
echo _tag( 'h2' , __( 'Events' ) );
echo _open( 'ol.dm_calendar.clearfix' );
if ($calendar->getOption( 'showWeekDays' ))
{

	foreach ($calendar->getWeekDayNames() as $weekDayName)
	{
		echo _open( 'li.week-day' );
		echo $weekDayName;
		echo _close( 'li.week-day' );
	}
}
// preceding days
foreach ($calendar->getPreceedingDays() as $day)
{
	echo _open( 'li.day.prev' );

	if ($calendar->getOption( 'numberPadDays' ))
	{
		echo $day;
	}
	echo _close( 'li.day.prev' );
}

// month days
foreach ($calendar->getDays() as $day)
{
	$dayContent = '';
	$dayTagOptions = '.day';
	if ($calendar->isDayInThePast($day, true)) {
		$dayTagOptions .= '.past';
	} else {
		$dayTagOptions .= $calendar->isCurrentDay( $day ) ? '.current' : '';
	}
	$dayTagOptions .= $day->hasAnyEvents() ? '.events' : '';
	$dayTagOptions .= $day->hasManyEvents() ? '.multi' : '';
	$isFirstEvent = true;

	if (!$day->hasAnyEvents())
	{
		$dayContent .= $day;
	}
	foreach ($day->getEvents() as $event)
	{
		if ($event instanceof dmHtmlCalendarEventInterface)
		{
			$dayTagOptions .= $calendar->parseClasses( $event->getAdditionalDayClasses($day) );
			$dayContent .= $event->renderEvent( $day , $isFirstEvent );
		} else
		{
			$dayContent .= $day . $event;
		}
		if ($isFirstEvent)
		{
			$isFirstEvent = false;
		}
	}
	echo _open( 'li' . $dayTagOptions );
	echo $dayContent;
	echo _close( 'li.day' );
}

// following days
foreach ($calendar->getFollowingDays() as $day)
{
	echo _open( 'li.day.next' );
	if ($calendar->getOption( 'numberPadDays' ))
	{
		echo $day;
	}
	echo _close( 'li.day.next' );
}

echo _close( 'ol.dm_calendar' );


text:
code_user=node['virtuoso']['code_user']
code_group=node['virtuoso']['code_group']
code_dir=node['virtuoso']['code_dir']
install_dir=node['virtuoso']['install_dir']

apt_package "autoconf" do
  action :install
end
apt_package "automake" do
  action :install
end
apt_package "libtool" do
  action :install
end
apt_package "flex" do
  action :install
end
apt_package "bison" do
  action :install
end
apt_package "gperf" do
  action :install
end
apt_package "gawk" do
  action :install
end
apt_package "m4" do
  action :install
end
apt_package "make" do
  action :install
end
apt_package "openssl" do
  action :install
end
apt_package "libssl-dev" do
  action :install
end

git code_dir do
  repository "git://github.com/openlink/virtuoso-opensource.git"
  revision node['virtuoso']['revision']
  user code_user
  group code_group
  action :sync
end

bash 'compile' do
  user code_user
  group code_group
  cwd code_dir
  environment ({'CFLAGS' => node['virtuoso']['cflags']})
  code <<-EOH
    ./autogen.sh
    ./configure --prefix="#{install_dir}" --program-transform-name="s/isql/isql-v/"
    make
  EOH
  action :run
  notifies :run, "execute[install]"
end

execute "install" do
  cwd code_dir
  command 'make install'
  action :nothing
  notifies :run, "bash[add to /usr/bin]"
end

bash "add to /usr/bin" do
  code <<-EOH
    ln -s #{install_dir}/bin/virtuoso-t /usr/local/bin/virtuoso-t
    ln -s #{install_dir}/bin/isql-v /usr/local/bin/isql-v
   EOH
  action :nothing
end


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

import persistentVolumeClaimModule from 'persistentvolumeclaim/module';

describe('Persistent Volume Claim card', () => {
  /** @type {!PersistentVolumeClaimCardController} */
  let ctrl;
  /**
   * @type {!NamespaceService}
   */
  let data;

  beforeEach(() => {
    angular.mock.module(persistentVolumeClaimModule.name);

    angular.mock.inject(($componentController, $rootScope, kdNamespaceService) => {

      /** @type {!PersistentVolumeClaimCardController} */
      ctrl = $componentController('kdPersistentVolumeClaimCard', {$scope: $rootScope});
      /** @type {!NamespaceService} */
      data = kdNamespaceService;
    });
  });

  it('should return true when persistent volume claim is bound', () => {
    // given
    ctrl.persistentVolumeClaim = {
      Status: 'Bound',
    };

    // then
    expect(ctrl.isBound()).toBeTruthy();
  });

  it('should return true when persistent volume claim is pending', () => {
    // given
    ctrl.persistentVolumeClaim = {
      Status: 'Pending',
    };

    // then
    expect(ctrl.isPending()).toBeTruthy();
  });

  it('should return true when persistent volume claim is lost', () => {
    // given
    ctrl.persistentVolumeClaim = {
      Status: 'Lost',
    };

    // then
    expect(ctrl.isLost()).toBeTruthy();
  });

  it('should get details href', () => {
    ctrl.persistentVolumeClaim = {
      objectMeta: {
        namespace: 'foo',
        name: 'bar',
      },
    };

    expect(ctrl.getPersistentVolumeClaimDetailHref()).toBe('#!/persistentvolumeclaim/foo/bar');
  });

  it('should return the value from Namespace service', () => {
    expect(ctrl.areMultipleNamespacesSelected()).toBe(data.areMultipleNamespacesSelected());
  });

  it('should format the "created at" tooltip correctly', () => {
    expect(ctrl.getCreatedAtTooltip('2016-06-06T09:13:12Z'))
        .toMatch('Created at 2016-06-06T09:13.*');
  });
});


text:
drop table if exists users;
drop table if exists user_roles;
drop table if exists roles_permissions;

create table users (
  id bigint auto_increment,
  username varchar(100),
  password varchar(100),
  password_salt varchar(100),
  constraint pk_users primary key(id)
) charset=utf8 ENGINE=InnoDB;
create unique index idx_users_username on users(username);

create table user_roles(
  id bigint auto_increment,
  username varchar(100),
  role_name varchar(100),
  constraint pk_user_roles primary key(id)
) charset=utf8 ENGINE=InnoDB;
create unique index idx_user_roles on user_roles(username, role_name);

create table roles_permissions(
  id bigint auto_increment,
  role_name varchar(100),
  permission varchar(100),
  constraint pk_roles_permissions primary key(id)
) charset=utf8 ENGINE=InnoDB;
create unique index idx_roles_permissions on roles_permissions(role_name, permission);


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<TITLE
>Built-in Functions</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:pgsql-docs@postgresql.org"><LINK
REL="HOME"
TITLE="PostgreSQL 9.6.2 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="PL/Perl - Perl Procedural Language"
HREF="plperl.html"><LINK
REL="PREVIOUS"
TITLE="Data Values in PL/Perl"
HREF="plperl-data.html"><LINK
REL="NEXT"
TITLE="Global Values in PL/Perl"
HREF="plperl-global.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2017-02-06T21:56:32">

PostgreSQL 9.6.2 Documentation

Prev	Up	Chapter 43. PL/Perl - Perl Procedural Language	Next

43.3. Built-in Functions

43.3.1. Database Access from PL/Perl

   Access to the database itself from your Perl function can be done
   via the following functions:

<TT
CLASS="LITERAL"
>spi_exec_query(<TT
CLASS="REPLACEABLE"
>query</TT
> [, <TT
CLASS="REPLACEABLE"
>max-rows</TT
>])</TT
>

       <TT
CLASS="LITERAL"
>spi_exec_query</TT
> executes an SQL command and
returns the entire row set as a reference to an array of hash
references.  You should only use this command when you know
that the result set will be relatively small.  Here is an
example of a query (<TT
CLASS="COMMAND"
>SELECT</TT
> command) with the
optional maximum number of rows:

$rv = spi_exec_query('SELECT * FROM my_table', 5);

        This returns up to 5 rows from the table
        <TT
CLASS="LITERAL"
>my_table</TT
>.  If <TT
CLASS="LITERAL"
>my_table</TT
>
        has a column <TT
CLASS="LITERAL"
>my_column</TT
>, you can get that
        value from row <TT
CLASS="LITERAL"
>$i</TT
> of the result like this:

$foo = $rv->{rows}[$i]->{my_column};

       The total number of rows returned from a <TT
CLASS="COMMAND"
>SELECT</TT
>
       query can be accessed like this:

$nrows = $rv->{processed}

       Here is an example using a different command type:

$query = "INSERT INTO my_table VALUES (1, 'test')";
$rv = spi_exec_query($query);

       You can then access the command status (e.g.,
       <TT
CLASS="LITERAL"
>SPI_OK_INSERT</TT
>) like this:

$res = $rv->{status};

       To get the number of rows affected, do:

$nrows = $rv->{processed};

       Here is a complete example:

CREATE TABLE test (
    i int,
    v varchar
);

INSERT INTO test (i, v) VALUES (1, 'first line');
INSERT INTO test (i, v) VALUES (2, 'second line');
INSERT INTO test (i, v) VALUES (3, 'third line');
INSERT INTO test (i, v) VALUES (4, 'immortal');

CREATE OR REPLACE FUNCTION test_munge() RETURNS SETOF test AS $$
    my $rv = spi_exec_query('select i, v from test;');
    my $status = $rv->{status};
    my $nrows = $rv->{processed};
    foreach my $rn (0 .. $nrows - 1) {
        my $row = $rv->{rows}[$rn];
        $row->{i} += 200 if defined($row->{i});
        $row->{v} =~ tr/A-Za-z/a-zA-Z/ if (defined($row->{v}));
        return_next($row);
    }
    return undef;
$$ LANGUAGE plperl;

SELECT * FROM test_munge();

<TT
CLASS="LITERAL"
>spi_query(<TT
CLASS="REPLACEABLE"
>command</TT
>)</TT
>

<TT
CLASS="LITERAL"
>spi_fetchrow(<TT
CLASS="REPLACEABLE"
>cursor</TT
>)</TT
>

<TT
CLASS="LITERAL"
>spi_cursor_close(<TT
CLASS="REPLACEABLE"
>cursor</TT
>)</TT
>

    <TT
CLASS="LITERAL"
>spi_query</TT
> and <TT
CLASS="LITERAL"
>spi_fetchrow</TT
>
    work together as a pair for row sets which might be large, or for cases
    where you wish to return rows as they arrive.
    <TT
CLASS="LITERAL"
>spi_fetchrow</TT
> works only with
    <TT
CLASS="LITERAL"
>spi_query</TT
>. The following example illustrates how
    you use them together:

CREATE TYPE foo_type AS (the_num INTEGER, the_text TEXT);

CREATE OR REPLACE FUNCTION lotsa_md5 (INTEGER) RETURNS SETOF foo_type AS $$
    use Digest::MD5 qw(md5_hex);
    my $file = '/usr/share/dict/words';
    my $t = localtime;
    elog(NOTICE, "opening file $file at $t" );
    open my $fh, '<', $file # ooh, it's a file access!
        or elog(ERROR, "cannot open $file for reading: $!");
    my @words = <$fh>;
    close $fh;
    $t = localtime;
    elog(NOTICE, "closed file $file at $t");
    chomp(@words);
    my $row;
    my $sth = spi_query("SELECT * FROM generate_series(1,$_[0]) AS b(a)");
    while (defined ($row = spi_fetchrow($sth))) {
        return_next({
            the_num => $row->{a},
            the_text => md5_hex($words[rand @words])
        });
    }
    return;
$$ LANGUAGE plperlu;

SELECT * from lotsa_md5(500);

     Normally, spi_fetchrow should be repeated until it
     returns <TT
CLASS="LITERAL"
>undef</TT
>, indicating that there are no more
     rows to read.  The cursor returned by <TT
CLASS="LITERAL"
>spi_query</TT
>
     is automatically freed when
     spi_fetchrow returns <TT
CLASS="LITERAL"
>undef</TT
>.
     If you do not wish to read all the rows, instead call
     spi_cursor_close to free the cursor.
     Failure to do so will result in memory leaks.

<TT
CLASS="LITERAL"
>spi_prepare(<TT
CLASS="REPLACEABLE"
>command</TT
>, <TT
CLASS="REPLACEABLE"
>argument types</TT
>)</TT
>

<TT
CLASS="LITERAL"
>spi_query_prepared(<TT
CLASS="REPLACEABLE"
>plan</TT
>, <TT
CLASS="REPLACEABLE"
>arguments</TT
>)</TT
>

<TT
CLASS="LITERAL"
>spi_exec_prepared(<TT
CLASS="REPLACEABLE"
>plan</TT
> [, <TT
CLASS="REPLACEABLE"
>attributes</TT
>], <TT
CLASS="REPLACEABLE"
>arguments</TT
>)</TT
>

<TT
CLASS="LITERAL"
>spi_freeplan(<TT
CLASS="REPLACEABLE"
>plan</TT
>)</TT
>

    <TT
CLASS="LITERAL"
>spi_prepare</TT
>, <TT
CLASS="LITERAL"
>spi_query_prepared</TT
>, <TT
CLASS="LITERAL"
>spi_exec_prepared</TT
>,
    and <TT
CLASS="LITERAL"
>spi_freeplan</TT
> implement the same functionality but for prepared queries.
    <TT
CLASS="LITERAL"
>spi_prepare</TT
> accepts a query string with numbered argument placeholders ($1, $2, etc)
    and a string list of argument types:

$plan = spi_prepare('SELECT * FROM test WHERE id > $1 AND name = $2',
                                                     'INTEGER', 'TEXT');

    Once a query plan is prepared by a call to <TT
CLASS="LITERAL"
>spi_prepare</TT
>, the plan can be used instead
    of the string query, either in <TT
CLASS="LITERAL"
>spi_exec_prepared</TT
>, where the result is the same as returned
    by <TT
CLASS="LITERAL"
>spi_exec_query</TT
>, or in <TT
CLASS="LITERAL"
>spi_query_prepared</TT
> which returns a cursor
    exactly as <TT
CLASS="LITERAL"
>spi_query</TT
> does, which can be later passed to <TT
CLASS="LITERAL"
>spi_fetchrow</TT
>.
    The optional second parameter to <TT
CLASS="LITERAL"
>spi_exec_prepared</TT
> is a hash reference of attributes;
    the only attribute currently supported is <TT
CLASS="LITERAL"
>limit</TT
>, which sets the maximum number of rows returned by a query.

    The advantage of prepared queries is that is it possible to use one prepared plan for more
    than one query execution. After the plan is not needed anymore, it can be freed with
    <TT
CLASS="LITERAL"
>spi_freeplan</TT
>:

CREATE OR REPLACE FUNCTION init() RETURNS VOID AS $$
        $_SHARED{my_plan} = spi_prepare('SELECT (now() + $1)::date AS now',
                                        'INTERVAL');
$$ LANGUAGE plperl;

CREATE OR REPLACE FUNCTION add_time( INTERVAL ) RETURNS TEXT AS $$
        return spi_exec_prepared(
                $_SHARED{my_plan},
                $_[0]
        )->{rows}->[0]->{now};
$$ LANGUAGE plperl;

CREATE OR REPLACE FUNCTION done() RETURNS VOID AS $$
        spi_freeplan( $_SHARED{my_plan});
        undef $_SHARED{my_plan};
$$ LANGUAGE plperl;

SELECT init();
SELECT add_time('1 day'), add_time('2 days'), add_time('3 days');
SELECT done();

  add_time  |  add_time  |  add_time
------------+------------+------------
 2005-12-10 | 2005-12-11 | 2005-12-12

    Note that the parameter subscript in <TT
CLASS="LITERAL"
>spi_prepare</TT
> is defined via
    $1, $2, $3, etc, so avoid declaring query strings in double quotes that might easily
    lead to hard-to-catch bugs.

    Another example illustrates usage of an optional parameter in <TT
CLASS="LITERAL"
>spi_exec_prepared</TT
>:

CREATE TABLE hosts AS SELECT id, ('192.168.1.'||id)::inet AS address
                      FROM generate_series(1,3) AS id;

CREATE OR REPLACE FUNCTION init_hosts_query() RETURNS VOID AS $$
        $_SHARED{plan} = spi_prepare('SELECT * FROM hosts
                                      WHERE address << $1', 'inet');
$$ LANGUAGE plperl;

CREATE OR REPLACE FUNCTION query_hosts(inet) RETURNS SETOF hosts AS $$
        return spi_exec_prepared(
                $_SHARED{plan},
                {limit => 2},
                $_[0]
        )->{rows};
$$ LANGUAGE plperl;

CREATE OR REPLACE FUNCTION release_hosts_query() RETURNS VOID AS $$
        spi_freeplan($_SHARED{plan});
        undef $_SHARED{plan};
$$ LANGUAGE plperl;

SELECT init_hosts_query();
SELECT query_hosts('192.168.1.0/30');
SELECT release_hosts_query();

    query_hosts
-----------------
 (1,192.168.1.1)
 (2,192.168.1.2)
(2 rows)

43.3.2. Utility Functions in PL/Perl

<TT
CLASS="LITERAL"
>elog(<TT
CLASS="REPLACEABLE"
>level</TT
>, <TT
CLASS="REPLACEABLE"
>msg</TT
>)</TT
>

       Emit a log or error message. Possible levels are
       <TT
CLASS="LITERAL"
>DEBUG</TT
>, <TT
CLASS="LITERAL"
>LOG</TT
>, <TT
CLASS="LITERAL"
>INFO</TT
>,
       <TT
CLASS="LITERAL"
>NOTICE</TT
>, <TT
CLASS="LITERAL"
>WARNING</TT
>, and <TT
CLASS="LITERAL"
>ERROR</TT
>.
       <TT
CLASS="LITERAL"
>ERROR</TT
>
        raises an error condition; if this is not trapped by the surrounding
        Perl code, the error propagates out to the calling query, causing
        the current transaction or subtransaction to be aborted.  This
        is effectively the same as the Perl <TT
CLASS="LITERAL"
>die</TT
> command.
        The other levels only generate messages of different
        priority levels.
        Whether messages of a particular priority are reported to the client,
        written to the server log, or both is controlled by the
        log_min_messages and
        client_min_messages configuration
        variables. See Chapter 19 for more
        information.

<TT
CLASS="LITERAL"
>quote_literal(<TT
CLASS="REPLACEABLE"
>string</TT
>)</TT
>

        Return the given string suitably quoted to be used as a string literal in an SQL
        statement string. Embedded single-quotes and backslashes are properly doubled.
        Note that quote_literal returns undef on undef input; if the argument
        might be undef, quote_nullable is often more suitable.

<TT
CLASS="LITERAL"
>quote_nullable(<TT
CLASS="REPLACEABLE"
>string</TT
>)</TT
>

        Return the given string suitably quoted to be used as a string literal in an SQL
        statement string; or, if the argument is undef, return the unquoted string "NULL".
        Embedded single-quotes and backslashes are properly doubled.

<TT
CLASS="LITERAL"
>quote_ident(<TT
CLASS="REPLACEABLE"
>string</TT
>)</TT
>

        Return the given string suitably quoted to be used as an identifier in
        an SQL statement string. Quotes are added only if necessary (i.e., if
        the string contains non-identifier characters or would be case-folded).
        Embedded quotes are properly doubled.

<TT
CLASS="LITERAL"
>decode_bytea(<TT
CLASS="REPLACEABLE"
>string</TT
>)</TT
>

        Return the unescaped binary data represented by the contents of the given string,
        which should be <TT
CLASS="TYPE"
>bytea</TT
> encoded.

<TT
CLASS="LITERAL"
>encode_bytea(<TT
CLASS="REPLACEABLE"
>string</TT
>)</TT
>

        Return the <TT
CLASS="TYPE"
>bytea</TT
> encoded form of the binary data contents of the given string.

<TT
CLASS="LITERAL"
>encode_array_literal(<TT
CLASS="REPLACEABLE"
>array</TT
>)</TT
>

<TT
CLASS="LITERAL"
>encode_array_literal(<TT
CLASS="REPLACEABLE"
>array</TT
>, <TT
CLASS="REPLACEABLE"
>delimiter</TT
>)</TT
>

        Returns the contents of the referenced array as a string in array literal format
        (see Section 8.15.2).
        Returns the argument value unaltered if it's not a reference to an array.
        The delimiter used between elements of the array literal defaults to "<TT
CLASS="LITERAL"
>, </TT
>"
        if a delimiter is not specified or is undef.

<TT
CLASS="LITERAL"
>encode_typed_literal(<TT
CLASS="REPLACEABLE"
>value</TT
>, <TT
CLASS="REPLACEABLE"
>typename</TT
>)</TT
>

         Converts a Perl variable to the value of the data type passed as a
         second argument and returns a string representation of this value.
         Correctly handles nested arrays and values of composite types.

<TT
CLASS="LITERAL"
>encode_array_constructor(<TT
CLASS="REPLACEABLE"
>array</TT
>)</TT
>

        Returns the contents of the referenced array as a string in array constructor format
        (see Section 4.2.12).
        Individual values are quoted using quote_nullable.
        Returns the argument value, quoted using quote_nullable,
        if it's not a reference to an array.

<TT
CLASS="LITERAL"
>looks_like_number(<TT
CLASS="REPLACEABLE"
>string</TT
>)</TT
>

        Returns a true value if the content of the given string looks like a
        number, according to Perl, returns false otherwise.
        Returns undef if the argument is undef.  Leading and trailing space is
        ignored. <TT
CLASS="LITERAL"
>Inf</TT
> and <TT
CLASS="LITERAL"
>Infinity</TT
> are regarded as numbers.

<TT
CLASS="LITERAL"
>is_array_ref(<TT
CLASS="REPLACEABLE"
>argument</TT
>)</TT
>

        Returns a true value if the given argument may be treated as an
        array reference, that is, if ref of the argument is <TT
CLASS="LITERAL"
>ARRAY</TT
> or
        <TT
CLASS="LITERAL"
>PostgreSQL::InServer::ARRAY</TT
>.  Returns false otherwise.

Prev	Home	Next

Data Values in PL/Perl	Up	Global Values in PL/Perl


text:
import React from 'react';
import { View } from 'react-native';
import PropTypes from 'prop-types';
import { compose, mapProps, setPropTypes } from 'recompose';
import { withFormik } from 'formik';
import Yup from 'yup';

import withUser from '@data/withUser';
import { Text as TextInput } from '@ui/inputs';
import Button from '@ui/Button';
import sentry from '@utils/sentry';

import Status from './FormStatusText';
import { withFieldValueHandler, withFieldTouchedHandler } from './formikSetters';

const enhance = compose(
  setPropTypes({
    onResetSuccess: PropTypes.func,
    resetPassword: PropTypes.func,
    token: PropTypes.string,
  }),
  withFormik({
    validationSchema: Yup.object().shape({
      password: Yup.string().required(),
      passwordConfirm: Yup.string()
        .oneOf([Yup.ref('password'), null], "Passwords don't match.")
        .required('A password is required'),
    }),
    handleSubmit: async (values, {
      props, setFieldError, setSubmitting, setStatus,
    }) => {
      props
        .resetPassword({ token: props.token, newPassword: values.password })
        .catch((...e) => {
          setStatus('There was an error resetting your password.');
          sentry.captureException(e);
          setFieldError('password', true); // todo: show real error message from server
        })
        .then((...args) => {
          setStatus('Your password was reset');
          if (props.onResetSuccess) props.onResetSuccess(...args);
        })
        .finally(() => setSubmitting(false));
    },
  }),
  withFieldValueHandler,
  withFieldTouchedHandler,
  setPropTypes({
    createFieldValueHandler: PropTypes.func,
    createFieldTouchedHandler: PropTypes.func,
    touched: PropTypes.shape({}),
    errors: PropTypes.shape({}),
    values: PropTypes.shape({}),
    handleSubmit: PropTypes.func,
    isSubmitting: PropTypes.bool,
    isValid: PropTypes.bool,
    status: PropTypes.string,
  }),
);

export const ChangePasswordFormWithoutData = enhance(
  ({
    createFieldValueHandler,
    createFieldTouchedHandler,
    touched,
    errors,
    values,
    handleSubmit,
    isValid,
    isSubmitting,
    status,
  }) => (
    <View>
      <TextInput
        label="New Password"
        type="password"
        value={values.password}
        onChangeText={createFieldValueHandler('password')}
        onBlur={createFieldTouchedHandler('password')}
        error={touched.password && errors.password}
      />
      <TextInput
        label="Confirm Password (enter it again)"
        type="password"
        value={values.passwordConfirm}
        onChangeText={createFieldValueHandler('passwordConfirm')}
        onBlur={createFieldTouchedHandler('passwordConfirm')}
        error={touched.passwordConfirm && errors.passwordConfirm}
      />
      {status ? <Status>{status}</Status> : null}
      <Button onPress={handleSubmit} title="Go" disabled={!isValid} loading={isSubmitting} />
    </View>
  ),
);

const withData = compose(
  withUser,
  mapProps(props => ({ ...props, onSubmit: props.resetPassword })),
);
export default withData(ChangePasswordFormWithoutData);