text:
'use strict';

import * as path from 'path';
import * as fs from 'original-fs';
import * as platform from 'vs/base/common/platform';
import * as nls from 'vs/nls';
import * as paths from 'vs/base/common/paths';
import * as types from 'vs/base/common/types';
import * as arrays from 'vs/base/common/arrays';
import { assign, mixin } from 'vs/base/common/objects';
import { IBackupMainService } from 'vs/platform/backup/common/backup';
import { trim } from 'vs/base/common/strings';
import { IEnvironmentService, ParsedArgs } from 'vs/platform/environment/common/environment';
import { IStorageService } from 'vs/code/electron-main/storage';
import { IPath, VSCodeWindow, IWindowConfiguration, IWindowState as ISingleWindowState, defaultWindowState, ReadyState, WindowMode } from 'vs/code/electron-main/window';
import { ipcMain as ipc, app, screen, BrowserWindow, dialog } from 'electron';
import { IPathWithLineAndColumn, parseLineAndColumnAware } from 'vs/code/electron-main/paths';
import { ILifecycleService, UnloadReason } from 'vs/code/electron-main/lifecycle';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ILogService } from 'vs/code/electron-main/log';
import { getPathLabel } from 'vs/base/common/labels';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IWindowSettings } from 'vs/platform/windows/common/windows';
import CommonEvent, { Emitter } from 'vs/base/common/event';
import product from 'vs/platform/node/product';

enum WindowError {
	UNRESPONSIVE,
	CRASHED
}

export enum OpenContext {

	// opening when running from the command line
	CLI,

	// macOS only: opening from the dock (also when opening files to a running instance from desktop)
	DOCK,

	// opening from the main application window
	MENU,

	// opening from a file or folder dialog
	DIALOG,

	// any other way of opening
	OTHER
}

export interface IOpenConfiguration {
	context: OpenContext;
	cli: ParsedArgs;
	userEnv?: platform.IProcessEnvironment;
	pathsToOpen?: string[];
	preferNewWindow?: boolean;
	forceNewWindow?: boolean;
	forceReuseWindow?: boolean;
	forceEmpty?: boolean;
	windowToUse?: VSCodeWindow;
	diffMode?: boolean;
	initialStartup?: boolean;
}

interface IWindowState {
	workspacePath?: string;
	uiState: ISingleWindowState;
}

interface IWindowsState {
	lastActiveWindow?: IWindowState;
	lastPluginDevelopmentHostWindow?: IWindowState;
	openedFolders: IWindowState[];
}

export interface IRecentPathsList {
	folders: string[];
	files: string[];
}

interface INativeOpenDialogOptions {
	pickFolders?: boolean;
	pickFiles?: boolean;
	path?: string;
	forceNewWindow?: boolean;
	window?: VSCodeWindow;
}

const ReopenFoldersSetting = {
	ALL: 'all',
	ONE: 'one',
	NONE: 'none'
};

export const IWindowsMainService = createDecorator<IWindowsMainService>('windowsMainService');

export interface IWindowsMainService {
	_serviceBrand: any;

	// events
	onWindowReady: CommonEvent<VSCodeWindow>;
	onWindowClose: CommonEvent<number>;
	onWindowReload: CommonEvent<number>;
	onPathsOpen: CommonEvent<IPath[]>;
	onRecentPathsChange: CommonEvent<void>;

	// methods
	ready(initialUserEnv: platform.IProcessEnvironment): void;
	reload(win: VSCodeWindow, cli?: ParsedArgs): void;
	open(openConfig: IOpenConfiguration): VSCodeWindow[];
	openExtensionDevelopmentHostWindow(openConfig: IOpenConfiguration): void;
	openFileFolderPicker(forceNewWindow?: boolean): void;
	openFilePicker(forceNewWindow?: boolean, path?: string, window?: VSCodeWindow): void;
	openFolderPicker(forceNewWindow?: boolean, window?: VSCodeWindow): void;
	openAccessibilityOptions(): void;
	focusLastActive(cli: ParsedArgs, context: OpenContext): VSCodeWindow;
	getLastActiveWindow(): VSCodeWindow;
	findWindow(workspacePath: string, filePath?: string, extensionDevelopmentPath?: string): VSCodeWindow;
	openNewWindow(context: OpenContext): void;
	sendToFocused(channel: string, ...args: any[]): void;
	sendToAll(channel: string, payload: any, windowIdsToIgnore?: number[]): void;
	getFocusedWindow(): VSCodeWindow;
	getWindowById(windowId: number): VSCodeWindow;
	getWindows(): VSCodeWindow[];
	getWindowCount(): number;
	addToRecentPathsList(paths: { path: string; isFile?: boolean; }[]): void;
	getRecentPathsList(workspacePath?: string, filesToOpen?: IPath[]): IRecentPathsList;
	removeFromRecentPathsList(path: string): void;
	removeFromRecentPathsList(paths: string[]): void;
	clearRecentPathsList(): void;
	quit(): void;
}

export class WindowsManager implements IWindowsMainService {

	_serviceBrand: any;

	private static MAX_TOTAL_RECENT_ENTRIES = 100;

	private static recentPathsListStorageKey = 'openedPathsList';
	private static workingDirPickerStorageKey = 'pickerWorkingDir';
	private static windowsStateStorageKey = 'windowsState';

	private static WINDOWS: VSCodeWindow[] = [];

	private initialUserEnv: platform.IProcessEnvironment;
	private windowsState: IWindowsState;

	private _onRecentPathsChange = new Emitter<void>();
	onRecentPathsChange: CommonEvent<void> = this._onRecentPathsChange.event;

	private _onWindowReady = new Emitter<VSCodeWindow>();
	onWindowReady: CommonEvent<VSCodeWindow> = this._onWindowReady.event;

	private _onWindowClose = new Emitter<number>();
	onWindowClose: CommonEvent<number> = this._onWindowClose.event;

	private _onWindowReload = new Emitter<number>();
	onWindowReload: CommonEvent<number> = this._onWindowReload.event;

	private _onPathsOpen = new Emitter<IPath[]>();
	onPathsOpen: CommonEvent<IPath> = this._onPathsOpen.event;

	constructor(
		@ILogService private logService: ILogService,
		@IStorageService private storageService: IStorageService,
		@IEnvironmentService private environmentService: IEnvironmentService,
		@ILifecycleService private lifecycleService: ILifecycleService,
		@IBackupMainService private backupService: IBackupMainService,
		@IConfigurationService private configurationService: IConfigurationService
	) { }

	public ready(initialUserEnv: platform.IProcessEnvironment): void {
		this.registerListeners();

		this.initialUserEnv = initialUserEnv;
		this.windowsState = this.storageService.getItem<IWindowsState>(WindowsManager.windowsStateStorageKey) || { openedFolders: [] };

		this.updateWindowsJumpList();
	}

	private registerListeners(): void {
		app.on('activate', (event: Event, hasVisibleWindows: boolean) => {
			this.logService.log('App#activate');

			// Mac only event: open new window when we get activated
			if (!hasVisibleWindows) {
				this.openNewWindow(OpenContext.DOCK);
			}
		});

		let macOpenFiles: string[] = [];
		let runningTimeout: number = null;
		app.on('open-file', (event: Event, path: string) => {
			this.logService.log('App#open-file: ', path);
			event.preventDefault();

			// Keep in array because more might come!
			macOpenFiles.push(path);

			// Clear previous handler if any
			if (runningTimeout !== null) {
				clearTimeout(runningTimeout);
				runningTimeout = null;
			}

			// Handle paths delayed in case more are coming!
			runningTimeout = setTimeout(() => {
				this.open({
					context: OpenContext.DOCK /* can also be opening from finder while app is running */,
					cli: this.environmentService.args,
					pathsToOpen: macOpenFiles,
					preferNewWindow: true /* dropping on the dock or opening from finder prefers to open in a new window */
				});
				macOpenFiles = [];
				runningTimeout = null;
			}, 100);
		});

		ipc.on('vscode:workbenchLoaded', (event, windowId: number) => {
			this.logService.log('IPC#vscode-workbenchLoaded');

			const win = this.getWindowById(windowId);
			if (win) {
				win.setReady();

				// Event
				this._onWindowReady.fire(win);
			}
		});

		ipc.on('vscode:broadcast', (event, windowId: number, target: string, broadcast: { channel: string; payload: any; }) => {
			if (broadcast.channel && !types.isUndefinedOrNull(broadcast.payload)) {
				this.logService.log('IPC#vscode:broadcast', target, broadcast.channel, broadcast.payload);

				// Handle specific events on main side
				this.onBroadcast(broadcast.channel, broadcast.payload);

				// Send to windows
				if (target) {
					const otherWindowsWithTarget = WindowsManager.WINDOWS.filter(w => w.id !== windowId && typeof w.openedWorkspacePath === 'string');
					const directTargetMatch = otherWindowsWithTarget.filter(w => this.isPathEqual(target, w.openedWorkspacePath));
					const parentTargetMatch = otherWindowsWithTarget.filter(w => paths.isEqualOrParent(target, w.openedWorkspacePath));

					const targetWindow = directTargetMatch.length ? directTargetMatch[0] : parentTargetMatch[0]; // prefer direct match over parent match
					if (targetWindow) {
						targetWindow.send('vscode:broadcast', broadcast);
					}
				} else {
					this.sendToAll('vscode:broadcast', broadcast, [windowId]);
				}
			}
		});

		this.lifecycleService.onBeforeQuit(() => {

			// 0-1 window open: Do not keep the list but just rely on the active window to be stored
			if (WindowsManager.WINDOWS.length < 2) {
				this.windowsState.openedFolders = [];
				return;
			}

			// 2-N windows open: Keep a list of windows that are opened on a specific folder to restore it in the next session as needed
			this.windowsState.openedFolders = WindowsManager.WINDOWS.filter(w => w.readyState === ReadyState.READY && !!w.openedWorkspacePath && !w.isExtensionDevelopmentHost).map(w => {
				return <IWindowState>{
					workspacePath: w.openedWorkspacePath,
					uiState: w.serializeWindowState()
				};
			});
		});

		app.on('will-quit', () => {
			this.storageService.setItem(WindowsManager.windowsStateStorageKey, this.windowsState);
		});

		// Update jump list when recent paths change
		this.onRecentPathsChange(() => this.updateWindowsJumpList());
	}

	private onBroadcast(event: string, payload: any): void {

		// Theme changes
		if (event === 'vscode:changeColorTheme' && typeof payload === 'string') {
			this.storageService.setItem(VSCodeWindow.colorThemeStorageKey, payload);
		}
	}

	public reload(win: VSCodeWindow, cli?: ParsedArgs): void {

		// Only reload when the window has not vetoed this
		this.lifecycleService.unload(win, UnloadReason.RELOAD).done(veto => {
			if (!veto) {
				win.reload(cli);

				// Emit
				this._onWindowReload.fire(win.id);
			}
		});
	}

