text:
import 'vs/css!./media/editordroptarget';
import { DataTransfers } from 'vs/base/browser/dnd';
import { addDisposableListener, DragAndDropObserver, EventHelper, EventType, isAncestor } from 'vs/base/browser/dom';
import { renderFormattedText } from 'vs/base/browser/formattedTextRenderer';
import { RunOnceScheduler } from 'vs/base/common/async';
import { toDisposable } from 'vs/base/common/lifecycle';
import { isMacintosh, isWeb } from 'vs/base/common/platform';
import { assertAllDefined, assertIsDefined } from 'vs/base/common/types';
import { localize } from 'vs/nls';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { Registry } from 'vs/platform/registry/common/platform';
import { activeContrastBorder } from 'vs/platform/theme/common/colorRegistry';
import { IThemeService, Themable } from 'vs/platform/theme/common/themeService';
import { isTemporaryWorkspace, IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { CodeDataTransfers, containsDragType, Extensions as DragAndDropExtensions, IDragAndDropContributionRegistry } from 'vs/platform/dnd/browser/dnd';
import { DraggedEditorGroupIdentifier, DraggedEditorIdentifier, DraggedTreeItemsIdentifier, extractTreeDropData, LocalSelectionTransfer, ResourcesDropHandler } from 'vs/workbench/browser/dnd';
import { fillActiveEditorViewState, IEditorGroupsAccessor, IEditorGroupView } from 'vs/workbench/browser/parts/editor/editor';
import { EditorInputCapabilities, IEditorIdentifier, IUntypedEditorInput } from 'vs/workbench/common/editor';
import { EDITOR_DRAG_AND_DROP_BACKGROUND, EDITOR_DROP_INTO_PROMPT_BACKGROUND, EDITOR_DROP_INTO_PROMPT_BORDER, EDITOR_DROP_INTO_PROMPT_FOREGROUND } from 'vs/workbench/common/theme';
import { GroupDirection, IEditorGroupsService, IMergeGroupOptions, MergeGroupMode } from 'vs/workbench/services/editor/common/editorGroupsService';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { ITreeViewsService } from 'vs/workbench/services/views/browser/treeViewsService';

interface IDropOperation {
	splitDirection?: GroupDirection;
}

function isDropIntoEditorEnabledGlobally(configurationService: IConfigurationService) {
	return configurationService.getValue<boolean>('editor.dropIntoEditor.enabled');
}

function isDragIntoEditorEvent(e: DragEvent): boolean {
	return e.shiftKey;
}

class DropOverlay extends Themable {

	private static readonly OVERLAY_ID = 'monaco-workbench-editor-drop-overlay';

	private container: HTMLElement | undefined;
	private overlay: HTMLElement | undefined;
	private dropIntoPromptElement?: HTMLSpanElement;

	private currentDropOperation: IDropOperation | undefined;

	private _disposed: boolean | undefined;
	get disposed(): boolean { return !!this._disposed; }

	private cleanupOverlayScheduler: RunOnceScheduler;

	private readonly editorTransfer = LocalSelectionTransfer.getInstance<DraggedEditorIdentifier>();
	private readonly groupTransfer = LocalSelectionTransfer.getInstance<DraggedEditorGroupIdentifier>();
	private readonly treeItemsTransfer = LocalSelectionTransfer.getInstance<DraggedTreeItemsIdentifier>();

	private readonly enableDropIntoEditor: boolean;

	constructor(
		private accessor: IEditorGroupsAccessor,
		private groupView: IEditorGroupView,
		@IThemeService themeService: IThemeService,
		@IConfigurationService private readonly configurationService: IConfigurationService,
		@IInstantiationService private readonly instantiationService: IInstantiationService,
		@IEditorService private readonly editorService: IEditorService,
		@IEditorGroupsService private readonly editorGroupService: IEditorGroupsService,
		@ITreeViewsService private readonly treeViewsDragAndDropService: ITreeViewsService,
		@IWorkspaceContextService private readonly contextService: IWorkspaceContextService
	) {
		super(themeService);

		this.cleanupOverlayScheduler = this._register(new RunOnceScheduler(() => this.dispose(), 300));

		this.enableDropIntoEditor = isDropIntoEditorEnabledGlobally(this.configurationService) && this.isDropIntoActiveEditorEnabled();

		this.create();
	}

	private create(): void {
		const overlayOffsetHeight = this.getOverlayOffsetHeight();

		// Container
		const container = this.container = document.createElement('div');
		container.id = DropOverlay.OVERLAY_ID;
		container.style.top = `${overlayOffsetHeight}px`;

		// Parent
		this.groupView.element.appendChild(container);
		this.groupView.element.classList.add('dragged-over');
		this._register(toDisposable(() => {
			this.groupView.element.removeChild(container);
			this.groupView.element.classList.remove('dragged-over');
		}));

		// Overlay
		this.overlay = document.createElement('div');
		this.overlay.classList.add('editor-group-overlay-indicator');
		container.appendChild(this.overlay);

		if (this.enableDropIntoEditor) {
			this.dropIntoPromptElement = renderFormattedText(localize('dropIntoEditorPrompt', "Hold __{0}__ to drop into editor", isMacintosh ? '⇧' : 'Shift'), {});
			this.dropIntoPromptElement.classList.add('editor-group-overlay-drop-into-prompt');
			this.overlay.appendChild(this.dropIntoPromptElement);
		}

		// Overlay Event Handling
		this.registerListeners(container);

		// Styles
		this.updateStyles();
	}

	protected override updateStyles(): void {
		const overlay = assertIsDefined(this.overlay);

		// Overlay drop background
		overlay.style.backgroundColor = this.getColor(EDITOR_DRAG_AND_DROP_BACKGROUND) || '';

		// Overlay contrast border (if any)
		const activeContrastBorderColor = this.getColor(activeContrastBorder);
		overlay.style.outlineColor = activeContrastBorderColor || '';
		overlay.style.outlineOffset = activeContrastBorderColor ? '-2px' : '';
		overlay.style.outlineStyle = activeContrastBorderColor ? 'dashed' : '';
		overlay.style.outlineWidth = activeContrastBorderColor ? '2px' : '';

		if (this.dropIntoPromptElement) {
			this.dropIntoPromptElement.style.backgroundColor = this.getColor(EDITOR_DROP_INTO_PROMPT_BACKGROUND) ?? '';
			this.dropIntoPromptElement.style.color = this.getColor(EDITOR_DROP_INTO_PROMPT_FOREGROUND) ?? '';

			const borderColor = this.getColor(EDITOR_DROP_INTO_PROMPT_BORDER);
			if (borderColor) {
				this.dropIntoPromptElement.style.borderWidth = '1px';
				this.dropIntoPromptElement.style.borderStyle = 'solid';
				this.dropIntoPromptElement.style.borderColor = borderColor;
			} else {
				this.dropIntoPromptElement.style.borderWidth = '0';
			}
		}
	}

	private registerListeners(container: HTMLElement): void {
		this._register(new DragAndDropObserver(container, {
			onDragEnter: e => undefined,
			onDragOver: e => {
				if (this.enableDropIntoEditor && isDragIntoEditorEvent(e)) {
					this.dispose();
					return;
				}

				const isDraggingGroup = this.groupTransfer.hasData(DraggedEditorGroupIdentifier.prototype);
				const isDraggingEditor = this.editorTransfer.hasData(DraggedEditorIdentifier.prototype);

				// Update the dropEffect to "copy" if there is no local data to be dragged because
				// in that case we can only copy the data into and not move it from its source
				if (!isDraggingEditor && !isDraggingGroup && e.dataTransfer) {
					e.dataTransfer.dropEffect = 'copy';
				}

				// Find out if operation is valid
				let isCopy = true;
				if (isDraggingGroup) {
					isCopy = this.isCopyOperation(e);
				} else if (isDraggingEditor) {
					const data = this.editorTransfer.getData(DraggedEditorIdentifier.prototype);
					if (Array.isArray(data)) {
						isCopy = this.isCopyOperation(e, data[0].identifier);
					}
				}

				if (!isCopy) {
					const sourceGroupView = this.findSourceGroupView();
					if (sourceGroupView === this.groupView) {
						if (isDraggingGroup || (isDraggingEditor && sourceGroupView.count < 2)) {
							this.hideOverlay();
							return; // do not allow to drop group/editor on itself if this results in an empty group
						}
					}
				}

				// Position overlay and conditionally enable or disable
				// editor group splitting support based on setting and
				// keymodifiers used.
				let splitOnDragAndDrop = !!this.editorGroupService.partOptions.splitOnDragAndDrop;
				if (this.isToggleSplitOperation(e)) {
					splitOnDragAndDrop = !splitOnDragAndDrop;
				}
				this.positionOverlay(e.offsetX, e.offsetY, isDraggingGroup, splitOnDragAndDrop);

				// Make sure to stop any running cleanup scheduler to remove the overlay
				if (this.cleanupOverlayScheduler.isScheduled()) {
					this.cleanupOverlayScheduler.cancel();
				}
			},

			onDragLeave: e => this.dispose(),
			onDragEnd: e => this.dispose(),

			onDrop: e => {
				EventHelper.stop(e, true);

				// Dispose overlay
				this.dispose();

				// Handle drop if we have a valid operation
				if (this.currentDropOperation) {
					this.handleDrop(e, this.currentDropOperation.splitDirection);
				}
			}
		}));

		this._register(addDisposableListener(container, EventType.MOUSE_OVER, () => {
			// Under some circumstances we have seen reports where the drop overlay is not being
			// cleaned up and as such the editor area remains under the overlay so that you cannot
			// type into the editor anymore. This seems related to using VMs and DND via host and
			// guest OS, though some users also saw it without VMs.
			// To protect against this issue we always destroy the overlay as soon as we detect a
			// mouse event over it. The delay is used to guarantee we are not interfering with the
			// actual DROP event that can also trigger a mouse over event.
			if (!this.cleanupOverlayScheduler.isScheduled()) {
				this.cleanupOverlayScheduler.schedule();
			}
		}));
	}

	private isDropIntoActiveEditorEnabled(): boolean {
		return !!this.groupView.activeEditor?.hasCapability(EditorInputCapabilities.CanDropIntoEditor);
	}

	private findSourceGroupView(): IEditorGroupView | undefined {

		// Check for group transfer
		if (this.groupTransfer.hasData(DraggedEditorGroupIdentifier.prototype)) {
			const data = this.groupTransfer.getData(DraggedEditorGroupIdentifier.prototype);
			if (Array.isArray(data)) {
				return this.accessor.getGroup(data[0].identifier);
			}
		}

		// Check for editor transfer
		else if (this.editorTransfer.hasData(DraggedEditorIdentifier.prototype)) {
			const data = this.editorTransfer.getData(DraggedEditorIdentifier.prototype);
			if (Array.isArray(data)) {
				return this.accessor.getGroup(data[0].identifier.groupId);
			}
		}

		return undefined;
	}

	private async handleDrop(event: DragEvent, splitDirection?: GroupDirection): Promise<void> {

		// Determine target group
		const ensureTargetGroup = () => {
			let targetGroup: IEditorGroupView;
			if (typeof splitDirection === 'number') {
				targetGroup = this.accessor.addGroup(this.groupView, splitDirection);
			} else {
				targetGroup = this.groupView;
			}

			return targetGroup;
		};

		// Check for group transfer
		if (this.groupTransfer.hasData(DraggedEditorGroupIdentifier.prototype)) {
			const data = this.groupTransfer.getData(DraggedEditorGroupIdentifier.prototype);
			if (Array.isArray(data)) {
				const sourceGroup = this.accessor.getGroup(data[0].identifier);
				if (sourceGroup) {
					if (typeof splitDirection !== 'number' && sourceGroup === this.groupView) {
						return;
					}

					// Split to new group
					let targetGroup: IEditorGroupView | undefined;
					if (typeof splitDirection === 'number') {
						if (this.isCopyOperation(event)) {
							targetGroup = this.accessor.copyGroup(sourceGroup, this.groupView, splitDirection);
						} else {
							targetGroup = this.accessor.moveGroup(sourceGroup, this.groupView, splitDirection);
						}
					}

					// Merge into existing group
					else {
						let mergeGroupOptions: IMergeGroupOptions | undefined = undefined;
						if (this.isCopyOperation(event)) {
							mergeGroupOptions = { mode: MergeGroupMode.COPY_EDITORS };
						}

						this.accessor.mergeGroup(sourceGroup, this.groupView, mergeGroupOptions);
					}

					if (targetGroup) {
						this.accessor.activateGroup(targetGroup);
					}
				}

				this.groupTransfer.clearData(DraggedEditorGroupIdentifier.prototype);
			}
		}

		// Check for editor transfer
		else if (this.editorTransfer.hasData(DraggedEditorIdentifier.prototype)) {
			const data = this.editorTransfer.getData(DraggedEditorIdentifier.prototype);
			if (Array.isArray(data)) {
				const draggedEditor = data[0].identifier;
				const targetGroup = ensureTargetGroup();

				const sourceGroup = this.accessor.getGroup(draggedEditor.groupId);
				if (sourceGroup) {
					if (sourceGroup === targetGroup) {
						return;
					}

					// Open in target group
					const options = fillActiveEditorViewState(sourceGroup, draggedEditor.editor, {
						pinned: true,										// always pin dropped editor
						sticky: sourceGroup.isSticky(draggedEditor.editor),	// preserve sticky state
					});

					const copyEditor = this.isCopyOperation(event, draggedEditor);
					if (!copyEditor) {
						sourceGroup.moveEditor(draggedEditor.editor, targetGroup, options);
					} else {
						sourceGroup.copyEditor(draggedEditor.editor, targetGroup, options);
					}

					// Ensure target has focus
					targetGroup.focus();
				}

				this.editorTransfer.clearData(DraggedEditorIdentifier.prototype);
			}
		}

		// Check for tree items
		else if (this.treeItemsTransfer.hasData(DraggedTreeItemsIdentifier.prototype)) {
			const data = this.treeItemsTransfer.getData(DraggedTreeItemsIdentifier.prototype);
			if (Array.isArray(data)) {
				const editors: IUntypedEditorInput[] = [];
				for (const id of data) {
					const dataTransferItem = await this.treeViewsDragAndDropService.removeDragOperationTransfer(id.identifier);
					if (dataTransferItem) {
						const treeDropData = await extractTreeDropData(dataTransferItem);
						editors.push(...treeDropData.map(editor => ({ ...editor, options: { ...editor.options, pinned: true } })));
					}
				}
				if (editors.length) {
					this.editorService.openEditors(editors, ensureTargetGroup(), { validateTrust: true });
				}
			}

			this.treeItemsTransfer.clearData(DraggedTreeItemsIdentifier.prototype);
		}

		// Check for URI transfer
		else {
			const dropHandler = this.instantiationService.createInstance(ResourcesDropHandler, { allowWorkspaceOpen: !isWeb || isTemporaryWorkspace(this.contextService.getWorkspace()) });
			dropHandler.handleDrop(event, () => ensureTargetGroup(), targetGroup => targetGroup?.focus());
		}
	}

	private isCopyOperation(e: DragEvent, draggedEditor?: IEditorIdentifier): boolean {
		if (draggedEditor?.editor.hasCapability(EditorInputCapabilities.Singleton)) {
			return false; // Singleton editors cannot be split
		}

		return (e.ctrlKey && !isMacintosh) || (e.altKey && isMacintosh);
	}

	private isToggleSplitOperation(e: DragEvent): boolean {
		return (e.altKey && !isMacintosh) || (e.shiftKey && isMacintosh);
	}

	private positionOverlay(mousePosX: number, mousePosY: number, isDraggingGroup: boolean, enableSplitting: boolean): void {
		const preferSplitVertically = this.accessor.partOptions.openSideBySideDirection === 'right';

		const editorControlWidth = this.groupView.element.clientWidth;
		const editorControlHeight = this.groupView.element.clientHeight - this.getOverlayOffsetHeight();

		let edgeWidthThresholdFactor: number;
		let edgeHeightThresholdFactor: number;
		if (enableSplitting) {
			if (isDraggingGroup) {
				edgeWidthThresholdFactor = preferSplitVertically ? 0.3 : 0.1; // give larger threshold when dragging group depending on preferred split direction
			} else {
				edgeWidthThresholdFactor = 0.1; // 10% threshold to split if dragging editors
			}

			if (isDraggingGroup) {
				edgeHeightThresholdFactor = preferSplitVertically ? 0.1 : 0.3; // give larger threshold when dragging group depending on preferred split direction
			} else {
				edgeHeightThresholdFactor = 0.1; // 10% threshold to split if dragging editors
			}
		} else {
			edgeWidthThresholdFactor = 0;
			edgeHeightThresholdFactor = 0;
		}

		const edgeWidthThreshold = editorControlWidth * edgeWidthThresholdFactor;
		const edgeHeightThreshold = editorControlHeight * edgeHeightThresholdFactor;

		const splitWidthThreshold = editorControlWidth / 3;		// offer to split left/right at 33%
		const splitHeightThreshold = editorControlHeight / 3;	// offer to split up/down at 33%

		// No split if mouse is above certain threshold in the center of the view
		let splitDirection: GroupDirection | undefined;
		if (
			mousePosX > edgeWidthThreshold && mousePosX < editorControlWidth - edgeWidthThreshold &&
			mousePosY > edgeHeightThreshold && mousePosY < editorControlHeight - edgeHeightThreshold
		) {
			splitDirection = undefined;
		}

		// Offer to split otherwise
		else {

			// User prefers to split vertically: offer a larger hitzone
			// for this direction like so:
			// ----------------------------------------------
			// |		|		SPLIT UP		|			|
			// | SPLIT 	|-----------------------|	SPLIT	|
			// |		|		  MERGE			|			|
			// | LEFT	|-----------------------|	RIGHT	|
			// |		|		SPLIT DOWN		|			|
			// ----------------------------------------------
			if (preferSplitVertically) {
				if (mousePosX < splitWidthThreshold) {
					splitDirection = GroupDirection.LEFT;
				} else if (mousePosX > splitWidthThreshold * 2) {
					splitDirection = GroupDirection.RIGHT;
				} else if (mousePosY < editorControlHeight / 2) {
					splitDirection = GroupDirection.UP;
				} else {
					splitDirection = GroupDirection.DOWN;
				}
			}

			// User prefers to split horizontally: offer a larger hitzone
			// for this direction like so:
			// ----------------------------------------------
			// |				SPLIT UP					|
			// |--------------------------------------------|
			// |  SPLIT LEFT  |	   MERGE	|  SPLIT RIGHT  |
			// |--------------------------------------------|
			// |				SPLIT DOWN					|
			// ----------------------------------------------
			else {
				if (mousePosY < splitHeightThreshold) {
					splitDirection = GroupDirection.UP;
				} else if (mousePosY > splitHeightThreshold * 2) {
					splitDirection = GroupDirection.DOWN;
				} else if (mousePosX < editorControlWidth / 2) {
					splitDirection = GroupDirection.LEFT;
				} else {
					splitDirection = GroupDirection.RIGHT;
				}
			}
		}

		// Draw overlay based on split direction
		switch (splitDirection) {
			case GroupDirection.UP:
				this.doPositionOverlay({ top: '0', left: '0', width: '100%', height: '50%' });
				this.toggleDropIntoPrompt(false);
				break;
			case GroupDirection.DOWN:
				this.doPositionOverlay({ top: '50%', left: '0', width: '100%', height: '50%' });
				this.toggleDropIntoPrompt(false);
				break;
			case GroupDirection.LEFT:
				this.doPositionOverlay({ top: '0', left: '0', width: '50%', height: '100%' });
				this.toggleDropIntoPrompt(false);
				break;
			case GroupDirection.RIGHT:
				this.doPositionOverlay({ top: '0', left: '50%', width: '50%', height: '100%' });
				this.toggleDropIntoPrompt(false);
				break;
			default:
				this.doPositionOverlay({ top: '0', left: '0', width: '100%', height: '100%' });
				this.toggleDropIntoPrompt(true);
		}

		// Make sure the overlay is visible now
		const overlay = assertIsDefined(this.overlay);
		overlay.style.opacity = '1';

		// Enable transition after a timeout to prevent initial animation
		setTimeout(() => overlay.classList.add('overlay-move-transition'), 0);

		// Remember as current split direction
		this.currentDropOperation = { splitDirection };
	}

	private doPositionOverlay(options: { top: string; left: string; width: string; height: string }): void {
		const [container, overlay] = assertAllDefined(this.container, this.overlay);

		// Container
		const offsetHeight = this.getOverlayOffsetHeight();
		if (offsetHeight) {
			container.style.height = `calc(100% - ${offsetHeight}px)`;
		} else {
			container.style.height = '100%';
		}

		// Overlay
		overlay.style.top = options.top;
		overlay.style.left = options.left;
		overlay.style.width = options.width;
		overlay.style.height = options.height;
	}

	private getOverlayOffsetHeight(): number {

		// With tabs and opened editors: use the area below tabs as drop target
		if (!this.groupView.isEmpty && this.accessor.partOptions.showTabs) {
			return this.groupView.titleHeight.offset;
		}

		// Without tabs or empty group: use entire editor area as drop target
		return 0;
	}

	private hideOverlay(): void {
		const overlay = assertIsDefined(this.overlay);

		// Reset overlay
		this.doPositionOverlay({ top: '0', left: '0', width: '100%', height: '100%' });
		overlay.style.opacity = '0';
		overlay.classList.remove('overlay-move-transition');

		// Reset current operation
		this.currentDropOperation = undefined;
	}

	private toggleDropIntoPrompt(showing: boolean) {
		if (!this.dropIntoPromptElement) {
			return;
		}
		this.dropIntoPromptElement.style.opacity = showing ? '1' : '0';
	}

	contains(element: HTMLElement): boolean {
		return element === this.container || element === this.overlay;
	}

	override dispose(): void {
		super.dispose();

		this._disposed = true;
	}
}

export interface IEditorDropTargetDelegate {

	/**
	 * A helper to figure out if the drop target contains the provided group.
	 */
	containsGroup?(groupView: IEditorGroupView): boolean;
}

export class EditorDropTarget extends Themable {

	private _overlay?: DropOverlay;

	private counter = 0;

	private readonly editorTransfer = LocalSelectionTransfer.getInstance<DraggedEditorIdentifier>();
	private readonly groupTransfer = LocalSelectionTransfer.getInstance<DraggedEditorGroupIdentifier>();

	constructor(
		private accessor: IEditorGroupsAccessor,
		private container: HTMLElement,
		private readonly delegate: IEditorDropTargetDelegate,
		@IThemeService themeService: IThemeService,
		@IConfigurationService private readonly configurationService: IConfigurationService,
		@IInstantiationService private readonly instantiationService: IInstantiationService
	) {
		super(themeService);

		this.registerListeners();
	}

	private get overlay(): DropOverlay | undefined {
		if (this._overlay && !this._overlay.disposed) {
			return this._overlay;
		}

		return undefined;
	}

	private registerListeners(): void {
		this._register(addDisposableListener(this.container, EventType.DRAG_ENTER, e => this.onDragEnter(e)));
		this._register(addDisposableListener(this.container, EventType.DRAG_LEAVE, () => this.onDragLeave()));
		this._register(addDisposableListener(this.container, EventType.DRAG_OVER, e => {
			if (!this.overlay) {
				this.onDragEnter(e);
			}
		}));
		[this.container, window].forEach(node => this._register(addDisposableListener(node as HTMLElement, EventType.DRAG_END, () => this.onDragEnd())));
	}

	private onDragEnter(event: DragEvent): void {
		if (isDropIntoEditorEnabledGlobally(this.configurationService) && isDragIntoEditorEvent(event)) {
			return;
		}

		this.counter++;

		// Validate transfer
		if (
			!this.editorTransfer.hasData(DraggedEditorIdentifier.prototype) &&
			!this.groupTransfer.hasData(DraggedEditorGroupIdentifier.prototype) &&
			event.dataTransfer
		) {
			const dndContributions = Registry.as<IDragAndDropContributionRegistry>(DragAndDropExtensions.DragAndDropContribution).getAll();
			const dndContributionKeys = Array.from(dndContributions).map(e => e.dataFormatKey);
			if (!containsDragType(event, DataTransfers.FILES, CodeDataTransfers.FILES, DataTransfers.RESOURCES, CodeDataTransfers.EDITORS, ...dndContributionKeys)) { // see https://github.com/microsoft/vscode/issues/25789
				event.dataTransfer.dropEffect = 'none';
				return; // unsupported transfer
			}
		}

		// Signal DND start
		this.updateContainer(true);

		const target = event.target as HTMLElement;
		if (target) {

			// Somehow we managed to move the mouse quickly out of the current overlay, so destroy it
			if (this.overlay && !this.overlay.contains(target)) {
				this.disposeOverlay();
			}

			// Create overlay over target
			if (!this.overlay) {
				const targetGroupView = this.findTargetGroupView(target);
				if (targetGroupView) {
					this._overlay = this.instantiationService.createInstance(DropOverlay, this.accessor, targetGroupView);
				}
			}
		}
	}

	private onDragLeave(): void {
		this.counter--;

		if (this.counter === 0) {
			this.updateContainer(false);
		}
	}

	private onDragEnd(): void {
		this.counter = 0;

		this.updateContainer(false);
		this.disposeOverlay();
	}

	private findTargetGroupView(child: HTMLElement): IEditorGroupView | undefined {
		const groups = this.accessor.groups;

		return groups.find(groupView => isAncestor(child, groupView.element) || this.delegate.containsGroup?.(groupView));
	}

	private updateContainer(isDraggedOver: boolean): void {
		this.container.classList.toggle('dragged-over', isDraggedOver);
	}

	override dispose(): void {
		super.dispose();

		this.disposeOverlay();
	}

	private disposeOverlay(): void {
		if (this.overlay) {
			this.overlay.dispose();
			this._overlay = undefined;
		}
	}
}


text:
<?php

$conf = include '../config.php';

$directory = 'img/background/';

$scanned_directory = array_diff(scandir('../' . $directory), array('..', '.'));
$key = array_rand($scanned_directory);

echo $conf['uri'] . '/' . $directory . $scanned_directory[$key];

redpajama_set_name: RedPajamaGithub


text:
<?php declare(strict_types=1);

namespace Smsapi\Client\CommandBus\Command\Sms;

use Smsapi\Client\Message\TextMessage;
use WyriHaximus\Tactician\CommandHandler\Annotations\Handler;

/**
 * @Handler("Smsapi\Client\CommandBus\Handler\Sms\SendGroupSmsHandler")
 */
final class SendGroupSmsCommand
{
    /**
     * @var string
     */
    private $group;

    /**
     * @var TextMessage
     */
    private $message;

    /**
     * @var array
     */
    private $additionalOptions;

    /**
     * @param string $group
     * @param array  $additionalOptions
     */
    public function __construct(string $group, TextMessage $message, array $additionalOptions = [])
    {
        $this->group = $group;
        $this->message = $message;
        $this->additionalOptions = $additionalOptions;
    }

    /**
     * @return string
     */
    public function getGroup(): string
    {
        return $this->group;
    }

    /**
     * @return TextMessage
     */
    public function getMessage(): TextMessage
    {
        return $this->message;
    }

    /**
     * @return array
     */
    public function getAdditionalOptions(): array
    {
        return $this->additionalOptions;
    }
}


text:
package org.elasticsearch.search.aggregations.bucket.sampler;

import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.search.aggregations.AggregationStreams;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.InternalAggregations;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator;

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

/**
 *
 */
public class UnmappedSampler extends InternalSampler {

    public static final Type TYPE = new Type("sampler", "umsampler");

    public static final AggregationStreams.Stream STREAM = new AggregationStreams.Stream() {
        @Override
        public UnmappedSampler readResult(StreamInput in) throws IOException {
            UnmappedSampler sampler = new UnmappedSampler();
            sampler.readFrom(in);
            return sampler;
        }
    };

    public static void registerStreams() {
        AggregationStreams.registerStream(STREAM, TYPE.stream());
    }

    UnmappedSampler() {
    }

    public UnmappedSampler(String name, List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData) {
        super(name, 0, InternalAggregations.EMPTY, pipelineAggregators, metaData);
    }

    @Override
    public Type type() {
        return TYPE;
    }

    @Override
    public InternalAggregation doReduce(List<InternalAggregation> aggregations, ReduceContext reduceContext) {
        for (InternalAggregation agg : aggregations) {
            if (!(agg instanceof UnmappedSampler)) {
                return agg.reduce(aggregations, reduceContext);
            }
        }
        return this;
    }

    @Override
    public XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
        builder.field(InternalAggregation.CommonFields.DOC_COUNT, 0);
        return builder;
    }

}


