text:
import * as net from 'net';
import * as os from 'os';
import * as path from 'path';
import * as protocol from '../omnisharp/protocol';
import * as serverUtils from "../omnisharp/utils";
import * as utils from '../common';
import * as vscode from 'vscode';
import AbstractProvider from './abstractProvider';
import { DebuggerEventsProtocol } from '../coreclr-debug/debuggerEventsProtocol';
import { OmniSharpServer } from '../omnisharp/server';
import { TestExecutionCountReport, ReportDotNetTestResults, DotNetTestRunStart, DotNetTestMessage, DotNetTestRunFailure, DotNetTestsInClassRunStart, DotNetTestDebugWarning, DotNetTestDebugProcessStart, DotNetTestDebugComplete, DotNetTestDebugStart, DotNetTestsInClassDebugStart, DotNetTestDebugStartFailure, DotNetTestRunInContextStart, DotNetTestDebugInContextStart } from '../omnisharp/loggingEvents';
import { EventStream } from '../EventStream';
import LaunchConfiguration from './launchConfiguration';
import Disposable from '../Disposable';
import CompositeDisposable from '../CompositeDisposable';
import { LanguageMiddlewareFeature } from '../omnisharp/LanguageMiddlewareFeature';

const TelemetryReportingDelay = 2 * 60 * 1000; // two minutes

export default class TestManager extends AbstractProvider {

    private _runCounts: { [testFrameworkName: string]: number };
    private _debugCounts: { [testFrameworkName: string]: number };
    private _telemetryIntervalId: NodeJS.Timer = undefined;
    private _eventStream: EventStream;

    constructor(server: OmniSharpServer, eventStream: EventStream, languageMiddlewareFeature: LanguageMiddlewareFeature) {
        super(server, languageMiddlewareFeature);
        this._eventStream = eventStream;

        // register commands
        let d1 = vscode.commands.registerCommand(
            'dotnet.test.run',
            async (testMethod, fileName, testFrameworkName) => this.runDotnetTest(testMethod, fileName, testFrameworkName));

        let d2 = vscode.commands.registerCommand(
            'dotnet.test.debug',
            async (testMethod, fileName, testFrameworkName) => this.debugDotnetTest(testMethod, fileName, testFrameworkName));

        let d4 = vscode.commands.registerCommand(
            'dotnet.classTests.run',
            async (className, methodsInClass, fileName, testFrameworkName) => this.runDotnetTestsInClass(className, methodsInClass, fileName, testFrameworkName));

        let d5 = vscode.commands.registerCommand(
            'dotnet.classTests.debug',
            async (className, methodsInClass, fileName, testFrameworkName) => this.debugDotnetTestsInClass(className, methodsInClass, fileName, testFrameworkName));

        let d6 = vscode.commands.registerTextEditorCommand(
            'dotnet.test.runTestsInContext',
            async (textEditor: vscode.TextEditor) => this._runDotnetTestsInContext(textEditor.document.fileName, textEditor.selection.active, textEditor.document.languageId));

        let d7 = vscode.commands.registerTextEditorCommand(
            'dotnet.test.debugTestsInContext',
            async (textEditor: vscode.TextEditor) => this._debugDotnetTestsInContext(textEditor.document.fileName, textEditor.document.uri, textEditor.selection.active, textEditor.document.languageId));

        this._telemetryIntervalId = setInterval(() =>
            this._reportTelemetry(), TelemetryReportingDelay);

        let d3 = new Disposable(() => {
            if (this._telemetryIntervalId !== undefined) {
                // Stop reporting telemetry
                clearInterval(this._telemetryIntervalId);
                this._telemetryIntervalId = undefined;
                this._reportTelemetry();
            }
        });

        this.addDisposables(new CompositeDisposable(d1, d2, d3, d4, d5, d6, d7));
    }

    private _recordRunRequest(testFrameworkName?: string): void {
        if (this._runCounts === undefined) {
            this._runCounts = {};
        }

        if (testFrameworkName === undefined) {
            testFrameworkName = 'context';
        }

        let count = this._runCounts[testFrameworkName];

        if (!count) {
            count = 1;
        }
        else {
            count += 1;
        }

        this._runCounts[testFrameworkName] = count;
    }

    private _recordDebugRequest(testFrameworkName?: string): void {
        if (this._debugCounts === undefined) {
            this._debugCounts = {};
        }

        if (testFrameworkName === undefined) {
            testFrameworkName = 'context';
        }

        let count = this._debugCounts[testFrameworkName];

        if (!count) {
            count = 1;
        }
        else {
            count += 1;
        }

        this._debugCounts[testFrameworkName] = count;
    }

    private _reportTelemetry(): void {
        this._eventStream.post(new TestExecutionCountReport(this._debugCounts, this._runCounts));
        this._runCounts = undefined;
        this._debugCounts = undefined;
    }

    private async _saveDirtyFiles(): Promise<boolean> {
        return Promise.resolve(
            vscode.workspace.saveAll(/*includeUntitled*/ false));
    }

    private async _runTest(fileName: string, testMethod: string, runSettings: string, testFrameworkName: string, targetFrameworkVersion: string, noBuild: boolean): Promise<protocol.V2.DotNetTestResult[]> {
        const request: protocol.V2.RunTestRequest = {
            FileName: fileName,
            MethodName: testMethod,
            RunSettings: runSettings,
            TestFrameworkName: testFrameworkName,
            TargetFrameworkVersion: targetFrameworkVersion,
            NoBuild: noBuild
        };

        try {
            let response = await serverUtils.runTest(this._server, request);
            return response.Results;
        }
        catch (error) {
            return undefined;
        }
    }

    private async _recordRunAndGetFrameworkVersion(fileName: string, testFrameworkName?: string): Promise<string> {

        await this._saveDirtyFiles();
        this._recordRunRequest(testFrameworkName);
        let projectInfo: protocol.ProjectInformationResponse;
        try {
            projectInfo = await serverUtils.requestProjectInformation(this._server, { FileName: fileName });
        }
        catch (error) {
            return undefined;
        }

        let targetFrameworkVersion: string;

        if (projectInfo.MsBuildProject) {
            targetFrameworkVersion = projectInfo.MsBuildProject.TargetFramework;
        }
        else {
            throw new Error('Expected project.json or .csproj project.');
        }

        return targetFrameworkVersion;
    }

    public async discoverTests(fileName: string, testFrameworkName: string, noBuild: boolean): Promise<protocol.V2.TestInfo[]> {

        let targetFrameworkVersion = await this._recordRunAndGetFrameworkVersion(fileName, testFrameworkName);
        let runSettings = vscode.workspace.getConfiguration('omnisharp').get<string>('testRunSettings');

        const request: protocol.V2.DiscoverTestsRequest = {
            FileName: fileName,
            RunSettings: runSettings,
            TestFrameworkName: testFrameworkName,
            TargetFrameworkVersion: targetFrameworkVersion,
            NoBuild: noBuild
        };

        try {
            let response = await serverUtils.discoverTests(this._server, request);
            return response.Tests;
        }
        catch (error) {
            return undefined;
        }
    }

    private _getRunSettings(): string | undefined {
        return vscode.workspace.getConfiguration('omnisharp').get<string>('testRunSettings');
    }

    public async runDotnetTest(testMethod: string, fileName: string, testFrameworkName: string, noBuild: boolean = false) {

        this._eventStream.post(new DotNetTestRunStart(testMethod));

        const listener = this._server.onTestMessage(e => {
            this._eventStream.post(new DotNetTestMessage(e.Message));
        });

        let targetFrameworkVersion = await this._recordRunAndGetFrameworkVersion(fileName, testFrameworkName);
        let runSettings = this._getRunSettings();

        try {
            let results = await this._runTest(fileName, testMethod, runSettings, testFrameworkName, targetFrameworkVersion, noBuild);
            this._eventStream.post(new ReportDotNetTestResults(results));
        }
        catch (reason) {
            this._eventStream.post(new DotNetTestRunFailure(reason));
        }
        finally {
            listener.dispose();
        }
    }

    public async runDotnetTestsInClass(className: string, methodsInClass: string[], fileName: string, testFrameworkName: string, noBuild: boolean = false) {

        //to do: try to get the class name here
        this._eventStream.post(new DotNetTestsInClassRunStart(className));

        const listener = this._server.onTestMessage(e => {
            this._eventStream.post(new DotNetTestMessage(e.Message));
        });

        let targetFrameworkVersion = await this._recordRunAndGetFrameworkVersion(fileName, testFrameworkName);
        let runSettings = this._getRunSettings();

        try {
            let results = await this._runTestsInClass(fileName, runSettings, testFrameworkName, targetFrameworkVersion, methodsInClass, noBuild);
            this._eventStream.post(new ReportDotNetTestResults(results));
        }
        catch (reason) {
            this._eventStream.post(new DotNetTestRunFailure(reason));
        }
        finally {
            listener.dispose();
        }
    }

    private async _runTestsInClass(fileName: string, runSettings: string, testFrameworkName: string, targetFrameworkVersion: string, methodsToRun: string[], noBuild: boolean): Promise<protocol.V2.DotNetTestResult[]> {
        const request: protocol.V2.RunTestsInClassRequest = {
            FileName: fileName,
            RunSettings: runSettings,
            TestFrameworkName: testFrameworkName,
            TargetFrameworkVersion: targetFrameworkVersion,
            MethodNames: methodsToRun,
            NoBuild: noBuild
        };

        let response = await serverUtils.runTestsInClass(this._server, request);
        return response.Results;
    }

    private async _runDotnetTestsInContext(fileName: string, active: vscode.Position, editorLangId: string) {
        if (editorLangId !== "csharp") {
            this._eventStream.post(new DotNetTestMessage(`${vscode.workspace.asRelativePath(fileName, false)} is not a C# file, cannot run tests`));
            return;
        }

        this._eventStream.post(new DotNetTestRunInContextStart(vscode.workspace.asRelativePath(fileName, false), active.line, active.character));

        const listener = this._server.onTestMessage(e => {
            this._eventStream.post(new DotNetTestMessage(e.Message));
        });

        let targetFrameworkVersion = await this._recordRunAndGetFrameworkVersion(fileName);
        let runSettings = this._getRunSettings();

        const request: protocol.V2.RunTestsInContextRequest = {
            FileName: fileName,
            Line: active.line,
            Column: active.character,
            RunSettings: runSettings,
            TargetFrameworkVersion: targetFrameworkVersion
        };

        try {
            let response = await serverUtils.runTestsInContext(this._server, request);
            if (response.ContextHadNoTests) {
                this._eventStream.post(new DotNetTestMessage(response.Failure));
            }
            else if (!response.Pass && response.Results === null) {
                this._eventStream.post(new DotNetTestRunFailure(response.Failure));
            }
            else {
                this._eventStream.post(new ReportDotNetTestResults(response.Results));
            }
        }
        catch (reason) {
            this._eventStream.post(new DotNetTestRunFailure(reason));
        }
        finally {
            listener.dispose();
        }
    }