	public open(openConfig: IOpenConfiguration): VSCodeWindow[] {
		const windowConfig = this.configurationService.getConfiguration<IWindowSettings>('window');

		let iPathsToOpen: IPath[];
		const usedWindows: VSCodeWindow[] = [];

		// Find paths from provided paths if any
		if (openConfig.pathsToOpen && openConfig.pathsToOpen.length > 0) {
			iPathsToOpen = openConfig.pathsToOpen.map(pathToOpen => {
				const iPath = this.toIPath(pathToOpen, false, openConfig.cli && openConfig.cli.goto);

				// Warn if the requested path to open does not exist
				if (!iPath) {
					const options: Electron.ShowMessageBoxOptions = {
						title: product.nameLong,
						type: 'info',
						buttons: [nls.localize('ok', "OK")],
						message: nls.localize('pathNotExistTitle', "Path does not exist"),
						detail: nls.localize('pathNotExistDetail', "The path '{0}' does not seem to exist anymore on disk.", pathToOpen),
						noLink: true
					};

					const activeWindow = BrowserWindow.getFocusedWindow();
					if (activeWindow) {
						dialog.showMessageBox(activeWindow, options);
					} else {
						dialog.showMessageBox(options);
					}
				}

				return iPath;
			});

			// get rid of nulls
			iPathsToOpen = arrays.coalesce(iPathsToOpen);

			if (iPathsToOpen.length === 0) {
				return null; // indicate to outside that open failed
			}
		}

		// Check for force empty
		else if (openConfig.forceEmpty) {
			iPathsToOpen = [Object.create(null)];
		}

		// Otherwise infer from command line arguments
		else {
			const ignoreFileNotFound = openConfig.cli._.length > 0; // we assume the user wants to create this file from command line
			iPathsToOpen = this.cliToPaths(openConfig.cli, ignoreFileNotFound);
		}

		let foldersToOpen = arrays.distinct(iPathsToOpen.filter(iPath => iPath.workspacePath && !iPath.filePath).map(iPath => iPath.workspacePath), folder => platform.isLinux ? folder : folder.toLowerCase()); // prevent duplicates
		let foldersToRestore = (openConfig.initialStartup && !openConfig.cli.extensionDevelopmentPath) ? this.backupService.getWorkspaceBackupPaths() : [];
		let filesToOpen: IPath[] = [];
		let filesToDiff: IPath[] = [];
		let emptyToOpen = iPathsToOpen.filter(iPath => !iPath.workspacePath && !iPath.filePath);
		let emptyToRestore = (openConfig.initialStartup && !openConfig.cli.extensionDevelopmentPath) ? this.backupService.getEmptyWorkspaceBackupPaths() : [];
		let filesToCreate = iPathsToOpen.filter(iPath => !!iPath.filePath && iPath.createFilePath);

		// Diff mode needs special care
		const candidates = iPathsToOpen.filter(iPath => !!iPath.filePath && !iPath.createFilePath);
		if (openConfig.diffMode) {
			if (candidates.length === 2) {
				filesToDiff = candidates;
			} else {
				emptyToOpen = [Object.create(null)]; // improper use of diffMode, open empty
			}

			foldersToOpen = []; 	// diff is always in empty workspace
			foldersToRestore = [];	// diff is always in empty workspace
			filesToCreate = []; 	// diff ignores other files that do not exist
		} else {
			filesToOpen = candidates;
		}

		// let the user settings override how folders are open in a new window or same window unless we are forced
		let openFolderInNewWindow = (openConfig.preferNewWindow || openConfig.forceNewWindow) && !openConfig.forceReuseWindow;
		if (!openConfig.forceNewWindow && !openConfig.forceReuseWindow && windowConfig && (windowConfig.openFoldersInNewWindow === 'on' || windowConfig.openFoldersInNewWindow === 'off')) {
			openFolderInNewWindow = (windowConfig.openFoldersInNewWindow === 'on');
		}

		// Handle files to open/diff or to create when we dont open a folder
		if (!foldersToOpen.length && (filesToOpen.length > 0 || filesToCreate.length > 0 || filesToDiff.length > 0)) {

			// let the user settings override how files are open in a new window or same window unless we are forced (not for extension development though)
			let openFilesInNewWindow: boolean;
			if (openConfig.forceNewWindow || openConfig.forceReuseWindow) {
				openFilesInNewWindow = openConfig.forceNewWindow && !openConfig.forceReuseWindow;
			} else {
				if (openConfig.context === OpenContext.DOCK) {
					openFilesInNewWindow = true; // only on macOS do we allow to open files in a new window if this is triggered via DOCK context
				}

				if (!openConfig.cli.extensionDevelopmentPath && windowConfig && (windowConfig.openFilesInNewWindow === 'on' || windowConfig.openFilesInNewWindow === 'off' || <any>windowConfig.openFilesInNewWindow === false /* TODO@Ben migration */)) {
					openFilesInNewWindow = (windowConfig.openFilesInNewWindow === 'on');
				}
			}

			// Open Files in last instance if any and flag tells us so
			const lastActiveWindow = this.getLastActiveWindow();
			if (!openFilesInNewWindow && lastActiveWindow) {
				lastActiveWindow.focus();
				const files = { filesToOpen, filesToCreate, filesToDiff }; // copy to object because they get reset shortly after
				lastActiveWindow.ready().then(readyWindow => {
					readyWindow.send('vscode:openFiles', files);
				});

				usedWindows.push(lastActiveWindow);
			}

			// Otherwise open instance with files
			else {
				const configuration = this.toConfiguration(openConfig, null, filesToOpen, filesToCreate, filesToDiff);
				const browserWindow = this.openInBrowserWindow(configuration, true /* new window */);
				usedWindows.push(browserWindow);

				openFolderInNewWindow = true; // any other folders to open must open in new window then
			}

			// Reset these because we handled them
			filesToOpen = [];
			filesToCreate = [];
			filesToDiff = [];
		}

		// Handle folders to open (instructed and to restore)
		let allFoldersToOpen = arrays.distinct([...foldersToOpen, ...foldersToRestore], folder => platform.isLinux ? folder : folder.toLowerCase()); // prevent duplicates
		if (allFoldersToOpen.length > 0) {

			// Check for existing instances
			const windowsOnWorkspacePath = arrays.coalesce(allFoldersToOpen.map(folderToOpen => this.findWindow(folderToOpen)));
			if (windowsOnWorkspacePath.length > 0) {
				const browserWindow = windowsOnWorkspacePath[0];
				browserWindow.focus(); // just focus one of them
				const files = { filesToOpen, filesToCreate, filesToDiff }; // copy to object because they get reset shortly after
				browserWindow.ready().then(readyWindow => {
					readyWindow.send('vscode:openFiles', files);
				});

				usedWindows.push(browserWindow);

				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
				filesToDiff = [];

				openFolderInNewWindow = true; // any other folders to open must open in new window then
			}

			// Open remaining ones
			allFoldersToOpen.forEach(folderToOpen => {
				if (windowsOnWorkspacePath.some(win => this.isPathEqual(win.openedWorkspacePath, folderToOpen))) {
					return; // ignore folders that are already open
				}

				const configuration = this.toConfiguration(openConfig, folderToOpen, filesToOpen, filesToCreate, filesToDiff);
				const browserWindow = this.openInBrowserWindow(configuration, openFolderInNewWindow, openFolderInNewWindow ? void 0 : openConfig.windowToUse);
				usedWindows.push(browserWindow);

				// Reset these because we handled them
				filesToOpen = [];
				filesToCreate = [];
				filesToDiff = [];

				openFolderInNewWindow = true; // any other folders to open must open in new window then
			});
		}

		// Handle empty
		if (emptyToRestore.length > 0) {
			emptyToRestore.forEach(emptyWorkspaceBackupFolder => {
				const configuration = this.toConfiguration(openConfig);
				const browserWindow = this.openInBrowserWindow(configuration, true /* new window */, null, emptyWorkspaceBackupFolder);
				usedWindows.push(browserWindow);

				openFolderInNewWindow = true; // any other folders to open must open in new window then
			});
		}

		// Only open empty if no empty workspaces were restored
		else if (emptyToOpen.length > 0) {
			emptyToOpen.forEach(() => {
				const configuration = this.toConfiguration(openConfig);
				const browserWindow = this.openInBrowserWindow(configuration, openFolderInNewWindow, openFolderInNewWindow ? void 0 : openConfig.windowToUse);
				usedWindows.push(browserWindow);

				openFolderInNewWindow = true; // any other folders to open must open in new window then
			});
		}

		// Remember in recent document list (unless this opens for extension development)
		// Also do not add paths when files are opened for diffing, only if opened individually
		if (!usedWindows.some(w => w.isExtensionDevelopmentHost) && !openConfig.cli.diff) {
			const recentPaths: { path: string; isFile?: boolean; }[] = [];

			iPathsToOpen.forEach(iPath => {
				if (iPath.filePath || iPath.workspacePath) {
					app.addRecentDocument(iPath.filePath || iPath.workspacePath);
					recentPaths.push({ path: iPath.filePath || iPath.workspacePath, isFile: !!iPath.filePath });
				}
			});

			if (recentPaths.length) {
				this.addToRecentPathsList(recentPaths);
			}
		}

		// Emit events
		this._onPathsOpen.fire(iPathsToOpen);

		return arrays.distinct(usedWindows);
	}

	public addToRecentPathsList(paths: { path: string; isFile?: boolean; }[]): void {
		if (!paths || !paths.length) {
			return;
		}

		const mru = this.getRecentPathsList();
		paths.forEach(p => {
			const {path, isFile} = p;

			if (isFile) {
				mru.files.unshift(path);
				mru.files = arrays.distinct(mru.files, (f) => platform.isLinux ? f : f.toLowerCase());
			} else {
				mru.folders.unshift(path);
				mru.folders = arrays.distinct(mru.folders, (f) => platform.isLinux ? f : f.toLowerCase());
			}

			// Make sure its bounded
			mru.folders = mru.folders.slice(0, WindowsManager.MAX_TOTAL_RECENT_ENTRIES);
			mru.files = mru.files.slice(0, WindowsManager.MAX_TOTAL_RECENT_ENTRIES);
		});

		this.storageService.setItem(WindowsManager.recentPathsListStorageKey, mru);
		this._onRecentPathsChange.fire();
	}

	public removeFromRecentPathsList(path: string): void;
	public removeFromRecentPathsList(paths: string[]): void;
	public removeFromRecentPathsList(arg1: any): void {
		let paths: string[];
		if (Array.isArray(arg1)) {
			paths = arg1;
		} else {
			paths = [arg1];
		}

		const mru = this.getRecentPathsList();
		let update = false;

		paths.forEach(path => {
			let index = mru.files.indexOf(path);
			if (index >= 0) {
				mru.files.splice(index, 1);
				update = true;
			}

			index = mru.folders.indexOf(path);
			if (index >= 0) {
				mru.folders.splice(index, 1);
				update = true;
			}
		});

		if (update) {
			this.storageService.setItem(WindowsManager.recentPathsListStorageKey, mru);
			this._onRecentPathsChange.fire();
		}
	}

	public clearRecentPathsList(): void {
		this.storageService.setItem(WindowsManager.recentPathsListStorageKey, { folders: [], files: [] });
		app.clearRecentDocuments();

		// Event
		this._onRecentPathsChange.fire();
	}

	public getRecentPathsList(workspacePath?: string, filesToOpen?: IPath[]): IRecentPathsList {
		let files: string[];
		let folders: string[];

		// Get from storage
		const storedRecents = this.storageService.getItem<IRecentPathsList>(WindowsManager.recentPathsListStorageKey);
		if (storedRecents) {
			files = storedRecents.files || [];
			folders = storedRecents.folders || [];
		} else {
			files = [];
			folders = [];
		}

		// Add currently files to open to the beginning if any
		if (filesToOpen) {
			files.unshift(...filesToOpen.map(f => f.filePath));
		}

		// Add current workspace path to beginning if set
		if (workspacePath) {
			folders.unshift(workspacePath);
		}

		// Clear those dupes
		files = arrays.distinct(files);
		folders = arrays.distinct(folders);

		return { files, folders };
	}

	private getWindowUserEnv(openConfig: IOpenConfiguration): platform.IProcessEnvironment {
		return assign({}, this.initialUserEnv, openConfig.userEnv || {});
	}

	public openExtensionDevelopmentHostWindow(openConfig: IOpenConfiguration): void {

		// Reload an existing extension development host window on the same path
		// We currently do not allow more than one extension development window
		// on the same extension path.
		let res = WindowsManager.WINDOWS.filter(w => w.config && this.isPathEqual(w.config.extensionDevelopmentPath, openConfig.cli.extensionDevelopmentPath));
		if (res && res.length === 1) {
			this.reload(res[0], openConfig.cli);
			res[0].focus(); // make sure it gets focus and is restored

			return;
		}

		// Fill in previously opened workspace unless an explicit path is provided and we are not unit testing
		if (openConfig.cli._.length === 0 && !openConfig.cli.extensionTestsPath) {
			const workspaceToOpen = this.windowsState.lastPluginDevelopmentHostWindow && this.windowsState.lastPluginDevelopmentHostWindow.workspacePath;
			if (workspaceToOpen) {
				openConfig.cli._ = [workspaceToOpen];
			}
		}

		// Make sure we are not asked to open a path that is already opened
		if (openConfig.cli._.length > 0) {
			res = WindowsManager.WINDOWS.filter(w => w.openedWorkspacePath && openConfig.cli._.indexOf(w.openedWorkspacePath) >= 0);
			if (res.length) {
				openConfig.cli._ = [];
			}
		}

		// Open it
		this.open({ context: openConfig.context, cli: openConfig.cli, forceNewWindow: true, forceEmpty: openConfig.cli._.length === 0 });
	}

	private toConfiguration(config: IOpenConfiguration, workspacePath?: string, filesToOpen?: IPath[], filesToCreate?: IPath[], filesToDiff?: IPath[]): IWindowConfiguration {
		const configuration: IWindowConfiguration = mixin({}, config.cli); // inherit all properties from CLI
		configuration.appRoot = this.environmentService.appRoot;
		configuration.execPath = process.execPath;
		configuration.userEnv = this.getWindowUserEnv(config);
		configuration.isInitialStartup = config.initialStartup;
		configuration.workspacePath = workspacePath;
		configuration.filesToOpen = filesToOpen;
		configuration.filesToCreate = filesToCreate;
		configuration.filesToDiff = filesToDiff;
		configuration.nodeCachedDataDir = this.environmentService.isBuilt && this.environmentService.nodeCachedDataDir;

		return configuration;
	}