text:
<?php

namespace Kassko\DataMapper\Annotation;

/**
* Property annotations to be used in Column annotation or Entity annotation.
*
* A property used in Entity annotation works for all properties.
* A property used in Column annotation only works for the annotated property.
* If a property used in both, the Column annotation is priority.
*
* @author kko
*/
trait SourceCommonTrait
{
    use MethodTrait;

    /**
     * @var string
     */
    public $id;

    /**
     * Loading strategy to use for this provider.
     *
     * @var bool
     */
    public $lazyLoading = false;

    /**
     * How so data contains data for one or severals fields.
     *
     * @var bool
     */
    public $supplySeveralFields = false;

    /**
     * Ids of sources which provide an intermediate value for a field.
     *
     * @var array
     */
    public $depends = [];

    /**
     * @var string
     *
     * @Enum({"checkReturnValue", "checkException"})
     */
    public $onFail = 'checkReturnValue';

    /**
     * @var string
     */
    public $exceptionClass = '\Exception';

    /**
     * @var string
     *
     * @Enum({"null", "false", "emptyString", "emptyArray"})
     */
    public $badReturnValue = 'null';

    /**
     * @var string
     */
    public $fallbackSourceId;

    /**
     * @var \Kassko\DataMapper\Annotation\Method
     */
    public $preprocessor = null;

