text:
// Original - Christopher Lloyd <cjwl@objc.net>
#import "NSTypesetter_concrete.h"
#import <AppKit/NSLayoutManager.h>
#import <AppKit/NSTextContainer.h>
#import <AppKit/NSTextStorage.h>
#import <AppKit/NSAttributedString.h>
#import <AppKit/NSColor.h>
#import <AppKit/NSParagraphStyle.h>
#import <AppKit/NSRangeArray.h>
#import <AppKit/NSTextAttachment.h>
#import <AppKit/NSTextTab.h>
#import <AppKit/NSImage.h>

@interface NSLayoutManager(private)
- (void)_rollbackLatestFragment;
@end

@implementation NSTypesetter_concrete

-init {
   [super init];
   _layoutNextFragment=[self methodForSelector:@selector(layoutNextFragment)];
   _glyphCacheRange=NSMakeRange(0,0);
   _glyphCacheCapacity=256;
   _glyphCache=NSZoneMalloc([self zone],sizeof(NSGlyph)*_glyphCacheCapacity);
   _characterCache=NSZoneMalloc([self zone],sizeof(unichar)*_glyphCacheCapacity);

   _glyphRangesInLine=[NSRangeArray new];
   return self;
}

-(void)dealloc {
   NSZoneFree([self zone],_glyphCache);
   NSZoneFree([self zone],_characterCache);
   [_container release];

   [_glyphRangesInLine release];
   [super dealloc];
}

static void loadGlyphAndCharacterCacheForLocation(NSTypesetter_concrete *self,unsigned location) {
   unsigned length=MIN(self->_glyphCacheCapacity,NSMaxRange(self->_attributesGlyphRange)-location);

   self->_glyphCacheRange=NSMakeRange(location,length);

   [self->_string getCharacters:self->_characterCache range:self->_glyphCacheRange];
   [self->_layoutManager getGlyphs:self->_glyphCache range:self->_glyphCacheRange];
}