    private _createLaunchConfiguration(program: string, args: string, cwd: string, debuggerEventsPipeName: string) {
        let debugOptions = vscode.workspace.getConfiguration('csharp').get('unitTestDebuggingOptions');

        // Get the initial set of options from the workspace setting
        let result: any;
        if (typeof debugOptions === "object") {
            // clone the options object to avoid changing it
            result = JSON.parse(JSON.stringify(debugOptions));
        } else {
            result = {};
        }

        let launchConfiguration: LaunchConfiguration = {
            ...result,
            type: result.type || "coreclr",
            name: ".NET Test Launch",
            request: "launch",
            debuggerEventsPipeName: debuggerEventsPipeName,
            program: program,
            args: args,
            cwd: cwd
        };

        // Now fill in the rest of the options
        return launchConfiguration;
    }

    private async _getLaunchConfigurationForVSTest(
        fileName: string,
        testMethod: string,
        runSettings: string,
        testFrameworkName: string,
        targetFrameworkVersion: string,
        debugEventListener: DebugEventListener,
        noBuild: boolean): Promise<LaunchConfiguration> {

        // Listen for test messages while getting start info.
        const listener = this._server.onTestMessage(e => {
            this._eventStream.post(new DotNetTestMessage(e.Message));
        });

        const request: protocol.V2.DebugTestGetStartInfoRequest = {
            FileName: fileName,
            MethodName: testMethod,
            RunSettings: runSettings,
            TestFrameworkName: testFrameworkName,
            TargetFrameworkVersion: targetFrameworkVersion,
            NoBuild: noBuild
        };

        try {
            let response = await serverUtils.debugTestGetStartInfo(this._server, request);
            return this._createLaunchConfiguration(
                response.FileName,
                response.Arguments,
                response.WorkingDirectory,
                debugEventListener.pipePath());
        }
        finally {
            listener.dispose();
        }
    }

    private async _recordDebugAndGetDebugValues(fileName: string, testFrameworkName?: string) {
        await this._saveDirtyFiles();
        this._recordDebugRequest(testFrameworkName);
        let projectInfo: protocol.ProjectInformationResponse;
        try {
            projectInfo = await serverUtils.requestProjectInformation(this._server, { FileName: fileName });
        }
        catch (error) {
            return undefined;
        }

        let debugEventListener: DebugEventListener = null;
        let targetFrameworkVersion: string;

        if (projectInfo.MsBuildProject) {
            targetFrameworkVersion = projectInfo.MsBuildProject.TargetFramework;
            debugEventListener = new DebugEventListener(fileName, this._server, this._eventStream);
            debugEventListener.start();
        }
        else {
            throw new Error('Expected .csproj project.');
        }

        return { debugEventListener, targetFrameworkVersion };
    }

    public async debugDotnetTest(testMethod: string, fileName: string, testFrameworkName: string, noBuild: boolean = false) {
        // We support to styles of 'dotnet test' for debugging: The legacy 'project.json' testing, and the newer csproj support
        // using VS Test. These require a different level of communication.

        this._eventStream.post(new DotNetTestDebugStart(testMethod));

        let { debugEventListener, targetFrameworkVersion } = await this._recordDebugAndGetDebugValues(fileName, testFrameworkName);
        let runSettings = this._getRunSettings();

        try {
            let config = await this._getLaunchConfigurationForVSTest(fileName, testMethod, runSettings, testFrameworkName, targetFrameworkVersion, debugEventListener, noBuild);
            const workspaceFolder = vscode.workspace.getWorkspaceFolder(vscode.Uri.file(fileName));
            return vscode.debug.startDebugging(workspaceFolder, config);
        }
        catch (reason) {
            this._eventStream.post(new DotNetTestDebugStartFailure(reason));
            if (debugEventListener !== null) {
                debugEventListener.close();
            }
        }
    }

    public async debugDotnetTestsInClass(className: string, methodsToRun: string[], fileName: string, testFrameworkName: string, noBuild: boolean = false) {

        this._eventStream.post(new DotNetTestsInClassDebugStart(className));

        let { debugEventListener, targetFrameworkVersion } = await this._recordDebugAndGetDebugValues(fileName, testFrameworkName);
        let runSettings = this._getRunSettings();

        try {
            let config = await this._getLaunchConfigurationForVSTestClass(fileName, methodsToRun, runSettings, testFrameworkName, targetFrameworkVersion, debugEventListener, noBuild);
            const workspaceFolder = vscode.workspace.getWorkspaceFolder(vscode.Uri.file(fileName));
            return vscode.debug.startDebugging(workspaceFolder, config);
        }
        catch (reason) {
            this._eventStream.post(new DotNetTestDebugStartFailure(reason));
            if (debugEventListener != null) {
                debugEventListener.close();
            }
        }
    }

    private async _debugDotnetTestsInContext(fileName: string, fileUri: vscode.Uri, active: vscode.Position, editorLangId: string) {
        if (editorLangId !== "csharp") {
            this._eventStream.post(new DotNetTestMessage(`${vscode.workspace.asRelativePath(fileName, false)} is not a C# file, cannot run tests`));
            return;
        }

        this._eventStream.post(new DotNetTestDebugInContextStart(vscode.workspace.asRelativePath(fileName, false), active.line, active.character));

        let { debugEventListener, targetFrameworkVersion } = await this._recordDebugAndGetDebugValues(fileName);

        let runSettings = this._getRunSettings();

        try {
            let config = await this._getLaunchConfigurationForVSTestInContext(fileName, active.line, active.character, runSettings, targetFrameworkVersion, debugEventListener);
            if (config === null) {
                return;
            }

            const workspaceFolder = vscode.workspace.getWorkspaceFolder(fileUri);
            return vscode.debug.startDebugging(workspaceFolder, config);
        }
        catch (reason) {
            this._eventStream.post(new DotNetTestRunFailure(reason));
            if (debugEventListener !== null) {
                debugEventListener.close();
            }
        }
    }

    private async _getLaunchConfigurationForVSTestClass(
        fileName: string,
        methodsToRun: string[],
        runSettings: string,
        testFrameworkName: string,
        targetFrameworkVersion: string,
        debugEventListener: DebugEventListener,
        noBuild: boolean): Promise<LaunchConfiguration> {

        const listener = this._server.onTestMessage(e => {
            this._eventStream.post(new DotNetTestMessage(e.Message));
        });

        const request: protocol.V2.DebugTestClassGetStartInfoRequest = {
            FileName: fileName,
            MethodNames: methodsToRun,
            RunSettings: runSettings,
            TestFrameworkName: testFrameworkName,
            TargetFrameworkVersion: targetFrameworkVersion,
            NoBuild: noBuild
        };

        try {
            let response = await serverUtils.debugTestClassGetStartInfo(this._server, request);
            return this._createLaunchConfiguration(response.FileName, response.Arguments, response.WorkingDirectory, debugEventListener.pipePath());
        }
        finally {
            listener.dispose();
        }
    }

    private async _getLaunchConfigurationForVSTestInContext(
        fileName: string,
        line: number,
        column: number,
        runSettings: string,
        targetFrameworkVersion: string,
        debugEventListener: DebugEventListener): Promise<LaunchConfiguration | null> {

        const listener = this._server.onTestMessage(e => {
            this._eventStream.post(new DotNetTestMessage(e.Message));
        });

        const request: protocol.V2.DebugTestsInContextGetStartInfoRequest = {
            FileName: fileName,
            Line: line,
            Column: column,
            RunSettings: runSettings,
            TargetFrameworkVersion: targetFrameworkVersion
        };

        try {
            let response = await serverUtils.debugTestsInContextGetStartInfo(this._server, request);
            if (!response.Succeeded) {
                if (response.ContextHadNoTests) {
                    this._eventStream.post(new DotNetTestMessage(response.FailureReason));
                }
                else {
                    this._eventStream.post(new DotNetTestRunFailure(response.FailureReason));
                }

                return null;
            }

            return this._createLaunchConfiguration(response.FileName, response.Arguments, response.WorkingDirectory, debugEventListener.pipePath());
        }
        finally {
            listener.dispose();
        }
    }
}

class DebugEventListener {
    static s_activeInstance: DebugEventListener = null;
    _fileName: string;
    _server: OmniSharpServer;
    _pipePath: string;
    _eventStream: EventStream;

    _serverSocket: net.Server;
    _isClosed: boolean = false;

    constructor(fileName: string, server: OmniSharpServer, eventStream: EventStream) {
        this._fileName = fileName;
        this._server = server;
        this._eventStream = eventStream;

        if (os.platform() === 'win32') {
            this._pipePath = "\\\\.\\pipe\\Microsoft.VSCode.CSharpExt.TestDebugEvents" + process.pid;
        }
        else {
            let tmpdir = utils.getUnixTempDirectory();
            this._pipePath = path.join(tmpdir, "ms-dotnettools.csharp-tde-" + process.pid);
        }
    }

    public async start(): Promise<void> {

        // We use our process id as part of the pipe name, so if we still somehow have an old instance running, close it.
        if (DebugEventListener.s_activeInstance !== null) {
            DebugEventListener.s_activeInstance.close();
        }

        DebugEventListener.s_activeInstance = this;

        this._serverSocket = net.createServer((socket: net.Socket) => {
            socket.on('data', (buffer: Buffer) => {
                let event: DebuggerEventsProtocol.DebuggerEvent;
                try {
                    event = DebuggerEventsProtocol.decodePacket(buffer);
                }
                catch (e) {
                    this._eventStream.post(new DotNetTestDebugWarning("Invalid event received from debugger"));
                    return;
                }

                switch (event.eventType) {
                    case DebuggerEventsProtocol.EventType.ProcessLaunched:
                        let processLaunchedEvent = <DebuggerEventsProtocol.ProcessLaunchedEvent>(event);
                        this._eventStream.post(new DotNetTestDebugProcessStart(processLaunchedEvent.targetProcessId));
                        this.onProcessLaunched(processLaunchedEvent.targetProcessId);
                        break;

                    case DebuggerEventsProtocol.EventType.DebuggingStopped:
                        this._eventStream.post(new DotNetTestDebugComplete());
                        this.onDebuggingStopped();
                        break;
                }
            });

            socket.on('end', () => {
                this.onDebuggingStopped();
            });
        });

        await this.removeSocketFileIfExists();
        return new Promise<void>((resolve, reject) => {
            let isStarted: boolean = false;
            this._serverSocket.on('error', (err: Error) => {
                if (!isStarted) {
                    reject(err.message);
                } else {
                    this._eventStream.post(new DotNetTestDebugWarning(`Communications error on debugger event channel. ${err.message}`));
                }
            });

            this._serverSocket.listen(this._pipePath, () => {
                isStarted = true;
                resolve();
            });
        });
    }

    public pipePath(): string {
        return this._pipePath;
    }

    public close() {
        if (this === DebugEventListener.s_activeInstance) {
            DebugEventListener.s_activeInstance = null;
        }

        if (this._isClosed) {
            return;
        }

        this._isClosed = true;

        if (this._serverSocket !== null) {
            this._serverSocket.close();
        }
    }