    /**
     * @var \Kassko\DataMapper\Annotation\Method
     */
    public $processor = null;

    /**
     * @var \Kassko\DataMapper\Annotation\Methods
     */
    public $preprocessors = [];

    /**
     * @var \Kassko\DataMapper\Annotation\Methods
     */
    public $processors = [];
}


text: output.value = $.create($.selection.attr($.attribute))


text:
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;

namespace Kliva.Helpers
{
    public static class DateTimeFormatHelper
    {
        /// <summary>
        /// An hour defined in minutes.
        /// </summary>
        private const double Hour = 60.0;

        /// <summary>
        /// A day defined in minutes.
        /// </summary>
        private const double Day = 24 * Hour;

        /// <summary>
        /// Format pattern for single-character meridiem designators.
        /// e.g. 4:30p
        /// </summary>
        private const string SingleMeridiemDesignator = "t";

        /// <summary>
        /// Format pattern for double-character meridiem designators.
        /// e.g. 4:30 p.m.
        /// </summary>
        private const string DoubleMeridiemDesignator = "tt";

        /// <summary>
        /// Date and time information used when getting the super short time
        /// pattern. Syncs with the current culture.
        /// </summary>
        private static DateTimeFormatInfo formatInfo_GetSuperShortTime = null;

        /// <summary>
        /// Date and time information used when getting the month and day
        /// pattern. Syncs with the current culture.
        /// </summary>
        private static DateTimeFormatInfo formatInfo_GetMonthAndDay = null;

        /// <summary>
        /// Date and time information used when getting the short time
        /// pattern. Syncs with the current culture.
        /// </summary>
        private static DateTimeFormatInfo formatInfo_GetShortTime = null;

        /// <summary>
        /// Lock object used to delimit a critical region when getting
        /// the super short time pattern.
        /// </summary>
        private static Object lock_GetSuperShortTime = new Object();

        /// <summary>
        /// Lock object used to delimit a critical region when getting
        /// the month and day pattern.
        /// </summary>
        private static Object lock_GetMonthAndDay = new Object();

        /// <summary>
        /// Lock object used to delimit a critical region when getting
        /// the short time pattern.
        /// </summary>
        private static Object lock_GetShortTime = new Object();

        /// <summary>
        /// Regular expression used to get the month and day pattern.
        /// </summary>
        private static readonly Regex rxMonthAndDay = new Regex("(d{1,2}[^A-Za-z]M{1,3})|(M{1,3}[^A-Za-z]d{1,2})");

        /// <summary>
        /// Regular expression used to get the seconds pattern with separator.
        /// </summary>
        private static readonly Regex rxSeconds = new Regex("([^A-Za-z]s{1,2})");