	private toIPath(anyPath: string, ignoreFileNotFound?: boolean, gotoLineMode?: boolean): IPath {
		if (!anyPath) {
			return null;
		}

		let parsedPath: IPathWithLineAndColumn;
		if (gotoLineMode) {
			parsedPath = parseLineAndColumnAware(anyPath);
			anyPath = parsedPath.path;
		}

		const candidate = path.normalize(anyPath);
		try {
			const candidateStat = fs.statSync(candidate);
			if (candidateStat) {
				return candidateStat.isFile() ?
					{
						filePath: candidate,
						lineNumber: gotoLineMode ? parsedPath.line : void 0,
						columnNumber: gotoLineMode ? parsedPath.column : void 0
					} :
					{ workspacePath: candidate };
			}
		} catch (error) {
			this.removeFromRecentPathsList(candidate); // since file does not seem to exist anymore, remove from recent

			if (ignoreFileNotFound) {
				return { filePath: candidate, createFilePath: true }; // assume this is a file that does not yet exist
			}
		}

		return null;
	}

	private cliToPaths(cli: ParsedArgs, ignoreFileNotFound?: boolean): IPath[] {

		// Check for pass in candidate or last opened path
		let candidates: string[] = [];
		if (cli._.length > 0) {
			candidates = cli._;
		}

		// No path argument, check settings for what to do now
		else {
			let reopenFolders: string;
			if (this.lifecycleService.wasUpdated) {
				reopenFolders = ReopenFoldersSetting.ALL; // always reopen all folders when an update was applied
			} else {
				const windowConfig = this.configurationService.getConfiguration<IWindowSettings>('window');
				reopenFolders = (windowConfig && windowConfig.reopenFolders) || ReopenFoldersSetting.ONE;
			}

			const lastActiveFolder = this.windowsState.lastActiveWindow && this.windowsState.lastActiveWindow.workspacePath;

			// Restore all
			if (reopenFolders === ReopenFoldersSetting.ALL) {
				const lastOpenedFolders = this.windowsState.openedFolders.map(o => o.workspacePath);

				// If we have a last active folder, move it to the end
				if (lastActiveFolder) {
					lastOpenedFolders.splice(lastOpenedFolders.indexOf(lastActiveFolder), 1);
					lastOpenedFolders.push(lastActiveFolder);
				}

				candidates.push(...lastOpenedFolders);
			}

			// Restore last active
			else if (lastActiveFolder && (reopenFolders === ReopenFoldersSetting.ONE || reopenFolders !== ReopenFoldersSetting.NONE)) {
				candidates.push(lastActiveFolder);
			}
		}

		const iPaths = candidates.map(candidate => this.toIPath(candidate, ignoreFileNotFound, cli.goto)).filter(path => !!path);
		if (iPaths.length > 0) {
			return iPaths;
		}

		// No path provided, return empty to open empty
		return [Object.create(null)];
	}

	private openInBrowserWindow(configuration: IWindowConfiguration, forceNewWindow?: boolean, windowToUse?: VSCodeWindow, emptyWorkspaceBackupFolder?: string): VSCodeWindow {
		let vscodeWindow: VSCodeWindow;

		if (!forceNewWindow) {
			vscodeWindow = windowToUse || this.getLastActiveWindow();

			if (vscodeWindow) {
				vscodeWindow.focus();
			}
		}

		// New window
		if (!vscodeWindow) {
			const windowConfig = this.configurationService.getConfiguration<IWindowSettings>('window');

			vscodeWindow = new VSCodeWindow({
				state: this.getNewWindowState(configuration),
				extensionDevelopmentPath: configuration.extensionDevelopmentPath,
				isExtensionTestHost: !!configuration.extensionTestsPath,
				allowFullscreen: this.lifecycleService.wasUpdated || (windowConfig && windowConfig.restoreFullscreen) || (windowConfig && windowConfig.newWindowDimensions && ['fullscreen', 'inherit'].indexOf(windowConfig.newWindowDimensions) >= 0),
				titleBarStyle: windowConfig ? windowConfig.titleBarStyle : void 0
			},
				this.logService,
				this.environmentService,
				this.configurationService,
				this.storageService
			);

			WindowsManager.WINDOWS.push(vscodeWindow);

			// Window Events
			vscodeWindow.win.webContents.removeAllListeners('devtools-reload-page'); // remove built in listener so we can handle this on our own
			vscodeWindow.win.webContents.on('devtools-reload-page', () => this.reload(vscodeWindow));
			vscodeWindow.win.webContents.on('crashed', () => this.onWindowError(vscodeWindow, WindowError.CRASHED));
			vscodeWindow.win.on('unresponsive', () => this.onWindowError(vscodeWindow, WindowError.UNRESPONSIVE));
			vscodeWindow.win.on('close', () => this.onBeforeWindowClose(vscodeWindow));
			vscodeWindow.win.on('closed', () => this.onWindowClosed(vscodeWindow));

			// Lifecycle
			this.lifecycleService.registerWindow(vscodeWindow);
		}

		// Existing window
		else {

			// Some configuration things get inherited if the window is being reused and we are
			// in extension development host mode. These options are all development related.
			const currentWindowConfig = vscodeWindow.config;
			if (!configuration.extensionDevelopmentPath && currentWindowConfig && !!currentWindowConfig.extensionDevelopmentPath) {
				configuration.extensionDevelopmentPath = currentWindowConfig.extensionDevelopmentPath;
				configuration.verbose = currentWindowConfig.verbose;
				configuration.debugBrkPluginHost = currentWindowConfig.debugBrkPluginHost;
				configuration.debugPluginHost = currentWindowConfig.debugPluginHost;
				configuration['extensions-dir'] = currentWindowConfig['extensions-dir'];
			}
		}

		// Only load when the window has not vetoed this
		this.lifecycleService.unload(vscodeWindow, UnloadReason.LOAD).done(veto => {
			if (!veto) {

				// Register window for backups
				if (!configuration.extensionDevelopmentPath) {
					this.backupService.registerWindowForBackupsSync(vscodeWindow.id, !configuration.workspacePath, emptyWorkspaceBackupFolder, configuration.workspacePath);
				}

				// Load it
				vscodeWindow.load(configuration);
			}
		});

		return vscodeWindow;
	}

	private getNewWindowState(configuration: IWindowConfiguration): ISingleWindowState {

		// extension development host Window - load from stored settings if any
		if (!!configuration.extensionDevelopmentPath && this.windowsState.lastPluginDevelopmentHostWindow) {
			return this.windowsState.lastPluginDevelopmentHostWindow.uiState;
		}

		// Known Folder - load from stored settings if any
		if (configuration.workspacePath) {
			const stateForWorkspace = this.windowsState.openedFolders.filter(o => this.isPathEqual(o.workspacePath, configuration.workspacePath)).map(o => o.uiState);
			if (stateForWorkspace.length) {
				return stateForWorkspace[0];
			}
		}

		// First Window
		const lastActive = this.getLastActiveWindow();
		if (!lastActive && this.windowsState.lastActiveWindow) {
			return this.windowsState.lastActiveWindow.uiState;
		}

		//
		// In any other case, we do not have any stored settings for the window state, so we come up with something smart
		//

		// We want the new window to open on the same display that the last active one is in
		let displayToUse: Electron.Display;
		const displays = screen.getAllDisplays();

		// Single Display
		if (displays.length === 1) {
			displayToUse = displays[0];
		}

		// Multi Display
		else {

			// on mac there is 1 menu per window so we need to use the monitor where the cursor currently is
			if (platform.isMacintosh) {
				const cursorPoint = screen.getCursorScreenPoint();
				displayToUse = screen.getDisplayNearestPoint(cursorPoint);
			}

			// if we have a last active window, use that display for the new window
			if (!displayToUse && lastActive) {
				displayToUse = screen.getDisplayMatching(lastActive.getBounds());
			}

			// fallback to first display
			if (!displayToUse) {
				displayToUse = displays[0];
			}
		}

		let state = defaultWindowState();
		state.x = displayToUse.bounds.x + (displayToUse.bounds.width / 2) - (state.width / 2);
		state.y = displayToUse.bounds.y + (displayToUse.bounds.height / 2) - (state.height / 2);

		// Check for newWindowDimensions setting and adjust accordingly
		const windowConfig = this.configurationService.getConfiguration<IWindowSettings>('window');
		let ensureNoOverlap = true;
		if (windowConfig && windowConfig.newWindowDimensions) {
			if (windowConfig.newWindowDimensions === 'maximized') {
				state.mode = WindowMode.Maximized;
				ensureNoOverlap = false;
			} else if (windowConfig.newWindowDimensions === 'fullscreen') {
				state.mode = WindowMode.Fullscreen;
				ensureNoOverlap = false;
			} else if (windowConfig.newWindowDimensions === 'inherit' && lastActive) {
				const lastActiveState = lastActive.serializeWindowState();
				if (lastActiveState.mode === WindowMode.Fullscreen) {
					state.mode = WindowMode.Fullscreen; // only take mode (fixes https://github.com/Microsoft/vscode/issues/19331)
				} else {
					state = lastActiveState;
				}

				ensureNoOverlap = false;
			}
		}

		if (ensureNoOverlap) {
			state = this.ensureNoOverlap(state);
		}

		return state;
	}

	private ensureNoOverlap(state: ISingleWindowState): ISingleWindowState {
		if (WindowsManager.WINDOWS.length === 0) {
			return state;
		}

		const existingWindowBounds = WindowsManager.WINDOWS.map(win => win.getBounds());
		while (existingWindowBounds.some(b => b.x === state.x || b.y === state.y)) {
			state.x += 30;
			state.y += 30;
		}

		return state;
	}

	public openFileFolderPicker(forceNewWindow?: boolean): void {
		this.doPickAndOpen({ pickFolders: true, pickFiles: true, forceNewWindow });
	}

	public openFilePicker(forceNewWindow?: boolean, path?: string, window?: VSCodeWindow): void {
		this.doPickAndOpen({ pickFiles: true, forceNewWindow, path, window });
	}

	public openFolderPicker(forceNewWindow?: boolean, window?: VSCodeWindow): void {
		this.doPickAndOpen({ pickFolders: true, forceNewWindow, window });
	}

	public openAccessibilityOptions(): void {
		let win = new BrowserWindow({
			alwaysOnTop: true,
			skipTaskbar: true,
			resizable: false,
			width: 450,
			height: 300,
			show: true,
			title: nls.localize('accessibilityOptionsWindowTitle', "Accessibility Options")
		});

		win.setMenuBarVisibility(false);

		win.loadURL('chrome://accessibility');
	}

	private doPickAndOpen(options: INativeOpenDialogOptions): void {
		this.getFileOrFolderPaths(options, (paths: string[]) => {
			if (paths && paths.length) {
				this.open({ context: OpenContext.DIALOG, cli: this.environmentService.args, pathsToOpen: paths, forceNewWindow: options.forceNewWindow });
			}
		});
	}

	private getFileOrFolderPaths(options: INativeOpenDialogOptions, clb: (paths: string[]) => void): void {
		const workingDir = options.path || this.storageService.getItem<string>(WindowsManager.workingDirPickerStorageKey);
		const focussedWindow = options.window || this.getFocusedWindow();

		let pickerProperties: ('openFile' | 'openDirectory' | 'multiSelections' | 'createDirectory')[];
		if (options.pickFiles && options.pickFolders) {
			pickerProperties = ['multiSelections', 'openDirectory', 'openFile', 'createDirectory'];
		} else {
			pickerProperties = ['multiSelections', options.pickFolders ? 'openDirectory' : 'openFile', 'createDirectory'];
		}

		dialog.showOpenDialog(focussedWindow && focussedWindow.win, {
			defaultPath: workingDir,
			properties: pickerProperties
		}, paths => {
			if (paths && paths.length > 0) {

				// Remember path in storage for next time
				this.storageService.setItem(WindowsManager.workingDirPickerStorageKey, path.dirname(paths[0]));

				// Return
				clb(paths);
			} else {
				clb(void (0));
			}
		});
	}

	public focusLastActive(cli: ParsedArgs, context: OpenContext): VSCodeWindow {
		const lastActive = this.getLastActiveWindow();
		if (lastActive) {
			lastActive.focus();

			return lastActive;
		}

		// No window - open new one
		this.windowsState.openedFolders = []; // make sure we do not open too much
		const res = this.open({ context, cli });

		return res && res[0];
	}

