text:
@implementation RoutingHTTPServer {
	NSMutableDictionary *routes;
	NSMutableDictionary *defaultHeaders;
	NSMutableDictionary *mimeTypes;
	dispatch_queue_t routeQueue;
}

@synthesize defaultHeaders;

- (id)init {
	if (self = [super init]) {
		connectionClass = [RoutingConnection self];
		routes = [[NSMutableDictionary alloc] init];
		defaultHeaders = [[NSMutableDictionary alloc] init];
		[self setupMIMETypes];
	}
	return self;
}

#if !OS_OBJECT_USE_OBJC_RETAIN_RELEASE
- (void)dealloc {
	if (routeQueue)
		dispatch_release(routeQueue);
}
#endif

- (void)setDefaultHeaders:(NSDictionary *)headers {
	if (headers) {
		defaultHeaders = [headers mutableCopy];
	} else {
		defaultHeaders = [[NSMutableDictionary alloc] init];
	}
}

- (void)setDefaultHeader:(NSString *)field value:(NSString *)value {
	[defaultHeaders setObject:value forKey:field];
}

- (dispatch_queue_t)routeQueue {
	return routeQueue;
}

- (void)setRouteQueue:(dispatch_queue_t)queue {
#if !OS_OBJECT_USE_OBJC_RETAIN_RELEASE
	if (queue)
		dispatch_retain(queue);

	if (routeQueue)
		dispatch_release(routeQueue);
#endif

	routeQueue = queue;
}

- (NSDictionary *)mimeTypes {
	return mimeTypes;
}

- (void)setMIMETypes:(NSDictionary *)types {
	NSMutableDictionary *newTypes;
	if (types) {
		newTypes = [types mutableCopy];
	} else {
		newTypes = [[NSMutableDictionary alloc] init];
	}

	mimeTypes = newTypes;
}

- (void)setMIMEType:(NSString *)theType forExtension:(NSString *)ext {
	[mimeTypes setObject:theType forKey:ext];
}

- (NSString *)mimeTypeForPath:(NSString *)path {
	NSString *ext = [[path pathExtension] lowercaseString];
	if (!ext || [ext length] < 1)
		return nil;

	return [mimeTypes objectForKey:ext];
}

- (void)get:(NSString *)path withBlock:(RequestHandler)block {
	[self handleMethod:@"GET" withPath:path block:block];
}

- (void)post:(NSString *)path withBlock:(RequestHandler)block {
	[self handleMethod:@"POST" withPath:path block:block];
}

- (void)put:(NSString *)path withBlock:(RequestHandler)block {
	[self handleMethod:@"PUT" withPath:path block:block];
}

- (void)delete:(NSString *)path withBlock:(RequestHandler)block {
	[self handleMethod:@"DELETE" withPath:path block:block];
}

- (void)subscribe:(NSString *)path withBlock:(RequestHandler)block {
	[self handleMethod:@"SUBSCRIBE" withPath:path block:block];
}

- (void)unsubscribe:(NSString *)path withBlock:(RequestHandler)block {
	[self handleMethod:@"UNSUBSCRIBE" withPath:path block:block];
}

- (void)handleMethod:(NSString *)method withPath:(NSString *)path block:(RequestHandler)block {
	Route *route = [self routeWithPath:path];
	route.handler = block;

	[self addRoute:route forMethod:method];
}

- (void)handleMethod:(NSString *)method withPath:(NSString *)path target:(id)target selector:(SEL)selector {
	Route *route = [self routeWithPath:path];
	route.target = target;
	route.selector = selector;

	[self addRoute:route forMethod:method];
}

- (void)addRoute:(Route *)route forMethod:(NSString *)method {
	method = [method uppercaseString];
	NSMutableArray *methodRoutes = [routes objectForKey:method];
	if (methodRoutes == nil) {
		methodRoutes = [NSMutableArray array];
		[routes setObject:methodRoutes forKey:method];
	}

	[methodRoutes addObject:route];

	// Define a HEAD route for all GET routes
	if ([method isEqualToString:@"GET"]) {
		[self addRoute:route forMethod:@"HEAD"];
	}
}

- (Route *)routeWithPath:(NSString *)path {
	Route *route = [[Route alloc] init];
	NSMutableArray *keys = [NSMutableArray array];

	if ([path length] > 2 && [path characterAtIndex:0] == '{') {
		// This is a custom regular expression, just remove the {}
		path = [path substringWithRange:NSMakeRange(1, [path length] - 2)];
	} else {
		NSRegularExpression *regex = nil;

		// Escape regex characters
		regex = [NSRegularExpression regularExpressionWithPattern:@"[.+()]" options:0 error:nil];
		path = [regex stringByReplacingMatchesInString:path options:0 range:NSMakeRange(0, path.length) withTemplate:@"\\\\$0"];

		// Parse any :parameters and * in the path
		regex = [NSRegularExpression regularExpressionWithPattern:@"(:(\\w+)|\\*)"
														  options:0
															error:nil];
		NSMutableString *regexPath = [NSMutableString stringWithString:path];
		__block NSInteger diff = 0;
		[regex enumerateMatchesInString:path options:0 range:NSMakeRange(0, path.length)
			usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
				NSRange replacementRange = NSMakeRange(diff + result.range.location, result.range.length);
				NSString *replacementString;

				NSString *capturedString = [path substringWithRange:result.range];
				if ([capturedString isEqualToString:@"*"]) {
					[keys addObject:@"wildcards"];
					replacementString = @"(.*?)";
				} else {
					NSString *keyString = [path substringWithRange:[result rangeAtIndex:2]];
					[keys addObject:keyString];
					replacementString = @"([^/]+)";
				}

				[regexPath replaceCharactersInRange:replacementRange withString:replacementString];
				diff += replacementString.length - result.range.length;
			}];

		path = [NSString stringWithFormat:@"^%@$", regexPath];
	}

	route.regex = [NSRegularExpression regularExpressionWithPattern:path options:NSRegularExpressionCaseInsensitive error:nil];
	if ([keys count] > 0) {
		route.keys = keys;
	}

	return route;
}

- (BOOL)supportsMethod:(NSString *)method {
	return ([routes objectForKey:method] != nil);
}

- (void)handleRoute:(Route *)route withRequest:(RouteRequest *)request response:(RouteResponse *)response {
	if (route.handler) {
		route.handler(request, response);
	} else {
		#pragma clang diagnostic push
		#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
		[route.target performSelector:route.selector withObject:request withObject:response];
		#pragma clang diagnostic pop
	}
}

- (RouteResponse *)routeMethod:(NSString *)method withPath:(NSString *)path parameters:(NSDictionary *)params request:(HTTPMessage *)httpMessage connection:(HTTPConnection *)connection {
	NSMutableArray *methodRoutes = [routes objectForKey:method];
	if (methodRoutes == nil)
		return nil;

	for (Route *route in methodRoutes) {
		NSTextCheckingResult *result = [route.regex firstMatchInString:path options:0 range:NSMakeRange(0, path.length)];
		if (!result)
			continue;

		// The first range is all of the text matched by the regex.
		NSUInteger captureCount = [result numberOfRanges];

		if (route.keys) {
			// Add the route's parameters to the parameter dictionary, accounting for
			// the first range containing the matched text.
			if (captureCount == [route.keys count] + 1) {
				NSMutableDictionary *newParams = [params mutableCopy];
				NSUInteger index = 1;
				BOOL firstWildcard = YES;
				for (NSString *key in route.keys) {
					NSString *capture = [path substringWithRange:[result rangeAtIndex:index]];
					if ([key isEqualToString:@"wildcards"]) {
						NSMutableArray *wildcards = [newParams objectForKey:key];
						if (firstWildcard) {
							// Create a new array and replace any existing object with the same key
							wildcards = [NSMutableArray array];
							[newParams setObject:wildcards forKey:key];
							firstWildcard = NO;
						}
						[wildcards addObject:capture];
					} else {
						[newParams setObject:capture forKey:key];
					}
					index++;
				}
				params = newParams;
			}
		} else if (captureCount > 1) {
			// For custom regular expressions place the anonymous captures in the captures parameter
			NSMutableDictionary *newParams = [params mutableCopy];
			NSMutableArray *captures = [NSMutableArray array];
			for (NSUInteger i = 1; i < captureCount; i++) {
				[captures addObject:[path substringWithRange:[result rangeAtIndex:i]]];
			}
			[newParams setObject:captures forKey:@"captures"];
			params = newParams;
		}

		RouteRequest *request = [[RouteRequest alloc] initWithHTTPMessage:httpMessage parameters:params];
		RouteResponse *response = [[RouteResponse alloc] initWithConnection:connection];
		if (!routeQueue) {
			[self handleRoute:route withRequest:request response:response];
		} else {
			// Process the route on the specified queue
			dispatch_sync(routeQueue, ^{
				@autoreleasepool {
					[self handleRoute:route withRequest:request response:response];
				}
			});
		}
		return response;
	}

	return nil;
}

- (void)setupMIMETypes {
	mimeTypes = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
				 @"application/x-javascript",   @"js",
				 @"image/gif",                  @"gif",
				 @"image/jpeg",                 @"jpg",
				 @"image/jpeg",                 @"jpeg",
				 @"image/png",                  @"png",
				 @"image/svg+xml",              @"svg",
				 @"image/tiff",                 @"tif",
				 @"image/tiff",                 @"tiff",
				 @"image/x-icon",               @"ico",
				 @"image/x-ms-bmp",             @"bmp",
				 @"text/css",                   @"css",
				 @"text/html",                  @"html",
				 @"text/html",                  @"htm",
				 @"text/plain",                 @"txt",
				 @"text/xml",                   @"xml",
				 nil];
}

@end


text:
package org.apache.derbyTesting.unitTests.store;

import org.apache.derby.iapi.store.raw.*;

import org.apache.derby.iapi.services.context.ContextManager;
import org.apache.derby.shared.common.sanity.SanityManager;
import org.apache.derby.iapi.services.context.ContextService;
import org.apache.derby.shared.common.error.StandardException;
import org.apache.derby.iapi.services.locks.LockFactory;
import org.apache.derby.iapi.store.access.AccessFactoryGlobals;

/**
	Transaction with context, a utility class for tests to create
	multiple interleaving transactions.
*/
public class T_TWC
{
	protected Transaction tran;
	protected ContextManager cm;
	protected ContextService contextService;
	protected LockFactory lf;
	protected RawStoreFactory rawStore;

	public T_TWC(ContextService contextService,
					LockFactory lockFactory,
					RawStoreFactory rawStoreFactory)
	{
		this.contextService = contextService;
		this.lf = lockFactory;
		this.rawStore = rawStoreFactory;
		tran = null;
		cm = null;
	}

	public T_TWC startUserTransaction()
		 throws StandardException
	{
		cm = contextService.newContextManager();
		contextService.setCurrentContextManager(cm);
		try {
		tran =
            rawStore.startTransaction(cm, AccessFactoryGlobals.USER_TRANS_NAME);

		if (SanityManager.DEBUG)
			SanityManager.ASSERT(tran != null);
		checkNullLockCount();
		}
		finally {
			contextService.resetCurrentContextManager(cm);
		}
		return this;
	}

	public void checkNullLockCount()
	{
		switchTransactionContext();
		try {
		if (SanityManager.DEBUG)
			SanityManager.ASSERT(
				!lf.areLocksHeld(tran.getCompatibilitySpace()),
				"Transaction holds locks.");
		} finally {
			resetContext();
		}
	}

	public void setSavePoint(String sp, Object kindOfSavepoint)
		 throws StandardException
	{
		switchTransactionContext();
		try {
		tran.setSavePoint(sp, null);
		} finally {
			resetContext();
		}
	}