        /// <summary>
        /// Gets the number representing the day of the week from a given
        /// <see cref="T:System.DateTime"/>
        /// object, relative to the first day of the week
        /// according to the current culture.
        /// </summary>
        /// <param name="dt">Date information.</param>
        /// <returns>
        /// A number representing the day of the week.
        /// e.g. if Monday is the first day of the week according to the
        /// relative culture, Monday returns 0, Tuesday returns 1, etc.
        /// </returns>
        public static int GetRelativeDayOfWeek(DateTime dt)
        {
            return ((int)dt.DayOfWeek - (int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek + 7) % 7;
        }

        #region DateTime comparison methods

        /// <summary>
        /// Indicates if a given
        /// <see cref="T:System.DateTime"/>
        /// object represents a future instance when compared to another
        /// <see cref="T:System.DateTime"/>
        /// object.
        /// </summary>
        /// <param name="relative">Relative date and time.</param>
        /// <param name="given">Given date and time.</param>
        /// <returns>
        /// True if given date and time represents a future instance.
        /// </returns>
        public static bool IsFutureDateTime(DateTime relative, DateTime given)
        {
            return relative < given;
        }

        /// <summary>
        /// Indicates if a given
        /// <see cref="T:System.DateTime"/>
        /// object represents a past year when compared to another
        /// <see cref="T:System.DateTime"/>
        /// object.
        /// </summary>
        /// <param name="relative">Relative date and time.</param>
        /// <param name="given">Given date and time.</param>
        /// <returns>
        /// True if given date and time is set to a past year.
        /// </returns>
        public static bool IsAnOlderYear(DateTime relative, DateTime given)
        {
            return relative.Year > given.Year;
        }

        /// <summary>
        /// Indicates if a given
        /// <see cref="T:System.DateTime"/>
        /// object represents a past week when compared to another
        /// <see cref="T:System.DateTime"/>
        /// object.
        /// </summary>
        /// <param name="relative">Relative date and time.</param>
        /// <param name="given">Given date and time.</param>
        /// <returns>
        /// True if given date and time is set to a past week.
        /// </returns>
        public static bool IsAnOlderWeek(DateTime relative, DateTime given)
        {
            if (IsAtLeastOneWeekOld(relative, given))
            {
                return true;
            }
            else
            {
                return GetRelativeDayOfWeek(given) > GetRelativeDayOfWeek(relative);
            }
        }

        /// <summary>
        /// Indicates if a given
        /// <see cref="T:System.DateTime"/>
        /// object is at least one week behind from another
        /// <see cref="T:System.DateTime"/>
        /// object.
        /// </summary>
        /// <param name="relative">Relative date and time.</param>
        /// <param name="given">Given date and time.</param>
        /// <returns>
        /// True if given date and time is at least one week behind.
        /// </returns>
        public static bool IsAtLeastOneWeekOld(DateTime relative, DateTime given)
        {
            return ((int)(relative - given).TotalMinutes >= 7 * Day);
        }

        /// <summary>
        /// Indicates if a given
        /// <see cref="T:System.DateTime"/>
        /// object corresponds to a past day in the same week as another
        /// <see cref="T:System.DateTime"/>
        /// object.
        /// </summary>
        /// <param name="relative">Relative date and time.</param>
        /// <param name="given">Given date and time.</param>
        /// <returns>
        /// True if given date and time is a past day in the relative week.
        /// </returns>
        public static bool IsPastDayOfWeek(DateTime relative, DateTime given)
        {
            return GetRelativeDayOfWeek(relative) > GetRelativeDayOfWeek(given);
        }

        /// <summary>
        /// Indicates if a given
        /// <see cref="T:System.DateTime"/>
        /// object corresponds to a past day in the same week as another
        /// <see cref="T:System.DateTime"/>
        /// object and at least three hours behind it.
        /// </summary>
        /// <param name="relative">Relative date and time.</param>
        /// <param name="given">Given date and time.</param>
        /// <returns>
        /// True if given date and time is a past day in the relative week
        /// and at least three hours behind the relative time.
        /// </returns>
        public static bool IsPastDayOfWeekWithWindow(DateTime relative, DateTime given)
        {
            return IsPastDayOfWeek(relative, given) && ((int)(relative - given).TotalMinutes > 3 * Hour);
        }

        #endregion

        #region Culture awareness methods

        /// <summary>
        /// Identifies if the current culture is set to Japanese.
        /// </summary>
        /// <returns>
        /// True if current culture is set to Japanese.
        /// </returns>
        public static bool IsCurrentCultureJapanese()
        {
            return (CultureInfo.CurrentCulture.Name.StartsWith("ja", StringComparison.OrdinalIgnoreCase));
        }

        /// <summary>
        /// Identifies if the current culture is set to Korean.
        /// </summary>
        /// <returns>
        /// True if current culture is set to Korean.
        /// </returns>
        public static bool IsCurrentCultureKorean()
        {
            return (CultureInfo.CurrentCulture.Name.StartsWith("ko", StringComparison.OrdinalIgnoreCase));
        }

        /// <summary>
        /// Identifies if the current culture is set to Turkish.
        /// </summary>
        /// <returns>
        /// True if current culture is set to Turkish.
        /// </returns>
        public static bool IsCurrentCultureTurkish()
        {
            return (CultureInfo.CurrentCulture.Name.StartsWith("tr", StringComparison.OrdinalIgnoreCase));
        }

        /// <summary>
        /// Identifies if the current culture is set to Hungarian.
        /// </summary>
        /// <returns>
        /// True if current culture is set to Hungarian.
        /// </returns>
        public static bool IsCurrentCultureHungarian()
        {
            return (CultureInfo.CurrentCulture.Name.StartsWith("hu", StringComparison.OrdinalIgnoreCase));
        }

        /// <summary>
        /// Identifies if the current UI culture is set to French.
        /// </summary>
        /// <returns>
        /// True if current UI culture is set to French.
        /// </returns>
        public static bool IsCurrentUICultureFrench()
        {
            return (CultureInfo.CurrentUICulture.Name.Equals("fr-FR", StringComparison.Ordinal));
        }

        #endregion

        #region String generating methods

        /// <summary>
        /// Gets the abbreviated day from a
        /// <see cref="T:System.DateTime"/>
        /// object.
        /// </summary>
        /// <param name="dt">Date information.</param>
        /// <returns>e.g. "Mon" for Monday when en-US.</returns>
        public static string GetAbbreviatedDay(DateTime dt)
        {
            if (DateTimeFormatHelper.IsCurrentCultureJapanese() || DateTimeFormatHelper.IsCurrentCultureKorean())
            {
                return "(" + dt.ToString("ddd", CultureInfo.CurrentCulture) + ")";
            }
            else
            {
                return dt.ToString("ddd", CultureInfo.CurrentCulture);
            }
        }

        /// <summary>
        /// Gets the time from a
        /// <see cref="T:System.DateTime"/>
        /// object in short Metro format.
        /// </summary>
        /// <remarks>
        /// Metro design guidelines normalize strings to lowercase.
        /// </remarks>
        /// <param name="dt">Time information.</param>
        /// <returns>"10:20p" for 10:20 p.m. when en-US.</returns>
        [SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "Metro design guidelines normalize strings to lowercase.")]
        public static string GetSuperShortTime(DateTime dt)
        {
            if (formatInfo_GetSuperShortTime == null)
            {
                lock (lock_GetSuperShortTime)
                {
                    StringBuilder result = new StringBuilder(string.Empty);
                    string seconds;

                    formatInfo_GetSuperShortTime = (DateTimeFormatInfo)CultureInfo.CurrentCulture.DateTimeFormat.Clone();

                    result.Append(formatInfo_GetSuperShortTime.LongTimePattern);
                    seconds = rxSeconds.Match(result.ToString()).Value;
                    result.Replace(" ", string.Empty);
                    result.Replace(seconds, string.Empty);
                    if (!(DateTimeFormatHelper.IsCurrentCultureJapanese()
                        || DateTimeFormatHelper.IsCurrentCultureKorean()
                        || DateTimeFormatHelper.IsCurrentCultureHungarian()))
                    {
                        result.Replace(DoubleMeridiemDesignator, SingleMeridiemDesignator);
                    }

                    formatInfo_GetSuperShortTime.ShortTimePattern = result.ToString();
                }
            }

            return dt.ToString("t", formatInfo_GetSuperShortTime).ToLowerInvariant();
        }

        /// <summary>
        /// Gets the month and day from a
        /// <see cref="T:System.DateTime"/>
        /// object.
        /// </summary>
        /// <param name="dt">Date information.</param>
        /// <returns>"05/24" for May 24th when en-US.</returns>
        public static string GetMonthAndDay(DateTime dt)
        {
            if (formatInfo_GetMonthAndDay == null)
            {
                lock (lock_GetMonthAndDay)
                {
                    StringBuilder result = new StringBuilder(string.Empty);

                    formatInfo_GetMonthAndDay = (DateTimeFormatInfo)CultureInfo.CurrentCulture.DateTimeFormat.Clone();

                    result.Append(rxMonthAndDay.Match(formatInfo_GetMonthAndDay.ShortDatePattern).Value);
                    if (result.ToString().Contains("."))
                    {
                        result.Append(".");
                    }

                    formatInfo_GetMonthAndDay.ShortDatePattern = result.ToString();
                }
            }

            return dt.ToString("d", formatInfo_GetMonthAndDay);
        }

        /// <summary>
        /// Gets the date in short pattern from a
        /// <see cref="T:System.DateTime"/>
        /// object.
        /// </summary>
        /// <param name="dt">Date information.</param>
        /// <returns>
        /// Date in short pattern as defined by the system locale.
        /// </returns>
        public static string GetShortDate(DateTime dt)
        {
            return dt.ToString("d", CultureInfo.CurrentCulture);
        }

        /// <summary>
        /// Gets the time in short pattern from a
        /// <see cref="T:System.DateTime"/>
        /// object.
        /// </summary>
        /// <param name="dt">Date information.</param>
        /// <returns>
        /// Time in short pattern as defined by the system locale.
        /// </returns>
        public static string GetShortTime(DateTime dt)
        {
            if (formatInfo_GetShortTime == null)
            {
                lock (lock_GetShortTime)
                {
                    StringBuilder result = new StringBuilder(string.Empty);
                    string seconds;

                    formatInfo_GetShortTime = (DateTimeFormatInfo)CultureInfo.CurrentCulture.DateTimeFormat.Clone();

                    result.Append(formatInfo_GetShortTime.LongTimePattern);
                    seconds = rxSeconds.Match(result.ToString()).Value;
                    result.Replace(seconds, string.Empty);

                    formatInfo_GetShortTime.ShortTimePattern = result.ToString();
                }
            }

            return dt.ToString("t", formatInfo_GetShortTime);
        }

        #endregion
    }
}


text:
#include <aws/glue/model/PutWorkflowRunPropertiesResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::Glue::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

PutWorkflowRunPropertiesResult::PutWorkflowRunPropertiesResult()
{
}

PutWorkflowRunPropertiesResult::PutWorkflowRunPropertiesResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

PutWorkflowRunPropertiesResult& PutWorkflowRunPropertiesResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  AWS_UNREFERENCED_PARAM(result);

  return *this;
}


text:
#pragma once
#include <aws/logs/CloudWatchLogs_EXPORTS.h>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace CloudWatchLogs
{
namespace Model
{

  /**
   *
Represents the rejected events.

See Also:
   AWS
   * API Reference

   */
  class AWS_CLOUDWATCHLOGS_API RejectedLogEventsInfo
  {
  public:
    RejectedLogEventsInfo();
    RejectedLogEventsInfo(Aws::Utils::Json::JsonView jsonValue);
    RejectedLogEventsInfo& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The log events that are too new.

     */
    inline int GetTooNewLogEventStartIndex() const{ return m_tooNewLogEventStartIndex; }

    /**
     *
The log events that are too new.

     */
    inline bool TooNewLogEventStartIndexHasBeenSet() const { return m_tooNewLogEventStartIndexHasBeenSet; }

    /**
     *
The log events that are too new.

     */
    inline void SetTooNewLogEventStartIndex(int value) { m_tooNewLogEventStartIndexHasBeenSet = true; m_tooNewLogEventStartIndex = value; }

    /**
     *
The log events that are too new.

     */
    inline RejectedLogEventsInfo& WithTooNewLogEventStartIndex(int value) { SetTooNewLogEventStartIndex(value); return *this;}

    /**
     *
The log events that are too old.

     */
    inline int GetTooOldLogEventEndIndex() const{ return m_tooOldLogEventEndIndex; }

    /**
     *
The log events that are too old.

     */
    inline bool TooOldLogEventEndIndexHasBeenSet() const { return m_tooOldLogEventEndIndexHasBeenSet; }

    /**
     *
The log events that are too old.

     */
    inline void SetTooOldLogEventEndIndex(int value) { m_tooOldLogEventEndIndexHasBeenSet = true; m_tooOldLogEventEndIndex = value; }

    /**
     *
The log events that are too old.

     */
    inline RejectedLogEventsInfo& WithTooOldLogEventEndIndex(int value) { SetTooOldLogEventEndIndex(value); return *this;}

    /**
     *
The expired log events.

     */
    inline int GetExpiredLogEventEndIndex() const{ return m_expiredLogEventEndIndex; }

    /**
     *
The expired log events.

     */
    inline bool ExpiredLogEventEndIndexHasBeenSet() const { return m_expiredLogEventEndIndexHasBeenSet; }

    /**
     *
The expired log events.

     */
    inline void SetExpiredLogEventEndIndex(int value) { m_expiredLogEventEndIndexHasBeenSet = true; m_expiredLogEventEndIndex = value; }

    /**
     *
The expired log events.

     */
    inline RejectedLogEventsInfo& WithExpiredLogEventEndIndex(int value) { SetExpiredLogEventEndIndex(value); return *this;}

  private:

    int m_tooNewLogEventStartIndex;
    bool m_tooNewLogEventStartIndexHasBeenSet = false;

    int m_tooOldLogEventEndIndex;
    bool m_tooOldLogEventEndIndexHasBeenSet = false;

    int m_expiredLogEventEndIndex;
    bool m_expiredLogEventEndIndexHasBeenSet = false;
  };

} // namespace Model
} // namespace CloudWatchLogs
} // namespace Aws


text:
@interface HomeViewController : UITableViewController

@property (weak,nonatomic) IBOutlet UIBarButtonItem *barButton;

@end


text:
@interface PodsDummy_Pods_DINCUITests : NSObject
@end
@implementation PodsDummy_Pods_DINCUITests
@end


text:
$Links = @()
$MarkdownLinks = Get-ChildItem $PSScriptRoot\..\* -Include '*.md' -Recurse | Select-String '^.*\[.*\]\((http.*)\).*$' -AllMatches
foreach ($Match in $MarkdownLinks)
{
    $Links += @{$Match.Matches.Groups.value[1] = $Match.Path}
}

$Files = $Links.Values | Sort-Object -Unique

Describe "Testing Resources" {

    foreach ($File in $Files)
    {
        Context "Testing Links: [$($File)]" {
            $FileLinks = $Links | Where-Object { $_.Values -eq $File}

            foreach ($Link in $FileLinks)
            {
                $Link = ($Link.Keys | Out-String).Trim()

                It "[$($Link)] should have 200 Status Code" {

                    $Results = Invoke-WebRequest -Uri $Link -UseBasicParsing
                    $Results.StatusCode | Should Be '200'
                }
            }
        }
    }
}


text:
from bottle import route, get, post, run, static_file, request
import json
import socket

scores = {}