	public getLastActiveWindow(): VSCodeWindow {
		if (WindowsManager.WINDOWS.length) {
			const lastFocussedDate = Math.max.apply(Math, WindowsManager.WINDOWS.map(w => w.lastFocusTime));
			const res = WindowsManager.WINDOWS.filter(w => w.lastFocusTime === lastFocussedDate);
			if (res && res.length) {
				return res[0];
			}
		}

		return null;
	}

	public findWindow(workspacePath: string, filePath?: string, extensionDevelopmentPath?: string): VSCodeWindow {
		if (WindowsManager.WINDOWS.length) {

			// Sort the last active window to the front of the array of windows to test
			const windowsToTest = WindowsManager.WINDOWS.slice(0);
			const lastActiveWindow = this.getLastActiveWindow();
			if (lastActiveWindow) {
				windowsToTest.splice(windowsToTest.indexOf(lastActiveWindow), 1);
				windowsToTest.unshift(lastActiveWindow);
			}

			// Find it
			const res = windowsToTest.filter(w => {

				// match on workspace
				if (typeof w.openedWorkspacePath === 'string' && (this.isPathEqual(w.openedWorkspacePath, workspacePath))) {
					return true;
				}

				// match on file
				if (typeof w.openedFilePath === 'string' && this.isPathEqual(w.openedFilePath, filePath)) {
					return true;
				}

				// match on file path
				if (typeof w.openedWorkspacePath === 'string' && filePath && paths.isEqualOrParent(filePath, w.openedWorkspacePath)) {
					return true;
				}

				// match on extension development path
				if (typeof extensionDevelopmentPath === 'string' && w.extensionDevelopmentPath === extensionDevelopmentPath) {
					return true;
				}

				return false;
			});

			if (res && res.length) {
				return res[0];
			}
		}

		return null;
	}

	public openNewWindow(context: OpenContext): void {
		this.open({ context, cli: this.environmentService.args, forceNewWindow: true, forceEmpty: true });
	}

	public sendToFocused(channel: string, ...args: any[]): void {
		const focusedWindow = this.getFocusedWindow() || this.getLastActiveWindow();

		if (focusedWindow) {
			focusedWindow.sendWhenReady(channel, ...args);
		}
	}

	public sendToAll(channel: string, payload: any, windowIdsToIgnore?: number[]): void {
		WindowsManager.WINDOWS.forEach(w => {
			if (windowIdsToIgnore && windowIdsToIgnore.indexOf(w.id) >= 0) {
				return; // do not send if we are instructed to ignore it
			}

			w.sendWhenReady(channel, payload);
		});
	}

	public getFocusedWindow(): VSCodeWindow {
		const win = BrowserWindow.getFocusedWindow();
		if (win) {
			return this.getWindowById(win.id);
		}

		return null;
	}

	public getWindowById(windowId: number): VSCodeWindow {
		const res = WindowsManager.WINDOWS.filter(w => w.id === windowId);
		if (res && res.length === 1) {
			return res[0];
		}

		return null;
	}

	public getWindows(): VSCodeWindow[] {
		return WindowsManager.WINDOWS;
	}

	public getWindowCount(): number {
		return WindowsManager.WINDOWS.length;
	}

	private onWindowError(vscodeWindow: VSCodeWindow, error: WindowError): void {
		console.error(error === WindowError.CRASHED ? '[VS Code]: render process crashed!' : '[VS Code]: detected unresponsive');

		// Unresponsive
		if (error === WindowError.UNRESPONSIVE) {
			dialog.showMessageBox(vscodeWindow.win, {
				title: product.nameLong,
				type: 'warning',
				buttons: [nls.localize('reopen', "Reopen"), nls.localize('wait', "Keep Waiting"), nls.localize('close', "Close")],
				message: nls.localize('appStalled', "The window is no longer responding"),
				detail: nls.localize('appStalledDetail', "You can reopen or close the window or keep waiting."),
				noLink: true
			}, result => {
				if (result === 0) {
					vscodeWindow.reload();
				} else if (result === 2) {
					this.onBeforeWindowClose(vscodeWindow); // 'close' event will not be fired on destroy(), so run it manually
					vscodeWindow.win.destroy(); // make sure to destroy the window as it is unresponsive
				}
			});
		}

		// Crashed
		else {
			dialog.showMessageBox(vscodeWindow.win, {
				title: product.nameLong,
				type: 'warning',
				buttons: [nls.localize('reopen', "Reopen"), nls.localize('close', "Close")],
				message: nls.localize('appCrashed', "The window has crashed"),
				detail: nls.localize('appCrashedDetail', "We are sorry for the inconvenience! You can reopen the window to continue where you left off."),
				noLink: true
			}, result => {
				if (result === 0) {
					vscodeWindow.reload();
				} else if (result === 1) {
					this.onBeforeWindowClose(vscodeWindow); // 'close' event will not be fired on destroy(), so run it manually
					vscodeWindow.win.destroy(); // make sure to destroy the window as it has crashed
				}
			});
		}
	}

	private onBeforeWindowClose(win: VSCodeWindow): void {
		if (win.readyState !== ReadyState.READY) {
			return; // only persist windows that are fully loaded
		}

		// On Window close, update our stored state of this window
		const state: IWindowState = { workspacePath: win.openedWorkspacePath, uiState: win.serializeWindowState() };
		if (win.isExtensionDevelopmentHost) {
			if (!win.isExtensionTestHost) {
				this.windowsState.lastPluginDevelopmentHostWindow = state; // do not let test run window state overwrite our extension development state
			}
		} else {
			this.windowsState.lastActiveWindow = state;

			this.windowsState.openedFolders.forEach(o => {
				if (this.isPathEqual(o.workspacePath, win.openedWorkspacePath)) {
					o.uiState = state.uiState;
				}
			});
		}
	}

	private onWindowClosed(win: VSCodeWindow): void {

		// Tell window
		win.dispose();

		// Remove from our list so that Electron can clean it up
		const index = WindowsManager.WINDOWS.indexOf(win);
		WindowsManager.WINDOWS.splice(index, 1);

		// Emit
		this._onWindowClose.fire(win.id);
	}

	private isPathEqual(pathA: string, pathB: string): boolean {
		if (pathA === pathB) {
			return true;
		}

		if (!pathA || !pathB) {
			return false;
		}

		pathA = path.normalize(pathA);
		pathB = path.normalize(pathB);

		if (pathA === pathB) {
			return true;
		}

		if (!platform.isLinux) {
			pathA = pathA.toLowerCase();
			pathB = pathB.toLowerCase();
		}

		return pathA === pathB;
	}

	private updateWindowsJumpList(): void {
		if (!platform.isWindows) {
			return; // only on windows
		}

		const jumpList: Electron.JumpListCategory[] = [];

		// Tasks
		jumpList.push({
			type: 'tasks',
			items: [
				{
					type: 'task',
					title: nls.localize('newWindow', "New Window"),
					description: nls.localize('newWindowDesc', "Opens a new window"),
					program: process.execPath,
					args: '-n', // force new window
					iconPath: process.execPath,
					iconIndex: 0
				}
			]
		});

		// Recent Folders
		if (this.getRecentPathsList().folders.length > 0) {

			// The user might have meanwhile removed items from the jump list and we have to respect that
			// so we need to update our list of recent paths with the choice of the user to not add them again
			// Also: Windows will not show our custom category at all if there is any entry which was removed
			// by the user! See https://github.com/Microsoft/vscode/issues/15052
			this.removeFromRecentPathsList(app.getJumpListSettings().removedItems.map(r => trim(r.args, '"')));

			// Add entries
			jumpList.push({
				type: 'custom',
				name: nls.localize('recentFolders', "Recent Folders"),
				items: this.getRecentPathsList().folders.slice(0, 7 /* limit number of entries here */).map(folder => {
					return <Electron.JumpListItem>{
						type: 'task',
						title: path.basename(folder) || folder, // use the base name to show shorter entries in the list
						description: nls.localize('folderDesc', "{0} {1}", path.basename(folder), getPathLabel(path.dirname(folder))),
						program: process.execPath,
						args: `"${folder}"`, // open folder (use quotes to support paths with whitespaces)
						iconPath: 'explorer.exe', // simulate folder icon
						iconIndex: 0
					};
				}).filter(i => !!i)
			});
		}

		// Recent
		jumpList.push({
			type: 'recent' // this enables to show files in the "recent" category
		});

		try {
			app.setJumpList(jumpList);
		} catch (error) {
			this.logService.log('#setJumpList', error); // since setJumpList is relatively new API, make sure to guard for errors
		}
	}

	public quit(): void {

		// If the user selected to exit from an extension development host window, do not quit, but just
		// close the window unless this is the last window that is opened.
		const vscodeWindow = this.getFocusedWindow();
		if (vscodeWindow && vscodeWindow.isExtensionDevelopmentHost && this.getWindowCount() > 1) {
			vscodeWindow.win.close();
		}

		// Otherwise: normal quit
		else {
			setTimeout(() => {
				app.quit();
			}, 10 /* delay to unwind callback stack (IPC) */);
		}
	}
}


text:
{{/* Get album folder or default to `gallery/`. */}}
{{ $album := "" }}
{{ with .Get "album" }}{{ $album = . }}{{else}}{{ $album = "gallery" }}{{end}}

{{/* Set image path and page bundle that images are associated with. */}}
{{ $album_path := "" }}
{{ $resource_page := "" }}
{{ if eq .Page.Parent.Type "widget_page" }}
  {{ $album_path = printf "%s/%s/*" (path.Base (path.Split .Page.Path).Dir) $album }}
  {{ $resource_page = $.Page.Parent }}
{{ else }}
  {{ $album_path = printf "%s/*" $album }}
  {{ $resource_page = $.Page }}
{{ end }}

  {{/* Attempt to automatically load gallery images from page bundle */}}
  {{ $images := ($resource_page.Resources.ByType "image").Match $album_path }}
  {{ with $images }}
  {{ range $images }}
    {{ $image := .Resize "x190" }}
    {{/* Check if the user set a caption for this image */}}
    {{ $filename := path.Base .Name }}
    {{ $caption := "" }}
    {{ if $.Page.Params.gallery_item }}
      {{ range (where (where $.Page.Params.gallery_item "album" $album) "image" $filename) }}
        {{ $caption = .caption }}
      {{ end }}
    {{ end }}

      {{/* Width & height (or low res src) required for lazy loading. */}}

  {{end}}

  {{else}}
  {{/* Load gallery images from the `static/media/` media library or internet */}}

  {{ if $.Page.Params.gallery_item }}
  {{ range (where $.Page.Params.gallery_item "album" $album) }}
  {{/* Set image path. */}}
  {{ $.Scratch.Set "src" .image }}
  {{ if gt (len .image) 4 }}
    {{ if ne "http" (slicestr .image 0 4) }}
      {{ $media_dir := site.Params.media_dir | default "media" }}
      {{ $.Scratch.Set "src" (printf "%s/%s" $media_dir .image | relURL) }}
    {{ end }}
  {{ end }}
  {{/* Don't lazy load image as cannot init image size from non-Hugo asset, resulting in inaccurate anchor scrolling & active link highlighting. */}}

  {{end}}
  {{else}}
    {{ errorf "Unable to load gallery in %s." .Page.File.Filename }}
  {{end}}
  {{end}}

redpajama_set_name: RedPajamaGithub