	public void rollbackToSavePoint(String sp, Object kindOfSavepoint)
		 throws StandardException
	{
		switchTransactionContext();
		try {
			tran.rollbackToSavePoint(sp, null);
		} finally {
			resetContext();
		}
	}

	public void switchTransactionContext()
	{
		contextService.setCurrentContextManager(cm);
	}
	public void resetContext() {
		contextService.resetCurrentContextManager(cm);
	}

	public void logAndDo(Loggable l)
		 throws StandardException
	{
		switchTransactionContext();
		try {
			tran.logAndDo(l);
		} finally {
			resetContext();
		}
	}

	public void commit()
		 throws StandardException
	{
		switchTransactionContext();
		try {
		tran.commit();
		} finally {
			resetContext();
		}
		checkNullLockCount();
	}

	public void abort()
		 throws StandardException
	{
		switchTransactionContext();
		try {
		tran.abort();
		} finally {
			resetContext();
		}
		checkNullLockCount();
	}

	public GlobalTransactionId getId()
		 throws StandardException
	{
		switchTransactionContext();
		try {
			return tran.getGlobalId();
		} finally {
			resetContext();
		}

	}
}

redpajama_set_name: RedPajamaGithub


text:
class Spree::OrderPageParams
  def initialize(order, page)
    @order = order
    @page = page
  end

  def attributes
    { title: title,
      body: body,
      slug: slug,
      user_id: user_id,
      layout: 'page_layout',
      render_layout_as_partial: true }
  end

  private
  attr_reader :page, :order

  def body
    'example'
  end

  def user_id
    order.user.id
  end

  def title
    page.title.present? ? page.title : order.name
  end

  def slug
    page.slug.present? ? page.slug : new_slug
  end

  def new_slug
    slug = '/' + title.parameterize
    return slug unless Spree::Page.find_by_slug(slug)
    "#{slug}-#{order.number}"
  end
end