HOST, PORT = "localhost", 9999
socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket_server.bind((HOST, PORT))
socket_server.listen(10)

print('Waiting for connection from Spark Streaming...')
conn, addr = socket_server.accept()
print('Got a connection. Ready to receive requests')

@get('/')
def index():
    return static_file('index.html', root='resources')

@route('/static/app/<filename>')
def get_static(filename):
    return static_file(filename, root='resources/app')

@get('/items')
def get_scores():
    items = [{'item':x, 'score':scores[x]} for x in scores]
    return json.dumps(sorted(items, key=lambda x: -x['score']))

@post('/items')
def update_snapshot():
    global scores
    new_scores = json.loads(str(request.body.getvalue().decode("utf-8")))
    for x in new_scores:
        scores[x['item']] = x['score']

@post('/items/<name>')
def interact(name):
    conn.send(bytes(name + '\n','utf-8'))

run(host='localhost', port=8080)


text:
FROM balenalib/i386-debian:bookworm-run
LABEL io.balena.device-type="edison"

RUN apt-get update && apt-get install -y --no-install-recommends \
		less \
		kmod \
		nano \
		net-tools \
		ifupdown \
		iputils-ping \
		i2c-tools \
		usbutils \
	&& rm -rf /var/lib/apt/lists/*

# MRAA
ENV MRAA_COMMIT 967585c9ea0e1a8818d2172d2395d8502f6180a2
ENV MRAA_VERSION 2.0.0
# UPM
ENV UPM_COMMIT 16e72d2ff709e27d411f38b002bc0284354951e2
ENV UPM_VERSION 1.7.1

# Install mraa
RUN set -x \
	&& buildDeps=' \
		libpcre3-dev \
		python-dev \
		swig \
		pkg-config \
	' \
	&& if ! apt-cache show 'build-essential' 2>/dev/null | grep -q '^Version:'; then buildDeps="$buildDeps build-essential"; fi \
	&& if ! apt-cache show 'git' 2>/dev/null | grep -q '^Version:'; then buildDeps="$buildDeps git"; fi \
	&& apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \
	&& mkdir /cmake \
	&& curl -SL https://cmake.org/files/v3.5/cmake-3.5.2.tar.gz -o cmake.tar.gz \
	&& echo "92d8410d3d981bb881dfff2aed466da55a58d34c7390d50449aa59b32bb5e62a  cmake.tar.gz" | sha256sum -c - \
	&& tar -xzf cmake.tar.gz -C /cmake --strip-components=1 \
	&& cd /cmake \
	&& ./configure \
	&& make -j $(nproc) \
	&& make install \
	&& cd / \
	&& git clone https://github.com/intel-iot-devkit/mraa.git \
	&& cd /mraa \
	&& git checkout $MRAA_COMMIT \
	&& mkdir build && cd build \
	&& cmake .. -DWERROR=NO -DBUILDSWIGNODE=OFF -DBUILDSWIGPYTHON=OFF -DCMAKE_INSTALL_PREFIX:PATH=/usr \
	&& make -j $(nproc) \
	&& make install \
	&& cd / \
	&& git clone https://github.com/intel-iot-devkit/upm.git \
	&& cd /upm \
	&& git checkout $UPM_COMMIT \
	&& mkdir build && cd build \
	&& cmake .. -DWERROR=NO -DBUILDSWIGNODE=OFF -DBUILDSWIGPYTHON=OFF -DCMAKE_INSTALL_PREFIX:PATH=/usr \
	&& make -j $(nproc) \
	&& make install \
	&& cd /cmake \
	&& make uninstall \
	&& apt-get purge -y --auto-remove $buildDeps \
	&& cd / && rm -rf mraa upm cmake

# Update Shared Library Cache
RUN echo "/usr/local/lib/i386-linux-gnu/" >> /etc/ld.so.conf \
	&& ldconfig

RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 32-bit (x86) \nOS: Debian Bookworm \nVariant: run variant \nDefault variable(s): UDEV=off \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature  (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info

RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
	&& chmod +x /bin/sh-shim \
	&& cp /bin/sh /bin/sh.real \
	&& mv /bin/sh-shim /bin/sh


text:
module("Ncr7.tContainer", package.seeall)

require "Tools/Object"
require "Tools/Register"

local Container = {}

function Container.initialize()
   local obj = { register=Ncr7.tRegister.new() }
   local container = Ncr7.tObject.New._object(Container, obj)
   container.register:createRegister('Container')
   return container
end

function Container:init(containersName)
  if(nil~=containersName) then
    for value,key in pairs(containersName) do
      self.register:createRegister(key)
    end
  end
end

function Container:reg(key)
  if(key == nil) then
    return self.register
  else
    return self.register:get(key)
  end
end

function Container:setParameter(key,value)
  return self.register:get('Container'):set(key,value)
end

function Container:getParameter(key)
  return self.register:get('Container'):get(key)
end

function new()
  return Container.initialize()
end

function bootstrap(ncr7LualibDir)
  local love2Dcontainer = {'Love.load','Love.draw','Love.keypressed','Love.textinput',
                           'Love.mousepressed','Love.mousereleased','Love.mousemoved'}
  _G.Container = Ncr7.tContainer.new()
  _G.Container:init(love2Dcontainer)
  _G.Container:setParameter('rootdir',ncr7LualibDir)
  return love2Dcontainer
end


text:
<?php

defined('_JEXEC') or die('Restricted access');

require_once( EBLOG_HELPERS . DIRECTORY_SEPARATOR . 'helper.php' );

class EasyBlogVideosHelper
{
	private $patterns	= array(
									'youtube.com'		=> 'youtube',
									'youtu.be'			=> 'youtube',
									'vimeo.com'			=> 'vimeo',
									'yahoo.com'			=> 'yahoo',
									'metacafe.com'		=> 'metacafe',
									'google.com'		=> 'google',
									'mtv.com'			=> 'mtv',
									'liveleak.com'		=> 'liveleak',
									'revver.com'		=> 'revver',
									'dailymotion.com'	=> 'dailymotion',
									'nicovideo.jp'		=> 'nicovideo',
									'blip.tv'			=> 'blip'
								);

	public function strip( $content )
	{

		// In case Joomla tries to entity the contents, we need to replace accordingly.
		$content	= str_ireplace( '"' , '"' , $content );

		$pattern	= array('/\{video:.*?\}/',
							'/\{"video":.*?\}/',
							'/\[embed=.*?\].*?\[\/embed\]/'
							);

		$replace    = array('','');

		return preg_replace( $pattern , $replace , $content );
	}

	/*
		isPlain - return only video url in the content when is true. else, return embeded video object
	*/
	public function processVideos( $content, $isPlain = false )
	{

		// @since 3.5
		// New pattern uses [embed=videolink] to process embedded videos from external URLs.
		//
		// videolink - External video URLs like Youtube, Google videos, MTV
		// video - Internal video URLs that are uploaded via media manager
		$pattern	= '/\[embed=(.*)\](.*)\[\/embed\]/uiU';
		preg_match_all( $pattern , $content , $matches , PREG_SET_ORDER );

		if( !empty( $matches ) )
		{
			foreach( $matches as $match )
			{
				$type 	= $match[1];
				$search	= $match[0];
				$result	= $match[2];

				switch( $type )
				{
					// Videos that are linked from external sites such as Youtube.
					case 'videolink':
						$content	= $this->processExternalVideos( $content , $isPlain , $search , $result );
					break;
					// Normal video embeds that are uploaded via media manager.
					case 'video':
						$content	= $this->processInternalVideos( $content , $isPlain , $search , $result );
					break;
				}
			}
		}

		// @legacy Prior to 3.5, internal videos uses the format of

		$content	= $this->processInternalVideos( $content , $isPlain );

		// @legacy Prior to 3.5, videos only uses {"video":"url" } so we still need to replace this if it exists.
		$content	= $this->processExternalVideos( $content , $isPlain );

		return $content;
	}

	public function processInternalVideos( $content , $isPlain = false , $findText = '' , $result = '' )
	{
		$cfg		= EasyBlogHelper::getConfig();

		// Since 3.0 uses a different video format, we need to do some tests here.
		if( $result )
		{
			require_once( EBLOG_CLASSES . DIRECTORY_SEPARATOR . 'json.php' );

			$json	= new Services_JSON();
			$data	= $json->decode( $result );

			$file		= trim( $data->file , '/\\' );
			$width		= $data->width;
			$height		= $data->height;
			$autostart	= $data->autostart;
			$place		= $data->place;

			if( $place == 'shared' )
			{
				$url		= rtrim( JURI::root() , '/' ) . '/' . trim( str_ireplace( '\\' , '/' , $cfg->get( 'main_shared_path' ) ) , '/\\') . '/' . $file;
			}
			else
			{
				$place 			= explode( ':' , $place );
				$url			= rtrim( JURI::root() , '/' ) . '/' . trim( $cfg->get( 'main_image_path' ) , '/\\') . '/' . $place[1] . '/' . $file;
			}

			$theme		= new CodeThemes();

			// Give a unique id for the video.
			$theme->set( 'uid'			, uniqid() );
			$theme->set( 'width' 		, $width );
			$theme->set( 'height'		, $height );
			$theme->set( 'autoplay'		, $autostart );
			$theme->set( 'url'			, $url );
			$output		= $theme->fetch( 'blog.video.php' );

			$content	= str_ireplace( $findText , $output , $content );

			return $content;
		}

		// @legacy Legacy support for prior to 3.5
		// This should be removed later.
		$pattern	= '#"easyblog-video*[^>]*#is';
		$html		= $content;

		preg_match( $pattern , $content , $matches );

		if( !empty($matches) && isset( $matches[0 ] ) )
		{
			// Match the value
			$input		= $matches[ 0 ];
			preg_match( '/value="(.*})"/i' , $input , $data );

			if( isset( $data[1] ) )
			{
				$json		= new Services_JSON();
				$data[1]	= str_ireplace( '"' , '' , $data[ 1 ] );
				$obj		= $json->decode( $data[ 1 ] );

				$theme		= new CodeThemes();
				$uri		= rtrim( JURI::root() , '/' ) . '/' . str_ireplace( "\\" , '/' , rtrim( $cfg->get( 'main_image_path' ) , '/' ) ) . '/' . $userId;
				$uri		.= '/' . $obj->path;

				$storage	= str_ireplace( '/' , DIRECTORY_SEPARATOR , rtrim( $cfg->get( 'main_image_path' ) , '/' ) );

				if( !isset( $obj->autoplay ) )
				{
					$obj->autoplay	= false;
				}

				$theme->set( 'url'		, $uri );
				$theme->set( 'width'	, $obj->width );
				$theme->set( 'height'	, $obj->height );
				$theme->set( 'autoplay'	, false );
				$theme->set( 'video'	, $obj );
				$theme->set( 'uid' 		, uniqid() );

				$output		= $theme->fetch( 'blog.video.php' );

				$pattern	= array( '#<div class="easyblog-placeholder-video(.*?)
(.*?)#is' );
				$content	= preg_replace( $pattern , $output , $content );

				// Remove unwanted data
				$content	= preg_replace( '#

(|\n|\r\n)
<input class="easyblog-video(.*?)
#is' , '' , $content );
				return $content;
			}
		}

		return $content;
	}

	/**
	 * Processes external video links such as youtube, vimeo etc.
	 *
	 * @access	public
	 *
	 */
	public function processExternalVideos( $content , $isPlain = false , $findText = '' , $jsonString = '' )
	{
		$cfg		= EasyBlogHelper::getConfig();

		if( !empty( $jsonString ) )
		{
			$json	= new Services_JSON();

			$data		= $json->decode( $jsonString );

			$search 	= !empty( $findText ) ? $findText : $jsonString;

			if( $isPlain )
			{
				$html 		= ' ' . $data->video . ' ';
				$content	= str_ireplace( $search , $html , $content );
			}
			else
			{
				// @task: Ensure that the width doesn't exceed the maximum width settings.
				$data->width	= $data->width > $cfg->get( 'max_video_width' ) ? $cfg->get( 'max_video_width' ) : $data->width;

				// @task: Ensure that the height doesn't exceed the maximum height settings.
				$data->height	= $data->height > $cfg->get( 'max_video_height' ) ? $cfg->get( 'max_video_height' ) : $data->height;

				$data->video	= strip_tags( $data->video );
				$output 	= $this->processVideoLink( $data->video , $data->width , $data->height );

				if( $output !== false )
				{
					$content	= str_ireplace( $search , $output , $content );
				}
			}
		}

		if( empty( $jsonString ) )
		{
			// @since 2.0.3515, video:"url" has been changed to "video":"url"
			$pattern	= '/\{"video":.*?\}/i';

			// In case Joomla tries to entity the contents, we need to replace accordingly.
			$tmpContent	= str_ireplace( '"' , '"' , $content );

			preg_match_all( $pattern , $tmpContent , $matches );
			$videos		= $matches[0];

			// @since 2.0.3515 Legacy support for older codes video:"url"
			if( empty( $videos ) )
			{
				$pattern	= '/\{video:.*?\}/i';
				preg_match_all( $pattern , $tmpContent , $matches );
				$videos		= $matches[0];
			}

			foreach( $videos as $video )
			{
				$json	= new Services_JSON();

				$data		= $json->decode( $video );

				$search 	= !empty( $findText ) ? $findText : $video;

				if( $isPlain )
				{
					$html 		= ' ' . $data->video . ' ';
					$content	= str_ireplace( $search , $html , $content );
				}
				else
				{
					// @task: Ensure that the width doesn't exceed the maximum width settings.
					$data->width	= $data->width > $cfg->get( 'max_video_width' ) ? $cfg->get( 'max_video_width' ) : $data->width;

					// @task: Ensure that the height doesn't exceed the maximum height settings.
					$data->height	= $data->height > $cfg->get( 'max_video_height' ) ? $cfg->get( 'max_video_height' ) : $data->height;

					$data->video	= strip_tags( $data->video );
					$output 	= $this->processVideoLink( $data->video , $data->width , $data->height );

					if( $output !== false )
					{
						$content	= str_ireplace( $search , $output , $content );
					}
				}
			}
		}

		return $content;
	}

	/**
	 * Given a set of content, try to match and return the list of videos that are found in the content.
	 * This is only applicable for videos that are supported by the library.
	 *
	 * @author	imarklee
	 * @access	public
	 * @param	string	$content	The html contents that we should look for.
	 * @return	Array				An array of videos that are found.
	 */
	public function getHTMLArray( $content )
	{
		// This will eventually contain all the video objects
		$result 	= array();

		// Store temporary content for legacy fixes.
		$tmpContent	= $content;

		// @since 3.5
		// New pattern uses [embed=videolink] to process embedded videos from external URLs.
		//
		// videolink - External video URLs like Youtube, Google videos, MTV
		// video - Internal video URLs that are uploaded via media manager
		$pattern	= '/\[embed=(.*)\](.*)\[\/embed\]/uiU';
		preg_match_all( $pattern , $content , $matches , PREG_SET_ORDER );

		if( !empty( $matches ) )
		{
			foreach( $matches as $match )
			{
				$type 		= $match[1];
				$search		= $match[0];
				$rawJSON	= $match[2];

				if( $type == 'videolink' || $type == 'video' )
				{
					$data		= $this->parseJSON( $rawJSON );

					// Let's remove it from the temporary content.
					$tmpContent	= str_ireplace( $search , '' , $tmpContent );

					switch( $type )
					{
						// Videos that are linked from external sites such as Youtube.
						case 'videolink':
							$html 	= $this->processVideoLink( $data->video , $data->width , $data->height );
						break;
						// Normal video embeds that are uploaded via media manager.
						case 'video':
							$html	= $this->processInternalVideoLink( $content , $rawJSON );
						break;
					}

					// Now, let's add the data object back to the result list.
					$result[]	= $html;
				}
			}
		}

		// @legacy prior to EasyBlog 3.5
		// @since 2.0.3515, video:"url" has been changed to "video":"url"
		$pattern	= '/\{"video":.*?\}/i';

		// In case Joomla tries to entity the contents, we need to replace accordingly.
		$tmpContent	= str_ireplace( '"' , '"' , $tmpContent );

		// @task: We search in $tmpContent instead of $content because the new [embed] codes might already replace the values.
		preg_match_all( $pattern , $tmpContent , $matches );
		$videos		= $matches[0];

		if( empty( $videos ) )
		{
			return $result;
		}

		foreach( $videos as $video )
		{
			$data		= $this->parseJSON( $video );
			$output		= $this->processVideoLink( $data->video , $data->width , $data->height );

			if( $output !== false )
			{
				$result[]		= $output;
			}
		}

		return $result;
	}

	/**
	 * Given a set of content, try to match and return the list of videos that are found in the content.
	 * This is only applicable for videos that are supported by the library.
	 *
	 * @author	imarklee
	 * @access	public
	 * @param	string	$content	The html contents that we should look for.
	 * @return	Array				An array of videos that are found.
	 */
	public function getVideoObjects( $content )
	{
		// This will eventually contain all the video objects
		$result 	= array();

		// Store temporary content for legacy fixes.
		$tmpContent	= $content;

		// @since 3.5
		// New pattern uses [embed=videolink] to process embedded videos from external URLs.
		//
		// videolink - External video URLs like Youtube, Google videos, MTV
		// video - Internal video URLs that are uploaded via media manager
		$pattern	= '/\[embed=(.*)\](.*)\[\/embed\]/uiU';
		preg_match_all( $pattern , $content , $matches , PREG_SET_ORDER );

		if( !empty( $matches ) )
		{
			foreach( $matches as $match )
			{
				$type 		= $match[1];
				$search		= $match[0];
				$rawJSON	= $match[2];

				$data		= $this->parseJSON( $rawJSON );

				// Let's remove it from the temporary content.
				$tmpContent	= str_ireplace( $search , '' , $tmpContent );

				switch( $type )
				{
					// Videos that are linked from external sites such as Youtube.
					case 'videolink':
						$data->html 	= $this->processVideoLink( $data->video , $data->width , $data->height );
					break;
					// Normal video embeds that are uploaded via media manager.
					case 'video':
						// TODO
					break;
				}

				// Now, let's add the data object back to the result list.
				$result[]	= $data;
			}
		}

		// @legacy prior to EasyBlog 3.5
		// @since 2.0.3515, video:"url" has been changed to "video":"url"
		$pattern	= '/\{"video":.*?\}/i';

		// In case Joomla tries to entity the contents, we need to replace accordingly.
		$tmpContent	= str_ireplace( '"' , '"' , $tmpContent );

		// @task: We search in $tmpContent instead of $content because the new [embed] codes might already replace the values.
		preg_match_all( $pattern , $tmpContent , $matches );
		$videos		= $matches[0];

		if( empty( $videos ) )
		{
			return $result;
		}

		foreach( $videos as $video )
		{
			$data		= $this->parseJSON( $video );
			$output		= $this->processVideoLink( $data->video , $data->width , $data->height );

			if( $output !== false )
			{
				$data->html 	= $output;
				$result[]		= $data;
			}
		}

		return $result;
	}

	private function parseJSON( $jsonRaw )
	{
		// Initialize the JSON library
		$json	= new Services_JSON();

		return $json->decode( $jsonRaw );
	}

	private function getDomain( $link )
	{

		$link = strip_tags( $link );
		$domain = "";

		if( stristr( $link , 'http://') === false && stristr( $link , 'https://') === false )
		{
			$link 	= 'http://' . $link;
		}

		// Remove any html codes if any
		$link	= strip_tags( $link );

		$link	= parse_url( $link );
		$link 	= explode( '.' , $link[ 'host' ] );

		if( count($link) >= 2 )
		{
			$domain = $link[ count( $link ) - 2 ] . '.' . $link[ count( $link ) - 1 ];
		}

		return $domain;
	}

	public function processInternalVideoLink( $content , $jsonString = '' )
	{
		$cfg		= EasyBlogHelper::getConfig();

		// Since 3.0 uses a different video format, we need to do some tests here.
		if( $jsonString )
		{
			require_once( EBLOG_CLASSES . DIRECTORY_SEPARATOR . 'json.php' );

			$json	= new Services_JSON();

			$data	= $json->decode( $jsonString );

			$file		= trim( $data->file , '/\\' );
			$width		= isset( $data->width ) ? $data->width : 0;
			$height		= $data->height;
			$autostart	= $data->autostart;
			$place		= $data->place;

			if( $place == 'shared' )
			{
				$url		= rtrim( JURI::root() , '/' ) . '/' . trim( str_ireplace( '\\' , '/' , $cfg->get( 'main_shared_path' ) ) , '/\\') . '/' . $file;
			}
			else
			{
				$place 			= explode( ':' , $place );
				$url			= rtrim( JURI::root() , '/' ) . '/' . trim( $cfg->get( 'main_image_path' ) , '/\\') . '/' . $place[1] . '/' . $file;
			}

			$theme		= new CodeThemes();

			// Give a unique id for the video.
			$theme->set( 'uid'			, uniqid() );
			$theme->set( 'width' 		, $width );
			$theme->set( 'height'		, $height );
			$theme->set( 'autoplay'		, $autostart );
			$theme->set( 'url'			, $url );
			$output		= $theme->fetch( 'blog.video.php' );

			return $output;
		}

		// @legacy Legacy support for prior to 3.5
		// This should be removed later.
		$pattern	= '#"easyblog-video*[^>]*#is';

		preg_match( $pattern , $content , $matches );

		if( !empty($matches) && isset( $matches[0 ] ) )
		{
			// Match the value
			$input		= $matches[ 0 ];
			preg_match( '/value="(.*})"/i' , $input , $data );

			if( isset( $data[1] ) )
			{
				$json		= new Services_JSON();
				$data[1]	= str_ireplace( '"' , '' , $data[ 1 ] );
				$obj		= $json->decode( $data[ 1 ] );

				$theme		= new CodeThemes();
				$uri		= rtrim( JURI::root() , '/' ) . '/' . str_ireplace( "\\" , '/' , rtrim( $cfg->get( 'main_image_path' ) , '/' ) ) . '/' . $userId;
				$uri		.= '/' . $obj->path;

				$storage	= str_ireplace( '/' , DIRECTORY_SEPARATOR , rtrim( $cfg->get( 'main_image_path' ) , '/' ) );

				if( !isset( $obj->autoplay ) )
				{
					$obj->autoplay	= false;
				}

				$theme->set( 'url'		, $uri );
				$theme->set( 'width'	, $obj->width );
				$theme->set( 'height'	, $obj->height );
				$theme->set( 'autoplay'	, false );
				$theme->set( 'video'	, $obj );
				$theme->set( 'uid' 		, uniqid() );

				$output		= $theme->fetch( 'blog.video.php' );

				$pattern	= array( '#getDomain( $link );

		if( !array_key_exists( $domain , $this->patterns ) )
		{
			// $content	= str_ireplace( $video , $html , $content );
			return false;
		}

		$provider	= JString::strtolower( $this->patterns[ $domain ] );

		$path		= EBLOG_CLASSES . DIRECTORY_SEPARATOR . 'videos' . DIRECTORY_SEPARATOR . $provider . '.php';

		require_once( $path );

		$class	= 'EasyBlogVideo' . ucfirst( $this->patterns[ $domain ] );

		if( class_exists( $class ) )
		{
			$object		= new $class();
			$html		= $object->getEmbedHTML( $link , $width , $height );

			return $html;
		}

		return false;
	}
}


text:
require "#{File.dirname(__FILE__)}/../test_helper"
require 'open-uri'

# Start the server

class ServerTest < Test::Unit::TestCase

  PORT = 43040
  URL = "http://localhost:#{PORT}/"

  def setup
    @pid = Process.fork do
       Dir.chdir RAILS_ROOT do
         # print "S"
         exec("script/server -p #{PORT} &> #{LOG}")
       end
     end
     sleep(5)
  end

  def teardown
    # Process.kill(9, @pid) doesn't work because Mongrel has double-forked itself away
    `ps awx | grep #{PORT} | grep -v grep | awk '{print $1}'`.split("\n").each do |pid|
      system("kill -9 #{pid}")
      # print "K"
    end
    sleep(2)
    @pid = nil
  end

  def test_association_reloading
    4.times do
      assert_match(/Sellers: index/, open(URL + 'sellers').read)
    end
  end

end


text:
module.exports = {
  openSeedFile,
  openSeedDirectory,
  openTorrentFile,
  openTorrentAddress,
  openFiles
}

var electron = require('electron')

var log = require('./log')
var windows = require('./windows')

/**
 * Show open dialog to create a single-file torrent.
 */
function openSeedFile () {
  if (!windows.main.win) return
  log('openSeedFile')
  var opts = {
    title: 'Select a file for the torrent.',
    properties: [ 'openFile' ]
  }
  setTitle(opts.title)
  electron.dialog.showOpenDialog(windows.main.win, opts, function (selectedPaths) {
    resetTitle()
    if (!Array.isArray(selectedPaths)) return
    windows.main.dispatch('showCreateTorrent', selectedPaths)
  })
}

/*
 * Show open dialog to create a single-file or single-directory torrent. On
 * Windows and Linux, open dialogs are for files *or* directories only, not both,
 * so this function shows a directory dialog on those platforms.
 */
function openSeedDirectory () {
  if (!windows.main.win) return
  log('openSeedDirectory')
  var opts = process.platform === 'darwin'
    ? {
      title: 'Select a file or folder for the torrent.',
      properties: [ 'openFile', 'openDirectory' ]
    }
    : {
      title: 'Select a folder for the torrent.',
      properties: [ 'openDirectory' ]
    }
  setTitle(opts.title)
  electron.dialog.showOpenDialog(windows.main.win, opts, function (selectedPaths) {
    resetTitle()
    if (!Array.isArray(selectedPaths)) return
    windows.main.dispatch('showCreateTorrent', selectedPaths)
  })
}

/*
 * Show flexible open dialog that supports selecting .torrent files to add, or
 * a file or folder to create a single-file or single-directory torrent.
 */
function openFiles () {
  if (!windows.main.win) return
  log('openFiles')
  var opts = process.platform === 'darwin'
    ? {
      title: 'Select a file or folder to add.',
      properties: [ 'openFile', 'openDirectory' ]
    }
    : {
      title: 'Select a file to add.',
      properties: [ 'openFile' ]
    }
  setTitle(opts.title)
  electron.dialog.showOpenDialog(windows.main.win, opts, function (selectedPaths) {
    resetTitle()
    if (!Array.isArray(selectedPaths)) return
    windows.main.dispatch('onOpen', selectedPaths)
  })
}

/*
 * Show open dialog to open a .torrent file.
 */
function openTorrentFile () {
  if (!windows.main.win) return
  log('openTorrentFile')
  var opts = {
    title: 'Select a .torrent file.',
    filters: [{ name: 'Torrent Files', extensions: ['torrent'] }],
    properties: [ 'openFile', 'multiSelections' ]
  }
  setTitle(opts.title)
  electron.dialog.showOpenDialog(windows.main.win, opts, function (selectedPaths) {
    resetTitle()
    if (!Array.isArray(selectedPaths)) return
    selectedPaths.forEach(function (selectedPath) {
      windows.main.dispatch('addTorrent', selectedPath)
    })
  })
}

/*
 * Show modal dialog to open a torrent URL (magnet uri, http torrent link, etc.)
 */
function openTorrentAddress () {
  log('openTorrentAddress')
  windows.main.dispatch('openTorrentAddress')
}

/**
 * Dialogs on do not show a title on Mac, so the window title is used instead.
 */
function setTitle (title) {
  if (process.platform === 'darwin') {
    windows.main.dispatch('setTitle', title)
  }
}

function resetTitle () {
  windows.main.dispatch('resetTitle')
}


text:
"use strict";

module.exports = require("./_iterate")("forEach");


text:
import random
import threading
import time

from spiderfoot import SpiderFootEvent, SpiderFootPlugin

class sfp_s3bucket(SpiderFootPlugin):

    meta = {
        'name': "Amazon S3 Bucket Finder",
        'summary': "Search for potential Amazon S3 buckets associated with the target and attempt to list their contents.",
        'flags': [],
        'useCases': ["Footprint", "Passive"],
        'categories': ["Crawling and Scanning"],
        'dataSource': {
            'website': "https://aws.amazon.com/s3/",
            'model': "FREE_NOAUTH_UNLIMITED",
            'favIcon': 'https://a0.awsstatic.com/libra-css/images/site/fav/favicon.ico',
            'logo': 'https://a0.awsstatic.com/libra-css/images/site/touch-icon-ipad-144-smile.png',
            'description': "Amazon S3 is cloud object storage with industry-leading scalability, data availability, security, and performance. "
            "S3 is ideal for data lakes, mobile applications, backup and restore, archival, IoT devices, ML, AI, and analytics."
        }
    }

    # Default options
    opts = {
        "endpoints": "s3.amazonaws.com,s3-external-1.amazonaws.com,s3-us-west-1.amazonaws.com,s3-us-west-2.amazonaws.com,s3.ap-south-1.amazonaws.com,s3-ap-south-1.amazonaws.com,s3.ap-northeast-2.amazonaws.com,s3-ap-northeast-2.amazonaws.com,s3-ap-southeast-1.amazonaws.com,s3-ap-southeast-2.amazonaws.com,s3-ap-northeast-1.amazonaws.com,s3.eu-central-1.amazonaws.com,s3-eu-central-1.amazonaws.com,s3-eu-west-1.amazonaws.com,s3-sa-east-1.amazonaws.com",
        "suffixes": "test,dev,web,beta,bucket,space,files,content,data,prod,staging,production,stage,app,media,development,-test,-dev,-web,-beta,-bucket,-space,-files,-content,-data,-prod,-staging,-production,-stage,-app,-media,-development",
        "_maxthreads": 20
    }

    # Option descriptions
    optdescs = {
        "endpoints": "Different S3 endpoints to check where buckets may exist, as per http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region",
        "suffixes": "List of suffixes to append to domains tried as bucket names",
        "_maxthreads": "Maximum threads"
    }

    results = None
    s3results = dict()
    lock = None

    def setup(self, sfc, userOpts=dict()):
        self.sf = sfc
        self.s3results = dict()
        self.results = self.tempStorage()
        self.lock = threading.Lock()

        for opt in list(userOpts.keys()):
            self.opts[opt] = userOpts[opt]

    # What events is this module interested in for input
    def watchedEvents(self):
        return ["DOMAIN_NAME", "LINKED_URL_EXTERNAL"]

    # What events this module produces
    def producedEvents(self):
        return ["CLOUD_STORAGE_BUCKET", "CLOUD_STORAGE_BUCKET_OPEN"]

    def checkSite(self, url):
        res = self.sf.fetchUrl(url, timeout=10, useragent="SpiderFoot", noLog=True)

        if not res['content']:
            return

        if "NoSuchBucket" in res['content']:
            self.debug(f"Not a valid bucket: {url}")
            return

        # Bucket found
        if res['code'] in ["301", "302", "200"]:
            # Bucket has files
            if "ListBucketResult" in res['content']:
                with self.lock:
                    self.s3results[url] = res['content'].count("<Key>")
            else:
                # Bucket has no files
                with self.lock:
                    self.s3results[url] = 0

    def threadSites(self, siteList):
        self.s3results = dict()
        running = True
        t = []

        for i, site in enumerate(siteList):
            if self.checkForStop():
                return False

            self.info("Spawning thread to check bucket: " + site)
            tname = str(random.SystemRandom().randint(0, 999999999))
            t.append(threading.Thread(name='thread_sfp_s3buckets_' + tname,
                                      target=self.checkSite, args=(site,)))
            t[i].start()

        # Block until all threads are finished
        while running:
            found = False
            for rt in threading.enumerate():
                if rt.name.startswith("thread_sfp_s3buckets_"):
                    found = True

            if not found:
                running = False

            time.sleep(0.25)

        # Return once the scanning has completed
        return self.s3results

    def batchSites(self, sites):
        i = 0
        res = list()
        siteList = list()

        for site in sites:
            if i >= self.opts['_maxthreads']:
                data = self.threadSites(siteList)
                if data is None:
                    return res

                for ret in list(data.keys()):
                    if data[ret]:
                        # bucket:filecount
                        res.append(f"{ret}:{data[ret]}")
                i = 0
                siteList = list()

            siteList.append(site)
            i += 1

        return res

    # Handle events sent to this module
    def handleEvent(self, event):
        eventName = event.eventType
        srcModuleName = event.module
        eventData = event.data

        if eventData in self.results:
            return

        self.results[eventData] = True

        self.debug(f"Received event, {eventName}, from {srcModuleName}")

        if eventName == "LINKED_URL_EXTERNAL":
            if ".amazonaws.com" in eventData:
                b = self.sf.urlFQDN(eventData)
                if b in self.opts['endpoints']:
                    try:
                        b += "/" + eventData.split(b + "/")[1].split("/")[0]
                    except Exception:
                        # Not a proper bucket path
                        return
                evt = SpiderFootEvent("CLOUD_STORAGE_BUCKET", b, self.__name__, event)
                self.notifyListeners(evt)
            return

        targets = [eventData.replace('.', '')]
        kw = self.sf.domainKeyword(eventData, self.opts['_internettlds'])
        if kw:
            targets.append(kw)

        urls = list()
        for t in targets:
            for e in self.opts['endpoints'].split(','):
                suffixes = [''] + self.opts['suffixes'].split(',')
                for s in suffixes:
                    if self.checkForStop():
                        return

                    b = t + s + "." + e
                    url = "https://" + b
                    urls.append(url)

        # Batch the scans
        ret = self.batchSites(urls)
        for b in ret:
            bucket = b.split(":")
            evt = SpiderFootEvent("CLOUD_STORAGE_BUCKET", bucket[0] + ":" + bucket[1], self.__name__, event)
            self.notifyListeners(evt)
            if bucket[2] != "0":
                bucketname = bucket[1].replace("//", "")
                evt = SpiderFootEvent("CLOUD_STORAGE_BUCKET_OPEN", bucketname + ": " + bucket[2] + " files found.",
                                      self.__name__, evt)
                self.notifyListeners(evt)

# End of sfp_s3bucket class


text:
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username
        self.email = email

    def __repr__(self):
        return '<User %r>' % self.username


text:
package com.alibaba.csp.sentinel.demo.dubbo.demo2;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ProtocolConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.spring.context.annotation.DubboComponentScan;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Eric Zhao
 */
@Configuration
@DubboComponentScan("com.alibaba.csp.sentinel.demo.dubbo.demo2")
public class ProviderConfiguration {

    @Bean
    public ApplicationConfig applicationConfig() {
        ApplicationConfig applicationConfig = new ApplicationConfig();
        applicationConfig.setName("demo-provider");
        return applicationConfig;
    }

    @Bean
    public RegistryConfig registryConfig() {
        RegistryConfig registryConfig = new RegistryConfig();
        registryConfig.setAddress("multicast://224.5.6.7:1234");
        return registryConfig;
    }

    @Bean
    public ProtocolConfig protocolConfig() {
        ProtocolConfig protocolConfig = new ProtocolConfig();
        protocolConfig.setName("dubbo");
        protocolConfig.setPort(25758);
        return protocolConfig;
    }
}


text:
<preference-headers xmlns:android="http://schemas.android.com/apk/res/android">

    <header
        android:fragment="com.fbs.rabbitears.activities.Settings$FeedItem"
        android:title="@string/pref_header_feed_item" />

</preference-headers>


text:
typedef struct SourceLoc
{
	char *filename;
	u32 line;
	u32 column;
} SourceLoc;

typedef enum ErrorLevel
{
	WARNING,
	ERROR,
} ErrorLevel;

void issue_diagnostic(ErrorLevel err_level, SourceLoc *context, char *fmt, ...);
void issue_error(SourceLoc *context, char *fmt, ...);
void issue_warning(SourceLoc *context, char *fmt, ...);

#endif


text:
'use strict';

/**
 * @ngdoc overview
 * @name androidNewTestAppApp
 * @description
 * # androidNewTestAppApp
 *
 * Main module of the application.
 */
angular
  .module('androidNewTestAppApp', [
    'ngAnimate',
    'ngCookies',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch',
    'ngCordova'
  ])
  .config(function ($routeProvider) {
      $routeProvider
          .when('/', {
              templateUrl: 'views/main.html',
              controller: 'MainCtrl',
              controllerAs: 'main'
          })
          .when('/weighMe', {
              templateUrl: 'views/weigh-me.html',
              controller: 'WeighMeCtrl',
              controllerAs: 'weighMe'
          })
          .when('/dashboard', {
              templateUrl: 'views/dashboard.html',
              controller: 'DashboardCtrl',
              controllerAs: 'dashboard'
          })
          .when('/settings', {
              templateUrl: 'views/settings.html',
              controller: 'SettingsCtrl',
              controllerAs: 'settings'
          })
          .when('/contactUs', {
              templateUrl: 'views/contact-us.html',
              controller: 'ContactUsCtrl',
              controllerAs: 'contactUs'
          })
          .otherwise({
              redirectTo: '/'
          });
  });

var PhoneGapInit = function () {
    this.boot = function () {
        angular.bootstrap(document, ['androidNewTestAppApp']);
    };

    if (window.phonegap !== undefined) {
        document.addEventListener('deviceready', function() {
            this.boot();
        });
    } else {
        console.log('PhoneGap not found, booting Angular manually');
        this.boot();
    }
};

angular.element(document).ready(function() {
    new PhoneGapInit();
});


text:
layout: page
title: Invisible Cities
date: 2016-03-01
tags: [books]
share: false
---

A collection of prose poems (short stories?) by Italo Calvino. Some describe it
as a novel, but that it is certainly not. I have enjoyed many of them, more
than the few excerpts below would suggest.

Although I've read Calvino before (*The Castle of Crossed Destinies* in
college), I picked it up this collection because of Tufte's *Envisioning
Information*.  In it, Calvino is quoted as writing that a city consists of,

> relationships between the measurements of its space and the events of its
> past: the height of the lamp-post and the distance from the ground of
> a hanged usurper's swaying feet; the line strung from the lamp-post to the
> railing opposite and the festoons that decorate the course of the queen's
> nuptial procession; the height of that railing and the leap of the adulterer
> who climbed over it at dawn; the tilt of a guttering cat's progress along it
> as he slips into the same window; the firing range of a gunboat which has
> suddenly appeared beyond the cape and the bomb that destroys the guttering;
> the rips in the fishnet and the three old men seated on the dock mending nets
> and telling each other for the hundredth time the story of the gunboat of the
> usurper, who some say was the queen's illegitimate son, abandoned in his
> swaddling clothes there on the dock.

There are many other arresting passages; for example, after a city's fall,

> in marble funerary urns they planted basil; wrought-iron gratings torn from the
> harem windows were used for roasting cat-meat on fires of inlaid wood.
>
> — p. 106

But what I most enjoyed was the short fable of bridges and stones:

> Marco Polo describes a bridge, stone by stone.
>
> "But which is the stone that supports the bridge?" Kublai Khan asks.
>
> "The bridge is not supported by one stone or another," Marco answers, "but by
> the line of the arch that they form."
>
> Kublai Khan remains silent, reflecting. Then he asks: "Why do you speak to me
> of the stones? Is is only the arch that matters to me."
>
> Polo answers: "Without the stones there is no arch."
>
> — p. 82

I think this is a good metaphor for social science. One is ultimately
interested in learning something about human nature and the forces that shape
the sweep of history. But to do so, one needs to study the particular:
understanding of the big is built from the study of the small, "without the
stones there is no arch."

Yet, as Kublai says, the stones are not interesting in themselves. This reminds
me of a recent post by Alex Tabarrok, criticizing a psychology study that
failed an (approximate) replication:

> In my view, Gilbert et al. are caught on the horns of a dilemma. If the
> studies don't replicate they aren't interesting and if the studies replicate
> but only under extremely precise conditions they also aren't interesting. We
> are interested in general features of the human condition not in descriptions
> of the choices that 75 female and 19 male Israeli students made at
> a particular point in time. Moreover, if changes in wording matter then
> surely so does the fact that the original study was on Israeli's in 2008 and
> the replication used Americans in 2013 (a lot has changed over these years!)
> and so must also a hundred other differences. But if so, what's the point?
>
> — Marginal Revolution: What is Replication


text:
package com.intellij.util.xml.ui;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.ui.UserActivityListener;
import com.intellij.util.Alarm;

public class CommitablePanelUserActivityListener implements UserActivityListener, Disposable {
  private final Committable myPanel;
  private final Project myProject;
  private final Alarm myAlarm = new Alarm();
  private boolean myApplying;

  public CommitablePanelUserActivityListener(Project project) {
    this(null, project);
  }

  public CommitablePanelUserActivityListener(final Committable panel, Project project) {
    myPanel = panel;
    myProject = project;
  }

  @Override
  final public void stateChanged() {
    if (myApplying) return;
    cancel();
    cancelAllRequests();
    myAlarm.addRequest(() -> {
      myApplying = true;
      cancel();
      try {
        applyChanges();
      }
      finally {
        myApplying = false;
      }
    }, 717);
  }

  private static void cancel() {
    final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
    if (indicator != null) {
      indicator.cancel();
    }
  }

  protected void applyChanges() {
    if (myPanel != null) {
      commit(myPanel);
    }
  }

  protected final void commit(final Committable panel) {
    ServiceManager.getService(getProject(), CommittableUtil.class).commit(panel);
  }

  protected final Project getProject() {
    return myProject;
  }

  public final boolean isWaiting() {
    return !myAlarm.isEmpty();
  }

  public final void cancelAllRequests() {
    myAlarm.cancelAllRequests();
  }

  @Override
  public void dispose() {
    cancelAllRequests();
  }
}


text:
FROM scratch

ADD /bin/app /app

ENTRYPOINT ["/app"]


text:
layout: page
title: Land Solutions Trade Fair
date: 2016-05-24
author: Megan Wells
tags: weekly links, java
status: published
summary: Pellentesque auctor lorem mollis tortor.
banner: images/banner/people.jpg
booking:
  startDate: 07/26/2018
  endDate: 07/29/2018
  ctyhocn: JHWNKHX
  groupCode: LSTF
published: true
---
Pellentesque imperdiet congue sem posuere feugiat. Aenean eget ultricies sapien, vel efficitur nunc. Integer consectetur tristique turpis imperdiet ornare. Vestibulum ultrices vestibulum lacus in sodales. Etiam imperdiet eu ipsum vel porttitor. Donec vitae imperdiet nisl, quis consequat eros. Praesent et est semper, ornare mauris fringilla, cursus sapien. Maecenas maximus efficitur eleifend. Pellentesque volutpat ex in mauris interdum tristique. Sed placerat posuere erat, ut porttitor eros facilisis sit amet. Etiam lacinia ligula vitae justo tempor accumsan.
Phasellus molestie auctor dolor, ac imperdiet ligula imperdiet dapibus. Proin vel tristique sem. Donec fringilla volutpat condimentum. Morbi magna sem, gravida non eleifend accumsan, hendrerit eu est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed imperdiet arcu eu orci accumsan commodo. Sed nec rhoncus est, quis mattis nisl. Praesent nec consectetur est. Praesent at tellus ipsum. Cras ullamcorper ac lectus sit amet auctor. Aliquam erat volutpat. In ornare velit vitae lorem mollis, vel ultricies lacus ultrices.

* Aliquam et elit ut leo bibendum pellentesque eget ut ipsum
* Suspendisse sit amet eros eget lectus tempus euismod posuere eu lorem.

Duis id tellus vitae dui efficitur imperdiet. Phasellus tempus porttitor nunc, ut vestibulum enim dictum quis. Vestibulum dapibus risus ac enim congue, ac fermentum ligula volutpat. Proin ac nibh quis nisi posuere ullamcorper sit amet quis orci. Integer magna nisl, ultricies eget tellus non, posuere fermentum dolor. Nunc ut orci sit amet massa convallis vehicula eu at nisl. Suspendisse id nisi nec dolor tristique condimentum. Mauris tempus nisl nec condimentum feugiat. Vestibulum feugiat pharetra enim quis feugiat. Phasellus eget tincidunt urna, iaculis maximus nibh.


text:
<?php

use yii\helpers\Html;
use kartik\widgets\ActiveForm;
use kartik\builder\Form;

use kartik\widgets\FileInput;

/* @var $this yii\web\View */
/* @var $model frontend\models\Organization */
/* @var $form yii\widgets\ActiveForm */
?>

<?php
$title = isset($model->filename) && !empty($model->filename) ? $model->filename : 'Avatar';
$pluginOptions = ($title === 'Avatar') ? [
            'overwriteInitial'=>true,
        ] :  [
            'overwriteInitial'=>true,
            'initialPreview'=>[
                Html::img("{$model->getImageFile()}", ['class'=>'file-preview-image', 'alt'=>"{$title}", 'title'=>"{$title}"]),
            ],
        ];

$form = ActiveForm::begin(['type'=>ActiveForm::TYPE_HORIZONTAL, 'options' => ['enctype' => 'multipart/form-data'], 'formConfig' => ['showErrors' => true]]);
echo Form::widget([
    'model'=>$model,
    'form'=>$form,
    'attributes'=>[
        'name'=>['type'=>Form::INPUT_TEXT, 'options'=>['placeholder'=>'Enter org name...']],
        'acronym'=>['type'=>Form::INPUT_TEXT, 'options'=>['placeholder'=>'Enter acronym...']],
        'org_type_id'=>['label' => 'Org Type', 'type'=>Form::INPUT_WIDGET,
            'widgetClass'=>'\kartik\widgets\Select2',
            'options'=>['data' => \frontend\models\OrgType::getTypes(), 'options'=>['placeholder'=>'Enter Org Type...']]],
        'nature'=>['type'=>Form::INPUT_TEXTAREA, 'options'=>['placeholder'=>'Enter nature...']],
        'image'=>['type'=>Form::INPUT_WIDGET,
            'widgetClass'=>'\kartik\widgets\FileInput',
            'options' => ['options' => ['accept' => 'image/*'],
        'pluginOptions' => [
            'overwriteInitial'=>true,
            'initialPreview'=>[
                Html::img("{$model->getImageFile()}", ['class'=>'file-preview-image', 'alt'=>"{$title}", 'title'=>"{$title}"]),
            ],
        ]]
        ],
        'actions'=>['type'=>Form::INPUT_RAW,
            'value'=>
                    '

' .
                    Html::resetButton('Reset', ['class'=>'btn btn-default']) .
                    Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['align' => 'inline', 'class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary'])
                    . '

'
        ],]
]);
ActiveForm::end();
?>


text:
/* jshint latedef:false */
/* jshint forin:false */
/* jshint noempty:false */

'use strict';

const msRest = require('ms-rest');
const ServiceClient = msRest.ServiceClient;

const models = require('./models');
const operations = require('./operations');

/**
 * @class
 * Initializes a new instance of the AutoRestRFC1123DateTimeTestService class.
 * @constructor
 *
 * @param {string} [baseUri] - The base URI of the service.
 *
 * @param {object} [options] - The parameter options
 *
 * @param {Array} [options.filters] - Filters to be added to the request pipeline
 *
 * @param {object} [options.requestOptions] - Options for the underlying request object
 * {@link https://github.com/request/request#requestoptions-callback Options doc}
 *
 * @param {boolean} [options.noRetryPolicy] - If set to true, turn off default retry policy
 *
 */
class AutoRestRFC1123DateTimeTestService extends ServiceClient {
  constructor(baseUri, options) {

    if (!options) options = {};

    super(null, options);

    this.baseUri = baseUri;
    if (!this.baseUri) {
      this.baseUri = 'https://localhost';
    }

    let packageInfo = this.getPackageJsonInfo(__dirname);
    this.addUserAgentInfo(`${packageInfo.name}/${packageInfo.version}`);
    this.datetimerfc1123 = new operations.Datetimerfc1123(this);
    this.models = models;
    msRest.addSerializationMixin(this);
  }

}

module.exports = AutoRestRFC1123DateTimeTestService;