text:
module joCurvelet2D_etc
    using JOLI: jo_convert, joLinearFunctionException
    function apply_fdct2Dwrap_real(v::Vector{vdt},n1::Integer,n2::Integer,m::Int128,rdt::DataType,nbs::Integer,nbac::Integer,actl::Integer,rctl::Integer,zfin::Integer) where vdt<:Union{AbstractFloat,Complex}
        C=Vector{Cdouble}(undef,m)
        eltype(v)<:Real || throw(joLinearFunctionException("joCurvelt2D: input vector must be real for real transform"))
        X=jo_convert(Cdouble,v,false)
        ccall((:jl_fdct_wrapping_real,:libdfdct_wrapping),Nothing,
            (Cint,Cint,Cint,Cint,Cint,Cint,Cint,Csize_t,Ptr{Array{Cdouble}},Ptr{Array{Cdouble}}),
            n1,n2,nbs,nbac,actl,rctl,zfin,m,X,C)
        C=jo_convert(rdt,C,false)
        return C
    end
    function apply_ifdct2Dwrap_real(v::Vector{vdt},n1::Integer,n2::Integer,m::Int128,rdt::DataType,nbs::Integer,nbac::Integer,actl::Integer,rctl::Integer,zfin::Integer) where vdt<:Union{AbstractFloat,Complex}
        X=Vector{Cdouble}(undef,n1*n2)
        eltype(v)<:Real || throw(joLinearFunctionException("joCurvelt2D: input vector must be real for real transform"))
        C=jo_convert(Cdouble,v,false)
        ccall((:jl_ifdct_wrapping_real,:libdfdct_wrapping),Nothing,
            (Cint,Cint,Cint,Cint,Cint,Cint,Cint,Csize_t,Ptr{Array{Cdouble}},Ptr{Array{Cdouble}}),
            n1,n2,nbs,nbac,actl,rctl,zfin,m,C,X)
        X=jo_convert(rdt,X,false)
        return X
    end
    function apply_fdct2Dwrap_cplx(v::Vector{vdt},n1::Integer,n2::Integer,m::Int128,rdt::DataType,nbs::Integer,nbac::Integer,actl::Integer,rctl::Integer,zfin::Integer) where vdt<:Union{AbstractFloat,Complex}
        C=Vector{Complex{Cdouble}}(undef,m)
        X=jo_convert(Complex{Cdouble},v,false)
        ccall((:jl_fdct_wrapping_cpx,:libdfdct_wrapping),Nothing,
            (Cint,Cint,Cint,Cint,Cint,Cint,Cint,Csize_t,Ptr{Array{Complex{Cdouble}}},Ptr{Array{Complex{Cdouble}}}),
            n1,n2,nbs,nbac,actl,rctl,zfin,m,X,C)
        C=jo_convert(rdt,C,false)
        return C
    end
    function apply_ifdct2Dwrap_cplx(v::Vector{vdt},n1::Integer,n2::Integer,m::Int128,rdt::DataType,nbs::Integer,nbac::Integer,actl::Integer,rctl::Integer,zfin::Integer) where vdt<:Union{AbstractFloat,Complex}
        X=Vector{Complex{Cdouble}}(undef,n1*n2)
        C=jo_convert(Complex{Cdouble},v,false)
        ccall((:jl_ifdct_wrapping_cpx,:libdfdct_wrapping),Nothing,
            (Cint,Cint,Cint,Cint,Cint,Cint,Cint,Csize_t,Ptr{Array{Complex{Cdouble}}},Ptr{Array{Complex{Cdouble}}}),
            n1,n2,nbs,nbac,actl,rctl,zfin,m,C,X)
        X=jo_convert(rdt,X,false)
        return X
    end
end
using .joCurvelet2D_etc

export joCurvelet2D
"""
    julia> op = joCurvelet2D(n1,n2;[DDT=joFloat,][RDT=DDT,]
                    [nbscales=...,][nbangles_coarse=...,][all_crvlts=...,]
                    [real_crvlts=...,][zero_finest=...,][name=...])

2D Curvelet transform (wrapping) over fast dimensions

# Signature

    function joCurvelet2D(n1::Integer,n2::Integer;DDT::DataType=joFloat,RDT::DataType=DDT,
            nbscales::Integer=0,
            nbangles_coarse::Integer=16,
            all_crvlts::Bool=false,
            real_crvlts::Bool=true,
            zero_finest::Bool=false,
            name::String="joCurvelt2D")

# Arguments

- `n1`,`n2`: image sizes
- keywords
    - `nbscales`: # of scales (requires #>=default; defaults to max(1,ceil(log2(min(n1,n2))-3)))
    - `nbangles_coarse`: # of angles at coarse scale (requires #%4==0, #>=8; defaults to 16)
    - `all_crvlts`: curvelets at finnest scales (defaults to false)
    - `real_crvlts`: real transform (defaults to true) and requires real input
    - `zero_finest`: zero out finnest scales (defaults to false)
    - `DDT`: domain data type
    - `RDT`: range data type
    - `name`: custom name

# Notes

- if DDT:<Real for complex transform then imaginary part will be neglected for transpose/adjoint
- isadjoint test at larger sizes (above 128) might require reseting tollerance to bigger number.

# Examples

real transform (64-bit)

    joCurvelet2D(32,32)

complex transform (64-bit)

    joCurvelet2D(32,32;real_crvlts=false)

real transform with curevelts at the finnest scales (64-bit)

    joCurvelet2D(32,32;all_crvlts=true)

real transform with zeros at the finnest scales (64-bit)

    joCurvelet2D(32,32;zero_finest=true)

complex transform with real 64-bit input for forward

    joCurvelet2D(32,32;DDT=Float64,real_crvlts=false)

complex transform with just precision specification for curvelets

    joCurvelet2D(32,32;DDT=Float32,RDT=Float64,real_crvlts=false)

complex transform with full type specification for curvelets (same as above)

    joCurvelet2D(32,32;DDT=Float32,RDT=ComplexF64,real_crvlts=false)

"""
function joCurvelet2D(n1::Integer,n2::Integer;DDT::DataType=joFloat,RDT::DataType=DDT,
            nbscales::Integer=0,
            nbangles_coarse::Integer=16,
            all_crvlts::Bool=false,
            real_crvlts::Bool=true,
            zero_finest::Bool=false,
            name::String="joCurvelt2D")

    nbs=convert(Cint,max(1,ceil(log2(min(n1,n2))-3)))
    nbs=convert(Cint,max(nbs,nbscales))
    nbs > 1 || throw(joLinearFunctionException("joCurvelt2D: not enough elements in one of dimensions"))
    if nbscales!=0 && nbs>nbscales
        @warn "Adjusted number of scales to required $nbs"
    end
    nbac=convert(Cint,max(8,nbangles_coarse))
    nbac%4==0 || throw(joLinearFunctionException("joCurvelt2D: nbangles_coarse must be multiple of 4"))
    if nbangles_coarse < 8
        @warn "Adjusted number of coarse angles to required $nbac"
    end
    actl=convert(Cint,all_crvlts)
    rctl=convert(Cint,real_crvlts)
    zfin=convert(Cint,zero_finest)
    if real_crvlts
        dtp=DDT
        rtp=RDT
        apply_fdct2Dwrap=joCurvelet2D_etc.apply_fdct2Dwrap_real
        apply_ifdct2Dwrap=joCurvelet2D_etc.apply_ifdct2Dwrap_real
        myname=name*"_wrapReal"
    else
        dtp=DDT
        rtp= RDT<:Complex ? RDT : Complex{RDT}
        apply_fdct2Dwrap=joCurvelet2D_etc.apply_fdct2Dwrap_cplx
        apply_ifdct2Dwrap=joCurvelet2D_etc.apply_ifdct2Dwrap_cplx
        myname=name*"_wrapCplx"
    end
    cfmap_size=ccall((:jl_fdct_sizes_map_size,:libdfdct_wrapping),Cint,
        (Cint,Cint,Cint),nbs,nbac,all_crvlts)
    cfmap=Vector{Cint}(undef,cfmap_size)
    m=Ref{Csize_t}(0)
    ccall((:jl_fdct_sizes,:libdfdct_wrapping),Nothing,
        (Cint,Cint,Cint,Cint,Cint,Ptr{Array{Cint}},Ref{Csize_t}),
        nbs,nbac,actl,n1,n2,cfmap,m)
    m=convert(Int128,m[])

    return joLinearFunction_A(m,n1*n2,
        v1->apply_fdct2Dwrap(v1,n1,n2,m,rtp,nbs,nbac,actl,rctl,zfin),
        v2->apply_ifdct2Dwrap(v2,n1,n2,m,dtp,nbs,nbac,actl,rctl,zfin),
        v3->apply_ifdct2Dwrap(v3,n1,n2,m,dtp,nbs,nbac,actl,rctl,zfin),
        v4->apply_fdct2Dwrap(v4,n1,n2,m,rtp,nbs,nbac,actl,rctl,zfin),
        dtp,rtp;
        name=myname
        )
end


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="x-ua-compatible" content="IE=edge"/>
<title>Test results - Class org.grails.cli.profile.commands.CommandRegistrySpec</title>
<link href="../css/base-style.css" rel="stylesheet" type="text/css"/>
<link href="../css/style.css" rel="stylesheet" type="text/css"/>

Class org.grails.cli.profile.commands.CommandRegistrySpec

all >
org.grails.cli.profile.commands > CommandRegistrySpec

1

tests

0

failures

0

ignored

0.008s

duration

100%

successful

Tests

Tests

Test
Duration
Result

Test that the command registry returns commands
0.008s
passed

Generated by
Gradle 2.1 at Nov 28, 2014 9:13:20 AM


text:
* {
	background-repeat: no-repeat;
	margin: 0;
	padding: 0;
}

body,h1,h2,h3,h4,h5,h6,a,button,input,select,option,textarea,th,td {
	color: #333;
	font: 12px/1.6em "Lucida Grande", "DejaVu Sans", "Bitstream Vera Sans",
		Verdana, Arial, sans-serif;
}

body {
	padding: 30px;
	text-align: center;
}

a,button {
	cursor: pointer;
}

input,select,textarea {
	border: 1px solid #c0c0c0;
	padding: 2px;
}

input[readonly=readonly] {
	border-color: #f0f0f0;
}

button {
	background-color: #e6e6e6;
	background-repeat: no-repeat;
	background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff),
		color-stop(25%, #ffffff), to(#e6e6e6));
	background-image: -webkit-linear-gradient(#ffffff, #ffffff 25%, #e6e6e6);
	background-image: -moz-linear-gradient(top, #ffffff, #ffffff 25%, #e6e6e6);
	background-image: -ms-linear-gradient(#ffffff, #ffffff 25%, #e6e6e6);
	background-image: -o-linear-gradient(#ffffff, #ffffff 25%, #e6e6e6);
	background-image: linear-gradient(#ffffff, #ffffff 25%, #e6e6e6);
	filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff',
		endColorstr='#e6e6e6', GradientType=0);
	border: 1px solid #ccc;
	border-bottom-color: #bbb;
	-moz-border-radius: 4px;
	-webkit-border-radius: 4px;
	-khtml-border-radius: 4px;
	border-radius: 4px;
	-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px
		rgba(0, 0, 0, 0.05);
	-moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px
		rgba(0, 0, 0, 0.05);
	box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px
		rgba(0, 0, 0, 0.05);
	color: #333;
	cursor: pointer;
	display: inline-block;
	padding: 4px 7px 5px;
	overflow: visible;
	text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
	-webkit-transition: 0.1s linear background-image;
	-moz-transition: 0.1s linear background-image;
	-ms-transition: 0.1s linear background-image;
	-o-transition: 0.1s linear background-image;
	transition: 0.1s linear background-image;
}

button span {
	background-position: 0 50%;
	display: block;
	padding-left: 21px;
}

button[type=submit],button.primary {
	background-color: #0064cd;
	background-repeat: repeat-x;
	background-image: -khtml-gradient(linear, left top, left bottom, from(#049cdb),
		to(#0064cd));
	background-image: -moz-linear-gradient(top, #049cdb, #0064cd);
	background-image: -ms-linear-gradient(top, #049cdb, #0064cd);
	background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #049cdb),
		color-stop(100%, #0064cd));
	background-image: -webkit-linear-gradient(top, #049cdb, #0064cd);
	background-image: -o-linear-gradient(top, #049cdb, #0064cd);
	background-image: linear-gradient(top, #049cdb, #0064cd);
	border-color: #0064cd #0064cd #003f81;
	border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
	color: #ffffff;
	filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#049cdb',
		endColorstr='#0064cd', GradientType=0);
	text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
}

button.success {
	background-color: #57a957;
	background-repeat: repeat-x;
	background-image: -khtml-gradient(linear, left top, left bottom, from(#62c462),
		to(#57a957));
	background-image: -moz-linear-gradient(top, #62c462, #57a957);
	background-image: -ms-linear-gradient(top, #62c462, #57a957);
	background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #62c462),
		color-stop(100%, #57a957));
	background-image: -webkit-linear-gradient(top, #62c462, #57a957);
	background-image: -o-linear-gradient(top, #62c462, #57a957);
	background-image: linear-gradient(top, #62c462, #57a957);
	border-color: #57a957 #57a957 #3d773d;
	border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
	filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#62c462',
		endColorstr='#57a957', GradientType=0);
	color: #ffffff;
	text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
}

button.warn {
	background-color: #c43c35;
	background-repeat: repeat-x;
	background-image: -khtml-gradient(linear, left top, left bottom, from(#ee5f5b),
		to(#c43c35));
	background-image: -moz-linear-gradient(top, #ee5f5b, #c43c35);
	background-image: -ms-linear-gradient(top, #ee5f5b, #c43c35);
	background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ee5f5b),
		color-stop(100%, #c43c35));
	background-image: -webkit-linear-gradient(top, #ee5f5b, #c43c35);
	background-image: -o-linear-gradient(top, #ee5f5b, #c43c35);
	background-image: linear-gradient(top, #ee5f5b, #c43c35);
	border-color: #c43c35 #c43c35 #882a25;
	border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
	color: #ffffff;
	filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ee5f5b',
		endColorstr='#c43c35', GradientType=0);
	text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
}

a {
	text-decoration: none;
}

pre {
	color: #333;
	text-align: left;
}

abbr {
	cursor: help;
}

ul {
	list-style: none;
}

dd ,.cdd{
	padding: 2px 0px 2px 0px;
}

.cdd{
	float: left;
}

.clearfix:after {
	clear: both;
	content: ".";
	display: block;
	font-size: 0;
	height: 0;
	visibility: hidden;
}

.clearfix {
	display: block;
}

.loader {
	background-image: url( ../../img/loader.gif ) !important;
}

.loader-light {
	background-image: url( ../../img/loader-light.gif ) !important;
}

#wrapper {
	position: relative;
	margin: 0 auto;
	margin-bottom: 30px;
	text-align: left;
}

#header {
	padding-bottom: 10px;
	position: fixed;
	z-index: 42;
}

#header #solr {
	background-image: url( ../../img/solr.png );
	display: block;
	height: 78px;
	width: 150px;
}

#header #solr span {
	display: none;
}

#main {
	min-width: 750px;
	position: relative;
}

#main.error {
	border: 0;
	min-height: 0;
	padding-top: 20px;
}

#main.error .message {
	background-color: #f00;
	background-image: url( ../../img/ico/construction.png );
	background-position: 10px 50%;
	color: #fff;
	font-weight: bold;
	margin-left: 150px;
	margin-bottom: 20px;
	padding: 10px;
	padding-left: 35px;
}

#main.error .code {
	border: 1px solid #c0c0c0;
	padding: 5px;
}

#meta {
	position: absolute;
	bottom: -26px;
	right: 0;
}

#meta li {
	float: left;
}

#meta li a {
	background-position: 10px 50%;
	display: block;
	height: 25px;
	line-height: 25px;
	padding-left: 31px;
	padding-right: 10px;
}

#meta li a:hover {
	background-color: #f0f0f0;
}

#meta .documentation a {
	background-image: url( ../../img/ico/document-text.png );
}

#meta .issues a {
	background-image: url( ../../img/ico/bug.png );
}

#meta .irc a {
	background-image: url( ../../img/ico/users.png );
}

#meta .mailinglist a {
	background-image: url( ../../img/ico/mail.png );
}

#meta .wiki-query-syntax a {
	background-image: url( ../../img/ico/script-code.png );
}

#environment {
	background-image: url( ../../img/ico/box.png );
	background-position: 5px 50%;
	display: none;
	font-weight: bold;
	margin-top: 10px;
	padding: 5px 10px;
	padding-left: 26px;
}

.has-environment #environment {
	display: block;
}

#environment.prod {
	background-color: #c37f7f;
	color: #fff;
}

#environment.test {
	background-color: #f5f5b2;
}

#environment.dev {
	background-color: #cce7cc;
}

#init-failures {
	border: 1px solid #f00;
	display: none;
	margin-left: 150px;
	margin-bottom: 20px;
}

#init-failures h2,#init-failures ul,#init-failures p {
	padding: 10px;
}

#init-failures h2 {
	background-color: #f00;
	color: #fff;
	font-weight: bold;
}

#init-failures p {
	color: #c0c0c0;
	padding-top: 0;
}

#content-wrapper {
	margin-left: 150px;
	border: 1px solid #c0c0c0;
	min-height: 500px;
}