text:
* [Ace Proxy](https://github.com/yosssi/ace-proxy) - Proxy for the Ace template engine
* [ace.yoss.si](https://github.com/yosssi/ace.yoss.si) - Website of Ace
* [Martini Acerender](https://github.com/yosssi/martini-acerender) - Martini middleware/handler for parsing Ace templates and rendering HTML
* [Hugo](https://github.com/spf13/hugo) - Static Site Generator written in Go
* [ace-util](https://github.com/catinello/ace-util) - Command line utility for the Ace HTML template engine.


text:
class OptionParserTest : public testing::Test
{};


text:
#import "SMLStandardHeader.h"

#import "NSToolbarItem+Smultron.h"
#import "SMLCommandsController.h"
#import "SMLDocumentsListCell.h"
#import "SMLApplicationDelegate.h"
#import "SMLBasicPerformer.h"
#import "SMLDragAndDropController.h"
#import "SMLToolsMenuController.h"
#import "SMLInterfacePerformer.h"
#import "SMLProjectsController.h"
#import "SMLVariousPerformer.h"
#import "SMLOpenSavePerformer.h"

@implementation SMLCommandsController

static id sharedInstance = nil;

@synthesize commandsTextView, commandsWindow, commandCollectionsArrayController, commandCollectionsTableView, commandsTableView, commandsArrayController;

+ (SMLCommandsController *)sharedInstance
{
	if (sharedInstance == nil) {
		sharedInstance = [[self alloc] init];
	}

	return sharedInstance;
}

- (id)init
{
    if (sharedInstance == nil) {
        sharedInstance = [super init];

		temporaryFilesArray = [[NSMutableArray alloc] init];
    }
    return sharedInstance;
}

- (void)openCommandsWindow
{
	if (commandsWindow == nil) {
		[NSBundle loadNibNamed:@"SMLCommands.nib" owner:self];

		[commandCollectionsTableView setDataSource:[SMLDragAndDropController sharedInstance]];
		[commandsTableView setDataSource:[SMLDragAndDropController sharedInstance]];

		[commandCollectionsTableView registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, @"SMLMovedCommandType", nil]];
		[commandCollectionsTableView setDraggingSourceOperationMask:(NSDragOperationCopy) forLocal:NO];

		[commandsTableView registerForDraggedTypes:[NSArray arrayWithObjects:NSStringPboardType, nil]];
		[commandsTableView setDraggingSourceOperationMask:(NSDragOperationCopy) forLocal:NO];

		NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
		[commandCollectionsArrayController setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
		[commandsArrayController setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];

		SMLDocumentsListCell *cell = [[SMLDocumentsListCell alloc] init];
		[cell setWraps:NO];
		[cell setLineBreakMode:NSLineBreakByTruncatingMiddle];
		[[commandCollectionsTableView tableColumnWithIdentifier:@"collection"] setDataCell:cell];

		NSToolbar *toolbar = [[NSToolbar alloc] initWithIdentifier:@"CommandsToolbarIdentifier"];
		[toolbar setShowsBaselineSeparator:YES];
		[toolbar setAllowsUserCustomization:YES];
		[toolbar setAutosavesConfiguration:YES];
		[toolbar setDisplayMode:NSToolbarDisplayModeDefault];
		[toolbar setSizeMode:NSToolbarSizeModeSmall];
		[toolbar setDelegate:self];
		[commandsWindow setToolbar:toolbar];

		//[commandCollectionsTableView setBackgroundColor:[[NSColor controlAlternatingRowBackgroundColors] objectAtIndex:1]];

	}

	[commandsWindow makeKeyAndOrderFront:self];
	[[SMLToolsMenuController sharedInstance] buildRunCommandMenu];
}

- (IBAction)newCollectionAction:(id)sender
{
	[commandCollectionsArrayController commitEditing];
	[commandsArrayController commitEditing];
	id collection = [SMLBasic createNewObjectForEntity:@"CommandCollection"];

	[SMLManagedObjectContext processPendingChanges];
	[commandCollectionsArrayController setSelectedObjects:[NSArray arrayWithObject:collection]];

	[commandsWindow makeFirstResponder:commandCollectionsTableView];
	[commandCollectionsTableView editColumn:0 row:[commandCollectionsTableView selectedRow] withEvent:nil select:NO];
}

- (IBAction)newCommandAction:(id)sender
{
	id collection;
	NSArray *commandCollections = [SMLBasic fetchAll:@"CommandCollectionSortKeyName"];
	if ([commandCollections count] == 0) {
		collection = [SMLBasic createNewObjectForEntity:@"CommandCollection"];
		[collection setValue:COLLECTION_STRING forKey:@"name"];
	}
	[commandsArrayController commitEditing];
	[commandCollectionsArrayController commitEditing];
	[self performInsertNewCommand];

	[commandsWindow makeFirstResponder:commandsTableView];
	[commandsTableView editColumn:0 row:[commandsTableView selectedRow] withEvent:nil select:NO];
}

- (id)performInsertNewCommand
{
	id collection;
	NSArray *commandCollections = [SMLBasic fetchAll:@"CommandCollectionSortKeyName"];
	if ([commandCollections count] == 0) {
		collection = [SMLBasic createNewObjectForEntity:@"CommandCollection"];
		[collection setValue:COLLECTION_STRING forKey:@"name"];
	} else {
		if (commandsWindow != nil && [[commandCollectionsArrayController selectedObjects] count] != 0) {
			collection = [[commandCollectionsArrayController selectedObjects] objectAtIndex:0];
		} else { // If no collection is selected choose the last one in the array
			collection = [commandCollections lastObject];
		}
	}

	id item = [SMLBasic createNewObjectForEntity:@"Command"];
	[[collection mutableSetValueForKey:@"commands"] addObject:item];
	[SMLManagedObjectContext processPendingChanges];
	[commandsArrayController setSelectedObjects:[NSArray arrayWithObject:item]];

	return item;
}

- (void)performDeleteCollection
{
	id collection = [[commandCollectionsArrayController selectedObjects] objectAtIndex:0];

	[SMLManagedObjectContext deleteObject:collection];

	[[SMLToolsMenuController sharedInstance] buildRunCommandMenu];
}

- (void)importCommands
{
	[self openCommandsWindow];
	NSOpenPanel *openPanel = [NSOpenPanel openPanel];
	[openPanel setResolvesAliases:YES];
	[openPanel beginSheetForDirectory:[SMLInterface whichDirectoryForOpen]
							file:nil
						   types:[NSArray arrayWithObject:@"smultronCommands"]
				  modalForWindow:commandsWindow
				   modalDelegate:self
				  didEndSelector:@selector(openPanelDidEnd:returnCode:contextInfo:)
					 contextInfo:nil];
}

- (void)openPanelDidEnd:(NSOpenPanel *)panel returnCode:(NSInteger)returnCode  contextInfo:(void  *)contextInfo
{
	if (returnCode == NSOKButton) {
		[self performCommandsImportWithPath:[panel filename]];
	}
	[commandsWindow makeKeyAndOrderFront:nil];
}

- (void)performCommandsImportWithPath:(NSString *)path
{
	NSData *data = [NSData dataWithContentsOfFile:path];
	NSArray *commands = (NSArray *)[NSKeyedUnarchiver unarchiveObjectWithData:data];
	if ([commands count] == 0) {
		return;
	}

	id collection = [SMLBasic createNewObjectForEntity:@"CommandCollection"];
	[collection setValue:[[commands objectAtIndex:0] valueForKey:@"collectionName"] forKey:@"name"];

	id item;
	for (item in commands) {
		id command = [SMLBasic createNewObjectForEntity:@"Command"];
		[command setValue:[item valueForKey:@"name"] forKey:@"name"];
		[command setValue:[item valueForKey:@"text"] forKey:@"text"];
		[command setValue:[item valueForKey:@"collectionName"] forKey:@"collectionName"];
		[command setValue:[item valueForKey:@"shortcutDisplayString"] forKey:@"shortcutDisplayString"];
		[command setValue:[item valueForKey:@"shortcutMenuItemKeyString"] forKey:@"shortcutMenuItemKeyString"];
		[command setValue:[item valueForKey:@"shortcutModifier"] forKey:@"shortcutModifier"];
		[command setValue:[item valueForKey:@"sortOrder"] forKey:@"sortOrder"];
		if ([item valueForKey:@"inline"] != nil) {
			[command setValue:[item valueForKey:@"inline"] forKey:@"inline"];
		}
		if ([item valueForKey:@"interpreter"] != nil) {
			[command setValue:[item valueForKey:@"interpreter"] forKey:@"interpreter"];
		}
		[[collection mutableSetValueForKey:@"commands"] addObject:command];
	}

	[SMLManagedObjectContext processPendingChanges];

	[commandCollectionsArrayController setSelectedObjects:[NSArray arrayWithObject:collection]];
}

- (void)exportCommands
{
	NSSavePanel *savePanel = [NSSavePanel savePanel];
	[savePanel setRequiredFileType:@"smultronCommands"];
	[savePanel beginSheetForDirectory:[SMLInterface whichDirectoryForSave]
								 file:[[[commandCollectionsArrayController selectedObjects] objectAtIndex:0] valueForKey:@"name"]
					   modalForWindow:commandsWindow
						modalDelegate:self
					   didEndSelector:@selector(exportCommandsPanelDidEnd:returnCode:contextInfo:)
						  contextInfo:nil];

}

- (void)exportCommandsPanelDidEnd:(NSSavePanel *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)context
{
	if (returnCode == NSOKButton) {
		id collection = [[commandCollectionsArrayController selectedObjects] objectAtIndex:0];

		NSMutableArray *exportArray = [NSMutableArray array];
		NSEnumerator *enumerator = [[collection mutableSetValueForKey:@"commands"] objectEnumerator];
		for (id item in enumerator) {
			NSMutableDictionary *command = [[NSMutableDictionary alloc] init];
			[command setValue:[item valueForKey:@"name"] forKey:@"name"];
			[command setValue:[item valueForKey:@"text"] forKey:@"text"];
			[command setValue:[collection valueForKey:@"name"] forKey:@"collectionName"];
			[command setValue:[item valueForKey:@"shortcutDisplayString"] forKey:@"shortcutDisplayString"];
			[command setValue:[item valueForKey:@"shortcutMenuItemKeyString"] forKey:@"shortcutMenuItemKeyString"];
			[command setValue:[item valueForKey:@"shortcutModifier"] forKey:@"shortcutModifier"];
			[command setValue:[item valueForKey:@"sortOrder"] forKey:@"sortOrder"];
			[command setValue:[NSNumber numberWithInteger:3] forKey:@"version"];
			[command setValue:[item valueForKey:@"inline"] forKey:@"inline"];
			[command setValue:[item valueForKey:@"interpreter"] forKey:@"interpreter"];
			[exportArray addObject:command];
		}

		NSData *data = [NSKeyedArchiver archivedDataWithRootObject:exportArray];
		[SMLOpenSave performDataSaveWith:data path:[sheet filename]];
	}

	[commandsWindow makeKeyAndOrderFront:nil];
}

- (void)windowWillClose:(NSNotification *)aNotification
{
	[commandCollectionsArrayController commitEditing];
	[commandsArrayController commitEditing];
}

- (NSManagedObjectContext *)managedObjectContext
{
	return SMLManagedObjectContext;
}

- (IBAction)runAction:(id)sender
{
	[self runCommand:[[commandsArrayController selectedObjects] objectAtIndex:0]];
}

- (IBAction)insertPathAction:(id)sender
{
	id document = SMLCurrentDocument;
	if (document == nil || [document valueForKey:@"path"] == nil) {
		NSBeep();
		return;
	}

	[commandsTextView insertText:[document valueForKey:@"path"]];
}

- (IBAction)insertDirectoryAction:(id)sender
{
	id document = SMLCurrentDocument;
	if (document == nil || [document valueForKey:@"path"] == nil) {
		NSBeep();
		return;
	}

	[commandsTextView insertText:[[document valueForKey:@"path"] stringByDeletingLastPathComponent]];
}

- (NSString *)commandToRunFromString:(NSString *)string
{
	NSMutableString *returnString = [NSMutableString stringWithString:string];
	id document = SMLCurrentDocument;
	if (document == nil || [[document valueForKey:@"isNewDocument"] boolValue] == YES || [document valueForKey:@"path"] == nil) {
		[returnString replaceOccurrencesOfString:@"%%p" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [returnString length])];
		[returnString replaceOccurrencesOfString:@"%%d" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [returnString length])];
	} else {
		NSString *path = [NSString stringWithFormat:@"\"%@\"", [document valueForKey:@"path"]]; // If there's a space in the path
		NSString *directory;
		if ([[SMLDefaults valueForKey:@"PutQuotesAroundDirectory"] boolValue] == YES) {
			directory = [NSString stringWithFormat:@"\"%@\"", [[document valueForKey:@"path"] stringByDeletingLastPathComponent]];
		} else {
			directory = [NSString stringWithFormat:@"%@", [[document valueForKey:@"path"] stringByDeletingLastPathComponent]];
		}
		[returnString replaceOccurrencesOfString:@"%%p" withString:path options:NSLiteralSearch range:NSMakeRange(0, [returnString length])];
		[returnString replaceOccurrencesOfString:@"%%d" withString:directory options:NSLiteralSearch range:NSMakeRange(0, [returnString length])];
	}

	if ([SMLCurrentTextView selectedRange].length > 0) {
		[returnString replaceOccurrencesOfString:@"%%s" withString:[SMLCurrentText substringWithRange:[SMLCurrentTextView selectedRange]] options:NSLiteralSearch range:NSMakeRange(0, [returnString length])];
	}

	[returnString replaceOccurrencesOfString:@" ~" withString:[NSString stringWithFormat:@" %@", NSHomeDirectory()] options:NSLiteralSearch range:NSMakeRange(0, [returnString length])];

	return returnString;
}

- (void)runCommand:(id)command
{
	[commandCollectionsArrayController commitEditing];
	[commandsArrayController commitEditing];

	isCommandRunning = YES;

	if ([command valueForKey:@"inline"] != nil && [[command valueForKey:@"inline"] boolValue] == YES) {
		currentCommandShouldBeInsertedInline = YES;
	} else {
		currentCommandShouldBeInsertedInline = NO;
	}

	NSString *commandString = [command valueForKey:@"text"];
	if (commandString == nil || [commandString length] < 1) {
		NSBeep();
		return;
	}

	if ([commandString length] > 2 && [commandString rangeOfString:@"#!" options:NSLiteralSearch range:NSMakeRange(0, 2)].location != NSNotFound) { // The command starts with a shebang so run it specially
		NSString *selectionStringPath;
		NSMutableString *commandToWrite = [NSMutableString stringWithString:commandString];

		if ([SMLCurrentTextView selectedRange].length > 0 && [commandString rangeOfString:@"%%s"].location != NSNotFound) {
			selectionStringPath = [SMLBasic genererateTemporaryPath];
			NSString *selectionString = [SMLCurrentText substringWithRange:[SMLCurrentTextView selectedRange]];
			[selectionString writeToFile:selectionStringPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
			[temporaryFilesArray addObject:selectionStringPath];
			[commandToWrite replaceOccurrencesOfString:@"%%s" withString:selectionStringPath options:NSLiteralSearch range:NSMakeRange(0, [commandToWrite length])];
		}

		id document = SMLCurrentDocument;
		NSString *path = [NSString stringWithFormat:@"\"%@\"", [document valueForKey:@"path"]]; // If there's a space in the path
		NSString *directory = [NSString stringWithFormat:@"\"%@\"", [[document valueForKey:@"path"] stringByDeletingLastPathComponent]];
		[commandToWrite replaceOccurrencesOfString:@"%%p" withString:path options:NSLiteralSearch range:NSMakeRange(0, [commandToWrite length])];
		[commandToWrite replaceOccurrencesOfString:@"%%d" withString:directory options:NSLiteralSearch range:NSMakeRange(0, [commandToWrite length])];

		NSString *commandPath = [SMLBasic genererateTemporaryPath];
		[commandToWrite writeToFile:commandPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
		[temporaryFilesArray addObject:commandPath];

		if ([command valueForKey:@"interpreter"] != nil && ![[command valueForKey:@"interpreter"] isEqualToString:@""]) {
			[SMLVarious performCommandAsynchronously:[NSString stringWithFormat:@"%@ %@", [command valueForKey:@"interpreter"], commandPath]];
		} else {
			[SMLVarious performCommandAsynchronously:[NSString stringWithFormat:@"%@ %@", [SMLDefaults valueForKey:@"RunText"], commandPath]];
		}

		if (checkIfTemporaryFilesCanBeDeletedTimer != nil) {
			[checkIfTemporaryFilesCanBeDeletedTimer invalidate];
		}
		checkIfTemporaryFilesCanBeDeletedTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(checkIfTemporaryFilesCanBeDeleted) userInfo:nil repeats:YES];

	} else {
		[SMLVarious performCommandAsynchronously:[self commandToRunFromString:commandString]];
	}
}

- (BOOL)currentCommandShouldBeInsertedInline
{
    return currentCommandShouldBeInsertedInline;
}

- (void)setCommandRunning:(BOOL)flag
{
    isCommandRunning = flag;
}

- (void)checkIfTemporaryFilesCanBeDeleted
{
	if (isCommandRunning == YES) {
		return;
	}

	if (checkIfTemporaryFilesCanBeDeletedTimer != nil) {
		[checkIfTemporaryFilesCanBeDeletedTimer invalidate];
		checkIfTemporaryFilesCanBeDeletedTimer = nil;
	}

	[self clearAnyTemporaryFiles];
}

- (void)clearAnyTemporaryFiles
{
	NSArray *enumeratorArray = [NSArray arrayWithArray:temporaryFilesArray];
	id item;
	NSFileManager *fileManager = [NSFileManager defaultManager];
	for (item in enumeratorArray) {
		if ([fileManager fileExistsAtPath:item]) {
			[fileManager removeItemAtPath:item error:nil];
		}
		[temporaryFilesArray removeObject:item];
	}
}

- (void)tableView:(NSTableView *)aTableView willDisplayCell:(id)aCell forTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
	if ([[SMLDefaults valueForKey:@"SizeOfDocumentsListTextPopUp"] integerValue] == 0) {
		[aCell setFont:[NSFont systemFontOfSize:11.0]];
	} else {
		[aCell setFont:[NSFont systemFontOfSize:13.0]];
	}
}

- (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar
{
    return [NSArray arrayWithObjects:@"NewCommandCollectionToolbarItem",
		@"NewCommandToolbarItem",
		@"FilterCommandsToolbarItem",
		@"RunCommandToolbarItem",
		NSToolbarFlexibleSpaceItemIdentifier,
		nil];
}

- (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)toolbar
{
	return [NSArray arrayWithObjects:@"NewCommandCollectionToolbarItem",
		NSToolbarFlexibleSpaceItemIdentifier,
		@"RunCommandToolbarItem",
		NSToolbarFlexibleSpaceItemIdentifier,
		@"FilterCommandsToolbarItem",
		@"NewCommandToolbarItem",
		nil];
}

- (NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)willBeInserted
{
    if ([itemIdentifier isEqualToString:@"NewCommandCollectionToolbarItem"]) {

		NSImage *newCommandCollectionImage = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"SMLNewCollectionIcon" ofType:@"pdf" inDirectory:@"Toolbar Icons"]];
		[[[newCommandCollectionImage representations] objectAtIndex:0] setAlpha:YES];

		return [NSToolbarItem createToolbarItemWithIdentifier:itemIdentifier name:NEW_COLLECTION_STRING image:newCommandCollectionImage action:@selector(newCollectionAction:) tag:0 target:self];

	} else if ([itemIdentifier isEqualToString:@"NewCommandToolbarItem"]) {

		NSImage *newCommandImage = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"SMLNewIcon" ofType:@"pdf" inDirectory:@"Toolbar Icons"]];
		[[[newCommandImage representations] objectAtIndex:0] setAlpha:YES];

		return [NSToolbarItem createToolbarItemWithIdentifier:itemIdentifier name:NSLocalizedStringFromTable(@"New Command", @"Localizable3", @"New Command") image:newCommandImage action:@selector(newCommandAction:) tag:0 target:self];

	} else if ([itemIdentifier isEqualToString:@"RunCommandToolbarItem"]) {

		NSImage *runCommandImage = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"SMLRunIcon" ofType:@"pdf" inDirectory:@"Toolbar Icons"]];
		[[[runCommandImage representations] objectAtIndex:0] setAlpha:YES];

		return [NSToolbarItem createToolbarItemWithIdentifier:itemIdentifier name:NSLocalizedStringFromTable(@"Run", @"Localizable3", @"Run") image:runCommandImage action:@selector(runAction:) tag:0 target:self];

	} else if ([itemIdentifier isEqualToString:@"FilterCommandsToolbarItem"]) {

		return [NSToolbarItem createSeachFieldToolbarItemWithIdentifier:itemIdentifier name:FILTER_STRING view:commandsFilterView];

	}

	return nil;
}

@end


text:
// Copyright 2015, Timothy Bogdala <tdb@animal-machine.com>
// See the LICENSE file for more details.