    private async onProcessLaunched(targetProcessId: number): Promise<void> {
        let request: protocol.V2.DebugTestLaunchRequest = {
            FileName: this._fileName,
            TargetProcessId: targetProcessId
        };

        const disposable = this._server.onTestMessage(e => {
            this._eventStream.post(new DotNetTestMessage(e.Message));
        });

        try {
            await serverUtils.debugTestLaunch(this._server, request);
        }
        finally {
            disposable.dispose();
        }
    }

    private onDebuggingStopped(): void {
        if (this._isClosed) {
            return;
        }

        let request: protocol.V2.DebugTestStopRequest = {
            FileName: this._fileName
        };
        try {
            serverUtils.debugTestStop(this._server, request);
            this.close();
        }
        catch (error) {
            return;
        }
    }

    private async removeSocketFileIfExists(): Promise<void> {
        if (os.platform() === 'win32') {
            // Win32 doesn't use the file system for pipe names
            return Promise.resolve();
        }
        else {
            return utils.deleteIfExists(this._pipePath);
        }
    }
}


text:
        {% if is_contact %}

{{ comments_count }}条留言

        {% else %}

{{ comments_count }}个评论

        {% endif %}

            {% for top_entry in top_comments %}
            {% set lastentry = top_comments|last %}

                                {{ top_entry.username }}

                            <time datetime="{{ top_entry.post_date|format_commenttime }}">{{ top_entry.post_date|format_commenttime }}</time>

                        {% if is_contact %}
                            {% if top_entry.username == fetch_admin().name%}
                            博主
                            {% endif %}
                        {% else %}
                            {% if top_entry.username == article.author.name %}
                            作者
                            {% endif %}
                        {% endif %}

{{ top_entry.content|safe }}

                {% for entry in get_article_comments(article_id, top_entry) %}

                                    {{ entry.username }}

                                <time datetime="{{ entry.post_date|format_commenttime }}">{{ entry.post_date|format_commenttime }}</time>

                        {% if is_contact %}
                            {% if entry.username == fetch_admin().name%}
                            博主
                            {% endif %}
                        {% else %}
                            {% if entry.username == article.author.name %}
                            作者
                            {% endif %}
                        {% endif %}

{{ entry.content|safe }}

                {% endfor %}
        {% endfor %}

redpajama_set_name: RedPajamaGithub


text:
A Java command line client for miscellaneous tools.

Version: ${my.release.version}

## Homepage / Download

Home for J-Utils is at:

https://webtools.leponceau.org

There you can find binaries and source code.

## Functionality

* github repositories listing and backup (uses command line git client by default, embedded jgit is available, too)
* recursive grep allowing to filter both file names (ant-style glob) and line patterns (regex)
* jenkins: re-queue all projects
* local maven repository search (class names and assets contained in jar files)
* transforms output of maven enforcer plugin's dependency conflict into a set of dependencies with unique versions
  to put into your dependencyManagement section. No more tedious version checking just to have determinate
  versions.
* Text(html)-2-image conversion with CSS support through CSS-BOX.

## Features

* Environment for easy addition of more functions, ie. command line parsing and help display.
* Functionality modules are detected by annotation scanning during compilation.

## Repository

https://github.com/jjYBdx4IL/misc


text:
'use strict';

/**
 * Subscription update details.
 *
 */
class SubscriptionUpdateParameters {
  /**
   * Create a SubscriptionUpdateParameters.
   * @member {string} [userId] User identifier path: /users/{uid}
   * @member {string} [productId] Product identifier path:
   * /products/{productId}
   * @member {date} [expirationDate] Subscription expiration date. The setting
   * is for audit purposes only and the subscription is not automatically
   * expired. The subscription lifecycle can be managed by using the `state`
   * property. The date conforms to the following format:
   * `yyyy-MM-ddTHH:mm:ssZ` as specified by the ISO 8601 standard.
   * @member {string} [displayName] Subscription name.
   * @member {string} [primaryKey] Primary subscription key.
   * @member {string} [secondaryKey] Secondary subscription key.
   * @member {string} [state] Subscription state. Possible states are * active
   * – the subscription is active, * suspended – the subscription is blocked,
   * and the subscriber cannot call any APIs of the product, * submitted – the
   * subscription request has been made by the developer, but has not yet been
   * approved or rejected, * rejected – the subscription request has been
   * denied by an administrator, * cancelled – the subscription has been
   * cancelled by the developer or administrator, * expired – the subscription
   * reached its expiration date and was deactivated. Possible values include:
   * 'suspended', 'active', 'expired', 'submitted', 'rejected', 'cancelled'
   * @member {string} [stateComment] Comments describing subscription state
   * change by the administrator.
   */
  constructor() {
  }

  /**
   * Defines the metadata of SubscriptionUpdateParameters
   *
   * @returns {object} metadata of SubscriptionUpdateParameters
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'SubscriptionUpdateParameters',
      type: {
        name: 'Composite',
        className: 'SubscriptionUpdateParameters',
        modelProperties: {
          userId: {
            required: false,
            serializedName: 'properties.userId',
            type: {
              name: 'String'
            }
          },
          productId: {
            required: false,
            serializedName: 'properties.productId',
            type: {
              name: 'String'
            }
          },
          expirationDate: {
            required: false,
            serializedName: 'properties.expirationDate',
            type: {
              name: 'DateTime'
            }
          },
          displayName: {
            required: false,
            serializedName: 'properties.displayName',
            type: {
              name: 'String'
            }
          },
          primaryKey: {
            required: false,
            serializedName: 'properties.primaryKey',
            constraints: {
              MaxLength: 256,
              MinLength: 1
            },
            type: {
              name: 'String'
            }
          },
          secondaryKey: {
            required: false,
            serializedName: 'properties.secondaryKey',
            constraints: {
              MaxLength: 256,
              MinLength: 1
            },
            type: {
              name: 'String'
            }
          },
          state: {
            required: false,
            serializedName: 'properties.state',
            type: {
              name: 'Enum',
              allowedValues: [ 'suspended', 'active', 'expired', 'submitted', 'rejected', 'cancelled' ]
            }
          },
          stateComment: {
            required: false,
            serializedName: 'properties.stateComment',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = SubscriptionUpdateParameters;


text:
<!doctype html>

	<meta charset="utf-8">

	<title>OneEngine Documentation - EngineThemes.com</title>

	<meta name="description" content="">
	<meta name="author" content="EngineThemes">
	<meta name="copyright" content="EngineThemes">
	<meta name="generator" content="Documenter v2.0 http://rxa.li/documenter">
	<meta name="date" content="2014-04-29T00:00:00+02:00">

	<link rel="stylesheet" href="assets/css/documenter_style.css" media="all">

	<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />

Start

INSTALLATION & SAMPLE DATA

USING PAGE-BUILDER BLOCKS

USING SECTION BLOCKS

ADDING HEADINGS FOR BLOCKS

ADDING CATEGORY ICONS

FOOTER SETTINGS

BLOG SETTINGS

Copyright EngineThemes 2014

		made with the Documenter v2.0

OneEngine Documentation

created: 04/29/2014

last updated: 05/13/2014

author: EngineThemes

homepage: http://www.enginethemes.com

contact: contact@enginethemes.com

INSTALLATION & SAMPLE DATA

			- Activating Theme

			- Installing Require Plugins

			- Importing Sample Data

			- Activating Header Menus

			- Set Static Frontpage

			- Importing Theme Options Sample

				- Sample Option Data Link: http://demo.enginethemes.com/oneengine/wp-admin/admin-ajax.php?action=redux_link_options&secret=2924531e9f964159351788dddd276c58

			- Sample Data: sample_data.xml locates in oneengine theme folder

USING PAGE-BUILDER BLOCKS

				Create a page using page builder

USING SECTION BLOCKS

				Create new block services

ADDING HEADINGS FOR BLOCKS

				- Adding heading title for each block.

ADDING CATEGORY ICONS

				- More than 369 Icons from FontAwesome.com

FOOTER SETTINGS

				Settings Up Footers

BLOG SETTINGS

				Setting Up For Blog Page


text:
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/RestaurantManagement"/>


text:
Team membership:  Matt Rosenlund (Captain) & Tom Nam (Mate)
Team conventions: Allman notation, markdown for changelog

$$

## *Version 1.*

Release Date: Mar 04, 2017

## Updated Components
for jobs  (Captain)

-	Changelog.md	(Captain)
-	Controllers	(Captain)
	-
-	Views
	-

## *Version 1.0*

Release Date: Mar 04, 2017

## Updated Components
for jobs 8,9,10 (Mate)

-	Changelog.md	(Mate)
-	controllers		(Mate)
	-	Views:			changed the makePrioritizedPanel function to include the action method for the form,
						added complete function to take care of the form completion functions
-	core			(Mate)
	-	MY_Controller:	added required caboose frameworks/components, added alerts for possible errors
-	views			(Mate)
	-	template:		added caboose substitution references, added alert reference
	-	template_sec.:	added caboose substitution references, added alert reference
	-	_alert:			created to add possible alert tags
	-	by_priority:	added form tags and checkboxes
	-	_menubar:		updated the roles to be uppercase in their links in order to make the forms for job 10 work
-	config			(Mate)
	-	config:			changed from using files to database
	-	autoload:		added caboose dependancies
-	data			(Mate)
	-	todo:			created a fresh sql file


text:
using UnityEngine;
using System.Collections;
using com.afroraydude.unity.firstgame.inner;

public class NewPlayerMovement : MonoBehaviour {
	public GameManager manager;

	//public Animator animator;
	public Rigidbody rigid;
	public string walkingStateName = "walking";

	public float moveSpeed;
	private float maxSpeed = 5f;
	public int deathCount;
	public float killY = -1.5f;
	public int up = 1;
	public int down = -1;
	public int left = -1;
	public int right = 1;

	public GameObject deathParticals;

	private Vector3 input;
	private Vector3 spawn;

	// Use this for initialization
	void Start () {
		rigid = rigid.GetComponent<Rigidbody> ();
		//animator = animator.GetComponent<Animator>();
		spawn = transform.position;
		manager = manager.GetComponent<GameManager>();
	}

	// Update is called once per frame
	void FixedUpdate ()
	{
		input = new Vector3 (Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
		if(rigid.velocity.magnitude < maxSpeed)
		{
			rigid.AddForce(input * moveSpeed);
			//animator.Play(walkingStateName);
		}
		if (transform.position.y <= killY)
		{
			Die ();
		}
	}

	void OnTriggerEnter(Collider other)
	{
		if (other.transform.tag == "Goal")
		{
			manager.CompleteLevel();

		}
		if (other.transform.tag == "Invisible") {
			Die();
		}

	}

	void OnCollisionEnter(Collision other)
	{
		if (other.transform.tag == "Enemy") {
			Die ();
		}
	}

	void Die() {
		deathCount += 1;
		Instantiate(deathParticals, transform.position, Quaternion.identity);
		transform.position = spawn;
	}
	public void Leave() {
		Application.LoadLevel (0);
	}
}


text:
<component name="libraryTable">
  <library name="Parse-1.9.4">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/MessagingTutorialSkeleton/libs/Parse-1.9.4.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
package com.qxcmp.web.view.modules.table;

public abstract class AbstractTableHeader extends AbstractTableSection {
}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/navigation_home"
            android:checked="true"
            android:icon="@drawable/ic_home_black_24dp"
            android:title="@string/nav_home" />
        <item
            android:id="@+id/navigation_icons"
            android:icon="@drawable/ic_view_module_black_24dp"
            android:title="@string/nav_icons" />
        <item
            android:id="@+id/navigation_apply"
            android:icon="@drawable/ic_input_black_24dp"
            android:title="@string/nav_apply" />
        <item
            android:id="@+id/navigation_wall"
            android:icon="@drawable/ic_wallpaper_black_24dp"
            android:title="@string/nav_wall" />
        <item
            android:id="@+id/navigation_req_icons"
            android:icon="@drawable/ic_question_answer_black_24dp"
            android:title="@string/nav_req_icons" />
    </group>
    <item
        android:id="@+id/navigation_subheader"
        android:title="@string/nav_others">
        <menu>
            <item
                android:id="@+id/navigation_about"
                android:title="@string/nav_about" />
        </menu>
    </item>
</menu>


text:
all::
	@echo === This demo is interactive: hit enter to move to next step
	./vw-demo


text:
var CombinedStream = require('combined-stream');
var util = require('util');
var path = require('path');
var http = require('http');
var https = require('https');
var parseUrl = require('url').parse;
var fs = require('fs');
var mime = require('mime-types');
var async = require('async');
var populate = require('./populate.js');

// Public API
module.exports = FormData;

// make it a Stream
util.inherits(FormData, CombinedStream);

/**
 * Create readable "multipart/form-data" streams.
 * Can be used to submit forms
 * and file uploads to other web applications.
 *
 * @constructor
 */
function FormData() {
    if (!(this instanceof FormData)) {
        throw new TypeError('Failed to construct FormData: Please use the _new_ operator, this object constructor cannot be called as a function.');
    }

    this._overheadLength = 0;
    this._valueLength = 0;
    this._lengthRetrievers = [];

    CombinedStream.call(this);
}

FormData.LINE_BREAK = '\r\n';
FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream';

FormData.prototype.append = function (field, value, options) {

    options = options || {};

    // allow filename as single option
    if (typeof options == 'string') {
        options = {filename: options};
    }

    var append = CombinedStream.prototype.append.bind(this);

    // all that streamy business can't handle numbers
    if (typeof value == 'number') {
        value = '' + value;
    }

    // https://github.com/felixge/node-form-data/issues/38
    if (util.isArray(value)) {
        // Please convert your array into string
        // the way web server expects it
        this._error(new Error('Arrays are not supported.'));
        return;
    }

    var header = this._multiPartHeader(field, value, options);
    var footer = this._multiPartFooter();

    append(header);
    append(value);
    append(footer);

    // pass along options.knownLength
    this._trackLength(header, value, options);
};

FormData.prototype._trackLength = function (header, value, options) {
    var valueLength = 0;

    // used w/ getLengthSync(), when length is known.
    // e.g. for streaming directly from a remote server,
    // w/ a known file a size, and not wanting to wait for
    // incoming file to finish to get its size.
    if (options.knownLength != null) {
        valueLength += +options.knownLength;
    } else if (Buffer.isBuffer(value)) {
        valueLength = value.length;
    } else if (typeof value === 'string') {
        valueLength = Buffer.byteLength(value);
    }

    this._valueLength += valueLength;

    // @check why add CRLF? does this account for custom/multiple CRLFs?
    this._overheadLength +=
        Buffer.byteLength(header) +
        FormData.LINE_BREAK.length;

    // empty or either doesn't have path or not an http response
    if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) )) {
        return;
    }

    // no need to bother with the length
    if (!options.knownLength) {
        this._lengthRetrievers.push(function (next) {

            if (value.hasOwnProperty('fd')) {

                // take read range into a account
                // `end` = Infinity –> read file till the end
                //
                // TODO: Looks like there is bug in Node fs.createReadStream
                // it doesn't respect `end` options without `start` options
                // Fix it when node fixes it.
                // https://github.com/joyent/node/issues/7819
                if (value.end != undefined && value.end != Infinity && value.start != undefined) {

                    // when end specified
                    // no need to calculate range
                    // inclusive, starts with 0
                    next(null, value.end + 1 - (value.start ? value.start : 0));

                    // not that fast snoopy
                } else {
                    // still need to fetch file size from fs
                    fs.stat(value.path, function (err, stat) {

                        var fileSize;

                        if (err) {
                            next(err);
                            return;
                        }

                        // update final size based on the range options
                        fileSize = stat.size - (value.start ? value.start : 0);
                        next(null, fileSize);
                    });
                }

                // or http response
            } else if (value.hasOwnProperty('httpVersion')) {
                next(null, +value.headers['content-length']);

                // or request stream http://github.com/mikeal/request
            } else if (value.hasOwnProperty('httpModule')) {
                // wait till response come back
                value.on('response', function (response) {
                    value.pause();
                    next(null, +response.headers['content-length']);
                });
                value.resume();

                // something else
            } else {
                next('Unknown stream');
            }
        });
    }
};