- (void)getLineFragmentRect:(NSRectPointer)lineFragmentRect usedRect:(NSRectPointer)lineFragmentUsedRect remainingRect:(NSRectPointer)remainingRect forStartingGlyphAtIndex:(unsigned)startingGlyphIndex proposedRect:(NSRect)proposedRect lineSpacing:(float)lineSpacing paragraphSpacingBefore:(float)paragraphSpacingBefore paragraphSpacingAfter:(float)paragraphSpacingAfter
{
	unsigned glyphIndex;
	NSRange  fragmentRange=NSMakeRange(_nextGlyphLocation,0);
	float    fragmentWidth=0;
	float    fragmentHeight=_fontDefaultLineHeight;
	NSRange  wordWrapRange=NSMakeRange(_nextGlyphLocation,0);
	float    wordWrapWidth=0;
	NSGlyph  wordWrapPreviousGlyph=NSNullGlyph;
	NSRect   fragmentRect;
	BOOL     isNominal,advanceScanRect=NO,endOfString=NO,endOfLine=NO;

	_scanRect = proposedRect;

	float wantedHeight = MAX(proposedRect.size.height, fragmentHeight);
	_scanRect.size.height = wantedHeight;

	_scanRect = [_container lineFragmentRectForProposedRect:_scanRect sweepDirection:NSLineSweepRight movementDirection:NSLineMovesDown remainingRect:remainingRect];
	if ([_glyphRangesInLine count] != 0 && _scanRect.origin.y > proposedRect.origin.y) {
		// We don't want the rects to move down, if it's not the first one of the line
		// We could use NSLineNoMove with lineFragmentRectForProposedRect but Cocoa doesn't do that
		_scanRect = NSZeroRect;
	}
	if (_scanRect.size.height < wantedHeight) {
		// Too small for our text
		_scanRect = NSZeroRect;
	}
	if (!NSEqualRects(_scanRect, NSZeroRect)) {
		// Add left/right padding
		_scanRect.size.width -= _container.lineFragmentPadding;
		if ([_glyphRangesInLine count] == 0) {
			// Add left padding too for the first fragment of the line
			_scanRect.size.width -= _container.lineFragmentPadding;
			_scanRect.origin.x += _container.lineFragmentPadding;
			_fullLineRect = _scanRect;
		}
		if (_scanRect.size.width <= 0.) {
			_scanRect = NSZeroRect;
		}
	}
	if (NSEqualRects(_scanRect, NSZeroRect)) {
		if ([_glyphRangesInLine count] == 0) {
			// No more room for another line
			return;
		} else {
			// No more room on that line - we will try next one - just reset the scanRect location to the end of the line
			// so the advanceScanRect logic will continue from the right place
			_scanRect.origin.x = NSMaxX(_fullLineRect);
			_scanRect.origin.y = NSMinY(proposedRect);
			_scanRect.size.width = 0;
			_scanRect.size.height = MAX(proposedRect.size.height, fragmentHeight);
		}
	}

	for(;(glyphIndex=NSMaxRange(fragmentRange))<NSMaxRange(_attributesGlyphRange);){
		NSGlyph  glyph;
		unichar  character;
		float    glyphAdvance,glyphMaxWidth;
		BOOL     fragmentExit=NO;

		_paragraphBreak=NO;
		fragmentRange.length++;
		_lineRange.length++;

		if(!NSLocationInRange(glyphIndex,_glyphCacheRange))
			loadGlyphAndCharacterCacheForLocation(self,glyphIndex);

		glyph=_glyphCache[glyphIndex-_glyphCacheRange.location];
		character=_characterCache[glyphIndex-_glyphCacheRange.location];
		if(character==' '){
			// We can word wrap from here if needed
			wordWrapRange=fragmentRange;
			wordWrapWidth=fragmentWidth;
			wordWrapPreviousGlyph=_previousGlyph;
			// Keep the info so we can rollback to that point even if we switch to another
			// fragment
			_wordWrapWidth=wordWrapWidth;
			_wordWrapRange=wordWrapRange;
			_wordWrapPreviousGlyph=wordWrapPreviousGlyph;
			_wordWrapScanRect = _scanRect;
		}

		if(character==NSAttachmentCharacter){
			NSTextAttachment         *attachment=[_attributes objectForKey:NSAttachmentAttributeName];
			id <NSTextAttachmentCell> cell=[attachment attachmentCell];
			NSSize                    size=[cell cellSize];

			fragmentHeight=size.height;
			glyphAdvance=_positionOfGlyph(_font,NULL,NSNullGlyph,_previousGlyph,&isNominal).x;
			glyphMaxWidth=size.width;
			_previousGlyph=NSNullGlyph;
		} else {
			if(glyph==NSControlGlyph){
				fragmentWidth+=_positionOfGlyph(_font,NULL,NSNullGlyph,_previousGlyph,&isNominal).x;
				_previousGlyph=NSNullGlyph;

				switch([self actionForControlCharacterAtIndex:glyphIndex]){

					case NSTypesetterZeroAdvancementAction:
						// do nothing
						break;

					case NSTypesetterWhitespaceAction:
						fragmentWidth+=_whitespaceAdvancement;
						break;

					case NSTypesetterHorizontalTabAction:{
						float      x=_scanRect.origin.x+fragmentWidth;
						NSTextTab *tab=[self textTabForGlyphLocation:x writingDirection:[_currentParagraphStyle baseWritingDirection] maxLocation:NSMaxX(_scanRect)];
						float      nextx;

						if(tab!=nil)
							nextx=[tab location];
						else {
							float interval=[_currentParagraphStyle defaultTabInterval];

							if(interval>0)
								nextx=(((int)(x/interval))+1)*interval;
							else
								nextx=x;
						}

						fragmentWidth+=nextx-x;
					}
						break;

					case NSTypesetterParagraphBreakAction:
						_paragraphBreak=YES;
						advanceScanRect=YES;
						break;
					case NSTypesetterLineBreakAction:
						advanceScanRect=YES;
						break;
					case NSTypesetterContainerBreakAction:
						advanceScanRect=YES;
						break;
				}

				break;
			}

			glyphAdvance=_positionOfGlyph(_font,NULL,glyph,_previousGlyph,&isNominal).x;
			if(!isNominal && fragmentRange.length>1){
				_lineRange.length--;
				fragmentRange.length--;
				fragmentWidth+=glyphAdvance;
				_previousGlyph=NSNullGlyph;
				fragmentExit=YES;
				break;
			}
			glyphMaxWidth=_positionOfGlyph(_font,NULL,NSNullGlyph,glyph,&isNominal).x;
		}

		switch(_lineBreakMode){

			case NSLineBreakByWordWrapping:
				if(_lineRange.length>1){
					if(fragmentWidth+glyphAdvance+glyphMaxWidth>_scanRect.size.width){
						if(wordWrapWidth>0){
							// Break the line at previously found wrap location
							_lineRange.length=NSMaxRange(wordWrapRange)-_lineRange.location;
							fragmentRange=wordWrapRange;
							fragmentWidth=wordWrapWidth;
							_previousGlyph=wordWrapPreviousGlyph;
							wordWrapWidth = _wordWrapWidth = 0;
						} else {
							if ([_glyphRangesInLine count] != 0) {
								// We need to rollback all of the previous fragments until one ending with a white space
								//		 because words can span on several fragment because of some attribute changes
								if (_wordWrapWidth > 0) {
									_lineRange.length=NSMaxRange(_wordWrapRange)-_lineRange.location;
									// Rollback all fragments up to the previous wrapable one
									do {
										NSRange range = [_glyphRangesInLine rangeAtIndex:[_glyphRangesInLine count]- 1];
										[_layoutManager _rollbackLatestFragment];
										[_glyphRangesInLine removeRangeAtIndex:[_glyphRangesInLine count]- 1];
										if (_wordWrapRange.location == range.location) {
											break;
										}
									} while ([_glyphRangesInLine count]);
									_scanRect = _wordWrapScanRect;
									fragmentRange=_wordWrapRange;
									fragmentWidth=_wordWrapWidth;
									_previousGlyph=_wordWrapPreviousGlyph;
									wordWrapWidth = _wordWrapWidth = 0;
								} else {
									// We'll put the whole fragment on next line
									// No more room on that line - we will try next one - just reset the scanRect location to the end of the line
									// so the advanceScanRect logic will continue from the right place
									_scanRect.origin.x = NSMaxX(_fullLineRect);
									_scanRect.origin.y = NSMinY(proposedRect);
									_scanRect.size.width = 0;
									_scanRect.size.height = MAX(proposedRect.size.height, fragmentHeight);
									_lineRange.length -= fragmentRange.length;
									fragmentRange.length=0;
									fragmentWidth=0;
								}
							} else {
								// No wrapping location candidate - we'll just break the line
								// at current glyph
								_lineRange.length--;
								fragmentRange.length--;
							}
						}
						fragmentExit=YES;
						advanceScanRect=YES;
					}
				}
				break;

			case NSLineBreakByCharWrapping:
				if(_lineRange.length>1){
					if(fragmentWidth+glyphAdvance+glyphMaxWidth>_scanRect.size.width){
						// Break the line at current glyph
						_lineRange.length--;
						fragmentRange.length--;
						fragmentExit=YES;
						advanceScanRect=YES;
					}
				}
				break;

			case NSLineBreakByClipping:
				// Nothing special to do
				break;

			case NSLineBreakByTruncatingHead:
			case NSLineBreakByTruncatingTail:
			case NSLineBreakByTruncatingMiddle:
				// TODO: implement these styles
				break;
			default:
				break;
		}

		if (fragmentExit == NO && _alignment == NSJustifiedTextAlignment) {
			if (character == ' ') {
				// Make a new fragment after a ' ' so we can insert some white spaces to justify the line
				_previousGlyph=glyph;
				fragmentWidth+=glyphAdvance;
				break;
			}
		}
		if(fragmentExit){
			_previousGlyph=NSNullGlyph;
			fragmentWidth+=glyphAdvance;
			break;
		}
		_previousGlyph=glyph;
		fragmentWidth+=glyphAdvance;
	}

	if(fragmentRange.length>0){
		_nextGlyphLocation=NSMaxRange(fragmentRange);

		if(_nextGlyphLocation>=_numberOfGlyphs) {
			endOfString=YES;
		} else {
			if(!NSLocationInRange(_nextGlyphLocation,_glyphCacheRange))
				loadGlyphAndCharacterCacheForLocation(self,_nextGlyphLocation);

			int nextChar=_characterCache[glyphIndex-_glyphCacheRange.location];
			if (nextChar == '\n') {
				endOfLine=YES;
			}
		}

		if(!advanceScanRect){
			fragmentWidth+=_positionOfGlyph(_font,NULL,NSNullGlyph,_previousGlyph,&isNominal).x;
			// This should be done only when switching font or something?
			if (glyphIndex==NSMaxRange(_attributesGlyphRange)) {
				_previousGlyph=NSNullGlyph;
			} else {
				// Break because of full justification
			}
		}
		float height = MAX(_scanRect.size.height,fragmentHeight);
		if (_scanRect.size.height != height) {
			// Check we still fit if something changed our height
			_scanRect.size.height=height;
			_scanRect = [_container lineFragmentRectForProposedRect:_scanRect sweepDirection:NSLineSweepRight movementDirection:NSLineMovesDown remainingRect:remainingRect];
		}
		if (!NSEqualRects(_scanRect, NSZeroRect)) {
			[_glyphRangesInLine addRange:fragmentRange];
			_maxAscender=MAX(_maxAscender,_fontAscender);
			[_layoutManager setTextContainer:_container forGlyphRange:fragmentRange];
			fragmentRect=_scanRect;
			fragmentRect.size.width=fragmentWidth;
			[_layoutManager setLineFragmentRect:_scanRect forGlyphRange:fragmentRange usedRect:fragmentRect];
			[_layoutManager setLocation:_scanRect.origin forStartOfGlyphRange:fragmentRange];
		} else {
			// Can't fit any more text
			return;
		}
	}

	if(advanceScanRect || endOfString){
		// We're done with a line - fix the fragment rects for its
		int   i,count=[_glyphRangesInLine count];
		float alignmentDelta=0;

		if(_alignment!=NSLeftTextAlignment){
			// Find the total line width so we can adjust the rect x origin according to the alignment
			float totalWidth=NSMaxX(_fullLineRect);

			float totalUsedWidth=0;
			if (count) {
				NSRange range=[_glyphRangesInLine rangeAtIndex:count-1];
				NSRect  usedRect=[_layoutManager lineFragmentUsedRectForGlyphAtIndex:range.location effectiveRange:NULL];
				totalUsedWidth=NSMaxX(usedRect);
			}

			// Calc the delta to apply to the origins so the alignment is respected
			switch(_alignment){

				case NSRightTextAlignment:
					alignmentDelta=totalWidth-totalUsedWidth;
					break;

				case NSCenterTextAlignment:
					alignmentDelta=(totalWidth-totalUsedWidth)/2;
					break;

				case NSJustifiedTextAlignment:
					if (!endOfString && !endOfLine) {
						int blankCount = 0;
						// Find the number of fragments ending with a ' '
						for(i=1;i<count;i++){
							NSRange range=[_glyphRangesInLine rangeAtIndex:i];
							if(!NSLocationInRange(range.location,_glyphCacheRange))
								loadGlyphAndCharacterCacheForLocation(self,range.location-1);

							int character=_characterCache[range.location-1-_glyphCacheRange.location];
							if (character==' '){
								blankCount++;
							}
						}
						if (blankCount) {
							alignmentDelta=(totalWidth-totalUsedWidth)/blankCount;
						}
					}
					break;

				default:
					break;
			}
		}

		int blankCount = 0;
		for(i=0;i<count;i++){
			NSRange range=[_glyphRangesInLine rangeAtIndex:i];
			NSRect  backRect=[_layoutManager lineFragmentRectForGlyphAtIndex:range.location effectiveRange:NULL];
			NSRect  usedRect=[_layoutManager lineFragmentUsedRectForGlyphAtIndex:range.location effectiveRange:NULL];
			NSPoint location=[_layoutManager locationForGlyphAtIndex:range.location];

			usedRect.size.height=backRect.size.height=_scanRect.size.height;
			location.y+=_maxAscender;
			if (_alignment == NSJustifiedTextAlignment) {
				if (i > 0) {
					if(!NSLocationInRange(range.location,_glyphCacheRange))
						loadGlyphAndCharacterCacheForLocation(self,range.location-1);

					int character=_characterCache[range.location-1-_glyphCacheRange.location];
					if (character==' ') {
						// Add some more pixels from here
						blankCount++;
					}
					usedRect.origin.x+=alignmentDelta*blankCount;
					location.x+=alignmentDelta*blankCount;
					if(i+1==count) {
						// Adjust the last rect
						backRect.origin.x+=alignmentDelta*blankCount;
						backRect.size.width-=alignmentDelta*blankCount;
					}
				}
			} else {
				if(i==0) {
					// Grow the first rect to it contains the white space added for justification
					backRect.size.width+=alignmentDelta;
				}
				usedRect.origin.x+=alignmentDelta;
				location.x+=alignmentDelta;
				if(i+1==count) {
					// Adjust the last rect
					backRect.origin.x+=alignmentDelta;
					backRect.size.width-=alignmentDelta;
				}
			}
			if(i+1<count || !advanceScanRect || endOfString) {
				[_layoutManager setLineFragmentRect:usedRect forGlyphRange:range usedRect:usedRect];
			} else {
				// Last rect
				[_layoutManager setLineFragmentRect:backRect forGlyphRange:range usedRect:usedRect];
			}
			[_layoutManager setLocation:location forStartOfGlyphRange:range];
		}
		// Some cleaning after we're done with the current line
		[_glyphRangesInLine removeAllRanges];
		_wordWrapWidth=0;
		_wordWrapRange = NSMakeRange(0,0);
	}

	if(advanceScanRect){
		_lineRange.location=NSMaxRange(fragmentRange);
		_lineRange.length=0;
		_scanRect.origin.x=0;
		_scanRect.origin.y+=_scanRect.size.height;
		_scanRect.size.width=1e7; // That's what Cocoa is sending
		_scanRect.size.height=0;
		_maxAscender=0;
	} else {
		_scanRect.origin.x+=fragmentWidth;
		_scanRect.size.width=NSMaxX(_fullLineRect)-_scanRect.origin.x;
	}
}