package main

import (
	"errors"
	"fmt"
	"math"
	"runtime"
	"strings"
	"time"

	"image"
	"image/draw"
	"image/png"
	"os"

	gl "github.com/go-gl/gl/v3.3-core/gl"
	glfw "github.com/go-gl/glfw/v3.1/glfw"
	mgl "github.com/go-gl/mathgl/mgl32"
	"github.com/tbogdala/cubez"
)

var (
	// UnlitColorVertShader is a basic color vertex shader
	UnlitColorVertShader = `#version 330
	uniform mat4 MVP_MATRIX;
	uniform vec4 MATERIAL_DIFFUSE;
  in vec3 VERTEX_POSITION;
	out vec4 vs_diffuse;

  void main()
  {
		vs_diffuse = MATERIAL_DIFFUSE;
		gl_Position = MVP_MATRIX * vec4(VERTEX_POSITION, 1.0);
  }`

	// UnlitColorFragShader is a basic color fragment shader
	UnlitColorFragShader = `#version 330
	in vec4 vs_diffuse;
  out vec4 colourOut;
  void main()
  {
    colourOut = vs_diffuse;
  }`

	DiffuseColorVertShader = `#version 330
	precision highp float;

	uniform mat4 MVP_MATRIX;
	uniform mat4 MV_MATRIX;
	in vec3 VERTEX_POSITION;
	in vec3 VERTEX_NORMAL;

	out vec3 vs_position;
	out vec3 vs_eye_normal;

	void main()
	{
	  vs_position = VERTEX_POSITION;
	  vs_eye_normal = normalize(mat3(MV_MATRIX) * VERTEX_NORMAL);
	  gl_Position = MVP_MATRIX * vec4(VERTEX_POSITION, 1.0);
	}`

	DiffuseColorFragShader = `#version 330
	precision highp float;

	uniform mat4 MV_MATRIX;
	uniform mat4 MVP_MATRIX;
	uniform vec4 MATERIAL_DIFFUSE;

	in vec3 vs_position;
	in vec3 vs_eye_normal;

	out vec4 frag_color;

	void main()
	{
		vec4 LIGHT_POSITION = vec4(-100.0, 100.0, 100.0, 1.0);
		vec4 LIGHT_DIFFUSE = vec4(1.0);

		vec4 eye_vertex = MV_MATRIX * vec4(vs_position, 1.0);
		vec3 s = normalize(vec3(LIGHT_POSITION-eye_vertex));
		float diffuseIntensity = max(dot(s,vs_eye_normal), 0.0);

	  frag_color = MATERIAL_DIFFUSE * diffuseIntensity;
	}`

	DiffuseTextureVertShader = `#version 330
	precision highp float;

	uniform mat4 MVP_MATRIX;
	uniform mat4 MV_MATRIX;
	in vec3 VERTEX_POSITION;
	in vec3 VERTEX_NORMAL;
	in vec2 VERTEX_UV_0;

	out vec3 vs_position;
	out vec3 vs_eye_normal;
	out vec2 vs_uv_0;

	void main()
	{
	  vs_position = VERTEX_POSITION;
		vs_uv_0 = VERTEX_UV_0;
	  vs_eye_normal = normalize(mat3(MV_MATRIX) * VERTEX_NORMAL);
	  gl_Position = MVP_MATRIX * vec4(VERTEX_POSITION, 1.0);
	}`

	DiffuseTextureFragShader = `#version 330
	precision highp float;
	uniform sampler2D MATERIAL_TEX_0;

	uniform mat4 MV_MATRIX;
	uniform mat4 MVP_MATRIX;
	uniform vec4 MATERIAL_DIFFUSE;

	in vec3 vs_position;
	in vec3 vs_eye_normal;
	in vec2 vs_uv_0;

	out vec4 frag_color;

	void main()
	{
		vec4 LIGHT_POSITION = vec4(-100.0, 100.0, 100.0, 1.0);
		vec4 LIGHT_DIFFUSE = vec4(1.0);

		vec4 eye_vertex = MV_MATRIX * vec4(vs_position, 1.0);
		vec3 s = normalize(vec3(LIGHT_POSITION-eye_vertex));
		float diffuseIntensity = max(dot(s,vs_eye_normal), 0.0);

	  frag_color = MATERIAL_DIFFUSE * texture2D(MATERIAL_TEX_0, vs_uv_0) * diffuseIntensity;
	}`

	UnlitTextureVertShader = `#version 330
  in vec3 VERTEX_POSITION;
  in vec2 VERTEX_UV_0;
  out vec3 vs_pos;
  out vec2 vs_tex_coord;
  void main()
  {
    vs_pos = VERTEX_POSITION;
    vs_tex_coord = VERTEX_UV_0;
    gl_Position = vec4(VERTEX_POSITION, 1.0);
  }`

	UnlitTextureFragShader = `#version 330
  uniform sampler2D MATERIAL_TEX_0;
  in vec3 vs_pos;
  in vec2 vs_tex_coord;
  out vec4 frag_color;
  void main()
  {
    frag_color = vec4(texture(MATERIAL_TEX_0, vs_tex_coord).rgb, 1.0);
  }`
)

// GLFW event handling must run on the main OS thread
func init() {
	runtime.LockOSThread()
}

type Entity struct {
	Node     *Renderable
	Collider cubez.Collider
}

func NewEntity(node *Renderable, collider cubez.Collider) *Entity {
	e := new(Entity)
	e.Node = node
	e.Collider = collider
	return e
}

type RenderLoopCallback func(delta float64)

// ExampleApp is a type representing the example application and holds on
// to related data like OpenGL windows.
type ExampleApp struct {
	// MainWindow is the main OpenGL window for the application
	MainWindow *glfw.Window

	// Width is how wide the app window is
	Width int

	// Height is how tall the app window is
	Height int

	// CameraPos is the position of the camera in world space
	CameraPos mgl.Vec3

	// CameraRotation is a quaternion representing the direction
	// the camera is looking.
	CameraRotation mgl.Quat

	// OnUpdate is called just prior to OnRender and can be used to update
	// the application data.
	OnUpdate RenderLoopCallback

	// OnRender is called at the end of the render loop and is meant to be
	// the spot where the application renders the objects to OpenGL.
	OnRender RenderLoopCallback
}

// NewApp returns a new ExampleApp object to control the display of the example app.
func NewApp() *ExampleApp {
	app := new(ExampleApp)
	app.CameraRotation = mgl.QuatIdent()
	return app
}

// InitGraphics creates an OpenGL window and initializes the required graphics libraries.
// It will either succeed or panic.
func (app *ExampleApp) InitGraphics(title string, w int, h int) {
	err := glfw.Init()
	if err != nil {
		panic("Can't init glfw! " + err.Error())
	}

	// request a OpenGL 3.3 core context
	glfw.WindowHint(glfw.Samples, 0)
	glfw.WindowHint(glfw.ContextVersionMajor, 3)
	glfw.WindowHint(glfw.ContextVersionMinor, 3)
	glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True)
	glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)

	// do the actual window creation
	app.MainWindow, err = glfw.CreateWindow(w, h, title, nil, nil)
	if err != nil {
		panic("Failed to create the main window! " + err.Error())
	}
	app.MainWindow.MakeContextCurrent()
	glfw.SwapInterval(0)

	// make sure that all of the GL functions are initialized
	err = gl.Init()
	if err != nil {
		panic("Failed to initialize GL! " + err.Error())
	}

	// set the app window dimensions
	app.Width = w
	app.Height = h

	gl.FrontFace(gl.CCW)
	gl.CullFace(gl.BACK)
	gl.Enable(gl.CULL_FACE)
}

// Terminate closes the OpenGL window and unloads the graphics libraries.
func (app *ExampleApp) Terminate() {
	app.MainWindow.SetShouldClose(true)
	glfw.Terminate()
}

// SetKeyCallback sets a key handler for the main window.
func (app *ExampleApp) SetKeyCallback(cb glfw.KeyCallback) {
	app.MainWindow.SetKeyCallback(cb)
}

var (
	// keeps track of the start of the last render loop
	lastRenderTime time.Time
)

// RenderLoop is the main render loop for the application
func (app *ExampleApp) RenderLoop() {
	lastRenderTime = time.Now()

	for !app.MainWindow.ShouldClose() {
		// get the time delta
		loopTime := time.Now()
		deltaNano := loopTime.Sub(lastRenderTime).Nanoseconds()
		deltaF := float64(deltaNano) * (1.0 / float64(time.Second))

		// call the Update callback
		if app.OnUpdate != nil {
			app.OnUpdate(deltaF)
		}

		// call the Render callback
		if app.OnRender != nil {
			app.OnRender(deltaF)
		}

		// draw the screen and get any input
		app.MainWindow.SwapBuffers()
		glfw.PollEvents()

		// update the last render time
		lastRenderTime = loopTime
	}
}

// Renderable is an object that can be drawn in the render loop
type Renderable struct {
	// Shader is the shader program to use to draw the renderable
	Shader uint32

	// Tex0 is the first texture to be bound to the shader
	Tex0 uint32

	// Color is a material color for the object passed to the shader when drawn.
	Color mgl.Vec4

	// Vao is the VAO object used to draw the object
	Vao uint32

	// VertVBO is the VBO that holds the vertex data
	VertVBO uint32

	// UvVBO is the VBO that holds the UV data
	UvVBO uint32

	// NormsVBO is the VBO that hold the normal data
	NormsVBO uint32

	// ElementsVBO is the VBO
	ElementsVBO uint32

	// FaceCount is the number of faces to draw for the object
	FaceCount int

	// Scale represents how to scale the object when drawing
	Scale mgl.Vec3

	// Location positions the object in world space
	Location mgl.Vec3

	// Rotation is the rotation of the object in world space
	Rotation mgl.Quat

	// LocalRotation is rotation applied to the object in local space
	LocalRotation mgl.Quat
}

// NewRenderable creates a new Renderable object.
func NewRenderable() *Renderable {
	r := new(Renderable)
	r.Scale = mgl.Vec3{1.0, 1.0, 1.0}
	return r
}

// GetTransformMat4 creates a transform matrix: scale * transform
func (r *Renderable) GetTransformMat4() mgl.Mat4 {
	scaleMat := mgl.Scale3D(r.Scale[0], r.Scale[1], r.Scale[2])
	transMat := mgl.Translate3D(r.Location[0], r.Location[1], r.Location[2])
	localRotMat := r.LocalRotation.Mat4()
	rotMat := r.Rotation.Mat4()
	modelTransform := rotMat.Mul4(transMat).Mul4(localRotMat).Mul4(scaleMat)
	return modelTransform
}