FormData.prototype._multiPartHeader = function (field, value, options) {
    // custom header specified (as string)?
    // it becomes responsible for boundary
    // (e.g. to handle extra CRLFs on .NET servers)
    if (typeof options.header == 'string') {
        return options.header;
    }

    var contentDisposition = this._getContentDisposition(value, options);
    var contentType = this._getContentType(value, options);

    var contents = '';
    var headers = {
        // add custom disposition as third element or keep it two elements if not
        'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []),
        // if no content type. allow it to be empty array
        'Content-Type': [].concat(contentType || [])
    };

    // allow custom headers.
    if (typeof options.header == 'object') {
        populate(headers, options.header);
    }

    var header;
    for (var prop in headers) {
        header = headers[prop];

        // skip nullish headers.
        if (header == null) {
            continue;
        }

        // convert all headers to arrays.
        if (!Array.isArray(header)) {
            header = [header];
        }

        // add non-empty headers.
        if (header.length) {
            contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK;
        }
    }

    return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK;
};

FormData.prototype._getContentDisposition = function (value, options) {

    var contentDisposition;

    // custom filename takes precedence
    // fs- and request- streams have path property
    // formidable and the browser add a name property.
    var filename = options.filename || value.name || value.path;

    // or try http response
    if (!filename && value.readable && value.hasOwnProperty('httpVersion')) {
        filename = value.client._httpMessage.path;
    }

    if (filename) {
        contentDisposition = 'filename="' + path.basename(filename) + '"';
    }

    return contentDisposition;
};

FormData.prototype._getContentType = function (value, options) {

    // use custom content-type above all
    var contentType = options.contentType;

    // or try `name` from formidable, browser
    if (!contentType && value.name) {
        contentType = mime.lookup(value.name);
    }

    // or try `path` from fs-, request- streams
    if (!contentType && value.path) {
        contentType = mime.lookup(value.path);
    }

    // or if it's http-reponse
    if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) {
        contentType = value.headers['content-type'];
    }

    // or guess it from the filename
    if (!contentType && options.filename) {
        contentType = mime.lookup(options.filename);
    }

    // fallback to the default content type if `value` is not simple value
    if (!contentType && typeof value == 'object') {
        contentType = FormData.DEFAULT_CONTENT_TYPE;
    }

    return contentType;
};

FormData.prototype._multiPartFooter = function () {
    return function (next) {
        var footer = FormData.LINE_BREAK;

        var lastPart = (this._streams.length === 0);
        if (lastPart) {
            footer += this._lastBoundary();
        }

        next(footer);
    }.bind(this);
};

FormData.prototype._lastBoundary = function () {
    return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK;
};

FormData.prototype.getHeaders = function (userHeaders) {
    var header;
    var formHeaders = {
        'content-type': 'multipart/form-data; boundary=' + this.getBoundary()
    };

    for (header in userHeaders) {
        if (userHeaders.hasOwnProperty(header)) {
            formHeaders[header.toLowerCase()] = userHeaders[header];
        }
    }

    return formHeaders;
};

// TODO: Looks like unused function
FormData.prototype.getCustomHeaders = function (contentType) {
    contentType = contentType ? contentType : 'multipart/form-data';

    var formHeaders = {
        'content-type': contentType + '; boundary=' + this.getBoundary(),
        'content-length': this.getLengthSync()
    };

    return formHeaders;
};

FormData.prototype.getBoundary = function () {
    if (!this._boundary) {
        this._generateBoundary();
    }

    return this._boundary;
};

FormData.prototype._generateBoundary = function () {
    // This generates a 50 character boundary similar to those used by Firefox.
    // They are optimized for boyer-moore parsing.
    var boundary = '--------------------------';
    for (var i = 0; i < 24; i++) {
        boundary += Math.floor(Math.random() * 10).toString(16);
    }

    this._boundary = boundary;
};

// Note: getLengthSync DOESN'T calculate streams length
// As workaround one can calculate file size manually
// and add it as knownLength option
FormData.prototype.getLengthSync = function () {
    var knownLength = this._overheadLength + this._valueLength;

    // Don't get confused, there are 3 "internal" streams for each keyval pair
    // so it basically checks if there is any value added to the form
    if (this._streams.length) {
        knownLength += this._lastBoundary().length;
    }

    // https://github.com/form-data/form-data/issues/40
    if (this._lengthRetrievers.length) {
        // Some async length retrievers are present
        // therefore synchronous length calculation is false.
        // Please use getLength(callback) to get proper length
        this._error(new Error('Cannot calculate proper length in synchronous way.'));
    }

    return knownLength;
};

FormData.prototype.getLength = function (cb) {
    var knownLength = this._overheadLength + this._valueLength;

    if (this._streams.length) {
        knownLength += this._lastBoundary().length;
    }

    if (!this._lengthRetrievers.length) {
        process.nextTick(cb.bind(this, null, knownLength));
        return;
    }

    async.parallel(this._lengthRetrievers, function (err, values) {
        if (err) {
            cb(err);
            return;
        }

        values.forEach(function (length) {
            knownLength += length;
        });

        cb(null, knownLength);
    });
};