-(void)layoutNextFragment {
	NSRect lineFragmentUsedRect;
	NSRect remainingRect;
	NSRect proposedRect = _scanRect;

	// FIXME: getLineFragmentRect: does actually more that it should do - part of its code (like filing the typesetter layout info) should really be moved to the layoutNextFragment
	// mehod
	[self getLineFragmentRect:&_scanRect usedRect:&lineFragmentUsedRect remainingRect:&remainingRect forStartingGlyphAtIndex:_nextGlyphLocation proposedRect:proposedRect lineSpacing:1 paragraphSpacingBefore:0 paragraphSpacingAfter:0];
}

-(void)fetchAttributes {
   NSFont  *nextFont;
   unsigned characterIndex=_nextGlyphLocation; // FIX
   NSGlyph  spaceGlyph;
   unichar  space=' ';

   _attributes=[_attributedString attributesAtIndex:characterIndex effectiveRange:&_attributesRange];

   _attributesGlyphRange=_attributesRange; // FIX

   nextFont=NSFontAttributeInDictionary(_attributes);
   if(_font!=nextFont){
    _previousGlyph=NSNullGlyph;
    _font=nextFont;
    _fontAscender=ceilf([_font ascender]);
    _fontDefaultLineHeight=ceilf([_font defaultLineHeightForFont]);
    _positionOfGlyph=(void *)[_font methodForSelector:@selector(positionOfGlyph:precededByGlyph:isNominal:)];

    [_font getGlyphs:&spaceGlyph forCharacters:&space length:1];
    _whitespaceAdvancement=[_font advancementForGlyph:spaceGlyph].width;
   }

   if((_currentParagraphStyle=[_attributes objectForKey:NSParagraphStyleAttributeName])==nil)
    _currentParagraphStyle=[NSParagraphStyle defaultParagraphStyle];
   _alignment=[_currentParagraphStyle alignment];
   _lineBreakMode=[_currentParagraphStyle lineBreakMode];
}

-(void)layoutGlyphsInLayoutManager:(NSLayoutManager *)layoutManager
       startingAtGlyphIndex:(unsigned)glyphIndex
   maxNumberOfLineFragments:(unsigned)maxNumLines
             nextGlyphIndex:(unsigned *)nextGlyph {

	[layoutManager retain];
   [_layoutManager release];
	_layoutManager=layoutManager;
   _textContainers=[layoutManager textContainers];

   [self setAttributedString:[layoutManager textStorage]];

   _nextGlyphLocation=0;
   _numberOfGlyphs=[_string length];
   _glyphCacheRange=NSMakeRange(0,0);
   _previousGlyph=NSNullGlyph;

	NSTextContainer *container = [[_textContainers objectAtIndex:0] retain];

   [_container release];
   _container=container;
   _containerSize=[_container containerSize];

   _attributesRange=NSMakeRange(0,0);
   _attributesGlyphRange=NSMakeRange(0,0);
   _attributes=nil;
   _font=nil;

   _lineRange=NSMakeRange(0,0);
   [_glyphRangesInLine removeAllRanges];
   _previousGlyph=NSNullGlyph;
   _scanRect.origin.x=0;
   _scanRect.origin.y=0;
   _scanRect.size.width=1e7; // That's what Cocoa is sending
   _scanRect.size.height=0;
   _maxAscender=0;
	_wordWrapWidth=0;
  while(_nextGlyphLocation<_numberOfGlyphs){

    if(!NSLocationInRange(_nextGlyphLocation,_attributesRange))
     [self fetchAttributes];

    _layoutNextFragment(self,NULL);
	   if (NSEqualRects(_scanRect, NSZeroRect)) {
		   break;
	   }
   }

   if(_font==nil){
    _font=NSFontAttributeInDictionary(nil);
    _fontAscender=ceilf([_font ascender]);
    _fontDefaultLineHeight=ceilf([_font defaultLineHeightForFont]);
    _positionOfGlyph=(void *)[_font methodForSelector:@selector(positionOfGlyph:precededByGlyph:isNominal:)];
   }

	if (((_paragraphBreak && _nextGlyphLocation>=_numberOfGlyphs) || _numberOfGlyphs == 0)) {
		NSRect remainingRect; // Ignored for now
		_scanRect.size.height=MAX(_scanRect.size.height,_fontDefaultLineHeight);
		_scanRect = [_container lineFragmentRectForProposedRect:_scanRect sweepDirection:NSLineSweepRight movementDirection:NSLineMovesDown remainingRect:&remainingRect];
		NSRect usedRect = _scanRect;
		usedRect.size.width = 10;
		[_layoutManager setExtraLineFragmentRect:_scanRect usedRect:usedRect textContainer:_container];
	} else {
		[_layoutManager setExtraLineFragmentRect:NSZeroRect	usedRect:NSZeroRect textContainer:_container];
	}
   _currentParagraphStyle=nil;
   _font=nil;
   _attributes=nil;

   [_container release];
   _container=nil;
   [self setAttributedString:nil];
   _textContainers=nil;
   [_layoutManager release];
   _layoutManager=nil;
}

@end