func (r *Renderable) Draw(perspective mgl.Mat4, view mgl.Mat4) {
	gl.UseProgram(r.Shader)
	gl.BindVertexArray(r.Vao)

	model := r.GetTransformMat4()

	var mvp mgl.Mat4
	shaderMvp := getUniformLocation(r.Shader, "MVP_MATRIX")
	if shaderMvp >= 0 {
		mvp = perspective.Mul4(view).Mul4(model)
		gl.UniformMatrix4fv(shaderMvp, 1, false, &mvp[0])
	}

	shaderMv := getUniformLocation(r.Shader, "MV_MATRIX")
	if shaderMv >= 0 {
		mv := view.Mul4(model)
		gl.UniformMatrix4fv(shaderMv, 1, false, &mv[0])
	}

	shaderTex0 := getUniformLocation(r.Shader, "DIFFUSE_TEX")
	if shaderTex0 >= 0 {
		gl.ActiveTexture(gl.TEXTURE0)
		gl.BindTexture(gl.TEXTURE_2D, r.Tex0)
		gl.Uniform1i(shaderTex0, 0)
	}

	shaderColor := getUniformLocation(r.Shader, "MATERIAL_DIFFUSE")
	if shaderColor >= 0 {
		gl.Uniform4f(shaderColor, r.Color[0], r.Color[1], r.Color[2], r.Color[3])
	}

	shaderTex1 := getUniformLocation(r.Shader, "MATERIAL_TEX_0")
	if shaderTex1 >= 0 {
		gl.ActiveTexture(gl.TEXTURE0)
		gl.BindTexture(gl.TEXTURE_2D, r.Tex0)
		gl.Uniform1i(shaderTex1, 0)
	}

	shaderCameraWorldPos := getUniformLocation(r.Shader, "CAMERA_WORLD_POSITION")
	if shaderCameraWorldPos >= 0 {
		gl.Uniform3f(shaderCameraWorldPos, -view[12], -view[13], -view[14])
	}

	shaderPosition := getAttribLocation(r.Shader, "VERTEX_POSITION")
	if shaderPosition >= 0 {
		gl.BindBuffer(gl.ARRAY_BUFFER, r.VertVBO)
		gl.EnableVertexAttribArray(uint32(shaderPosition))
		gl.VertexAttribPointer(uint32(shaderPosition), 3, gl.FLOAT, false, 0, gl.PtrOffset(0))
	}

	shaderNormal := getAttribLocation(r.Shader, "VERTEX_NORMAL")
	if shaderNormal >= 0 {
		gl.BindBuffer(gl.ARRAY_BUFFER, r.NormsVBO)
		gl.EnableVertexAttribArray(uint32(shaderNormal))
		gl.VertexAttribPointer(uint32(shaderNormal), 3, gl.FLOAT, false, 0, gl.PtrOffset(0))
	}

	shaderVertUv := getAttribLocation(r.Shader, "VERTEX_UV_0")
	if shaderVertUv >= 0 {
		gl.BindBuffer(gl.ARRAY_BUFFER, r.UvVBO)
		gl.EnableVertexAttribArray(uint32(shaderVertUv))
		gl.VertexAttribPointer(uint32(shaderVertUv), 2, gl.FLOAT, false, 0, gl.PtrOffset(0))
	}

	gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, r.ElementsVBO)
	gl.DrawElements(gl.TRIANGLES, int32(r.FaceCount*3), gl.UNSIGNED_INT, gl.PtrOffset(0))
	gl.BindVertexArray(0)
}

// setup a cache for the uniform and attribute getter functions
var (
	uniCache  = make(map[string]int32)
	attrCache = make(map[string]int32)
)

func getUniformLocation(prog uint32, name string) int32 {
	// attempt to get it from the cache first
	ul, found := uniCache[name]
	if found {
		return ul
	}

	// pull the location from the shader and cache it
	uniGLName := name + "\x00"
	ul = gl.GetUniformLocation(prog, gl.Str(uniGLName))

	// cache even if it returns -1 so that it doesn't repeatedly check
	uniCache[name] = ul
	return ul
}

func getAttribLocation(prog uint32, name string) int32 {
	// attempt to get it from the cache first
	al, found := attrCache[name]
	if found {
		return al
	}

	// pull the location from the shader and cache it
	attrGLName := name + "\x00"
	al = gl.GetAttribLocation(prog, gl.Str(attrGLName))

	// cache even if it returns -1 so that it doesn't repeatedly check
	attrCache[name] = al
	return al
}

// LoadShaderProgram loads shader objects and then attaches them to a program
func LoadShaderProgram(vertShader, fragShader string) (uint32, error) {
	// create the program
	prog := gl.CreateProgram()

	// create the vertex shader
	vs := gl.CreateShader(gl.VERTEX_SHADER)
	cVertShader, free := gl.Strs(vertShader + "\x00")
	gl.ShaderSource(vs, 1, cVertShader, nil)
	gl.CompileShader(vs)
	free()

	var status int32
	gl.GetShaderiv(vs, gl.COMPILE_STATUS, &status)
	if status == gl.FALSE {
		var logLength int32
		gl.GetShaderiv(vs, gl.INFO_LOG_LENGTH, &logLength)
		log := strings.Repeat("\x00", int(logLength+1))
		gl.GetShaderInfoLog(vs, logLength, nil, gl.Str(log))

		err := fmt.Sprintf("Failed to compile the vertex shader!\n%s", log)
		fmt.Println(err)
		return 0, errors.New(err)
	}
	defer gl.DeleteShader(vs)

	// create the fragment shader
	fs := gl.CreateShader(gl.FRAGMENT_SHADER)
	cFragShader, free := gl.Strs(fragShader + "\x00")
	gl.ShaderSource(fs, 1, cFragShader, nil)
	gl.CompileShader(fs)
	free()

	gl.GetShaderiv(fs, gl.COMPILE_STATUS, &status)
	if status == gl.FALSE {
		var logLength int32
		gl.GetShaderiv(fs, gl.INFO_LOG_LENGTH, &logLength)
		log := strings.Repeat("\x00", int(logLength+1))
		gl.GetShaderInfoLog(fs, logLength, nil, gl.Str(log))

		err := fmt.Sprintf("Failed to compile the fragment shader!\n%s", log)
		fmt.Println(err)
		return 0, errors.New(err)
	}
	defer gl.DeleteShader(fs)

	// attach the shaders to the program and link
	// attach the shaders to the program and link
	gl.AttachShader(prog, vs)
	gl.AttachShader(prog, fs)
	gl.LinkProgram(prog)

	gl.GetProgramiv(prog, gl.LINK_STATUS, &status)
	if status == gl.FALSE {
		var logLength int32
		gl.GetProgramiv(prog, gl.INFO_LOG_LENGTH, &logLength)
		log := strings.Repeat("\x00", int(logLength+1))
		gl.GetProgramInfoLog(prog, logLength, nil, gl.Str(log))

		error := fmt.Sprintf("Failed to link the program!\n%s", log)
		fmt.Println(error)
		return 0, errors.New(error)
	}

	return prog, nil
}

func loadFile(filePath string) (rgba_flipped *image.NRGBA, e error) {
	imgFile, err := os.Open(filePath)
	if err != nil {
		return nil, fmt.Errorf("Failed to open the texture file: %v\n", err)
	}

	img, err := png.Decode(imgFile)
	imgFile.Close()
	if err != nil {
		return nil, fmt.Errorf("Failed to decode the texture: %v\n", err)
	}

	// if the source image doesn't have alpha, set it manually
	b := img.Bounds()
	rgba := image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
	draw.Draw(rgba, rgba.Bounds(), img, b.Min, draw.Src)

	// flip the image vertically
	rows := b.Max.Y
	rgba_flipped = image.NewNRGBA(image.Rect(0, 0, b.Max.X, b.Max.Y))
	for dy := 0; dy < rows; dy++ {
		sy := b.Max.Y - dy - 1
		for dx := 0; dx < b.Max.X; dx++ {
			soffset := sy*rgba.Stride + dx*4
			doffset := dy*rgba_flipped.Stride + dx*4
			copy(rgba_flipped.Pix[doffset:doffset+4], rgba.Pix[soffset:soffset+4])
		}
	}

	return rgba_flipped, nil
}

func LoadImageToTexture(filePath string) (glTex uint32, e error) {
	gl.GenTextures(1, &glTex)
	gl.ActiveTexture(gl.TEXTURE0)
	gl.BindTexture(gl.TEXTURE_2D, glTex)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR_MIPMAP_LINEAR)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT)

	rgba_flipped, err := loadFile(filePath)
	if err != nil {
		return glTex, err
	}

	imageSize := int32(rgba_flipped.Bounds().Max.X)

	gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RGBA, imageSize, imageSize, 0, gl.RGBA, gl.UNSIGNED_BYTE, gl.Ptr(rgba_flipped.Pix))
	gl.GenerateMipmap(gl.TEXTURE_2D)
	return glTex, nil
}

// CreateCube makes a new Renderable object with the specified dimensions for the cube.
func CreateCube(xmin, ymin, zmin, xmax, ymax, zmax float32) *Renderable {
	/* Cube vertices are layed out like this:

	  +--------+           6          5
	/ |       /|
	+--------+ |        1          0        +Y
	| |      | |                            |___ +X
	| +------|-+           7          4    /
	|/       |/                           +Z
	+--------+          2          3

	*/

	verts := [...]float32{
		xmax, ymax, zmax, xmin, ymax, zmax, xmin, ymin, zmax, xmax, ymin, zmax, // v0,v1,v2,v3 (front)
		xmax, ymax, zmin, xmax, ymax, zmax, xmax, ymin, zmax, xmax, ymin, zmin, // v5,v0,v3,v4 (right)
		xmax, ymax, zmin, xmin, ymax, zmin, xmin, ymax, zmax, xmax, ymax, zmax, // v5,v6,v1,v0 (top)
		xmin, ymax, zmax, xmin, ymax, zmin, xmin, ymin, zmin, xmin, ymin, zmax, // v1,v6,v7,v2 (left)
		xmax, ymin, zmax, xmin, ymin, zmax, xmin, ymin, zmin, xmax, ymin, zmin, // v3,v2,v7,v4 (bottom)
		xmin, ymax, zmin, xmax, ymax, zmin, xmax, ymin, zmin, xmin, ymin, zmin, // v6,v5,v4,v7 (back)
	}
	indexes := [...]uint32{
		0, 1, 2, 2, 3, 0,
		4, 5, 6, 6, 7, 4,
		8, 9, 10, 10, 11, 8,
		12, 13, 14, 14, 15, 12,
		16, 17, 18, 18, 19, 16,
		20, 21, 22, 22, 23, 20,
	}
	uvs := [...]float32{
		1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0,
		1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0,
		1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0,
		1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0,
		1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0,
		1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0,
	}
	normals := [...]float32{
		0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, // v0,v1,v2,v3 (front)
		1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, // v5,v0,v3,v4 (right)
		0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, // v5,v6,v1,v0 (top)
		-1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, // v1,v6,v7,v2 (left)
		0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, // v3,v2,v7,v4 (bottom)
		0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, // v6,v5,v4,v7 (back)
	}

	r := NewRenderable()
	gl.GenVertexArrays(1, &r.Vao)
	r.FaceCount = 12

	const floatSize = 4
	const uintSize = 4

	// create a VBO to hold the vertex data
	gl.GenBuffers(1, &r.VertVBO)
	gl.BindBuffer(gl.ARRAY_BUFFER, r.VertVBO)
	gl.BufferData(gl.ARRAY_BUFFER, floatSize*len(verts), gl.Ptr(&verts[0]), gl.STATIC_DRAW)

	// create a VBO to hold the uv data
	gl.GenBuffers(1, &r.UvVBO)
	gl.BindBuffer(gl.ARRAY_BUFFER, r.UvVBO)
	gl.BufferData(gl.ARRAY_BUFFER, floatSize*len(uvs), gl.Ptr(&uvs[0]), gl.STATIC_DRAW)

	// create a VBO to hold the normals data
	gl.GenBuffers(1, &r.NormsVBO)
	gl.BindBuffer(gl.ARRAY_BUFFER, r.NormsVBO)
	gl.BufferData(gl.ARRAY_BUFFER, floatSize*len(normals), gl.Ptr(&normals[0]), gl.STATIC_DRAW)

	// create a VBO to hold the face indexes
	gl.GenBuffers(1, &r.ElementsVBO)
	gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, r.ElementsVBO)
	gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, uintSize*len(indexes), gl.Ptr(&indexes[0]), gl.STATIC_DRAW)

	return r
}