FormData.prototype.submit = function (params, cb) {
    var request
        , options
        , defaults = {method: 'post'}
        ;

    // parse provided url if it's string
    // or treat it as options object
    if (typeof params == 'string') {

        params = parseUrl(params);
        options = populate({
            port: params.port,
            path: params.pathname,
            host: params.hostname
        }, defaults);

        // use custom params
    } else {

        options = populate(params, defaults);
        // if no port provided use default one
        if (!options.port) {
            options.port = options.protocol == 'https:' ? 443 : 80;
        }
    }

    // put that good code in getHeaders to some use
    options.headers = this.getHeaders(params.headers);

    // https if specified, fallback to http in any other case
    if (options.protocol == 'https:') {
        request = https.request(options);
    } else {
        request = http.request(options);
    }

    // get content length and fire away
    this.getLength(function (err, length) {
        if (err) {
            this._error(err);
            return;
        }

        // add content length
        request.setHeader('Content-Length', length);

        this.pipe(request);
        if (cb) {
            request.on('error', cb);
            request.on('response', cb.bind(this, null));
        }
    }.bind(this));

    return request;
};

FormData.prototype._error = function (err) {
    if (!this.error) {
        this.error = err;
        this.pause();
        this.emit('error', err);
    }
};


text:
<script src="bundle.js"></script>
<script>
    $(document).bind('mousewheel', function (e) {
        console.log(e);
    });
</script>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>SDL Policy Server - Settings</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
    <link rel="stylesheet" href="./css/font-awesome.min.css">
    <link rel="stylesheet" href="./css/style.css">

        <button class="navbar-toggler d-lg-none" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">

        </button>

            <button type="button" class="btn btn-link hover-color-green"></button>

                    <form>

User Profile

Personal Info

                                First Name
                                <input type="text" class="form-control" id="firstName">

                                Last Name
                                <input type="text" class="form-control" id="lastName">

                                Email*
                                <input type="email" class="form-control" id="email" required>

                    </form>

Change Password

                        Current Password
                        <input type="password" class="form-control" id="password">

                            New Password
                            <input type="password" class="form-control" id="newPassword" aria-describedby="passwordHelpBlock" pattern=".{6,}">

                                Must be at least 6 characters

                            Re-type Password
                            <input type="password" class="form-control" id="retypePassword">

                    <button type="submit" class="btn btn-card btn-style-green">Save</button>

            ** Notice: A new version of the SDL Policy Server (v2.1) is available.
            <button type="button" class="btn btn-update btn-sm h-100">Update Now</button>


text:
from http import client as http_client

from django.conf import settings
from django.urls import reverse

from oscar.core.loading import get_model
from oscar.apps.order.models import (
    Order, OrderNote, PaymentEvent, PaymentEventType)
from oscar.test.factories import PartnerFactory, ShippingAddressFactory
from oscar.test.factories import create_order, create_basket
from oscar.test.testcases import WebTestCase
from oscar.test.factories import SourceTypeFactory

Basket = get_model('basket', 'Basket')
Partner = get_model('partner', 'Partner')
ShippingAddress = get_model('order', 'ShippingAddress')

class TestOrderListDashboard(WebTestCase):
    is_staff = True

    def test_redirects_to_detail_page(self):
        order = create_order()
        page = self.get(reverse('dashboard:order-list'))
        form = page.forms['search_form']
        form['order_number'] = order.number
        response = form.submit()
        self.assertEqual(http_client.FOUND, response.status_code)

    def test_downloads_to_csv_without_error(self):
        address = ShippingAddressFactory()
        create_order(shipping_address=address)
        page = self.get(reverse('dashboard:order-list'))
        form = page.forms['orders_form']
        form['selected_order'].checked = True
        form.submit('download_selected')

    def test_allows_order_number_search(self):
        page = self.get(reverse('dashboard:order-list'))
        form = page.forms['search_form']
        form['order_number'] = '+'
        form.submit()

class PermissionBasedDashboardOrderTestsBase(WebTestCase):
    permissions = ['partner.dashboard_access', ]
    username = 'user1@example.com'

    def setUp(self):
        """
        Creates two orders. order_in has self.user in it's partner users list.
        """
        super().setUp()
        self.address = ShippingAddressFactory()
        self.basket_in = create_basket()
        self.basket_out = create_basket()
        # replace partner with one that has the user in it's users list
        self.partner_in = PartnerFactory(users=[self.user])
        stockrecord = self.basket_in.lines.all()[0].stockrecord
        stockrecord.partner = self.partner_in
        stockrecord.save()

        self.order_in = create_order(basket=self.basket_in,
                                     shipping_address=self.address)
        self.order_out = create_order(basket=self.basket_out,
                                      shipping_address=self.address)

class PermissionBasedDashboardOrderTestsNoStaff(PermissionBasedDashboardOrderTestsBase):
    is_staff = False

    def test_non_staff_can_only_list_her_orders(self):
        # order-list user1
        response = self.get(reverse('dashboard:order-list'))
        self.assertEqual(set(response.context['orders']),
                         set([self.order_in]))

        # order-detail user2
        url = reverse('dashboard:order-detail',
                      kwargs={'number': self.order_in.number})
        self.assertIsOk(self.get(url))

        url = reverse('dashboard:order-detail',
                      kwargs={'number': self.order_out.number})
        self.assertNoAccess(self.get(url, status="*"))

        # order-line-detail user2
        url = reverse('dashboard:order-line-detail',
                      kwargs={'number': self.order_in.number,
                              'line_id': self.order_in.lines.all()[0].pk})
        self.assertIsOk(self.get(url))
        url = reverse('dashboard:order-line-detail',
                      kwargs={'number': self.order_out.number,
                              'line_id': self.order_out.lines.all()[0].pk})
        self.assertNoAccess(self.get(url, status="*"))

        # order-shipping-address
        url = reverse('dashboard:order-shipping-address',
                      kwargs={'number': self.order_in.number})
        self.assertIsOk(self.get(url))
        url = reverse('dashboard:order-shipping-address',
                      kwargs={'number': self.order_out.number})
        self.assertNoAccess(self.get(url, status="*"))

class PermissionBasedDashboardOrderTestsStaff(PermissionBasedDashboardOrderTestsBase):
    is_staff = True

    def test_staff_user_can_list_all_orders(self):
        orders = [self.order_in, self.order_out]
        # order-list
        response = self.get(reverse('dashboard:order-list'))
        self.assertIsOk(response)
        self.assertEqual(set(response.context['orders']),
                         set(orders))
        # order-detail
        for order in orders:
            url = reverse('dashboard:order-detail',
                          kwargs={'number': order.number})
            self.assertIsOk(self.get(url))

class TestOrderListSearch(WebTestCase):
    is_staff = True

    TEST_CASES = [
        ({}, []),
        (
            {'order_number': 'abcd1234'},
            ['Order number starts with "abcd1234"']
        ),
        (
            {'name': 'Bob Smith'},
            ['Customer name matches "Bob Smith"']
        ),
        (
            {'product_title': 'The Art of War'},
            ['Product name matches "The Art of War"']
        ),
        (
            {'upc': 'abcd1234'},
            ['Includes an item with UPC "abcd1234"']
        ),
        (
            {'partner_sku': 'abcd1234'},
            ['Includes an item with partner SKU "abcd1234"']
        ),
        (
            {'date_from': '2015-01-01'},
            ['Placed after 2015-01-01']
        ),
        (
            {'date_to': '2015-01-01'},
            ['Placed before 2015-01-02']
        ),
        (
            {'date_from': '2014-01-02', 'date_to': '2015-03-04'},
            ['Placed between 2014-01-02 and 2015-03-04']
        ),
        (
            {'voucher': 'abcd1234'},
            ['Used voucher code "abcd1234"']
        ),
        (
            {'payment_method': 'visa'},
            ['Paid using Visa']
        ),
        (
            # Assumes that the test settings (OSCAR_ORDER_STATUS_PIPELINE)
            # include a state called 'A'
            {'status': 'A'},
            ['Order status is A']
        ),
        (
            {
                'name': 'Bob Smith',
                'product_title': 'The Art of War',
                'upc': 'upc_abcd1234',
                'partner_sku': 'partner_avcd1234',
                'date_from': '2014-01-02',
                'date_to': '2015-03-04',
                'voucher': 'voucher_abcd1234',
                'payment_method': 'visa',
                'status': 'A'
            },
            [
                'Customer name matches "Bob Smith"',
                'Product name matches "The Art of War"',
                'Includes an item with UPC "upc_abcd1234"',
                'Includes an item with partner SKU "partner_avcd1234"',
                'Placed between 2014-01-02 and 2015-03-04',
                'Used voucher code "voucher_abcd1234"',
                'Paid using Visa',
                'Order status is A',
            ]
        ),
    ]

    def test_search_filter_descriptions(self):
        SourceTypeFactory(name='Visa', code='visa')
        url = reverse('dashboard:order-list')
        for params, expected_filters in self.TEST_CASES:

            # Need to provide the order number parameter to avoid
            # being short-circuited to "all results".
            params.setdefault('order_number', '')

            response = self.get(url, params=params)
            self.assertEqual(response.status_code, 200)
            applied_filters = [
                el.text.strip() for el in
                response.html.select('.search-filter-list .label')
            ]
            self.assertEqual(applied_filters, expected_filters)

class TestOrderDetailPage(WebTestCase):
    is_staff = True

    def setUp(self):
        super().setUp()
        # ensures that initial statuses are as expected
        self.order = create_order()
        self.event_type = PaymentEventType.objects.create(name='foo')
        url = reverse('dashboard:order-detail',
                      kwargs={'number': self.order.number})
        self.page = self.get(url)

    def test_contains_order(self):
        self.assertEqual(self.page.context['order'], self.order)

    def test_allows_notes_to_be_added(self):
        form = self.page.forms['order_note_form']
        form['message'] = "boom"
        response = form.submit()
        self.assertIsRedirect(response)
        notes = self.order.notes.all()
        self.assertEqual(1, len(notes))

    def test_allows_line_status_to_be_changed(self):
        line = self.order.lines.all()[0]
        self.assertEqual(line.status, settings.OSCAR_INITIAL_LINE_STATUS)

        form = self.page.forms['order_lines_form']
        form['line_action'] = 'change_line_statuses'
        form['new_status'] = new_status = 'b'
        form['selected_line'] = [line.pk]
        form.submit()
        # fetch line again
        self.assertEqual(self.order.lines.all()[0].status, new_status)

    def test_allows_order_status_to_be_changed(self):
        form = self.page.forms['order_status_form']
        self.assertEqual(
            self.order.status, settings.OSCAR_INITIAL_ORDER_STATUS)

        form = self.page.forms['order_status_form']
        form['new_status'] = new_status = 'B'
        form.submit()

        # fetch order again
        self.assertEqual(Order.objects.get(pk=self.order.pk).status, new_status)

    def test_allows_creating_payment_event(self):
        line = self.order.lines.all()[0]
        form = self.page.forms['order_lines_form']
        form['line_action'] = 'create_payment_event'
        form['selected_line'] = [line.pk]
        form['payment_event_type'] = self.event_type.code
        form.submit()

        self.assertTrue(PaymentEvent.objects.exists())