text:
{-# LANGUAGE DeriveGeneric #-}

module Permissions where

import Data.Aeson
-- import Database.PostgreSQL.Simple.ToRow
-- import Database.PostgreSQL.Simple.FromRow
-- import Database.PostgreSQL.Simple.ToField
-- import Database.PostgreSQL.Simple.FromField
import GHC.Generics
import EntityID
import User

data Ownership = Ownership
  { _permOwner      :: EntityID User
  , _permGroup      :: EntityID Group
  , _permOwnerRead  :: Bool
  , _permOwnerWrite :: Bool
  , _permGroupRead  :: Bool
  , _permGroupWrite :: Bool
  , _publicRead     :: Bool
  } deriving (Eq, Ord, Show, Read, Generic)

instance ToJSON   Ownership where
instance FromJSON Ownership where

-- instance ToRow Ownership where
--   toRow (Ownership o g oR oW gR gW pR) =
--     [toField o, toField g, toField oR, toField oW
--     ,toField gR, toField gW, toField pR
--     ]

-- instance FromRow Ownership where
--   fromRow = Ownership <$> field <*> field <*> field
--             <*> field <*> field <*> field <*> field

-- instance FromField Ownership where
--   fromField a b = read <$> fromField a b

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using ServiceStack.ServiceModel.Tests.DataContracts;
using ServiceStack.Text;

namespace ServiceStack.ServiceModel.Tests
{
	[TestFixture]
	public class StringConverterUtilsTests
	{
		public class StringEnumerable : IEnumerable<string>
		{
			public List<string> Items = new[] { "a", "b", "c" }.ToList();

			public IEnumerator<string> GetEnumerator()
			{
				return Items.GetEnumerator();
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}

			public static StringEnumerable Parse(string value)
			{
				return new StringEnumerable {
					Items = value.To<List<string>>()
				};
			}

		}

		[Test]
		public void Create_super_list_type_of_int_from_string()
		{
			var textValue = "1,2,3";
			var convertedValue = textValue.Split(',').ToList().ConvertAll(x => Convert.ToInt32(x));
			var result = TypeSerializer.DeserializeFromString<ArrayOfIntId>(textValue);
			Assert.That(result, Is.EquivalentTo(convertedValue));
		}

		[Test]
		public void Create_guid_from_string()
		{
			var textValue = "40DFA5A2-8054-4b3e-B7F5-06E61FF387EF";
			var convertedValue = new Guid(textValue);
			var result = TypeSerializer.DeserializeFromString<Guid>(textValue);
			Assert.That(result, Is.EqualTo(convertedValue));
		}

		[Test]
		public void Create_int_from_string()
		{
			var textValue = "99";
			var convertedValue = int.Parse(textValue);
			var result = TypeSerializer.DeserializeFromString<int>(textValue);
			Assert.That(result, Is.EqualTo(convertedValue));
		}

		[Test]
		public void Create_bool_from_string()
		{
			var textValue = "True";
			var convertedValue = bool.Parse(textValue);
			var result = TypeSerializer.DeserializeFromString<bool>(textValue);
			Assert.That(result, Is.EqualTo(convertedValue));
		}

		[Test]
		public void Create_string_array_from_string()
		{
			var convertedValue = new[] { "Hello", "World" };
			var textValue = string.Join(",", convertedValue);
			var result = TypeSerializer.DeserializeFromString<string[]>(textValue);
			Assert.That(result, Is.EqualTo(convertedValue));
		}

		[Test]
		public void Create_from_StringEnumerable()
		{
			var value = StringEnumerable.Parse("d,e,f");
			var convertedValue = TypeSerializer.SerializeToString(value);
			var result = TypeSerializer.DeserializeFromString<StringEnumerable>(convertedValue);
			Assert.That(result, Is.EquivalentTo(value.Items));
		}

	}
}


text:
namespace Appccelerate.ScopingEventBroker
{
    using System;

    public interface IEventScope : IDisposable
    {
        void Release();

        void Cancel();
    }
}


text:
package org.killbill.billing.overdue;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;
import org.killbill.billing.account.api.ImmutableAccountData;
import org.killbill.billing.overdue.api.OverdueState;
import org.killbill.billing.overdue.glue.TestOverdueModule.ApplicatorBlockingApi;
import org.mockito.Mockito;
import org.testng.Assert;

import org.killbill.billing.account.api.AccountApiException;
import org.killbill.billing.invoice.api.Invoice;
import org.killbill.billing.invoice.api.InvoiceItem;
import org.killbill.billing.entitlement.api.BlockingState;
import org.killbill.billing.subscription.api.user.SubscriptionBaseApiException;
import org.killbill.billing.callcontext.InternalTenantContext;
import org.killbill.billing.account.api.AccountInternalApi;
import org.killbill.billing.invoice.api.InvoiceInternalApi;
import org.killbill.billing.junction.BlockingInternalApi;

import com.google.inject.Inject;

public class TestOverdueHelper {

    private final String configXml =
            "<overdueConfig>" +
            "   <accountOverdueStates>" +
            "       <initialReevaluationInterval>" +
            "           <unit>DAYS</unit><number>100</number>" +
            "       </initialReevaluationInterval>" +
            "       <state name=\"OD3\">" +
            "           <condition>" +
            "               <timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>" +
            "                   <unit>DAYS</unit><number>50</number>" +
            "               </timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>" +
            "           </condition>" +
            "           <externalMessage>Reached OD3</externalMessage>" +
            "           <blockChanges>true</blockChanges>" +
            "           <disableEntitlementAndChangesBlocked>true</disableEntitlementAndChangesBlocked>" +
            "       </state>" +
            "       <state name=\"OD2\">" +
            "           <condition>" +
            "               <timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>" +
            "                   <unit>DAYS</unit><number>40</number>" +
            "               </timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>" +
            "           </condition>" +
            "           <externalMessage>Reached OD2</externalMessage>" +
            "           <blockChanges>true</blockChanges>" +
            "           <disableEntitlementAndChangesBlocked>true</disableEntitlementAndChangesBlocked>" +
            "           <autoReevaluationInterval>" +
            "               <unit>DAYS</unit><number>5</number>" +
            "           </autoReevaluationInterval>" +
            "       </state>" +
            "       <state name=\"OD1\">" +
            "           <condition>" +
            "               <timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>" +
            "                   <unit>DAYS</unit><number>30</number>" +
            "               </timeSinceEarliestUnpaidInvoiceEqualsOrExceeds>" +
            "           </condition>" +
            "           <externalMessage>Reached OD1</externalMessage>" +
            "           <blockChanges>true</blockChanges>" +
            "           <disableEntitlementAndChangesBlocked>false</disableEntitlementAndChangesBlocked>" +
            "           <autoReevaluationInterval>" +
            "               <unit>DAYS</unit><number>100</number>" + // this number is intentionally too high
            "           </autoReevaluationInterval>" +
            "       </state>" +
            "   </accountOverdueStates>" +
            "</overdueConfig>";

    private final AccountInternalApi accountInternalApi;
    private final InvoiceInternalApi invoiceInternalApi;
    private final BlockingInternalApi blockingInternalApi;

    @Inject
    public TestOverdueHelper(final AccountInternalApi accountInternalApi,
                             final InvoiceInternalApi invoiceInternalApi,
                             final BlockingInternalApi blockingInternalApi) {
        this.accountInternalApi = accountInternalApi;
        this.invoiceInternalApi = invoiceInternalApi;
        this.blockingInternalApi = blockingInternalApi;
    }

    public void checkStateApplied(final OverdueState state) {
        final BlockingState result = ((ApplicatorBlockingApi) blockingInternalApi).getBlockingState();
        checkStateApplied(result, state);
    }

    public void checkStateApplied(final BlockingState result, final OverdueState state) {
        Assert.assertEquals(result.getStateName(), state.getName());
        Assert.assertEquals(result.isBlockChange(), state.isBlockChanges());
        Assert.assertEquals(result.isBlockEntitlement(), state.isDisableEntitlementAndChangesBlocked());
        Assert.assertEquals(result.isBlockBilling(), state.isDisableEntitlementAndChangesBlocked());
    }

    public ImmutableAccountData createImmutableAccountData(final LocalDate dateOfLastUnPaidInvoice) throws SubscriptionBaseApiException, AccountApiException {

        final UUID accountId = UUID.randomUUID();
        final ImmutableAccountData account = Mockito.mock(ImmutableAccountData.class);
        Mockito.when(account.getId()).thenReturn(accountId);
        Mockito.when(account.getTimeZone()).thenReturn(DateTimeZone.UTC);
        Mockito.when(accountInternalApi.getImmutableAccountDataById(Mockito.eq(account.getId()), Mockito.<InternalTenantContext>any())).thenReturn(account);

        final Invoice invoice = Mockito.mock(Invoice.class);
        Mockito.when(invoice.getInvoiceDate()).thenReturn(dateOfLastUnPaidInvoice);
        Mockito.when(invoice.getBalance()).thenReturn(BigDecimal.TEN);
        Mockito.when(invoice.getId()).thenReturn(UUID.randomUUID());

        final InvoiceItem item = Mockito.mock(InvoiceItem.class);
        final List<InvoiceItem> items = new ArrayList<InvoiceItem>();
        items.add(item);

        Mockito.when(invoice.getInvoiceItems()).thenReturn(items);

        final List<Invoice> invoices = new ArrayList<Invoice>();
        invoices.add(invoice);
        Mockito.when(invoiceInternalApi.getUnpaidInvoicesByAccountId(Mockito.<UUID>any(), Mockito.<LocalDate>any(), Mockito.<InternalTenantContext>any())).thenReturn(invoices);

        return account;
    }

    public String getConfigXml() {
        return configXml;
    }
}


text:
apt-get install -y apache2
a2enmod rewrite
a2enmod headers

# set Apache Settings
sed -i "s/#ServerRoot.*/ServerName ubuntu/" /etc/apache2/apache2.conf
sed -i "s|DocumentRoot.*|DocumentRoot /var/www|" /etc/apache2/sites-available/000-default.conf
test -d /var/www/html && rm -r /var/www/html

# Create a domainname directory for the example
mkdir -p /var/www/phpinfo.dev
echo "<?php phpinfo();" | tee /var/www/phpinfo.dev/index.php

# Configure Apache Hosts
vhost="<VirtualHost *:80>
    ServerName phpinfo.dev
    DocumentRoot /var/www/phpinfo.dev
    <Directory \"/var/www/phpinfo.dev\">
        Order allow,deny
        Allow from all
        Require all granted
        AllowOverride All
    </Directory>
</VirtualHost>"
echo "$vhost" | tee /etc/apache2/sites-available/phpinfo.dev.conf
a2ensite phpinfo.dev

# Restart apache2 service
service apache2 restart


text:
package main

import (
	"io"
	"strings"
	"text/template"
)

var generateTemplate = `
/*
 *  WARNING: CODE GENERATED AUTOMATICALLY.
 *
 *  To update any changes, run "go generate" in the main project
 *  directory and then commit this file.
 *
 *  THIS FILE SHOULD NOT BE EDITED BY HAND.
 *
 */

package meta

{{range $k, $v := .Fields -}}
// {{title $k}} is a helper function to return a slice copy of {{$v.Key}} values.
func (s Set) {{title $k}}() []{{$v.Key}} {
	{{$k}} := make([]{{$v.Key}}, len(s.{{$k}}))
        copy({{$k}}, s.{{$k}})
        return {{$k}}
}

{{end -}}

{{range $k, $v := .Lookup -}}
// {{$v.Key}} is a helper function to return a {{$v.Key}} value and true if one exists.
func (s Set) {{$v.Key}}({{join ", " $v.Fields}} string) ({{$v.Key}}, bool) {
	for _, v := range s.{{$k}} {
		{{range $f := $v.Fields -}}
		if {{$f}} != v.{{title $f}} {
			continue
		}
		{{end -}}
		return v, true
	}
	return {{$v.Key}}{{"{}"}}, false
}

{{end -}}
`

type Generate struct {
	Fields map[string]struct {
		Key string //nolint:unused // used in template
	}
	Lookup map[string]struct {
		Key    string   //nolint:unused // used in template
		Fields []string //nolint:unused // used in template
	}
}

func (g Generate) Write(w io.Writer) error {

	t, err := template.New("generate").Funcs(
		template.FuncMap{
			"title": func(s string) string { return strings.Title(s) },
			"join":  func(k string, s []string) string { return strings.Join(s, k) },
		},
	).Parse(generateTemplate)
	if err != nil {
		return err
	}
	if err := t.Execute(w, g); err != nil {
		return err
	}

	return nil
}


text:
        Date
        Rows in file
        Rows uploaded
        Status
        Summary
        Actions
        Download original files

        {{job.DateCreatedF}}

          -
          {{job.TotalRows}}

          -
          {{job.TotalRowsCommitted}}

              {{getProgress(job).Percent}}%

            View duplicated rows

            View small number warnings

            View validation failures

            View column error

            View details

              100%

            Upload

            or

            Cancel

            Ignore

            or

            Cancel

          -

          {{job.OriginalFile}}

  Show more upload jobs

  You have not uploaded any data files yet.

<ft-light-box [lightBoxConfig]="lightBoxConfig" (emitLightBoxActionConfirmed)="updateLightBoxActionConfirmed($event)">
</ft-light-box>


text:
<?php

namespace CL\Transfer;

use Harp\Harp\Config;
use Harp\Validate\Assert;
use Harp\Money\FreezableValueTrait;
use Harp\Harp\Model\SoftDeleteTrait;

trait ItemTrait
{
    use SoftDeleteTrait;
    use FreezableValueTrait;

    public static function initialize(Config $config)
    {
        SoftDeleteTrait::initialize($config);
        FreezableValueTrait::initialize($config);

        $config
            ->addAsserts([
                new Assert\Present('quantity'),
                new Assert\Number('quantity'),
                new Assert\GreaterThan('quantity', 0),
            ]);
    }

    public $quantity = 1;

    public function getDescription()
    {
        return 'Item';
    }

    public function getName()
    {
        return $this->getId();
    }

    public function getTotalValue()
    {
        return $this->getValue()->multiply($this->quantity);
    }
}


text:
package techreborn.blockentity.machine.tier0.block.blockbreaker;

import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.loot.context.LootContext;
import net.minecraft.loot.context.LootContextParameters;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.tag.BlockTags;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import reborncore.common.blockentity.RedstoneConfiguration;
import techreborn.blockentity.machine.tier0.block.BlockProcessable;
import techreborn.blockentity.machine.tier0.block.BlockProcessor;
import techreborn.blockentity.machine.tier0.block.BlockProcessorUtils;
import techreborn.blockentity.machine.tier0.block.ProcessingStatus;
import techreborn.init.TRContent;

import java.util.Collections;
import java.util.List;
import java.util.UUID;

/**
 * Class handling the process of breaking a block
 *

 * The main purpose of this class is to implement the {@link #onTick(World, BlockPos)}.
 * This method defines the logic for breaking a block
 *
 * @author SimonFlapse
 * @see techreborn.blockentity.machine.tier0.block.BlockBreakerBlockEntity
 */
public class BlockBreakerProcessor extends BlockBreakerNbt implements BlockProcessor {

	private UUID processorId = UUID.randomUUID();
	private BlockProcessable processable;

	private int outputSlot;
	private int fakeInputSlot;

	private int baseBreakTime;
	private int baseCostToBreak;

	public BlockBreakerProcessor(BlockProcessable processable, int outputSlot, int fakeInputSlot, int baseBreakTime, int baseCostToBreak) {
		this.processable = processable;

		this.outputSlot = outputSlot;
		this.fakeInputSlot = fakeInputSlot;

		this.baseBreakTime = baseBreakTime;
		this.baseCostToBreak = baseCostToBreak;
	}

	@Override
	public ProcessingStatus getStatusEnum() {
		return status;
	}

	public ProcessingStatus onTick(World world, BlockPos positionInFront) {
		handleBlockBreakingProgressReset(world, positionInFront);

		if (!ensureRedstoneEnabled()) return status;

		if (!handleInterrupted()) return status;

		ItemStack outputItemStack = processable.getInventory().getStack(outputSlot);

		BlockState blockInFront = world.getBlockState(positionInFront);

		if (!handleBlockInFrontRemoved(blockInFront)) return status;

		Item currentBreakingItem = processable.getInventory().getStack(fakeInputSlot).getItem();

		ItemStack item = blockInFront.getBlock().asItem().getDefaultStack();

		List<ItemStack> blockDrops = world instanceof ServerWorld
			? blockInFront.getDroppedStacks((new LootContext.Builder((ServerWorld) world)).random(world.random).parameter(LootContextParameters.ORIGIN, Vec3d.ofCenter(positionInFront)).parameter(LootContextParameters.TOOL, TRContent.Machine.BLOCK_BREAKER.getStack()))
			: Collections.singletonList(item);
		ItemStack blockDrop = blockDrops.isEmpty() ? null : blockDrops.get(0);
		if (blockDrop != null) {
			blockDrop.setCount(1);
		}

		ItemStack fakeItem = item.copy();

		if (fakeItem.isOf(Items.AIR)) {
			currentBreakingItem = null;
		}

		processable.getInventory().setStack(fakeInputSlot, fakeItem);

		float hardness = BlockProcessorUtils.getHardness(world, blockInFront, positionInFront);

		if (!ensureBlockCanBeBroken(blockInFront, fakeItem, hardness)) return status;

		this.breakTime = BlockProcessorUtils.getProcessTimeWithHardness(processable, baseBreakTime, hardness);

		if (!ensureBlockNotReplaced(currentBreakingItem, item)) return status;

		if (!ensureBlockFitInOutput(outputItemStack, blockDrop)) return status;

		if (!increaseBreakTime(world, positionInFront)) return status;

		BlockProcessorUtils.playSound(processable, currentBreakTime);

		breakBlock(world, positionInFront, outputItemStack, blockDrop);

		status = BlockBreakerStatus.PROCESSING;

		return status;
	}

	private boolean ensureRedstoneEnabled() {
		if (!processable.isActive(RedstoneConfiguration.RECIPE_PROCESSING)) {
			return breakControlFlow(BlockBreakerStatus.IDLE_PAUSED);
		}

		return true;
	}

	private void handleBlockBreakingProgressReset(World world, BlockPos pos) {
		//Resets the BlockBreakingProgress, otherwise the progress will be buggy when a new block has been placed
		if (currentBreakTime == 0) {
			setBlockBreakingProgress(world, pos, -1);
		}
	}

	private boolean handleInterrupted() {
		//Persists the last status message until the currentBreakTime is back to 0
		//Set the currentBreakTime to less than 0 for as many ticks as you want a message to persist.
		//The machine processing is halted while persisting messages.
		if (currentBreakTime < 0) {
			this.currentBreakTime++;
			return false;
		}
		return true;
	}

	private boolean handleBlockInFrontRemoved(BlockState blockInFront) {
		//Makes sure that if the block in front is removed, the processing resets
		if (blockInFront.isOf(Blocks.AIR)) {
			processable.getInventory().setStack(fakeInputSlot, ItemStack.EMPTY);
			resetProcessing(0);
		}

		return true;
	}

	private boolean ensureBlockCanBeBroken(BlockState blockInFront, ItemStack fakeItem, float hardness) {
		//Resets time if there is no block
		//If breaking the block returns no output, skip breaking it
		//Blocks with a hardness below 0 are unbreakable
		//shulker boxes don't drop their content when broken, so ignore them for now
		if (blockInFront.isAir() || fakeItem.isEmpty() || hardness < 0 || blockInFront.isIn(BlockTags.SHULKER_BOXES)) {
			return breakControlFlow(BlockBreakerStatus.IDLE);
		}

		return true;
	}

	private boolean ensureBlockNotReplaced(Item currentBreakingItem, ItemStack item) {
		//Ensures that a piston cannot be abused to push in another block without resetting the progress
		if (currentBreakingItem != null && !ItemStack.EMPTY.isOf(currentBreakingItem) && !item.isOf(currentBreakingItem)) {
			return breakControlFlow(BlockBreakerStatus.INTERRUPTED);
		}

		return true;
	}

	private boolean ensureBlockFitInOutput(ItemStack currentStack, ItemStack blockDrop) {
		if (blockDrop == null || blockDrop.getCount() == 0) {
			return true;
		}

		//Ensures that the block is the same as the one currently in the output slot
		if (!currentStack.isOf(ItemStack.EMPTY.getItem()) && !currentStack.isOf(blockDrop.getItem())) {
			return breakControlFlow(BlockBreakerStatus.OUTPUT_BLOCKED);
		}

		//Ensure that output slot can fit the block
		if (currentStack.getMaxCount() < currentStack.getCount() + blockDrop.getCount()) {
			return breakControlFlow(BlockBreakerStatus.OUTPUT_FULL);
		}

		return true;
	}

	private boolean increaseBreakTime(World world, BlockPos blockPos) {
		//if (!tryUseExact(getEuPerTick(baseCostToBreak))) {
		if (!processable.consumeEnergy(baseCostToBreak)) {
			return breakControlFlow(BlockBreakerStatus.NO_ENERGY);
		}

		setBlockBreakingProgress(world, blockPos);
		this.currentBreakTime++;
		return true;
	}

	private void breakBlock(World world, BlockPos positionInFront, ItemStack currentStack, ItemStack blockDrop) {
		if (currentBreakTime >= breakTime) {

			world.breakBlock(positionInFront, false);

			resetProcessing(0);

			if (blockDrop == null || blockDrop.getCount() == 0) {
				return;
			}
			if (currentStack.isOf(ItemStack.EMPTY.getItem())) {
				processable.getInventory().setStack(outputSlot, blockDrop);
			} else {
				int currentCount = currentStack.getCount();
				currentStack.setCount(currentCount + blockDrop.getCount());
			}
		}
	}

	private void resetProcessing(int tick) {
		this.currentBreakTime = tick;
		breakTime = baseBreakTime;
	}

	private void setBlockBreakingProgress(World world, BlockPos blockPos) {
		setBlockBreakingProgress(world, blockPos, getProgress() / 10);
	}

	private void setBlockBreakingProgress(World world, BlockPos blockPos, int breakingProgress) {
		world.setBlockBreakingInfo(processorId.hashCode(), blockPos, breakingProgress);
	}

	@Override
	public int getCurrentTickTime() {
		return this.getCurrentBreakTime();
	}

	@Override
	public int getTickTime() {
		return this.getBreakTime();
	}

	private boolean breakControlFlow(ProcessingStatus status) {
		resetProcessing(-20);
		this.status = status;
		return false;
	}
}


text:
package nam.client.src.main.resources.maven;

import aries.codegen.AbstractFileGenerator;
import aries.generation.engine.GenerationContext;

public class MavenServerPropertiesFileGenerator extends AbstractFileGenerator {

	public MavenServerPropertiesFileGenerator(GenerationContext context) {
		this.context = context;
	}

}


text:
function [ c, gamma, zeta, mu, cL, zetaL ] = computeEigenfunctions( obj, ...
                                                 diffOp, varargin )
% COMPUTEEIGENFUNCTIONS Compute eigenvalues, eigenfunctions, and left
% eigenfunctions of Koopman generator.
%
% diffOp is an nlsaKernelOperator object providing the basis functions.
%
% Output arguments:
%
% c: A matrix of size [ nPhi nEig ] storing the expansion coefficients of the
%    Koopman eigenfunctions. nPhi is the number of diffusion eigenfunctions
%    employed, and nEig is the number of computed Koopman eigenfunctions.
%
% gamma: A row vector of size [ 1 nEig ] storing the generator eigenvalues.
%
% zeta: A matrix of size [ nS nPhi ] storing the values of the Koopman
%      eigenfunctions. nS is the number of samples.
%
% mu: A column vector of size [ nS 1 ] storing the inner product weights with
%     repect to which the phi are orthonormal.
%
% cL: A matrix of size [ nPhi nEig ] storing the expansion coefficients of the
%     left eigenfunctions.
%
% zetaL: A matrix of size [ nS nPhi ] storing the values of the left
%        eigenfunctions.
%
% Modified 2020/08/28

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Validate input arguments
if ~isa( diffOp, 'nlsaKernelOperator' ) || ~isscalar( diffOp )
    msgStr = [ 'Second input argument must be a scalar nlsaKernelOperator ' ...
               'object.' ];
    error( msgStr )
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Parse options, setup logfile and write calculation summary
Opt.ifCalcOperator                   = true;
Opt.ifLeftEigenfunctions             = false;
Opt.ifWriteOperator                  = false;
Opt.ifWriteEigenfunctions            = true;
Opt.ifWriteEigenfunctionCoefficients = true;
Opt.logFile                          = '';
Opt.logPath                          = getOperatorPath( obj );
Opt.logFilePermissions               = 'w';

Opt = parseargs( Opt, varargin{ : } );
nEig = getNEigenfunction( obj );
idxPhi = getBasisFunctionIndices( obj );

if isempty( Opt.logFile )
    logId = 1;
else
    logId = fopen( fullfile( Opt.logPath, Opt.logFile ), ...
                   Opt.logFilePermissions );
end
ifZeta  = Opt.ifWriteEigenfunctions || nargout > 2;
ifCL    = Opt.ifLeftEigenfunctions || nargout > 4;
ifZetaL = ( ifCL && Opt.ifWriteEigenfunctions ) || nargout == 5;
clk = clock;
[ ~, hostname ] = unix( 'hostname' );
fprintf( logId, 'computeEigenfunctions starting on %i/%i/%i %i:%i:%2.1f \n', ...
    clk( 1 ), clk( 2 ), clk( 3 ), clk( 4 ), clk( 5 ), clk( 6 ) );
fprintf( logId, 'Hostname %s \n', hostname );
fprintf( logId, 'Path %s \n', obj.path );
fprintf( logId, 'Number of eigenfunctions       = %i \n', nEig );
fprintf( logId, 'Basis function incices         = %s \n', idx2str( idxPhi ) );

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Read or compute the generator matrix
if ~Opt.ifCalcOperator
    tWall0 = tic;
    V = getOperator( obj );
    tWall = toc( tWall0 );
    fprintf( logId, 'READ %2.4f \n', tWall );
else
    if ~isempty( Opt.logFile )
        fclose( logId );
    end
    V = computeOperator( obj, diffOp, 'logPath', Opt.logPath, ...
                                      'logFile', Opt.logFile, ...
                                      'logFilePermissions', 'a', ...
                                      'ifWriteOperator', Opt.ifWriteOperator );
    if ~isempty( Opt.logFile )
        logId = fopen( fullfile( Opt.logPath, Opt.logFile ), 'a' );
    end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Solve the generator eigenvalue problem
% c is a matrix storing the expansion coefficients of the eigenfunctions of
% the generator in the eigenbasis of diffOp
tWall0 = tic;
[ c, gamma ]  = eig( V );
gamma         = diag( gamma ).';
tWall         = toc( tWall0 );
fprintf( logId, 'EIGV %2.4f \n', tWall );

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% If requested compute the left eigenvectors.
% cL is a matrix storing the expansion coefficients of the left eigenfunctions
% the generator in the eigenbasis of diffOp
if ifCL
    tWall0 = tic;
    S = c * c';  % analysis operator
    cL = S \ c;  % dual basis
    tWall         = toc( tWall0 );
    fprintf( logId, 'EIGVL %2.4f \n', tWall );
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Truncate to the selected number of eigenfunctions
c = c( :, 1 : nEig );
gamma = gamma( 1 : nEig ) .'; % gamma is a row vector
if ifCL
    cL  = cL( :, 1 : nEig );
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% If requested, evaluate the eigenfunctions
if ifZeta
    tWall0 = tic;
    [ phi, mu ] = getEigenfunctions( diffOp );
    phi = phi( :, idxPhi );
    zeta = phi * c;
    tWall = toc( tWall0 );
    fprintf( logId, 'EVALEIG %2.4f \n', tWall );
end
if ifZetaL
    tWall0 = tic;
    zetaL = phi * cL;
    tWall = toc( tWall0 );
    fprintf( logId, 'EVALEIGL %2.4f \n', tWall );
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Write out results
tWall0 = tic;
if Opt.ifWriteEigenfunctionCoefficients
    setEigenvalues( obj, gamma )
    setEigenfunctionCoefficients( obj, c )
    if Opt.ifLeftEigenfunctions
        setLeftEigenfunctionCoefficients( obj, cL )
    end
end
if Opt.ifWriteEigenfunctions
    setEigenfunctions( obj, zeta, mu, '-v7.3' )
    if Opt.ifLeftEigenfunctions
        setLeftEigenfunctions( obj, zetaL, mu, '-v7.3' )
    end
end
tWall = toc( tWall0 );
fprintf( logId, 'WRITEEIG %2.4f \n', tWall );

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clk = clock; % Exit gracefully
fprintf( logId, 'computeEigenfunctions finished on %i/%i/%i %i:%i:%2.1f \n', ...
    clk( 1 ), clk( 2 ), clk( 3 ), clk( 4 ), clk( 5 ), clk( 6 ) );
if ~isempty( Opt.logFile )
    fclose( logId );
end


text:
package org.alien4cloud.tosca.model.definitions;

public interface UpperBoundedDefinition {

    void setUpperBound(int upperBound);

}


text:
"""
Summary measures for ergodic Markov chains.
"""
__author__ = "Sergio J. Rey <sjsrey@gmail.com>, Wei Kang <weikang9009@gmail.com>"

__all__ = ["steady_state", "var_mfpt_ergodic", "mfpt"]

import numpy as np
import numpy.linalg as la
import quantecon as qe
from warnings import warn
from .util import fill_empty_diagonals

def _steady_state_ergodic(P):
    """
    Calculates the steady state probability vector for a regular Markov
    transition matrix P.

    Parameters
    ----------
    P        : array
               (k, k), an ergodic Markov transition probability matrix.

    Returns
    -------
             : array
               (k, ), steady state distribution.

    Examples
    --------
    Taken from :cite:`Kemeny1967`. Land of Oz example where the states are
    Rain, Nice and Snow, so there is 25 percent chance that if it
    rained in Oz today, it will snow tomorrow, while if it snowed today in
    Oz there is a 50 percent chance of snow again tomorrow and a 25
    percent chance of a nice day (nice, like when the witch with the monkeys
    is melting).

    >>> import numpy as np
    >>> import giddy
    >>> p=np.array([[.5, .25, .25],[.5,0,.5],[.25,.25,.5]])
    >>> giddy.ergodic._steady_state_ergodic(p)
    array([0.4, 0.2, 0.4])

    Thus, the long run distribution for Oz is to have 40 percent of the
    days classified as Rain, 20 percent as Nice, and 40 percent as Snow
    (states are mutually exclusive).

    """

    v, d = la.eig(np.transpose(P))
    d = np.array(d)

    # for a regular P maximum eigenvalue will be 1
    mv = max(v)
    # find its position
    i = v.tolist().index(mv)

    row = abs(d[:, i])

    # normalize eigenvector corresponding to the eigenvalue 1
    return row / sum(row)

def steady_state(P, fill_empty_classes=False):
    """
    Generalized function for calculating the steady state distribution
    for a regular or reducible Markov transition matrix P.

    Parameters
    ----------
    P        : array
               (k, k), an ergodic or non-ergodic Markov transition probability
               matrix.
    fill_empty_classes: bool, optional
                        If True, assign 1 to diagonal elements which fall in rows full
                        of 0s to ensure the transition probability matrix is a
                        stochastic one. Default is False.

    Returns
    -------
             : array
               If the Markov chain is irreducible, meaning that
               there is only one communicating class, there is one unique
               steady state distribution towards which the system is
               converging in the long run. Then steady_state is the
               same as _steady_state_ergodic (k, ).
               If the Markov chain is reducible, but only has 1 recurrent
               class, there will be one steady state distribution as well.
               If the Markov chain is reducible and there are multiple
               recurrent classes (num_rclasses), the system could be trapped
               in any one of  these recurrent classes. Then, there will be
               `num_rclasses` steady state distributions. The returned array
               will of (num_rclasses, k) dimension.

    Examples
    --------

    >>> import numpy as np
    >>> from giddy.ergodic import steady_state

    Irreducible Markov chain
    >>> p = np.array([[.5, .25, .25],[.5,0,.5],[.25,.25,.5]])
    >>> steady_state(p)
    array([0.4, 0.2, 0.4])

    Reducible Markov chain: two communicating classes
    >>> p = np.array([[.5, .5, 0],[.2,0.8,0],[0,0,1]])
    >>> steady_state(p)
    array([[0.28571429, 0.71428571, 0.        ],
           [0.        , 0.        , 1.        ]])

    Reducible Markov chain: two communicating classes
    >>> p = np.array([[.5, .5, 0],[.2,0.8,0],[0,0,0]])
    >>> steady_state(p, fill_empty_classes = True)
    array([[0.28571429, 0.71428571, 0.        ],
           [0.        , 0.        , 1.        ]])

    >>> steady_state(p, fill_empty_classes = False)
    Traceback (most recent call last):
        ...
    ValueError: Input transition probability matrix has 1 rows full of 0s. Please set fill_empty_classes=True to set diagonal elements for these rows to be 1 to make sure the matrix is stochastic.

    """

    P = np.asarray(P)
    rows0 = (P.sum(axis=1) == 0).sum()
    if rows0 > 0:
        if fill_empty_classes:
            P = fill_empty_diagonals(P)
        else:
            raise ValueError(
                "Input transition probability matrix has "
                "%d rows full of 0s. Please set "
                "fill_empty_classes=True to set diagonal "
                "elements for these rows to be 1 to make "
                "sure the matrix is stochastic." % rows0
            )
    mc = qe.MarkovChain(P)
    num_classes = mc.num_communication_classes
    if num_classes == 1:
        return mc.stationary_distributions[0]
    else:
        return mc.stationary_distributions

def _fmpt_ergodic(P):
    warn('_fmpt_ergodic is deprecated. It will be replaced in giddy 2.5 with _mfpt_',
         DeprecationWarning, stacklevel=2)
    return _mfpt_ergodic(P)

def _mfpt_ergodic(P):
    """
    Calculates the matrix of mean first passage times for an ergodic transition
    probability matrix.

    Parameters
    ----------
    P    : array
           (k, k), an ergodic Markov transition probability matrix.

    Returns
    -------
    M    : array
           (k, k), elements are the expected value for the number of intervals
           required for a chain starting in state i to first enter state j.
           If i=j then this is the recurrence time.

    Examples
    --------
    >>> import numpy as np
    >>> import giddy
    >>> p=np.array([[.5, .25, .25],[.5,0,.5],[.25,.25,.5]])
    >>> fm = giddy.ergodic._mfpt_ergodic(p)
    >>> fm
    array([[2.5       , 4.        , 3.33333333],
           [2.66666667, 5.        , 2.66666667],
           [3.33333333, 4.        , 2.5       ]])

    Thus, if it is raining today in Oz we can expect a nice day to come
    along in another 4 days, on average, and snow to hit in 3.33 days. We can
    expect another rainy day in 2.5 days. If it is nice today in Oz, we would
    experience a change in the weather (either rain or snow) in 2.67 days from
    today. (That wicked witch can only die once so I reckon that is the
    ultimate absorbing state).

    Notes
    -----
    Uses formulation (and examples on p. 218) in :cite:`Kemeny1967`.

    """

    P = np.asarray(P)
    k = P.shape[0]
    A = np.zeros_like(P)
    ss = _steady_state_ergodic(P)
    for i in range(k):
        A[:, i] = ss
    A = A.transpose()
    I = np.identity(k)
    Z = la.inv(I - P + A)
    E = np.ones_like(Z)
    A_diag = np.diag(A)
    A_diag = A_diag + (A_diag == 0)
    D = np.diag(1.0 / A_diag)
    Zdg = np.diag(np.diag(Z))
    M = (I - Z + E.dot(Zdg)).dot(D)
    return M

def fmpt(P, fill_empty_classes=False):
    warn('fmpt is deprecated. It will be replaced in giddy 2.5 with mfpt',
         DeprecationWarning, stacklevel=2)
    return mfpt(P, fill_empty_classes)

def mfpt(P, fill_empty_classes=False):
    """
    Generalized function for calculating mean first passage times for an
    ergodic or non-ergodic transition probability matrix.

    Parameters
    ----------
    P        : array
               (k, k), an ergodic/non-ergodic Markov transition probability
               matrix.
    fill_empty_classes: bool, optional
                        If True, assign 1 to diagonal elements which fall in rows full
                        of 0s to ensure the transition probability matrix is a
                        stochastic one. Default is False.

    Returns
    -------
    mfpt_all : array
               (k, k), elements are the expected value for the number of
               intervals required for a chain starting in state i to first
               enter state j. If i=j then this is the recurrence time.

    Examples
    --------
    >>> import numpy as np
    >>> from giddy.ergodic import mfpt
    >>> np.set_printoptions(suppress=True) #prevent scientific format

    Irreducible Markov chain
    >>> p = np.array([[.5, .25, .25],[.5,0,.5],[.25,.25,.5]])
    >>> fm = mfpt(p)
    >>> fm
    array([[2.5       , 4.        , 3.33333333],
           [2.66666667, 5.        , 2.66666667],
           [3.33333333, 4.        , 2.5       ]])

    Thus, if it is raining today in Oz we can expect a nice day to come
    along in another 4 days, on average, and snow to hit in 3.33 days. We can
    expect another rainy day in 2.5 days. If it is nice today in Oz, we would
    experience a change in the weather (either rain or snow) in 2.67 days from
    today.

    Reducible Markov chain: two communicating classes (this is an
    artificial example)
    >>> p = np.array([[.5, .5, 0],[.2,0.8,0],[0,0,1]])
    >>> mfpt(p)
    array([[3.5, 2. , inf],
           [5. , 1.4, inf],
           [inf, inf, 1. ]])

    Thus, if it is raining today in Oz we can expect a nice day to come
    along in another 2 days, on average, and should not expect snow to hit.
    We can expect another rainy day in 3.5 days. If it is nice today in Oz,
    we should expect a rainy day in 5 days.

    >>> p = np.array([[.5, .5, 0],[.2,0.8,0],[0,0,0]])
    >>> mfpt(p, fill_empty_classes=True)
    array([[3.5, 2. , inf],
           [5. , 1.4, inf],
           [inf, inf, 1. ]])

    >>> p = np.array([[.5, .5, 0],[.2,0.8,0],[0,0,0]])
    >>> mfpt(p, fill_empty_classes=False)
    Traceback (most recent call last):
        ...
    ValueError: Input transition probability matrix has 1 rows full of 0s. Please set fill_empty_classes=True to set diagonal elements for these rows to be 1 to make sure the matrix is stochastic.
    """

    P = np.asarray(P)
    rows0 = (P.sum(axis=1) == 0).sum()
    if rows0 > 0:
        if fill_empty_classes:
            P = fill_empty_diagonals(P)
        else:
            raise ValueError(
                "Input transition probability matrix has "
                "%d rows full of 0s. Please set "
                "fill_empty_classes=True to set diagonal "
                "elements for these rows to be 1 to make "
                "sure the matrix is stochastic." % rows0
            )
    mc = qe.MarkovChain(P)
    num_classes = mc.num_communication_classes
    if num_classes == 1:
        mfpt_all = _mfpt_ergodic(P)
    else:  # deal with non-ergodic Markov chains
        k = P.shape[0]
        mfpt_all = np.zeros((k, k))
        for desti in range(k):
            b = np.ones(k - 1)
            p_sub = np.delete(np.delete(P, desti, 0), desti, 1)
            p_calc = np.eye(k - 1) - p_sub
            m = np.full(k - 1, np.inf)
            row0 = (p_calc != 0).sum(axis=1)
            none0 = np.arange(k - 1)
            try:
                m[none0] = np.linalg.solve(p_calc, b)
            except np.linalg.LinAlgError as err:
                if "Singular matrix" in str(err):
                    if (row0 == 0).sum() > 0:
                        index0 = set(np.argwhere(row0 == 0).flatten())
                        x = (p_calc[:, list(index0)] != 0).sum(axis=1)
                        setx = set(np.argwhere(x).flatten())
                        while not setx.issubset(index0):
                            index0 = index0.union(setx)
                            x = (p_calc[:, list(index0)] != 0).sum(axis=1)
                            setx = set(np.argwhere(x).flatten())
                        none0 = np.asarray(list(set(none0).difference(index0)))
                        if len(none0) >= 1:
                            p_calc = p_calc[none0, :][:, none0]
                            b = b[none0]
                            m[none0] = np.linalg.solve(p_calc, b)
            recc = (
                np.nan_to_num(
                    (np.delete(P, desti, 1)[desti] * m), 0, posinf=np.inf
                ).sum()
                + 1
            )
            mfpt_all[:, desti] = np.insert(m, desti, recc)
            mfpt_all = np.where(mfpt_all < -1e16, np.inf, mfpt_all)
            mfpt_all = np.where(mfpt_all > 1e16, np.inf, mfpt_all)
    return mfpt_all

def var_fmpt_ergodic(p):
    warn('var_fmpt_ergodic is deprecated. It will be replaced in giddy 2.5 with var_fmpt_ergodic',
         DeprecationWarning, stacklevel=2)
    return var_mfpt_ergodic(p)

def var_mfpt_ergodic(p):
    """
    Variances of mean first passage times for an ergodic transition
    probability matrix.

    Parameters
    ----------
    P      : array
             (k, k), an ergodic Markov transition probability matrix.

    Returns
    -------
           : array
             (k, k), elements are the variances for the number of intervals
             required for a chain starting in state i to first enter state j.

    Examples
    --------
    >>> import numpy as np
    >>> from giddy.ergodic import var_mfpt_ergodic
    >>> p=np.array([[.5, .25, .25],[.5,0,.5],[.25,.25,.5]])
    >>> vfm=var_mfpt_ergodic(p)
    >>> vfm
    array([[ 5.58333333, 12.        ,  6.88888889],
           [ 6.22222222, 12.        ,  6.22222222],
           [ 6.88888889, 12.        ,  5.58333333]])

    Notes
    -----
    Uses formulation (and examples on p. 83) in :cite:`Kemeny1967`.

    """

    P = np.asarray(p)
    k = P.shape[0]
    A = _steady_state_ergodic(P)
    A = np.tile(A, (k, 1))
    I = np.identity(k)
    Z = la.inv(I - P + A)
    E = np.ones_like(Z)
    D = np.diag(1.0 / np.diag(A))
    Zdg = np.diag(np.diag(Z))
    M = (I - Z + E.dot(Zdg)).dot(D)
    ZM = Z.dot(M)
    ZMdg = np.diag(np.diag(ZM))
    W = M.dot(2 * Zdg.dot(D) - I) + 2 * (ZM - E.dot(ZMdg))
    return np.array(W - np.multiply(M, M))


text:
package com.chen.web.admin.dept;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.chen.service.DeptService;
import com.chen.web.Controller;

@WebServlet("/admin/dept/change.do")
public class ChangeServlet extends Controller{

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		forward("dept/change.jsp", request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String sid = request.getParameter("id");
		String deptname = request.getParameter("deptname");
		Map<String, Object> map = new HashMap<String, Object>();
		if(sid == null || StringUtils.isNumeric(sid)){
			map.put("result", "error");
			map.put("message", "·Ç·¨²Ù×÷");
		}
		Long id = Long.valueOf(sid);
		if(id < 0){
			map.put("result", "error");
			map.put("message", "idΪ¸ºÊý£¬·Ç·¨²Ù×÷");
			map.put("value", deptname);
		}
		if(deptname == null){
			map.put("result", "error");
			map.put("message", "ÊäÈëµÄÃû×ÖΪ¿Õ£¬·Ç·¨²Ù×÷");
			map.put("value", deptname);
		}
		DeptService ds = new DeptService();
		if(ds.changeDept(deptname, id) > 0){
			map.put("result", "success");
			map.put("message", "Ð޸ijɹ¦");
			map.put("value", deptname);
		}else{
			map.put("result", "error");
			map.put("message", "id²»´æÔÚ");
			map.put("value", deptname);
		}
		renderJson(response, map);
	}

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="<?php echo ADMIN_THEME?>images/reset.css" rel="stylesheet" type="text/css" />
<link href="<?php echo ADMIN_THEME?>images/system.css" rel="stylesheet" type="text/css" />
<link href="<?php echo ADMIN_THEME?>images/dialog.css" rel="stylesheet" type="text/css" />
<link href="<?php echo ADMIN_THEME?>images/main.css" rel="stylesheet" type="text/css" />
<link href="<?php echo ADMIN_THEME?>images/switchbox.css" rel="stylesheet" type="text/css" />
<link href="<?php echo ADMIN_THEME?>images/table_form.css" rel="stylesheet" type="text/css" />

<title>后台管理</title>

<a href='<?php echo purl("admin")?>' class="on">广告位管理|
<a href='<?php echo purl("admin/add")?>'>添加广告位|
<a href='<?php echo purl("admin/cache")?>'>更新广告缓存

<form action="" method="post">

	  选择 <input name="deletec" id="deletec" type="checkbox" onClick="setC()">
		广告位名称
		宽x高
		显示类型
		管理操作

    <?php foreach ($list as $t) {
	?>

	  <input name="data[]" type="checkbox" class="deletec" value="<?php echo $t['id'];?>">
	  <?php echo $t['adname'];?>
	  <?php echo $t['width'];?>x<?php echo $t['height'];?>
	  <?php echo $t['showtype'] ? '顺序显示' : '随机显示';?>

      <a href="<?php echo purl('admin/alist/',array('aid'=>$t[id]));?>">广告管理 |
      <a href="<?php echo purl('admin/edit/',array('id'=>$t[id]));?>">修改 |
      <a href="javascript:;" onClick="if(confirm('确定删除吗?')){ window.location.href='<?php echo purl('admin/del/',array('id'=>$t['id']));?>'; }">删除 |
      <a href="javascript:;" onClick="getViewData(<?php echo $t['id']?>);">调用代码

      <?php } ?>

      <input type="submit" class="button" value="删  除" name="submit">

<?php echo $pagelist['html']?>

</form>


text:
const passport = require('passport'),
  User = require('../models/user'),
  config = require('./main'),
  JwtStrategy = require('passport-jwt').Strategy,
  ExtractJwt = require('passport-jwt').ExtractJwt,
  LocalStrategy = require('passport-local');

// Setting username field to email rather than username
const localOptions = {
  usernameField: 'email'
};

// Setting up local login strategy
const localLogin = new LocalStrategy(localOptions, (email, password, done) => {
  User.findOne({ email }, (err, user) => {
    if (err) { return done(err); }
    if (!user) { return done(null, false, { error: 'Your login details could not be verified. Please try again.' }); }

    user.comparePassword(password, (err, isMatch) => {
      if (err) { return done(err); }
      if (!isMatch) { return done(null, false, { error: 'Your login details could not be verified. Please try again.' }); }

      return done(null, user);
    });
  });
});

// Setting JWT strategy options
const jwtOptions = {
  // Telling Passport to check authorization headers for JWT
  jwtFromRequest: ExtractJwt.fromAuthHeader(),
  // Telling Passport where to find the secret
  secretOrKey: config.secret

  // TO-DO: Add issuer and audience checks
};

// Setting up JWT login strategy
const jwtLogin = new JwtStrategy(jwtOptions, (payload, done) => {
  User.findById(payload._id, (err, user) => {
    if (err) { return done(err, false); }

    if (user) {
      done(null, user);
    } else {
      console.log("hitme", user);
      done(null, false);

    }
  });
});

passport.use(jwtLogin);
passport.use(localLogin);