// CreateSphere generates a 3d uv-sphere with the given radius and returns a Renderable.
func CreateSphere(radius float32, rings int, sectors int) *Renderable {
	// nothing to create
	if rings < 2 || sectors < 2 {
		return nil
	}

	const piDiv2 = math.Pi / 2.0

	verts := make([]float32, 0, rings*sectors)
	indexes := make([]uint32, 0, rings*sectors)
	uvs := make([]float32, 0, rings*sectors)
	normals := make([]float32, 0, rings*sectors)

	R := float64(1.0 / float32(rings-1))
	S := float64(1.0 / float32(sectors-1))

	for ri := 0; ri < int(rings); ri++ {
		for si := 0; si < int(sectors); si++ {
			y := float32(math.Sin(-piDiv2 + math.Pi*float64(ri)*R))
			x := float32(math.Cos(2.0*math.Pi*float64(si)*S) * math.Sin(math.Pi*float64(ri)*R))
			z := float32(math.Sin(2.0*math.Pi*float64(si)*S) * math.Sin(math.Pi*float64(ri)*R))

			uvs = append(uvs, float32(si)*float32(S))
			uvs = append(uvs, float32(ri)*float32(R))

			verts = append(verts, x*radius)
			verts = append(verts, y*radius)
			verts = append(verts, z*radius)

			normals = append(normals, x)
			normals = append(normals, y)
			normals = append(normals, z)

			currentRow := ri * sectors
			nextRow := (ri + 1) * sectors

			indexes = append(indexes, uint32(currentRow+si))
			indexes = append(indexes, uint32(nextRow+si))
			indexes = append(indexes, uint32(nextRow+si+1))

			indexes = append(indexes, uint32(currentRow+si))
			indexes = append(indexes, uint32(nextRow+si+1))
			indexes = append(indexes, uint32(currentRow+si+1))
		}
	}

	r := NewRenderable()
	gl.GenVertexArrays(1, &r.Vao)
	r.FaceCount = rings * sectors * 2

	const floatSize = 4
	const uintSize = 4

	// create a VBO to hold the vertex data
	gl.GenBuffers(1, &r.VertVBO)
	gl.BindBuffer(gl.ARRAY_BUFFER, r.VertVBO)
	gl.BufferData(gl.ARRAY_BUFFER, floatSize*len(verts), gl.Ptr(&verts[0]), gl.STATIC_DRAW)

	// create a VBO to hold the uv data
	gl.GenBuffers(1, &r.UvVBO)
	gl.BindBuffer(gl.ARRAY_BUFFER, r.UvVBO)
	gl.BufferData(gl.ARRAY_BUFFER, floatSize*len(uvs), gl.Ptr(&uvs[0]), gl.STATIC_DRAW)

	// create a VBO to hold the normals data
	gl.GenBuffers(1, &r.NormsVBO)
	gl.BindBuffer(gl.ARRAY_BUFFER, r.NormsVBO)
	gl.BufferData(gl.ARRAY_BUFFER, floatSize*len(normals), gl.Ptr(&normals[0]), gl.STATIC_DRAW)

	// create a VBO to hold the face indexes
	gl.GenBuffers(1, &r.ElementsVBO)
	gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, r.ElementsVBO)
	gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, uintSize*len(indexes), gl.Ptr(&indexes[0]), gl.STATIC_DRAW)

	return r
}

// CreatePlaneXZ makes a 2d Renderable object on the XZ plane for the given size,
// where (x0,z0) is the lower left and (x1, z1) is the upper right coordinate.
func CreatePlaneXZ(x0, z0, x1, z1 float32, scaleUVs float32) *Renderable {
	verts := [12]float32{
		x0, 0.0, z0,
		x1, 0.0, z0,
		x0, 0.0, z1,
		x1, 0.0, z1,
	}
	indexes := [6]uint32{
		0, 1, 2,
		1, 3, 2,
	}
	uvs := [8]float32{
		0.0, 0.0,
		scaleUVs, 0.0,
		0.0, scaleUVs,
		scaleUVs, scaleUVs,
	}

	normals := [12]float32{
		0.0, 1.0, 0.0,
		0.0, 1.0, 0.0,
		0.0, 1.0, 0.0,
		0.0, 1.0, 0.0,
	}

	return createPlane(x0, z0, x1, z1, verts, indexes, uvs, normals)
}

// CreatePlaneXY makes a 2d Renderable object on the XY plane for the given size,
// where (x0,y0) is the lower left and (x1, y1) is the upper right coordinate.
func CreatePlaneXY(x0, y0, x1, y1 float32, scaleUVs float32) *Renderable {
	verts := [12]float32{
		x0, y0, 0.0,
		x1, y0, 0.0,
		x0, y1, 0.0,
		x1, y1, 0.0,
	}
	indexes := [6]uint32{
		0, 1, 2,
		1, 3, 2,
	}
	uvs := [8]float32{
		0.0, 0.0,
		scaleUVs, 0.0,
		0.0, scaleUVs,
		scaleUVs, scaleUVs,
	}
	normals := [12]float32{
		0.0, 0.0, 1.0,
		0.0, 0.0, 1.0,
		0.0, 0.0, 1.0,
		0.0, 0.0, 1.0,
	}

	return createPlane(x0, y0, x1, y1, verts, indexes, uvs, normals)
}

func createPlane(x0, y0, x1, y1 float32, verts [12]float32, indexes [6]uint32, uvs [8]float32, normals [12]float32) *Renderable {
	const floatSize = 4
	const uintSize = 4

	r := NewRenderable()
	gl.GenVertexArrays(1, &r.Vao)
	r.FaceCount = 2

	// create a VBO to hold the vertex data
	gl.GenBuffers(1, &r.VertVBO)
	gl.BindBuffer(gl.ARRAY_BUFFER, r.VertVBO)
	gl.BufferData(gl.ARRAY_BUFFER, floatSize*len(verts), gl.Ptr(&verts[0]), gl.STATIC_DRAW)

	// create a VBO to hold the uv data
	gl.GenBuffers(1, &r.UvVBO)
	gl.BindBuffer(gl.ARRAY_BUFFER, r.UvVBO)
	gl.BufferData(gl.ARRAY_BUFFER, floatSize*len(uvs), gl.Ptr(&uvs[0]), gl.STATIC_DRAW)

	// create a VBO to hold the normals data
	gl.GenBuffers(1, &r.NormsVBO)
	gl.BindBuffer(gl.ARRAY_BUFFER, r.NormsVBO)
	gl.BufferData(gl.ARRAY_BUFFER, floatSize*len(normals), gl.Ptr(&normals[0]), gl.STATIC_DRAW)

	// create a VBO to hold the face indexes
	gl.GenBuffers(1, &r.ElementsVBO)
	gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, r.ElementsVBO)
	gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, uintSize*len(indexes), gl.Ptr(&indexes[0]), gl.STATIC_DRAW)

	return r
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rv_wait_movie_trailer_recommend"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="@dimen/dp_10"/>


text:
<?php

namespace backend\modules\ourclients;

class Ourclients extends \yii\base\Module
{
    public $controllerNamespace = 'backend\modules\ourclients\controllers';

    public function init()
    {
        parent::init();

        // custom initialization code goes here
    }
}


text:
@import CoreGraphics;

extern const float kDefaultBounceSpeed;
extern const float kDefaultBaseAnchorHeight;

@interface BouncyComponent : JLFGKComponent

@property (assign, nonatomic) float bounceSpeed;
@property (assign, nonatomic) CGPoint baseAnchorPoint;

- (void)startBouncing;
- (void)stopBouncing;

@end


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>wtf.util.BasePool</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

Visit WTF Online

        Package wtf ::
        Module util ::
        Class BasePool

[hide private]

[frames] | no frames]

Class BasePool

source code

object --+
         |
        BasePool

Known Subclasses:

ext.memcache.MemcacheConnectionPool

Abstract pool of arbitrary objects

        Instance Methods
        [hide private]

          __init__(self,
        maxout,
        maxcached)

      Initialization

            source code

          __del__(self)

      Destruction

            source code

      <tt class="rst-rst-rst-docutils literal rst-rst-docutils literal rst-docutils literal">PooledInterface</tt>

          _create(self)

      Create a pooled object

            source code

      PooledInterface

          get_obj(self)

      Get a object from the pool

            source code

          put_obj(self,
        obj)

      Put an object back into the pool

            source code

          del_obj(self,
        obj)

      Remove object from pool

            source code

          clear(self)

      Clear the currently cached connections

            source code

          shutdown(self)

      Shutdown this pool

            source code

          _fork_protect(self)

      Check if the current PID differs from the stored one

            source code

Inherited from object:
      __delattr__,
      __format__,
      __getattribute__,
      __hash__,
      __new__,
      __reduce__,
      __reduce_ex__,
      __repr__,
      __setattr__,
      __sizeof__,
      __str__,
      __subclasshook__

        Class Variables
        [hide private]

      <tt class="rst-docutils literal">NoneType</tt>

        _LOCK = None

      Locking class.

      <tt class="rst-rst-docutils literal rst-docutils literal">bool</tt>

        _FORK_PROTECT = False

      Clear the pool, when the PID changes?

        Instance Variables
        [hide private]

      <tt class="rst-docutils literal">int</tt>

        _maxcached

      Maximum number of pooled objects to be cached

      <tt class="rst-docutils literal">int</tt>

        _maxout

      Hard maximum number of pooled objects to be handed out

      <tt class="rst-docutils literal">threading.Condition</tt>

        _not_empty

      "not empty" condition

      <tt class="rst-docutils literal">threading.Condition</tt>

        _not_full

      "not full" condition

      <tt class="rst-docutils literal">dict</tt>

        _obj

      References to handed out objects, Note that the objects need to
be hashable

      <tt class="rst-docutils literal">int</tt>

        _pid = None

      PID of currently handed out and cached objects

      <tt class="rst-docutils literal">collections.deque</tt>

        _pool

      actual object pool

        Properties
        [hide private]

Inherited from object:
      __class__

        Method Details
        [hide private]

__init__(self,
        maxout,
        maxcached)

(Constructor)

  	source code

  Initialization

Overrides:
        object.__init__

_create(self)

  	source code

Create a pooled object

This method must be implemented by subclasses.

Returns: <tt class="rst-rst-rst-rst-docutils literal rst-rst-rst-docutils literal rst-rst-docutils literal rst-docutils literal">PooledInterface</tt>

A new object

get_obj(self)

  	source code

  Get a object from the pool

Returns: PooledInterface

The new object. If no objects are available in the pool, a
new one is created (by calling _create). If no object
can be created (because of limits), the method blocks.

put_obj(self,
        obj)

  	source code

Put an object back into the pool

If the pool is full, the object is destroyed instead. If the object
does not come from this pool, it is an error (<tt class="rst-docutils literal">assert</tt>).

Parameters:

obj (PooledInterface) - The object to put back

del_obj(self,
        obj)

  	source code

Remove object from pool

If the object original came not from this pool, this is not an error.

Parameters:

obj (PooledInterface) - The object to remove

clear(self)

  	source code

Clear the currently cached connections

Connections handed out are not affected. This just empties the cached
ones.

shutdown(self)

  	source code

Shutdown this pool

The queue will be emptied and all objects destroyed. No more
objects will be created in this pool. Waiting consumers of the pool
will get an <tt class="rst-docutils literal">AssertionError</tt>, because they shouldn't consume anymore
anyway.

_fork_protect(self)

  	source code

Check if the current PID differs from the stored one

If they actually differed, we forked and clear the pool. This
function should only be called within a locked environment.

        Class Variable Details
        [hide private]