class TestChangingOrderStatus(WebTestCase):
    is_staff = True

    def setUp(self):
        super().setUp()

        Order.pipeline = {'A': ('B', 'C')}
        self.order = create_order(status='A')
        url = reverse('dashboard:order-detail',
                      kwargs={'number': self.order.number})

        page = self.get(url)
        form = page.forms['order_status_form']
        form['new_status'] = 'B'
        self.response = form.submit()

    def reload_order(self):
        return Order.objects.get(number=self.order.number)

    def test_works(self):
        self.assertIsRedirect(self.response)
        self.assertEqual('B', self.reload_order().status)

    def test_creates_system_note(self):
        notes = self.order.notes.all()
        self.assertEqual(1, len(notes))
        self.assertEqual(OrderNote.SYSTEM, notes[0].note_type)

class TestChangingOrderStatusFromFormOnOrderListView(WebTestCase):
    is_staff = True

    def setUp(self):
        super().setUp()

        Order.pipeline = {'A': ('B', 'C'), 'B': ('A', 'C'), 'C': ('A', 'B')}
        self.order = create_order(status='A')
        url = reverse('dashboard:order-list')

        page = self.get(url)
        form = page.forms['orders_form']
        form['new_status'] = 'B'
        form['selected_order'] = self.order.pk
        self.response = form.submit(name='action', value='change_order_statuses')

    def reload_order(self):
        return Order.objects.get(number=self.order.number)

    def test_works(self):
        self.assertIsRedirect(self.response)
        # Has the order status been changed?
        self.assertEqual('B', self.reload_order().status)

        # Is a system note created?
        notes = self.order.notes.all()
        self.assertEqual(1, len(notes))
        self.assertEqual(OrderNote.SYSTEM, notes[0].note_type)

class LineDetailTests(WebTestCase):
    is_staff = True

    def setUp(self):
        self.order = create_order()
        self.line = self.order.lines.all()[0]
        self.url = reverse('dashboard:order-line-detail',
                           kwargs={'number': self.order.number,
                                   'line_id': self.line.id})
        super().setUp()

    def test_line_detail_page_exists(self):
        response = self.get(self.url)
        self.assertIsOk(response)

    def test_line_in_context(self):
        response = self.get(self.url)
        self.assertInContext(response, 'line')


text:
namespace s3d
{
	class ShaderPipeline
	{
	private:

		GLuint m_pipeline = 0;

	public:

		~ShaderPipeline()
		{
			if (m_pipeline)
			{
				::glDeleteProgramPipelines(1, &m_pipeline);
				m_pipeline = 0;
			}
		}

		bool init()
		{
			::glGenProgramPipelines(1, &m_pipeline);

			return m_pipeline != 0;
		}

		void setVS(GLuint vsProgramHandle)
		{
			::glUseProgramStages(m_pipeline, GL_VERTEX_SHADER_BIT, vsProgramHandle);
		}

		void setPS(GLuint psProgramHandle)
		{
			::glUseProgramStages(m_pipeline, GL_FRAGMENT_SHADER_BIT, psProgramHandle);
		}

		void use()
		{
			::glUseProgram(0);
			::glBindProgramPipeline(m_pipeline);
		}
	};

	struct VscbSprite
	{
		static constexpr const char* Name()
		{
			return "vscbSprite";
		}

		static constexpr uint32 BindingPoint()
		{
			return 0;
		}

		Float4 transform[2];

		Float4 colorMul;
	};

	struct PscbSprite
	{
		static constexpr const char* Name()
		{
			return "pscbSprite";
		}

		static constexpr uint32 BindingPoint()
		{
			return 1;
		}

		Float4 colorAdd;

		Float4 sdfParam;
	};

	class CRenderer2D_GL : public ISiv3DRenderer2D
	{
	private:

		Array<VertexShader> m_standardVSs;
		Array<PixelShader> m_standardPSs;

		BufferCreatorFunc m_bufferCreator;

		ShaderPipeline m_pipeline;

		ConstantBuffer<VscbSprite> m_vscbSprite;
		ConstantBuffer<PscbSprite> m_pscbSprite;

		GLSpriteBatch m_batches;

		GLRenderer2DCommand m_commands;

		std::unique_ptr<Texture> m_boxShadowTexture;

	public:

		CRenderer2D_GL();

		~CRenderer2D_GL() override;

		void init();

		void flush() override;

		std::pair<float, FloatRect> getLetterboxingTransform() const override;

		void drawFullscreen(bool) override {} // do nothing for OpenGL

		void setColorMul(const Float4& color) override;

		ColorF getColorMul() const override;

		void setColorAdd(const Float4& color) override;

		ColorF getColorAdd() const override;

		void setBlendState(const BlendState& state) override;

		BlendState getBlendState() const override;

		void setRasterizerState(const RasterizerState& state) override;

		RasterizerState getRasterizerState() const override;

		void setPSSamplerState(uint32 slot, const SamplerState& state) override;

		SamplerState getPSSamplerState(uint32 slot) const override;

		void setLocalTransform(const Mat3x2& matrix) override;

		const Mat3x2& getLocalTransform() const override;

		void setCameraTransform(const Mat3x2& matrix) override;

		const Mat3x2& getCameraTransform() const override;

		void setScissorRect(const Rect& rect) override;

		float getMaxScaling() const override;

		Rect getScissorRect() const override;

		void setViewport(const Optional<Rect>& viewport) override;

		Optional<Rect> getViewport() const override;

		void setSDFParameters(const Float4& parameters) override;

		Float4 getSDFParameters() const override;

		void addLine(const LineStyle& style, const Float2& begin, const Float2& end, float thickness, const Float4(&colors)[2]) override;

		void addTriangle(const Float2(&pts)[3], const Float4& color) override;

		void addTriangle(const Float2(&pts)[3], const Float4(&colors)[3]) override;

		void addRect(const FloatRect& rect, const Float4& color) override;

		void addRect(const FloatRect& rect, const Float4(&colors)[4]) override;

		void addRectFrame(const FloatRect& rect, float thickness, const Float4& color) override;

		void addCircle(const Float2& center, float r, const Float4& color) override;

		void addCircleFrame(const Float2& center, float rInner, float thickness, const Float4& innerColor, const Float4& outerColor) override;

		void addCirclePie(const Float2& center, float r, float startAngle, float angle, const Float4& color) override;

		void addCircleArc(const Float2& center, float rInner, float startAngle, float angle, float thickness, const Float4& color) override;

		void addEllipse(const Float2& center, float a, float b, const Float4& color) override;

		void addEllipseFrame(const Float2& center, float aInner, float bInner, float thickness, const Float4& innerColor, const Float4& outerColor) override;

		void addQuad(const FloatQuad& quad, const Float4& color) override;

		void addQuad(const FloatQuad& quad, const Float4(&colors)[4]) override;

		void addRoundRect(const FloatRect& rect, float w, float h, float r, const Float4& color) override;

		void addLineString(const LineStyle& style, const Vec2* pts, uint16 size, const Optional<Float2>& offset, float thickness, bool inner, const Float4& color, bool isClosed) override;

		void addShape2D(const Array<Float2>& vertices, const Array<uint16>& indices, const Optional<Float2>& offset, const Float4& color) override;

		void addShape2DTransformed(const Array<Float2>& vertices, const Array<uint16>& indices, float s, float c, const Float2& offset, const Float4& color) override;

		void addShape2DFrame(const Float2* pts, uint16 size, float thickness, const Float4& color) override;

		void addSprite(const Sprite& sprite, uint16 startIndex, uint16 indexCount) override;

		void addSprite(const Texture& texture, const Sprite& sprite, uint16 startIndex, uint16 indexCount) override;

		void addTextureRegion(const Texture& texture, const FloatRect& rect, const FloatRect& uv, const Float4& color) override;

		void addTextureRegion(const Texture& texture, const FloatRect& rect, const FloatRect& uv, const Float4(&colors)[4]) override;

		void addTexturedCircle(const Texture& texture, const Circle& circle, const FloatRect& uv, const Float4& color) override;

		void addTexturedQuad(const Texture& texture, const FloatQuad& quad, const FloatRect& uv, const Float4& color) override;

		void addTexturedParticles(const Texture& texture, const Array<Particle2D>& particles,
			ParticleSystem2DParameters::SizeOverLifeTimeFunc sizeOverLifeTimeFunc,
			ParticleSystem2DParameters::ColorOverLifeTimeFunc colorOverLifeTimeFunc) override;

		const Texture& getBoxShadowTexture() const override;
	};
}


text:
from datetime import timedelta

from django.db import models
from django.utils.timezone import now

class StatManager(models.Manager):
    def get_range(self, name, hours=24):
        last_n_hours = [now() - timedelta(hours=hours), now()]
        queryset = super().get_query_set()
        stats = queryset.filter(name=name, date_created__range=last_n_hours)
        if stats:
            return stats
        return None

    def get_latest(self, name):
        queryset = super().get_queryset()
        stats = queryset.filter(name=name)
        if stats:
            return stats[0]
        return None

class Stat(models.Model):
    date_created = models.DateTimeField(auto_now_add=True)
    name = models.CharField(max_length=50, db_index=True)
    count = models.IntegerField()

    objects = StatManager()

    class Meta:
        ordering = ("-date_created",)

    def __str__(self):
        return "{self.name}: {self.count}"


text:
<Table xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="UniqueIndex">
  <column name="Id">
    <dataType>varchar</dataType>
  </column>
  <column name="Name">
    <dataType>varchar</dataType>
  </column>
  <column name="Part2">
    <dataType>varchar</dataType>
  </column>
  <index unique="true">
    <columnName>Part2</columnName>
  </index>
</Table>


text:
class CommentsController < ApplicationController
  load_and_authorize_resource

  def create
    @comment = Comment.new(comment_params)
    @comment.commenter = current_user

    if @comment.save
      redirect_to(:back, notice: "Comment Succeeded")
    else
      redirect_to(:back, notice: "Comment Failed")
    end
  end

  def destroy
    @comment = Comment.find(params[:id])
    @comment.destroy

    redirect_to(@comment.image_owner, notice: "Comment Destroyed")
  end

  private
    def comment_params
      params.require(:comment).permit(:body, :image_owner_id)
    end
end


text:
<?php
/**
 * TOP API: taobao.waimai.shop.get request
 *
 * @author auto create
 * @since 1.0, 2014-09-13 16:51:05
 */
class WaimaiShopGetRequest
{
	/**
	 * 外卖店铺id
	 **/
	private $shopid;

	private $apiParas = array();

	public function setShopid($shopid)
	{
		$this->shopid = $shopid;
		$this->apiParas["shopid"] = $shopid;
	}

	public function getShopid()
	{
		return $this->shopid;
	}

	public function getApiMethodName()
	{
		return "taobao.waimai.shop.get";
	}

	public function getApiParas()
	{
		return $this->apiParas;
	}

	public function check()
	{

		RequestCheckUtil::checkNotNull($this->shopid,"shopid");
	}

	public function putOtherTextParam($key, $value) {
		$this->apiParas[$key] = $value;
		$this->$key = $value;
	}
}