#content {
	float: none;
	/*padding: 10px;*/
}

#content>.loader {
	background-position: 0 50%;
	padding-left: 21px;
}

#content iframe {
	border: 0;
	display: block;
	min-height: 400px;
	width: 100%;
}

#content .block {
	margin-bottom: 10px;
}

#content .block h2 {
	background-color: #fafafa;
	background-position: 5px 50%;
	border-bottom: 1px solid #f0f0f0;
	font-weight: bold;
	padding: 5px;
	padding-left: 26px;
}

#content .block.disabled,#content .block.disabled h2 {
	color: #c0c0c0;
}

#content .block .message,#content .block .content {
	padding: 5px;
}

#content .block .message {
	display: none;
}

/* syntax */
pre.syntax {
	overflow: auto;
}

pre.syntax code {
	display: block;
	color: #000;
}

pre.syntax .comment,pre.syntax .template_comment,pre.syntax .diff .header,pre.syntax .javadoc
	{
	color: #998;
	font-style: italic;
}

pre.syntax .keyword,pre.syntax .css .rule .keyword,pre.syntax .winutils,pre.syntax .javascript .title,pre.syntax .lisp .title,pre.syntax .subst
	{
	color: #000;
	font-weight: bold;
}

pre.syntax .number,pre.syntax .hexcolor {
	color: #40a070;
}

pre.syntax.language-json .number {
	color: blue;
}

pre.syntax.language-json .literal {
	color: firebrick;
}

pre.syntax .string,pre.syntax .tag .value,pre.syntax .phpdoc,pre.syntax .tex .formula
	{
	color: #d14;
}

pre.syntax.language-json .string {
	color: green;
}

pre.syntax .title,pre.syntax .id {
	color: #900;
	font-weight: bold;
}

pre.syntax .javascript .title,pre.syntax .lisp .title,pre.syntax .subst
	{
	font-weight: normal;
}

pre.syntax .class .title,pre.syntax .tex .command {
	color: #458;
	font-weight: bold;
}

pre.syntax .tag,pre.syntax .css .keyword,pre.syntax .html .keyword,pre.syntax .tag .title,pre.syntax .django .tag .keyword
	{
	color: #000080;
	font-weight: normal;
}

pre.syntax .attribute,pre.syntax .variable,pre.syntax .instancevar,pre.syntax .lisp .body
	{
	color: #008080;
}

pre.syntax.language-json .attribute {
	color: black;
	font-weight: bold;
}

pre.syntax .regexp {
	color: #009926;
}

pre.syntax .class {
	color: #458;
	font-weight: bold;
}

pre.syntax .symbol,pre.syntax .ruby .symbol .string,pre.syntax .ruby .symbol .keyword,pre.syntax .ruby .symbol .keymethods,pre.syntax .lisp .keyword,pre.syntax .tex .special
	{
	color: #990073;
}

pre.syntax .builtin,pre.syntax .built_in,pre.syntax .lisp .title {
	color: #0086b3;
}

pre.syntax .preprocessor,pre.syntax .pi,pre.syntax .doctype,pre.syntax .shebang,pre.syntax .cdata
	{
	color: #999;
	font-weight: bold;
}

pre.syntax .deletion {
	background: #fdd;
}

pre.syntax .addition {
	background: #dfd;
}

pre.syntax .diff .change {
	background: #0086b3;
}

pre.syntax .chunk {
	color: #aaa;
}

pre.syntax .tex .formula {
	opacity: 0.5;
}

#content .tree li,#content .tree ins {
	background-color: transparent;
	background-image: url( ../../img/tree.png );
	background-repeat: no-repeat;
}

#content .tree li {
	background-position: -54px 0;
	background-repeat: repeat-y;
	line-height: 22px;
}

#content .tree li.jstree-last {
	background: transparent;
}

#content .tree .jstree-open>ins {
	background-position: -36px 0;
}

#content .tree .jstree-closed>ins {
	background-position: -18px 0;
}

#content .tree .jstree-leaf>ins {
	background-position: 0 0;
}

#content .tree .jstree-hovered {
	background: #e7f4f9;
	border: 1px solid #d8f0fa;
	padding: 0 2px 0 1px;
}

#content .tree .jstree-clicked {
	background: #beebff;
	border: 1px solid #99defd;
	padding: 0 2px 0 1px;
}

#content .tree a.active {
	background-color: #f0f0f0;
	color: #00f;
}

#content .tree a .jstree-icon {
	background-image: url( ../../img/ico/folder.png );
}

#content .tree .jstree-leaf a .jstree-icon {
	background-image: url( ../../img/ico/document-text.png );
}

#content .tree .jstree-search {
	font-style: italic;
}

#content .tree a.jstree-search {
	color: aqua;
}

#connection_status {
	display: none;
	padding: 30px;
}

#connection_status span {
	background-image: url( ../../img/ico/network-status-busy.png );
	background-position: 0 50%;
	color: #800;
	padding-left: 26px;
}

#connection_status.online span,#connection_status.online span a {
	color: #080;
}

#connection_status.online span {
	background-image: url( ../../img/ico/network-status.png );
}

#connection_status.online span a {
	text-decoration: underline;
}

#connection_status.online span a:hover {
	text-decoration: none;
}

#content .address-bar {
	margin-bottom: 10px;
	background-image: url( ../../img/ico/ui-address-bar.png );
	background-position: 5px 50%;
	border: 1px solid #f0f0f0;
	box-shadow: 1px 1px 0 #f0f0f0;
	-moz-box-shadow: 1px 1px 0 #f0f0f0;
	-webkit-box-shadow: 1px 1px 0 #f0f0f0;
	color: #c0c0c0;
	display: block;
	overflow: hidden;
	padding: 5px;
	padding-left: 26px;
	white-space: nowrap;
}

#content .address-bar:focus,#content .address-bar:hover {
	border-color: #c0c0c0;
	box-shadow: 1px 1px 0 #d8d8d8;
	-moz-box-shadow: 1px 1px 0 #d8d8d8;
	-webkit-box-shadow: 1px 1px 0 #d8d8d8;
	color: #333;
}

.type_or_name{
	float: left; padding: 3px;
}

#content .content input.number {
	width: 60px;
}

#content .content input.text {
	width: 250px;
}
#content .content dd span {
	width: 110px;
	display: block;
	float: left;
	text-align: right;
}
#content .content textarea {
	width: 99%;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;

namespace CollisisionEditor2
{
 /*   class DesignerItemAdorner : Adorner
    {
        private VisualCollection visuals;
        private DesignerItemAdornerChrome chrome;

        protected override int VisualChildrenCount
        {
            get
            {
                return this.visuals.Count;
            }
        }

        public DesignerItemAdorner(ContentControl designerItem)
            : base(designerItem)
        {
            this.chrome = new DesignerItemAdornerChrome();
            this.chrome.DataContext = designerItem;
            this.visuals = new VisualCollection(this);
        }

        protected override Size ArrangeOverride(Size arrangeBounds)
        {
            this.chrome.Arrange(new Rect(arrangeBounds));
            return arrangeBounds;
        }

        protected override Visual GetVisualChild(int index)
        {
            return this.visuals[index];
        }
    } */
}


text:
require 'chef-dk/command/base'
require 'mixlib/shellout'

module ChefDK
  module Command
    class Exec < ChefDK::Command::Base
      banner "Usage: chef exec SYSTEM_COMMAND"

      def run(params)
        # Set ENV directly on the "parent" process (us) before running #exec to
        # ensure the custom PATH is honored when finding the command to exec
        omnibus_env.each {|var, value| ENV[var] = value }
        exec(*params)
        raise "Exec failed without an exception, your ruby is buggy"  # should never get here
      end

      def needs_version?(params)
        # Force version to get passed down to command
        false
      end

      def needs_help?(params)
        ['-h', '--help'].include? params[0]
      end
    end
  end
end


text:
/**
 * @tagName tagValue
 */


text:
using System;
using System.Collections.Generic;
using LanguageExt.ClassInstances;
using LanguageExt.TypeClasses;
using static LanguageExt.TypeClass;
using static LanguageExt.Prelude;