_LOCK

  Locking class. By default this is <tt class="rst-docutils literal">threading.Lock</tt>. However,
if the pooled object's initializer or destructor (<tt class="rst-docutils literal">.destroy</tt>) are
calling back into get_conn or put_conn, it should be <tt class="rst-docutils literal">RLock</tt>.

Type:

<tt class="rst-rst-docutils literal rst-docutils literal">NoneType</tt>

Value:

None

         Home

         Trees

         Indices

         Help

Visit WTF Online


text:
'use strict';

var path = require('path');
var fs = require('fs');

/**
 * Expose `relative`
 */

module.exports = relative;

/**
 * Get the relative path from `a` to `b`.
 */

function relative(a, b, stat) {
  if (typeof a !== 'string') {
    throw new TypeError('relative expects a string.');
  }

  if (a == '' && !b) return a;

  var len = arguments.length;
  if (len === 1) {
    b = a; a = process.cwd(); stat = null;
  }

  if (len === 2 && typeof b === 'boolean') {
    b = a; a = process.cwd(); stat = true;
  }

  if (len === 2 && typeof b === 'object') {
    stat = b; b = a; a = process.cwd();
  }

  var origB = b;

  // see if a slash exists before normalizing
  var slashA = endsWith(a, '/');
  var slashB = endsWith(b, '/');

  a = normalize(a);
  b = normalize(b);

  // if `a` had a slash, add it back
  if (slashA) { a = a + '/'; }

  if (isFile(a, stat)) {
    a = path.dirname(a);
  }

  var res = path.relative(a, b);
  if (res === '') {
    return '.';
  }

  // if `b` originally had a slash, and the path ends
  // with `b` missing a slash, then re-add the slash.
  var noslash = trimEnd(origB, '/');
  if (slashB && (res === noslash || endsWith(res, noslash))) {
    res = res + '/';
  }
  return res;
}

/**
 * Get the path relative to the given base path.
 */

relative.toBase = function toBase(base, fp) {
  base = normalize(base);
  fp = normalize(fp);

  var res = fp.slice(base.length);
  if (res.charAt(0) === '/') {
    res = res.slice(1);
  }
  return res;
};

/**
 * Normalize slashes in paths. This is necessary b/c
 * paths are not calculated the same by node.js when
 * windows paths are used.
 */

function normalize(str) {
  return str.replace(/[\\\/]+/g, '/');
}

/**
 * Remove the given character from the path.
 */

function trimEnd(fp, ch) {
  return fp.slice(0, fp.length - ch.length);
}

/**
 * Does the path end with the given `ch`aracter?
 */

function endsWith(fp, ch) {
  return fp.slice(-ch.length)[0] === ch;
}

/**
 * If `fp` exists, return a `stat` object,
 * otherwise return `null`.
 */

function tryStats(fp) {
  try {
    return fs.statSync(fp);
  } catch(err) {}
  return null;
}

/**
 * Returns true if `fp` is a directory. To use a `fs`
 * stat object to actually check the file system,
 * either pass `true` as the second arg, or pass your
 * own stat object as the second arg.
 *
 * @param  {String} `fp`
 * @param  {Boolean|Object} `stat`
 * @return {Boolean}
 */

function isDir(fp, stat) {
  if (endsWith(fp, '/')) {
    return true;
  }

  if (stat === null) {
    // try to get the directory info if it hasn't been done yet
    // to ensure directories containing dots are well handle
    stat = tryStats(fp);
  }

  if (stat != null && typeof stat === 'object') {
    return stat.isDirectory();
  }

  var segs = fp.split('/');
  var last = segs[segs.length - 1];
  if (last && last.indexOf('.') !== -1) {
    return false;
  }
  return true;
}

/**
 * Return true if `fp` looks like a file, or
 * actually is a file if fs.stat is used.
 */

function isFile(fp, stat) {
  if (stat === true) {
    stat = tryStats(fp);
  }
  return !isDir(fp, stat);
}


text:
package com.whitestein.vaadin.widgets.uiserver;

import org.vaadin.addonhelpers.TServer;

/**
 * The main method in this helper class opens a web server to
 * http://localhost:9998/ to serve all your test UIs for development and
 * integration testing.
 */
public class Server extends TServer {

    public static void main(String... args) throws Exception {
        new Server().startServer();

        System.out.println("Running on: http://localhost:9998/");
    }

}


text:
package org.apache.geode.logging.log4j.internal.impl;

import static org.apache.geode.logging.internal.spi.LogWriterLevel.INFO;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.apache.logging.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import org.apache.geode.logging.internal.Configuration;
import org.apache.geode.logging.internal.log4j.api.FastLogger;
import org.apache.geode.logging.internal.log4j.api.LogService;
import org.apache.geode.logging.internal.spi.LogConfig;
import org.apache.geode.logging.internal.spi.LogConfigSupplier;
import org.apache.geode.logging.internal.spi.LogLevelUpdateOccurs;
import org.apache.geode.logging.internal.spi.LogLevelUpdateScope;
import org.apache.geode.test.junit.categories.LoggingTest;

/**
 * Integration tests for {@link FastLogger} when using the default {@code log4j2.xml} for Geode.
 */
@Category(LoggingTest.class)
public class FastLoggerWithDefaultConfigIntegrationTest {

  private Logger logger;

  @Before
  public void setUp() {
    LogConfig logConfig = mock(LogConfig.class);
    LogConfigSupplier logConfigSupplier = mock(LogConfigSupplier.class);

    when(logConfig.getLogLevel()).thenReturn(INFO.intLevel());
    when(logConfig.getSecurityLogLevel()).thenReturn(INFO.intLevel());
    when(logConfigSupplier.getLogConfig()).thenReturn(logConfig);

    Configuration configuration =
        Configuration.create(LogLevelUpdateOccurs.ALWAYS, LogLevelUpdateScope.GEODE_LOGGERS);
    configuration.initialize(logConfigSupplier);
  }

  /**
   * LogService isUsingGemFireDefaultConfig should be true
   */
  @Test
  public void isUsingGemFireDefaultConfig() {
    assertThat(Log4jLoggingProvider.isUsingGemFireDefaultConfig()).isTrue();
  }

  /**
   * LogService getLogger should return loggers wrapped in FastLogger
   */
  @Test
  public void logServiceReturnsFastLoggers() {
    logger = LogService.getLogger();

    assertThat(logger).isInstanceOf(FastLogger.class);
  }

  /**
   * FastLogger isDelegating should be false
   */
  @Test
  public void isDelegatingShouldBeFalse() {
    logger = LogService.getLogger();

    assertThat(((FastLogger) logger).isDelegating()).isFalse();
  }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>

	<video va id="video" controls="" preload="none" mediagroup="myVideoGroup" poster="http://media.w3.org/2010/05/bunny/poster.png">
      <source id="mp4" src="http://media.w3.org/2010/05/bunny/trailer.mp4" type="video/mp4">

      <source id="ogv" src="http://media.w3.org/2010/05/sintel/trailer.ogv" type="video/ogg">

Your user agent does not support the HTML5 Video element.

    </video>


text:
struct Foo {
    x: int
}

impl Fo { //~ERROR inherent implementations are not allowed for types not defined in the current module
    fn foo() {}
}

fn main() {}


text:
<h3 md-dialog-title>Agregar cliente</h3>
<md-dialog-content class="imput-edit">

</md-dialog-content>
<md-dialog-actions>
    <button md-button md-dialog-close>Cancelar</button>
    <!-- Can optionally provide a result for the closing dialog. -->
    <button md-raised-button color="primary" [md-dialog-close]="true">Guardar</button>
</md-dialog-actions>


text:
package com.kakai.android.autoviewmodelfactory.presentation;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.widget.TextView;

import com.kakai.android.autoviewmodelfactory.R;

import javax.inject.Inject;

import dagger.android.AndroidInjection;
import dagger.android.support.DaggerAppCompatActivity;

public class MainActivity extends DaggerAppCompatActivity {

    @Inject
    MainViewModelFactory viewModelFactory;

    private MainViewModel viewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        AndroidInjection.inject(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewModel = ViewModelProviders.of(this, viewModelFactory).get(MainViewModel.class);

        viewModel.getMessage().observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String message) {
                ((TextView) findViewById(R.id.message)).setText(message);
            }
        });
    }

    public String getTestString() {
        return "test";
    }

    public String getAnotherTestString() {
        return "another test";
    }
}


text:
module Network.Transport.TCP.Internal
  ( forkServer
  , recvWithLength
  , recvExact
  , recvInt32
  , tryCloseSocket
  ) where

#if ! MIN_VERSION_base(4,6,0)
import Prelude hiding (catch)
#endif

import Network.Transport.Internal (decodeInt32, void, tryIO, forkIOWithUnmask)

#ifdef USE_MOCK_NETWORK
import qualified Network.Transport.TCP.Mock.Socket as N
#else
import qualified Network.Socket as N
#endif
  ( HostName
  , ServiceName
  , Socket
  , SocketType(Stream)
  , SocketOption(ReuseAddr)
  , getAddrInfo
  , defaultHints
  , socket
  , bind -- bindSocket
  , listen
  , addrFamily
  , addrAddress
  , defaultProtocol
  , setSocketOption
  , accept
  , sClose
  , socketPort
  )

#ifdef USE_MOCK_NETWORK
import qualified Network.Transport.TCP.Mock.Socket.ByteString as NBS (recv)
#else
import qualified Network.Socket.ByteString as NBS (recv)
#endif

import Control.Concurrent (ThreadId)
import Control.Monad (forever, when)
import Control.Exception (SomeException, catch, bracketOnError, throwIO, mask_)
import Control.Applicative ((<$>), (<*>))
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS (length, concat, null)
import Data.Int (Int32)
import Data.ByteString.Lazy.Internal (smallChunkSize)

-- | Start a server at the specified address.
--
-- This sets up a server socket for the specified host and port. Exceptions
-- thrown during setup are not caught.
--
-- Once the socket is created we spawn a new thread which repeatedly accepts
-- incoming connections and executes the given request handler. If any
-- exception occurs the thread terminates and calls the terminationHandler.
-- This exception may occur because of a call to 'N.accept', because the thread
-- was explicitly killed, or because of a synchronous exception thrown by the
-- request handler. Typically, you should avoid the last case by catching any
-- relevant exceptions in the request handler.
--
-- The request handler should spawn threads to handle each individual request
-- or the server will block. Once a thread has been spawned it will be the
-- responsibility of the new thread to close the socket when an exception
-- occurs.
--
-- The return value includes the port was bound to. This is not always the same
-- port as that given in the argument. For example, binding to port 0 actually
-- binds to a random port, selected by the OS.
forkServer :: N.HostName               -- ^ Host
           -> N.ServiceName            -- ^ Port
           -> Int                      -- ^ Backlog (maximum number of queued connections)
           -> Bool                     -- ^ Set ReuseAddr option?
           -> (SomeException -> IO ()) -- ^ Termination handler
           -> (N.Socket -> IO ())      -- ^ Request handler
           -> IO (N.ServiceName, ThreadId)