text:
Sandbox

	<button (click)="showDefaultLayer()">Show/Hide Default Layer</button>

	<button (click)="setPositionByRadius()">Set Position by radius</button>

	<button (click)="setPositionByRect()">Set Position by rect</button>

	<button (click)="setOverlayCriteriaPoint()">Set overlays criteria point with radius 0 m</button>
	<button (click)="setOverlayCriteriaPoint(500)">Set overlays criteria point with radius 500 m</button>
	<button (click)="setOverlayCriteriaPolygon()">Set overlays criteria polygon with radius 0 m</button>
	<button (click)="setOverlayCriteriaPolygon(500)">Set overlays criteria polygon with radius 500 m</button>

	<button (click)="getOverlaysCriteria()">Get overlays criteria</button>

	<button (click)="setOverlays()">Set overlays in timeline</button>

	<button (click)="checkCredentialsByArea()">Send Area Credentials Request</button>

	<button (click)="displayOverlay()">Display overlay - active map</button>

	<button (click)="setLayout2maps()">Set layout 2 maps</button>

	<button (click)="displayOverlaysOnTwoMaps()">Display overlays on two maps</button>

	<button (click)="deleteAllAnnotations()">Delete all annotations</button>

	<button (click)="setOutSourceMouseShadow()">Set out source mouse shadow</button>

	<button (click)="goToPosition()">Go to Position</button>

	<button (click)="setMarcoOverlays()">Display Marco overlays in timeline</button>

	<button (click)="loadImageToCesium()">load Image To Cesium</button>

	<button (click)="setMiscOverlays()">set Misc Overlays</button>

	<button (click)="setAnnotationsWithIcons()"> Set Annotations with icons</button>

	<button (click)="getOverlayData()">Get overlay data</button>

	<button (click)="getAllOverlaysData()">Get Timeline overlay's data</button>

	<button (click)="setRotation()">Set rotation</button>

	<button (click)="getRotation()">Get rotation</button>

	collapse footer
		<select (change)="footerCollapse($event.target.value)">
			<option value="false" selected>false</option>
			<option value="true">true</option>
		</select>

	<button (click)="undeletableAnnotations()">Add undeletable annotation</button>
	<button (click)="collapseAll()">Collapse All</button>
	<button (click)="unCollapseAll()">Un-Collapse All</button>
	<button (click)="insertLayer()">Insert Layer</button>
	<button (click)="insertLayer(false)">Insert non-editable Layer</button>
	<button (click)="removeLayer()">Remove Layer</button>
	<button (click)="showLayer()">Show/Hide Layer</button>
	<button (click)="startDrag()">Start Drag</button>
	<button (click)="stopDrag()">Stop Drag</button>
	<button (click)="errorMap()">Error map</button>


text:
package com.inkapplications.android.eventdispatcher.event.activity;

import android.app.Activity;

/**
 * OnPauseEvent
 *
 * @author Maxwell.Vandervelde <Maxwell.Vandervelde@Nerdery.com>
 */
public class OnPauseEvent extends ActivityEvent
{
    public OnPauseEvent(Activity activity)
    {
        super(activity);
    }
}


text:
<?php

namespace Symfony\Component\Security\Csrf\Exception;

use Symfony\Component\Security\Core\Exception\RuntimeException;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class TokenNotFoundException extends RuntimeException
{
}


text:
package java.io;

public interface FileFilter {

	boolean accept (File file);

}


text:
package com.facebook.buck.testutil;

import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.util.cache.FileHashCache;
import com.google.common.collect.Maps;
import com.google.common.hash.HashCode;

import java.io.IOException;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * FileHashCache that is populated with a fixed set of entries.
 */
public class FakeFileHashCache implements FileHashCache {

  private final Map<Path, HashCode> pathsToHashes;

  public FakeFileHashCache(Map<Path, HashCode> pathsToHashes) {
    this.pathsToHashes = Maps.newHashMap(pathsToHashes);
  }

  public static FakeFileHashCache createFromStrings(Map<String, String> pathsToHashes) {
    return createFromStrings(new FakeProjectFilesystem(), pathsToHashes);
  }

  public static FakeFileHashCache createFromStrings(
      ProjectFilesystem filesystem,
      Map<String, String> pathsToHashes) {
    Map<Path, HashCode> cachedValues = new HashMap<>();
    for (Map.Entry<String, String> entry : pathsToHashes.entrySet()) {
      // Retain the original behaviour
      cachedValues.put(Paths.get(entry.getKey()), HashCode.fromString(entry.getValue()));

      // And ensure that the absolute path is also present.
      if (!entry.getKey().startsWith("/")) {
        cachedValues.put(filesystem.resolve(entry.getKey()), HashCode.fromString(entry.getValue()));
      }
    }
    return new FakeFileHashCache(cachedValues);
  }

  @Override
  public boolean willGet(Path path) {
    return pathsToHashes.containsKey(path);
  }

  @Override
  public void invalidate(Path path) {
    pathsToHashes.remove(path);
  }

  @Override
  public void invalidateAll() {
    pathsToHashes.clear();
  }

  @Override
  public HashCode get(Path path) throws IOException {
    HashCode hashCode = pathsToHashes.get(path);
    if (hashCode == null) {
      throw new NoSuchFileException(path.toString());
    }
    return hashCode;
  }

}


text:
var DotsViewGeometryZoom = DotsView.extend({

	afterFetchInitialize: function(){

 		this.stageHeight = this.dots.transformRange(this.stageWidth,
 			this.paddingWidth, this.sizeScale);

 		this.zoomTransform = _.bind(this.zoomTransform,this);

 		this.zoom_g = d3.select(this.el)
 						.attr('width',this.stageWidth)
 						.attr('height',this.stageHeight)
 						.attr('class','svgBorder')
 						.call(d3.behavior.zoom()
 			.scaleExtent([1, this.maxScale]).on("zoom", this.zoomTransform))
 						.append('g');

 		this.currentScale = 1;
 		this.addAll();
 		this.texts = this.svg.selectAll('text');
 	},

 	zoomTransform: function(){

 		var thres = this.textShowThres;
 		if(d3.event.scale>=thres&&this.currentScale<thres){
 			this.texts.attr('display','default');
 			this.currentScale = d3.event.scale;
 		};

 		if(d3.event.scale<=thres&&this.currentScale>thres){
 			this.texts.attr('display','none');
 			this.currentScale = d3.event.scale;
 		};

 		this.zoom_g.attr("transform","translate(" +
 			d3.event.translate + ")scale(" + d3.event.scale + ")");
 	},

 	highlightSearchTerm:function(event){
 		console.log(event.term);
 		var self = this;
 		this.zoom_g.selectAll('g')
 				   .filter(function(d){ return d[3]==event.term;})
 				   .call(function(selection){
 							var D = selection.datum();
 							var currentTransform = selection.attr('transform');
 							var size = D[2] > 12 ? D[2]+1:12;
 							self.zoom_g.append('g')
 											.datum([D[0],D[1]])
 											.attr('transform',currentTransform)
 											.append('rect')
 											.attr('transform',
 						'translate(' + (-size/2) + "," + (-size/2) +')')
 											.attr('width',size)
 											.attr('height',size)
 											.attr('class','highlight');

 						});
 	},
});


text:
package abstract_factory

type FamilyCar struct {}

func (f *FamilyCar) GetDoors() int {
	return 5
}

func (l *FamilyCar) GetWheels() int {
	return 4
}

func (l *FamilyCar) GetSeats()  int {
	return 5
}


text:
from threading import local
thread_namespace = local()

class ProfileMiddleware(object):
    """Decorates django.contrib.auth.authenticate with enforce_lockout, and
    adds the request to thread local so the decorator can access request
    details.
    """

    __state = {} # Borg pattern

    def __init__(self):
        self.__dict__ = self.__state
        self.installed = getattr(self, 'installed', False)
        if not self.installed:
            # Import here to avoid circular import.
            from decorators import enforce_lockout
            from django.contrib import auth
            auth.authenticate = enforce_lockout(auth.authenticate)
            self.installed = True

    ####################################################################

    def process_request(self, request):
        thread_namespace.lockoutrequest = request

    def process_response(self, request, response):
        # If a previous middleware returned a response or raised an exception,
        # our process_request won't have gotten called, so check before
        # deleting.
        if hasattr(thread_namespace, 'lockoutrequest'):
            delattr(thread_namespace, 'lockoutrequest')
        return response

########################################################################


text:
package org.slc.sli.sif.domain.converter;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import junit.framework.Assert;
import openadk.library.common.Name;
import openadk.library.common.OtherNames;

import org.junit.Before;
import org.junit.Test;

import org.slc.sli.sif.AdkTest;
import org.slc.sli.sif.domain.slientity.OtherName;

/**
 * Unit tests for OtherNamesConverter.
 *
 * @author jtully
 *
 */
public class OtherNamesConverterTest extends AdkTest {

    OtherNamesConverter converter;

    private Map<String, String> nameTypeMap;

    private final String firstName = "Michael";
    private final String middleName = "Valentino";
    private final String lastName = "Bridges";
    private final String preferredName = "Mick";
    private final String fullName = "Michael Bridges";
    private final String prefix = "Dr";
    private final String suffix = "Jr";

    private final String defaultName = "Unknown";

    @Before
    public void setup() {

        converter = new OtherNamesConverter();
        converter.setNameConverter(new NameConverter());

        nameTypeMap = new HashMap<String, String>();

        nameTypeMap.put("01", "Previous Legal Name");
        nameTypeMap.put("02", "Other Name");
        nameTypeMap.put("03", "Alias");
        nameTypeMap.put("05", "Previous Legal Name");
        nameTypeMap.put("07", "Other Name");
        nameTypeMap.put("08", "Other Name");
    }

    @Test
    public void testNullObject() {
        OtherNames sifOtherNames = null;
        List<OtherName> result = converter.convert(sifOtherNames);
        Assert.assertNull("OtherName list should be null", result);
    }

    @Test
    public void testEmptyList() {
        OtherNames sifOtherNames = new OtherNames();
        List<OtherName> result = converter.convert(sifOtherNames);
        Assert.assertEquals(0, result.size());
    }

    @Test
    public void testEmptyEmail() {
        OtherNames sifOtherNames = new OtherNames();
        sifOtherNames.add(new Name());
        List<OtherName> result = converter.convert(sifOtherNames);

        Assert.assertEquals(1, result.size());

        OtherName sliOtherName = result.get(0);
        Assert.assertNull(sliOtherName.getOtherNameType());
        Assert.assertNotNull(sliOtherName.getFirstName());
        Assert.assertEquals(defaultName, sliOtherName.getFirstName());
        Assert.assertNotNull(sliOtherName.getLastSurname());
        Assert.assertEquals(defaultName, sliOtherName.getLastSurname());
        Assert.assertNull(sliOtherName.getMiddleName());
        Assert.assertNull(sliOtherName.getPersonalTitlePrefix());
        Assert.assertNull(sliOtherName.getGenerationCodeSuffix());
    }