namespace LanguageExt
{
    ///
    /// <para>
    /// To create a vector clock, start from `Empty` or `Single` and `Insert`
    /// elements into it.  As a shortcut, `fromList` just inserts all the
    /// elements in a list, in order.
    /// </para>
    ///
    ///     var vc = VectorClock<char>.Empty;
    ///     vc = vc.Insert('a', 1);
    ///     vc = vc.Insert('b', 2);
    ///     vc == VectorClock<char>.fromList(Seq(('a', 1), ('b', 2)))
    ///
    /// <para>
    /// Note that, for different keys, the order of insertion does not
    /// matter:
    /// </para>
    ///
    ///     fromList(Seq(('a', 1), ('b', 2)) == fromList(Seq(('b', 2), ('a', 1))
    ///
    /// <para>
    /// Once you have a given vector clock, you can 'lookup' its fields,
    /// check that keys are 'member's, or convert it back 'toList' form.
    /// </para>
    ///
    ///     vc.Lookup('a') == Some(1)
    ///     vc.Lookup('c') == None
    ///
    /// <para>
    /// The main operations that you would do with a vector clock are to
    /// increment the entry corresponding to the current process and to
    /// update the process's vector clock with the 'max' of its and the
    /// received message's clocks.
    /// </para>
    ///
    ///     vc.Inc('a') == Some [('a', 2), ('b', 2)]
    ///     VectorClock.max( [('a', 1), ('b', 2)], [('c', 3), ('b', 1)] ) == [('a', 1), ('b', 2), ('c' 3)]
    ///
    /// <para>
    /// Finally, upon receiving different messages, you may wish to
    /// discover the relationship, if any, between them.  This
    /// information could be useful in determining the correct order to
    /// process the messages.
    /// </para>
    ///
    ///     VectorClock.relation (fromList [('a', 1), ('b', 2)], fromList [('a', 2), ('b', 2)]) == Causes
    ///     VectorClock.relation (fromList [('a', 2), ('b', 2)], fromList [('a', 1), ('b', 2)]) == CausedBy
    ///     VectorClock.relation (fromList [('a', 2), ('b', 2)], fromList [('a', 1), ('b', 3)]) == Concurrent
    ///
    /// <para>
    /// A vector clock is, conceptually, an associative list sorted by the
    /// value of the key, where each key appears only once.
    /// </para>
    ///
    public record VectorClock(Seq<(A, long)> Entries)
        where A : IComparable
    {
        public static readonly VectorClock Empty = new(Seq<(A, long)>());

        public virtual bool Equals(VectorClock? rhs) =>
            rhs is not null &&
            GetHashCode() == rhs.GetHashCode() &&
            Count == rhs.Count &&
            Entries.Zip(rhs.Entries).ForAll(p => TypeClass.equals<OrdDefault, A>(p.Left.Item1, p.Right.Item1)) &&
            Entries.Zip(rhs.Entries).ForAll(p => p.Left.Item2 == p.Right.Item2);

        public override int GetHashCode() =>
            Entries.GetHashCode();

        ///
        /// A vector clock with a single element
        ///
        public static VectorClock Single(A x, long y) =>
            fromList(Seq1((x, y)));

        ///
        /// Insert each entry in the list one at a time.
        ///
        public static VectorClock fromList(Seq<(A x, long y)> list) =>
            list.Fold(Empty, (vc, pair) => vc.Insert(pair.x, pair.y));

        ///
        /// All the entries in the vector clock.  Note that this is /not/ the inverse of 'fromList'
        ///
        public Seq<(A x, long y)> ToSeq() =>
            Entries;

        ///
        /// Is the vector clock empty?
        ///
        public bool IsEmpty =>
            Entries.IsEmpty;

        ///
        /// The number of entries in the vector clock.
        ///
        public int Count =>
            Entries.Count;

        ///
        /// Lookup the value for a key in the vector clock and remove the corresponding entry
        ///
        public (Option<long> Value, VectorClock Clock) Extract(A index)
        {
            Option<long> value = default;
            return (value, new VectorClock(go(Entries).ToSeq()));

            IEnumerable<(A x, long y)> go(Seq<(A x, long y)> zs)
            {
                foreach (var z in zs)
                {
                    if (equals<OrdDefault, A>(z.x, index))
                    {
                        value = z.y;
                    }
                    else
                    {
                        yield return z;
                    }
                }
            }
        }

        ///
        /// Lookup the value for a key in the vector clock.
        ///
        public Option<long> Lookup(A index)
        {
            foreach (var z in Entries)
            {
                if (equals<OrdDefault, A>(z.Item1, index)) return z.Item2;
            }

            return None;
        }

        ///
        /// Is a member?
        ///
        public bool Contains(A index) =>
            Lookup(index).IsSome;

        ///
        /// Delete
        ///
        public VectorClock Remove(A index) =>
            new VectorClock(Entries.Filter(e => !equals<OrdDefault, A>(e.Item1, index)).ToSeq());

        ///
        /// Insert or replace the entry for a key.
        ///
        public VectorClock Insert(A index, long value)
        {
            return new VectorClock(go(Entries));

            Seq<(A, long)> go(Seq<(A, long)> entries) =>
                entries.IsEmpty
                    ? Seq1((index, value))
                    : entries.Head switch
                      {
                          (var x1, _) xy when lessThan<OrdDefault, A>(x1, index) => xy.Cons(go(entries.Tail)),
                          (var x1, _) xy when equals<OrdDefault, A>(x1, index)   => (index, value).Cons(entries.Tail),
                          var xy                                                    => (index, value).Cons(xy.Cons(entries.Tail)),
                      };
        }

        ///
        /// Increment the entry for a key by 1
        ///
        public Option<VectorClock> Inc(A index) =>
            Lookup(index).Map(y => Insert(index, y + 1));

        ///
        /// Increment the entry for a key by 1
        ///
        public VectorClock Inc(A index, long defaultValue) =>
            Lookup(index).Case switch
            {
                long y => Insert(index, y + 1),
                _      => Insert(index, defaultValue + 1)
            };

        ///
        /// Combine two vector clocks entry-by-entry
        ///
        /// <param name="f">a function that takes the /key/, the value of the entry in
        /// the left hand vector clock, if it exists, the value in the
        /// right hand vector clock, if it exists, and, if it wishes to
        /// keep a value for this /key/ in the resulting vector clock,
        /// returns it.</param>
        /// <param name="vc1">the left hand vector clock</param>
        /// <param name="vc2">he right hand vector clock</param>
        /// <returns></returns>
        public static VectorClock combine(
            Func<A, Option<long>, Option<long>, Option<long>> f,
            VectorClock vc1,
            VectorClock vc2)
        {
            return new VectorClock(go(vc1.Entries, vc2.Entries).Somes());

            Seq<Option<(A, long)>> go(Seq<(A, long)> es1, Seq<(A, long)> es2) =>
                (es1.IsEmpty, es2.IsEmpty) switch
                {
                    (true,  _) => es2.Map(xy => mk(xy.Item1, f(xy.Item1, None, Some(xy.Item2)))),
                    (_,  true) => es1.Map(xy => mk(xy.Item1, f(xy.Item1, Some(xy.Item2), None))),
                    _          => compare<OrdDefault, A>(es1.Head.Item1, es2.Head.Item1) switch
                                  {
                                      var c when c < 0  => mk(es1.Head.Item1, f(es1.Head.Item1, Some(es1.Head.Item2), None)).Cons(go(es1.Tail, es2)),
                                      var c when c == 0 => mk(es1.Head.Item1, f(es1.Head.Item1, Some(es1.Head.Item2), Some(es2.Head.Item2))).Cons(go(es1.Tail, es2.Tail)),
                                      _                 => mk(es2.Head.Item1, f(es2.Head.Item1, None, Some(es2.Head.Item2))).Cons(go(es1, es2.Tail)),
                                  }
                };

            static Option<(A, long)> mk(A x, Option<long> v) =>
                v.Map(y => (x, y));
        }

        ///
        /// The maximum of the two vector clocks.
        ///
        public VectorClock Max(VectorClock vc2) =>
            max(this, vc2);

        ///
        /// The maximum of the two vector clocks.
        ///
        public static VectorClock max(VectorClock vc1, VectorClock vc2)
        {
            return combine(maxEntry, vc1, vc2);

            static Option<long> maxEntry(A _, Option<long> ea, Option<long> eb) =>
                (ea.Case, eb.Case) switch
                {
                    (null, null)     => None,
                    (long x, null)   => Some(x),
                    (null, long y)   => Some(y),
                    (long x, long y) => Some(Math.Max(x, y)),
                    _                => None
                };
        }

        ///
        /// The relation between the two vector clocks.
        ///
        public Relation Relation(VectorClock vc2) =>
            relation(this, vc2);

        ///
        /// The relation between the two vector clocks.
        ///
        public static Relation relation(VectorClock vc1, VectorClock vc2)
        {
            return go(vc1.Entries, vc2.Entries);

            static Relation go(Seq<(A, long)> es1, Seq<(A, long)> es2) =>
                (es1.IsEmpty, es2.IsEmpty) switch
                {
                    (false, false) => TypeClass.equals<OrdDefault, A>(es1.Head.Item1, es2.Head.Item1)
                                          ? es1.Head.Item2 == es2.Head.Item2
                                                ? go(es1.Tail, es2.Tail)
                                                : es1.Head.Item2 < es2.Head.Item2
                                                    ? checkCauses(es1.Tail, es2.Tail) ? LanguageExt.Relation.Causes : LanguageExt.Relation.Concurrent
                                                    : checkCauses(es2.Tail, es1.Tail)
                                                        ? LanguageExt.Relation.CausedBy
                                                        : LanguageExt.Relation.Concurrent
                                          : TypeClass.lessThan<OrdDefault, A>(es1.Head.Item1, es2.Head.Item1)
                                              ? checkCauses(es2, es1.Tail) ? LanguageExt.Relation.CausedBy : LanguageExt.Relation.Concurrent
                                              : TypeClass.greaterThan<OrdDefault, A>(es1.Head.Item1, es2.Head.Item1)
                                                  ? checkCauses(es1, es2.Tail) ? LanguageExt.Relation.Causes : LanguageExt.Relation.Concurrent
                                                  : LanguageExt.Relation.Concurrent,
                    (true, _) => LanguageExt.Relation.Causes,
                    (_, true) => LanguageExt.Relation.CausedBy,
                };

            static bool checkCauses(Seq<(A, long)> es1, Seq<(A, long)> es2) =>
                (es1.IsEmpty, es2.IsEmpty) switch
                {
                    (false, false) => TypeClass.equals<OrdDefault, A>(es1.Head.Item1, es2.Head.Item1)
                                          ? es1.Head.Item2 <= es2.Head.Item2 && checkCauses(es1.Tail, es2.Tail)
                                          : !TypeClass.lessThan<OrdDefault, A>(es1.Head.Item1, es2.Head.Item1) && checkCauses(es1, es2.Tail),
                    (true, _) => true,
                    _         => false
                };
        }

        ///
        /// Short-hand for relation(vc1, vc2) == Relation.Causes
        ///
        public bool Causes(VectorClock vc2) =>
            causes(this, vc2);

        ///
        /// Short-hand for relation(vc1, vc2) == Relation.Causes
        ///
        public static bool causes(VectorClock vc1, VectorClock vc2) =>
            relation(vc1, vc2) == LanguageExt.Relation.Causes;

        ///
        /// If vc2 causes vc1, compute the smallest vc3
        ///
        /// <remarks>Note that the /first/ parameter is the newer vector clock.</remarks>
        public Option<VectorClock> Diff(VectorClock vc2) =>
            diff(this, vc2);

        ///
        /// If vc2 causes vc1, compute the smallest vc3
        ///
        /// <remarks>Note that the /first/ parameter is the newer vector clock.</remarks>
        public static Option<VectorClock> diff(VectorClock vc1, VectorClock vc2)
        {
            return vc1 == vc2
                       ? Some(Empty)
                       : causes(vc2, vc1)
                           ? Some(combine(diffOne, vc1, vc2))
                           : None;

            static Option<long> diffOne(A _, Option<long> ox, Option<long> oy) =>
                (ox.Case, oy.Case) switch
                {
                    (null, null)     => None,
                    (long x, null)   => Some(x),
                    (null, long y)   => throw new InvalidOperationException("diff broken"),
                    (long x, long y) => x == y ? None : Some(x),
                    _                => None
                };
        }

        bool? valid;
        public bool Valid
        {
            get
            {
                if (valid.HasValue) return valid.Value;
                var keys     = Entries.Map(e => e.Item1);
                var sorted   = keys.Sort<OrdDefault, A>() == keys;
                var distinct = Entries.Distinct<EqTuple2<OrdDefault, TLong, A, long>, (A, long)>().Count == Entries.Count;
                valid = sorted && distinct;
                return valid.Value;
            }
        }
    }
}
#nullable disable


text:
DEBUG=false

ORIGIN_STR=
TARGET_STR=
TARGET_DIR=$(pwd)

#====================================

DEBUG() {
    if $DEBUG; then
        $@
    fi
}

function Help() {
cat <<EOF

--------------------------------------------------------------------------------
USAGE:
dir_string_replace.sh [-p path] origin_string target_string

OPTIONS:
-p: path. default is current dir.

DESCRIPTION:
replace origin_string with target_string on all files under given path.
--------------------------------------------------------------------------------

EOF
}

#process options
function ProcessOptions() {
    while getopts ":hp:" opt; do
        DEBUG echo "opt: $opt"
        case "$opt" in
            "h")
                Help
                exit 0
                ;;
            "p")
                TARGET_DIR=$OPTARG
                ;;
            "?")
                #Unknown option
                echo "* unknown option: $opt"
                Help
                exit 1
                ;;
            ":")
                #an option needs a value, which, however, is not presented
                echo "* option -$opt needs a value, but it is not presented"
                Help
                exit 1
                ;;
            *)
                #unknown error, should not occur
                echo "* unknown error while processing options and params"
                Help
                exit 1
                ;;
        esac
    done
    return $OPTIND
}