forkServer host port backlog reuseAddr terminationHandler requestHandler = do
    -- Resolve the specified address. By specification, getAddrInfo will never
    -- return an empty list (but will throw an exception instead) and will return
    -- the "best" address first, whatever that means
    addr:_ <- N.getAddrInfo (Just N.defaultHints) (Just host) (Just port)
    bracketOnError (N.socket (N.addrFamily addr) N.Stream N.defaultProtocol)
                   tryCloseSocket $ \sock -> do
      when reuseAddr $ N.setSocketOption sock N.ReuseAddr 1
      N.bind sock (N.addrAddress addr)
      N.listen sock backlog
      -- We start listening for incoming requests in a separate thread. When
      -- that thread is killed, we close the server socket and the termination
      -- handler. We have to make sure that the exception handler is installed
      -- /before/ any asynchronous exception occurs. So we mask_, then fork
      -- (the child thread inherits the masked state from the parent), then
      -- unmask only inside the catch.
      (,) <$> fmap show (N.socketPort sock) <*>
        (mask_ $ forkIOWithUnmask $ \unmask ->
          catch (unmask (forever $ acceptRequest sock)) $ \ex -> do
            tryCloseSocket sock
            terminationHandler ex)
  where
    acceptRequest :: N.Socket -> IO ()
    acceptRequest sock = bracketOnError (N.accept sock)
                                        (tryCloseSocket . fst)
                                        (requestHandler . fst)

-- | Read a length and then a payload of that length
recvWithLength :: N.Socket -> IO [ByteString]
recvWithLength sock = recvInt32 sock >>= recvExact sock

-- | Receive a 32-bit integer
recvInt32 :: Num a => N.Socket -> IO a
recvInt32 sock = decodeInt32 . BS.concat <$> recvExact sock 4

-- | Close a socket, ignoring I/O exceptions
tryCloseSocket :: N.Socket -> IO ()
tryCloseSocket sock = void . tryIO $
  N.sClose sock

-- | Read an exact number of bytes from a socket
--
-- Throws an I/O exception if the socket closes before the specified
-- number of bytes could be read
recvExact :: N.Socket                -- ^ Socket to read from
          -> Int32                   -- ^ Number of bytes to read
          -> IO [ByteString]
recvExact _ len | len < 0 = throwIO (userError "recvExact: Negative length")
recvExact sock len = go [] len
  where
    go :: [ByteString] -> Int32 -> IO [ByteString]
    go acc 0 = return (reverse acc)
    go acc l = do
      bs <- NBS.recv sock (fromIntegral l `min` smallChunkSize)
      if BS.null bs
        then throwIO (userError "recvExact: Socket closed")
        else go (bs : acc) (l - fromIntegral (BS.length bs))


text:
package cz.metacentrum.perun.core.impl.modules.attributes;

import cz.metacentrum.perun.core.api.Attribute;
import cz.metacentrum.perun.core.api.AttributeDefinition;
import cz.metacentrum.perun.core.api.AttributesManager;
import cz.metacentrum.perun.core.api.ExtSource;
import cz.metacentrum.perun.core.api.User;
import cz.metacentrum.perun.core.api.UserExtSource;
import cz.metacentrum.perun.core.api.exceptions.ExtSourceNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.api.exceptions.UserExtSourceExistsException;
import cz.metacentrum.perun.core.impl.PerunSessionImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Class for checking logins uniqueness in the namespace and filling elixir-persistent id.
 * It is only storage! Use module login elixir_persistent for access the value.
 *
 * @author Sona Mastrakova <sona.mastrakova@gmail.com>
 * @author Ondrej Velisek <ondrejvelisek@gmail.com>
 *
 * @date 06.07.2015
 */
public class urn_perun_user_attribute_def_def_login_namespace_elixir_persistent_shadow extends urn_perun_user_attribute_def_def_login_namespace {

	private final static Logger log = LoggerFactory.getLogger(urn_perun_user_attribute_def_def_login_namespace_elixir_persistent_shadow.class);
	private final static String extSourceNameElixir = "https://login.elixir-czech.org/idp/";
	private final static String domainNameElixir = "@elixir-europe.org";
	private final static String attrNameElixir = "login-namespace:elixir-persistent-shadow";

	/**
	 * Filling implemented for login:namespace:elixir-persistent attribute
	 * Format is: "[hash]@elixir-europe.org" where [hash] represents sha1hash counted from user's id and perun instance id a login-namespace name
	 *
	 * @param perunSession PerunSession
	 * @param user User to fill attribute for
	 * @param attribute Attribute to fill value to
	 * @return Filled attribute
	 * @throws InternalErrorException
	 */
	@Override
	public Attribute fillAttribute(PerunSessionImpl perunSession, User user, AttributeDefinition attribute) throws InternalErrorException {

		Attribute filledAttribute = new Attribute(attribute);

		if (attribute.getFriendlyName().equals(attrNameElixir)) {
			filledAttribute.setValue(sha1HashCount(user, domainNameElixir).toString() + domainNameElixir);
			return filledAttribute;
		} else {
			// without value
			return filledAttribute;
		}
	}

	/**
	 * ChangedAttributeHook() sets UserExtSource with following properties:
	 *  - extSourceType is IdP
	 *  - extSourceName is https://engine.elixir-idp.ics.muni.cz/authentication/idp/metadata
	 *  - user's extSource login is the same as his elixir-persistent attribute
	 *
	 * @param session PerunSession
	 * @param user User to set UserExtSource for
	 * @param attribute Attribute containing elixirID
	 * @throws cz.metacentrum.perun.core.api.exceptions.InternalErrorException
	 */
	@Override
	public void changedAttributeHook(PerunSessionImpl session, User user, Attribute attribute) throws InternalErrorException {
		try {
			String userNamespace = attribute.getFriendlyNameParameter();

			if(userNamespace.equals("elixir-persistent-shadow") && attribute.getValue() != null){
				ExtSource extSource = session.getPerunBl().getExtSourcesManagerBl().getExtSourceByName(session, extSourceNameElixir);
				UserExtSource userExtSource = new UserExtSource(extSource, 0, attribute.getValue().toString());

				session.getPerunBl().getUsersManagerBl().addUserExtSource(session, user, userExtSource);
			}
		} catch (UserExtSourceExistsException ex) {
			log.warn("Elixir IdP external source already exists for the user.", ex);
		} catch (ExtSourceNotExistsException ex) {
			throw new InternalErrorException("IdP external source for elixir doesn't exist.", ex);
		}
	}

	@Override
	public AttributeDefinition getAttributeDefinition() {
		AttributeDefinition attr = new AttributeDefinition();
		attr.setNamespace(AttributesManager.NS_USER_ATTR_DEF);
		attr.setFriendlyName("login-namespace:elixir-persistent-shadow");
		attr.setDisplayName("ELIXIR login");
		attr.setType(String.class.getName());
		attr.setDescription("Login to ELIXIR. Do not use it directly! " +
				"Use \"user:virt:login-namespace:elixir-persistent\" attribute instead.");
		return attr;
	}
}


text:
require "test_helper"

unless ENV['OFFLINE']
  describe Mine::Fetch::Http::Get do
    let(:get) { Mine::Fetch::Http::Get.new("http://example.com/") }

    let(:response) { get.() }

    it 'fetches with success' do
      assert Net::HTTPOK === response.http_response
    end

    it 'fetches body' do
      assert_match /^\s*<!doctype html>/, response.body
    end
  end
end


text:
pre {
font-family: inherit;
}

table.issue {
  table-layout: fixed;
  width: 100%;
  margin-top: 1em;
  border-collapse: collapse;
  border-spacing: 0px;
}

table.issue, table.issue td, table.issue th {
  border: 1px solid black;
  padding: 5px;
}

table.issue .timestamp {
  width: 20px;
}

table.issue .type {
  width: 20px;
}

table.issue .message .output {
  margin: 0px;
  overflow-x: auto;
  width: 100%;
}

table.links {
  table-layout: fixed;
  width: 100%;
}


text:
package com.qh.common.domain;

import java.io.Serializable;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

@SuppressWarnings("serial")
public class ScheduleJob implements Serializable ,Job {

	public static final String STATUS_RUNNING = "1";
	public static final String STATUS_NOT_RUNNING = "0";
	public static final String CONCURRENT_IS = "1";
	public static final String CONCURRENT_NOT = "0";

	/**
	 * 任务名称
	 */
	private String jobName;
	/**
	 * 任务分组
	 */
	private String jobGroup;
	/**
	 * 任务状态 是否启动任务
	 */
	private String jobStatus;
	/**
	 * cron表达式
	 */
	private String cronExpression;
	/**
	 * 描述
	 */
	private String description;
	/**
	 * 任务执行时调用哪个类的方法 包名+类名
	 */
	private String beanClass;
	/**
	 * 任务是否有状态
	 */
	private String isConcurrent;

	/**
	 * Spring bean
	 */
	private String springBean;

	/**
	 * 任务调用的方法名
	 */
	private String methodName;

	public String getJobName() {
		return jobName;
	}

	public void setJobName(String jobName) {
		this.jobName = jobName;
	}

	public String getJobGroup() {
		return jobGroup;
	}

	public void setJobGroup(String jobGroup) {
		this.jobGroup = jobGroup;
	}

	public String getJobStatus() {
		return jobStatus;
	}

	public void setJobStatus(String jobStatus) {
		this.jobStatus = jobStatus;
	}

	public String getCronExpression() {
		return cronExpression;
	}

	public void setCronExpression(String cronExpression) {
		this.cronExpression = cronExpression;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String getBeanClass() {
		return beanClass;
	}

	public void setBeanClass(String beanClass) {
		this.beanClass = beanClass;
	}

	public String getIsConcurrent() {
		return isConcurrent;
	}

	public void setIsConcurrent(String isConcurrent) {
		this.isConcurrent = isConcurrent;
	}

	public String getMethodName() {
		return methodName;
	}

	public void setMethodName(String methodName) {
		this.methodName = methodName;
	}

	public String getSpringBean() {
		return springBean;
	}

	public void setSpringBean(String springBean) {
		this.springBean = springBean;
	}

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		// TODO Auto-generated method stub

	}

}


text:
package com.google.android.things.contrib.driver.ws2812b.util;

import android.graphics.Color;

import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;

import static org.mockito.Matchers.anyInt;

public class ColorMock {
    public static void mockStatic() {
        PowerMockito.mockStatic(Color.class);

        mockRed();
        mockGreen();
        mockBlue();
        mockRgb();
        mockArgb();
    }

    private static void mockRgb() {
        Mockito.when(Color.rgb(anyInt(), anyInt(), anyInt())).thenAnswer(new Answer() {
            @Override
            public Integer answer(InvocationOnMock invocation) throws Throwable {
                int r = invocation.getArgumentAt(0, Integer.class);
                int g = invocation.getArgumentAt(1, Integer.class);
                int b = invocation.getArgumentAt(2, Integer.class);
                return (r << 16) | (g << 8) | b;
            }
        });
    }

    private static void mockArgb() {
        Mockito.when(Color.argb(anyInt(), anyInt(), anyInt(), anyInt())).thenAnswer(new Answer() {
            @Override
            public Integer answer(InvocationOnMock invocation) throws Throwable {
                int a = invocation.getArgumentAt(0, Integer.class);
                int r = invocation.getArgumentAt(1, Integer.class);
                int g = invocation.getArgumentAt(2, Integer.class);
                int b = invocation.getArgumentAt(3, Integer.class);
                return (a << 24) | (r << 16) | (g << 8) | b;
            }
        });
    }

    private static void mockBlue() {
        Mockito.when(Color.blue(anyInt())).thenAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                int c = invocation.getArgumentAt(0, Integer.class);
                return c & 0xff;
            }
        });
    }

    private static void mockGreen() {
        Mockito.when(Color.green(anyInt())).thenAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                int c = invocation.getArgumentAt(0, Integer.class);
                return (c >> 8) & 0xff;
            }
        });
    }

    private static void mockRed() {
        Mockito.when(Color.red(anyInt())).thenAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                int c = invocation.getArgumentAt(0, Integer.class);
                return (c >> 16) & 0xff;
            }
        });
    }
}