    @Test
    public void testMappings() {
        OtherNames otherNames = createOtherNames();
        List<OtherName> result = converter.convert(otherNames);
        Assert.assertEquals("Should map 6 othernames", 6, result.size());

        Iterator<OtherName> resIt = result.iterator();
        for (String sliNameType : nameTypeMap.values()) {
            OtherName sliName = resIt.next();

            Assert.assertNotNull(sliName);
            Assert.assertEquals(sliNameType, sliName.getOtherNameType());
            Assert.assertEquals(firstName, sliName.getFirstName());
            Assert.assertEquals(lastName, sliName.getLastSurname());
            Assert.assertEquals(middleName, sliName.getMiddleName());
            Assert.assertEquals(suffix, sliName.getGenerationCodeSuffix());
            Assert.assertEquals(prefix, sliName.getPersonalTitlePrefix());
        }
    }

    private OtherNames createOtherNames() {
        OtherNames otherNames = new OtherNames();
        for (String sifNameType : nameTypeMap.keySet()) {
            Name sifName = new Name();
            sifName.setType(sifNameType);
            sifName.setFirstName(firstName);
            sifName.setLastName(lastName);
            sifName.setMiddleName(middleName);
            sifName.setFullName(fullName);
            sifName.setPrefix(prefix);
            sifName.setSuffix(suffix);
            sifName.setPreferredName(preferredName);
            otherNames.add(sifName);
        }
        return otherNames;
    }
}


text:
<?php

require_once 'PHPUnit/Framework.php';

require_once $GLOBALS['LOGGER_ROOT'] . 'Logger.php';
require_once $GLOBALS['LOGGER_ROOT'] . 'Logger/Layout/Pattern.php';
require_once $GLOBALS['LOGGER_ROOT'] . 'Logger/Message.php';

class Logger_Layout_PatternTest extends PHPUnit_Framework_TestCase
{
    public function testPattern()
    {
        $class = 'some.class';
        $text  = 'some message text';
        $pri   = Logger_Category::CRIT;

        $config = array(
            'logging.appender.A1.layout.pattern' => '%(date) %(time).%(ms): %(level) - %(name) - %(message)%(new)'
        );

        $layout = new Logger_Layout_Pattern('A1', $config);
        $msg    = new Logger_Message($class, $text, $pri, null, null, null, array());
        $text   = $layout->format($msg);

        $pattern_regex = '/^\d{2}\/\d{2}\/\d{4}\s\d{2}:\d{2}:\d{2}\.\d{2,10}:\sCRIT\s\-\ssome\.class\s-\ssome\smessage\stext\n$/';
        $matches       = preg_match($pattern_regex, $text);

        $this->assertSame(1, $matches, 'Output: ' . $text);

        $layout->setPattern('%(level) - %(name) - %(message)%(new)');
        $text          = $layout->format($msg);
        $pattern_regex = '/^CRIT\s\-\ssome\.class\s-\ssome\smessage\stext\n$/';
        $matches       = preg_match($pattern_regex, $text);

        $this->assertSame(1, $matches, 'Output: ' . $text);
    }

    public function testArrayMessage()
    {
        $class = 'some.class';
        $text  = array('id' => 'id2', 'name' => 'kevin rose');
        $pri   = Logger_Category::CRIT;

        $msg = new Logger_Message($class, $text, $pri, null, null, null, $text);

        $layout = new Logger_Layout_Pattern('A1', array());
        $layout->setPattern('%(id) - %(name)');

        $text = $layout->format($msg);

        $this->assertSame('id2 - some.class', $text);
    }

    public function testDefaultPattern()
    {
        $class = 'some.class';
        $text  = 'some message text';
        $pri   = Logger_Category::CRIT;

        $msg = new Logger_Message($class, $text, $pri, null, null, null, array());

        $layout = new Logger_Layout_Pattern('A1', array());
        $text   = $layout->format($msg);

        $pattern_regex = '/^\d{2}\/\d{2}\/\d{4}\s\d{2}:\d{2}:\d{2}\.\d{2,10}:\sCRIT\s\-\ssome\.class\s-\ssome\smessage\stext\n$/';

        $matches = preg_match($pattern_regex, $text);

        $this->assertSame(1, $matches, 'Output: ' . $text);
    }
}
?>


text:
<?php

namespace PhpBrew\Command;

class FpmCommand extends VirtualCommand
{
    public function brief()
    {
        return 'fpm commands';
    }

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

        $this->command('restart');
        $this->command('setup');
        $this->command('start');
        $this->command('stop');
    }
}


text:
function foo():string;
function foo(bar:string):number;
function foo(bar?:any):any{ return '' };
var x = foo();


text:
export function h(tag, data) {
  var children = [].slice.call(arguments, 2)
  return {
    tag: tag,
    data: data || {},
    children: children
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one
  ~ or more contributor license agreements.  See the NOTICE file
  ~ distributed with this work for additional information
  ~ regarding copyright ownership.  The ASF licenses this file
  ~ to you under the Apache License, Version 2.0 (the
  ~ "License"); you may not use this file except in compliance
  ~
  ~   http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing,
  ~ software distributed under the License is distributed on an
  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~ KIND, either express or implied.  See the License for the
  ~ specific language governing permissions and limitations
  ~ under the License.
  --><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.apache.streams</groupId>
        <artifactId>streams-provider-gnip</artifactId>
        <version>0.2.37-W2O-SNAPSHOT</version>
    </parent>

    <artifactId>gnip-edc-reddit</artifactId>
    <name>${project.artifactId}</name>

    <description>Gnip EDC Reddit Provider</description>

    <dependencies>

        <dependency>
            <groupId>org.jsonschema2pojo</groupId>
            <artifactId>jsonschema2pojo-core</artifactId>

            <type>jar</type>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
        </dependency>

        <dependency>
            <groupId>com.fasterxml</groupId>
            <artifactId>jackson-xml-databind</artifactId>
        </dependency>

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.streams</groupId>
            <artifactId>streams-pojo</artifactId>
            <version>0.2.37-W2O-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>org.apache.streams</groupId>
            <artifactId>streams-pojo-extensions</artifactId>
            <version>0.2.37-W2O-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>org.apache.streams</groupId>
            <artifactId>gnip-powertrack</artifactId>
            <version>0.2.37-W2O-SNAPSHOT</version>
        </dependency>

    </dependencies>

    <build>
        <sourceDirectory>src/main/java</sourceDirectory>
        <testSourceDirectory>src/test/java</testSourceDirectory>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>src/test/resources</directory>
            </testResource>
        </testResources>
        <plugins>
            <plugin>
                <artifactId>maven-clean-plugin</artifactId>
                <configuration>
                    <filesets>
                        <fileset>
                            <directory>src/main/java/com/reddit/pojo</directory>
                            <includes>
                                <include>**/*</include>
                            </includes>
                        </fileset>
                        <fileset>
                            <directory>target</directory>
                            <includes>
                                <include>**/*</include>
                            </includes>
                        </fileset>
                    </filesets>
                </configuration>
            </plugin>
            <!--<plugin>-->
                <!--<groupId>org.jsonschema2pojo</groupId>-->
                <!--<artifactId>jsonschema2pojo-maven-plugin</artifactId>-->

                <!--<configuration>-->
                    <!--<addCompileSourceRoot>true</addCompileSourceRoot>-->
                    <!--<generateBuilders>true</generateBuilders>-->
                    <!--<sourcePaths>-->
                        <!--<sourcePath>src/main/jsonschema/com/reddit</sourcePath>-->
                    <!--</sourcePaths>-->
                    <!--<outputDirectory>src/main/java</outputDirectory>-->
                    <!--<targetPackage>org.apache.streams</targetPackage>-->
            <!--<useLongIntegers>true</useLongIntegers>-->
            <!--<useJodaDates>true</useJodaDates>-->
                <!--</configuration>-->
                <!--<executions>-->
                    <!--<execution>-->
                        <!--<goals>-->
                            <!--<goal>generate</goal>-->
                        <!--</goals>-->
                    <!--</execution>-->
                <!--</executions>-->
            <!--</plugin>-->
        </plugins>
    </build>
</project>


text:
package com.scaleoutsoftware.soss.hserver.hadoop;

import com.scaleoutsoftware.soss.hserver.MapOutputAccumulator;
import com.scaleoutsoftware.soss.hserver.RunHadoopMapContext;
import com.scaleoutsoftware.soss.hserver.interop.RunMapContext;

import java.io.IOException;

/**
 * Abstraction of the mapping side of the hadoop MR job pipeline.
 *
 * @param <INKEY>  mapper input key type
 * @param <INVALUE>  mapper input value type
 * @param <OUTKEY> mapper output key type
 * @param <OUTVALUE> mapper output value type
 */
public interface MapperWrapper<INKEY, INVALUE, OUTKEY, OUTVALUE> {

    /**
     * Run single input split.
     *
     * @param mapOutputAccumulator mapOutputAccumulator
     * @param split
     * @param splitIndex
     * @throws IOException
     * @throws ClassNotFoundException
     * @throws InterruptedException
     */
    @SuppressWarnings("unchecked")
    void runSplit(MapOutputAccumulator<OUTKEY, OUTVALUE> mapOutputAccumulator, Object split, int splitIndex)
        throws IOException, ClassNotFoundException, InterruptedException;

    Class<OUTKEY> getMapOutputKeyClass();

    Class<OUTVALUE> getMapOutputValueClass();

    ReducerWrapper<OUTKEY, OUTVALUE, OUTKEY, OUTVALUE> getCombiner(MapOutputAccumulator<OUTKEY, OUTVALUE> consumer, RunMapContext<OUTKEY, OUTVALUE> mapContext) throws IOException, ClassNotFoundException, InterruptedException;

    PartitionerWrapper<OUTKEY, OUTVALUE> getPartitioner();

    boolean hasCombiner();
}


text:
package org.swtk.eng.stanford.util.functions;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.swtk.eng.stanford.dto.TreeNode;
import org.swtk.eng.stanford.dto.adapter.TreeNodeAdapter;

import com.trimc.blogger.commons.LogManager;
import com.trimc.blogger.commons.exception.BusinessException;
import com.trimc.blogger.commons.type.EngGrammarUpperType;

public class FindAdjNounsFunction {

	public static LogManager	logger	= new LogManager(FindAdjNounsFunction.class);

	public static Collection<String> process(TreeNode root) throws BusinessException {
		Set<String> set = new TreeSet<String>();

		List<TreeNode> list = TreeNodeAdapter.toList(root);
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < list.size(); i++) {
			TreeNode current = list.get(i);

			boolean isAdj = EngGrammarUpperType.ADJECTIVE == current.getGrammarType().getUpperType();
			boolean isNoun = EngGrammarUpperType.NOUN == current.getGrammarType().getUpperType();
			boolean isNp = current.getText().contains("_");

			if (isAdj) {
				sb.append(current.getText() + " ");
			} else if (isNoun || isNp) {
				sb.append(current.getText());
				set.add(sb.toString().trim());
				sb = new StringBuilder();
			}
		}

		logger.debug("Adj-Nouns Found (total = %s)", set.size());
		return set;
	}
}