#process args
function ProcessArgs() {
    DEBUG echo "args: $@"
    if [ $# -eq 0 ]; then
        Help
    fi

    local i=0
    for arg in $@; do
        [ $i -eq 0 ] && ORIGIN_STR=$arg
        [ $i -eq 1 ] && TARGET_STR=$arg
        let i++
    done
}

#====================================

ProcessOptions "$@"
arg_start=$?
ProcessArgs "${@:$arg_start}"

DEBUG echo "origin string: $ORIGIN_STR"
DEBUG echo "target string: $TARGET_STR"
DEBUG echo "target path: $TARGET_DIR"

if [ ! -d "$TARGET_DIR" ]; then
    echo "target dir not exits: $TARGET_DIR"
    exit 2
fi

if [ "$ORIGIN_STR" == "" -o "TARGET_STR" == "" ]; then
    echo "need two strings: origin string and target string"
    exit 3
fi

echo
grep -rs --color "$ORIGIN_STR"

if [ $? -ne 0 ]; then
    echo "find no \"$ORIGIN_STR\" under \"$TARGET_DIR\""
    echo
    exit 4
fi

echo
read -p "replace with \"$TARGET_STR\" ? (Y/n): "
if [[ ( "$REPLY" == "n" ) || ( "$REPLY" == "N" ) ]]; then
    exit 0
else
    grep -rls "$ORIGIN_STR" | xargs -i sed -i "s/$ORIGIN_STR/$TARGET_STR/" "{}"
fi


text:
//
//  TableViewHeader.m
//  AllScrollViewDemo
//
//  Created by ciyouzen on 8/26/15.
//  Copyright (c) 2015 dvlproad. All rights reserved.
//

#import "TableViewHeader.h"

@implementation TableViewHeader

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end


text:
require 'json'
require 'uri'
class ScatterPlotChart

  attr_accessor :experiment, :x_axis, :y_axis,
                :x_axis_label, :y_axis_label,
                :x_axis_type, :y_axis_type,
                :chart_data, :linear_regression_data,
                :type_of_x, :type_of_y,
                :categories_for_x, :categories_for_y,
                :x_axis_notation, :y_axis_notation

  include URI::Escape

  def initialize(experiment, x_axis, y_axis, type_of_x, type_of_y, additional=nil)
    @experiment = experiment
    @x_axis = URI.escape(x_axis)
    @y_axis = URI.escape(y_axis)
    @type_of_x = URI.escape(type_of_x)
    @type_of_y = URI.escape(type_of_y)
    @x_axis_label = experiment.input_parameter_label_for(x_axis) || x_axis
    @y_axis_label = experiment.input_parameter_label_for(y_axis) || y_axis
    @categories_for_x  = []
    @categories_for_y  = []
    additional ||= {}

    @x_axis_type = additional[:x_axis_type]
    @y_axis_type = additional[:y_axis_type]
    unescaped_x_notation = additional[:x_axis_notation]
    if unescaped_x_notation !=nil then @x_axis_notation = URI.escape(unescaped_x_notation) else @x_axis_notation= additional[:x_axis_notation] end
    unescaped_y_notation = additional[:y_axis_notation]
    if unescaped_y_notation !=nil then @y_axis_notation = URI.escape(unescaped_y_notation) else @y_axis_notation= additional[:y_axis_notation] end
  end

  def prepare_chart_data
    scatter_plot_csv = @experiment.create_scatter_plot_csv_for(@x_axis, @y_axis)
    @chart_data = Hash.new

    array_for_single_x = array_of_categories_for_axis(0)
    array_for_single_y = array_of_categories_for_axis(1)

    column_x_idx, column_y_idx, simulation_ind_idx = -1, -1, -1
    CSV.parse(scatter_plot_csv) do |row|
      if column_x_idx < 0
        column_x_idx = row.index(@x_axis)
        column_y_idx = row.index(@y_axis)
        simulation_ind_idx = row.index('simulation_run_ind')
      else
        if type_of_x == "string" && type_of_y == "string"
          if @chart_data.has_key? array_for_single_x.index(row[column_x_idx])
            @chart_data[array_for_single_x.index(row[column_x_idx])] << [array_for_single_y.index(row[column_y_idx]), row[simulation_ind_idx]]
          else
            @chart_data[array_for_single_x.index(row[column_x_idx])] = [[array_for_single_y.index(row[column_y_idx]), row[simulation_ind_idx]]]
          end
        elsif type_of_x == "string"
          if @chart_data.has_key? array_for_single_x.index(row[column_x_idx])
              @chart_data[array_for_single_x.index(row[column_x_idx])] << [row[column_y_idx], row[simulation_ind_idx]]
          else
              @chart_data[array_for_single_x.index(row[column_x_idx])] = [[row[column_y_idx], row[simulation_ind_idx]]]
          end
        elsif type_of_y == "string"
          if @chart_data.has_key? row[column_x_idx]
            @chart_data[row[column_x_idx]] << [array_for_single_y.index(row[column_y_idx]), row[simulation_ind_idx]]
          else
            @chart_data[row[column_x_idx]] = [[array_for_single_y.index(row[column_y_idx]), row[simulation_ind_idx]]]
          end
        else
          if @chart_data.has_key? row[column_x_idx]
            @chart_data[row[column_x_idx]] << [row[column_y_idx], row[simulation_ind_idx]]
          else
              @chart_data[row[column_x_idx]] = [[row[column_y_idx], row[simulation_ind_idx]]]
          end
        end
      end
    end

    if (type_of_x != "string" && type_of_y != "string")
      x_values = []
      y_values = []
      @chart_data.each do |x_value, y_values_simulation_ids|
        y_values_simulation_ids.each do |y_value, simulation_id|
          if type_of_x == 'string'
            x_values.push(x_value)
          else
            x_values.push(x_value.to_f)
          end

          if type_of_y == 'string'
            y_values.push(y_value)
          else
            y_values.push(y_value.to_f)
          end
        end
      end

      rinruby = RinRuby.new(false)
      rinruby.x_values = x_values
      rinruby.y_values = y_values
      rinruby.eval("res = lm(y_values~x_values)
                b = coef(res)[1]
                a = coef(res)[2]")
      sorted_array = x_values.sort()
      x_min, x_max = sorted_array[0], sorted_array[sorted_array.length-1]
      a = rinruby.pull("a").to_f
      b = rinruby.pull("b").to_f
      rinruby.quit
      x1, y1 = x_min, a*x_min+b
      x2, y2 = x_max, a*x_max+b

      @linear_regression_data = [[x1, y1],[x2, y2]]
    end

    if type_of_x == "string"
      @categories_for_x = array_for_single_x
    end

    if type_of_y == "string"
      @categories_for_y = array_for_single_y
    end

  end

  def linear_regression_possible?
    @linear_regression_data.flatten.all? { |item| !item.nan? }
  end

  def array_of_categories_for_axis(number_of_column)
    scatter_plot_csv = @experiment.create_scatter_plot_csv_for(@x_axis, @y_axis)
    array = scatter_plot_csv.split("\n")
    array.delete_at(0)
    array.each_with_index { |item, index |
      array[index] = item.split(",")
    }
    array = array.map {|row| row[number_of_column]}
    array = array.sort.uniq
    return array
  end

end


text:
import { createAction } from 'redux-actions';

import types from '../constants/ActionTypes';
import ModalTypes from '../constants/ModalTypes';

const cancelReservationEdit = createAction(types.UI.CANCEL_RESERVATION_EDIT);

const cancelReservationEditInInfoModal = createAction(
  types.UI.CANCEL_RESERVATION_EDIT_IN_INFO_MODAL,
);

const changeAdminReservationFilters = createAction(types.UI.CHANGE_ADMIN_RESERVATIONS_FILTERS);

const changeAdminResourcesPageDate = createAction(types.UI.CHANGE_ADMIN_RESOURCES_PAGE_DATE);

const changeSearchFilters = createAction(types.UI.CHANGE_SEARCH_FILTERS);

const clearReservations = createAction(types.UI.CLEAR_RESERVATIONS);

const closeConfirmReservationModal = createAction(
  types.UI.CLOSE_MODAL,
  () => ModalTypes.RESERVATION_CONFIRM,
);

const closeReservationCancelModal = createAction(
  types.UI.CLOSE_MODAL,
  () => ModalTypes.RESERVATION_CANCEL,
);

const closeReservationCommentModal = createAction(
  types.UI.CLOSE_MODAL,
  () => ModalTypes.RESERVATION_COMMENT,
);

const closeReservationSuccessModal = createAction(
  types.UI.CLOSE_MODAL,
  () => ModalTypes.RESERVATION_SUCCESS,
);

const closeResourceTermsModal = createAction(types.UI.CLOSE_MODAL, () => ModalTypes.RESOURCE_TERMS);

const disableGeoposition = createAction(types.UI.DISABLE_GEOPOSITION);
const disableTimeRange = createAction(types.UI.DISABLE_TIME_RANGE);
const enableGeopositionRequest = createAction(types.UI.ENABLE_GEOPOSITION_REQUEST);
const enableGeopositionSuccess = createAction(types.UI.ENABLE_GEOPOSITION_SUCCESS);
const enableGeopositionError = createAction(types.UI.ENABLE_GEOPOSITION_ERROR);

const enableGeoposition = () => (dispatch) => {
  dispatch(enableGeopositionRequest());
  if (!navigator.geolocation) {
    dispatch(enableGeopositionError());
  }
  navigator.geolocation.getCurrentPosition(
    position => dispatch(enableGeopositionSuccess(position)),
    error => dispatch(enableGeopositionError(error)),
  );
};

const enableTimeRange = createAction(types.UI.ENABLE_TIME_RANGE);

const selectAdminResourceType = createAction(types.UI.SELECT_ADMIN_RESOURCE_TYPE);

const hideReservationInfoModal = createAction(types.UI.HIDE_RESERVATION_INFO_MODAL);

const openConfirmReservationModal = createAction(
  types.UI.OPEN_MODAL,
  () => ModalTypes.RESERVATION_CONFIRM,
);

const openReservationCancelModal = createAction(
  types.UI.OPEN_MODAL,
  () => ModalTypes.RESERVATION_CANCEL,
);

const openReservationCommentModal = createAction(
  types.UI.OPEN_MODAL,
  () => ModalTypes.RESERVATION_COMMENT,
);

const selectReservationToCancel = createAction(types.UI.SELECT_RESERVATION_TO_CANCEL);

const selectReservationToEdit = createAction(types.UI.SELECT_RESERVATION_TO_EDIT);

const selectReservationToShow = createAction(types.UI.SELECT_RESERVATION_TO_SHOW);

const openResourceTermsModal = createAction(types.UI.OPEN_MODAL, () => ModalTypes.RESOURCE_TERMS);

const showReservationInfoModal = createAction(types.UI.SHOW_RESERVATION_INFO_MODAL);

const startReservationEditInInfoModal = createAction(types.UI.START_RESERVATION_EDIT_IN_INFO_MODAL);

const setSelectedTimeSlots = createAction(types.UI.SET_SELECTED_TIME_SLOTS);

const toggleResourceMap = createAction(types.UI.TOGGLE_RESOURCE_SHOW_MAP);

const unselectAdminResourceType = createAction(types.UI.UNSELECT_ADMIN_RESOURCE_TYPE);

const myPremisesSetSelectedTimeSlots = createAction(types.UI.MY_PREMISES_SET_SELECTED_TIME_SLOTS);

const changeFontSize = createAction(types.UI.CHANGE_FONTSIZE, fontsize => fontsize);

const toggleContrast = createAction(types.UI.TOGGLE_HIGH_CONTRAST);

const setAccessibilityPreferences = createAction(types.UI.SET_ACCESSIBILITY_PREFERENCES);

export {
  cancelReservationEdit,
  cancelReservationEditInInfoModal,
  changeAdminReservationFilters,
  changeAdminResourcesPageDate,
  changeSearchFilters,
  clearReservations,
  closeConfirmReservationModal,
  closeReservationCancelModal,
  closeReservationCommentModal,
  closeReservationSuccessModal,
  closeResourceTermsModal,
  disableGeoposition,
  disableTimeRange,
  enableGeoposition,
  enableTimeRange,
  selectAdminResourceType,
  hideReservationInfoModal,
  openConfirmReservationModal,
  openReservationCancelModal,
  openReservationCommentModal,
  openResourceTermsModal,
  selectReservationToCancel,
  selectReservationToEdit,
  selectReservationToShow,
  showReservationInfoModal,
  startReservationEditInInfoModal,
  toggleResourceMap,
  unselectAdminResourceType,
  setSelectedTimeSlots,
  myPremisesSetSelectedTimeSlots,
  changeFontSize,
  toggleContrast,
  setAccessibilityPreferences,
};