text:
package grails.plugins.crm.core;

import groovy.lang.ExpandoMetaClass;
import org.codehaus.groovy.ast.ASTNode;
import org.codehaus.groovy.ast.ClassHelper;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.MethodNode;
import org.codehaus.groovy.ast.Parameter;
import org.codehaus.groovy.ast.PropertyNode;
import org.codehaus.groovy.ast.AnnotationNode;
import org.codehaus.groovy.ast.expr.*;
import org.codehaus.groovy.ast.stmt.BlockStatement;
import org.codehaus.groovy.ast.stmt.EmptyStatement;
import org.codehaus.groovy.ast.stmt.ExpressionStatement;
import org.codehaus.groovy.ast.stmt.IfStatement;
import org.codehaus.groovy.ast.stmt.ReturnStatement;
import org.codehaus.groovy.ast.stmt.Statement;
import org.codehaus.groovy.classgen.VariableScopeVisitor;
import org.codehaus.groovy.control.CompilePhase;
import org.codehaus.groovy.control.SourceUnit;
import org.codehaus.groovy.grails.compiler.injection.GrailsASTUtils;
import org.codehaus.groovy.transform.ASTTransformation;
import org.codehaus.groovy.transform.GroovyASTTransformation;

import java.lang.reflect.Modifier;
import java.util.UUID;

import static org.codehaus.groovy.transform.AbstractASTTransformUtil.*;

@GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS)
public class UuidASTTransformation implements ASTTransformation {

    //private static final Log LOG = LogFactory.getLog(UuidASTTransformation.class);

    public void visit(ASTNode[] nodes, SourceUnit sourceUnit) {

        //System.out.println("Modifying source unit " + sourceUnit.getName());

        ExpandoMetaClass.disableGlobally();

        for (ASTNode astNode : nodes) {
            if (astNode instanceof ClassNode) {
                ClassNode theClass = (ClassNode) astNode;
                AnnotationNode uuidDefinition = GrailsASTUtils.findAnnotation(ClassHelper.make(UuidEntity.class), theClass.getAnnotations());
                Expression indexExpr = uuidDefinition.getMember("index");
                Boolean addIndex = false;
                if(indexExpr != null) {
                    addIndex = ((ConstantExpression) indexExpr).isTrueExpression();
                }

                if (!GrailsASTUtils.hasOrInheritsProperty(theClass, "guid")) {
                    System.out.println("Adding guid field to class " + theClass.getName());
                    theClass.addProperty("guid", Modifier.PUBLIC, ClassHelper.STRING_TYPE, createUUIDMethodCall(), null, null);

                    Statement guidConstraintExpression = createStringConstraint("guid", 36, false);

                    PropertyNode constraints = theClass.getProperty("constraints");
                    if (constraints != null) {
                        if (constraints.getInitialExpression() instanceof ClosureExpression) {
                            ClosureExpression ce = (ClosureExpression) constraints.getInitialExpression();
                            ((BlockStatement) ce.getCode()).addStatement(guidConstraintExpression);
                        } else {
                            System.err.println("Do not know how to add constraints expression to non ClosureExpression " + constraints.getInitialExpression());
                        }
                    } else {
                        Statement[] constraintsStatement = {guidConstraintExpression};
                        BlockStatement closureBlock = new BlockStatement(constraintsStatement, null);
                        ClosureExpression constraintsClosure = new ClosureExpression(Parameter.EMPTY_ARRAY, closureBlock);
                        theClass.addProperty("constraints", Modifier.STATIC | Modifier.PUBLIC, ClassHelper.OBJECT_TYPE, constraintsClosure, null, null);

                    }

                    if(addIndex) {
                        System.out.println("Adding guid index: " + theClass.getNameWithoutPackage().replaceAll("\\B([A-Z])", "_$1").toLowerCase()+"_guid_idx to class " + theClass.getName());

                        Statement guidMappingExpression = createMapping("guid", "index", theClass.getNameWithoutPackage().replaceAll("\\B([A-Z])", "_$1").toLowerCase()+"_guid_idx");

                        PropertyNode mapping = theClass.getProperty("mapping");
                        if (mapping != null) {
                            if (mapping.getInitialExpression() instanceof ClosureExpression) {
                                ClosureExpression ce = (ClosureExpression) mapping.getInitialExpression();
                                ((BlockStatement) ce.getCode()).addStatement(guidMappingExpression);
                            } else {
                                System.err.println("Do not know how to add mapping expression to non ClosureExpression " + mapping.getInitialExpression());
                            }
                        } else {
                            Statement[] mappingStatement = {guidMappingExpression};
                            BlockStatement closureBlock = new BlockStatement(mappingStatement, null);
                            ClosureExpression mappingClosure = new ClosureExpression(Parameter.EMPTY_ARRAY, closureBlock);
                            theClass.addProperty("mapping", Modifier.STATIC | Modifier.PUBLIC, ClassHelper.OBJECT_TYPE, mappingClosure, null, null);
                        }
                    }

                    createHashCode(theClass);
                    createEquals(theClass);
                }

                VariableScopeVisitor scopeVisitor = new VariableScopeVisitor(sourceUnit);
                scopeVisitor.visitClass(theClass);
            }
        }

        ExpandoMetaClass.enableGlobally();
    }

    // This method returns an expression that is used to initialize the newly created property
    private Expression createUUIDMethodCall() {
        Expression randomUUIDExpr = new MethodCallExpression(new ClassExpression(new ClassNode(UUID.class)), "randomUUID", ArgumentListExpression.EMPTY_ARGUMENTS);
        return new MethodCallExpression(randomUUIDExpr, "toString", ArgumentListExpression.EMPTY_ARGUMENTS);
    }

    private Statement createStringConstraint(String propertyName, int maxSize, boolean blank) {
        NamedArgumentListExpression nale = new NamedArgumentListExpression();
        nale.addMapEntryExpression(new MapEntryExpression(new ConstantExpression("maxSize"), new ConstantExpression(36)));
        nale.addMapEntryExpression(new MapEntryExpression(new ConstantExpression("blank"), ConstantExpression.FALSE));

        MethodCallExpression mce = new MethodCallExpression(VariableExpression.THIS_EXPRESSION, propertyName, nale);
        return new ExpressionStatement(mce);
    }

    private Statement createMapping(String propertyName, String mappingName, String mappingValue) {
        NamedArgumentListExpression nale = new NamedArgumentListExpression();
        nale.addMapEntryExpression(new MapEntryExpression(new ConstantExpression(mappingName), new ConstantExpression(mappingValue)));

        MethodCallExpression mce = new MethodCallExpression(VariableExpression.THIS_EXPRESSION, propertyName, nale);
        return new ExpressionStatement(mce);
    }

    private void createHashCode(ClassNode cNode) {
        // make a public method if none exists otherwise try a private method with leading underscore
        boolean hasExistingHashCode = hasDeclaredMethod(cNode, "hashCode", 0);
        if (hasExistingHashCode && hasDeclaredMethod(cNode, "_hashCode", 0)) return;

        System.out.println("Adding hashCode() to class " + cNode.getName());

        final BlockStatement body = new BlockStatement();

        body.addStatement(guidHashStatements(cNode));

        cNode.addMethod(new MethodNode(hasExistingHashCode ? "_hashCode" : "hashCode", hasExistingHashCode ? ACC_PRIVATE : ACC_PUBLIC,
                ClassHelper.int_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, body));
    }

    private Statement guidHashStatements(ClassNode cNode) {
        //Expression getter = new MethodCallExpression(VariableExpression.THIS_EXPRESSION, "getGuid", MethodCallExpression.NO_ARGUMENTS);
        Expression getter = new PropertyExpression(VariableExpression.THIS_EXPRESSION, "guid");
        return new ExpressionStatement(new MethodCallExpression(getter, "hashCode", ArgumentListExpression.EMPTY_ARGUMENTS));
    }

    public static void createEquals(ClassNode cNode) {
        // make a public method if none exists otherwise try a private method with leading underscore
        boolean hasExistingEquals = hasDeclaredMethod(cNode, "equals", 1);
        if (hasExistingEquals && hasDeclaredMethod(cNode, "_equals", 1)) return;

        System.out.println("Adding equals(other) to class " + cNode.getName());

        final BlockStatement body = new BlockStatement();
        VariableExpression other = new VariableExpression("other");

        // some short circuit cases for efficiency
        body.addStatement(returnFalseIfNull(other));
        body.addStatement(returnTrueIfIdentical(VariableExpression.THIS_EXPRESSION, other));

        body.addStatement(returnFalseIfWrongType(cNode, other));

        body.addStatement(returnFalseIfPropertyNotEqual(cNode.getProperty("guid"), other));

        body.addStatement(new IfStatement(
                isTrueExpr(new MethodCallExpression(VariableExpression.SUPER_EXPRESSION, "equals", other)),
                new EmptyStatement(),
                new ReturnStatement(ConstantExpression.FALSE)
        ));

        // default
        body.addStatement(new ReturnStatement(ConstantExpression.TRUE));

        Parameter[] params = {new Parameter(ClassHelper.OBJECT_TYPE, other.getName())};
        cNode.addMethod(new MethodNode(hasExistingEquals ? "_equals" : "equals", hasExistingEquals ? ACC_PRIVATE : ACC_PUBLIC,
                ClassHelper.boolean_TYPE, params, ClassNode.EMPTY_ARRAY, body));
    }
}


text:
The original version of AfterPhylo is available at
[https://github.com/qiyunzhu/AfterPhylo](https://github.com/qiyunzhu/AfterPhylo). The
LICENSE of the modified version is available [here](LICENSE).

The modification alters the behavior of the program by printing the
output to the `STDOUT` instead of printing it to file. The reporting
done by the program to `STDERR` is left unchanged.

redpajama_set_name: RedPajamaGithub


text:
import getWindow from 'ember-user-activity/utils/window';

export default function getScroll(elem, direction) {
  if (elem === null || elem === undefined) {
    return;
  }

  if (elem.jquery) {
    // Convert to DOM element if jQuery was used
    elem = elem[0];
  }

  if (elem === null || elem === undefined) {
    return;
  }

  // `window`/`document` do not have scrollLeft attributes
  // Instead, we look at `pageXOffset`, which is an alias for `scrollX`,
  // But has better browser support (namely IE)
  // https://developer.mozilla.org/en-US/docs/Web/API/Window/pageXOffset
  let windowObj = getWindow(elem);
  if (windowObj) {
    if (direction === 'left') {
      return windowObj.pageXOffset;
    }
    return windowObj.pageYOffset;
  }

  if (direction === 'left') {
    return elem.scrollLeft;
  }

  return elem.scrollTop;
}


text:
/**
 *
 */
package javax.jmdns.impl;

import java.net.InetAddress;

import javax.jmdns.JmDNS;
import javax.jmdns.NetworkTopologyEvent;
import javax.jmdns.NetworkTopologyListener;

/**
 * @author Cédrik Lime, Pierre Frisch
 */
public class NetworkTopologyEventImpl extends NetworkTopologyEvent implements
		Cloneable {

	/**
     *
     */
	private static final long serialVersionUID = 1445606146153550463L;

	private final InetAddress _inetAddress;

	/**
	 * Constructs a Network Topology Event.
	 *
	 * @param jmDNS
	 * @param inetAddress
	 * @exception IllegalArgumentException
	 *                if source is null.
	 */
	public NetworkTopologyEventImpl(JmDNS jmDNS, InetAddress inetAddress) {
		super(jmDNS);
		this._inetAddress = inetAddress;
	}

	NetworkTopologyEventImpl(NetworkTopologyListener jmmDNS,
			InetAddress inetAddress) {
		super(jmmDNS);
		this._inetAddress = inetAddress;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see javax.jmdns.NetworkTopologyEvent#getDNS()
	 */
	@Override
	public JmDNS getDNS() {
		return (this.getSource() instanceof JmDNS ? (JmDNS) getSource() : null);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see javax.jmdns.NetworkTopologyEvent#getInetAddress()
	 */
	@Override
	public InetAddress getInetAddress() {
		return _inetAddress;
	}

	@Override
	public String toString() {
		StringBuilder buf = new StringBuilder();
		buf.append("[" + this.getClass().getSimpleName() + "@"
				+ System.identityHashCode(this) + " ");
		buf.append("\n\tinetAddress: '");
		buf.append(this.getInetAddress());
		buf.append("']");
		// buf.append("' source: ");
		// buf.append("\n\t" + source + "");
		// buf.append("\n]");
		return buf.toString();
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Object#clone()
	 */
	@Override
	public NetworkTopologyEventImpl clone() throws CloneNotSupportedException {
		return new NetworkTopologyEventImpl(getDNS(), getInetAddress());
	}

}


text:
		<title>EVE-MLP Help</title>

In general, I try to make things clear enough to not need documentation;
		if there's anything you think could be clearer, let me know and I'll try to
		fix the app rather than documenting the problem.

That said, some things that I can't think how to easily fix:

When picking a game folder, if you pick a junction point / symlink,
			the directory picker will pick the target of the link instead. To work
			around this, pick a folder inside the game folder (eg. "bin"),
			and MLP will automtically try the parent folder.

For Linux and OSX users, the "wine command" and "wine flags" fields
			are separate so that you can have a common command as default (eg.
			"optirun /usr/bin/wine explorer") with separate flags for each character
			(eg. "/desktop=Main,1920x1080" for your main, "/desktop=Market,800x600"
			for your market alt)


text:
define([
    // Includes all dependant libraries / files.
    ], function() {
        var createToDoResponse = {
            insertToDo 	: insertToDo                            // Method declaration.
        };

        // Function to Call Sync function to insert new todo
        function insertToDo(todoDetails,callback) {
            var dataSetId = "toDo",
                id = localStorage.getItem(sessionKey);
            var params ={
                "request": {                                    // creates request parameters
                    "header":
                    {
                       "sessionId":id
                    },
                    "payload":
                    {
                        "createToDo":
                        {
                            "title":todoDetails.title,
                            "description":todoDetails.description,
                            "deadline":todoDetails.deadline,
                            "assignedTo": todoDetails.assignedTo,
                            "latitude":todoDetails.latitude,
                            "longitude":todoDetails.longitude
                        }
                    }
                }
            };

            // Calling fh Sync to create new Todo
            $fh.sync.doCreate(dataSetId, params,function success(response){         // Return success callback.
                return callback(null,response);
            },function failure(code,message) {                                      // Return failure callback.
                return callback(code,null);
            });
        }
        return createToDoResponse;
    });


text:
package at.mg.androidstudiosandbox.things;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import at.mg.androidstudiosandbox.R;

/**
 * ViewHolder for the RecyclerView
 * <p/>
 * Created by Markus on 12.12.2014.
 */
public class RecyclerListViewHolder extends RecyclerView.ViewHolder {

    public final TextView title;
    public final TextView desc;
    public final TextView date;

    public RecyclerListViewHolder(View itemView) {
        super(itemView);

        title = (TextView) itemView.findViewById(R.id.recentry_title);
        desc = (TextView) itemView.findViewById(R.id.recentry_desc);
        date = (TextView) itemView.findViewById(R.id.recentry_date);

    }
}


text:
// Type definitions for Dojo v1.9
// Project: http://dojotoolkit.org
// Definitions by: Michael Van Sickle <https://github.com/vansimke>
// Definitions: https://github.com/borisyankov/DefinitelyTyped

declare module dojox {

    /**
     * Permalink: http://dojotoolkit.org/api/1.9/dojox/html.html
     *
     * Deprecated.  Should require dojox/html modules directly rather than trying to access them through
     * this module.
     *
     */
    interface html {
    }
    module html {
        /**
         * Permalink: http://dojotoolkit.org/api/1.9/dojox/html/ellipsis.html
         *
         * offers cross-browser support for text-overflow: ellipsis
         * Add "dojoxEllipsis" on any node that you want to ellipsis-ize. In order to function properly,
         * the node with the dojoxEllipsis class set on it should be a child of a node with a defined width.
         * It should also be a block-level element (i.e. <div>) - it will not work on td elements.
         * NOTE: When using the dojoxEllipsis class within tables, the table needs to have the table-layout: fixed style
         *
         */
        interface ellipsis {
        }
        /**
         * Permalink: http://dojotoolkit.org/api/1.9/dojox/html/entities.html
         *
         *
         */
        interface entities {
            /**
             *
             */
            html: any[];
            /**
             *
             */
            latin: any[];
            /**
             * Function to obtain an entity encoding for a specified character
             *
             * @param str The string to process for possible entity encoding to decode.
             * @param m An optional list of character to entity name mappings (array ofarrays).  If not provided, it uses the HTML and Latin entities as theset to map and decode.
             */
            decode(str: any, m: any): void;
            /**
             * Function to obtain an entity encoding for a specified character
             *
             * @param str The string to process for possible entity encoding.
             * @param m An optional list of character to entity name mappings (array ofarrays).  If not provided, it uses the and Latin entities as theset to map and escape.
             */
            encode(str: any, m: any): void;
        }
        /**
         * Permalink: http://dojotoolkit.org/api/1.9/dojox/html/metrics.html
         *
         *
         */
        interface metrics {
            /**
             *
             * @param recalculate
             */
            getCachedFontMeasurements(recalculate: any): any;
            /**
             * Returns an object that has pixel equivilents of standard font size values.
             *
             */
            getFontMeasurements(): Object;
            /**
             *
             */
            getScrollbar(): Object;
            /**
             *
             * @param text
             * @param style
             * @param className               Optional
             */
            getTextBox(text: String, style: Object, className: String): void;
            /**
             *
             */
            initOnFontResize(): void;
        }
        /**
         * Permalink: http://dojotoolkit.org/api/1.9/dojox/html/styles.html
         *
         *
         */
        interface styles {
            /**
             *
             */
            entities: Object;
            /**
             *
             */
            "ext-dojo": Object;
            /**
             *
             */
            metrics: Object;
            /**
             * Getter/Setter
             * If passed a title, enables a that style sheet. All other
             * toggle-able style sheets are disabled.
             * If no argument is passed, returns currently enabled
             * style sheet.
             *
             * @param title               Optional
             */
            activeStyleSheet(title: String): void;
            /**
             * Disables the dynamic style sheet with the name passed in the
             * argument. If no arg is passed, defaults to the default style sheet.
             *
             * @param styleSheetName
             */
            disableStyleSheet(styleSheetName: String): void;
            /**
             * Enables the style sheet with the name passed in the
             * argument. Deafults to the default style sheet.
             *
             * @param styleSheetName
             */
            enableStyleSheet(styleSheetName: String): void;
            /**
             * Creates and returns a dynamically created style sheet
             * used for dynamic styles
             *
             * @param styleSheetName               OptionalThe name given the style sheet so that multiplestyle sheets can be created and referenced. Ifno argument is given, the name "default" is used.
             */
            getDynamicStyleSheet(styleSheetName: String): any;
            /**
             * Returns the style sheet that was initially enabled
             * on document launch.
             * TODO, does not work.
             *
             */
            getPreferredStyleSheet(): void;
            /**
             * Returns a style sheet based on the argument.
             * Searches dynamic style sheets first. If no matches,
             * searches document style sheets.
             *
             * @param styleSheetName               OptionalA title or an href to a style sheet. Title can bean attribute in a tag, or a dynamic style sheetreference. Href can be the name of the file.If no argument, the assumed created dynamic stylesheet is used.
             */
            getStyleSheet(styleSheetName: String): void;
            /**
             * Collects all the style sheets referenced in the HTML page,
             * including any included via @import.
             *
             */
            getStyleSheets(): any;
            /**
             * Searches HTML for style sheets that are "toggle-able" -
             * can be enabled and disabled. These would include sheets
             * with the title attribute, as well as the REL attribute.
             *
             */
            getToggledStyleSheets(): any;
            /**
             * Creates a style and attaches it to a dynamically created stylesheet
             *
             * @param selector A fully qualified class name, as it would appear ina CSS dojo.doc. Start classes with periods, targetnodes with '#'. Large selectors can also be createdlike:"#myDiv.myClass span input"
             * @param declaration A single string that would make up a style block, notincluding the curly braces. Include semi-colons betweenstatements. Do not use JavaScript style declarationsin camel case, use as you would in a CSS dojo.doc:"color:#ffoooo;font-size:12px;margin-left:5px;"
             * @param styleSheetName               OptionalName of the dynamic style sheet this rule should beinserted into. If is not found by that name, it iscreated. If no name is passed, the name "default" isused.
             */
            insertCssRule(selector: String, declaration: String, styleSheetName: String): String;
            /**
             * Not implemented - it seems to have some merit for changing some complex
             * selectors. It's not much use for changing simple ones like "span".
             * For now, simply write a new rule which will cascade over the first.
             *
             * Modifies an existing cssRule
             *
             * @param selector
             * @param declaration
             * @param styleSheetName
             */
            modifyCssRule(selector: any, declaration: any, styleSheetName: any): void;
            /**
             * Removes a cssRule base on the selector and declaration passed
             * The declaration is needed for cases of dupe selectors
             * Only removes DYNAMICALLY created cssRules. If you
             * created it with dh.insertCssRule, it can be removed.
             *
             * @param selector
             * @param declaration
             * @param styleSheetName
             */
            removeCssRule(selector: String, declaration: String, styleSheetName: String): void;
        }
        module styles {
            /**
             * Permalink: http://dojotoolkit.org/api/1.9/dojox/html/styles._ContentSetter.html
             *
             *
             * @param params
             * @param node
             */
            class _ContentSetter {
                constructor(params: Object, node: String);
                /**
                 * Adjust relative paths in html string content to point to this page
                 * Only useful if you grab content from a another folder than the current one
                 *
                 */
                "adjustPaths": boolean;
                /**
                 * Should the content be treated as a full html document,
                 * and the real content stripped of ,  wrapper before injection
                 *
                 */
                "cleanContent": boolean;
                /**
                 * The content to be placed in the node. Can be an HTML string, a node reference, or a enumerable list of nodes
                 *
                 */
                "content": string;
                /**
                 *
                 */
                "executeScripts": boolean;
                /**
                 * Should the content be treated as a full html document,
                 * and the real content stripped of <html> <body> wrapper before injection
                 *
                 */
                "extractContent": boolean;
                /**
                 * Usually only used internally, and auto-generated with each instance
                 *
                 */
                "id": Object;
                /**
                 * An node which will be the parent element that we set content into
                 *
                 */
                "node": HTMLElement;
                /**
                 * Should the node by passed to the parser after the new content is set
                 *
                 */
                "parseContent": boolean;
                /**
                 * Flag passed to parser.  Root for attribute names to search for.   If scopeName is dojo,
                 * will search for data-dojo-type (or dojoType).  For backwards compatibility
                 * reasons defaults to dojo._scopeName (which is "dojo" except when
                 * multi-version support is used, when it will be something like dojo16, dojo20, etc.)
                 *
                 */
                "parserScope": string;
                /**
                 *
                 */
                "referencePath": string;
                /**
                 *
                 */
                "renderStyles": boolean;
                /**
                 *
                 */
                "scriptHasHooks": boolean;
                /**
                 *
                 */
                "scriptHookReplacement": Object;
                /**
                 * Start the child widgets after parsing them.   Only obeyed if parseContent is true.
                 *
                 */
                "startup": boolean;
                /**
                 *
                 */
                empty(): void;
                /**
                 * front-end to the set-content sequence
                 *
                 * @param cont               OptionalAn html string, node or enumerable list of nodes for insertion into the domIf not provided, the object's content property will be used
                 * @param params               Optional
                 */
                set(cont: String, params: Object): any;
                /**
                 * front-end to the set-content sequence
                 *
                 * @param cont               OptionalAn html string, node or enumerable list of nodes for insertion into the domIf not provided, the object's content property will be used
                 * @param params               Optional
                 */
                set(cont: HTMLElement, params: Object): any;
                /**
                 * front-end to the set-content sequence
                 *
                 * @param cont               OptionalAn html string, node or enumerable list of nodes for insertion into the domIf not provided, the object's content property will be used
                 * @param params               Optional
                 */
                set(cont: NodeList, params: Object): any;
                /**
                 * sets the content on the node
                 *
                 */
                setContent(): void;
                /**
                 *
                 */
                tearDown(): void;
                /**
                 * Called after instantiation, but before set();
                 * It allows modification of any of the object properties - including the node and content
                 * provided - before the set operation actually takes place
                 * This implementation extends that of dojo.html._ContentSetter
                 * to add handling for adjustPaths, renderStyles on the html string content before it is set
                 *
                 */
                onBegin(): void;
                /**
                 *
                 * @param err
                 */
                onContentError(err: any): String;
                /**
                 * Called after set(), when the new content has been pushed into the node
                 * It provides an opportunity for post-processing before handing back the node to the caller
                 * This implementation extends that of dojo.html._ContentSetter
                 *
                 */
                onEnd(): any;
                /**
                 *
                 * @param err
                 */
                onExecError(err: any): String;
            }
            /**
             * Permalink: http://dojotoolkit.org/api/1.9/dojox/html/styles.entities.html
             *
             *
             */
            interface entities {
                /**
                 *
                 */
                html: any[];
                /**
                 *
                 */
                latin: any[];
                /**
                 * Function to obtain an entity encoding for a specified character
                 *
                 * @param str The string to process for possible entity encoding to decode.
                 * @param m An optional list of character to entity name mappings (array ofarrays).  If not provided, it uses the HTML and Latin entities as theset to map and decode.
                 */
                decode(str: any, m: any): void;
                /**
                 * Function to obtain an entity encoding for a specified character
                 *
                 * @param str The string to process for possible entity encoding.
                 * @param m An optional list of character to entity name mappings (array ofarrays).  If not provided, it uses the and Latin entities as theset to map and escape.
                 */
                encode(str: any, m: any): void;
            }
            /**
             * Permalink: http://dojotoolkit.org/api/1.9/dojox/html/styles.ext-dojo.html
             *
             *
             */
            interface ext_dojo {
                /**
                 *
                 */
                style: Object;
            }
            /**
             * Permalink: http://dojotoolkit.org/api/1.9/dojox/html/styles.metrics.html
             *
             *
             */
            interface metrics {
                /**
                 *
                 * @param recalculate
                 */
                getCachedFontMeasurements(recalculate: any): any;
                /**
                 * Returns an object that has pixel equivilents of standard font size values.
                 *
                 */
                getFontMeasurements(): Object;
                /**
                 *
                 */
                getScrollbar(): Object;
                /**
                 *
                 * @param text
                 * @param style
                 * @param className               Optional
                 */
                getTextBox(text: String, style: Object, className: String): void;
                /**
                 *
                 */
                initOnFontResize(): void;
            }
        }

        module _base {
            /**
             * Permalink: http://dojotoolkit.org/api/1.9/dojox/html/_base._ContentSetter.html
             *
             *
             * @param params
             * @param node
             */
            class _ContentSetter {
                constructor(params: Object, node: String);
                /**
                 * Adjust relative paths in html string content to point to this page
                 * Only useful if you grab content from a another folder than the current one
                 *
                 */
                "adjustPaths": boolean;
                /**
                 * Should the content be treated as a full html document,
                 * and the real content stripped of ,  wrapper before injection
                 *
                 */
                "cleanContent": boolean;
                /**
                 * The content to be placed in the node. Can be an HTML string, a node reference, or a enumerable list of nodes
                 *
                 */
                "content": string;
                /**
                 *
                 */
                "executeScripts": boolean;
                /**
                 * Should the content be treated as a full html document,
                 * and the real content stripped of <html> <body> wrapper before injection
                 *
                 */
                "extractContent": boolean;
                /**
                 * Usually only used internally, and auto-generated with each instance
                 *
                 */
                "id": Object;
                /**
                 * An node which will be the parent element that we set content into
                 *
                 */
                "node": HTMLElement;
                /**
                 * Should the node by passed to the parser after the new content is set
                 *
                 */
                "parseContent": boolean;
                /**
                 * Flag passed to parser.  Root for attribute names to search for.   If scopeName is dojo,
                 * will search for data-dojo-type (or dojoType).  For backwards compatibility
                 * reasons defaults to dojo._scopeName (which is "dojo" except when
                 * multi-version support is used, when it will be something like dojo16, dojo20, etc.)
                 *
                 */
                "parserScope": string;
                /**
                 *
                 */
                "referencePath": string;
                /**
                 *
                 */
                "renderStyles": boolean;
                /**
                 *
                 */
                "scriptHasHooks": boolean;
                /**
                 *
                 */
                "scriptHookReplacement": Object;
                /**
                 * Start the child widgets after parsing them.   Only obeyed if parseContent is true.
                 *
                 */
                "startup": boolean;
                /**
                 *
                 */
                empty(): void;
                /**
                 * front-end to the set-content sequence
                 *
                 * @param cont               OptionalAn html string, node or enumerable list of nodes for insertion into the domIf not provided, the object's content property will be used
                 * @param params               Optional
                 */
                set(cont: String, params: Object): any;
                /**
                 * front-end to the set-content sequence
                 *
                 * @param cont               OptionalAn html string, node or enumerable list of nodes for insertion into the domIf not provided, the object's content property will be used
                 * @param params               Optional
                 */
                set(cont: HTMLElement, params: Object): any;
                /**
                 * front-end to the set-content sequence
                 *
                 * @param cont               OptionalAn html string, node or enumerable list of nodes for insertion into the domIf not provided, the object's content property will be used
                 * @param params               Optional
                 */
                set(cont: NodeList, params: Object): any;
                /**
                 * sets the content on the node
                 *
                 */
                setContent(): void;
                /**
                 *
                 */
                tearDown(): void;
                /**
                 * Called after instantiation, but before set();
                 * It allows modification of any of the object properties - including the node and content
                 * provided - before the set operation actually takes place
                 * This implementation extends that of dojo.html._ContentSetter
                 * to add handling for adjustPaths, renderStyles on the html string content before it is set
                 *
                 */
                onBegin(): void;
                /**
                 *
                 * @param err
                 */
                onContentError(err: any): String;
                /**
                 * Called after set(), when the new content has been pushed into the node
                 * It provides an opportunity for post-processing before handing back the node to the caller
                 * This implementation extends that of dojo.html._ContentSetter
                 *
                 */
                onEnd(): any;
                /**
                 *
                 * @param err
                 */
                onExecError(err: any): String;
            }
        }

        module ext_dojo {
            module style {
            }

        }

        module format {
        }

    }
}

declare module "dojox/html" {
    var exp: dojox.html
    export=exp;
}
declare module "dojox/html/ellipsis" {
    var exp: dojox.html.ellipsis
    export=exp;
}
declare module "dojox/html/entities" {
    var exp: dojox.html.entities
    export=exp;
}
declare module "dojox/html/metrics" {
    var exp: dojox.html.metrics
    export=exp;
}
declare module "dojox/html/styles" {
    var exp: dojox.html.styles
    export=exp;
}
declare module "dojox/html/styles._ContentSetter" {
    var exp: dojox.html.styles._ContentSetter
    export=exp;
}
declare module "dojox/html/styles.ext-dojo" {
    var exp: dojox.html.styles.ext_dojo
    export=exp;
}
declare module "dojox/html/styles.metrics" {
    var exp: dojox.html.styles.metrics
    export=exp;
}
declare module "dojox/html/styles.entities" {
    var exp: dojox.html.styles.entities
    export=exp;
}
declare module "dojox/html/_base._ContentSetter" {
    var exp: dojox.html._base._ContentSetter
    export=exp;
}


text:
#include "ogr_mssqlspatial.h"

CPL_CVSID("$Id: ogrmssqlspatialdatasource.cpp 27044 2014-03-16 23:41:27Z rouault $");

/************************************************************************/
/*                          OGRMSSQLSpatialDataSource()                 */
/************************************************************************/

OGRMSSQLSpatialDataSource::OGRMSSQLSpatialDataSource()

{
    pszName = NULL;
    pszCatalog = NULL;
    papoLayers = NULL;
    nLayers = 0;

    nKnownSRID = 0;
    panSRID = NULL;
    papoSRS = NULL;

    nGeometryFormat = MSSQLGEOMETRY_NATIVE;

    bUseGeometryColumns = CSLTestBoolean(CPLGetConfigOption("MSSQLSPATIAL_USE_GEOMETRY_COLUMNS", "YES"));
    bListAllTables = CSLTestBoolean(CPLGetConfigOption("MSSQLSPATIAL_LIST_ALL_TABLES", "NO"));
}

/************************************************************************/
/*                         ~OGRMSSQLSpatialDataSource()                 */
/************************************************************************/

OGRMSSQLSpatialDataSource::~OGRMSSQLSpatialDataSource()

{
    int         i;

    CPLFree( pszName );
    CPLFree( pszCatalog );

    for( i = 0; i < nLayers; i++ )
        delete papoLayers[i];

    CPLFree( papoLayers );

    for( i = 0; i < nKnownSRID; i++ )
    {
        if( papoSRS[i] != NULL )
            papoSRS[i]->Release();
    }
    CPLFree( panSRID );
    CPLFree( papoSRS );
}

/************************************************************************/
/*                           TestCapability()                           */
/************************************************************************/

int OGRMSSQLSpatialDataSource::TestCapability( const char * pszCap )

{
    if( EQUAL(pszCap,ODsCCreateLayer) || EQUAL(pszCap,ODsCDeleteLayer) )
        return TRUE;
    else
        return FALSE;
}

/************************************************************************/
/*                              GetLayer()                              */
/************************************************************************/

OGRLayer *OGRMSSQLSpatialDataSource::GetLayer( int iLayer )

{
    if( iLayer < 0 || iLayer >= nLayers )
        return NULL;
    else
        return papoLayers[iLayer];
}

/************************************************************************/
/*                            DeleteLayer()                             */
/************************************************************************/

int OGRMSSQLSpatialDataSource::DeleteLayer( int iLayer )

{
    if( iLayer < 0 || iLayer >= nLayers )
        return OGRERR_FAILURE;

/* -------------------------------------------------------------------- */
/*      Blow away our OGR structures related to the layer.  This is     */
/*      pretty dangerous if anything has a reference to this layer!     */
/* -------------------------------------------------------------------- */
    const char* pszLayerName = papoLayers[iLayer]->GetTableName();
    const char* pszSchemaName = papoLayers[iLayer]->GetSchemaName();

    CPLODBCStatement oStmt( &oSession );
    if (bUseGeometryColumns)
        oStmt.Appendf( "DELETE FROM geometry_columns WHERE f_table_schema = '%s' AND f_table_name = '%s'\n",
            pszSchemaName, pszLayerName );
    oStmt.Appendf("DROP TABLE [%s].[%s]", pszSchemaName, pszLayerName );

    CPLDebug( "MSSQLSpatial", "DeleteLayer(%s)", pszLayerName );

    delete papoLayers[iLayer];
    memmove( papoLayers + iLayer, papoLayers + iLayer + 1,
             sizeof(void *) * (nLayers - iLayer - 1) );
    nLayers--;

    if ( strlen(pszLayerName) == 0 )
        return OGRERR_NONE;

/* -------------------------------------------------------------------- */
/*      Remove from the database.                                       */
/* -------------------------------------------------------------------- */

    oSession.BeginTransaction();

    if( !oStmt.ExecuteSQL() )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                    "Error deleting layer: %s", GetSession()->GetLastError() );

        return OGRERR_FAILURE;
    }

    oSession.CommitTransaction();

    return OGRERR_NONE;
}

/************************************************************************/
/*                            CreateLayer()                             */
/************************************************************************/

OGRLayer * OGRMSSQLSpatialDataSource::CreateLayer( const char * pszLayerName,
                                          OGRSpatialReference *poSRS,
                                          OGRwkbGeometryType eType,
                                          char ** papszOptions )

{
    char                *pszTableName = NULL;
    char                *pszSchemaName = NULL;
    const char          *pszGeomType = NULL;
    const char          *pszGeomColumn = NULL;
    int                 nCoordDimension = 3;

    /* determine the dimension */
    if( eType == wkbFlatten(eType) )
        nCoordDimension = 2;

    if( CSLFetchNameValue( papszOptions, "DIM") != NULL )
        nCoordDimension = atoi(CSLFetchNameValue( papszOptions, "DIM"));

    /* MSSQL Schema handling:
       Extract schema name from input layer name or passed with -lco SCHEMA.
       Set layer name to "schema.table" or to "table" if schema is not
       specified
    */
    const char* pszDotPos = strstr(pszLayerName,".");
    if ( pszDotPos != NULL )
    {
      int length = pszDotPos - pszLayerName;
      pszSchemaName = (char*)CPLMalloc(length+1);
      strncpy(pszSchemaName, pszLayerName, length);
      pszSchemaName[length] = '\0';

      if( CSLFetchBoolean(papszOptions,"LAUNDER", TRUE) )
          pszTableName = LaunderName( pszDotPos + 1 ); //skip "."
      else
          pszTableName = CPLStrdup( pszDotPos + 1 ); //skip "."
    }
    else
    {
      pszSchemaName = NULL;
      if( CSLFetchBoolean(papszOptions,"LAUNDER", TRUE) )
          pszTableName = LaunderName( pszLayerName ); //skip "."
      else
          pszTableName = CPLStrdup( pszLayerName ); //skip "."
    }

    if( CSLFetchNameValue( papszOptions, "SCHEMA" ) != NULL )
    {
        CPLFree(pszSchemaName);
        pszSchemaName = CPLStrdup(CSLFetchNameValue( papszOptions, "SCHEMA" ));
    }

    if (pszSchemaName == NULL)
        pszSchemaName = CPLStrdup("dbo");

/* -------------------------------------------------------------------- */
/*      Do we already have this layer?  If so, should we blow it        */
/*      away?                                                           */
/* -------------------------------------------------------------------- */
    int iLayer;

    for( iLayer = 0; iLayer < nLayers; iLayer++ )
    {
        if( EQUAL(pszLayerName,papoLayers[iLayer]->GetTableName()) )
        {
            if( CSLFetchNameValue( papszOptions, "OVERWRITE" ) != NULL
                && !EQUAL(CSLFetchNameValue(papszOptions,"OVERWRITE"),"NO") )
            {
                if (!pszSchemaName)
                    pszSchemaName = CPLStrdup(papoLayers[iLayer]->GetSchemaName());

                DeleteLayer( iLayer );
            }
            else
            {
                CPLError( CE_Failure, CPLE_AppDefined,
                          "Layer %s already exists, CreateLayer failed.\n"
                          "Use the layer creation option OVERWRITE=YES to "
                          "replace it.",
                          pszLayerName );

                CPLFree( pszSchemaName );
                CPLFree( pszTableName );
                return NULL;
            }
        }
    }

/* -------------------------------------------------------------------- */
/*      Handle the GEOM_TYPE option.                                    */
/* -------------------------------------------------------------------- */
    if ( eType != wkbNone )
    {
        pszGeomType = CSLFetchNameValue( papszOptions, "GEOM_TYPE" );

        if( !pszGeomType )
            pszGeomType = "geometry";

        if( !EQUAL(pszGeomType, "geometry")
            && !EQUAL(pszGeomType, "geography"))
        {
            CPLError( CE_Failure, CPLE_AppDefined,
                      "FORMAT=%s not recognised or supported.",
                      pszGeomType );

            CPLFree( pszSchemaName );
            CPLFree( pszTableName );
            return NULL;
        }

        /* determine the geometry column name */
        pszGeomColumn =  CSLFetchNameValue( papszOptions, "GEOM_NAME");
        if (!pszGeomColumn)
            pszGeomColumn = "ogr_geometry";
    }

/* -------------------------------------------------------------------- */
/*      Initialize the metadata tables                                  */
/* -------------------------------------------------------------------- */

    if (InitializeMetadataTables() != OGRERR_NONE)
    {
        CPLFree( pszSchemaName );
        CPLFree( pszTableName );
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Try to get the SRS Id of this spatial reference system,         */
/*      adding to the srs table if needed.                              */
/* -------------------------------------------------------------------- */
    int nSRSId = 0;

    if( CSLFetchNameValue( papszOptions, "SRID") != NULL )
        nSRSId = atoi(CSLFetchNameValue( papszOptions, "SRID"));

    if( nSRSId == 0 && poSRS != NULL )
        nSRSId = FetchSRSId( poSRS );

/* -------------------------------------------------------------------- */
/*      Create a new table and create a new entry in the geometry,      */
/*      geometry_columns metadata table.                                */
/* -------------------------------------------------------------------- */

    CPLODBCStatement oStmt( &oSession );

    if( eType != wkbNone && bUseGeometryColumns)
    {
        const char *pszGeometryType = OGRToOGCGeomType(eType);

        oStmt.Appendf( "DELETE FROM geometry_columns WHERE f_table_schema = '%s' "
            "AND f_table_name = '%s'\n", pszSchemaName, pszTableName );

        oStmt.Appendf("INSERT INTO [geometry_columns] ([f_table_catalog], [f_table_schema] ,[f_table_name], "
            "[f_geometry_column],[coord_dimension],[srid],[geometry_type]) VALUES ('%s', '%s', '%s', '%s', %d, %d, '%s')\n",
            pszCatalog, pszSchemaName, pszTableName, pszGeomColumn, nCoordDimension, nSRSId, pszGeometryType );
    }

    if( eType == wkbNone )
    {
        oStmt.Appendf("CREATE TABLE [%s].[%s] ([ogr_fid] [int] IDENTITY(1,1) NOT NULL"
            "CONSTRAINT [PK_%s] PRIMARY KEY CLUSTERED ([ogr_fid] ASC))",
            pszSchemaName, pszTableName, pszTableName);
    }
    else
    {
        oStmt.Appendf("CREATE TABLE [%s].[%s] ([ogr_fid] [int] IDENTITY(1,1) NOT NULL, "
            "[%s] [%s] NULL, CONSTRAINT [PK_%s] PRIMARY KEY CLUSTERED ([ogr_fid] ASC))",
            pszSchemaName, pszTableName, pszGeomColumn, pszGeomType, pszTableName);
    }
    oSession.BeginTransaction();

    if( !oStmt.ExecuteSQL() )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                    "Error creating layer: %s", GetSession()->GetLastError() );

        return NULL;
    }

    oSession.CommitTransaction();

/* -------------------------------------------------------------------- */
/*      Create the layer object.                                        */
/* -------------------------------------------------------------------- */
    OGRMSSQLSpatialTableLayer   *poLayer;

    poLayer = new OGRMSSQLSpatialTableLayer( this );

    poLayer->SetLaunderFlag( CSLFetchBoolean(papszOptions,"LAUNDER",TRUE) );
    poLayer->SetPrecisionFlag( CSLFetchBoolean(papszOptions,"PRECISION",TRUE));

    char *pszWKT = NULL;
    if( poSRS && poSRS->exportToWkt( &pszWKT ) != OGRERR_NONE )
    {
        CPLFree(pszWKT);
        pszWKT = NULL;
    }

    if (poLayer->Initialize(pszSchemaName, pszTableName, pszGeomColumn, nCoordDimension, nSRSId, pszWKT, eType) == OGRERR_FAILURE)
    {
        CPLFree( pszSchemaName );
        CPLFree( pszTableName );
        CPLFree( pszWKT );
        return NULL;
    }

    CPLFree( pszSchemaName );
    CPLFree( pszTableName );
    CPLFree( pszWKT );

/* -------------------------------------------------------------------- */
/*      Add layer to data source layer list.                            */
/* -------------------------------------------------------------------- */
    papoLayers = (OGRMSSQLSpatialTableLayer **)
        CPLRealloc( papoLayers,  sizeof(OGRMSSQLSpatialTableLayer *) * (nLayers+1) );

    papoLayers[nLayers++] = poLayer;

    return poLayer;
}

/************************************************************************/
/*                             OpenTable()                              */
/************************************************************************/

int OGRMSSQLSpatialDataSource::OpenTable( const char *pszSchemaName, const char *pszTableName,
                    const char *pszGeomCol, int nCoordDimension,
                    int nSRID, const char *pszSRText, OGRwkbGeometryType eType, int bUpdate )

{
/* -------------------------------------------------------------------- */
/*      Create the layer object.                                        */
/* -------------------------------------------------------------------- */
    OGRMSSQLSpatialTableLayer  *poLayer = new OGRMSSQLSpatialTableLayer( this );

    if( poLayer->Initialize( pszSchemaName, pszTableName, pszGeomCol, nCoordDimension, nSRID, pszSRText, eType ) )
    {
        delete poLayer;
        return FALSE;
    }

/* -------------------------------------------------------------------- */
/*      Add layer to data source layer list.                            */
/* -------------------------------------------------------------------- */
    papoLayers = (OGRMSSQLSpatialTableLayer **)
        CPLRealloc( papoLayers,  sizeof(OGRMSSQLSpatialTableLayer *) * (nLayers+1) );
    papoLayers[nLayers++] = poLayer;

    return TRUE;
}

/************************************************************************/
/*                       GetLayerCount()                                */
/************************************************************************/

int OGRMSSQLSpatialDataSource::GetLayerCount()
{
    return nLayers;
}

/************************************************************************/
/*                       ParseValue()                                   */
/************************************************************************/

int OGRMSSQLSpatialDataSource::ParseValue(char** pszValue, char* pszSource, const char* pszKey, int nStart, int nNext, int nTerm, int bRemove)
{
    int nLen = strlen(pszKey);
    if ((*pszValue) == NULL && nStart + nLen < nNext &&
            EQUALN(pszSource + nStart, pszKey, nLen))
    {
        *pszValue = (char*)CPLMalloc( sizeof(char) * (nNext - nStart - nLen + 1) );
        if (*pszValue)
            strncpy(*pszValue, pszSource + nStart + nLen, nNext - nStart - nLen);
        (*pszValue)[nNext - nStart - nLen] = 0;

        if (bRemove)
        {
            // remove the value from the source string
            if (pszSource[nNext] == ';')
                memmove( pszSource + nStart, pszSource + nNext + 1, nTerm - nNext);
            else
                memmove( pszSource + nStart, pszSource + nNext, nTerm - nNext + 1);
        }
        return TRUE;
    }
    return FALSE;
}

/************************************************************************/
/*                                Open()                                */
/************************************************************************/

int OGRMSSQLSpatialDataSource::Open( const char * pszNewName, int bUpdate,
                             int bTestOpen )

{
    CPLAssert( nLayers == 0 );

    if( !EQUALN(pszNewName,"MSSQL:",6) )
    {
        if( !bTestOpen )
            CPLError( CE_Failure, CPLE_AppDefined,
                      "%s does not conform to MSSSQLSpatial naming convention,"
                      " MSSQL:*\n", pszNewName );
        return FALSE;
    }

    /* Determine if the connection string contains specific values */
    char* pszTableSpec = NULL;
    char* pszGeometryFormat = NULL;
    char* pszConnectionName = CPLStrdup(pszNewName + 6);
    char* pszDriver = NULL;
    int nCurrent, nNext, nTerm;
    nCurrent = nNext = nTerm = strlen(pszConnectionName);

    while (nCurrent > 0)
    {
        --nCurrent;
        if (pszConnectionName[nCurrent] == ';')
        {
            nNext = nCurrent;
            continue;
        }

        if (ParseValue(&pszCatalog, pszConnectionName, "database=",
            nCurrent, nNext, nTerm, FALSE))
            continue;

        if (ParseValue(&pszTableSpec, pszConnectionName, "tables=",
            nCurrent, nNext, nTerm, TRUE))
            continue;

        if (ParseValue(&pszDriver, pszConnectionName, "driver=",
            nCurrent, nNext, nTerm, FALSE))
            continue;

        if (ParseValue(&pszGeometryFormat, pszConnectionName,
            "geometryformat=", nCurrent, nNext, nTerm, TRUE))
        {
            if (EQUALN(pszGeometryFormat,"wkbzm",5))
                nGeometryFormat = MSSQLGEOMETRY_WKBZM;
            else if (EQUALN(pszGeometryFormat, "wkb",3))
                nGeometryFormat = MSSQLGEOMETRY_WKB;
            else if (EQUALN(pszGeometryFormat,"wkt",3))
                nGeometryFormat = MSSQLGEOMETRY_WKT;
            else if (EQUALN(pszGeometryFormat,"native",6))
                nGeometryFormat = MSSQLGEOMETRY_NATIVE;
            else
            {
                CPLError( CE_Failure, CPLE_AppDefined,
                    "Invalid geometry type specified: %s,"
                      " MSSQL:*\n", pszGeometryFormat );

                CPLFree(pszTableSpec);
                CPLFree(pszGeometryFormat);
                CPLFree(pszConnectionName);
                CPLFree(pszDriver);
                return FALSE;
            }

            CPLFree(pszGeometryFormat);
            pszGeometryFormat = NULL;
            continue;
        }
    }

    /* Determine if the connection string contains the catalog portion */
    if( pszCatalog == NULL )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                      "'%s' does not contain the 'database' portion\n", pszNewName );

        CPLFree(pszTableSpec);
        CPLFree(pszGeometryFormat);
        CPLFree(pszConnectionName);
        CPLFree(pszDriver);
        return FALSE;
    }

    pszName = CPLStrdup(pszNewName);

    char  **papszTableNames=NULL;
    char  **papszSchemaNames=NULL;
    char  **papszGeomColumnNames=NULL;
    char  **papszCoordDimensions=NULL;
    char  **papszSRIds=NULL;
    char  **papszSRTexts=NULL;

    /* Determine if the connection string contains the TABLES portion */
    if( pszTableSpec != NULL )
    {
        char          **papszTableList;
        int             i;

        papszTableList = CSLTokenizeString2( pszTableSpec, ",", 0 );

        for( i = 0; i < CSLCount(papszTableList); i++ )
        {
            char      **papszQualifiedParts;

            // Get schema and table name
            papszQualifiedParts = CSLTokenizeString2( papszTableList[i],
                                                      ".", 0 );

            /* Find the geometry column name if specified */
            if( CSLCount( papszQualifiedParts ) >= 1 )
            {
                char* pszGeomColumnName = NULL;
                char* pos = strchr(papszQualifiedParts[CSLCount( papszQualifiedParts ) - 1], '(');
                if (pos != NULL)
                {
                    *pos = '\0';
                    pszGeomColumnName = pos+1;
                    int len = strlen(pszGeomColumnName);
                    if (len > 0)
                        pszGeomColumnName[len - 1] = '\0';
                }
                papszGeomColumnNames = CSLAddString( papszGeomColumnNames,
                        pszGeomColumnName ? pszGeomColumnName : "");
            }

            if( CSLCount( papszQualifiedParts ) == 2 )
            {
                papszSchemaNames = CSLAddString( papszSchemaNames,
                                                papszQualifiedParts[0] );
                papszTableNames = CSLAddString( papszTableNames,
                                                papszQualifiedParts[1] );
            }
            else if( CSLCount( papszQualifiedParts ) == 1 )
            {
                papszSchemaNames = CSLAddString( papszSchemaNames, "dbo");
                papszTableNames = CSLAddString( papszTableNames,
                                                papszQualifiedParts[0] );
            }

            CSLDestroy(papszQualifiedParts);
        }

        CSLDestroy(papszTableList);
    }

    CPLFree(pszTableSpec);

    /* Initialize the SQL Server connection. */
    int nResult;
    if ( pszDriver != NULL )
    {
        /* driver has been specified */
        CPLDebug( "OGR_MSSQLSpatial", "EstablishSession(Connection:\"%s\")", pszConnectionName);
        nResult = oSession.EstablishSession( pszConnectionName, "", "" );
    }
    else
    {
        /* no driver has been specified, defautls to SQL Server */
        CPLDebug( "OGR_MSSQLSpatial", "EstablishSession(Connection:\"%s\")", pszConnectionName);
        nResult = oSession.EstablishSession( CPLSPrintf("DRIVER=SQL Server;%s", pszConnectionName), "", "" );
    }

    CPLFree(pszDriver);

    if( !nResult )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "Unable to initialize connection to the server for %s,\n"
                  "%s", pszNewName, oSession.GetLastError() );

        CSLDestroy( papszTableNames );
        CSLDestroy( papszSchemaNames );
        CSLDestroy( papszGeomColumnNames );
        CSLDestroy( papszCoordDimensions );
        CSLDestroy( papszSRIds );
        CSLDestroy( papszSRTexts );
        CPLFree(pszGeometryFormat);
        CPLFree(pszConnectionName);
        return FALSE;
    }

    char** papszTypes = NULL;

    /* if requesting all user database table then this takes priority */
 	if (papszTableNames == NULL && bListAllTables)
 	{
 	    CPLODBCStatement oStmt( &oSession );

 	    oStmt.Append( "select sys.schemas.name, sys.schemas.name + '.' + sys.objects.name, sys.columns.name from sys.columns join sys.types on sys.columns.system_type_id = sys.types.system_type_id and sys.columns.user_type_id = sys.types.user_type_id join sys.objects on sys.objects.object_id = sys.columns.object_id join sys.schemas on sys.objects.schema_id = sys.schemas.schema_id where (sys.types.name = 'geometry' or sys.types.name = 'geography') and (sys.objects.type = 'U' or sys.objects.type = 'V') union all select sys.schemas.name, sys.schemas.name + '.' + sys.objects.name, '' from sys.objects join sys.schemas on sys.objects.schema_id = sys.schemas.schema_id where not exists (select * from sys.columns sc1 join sys.types on sc1.system_type_id = sys.types.system_type_id where (sys.types.name = 'geometry' or sys.types.name = 'geography') and sys.objects.object_id = sc1.object_id) and (sys.objects.type = 'U' or sys.objects.type = 'V')" );

 	    if( oStmt.ExecuteSQL() )
 	    {
 	        while( oStmt.Fetch() )
 	        {
 	            papszSchemaNames =
 	                    CSLAddString( papszSchemaNames, oStmt.GetColData(0) );
 	            papszTableNames =
 	                    CSLAddString( papszTableNames, oStmt.GetColData(1) );
 	            papszGeomColumnNames =
 	                    CSLAddString( papszGeomColumnNames, oStmt.GetColData(2) );
 	        }
 	    }
 	}

    /* Determine the available tables if not specified. */
    if (papszTableNames == NULL && bUseGeometryColumns)
    {
        CPLODBCStatement oStmt( &oSession );

        /* Use join to make sure the existence of the referred column/table */
        oStmt.Append( "SELECT f_table_schema, f_table_name, f_geometry_column, coord_dimension, g.srid, srtext, geometry_type FROM dbo.geometry_columns g JOIN INFORMATION_SCHEMA.COLUMNS ON f_table_schema = TABLE_SCHEMA and f_table_name = TABLE_NAME and f_geometry_column = COLUMN_NAME left outer join dbo.spatial_ref_sys s on g.srid = s.srid");

        if( oStmt.ExecuteSQL() )
        {
            while( oStmt.Fetch() )
            {
                papszSchemaNames =
                        CSLAddString( papszSchemaNames, oStmt.GetColData(0) );
                papszTableNames =
                        CSLAddString( papszTableNames, oStmt.GetColData(1) );
                papszGeomColumnNames =
                        CSLAddString( papszGeomColumnNames, oStmt.GetColData(2) );
                papszCoordDimensions =
                        CSLAddString( papszCoordDimensions, oStmt.GetColData(3) );
                papszSRIds =
                        CSLAddString( papszSRIds, oStmt.GetColData(4) );
                papszSRTexts =
                        CSLAddString( papszSRTexts, oStmt.GetColData(5) );
                papszTypes =
                        CSLAddString( papszTypes, oStmt.GetColData(6) );
            }
        }
        else
        {
            /* probably the table is missing at all */
            InitializeMetadataTables();
        }
    }

    /* Query catalog for tables having geometry columns */
    if (papszTableNames == NULL)
    {
        CPLODBCStatement oStmt( &oSession );

        oStmt.Append( "SELECT sys.schemas.name, sys.schemas.name + '.' + sys.objects.name, sys.columns.name from sys.columns join sys.types on sys.columns.system_type_id = sys.types.system_type_id and sys.columns.user_type_id = sys.types.user_type_id join sys.objects on sys.objects.object_id = sys.columns.object_id join sys.schemas on sys.objects.schema_id = sys.schemas.schema_id where (sys.types.name = 'geometry' or sys.types.name = 'geography') and (sys.objects.type = 'U' or sys.objects.type = 'V')");

        if( oStmt.ExecuteSQL() )
        {
            while( oStmt.Fetch() )
            {
                papszSchemaNames =
                        CSLAddString( papszSchemaNames, oStmt.GetColData(0) );
                papszTableNames =
                        CSLAddString( papszTableNames, oStmt.GetColData(1) );
                papszGeomColumnNames =
                        CSLAddString( papszGeomColumnNames, oStmt.GetColData(2) );
            }
        }
    }

    int nSRId, nCoordDimension;
    OGRwkbGeometryType eType;

    for( int iTable = 0;
         papszTableNames != NULL && papszTableNames[iTable] != NULL;
         iTable++ )
    {
        if (papszSRIds != NULL)
            nSRId = atoi(papszSRIds[iTable]);
        else
            nSRId = -1;

        if (papszCoordDimensions != NULL)
            nCoordDimension = atoi(papszCoordDimensions[iTable]);
        else
            nCoordDimension = 2;

        if (papszTypes != NULL)
            eType = OGRFromOGCGeomType(papszTypes[iTable]);
        else
            eType = wkbUnknown;

        if( strlen(papszGeomColumnNames[iTable]) > 0 )
            OpenTable( papszSchemaNames[iTable], papszTableNames[iTable], papszGeomColumnNames[iTable],
                    nCoordDimension, nSRId, papszSRTexts? papszSRTexts[iTable] : NULL, eType, bUpdate );
        else
            OpenTable( papszSchemaNames[iTable], papszTableNames[iTable], NULL,
                    nCoordDimension, nSRId, papszSRTexts? papszSRTexts[iTable] : NULL, wkbNone, bUpdate );
    }

    CSLDestroy( papszTableNames );
    CSLDestroy( papszSchemaNames );
    CSLDestroy( papszGeomColumnNames );
    CSLDestroy( papszCoordDimensions );
    CSLDestroy( papszSRIds );
    CSLDestroy( papszSRTexts );
    CSLDestroy( papszTypes );

    CPLFree(pszGeometryFormat);
    CPLFree(pszConnectionName);

    bDSUpdate = bUpdate;

    return TRUE;
}

/************************************************************************/
/*                             ExecuteSQL()                             */
/************************************************************************/

OGRLayer * OGRMSSQLSpatialDataSource::ExecuteSQL( const char *pszSQLCommand,
                                          OGRGeometry *poSpatialFilter,
                                          const char *pszDialect )

{
/* -------------------------------------------------------------------- */
/*      Use generic implementation for recognized dialects              */
/* -------------------------------------------------------------------- */
    if( IsGenericSQLDialect(pszDialect) )
        return OGRDataSource::ExecuteSQL( pszSQLCommand,
                                          poSpatialFilter,
                                          pszDialect );

/* -------------------------------------------------------------------- */
/*      Special case DELLAYER: command.                                 */
/* -------------------------------------------------------------------- */
    if( EQUALN(pszSQLCommand,"DELLAYER:",9) )
    {
        const char *pszLayerName = pszSQLCommand + 9;

        while( *pszLayerName == ' ' )
            pszLayerName++;

        for( int iLayer = 0; iLayer < nLayers; iLayer++ )
        {
            if( EQUAL(papoLayers[iLayer]->GetName(),
                      pszLayerName ))
            {
                DeleteLayer( iLayer );
                break;
            }
        }
        return NULL;
    }

    CPLDebug( "MSSQLSpatial", "ExecuteSQL(%s) called.", pszSQLCommand );

    if( EQUALN(pszSQLCommand, "DROP SPATIAL INDEX ON ", 22) )
    {
        /* Handle command to drop a spatial index. */
        OGRMSSQLSpatialTableLayer  *poLayer = new OGRMSSQLSpatialTableLayer( this );

        if (poLayer)
        {
            if( poLayer->Initialize( "dbo", pszSQLCommand + 22, NULL, 0, 0, NULL, wkbUnknown ) != CE_None )
            {
                CPLError( CE_Failure, CPLE_AppDefined,
                      "Failed to initialize layer '%s'", pszSQLCommand + 22 );
            }
            poLayer->DropSpatialIndex();
            delete poLayer;
        }
        return NULL;
    }
    else if( EQUALN(pszSQLCommand, "CREATE SPATIAL INDEX ON ", 24) )
    {
        /* Handle command to create a spatial index. */
        OGRMSSQLSpatialTableLayer  *poLayer = new OGRMSSQLSpatialTableLayer( this );

        if (poLayer)
        {
            if( poLayer->Initialize( "dbo", pszSQLCommand + 24, NULL, 0, 0, NULL, wkbUnknown ) != CE_None )
            {
                CPLError( CE_Failure, CPLE_AppDefined,
                      "Failed to initialize layer '%s'", pszSQLCommand + 24 );
            }
            poLayer->CreateSpatialIndex();
            delete poLayer;
        }
        return NULL;
    }

    /* Execute the command natively */
    CPLODBCStatement *poStmt = new CPLODBCStatement( &oSession );
    poStmt->Append( pszSQLCommand );

    if( !poStmt->ExecuteSQL() )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "%s", oSession.GetLastError() );
        delete poStmt;
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Are there result columns for this statement?                    */
/* -------------------------------------------------------------------- */
    if( poStmt->GetColCount() == 0 )
    {
        delete poStmt;
        CPLErrorReset();
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Create a results layer.  It will take ownership of the          */
/*      statement.                                                      */
/* -------------------------------------------------------------------- */

    OGRMSSQLSpatialSelectLayer *poLayer = NULL;

    poLayer = new OGRMSSQLSpatialSelectLayer( this, poStmt );

    if( poSpatialFilter != NULL )
        poLayer->SetSpatialFilter( poSpatialFilter );

    return poLayer;
}

/************************************************************************/
/*                          ReleaseResultSet()                          */
/************************************************************************/

void OGRMSSQLSpatialDataSource::ReleaseResultSet( OGRLayer * poLayer )

{
    delete poLayer;
}

/************************************************************************/
/*                            LaunderName()                             */
/************************************************************************/

char *OGRMSSQLSpatialDataSource::LaunderName( const char *pszSrcName )

{
    char    *pszSafeName = CPLStrdup( pszSrcName );
    int     i;

    for( i = 0; pszSafeName[i] != '\0'; i++ )
    {
        pszSafeName[i] = (char) tolower( pszSafeName[i] );
        if( pszSafeName[i] == '-' || pszSafeName[i] == '#' )
            pszSafeName[i] = '_';
    }

    return pszSafeName;
}

/************************************************************************/
/*                      InitializeMetadataTables()                      */
/*                                                                      */
/*      Create the metadata tables (SPATIAL_REF_SYS and                 */
/*      GEOMETRY_COLUMNS).                                              */
/************************************************************************/

OGRErr OGRMSSQLSpatialDataSource::InitializeMetadataTables()

{
    if (bUseGeometryColumns)
    {
        CPLODBCStatement oStmt( &oSession );

        oStmt.Append( "IF NOT EXISTS (SELECT * FROM sys.objects WHERE "
            "object_id = OBJECT_ID(N'[dbo].[geometry_columns]') AND type in (N'U')) "
            "CREATE TABLE geometry_columns (f_table_catalog varchar(128) not null, "
            "f_table_schema varchar(128) not null, f_table_name varchar(256) not null, "
            "f_geometry_column varchar(256) not null, coord_dimension integer not null, "
            "srid integer not null, geometry_type varchar(30) not null, "
            "CONSTRAINT geometry_columns_pk PRIMARY KEY (f_table_catalog, "
            "f_table_schema, f_table_name, f_geometry_column));\n" );

        oStmt.Append( "IF NOT EXISTS (SELECT * FROM sys.objects "
            "WHERE object_id = OBJECT_ID(N'[dbo].[spatial_ref_sys]') AND type in (N'U')) "
            "CREATE TABLE spatial_ref_sys (srid integer not null "
            "PRIMARY KEY, auth_name varchar(256), auth_srid integer, srtext varchar(2048), proj4text varchar(2048))" );

        oSession.BeginTransaction();

        if( !oStmt.ExecuteSQL() )
        {
            CPLError( CE_Failure, CPLE_AppDefined,
                        "Error initializing the metadata tables : %s", GetSession()->GetLastError() );
            return OGRERR_FAILURE;
        }

        oSession.CommitTransaction();
    }

    return OGRERR_NONE;
}

/************************************************************************/
/*                              FetchSRS()                              */
/*                                                                      */
/*      Return a SRS corresponding to a particular id.  Note that       */
/*      reference counting should be honoured on the returned           */
/*      OGRSpatialReference, as handles may be cached.                  */
/************************************************************************/

OGRSpatialReference *OGRMSSQLSpatialDataSource::FetchSRS( int nId )

{
    if( nId <= 0 )
        return NULL;

/* -------------------------------------------------------------------- */
/*      First, we look through our SRID cache, is it there?             */
/* -------------------------------------------------------------------- */
    int  i;

    for( i = 0; i < nKnownSRID; i++ )
    {
        if( panSRID[i] == nId )
            return papoSRS[i];
    }

    OGRSpatialReference *poSRS = NULL;

/* -------------------------------------------------------------------- */
/*      Try looking up in spatial_ref_sys table                         */
/* -------------------------------------------------------------------- */
    if (bUseGeometryColumns)
    {
        CPLODBCStatement oStmt( GetSession() );
        oStmt.Appendf( "SELECT srtext FROM spatial_ref_sys WHERE srid = %d", nId );

        if( oStmt.ExecuteSQL() && oStmt.Fetch() )
        {
            if ( oStmt.GetColData( 0 ) )
            {
                poSRS = new OGRSpatialReference();
                char* pszWKT = (char*)oStmt.GetColData( 0 );
                if( poSRS->importFromWkt( &pszWKT ) != OGRERR_NONE )
                {
                    delete poSRS;
                    poSRS = NULL;
                }
            }
        }
    }

/* -------------------------------------------------------------------- */
/*      Try looking up the EPSG list                                    */
/* -------------------------------------------------------------------- */
    if (!poSRS)
    {
        poSRS = new OGRSpatialReference();
        if( poSRS->importFromEPSG( nId ) != OGRERR_NONE )
        {
            delete poSRS;
            poSRS = NULL;
        }
    }

/* -------------------------------------------------------------------- */
/*      Add to the cache.                                               */
/* -------------------------------------------------------------------- */
    if (poSRS)
    {
        panSRID = (int *) CPLRealloc(panSRID,sizeof(int) * (nKnownSRID+1) );
        papoSRS = (OGRSpatialReference **)
            CPLRealloc(papoSRS, sizeof(void*) * (nKnownSRID + 1) );
        panSRID[nKnownSRID] = nId;
        papoSRS[nKnownSRID] = poSRS;
        nKnownSRID++;
    }

    return poSRS;
}

/************************************************************************/
/*                             FetchSRSId()                             */
/*                                                                      */
/*      Fetch the id corresponding to an SRS, and if not found, add     */
/*      it to the table.                                                */
/************************************************************************/

int OGRMSSQLSpatialDataSource::FetchSRSId( OGRSpatialReference * poSRS)

{
    char                *pszWKT = NULL;
    int                 nSRSId = 0;
    const char*         pszAuthorityName;

    if( poSRS == NULL )
        return 0;

    OGRSpatialReference oSRS(*poSRS);
    poSRS = NULL;

    pszAuthorityName = oSRS.GetAuthorityName(NULL);

    if( pszAuthorityName == NULL || strlen(pszAuthorityName) == 0 )
    {
/* -------------------------------------------------------------------- */
/*      Try to identify an EPSG code                                    */
/* -------------------------------------------------------------------- */
        oSRS.AutoIdentifyEPSG();

        pszAuthorityName = oSRS.GetAuthorityName(NULL);
        if (pszAuthorityName != NULL && EQUAL(pszAuthorityName, "EPSG"))
        {
            const char* pszAuthorityCode = oSRS.GetAuthorityCode(NULL);
            if ( pszAuthorityCode != NULL && strlen(pszAuthorityCode) > 0 )
            {
                /* Import 'clean' SRS */
                oSRS.importFromEPSG( atoi(pszAuthorityCode) );

                pszAuthorityName = oSRS.GetAuthorityName(NULL);
            }
        }
    }
/* -------------------------------------------------------------------- */
/*      Check whether the EPSG authority code is already mapped to a    */
/*      SRS ID.                                                         */
/* -------------------------------------------------------------------- */
    int  nAuthorityCode = 0;
    if( pszAuthorityName != NULL && EQUAL( pszAuthorityName, "EPSG" ) )
    {
        /* For the root authority name 'EPSG', the authority code
         * should always be integral
         */
        nAuthorityCode = atoi( oSRS.GetAuthorityCode(NULL) );

        CPLODBCStatement oStmt( &oSession );
        oStmt.Appendf("SELECT srid FROM spatial_ref_sys WHERE "
                         "auth_name = '%s' AND auth_srid = %d",
                         pszAuthorityName,
                         nAuthorityCode );

        if( oStmt.ExecuteSQL() && oStmt.Fetch() && oStmt.GetColData( 0 ) )
        {
            nSRSId = atoi(oStmt.GetColData( 0 ));
            return nSRSId;
        }
    }

/* -------------------------------------------------------------------- */
/*      Translate SRS to WKT.                                           */
/* -------------------------------------------------------------------- */
    if( oSRS.exportToWkt( &pszWKT ) != OGRERR_NONE )
    {
        CPLFree(pszWKT);
        return 0;
    }

/* -------------------------------------------------------------------- */
/*      Try to find in the existing table.                              */
/* -------------------------------------------------------------------- */
    CPLODBCStatement oStmt( &oSession );

    oStmt.Append( "SELECT srid FROM spatial_ref_sys WHERE srtext = ");
    OGRMSSQLAppendEscaped(&oStmt, pszWKT);

/* -------------------------------------------------------------------- */
/*      We got it!  Return it.                                          */
/* -------------------------------------------------------------------- */
    if( oStmt.ExecuteSQL() )
    {
        if ( oStmt.Fetch() && oStmt.GetColData( 0 ) )
        {
            nSRSId = atoi(oStmt.GetColData( 0 ));
            CPLFree(pszWKT);
            return nSRSId;
        }
    }
    else
    {
        /* probably the table is missing at all */
        if( InitializeMetadataTables() != OGRERR_NONE )
        {
            CPLFree(pszWKT);
            return 0;
        }
    }

/* -------------------------------------------------------------------- */
/*      Try adding the SRS to the SRS table.                            */
/* -------------------------------------------------------------------- */
    char    *pszProj4 = NULL;
    if( oSRS.exportToProj4( &pszProj4 ) != OGRERR_NONE )
    {
        CPLFree( pszProj4 );
        CPLFree(pszWKT);
        return 0;
    }

/* -------------------------------------------------------------------- */
/*      Check whether the auth_code can be used as srid.                */
/* -------------------------------------------------------------------- */
    nSRSId = nAuthorityCode;

    oStmt.Clear();
    oSession.BeginTransaction();
    if (nAuthorityCode > 0)
    {
        oStmt.Appendf("SELECT srid FROM spatial_ref_sys where srid = %d", nAuthorityCode);
        if ( oStmt.ExecuteSQL() && oStmt.Fetch())
        {
            nSRSId = 0;
        }
    }

/* -------------------------------------------------------------------- */
/*      Get the current maximum srid in the srs table.                  */
/* -------------------------------------------------------------------- */

    if (nSRSId == 0)
    {
        oStmt.Clear();
        oStmt.Append("SELECT COALESCE(MAX(srid) + 1, 32768) FROM spatial_ref_sys where srid between 32768 and 65536");

        if ( oStmt.ExecuteSQL() && oStmt.Fetch() && oStmt.GetColData( 0 ) )
        {
            nSRSId = atoi(oStmt.GetColData( 0 ));
        }
    }

    if (nSRSId == 0)
    {
        /* unable to allocate srid */
        oSession.RollbackTransaction();
        CPLFree( pszProj4 );
        CPLFree(pszWKT);
        return 0;
    }

    oStmt.Clear();
    if( nAuthorityCode > 0 )
    {
        oStmt.Appendf(
                 "INSERT INTO spatial_ref_sys (srid, auth_srid, auth_name, srtext, proj4text) "
                 "VALUES (%d, %d, ", nSRSId, nAuthorityCode );
        OGRMSSQLAppendEscaped(&oStmt, pszAuthorityName);
        oStmt.Append(", ");
        OGRMSSQLAppendEscaped(&oStmt, pszWKT);
        oStmt.Append(", ");
        OGRMSSQLAppendEscaped(&oStmt, pszProj4);
        oStmt.Append(")");
    }
    else
    {
        oStmt.Appendf(
                 "INSERT INTO spatial_ref_sys (srid,srtext,proj4text) VALUES (%d, ", nSRSId);
        OGRMSSQLAppendEscaped(&oStmt, pszWKT);
        oStmt.Append(", ");
        OGRMSSQLAppendEscaped(&oStmt, pszProj4);
        oStmt.Append(")");
    }

    /* Free everything that was allocated. */
    CPLFree( pszProj4 );
    CPLFree( pszWKT);

    if ( oStmt.ExecuteSQL() )
        oSession.CommitTransaction();
    else
        oSession.RollbackTransaction();

    return nSRSId;
}


text:
namespace Com.Ctrip.Framework.Apollo.Core.Schedule;

public class ExponentialSchedulePolicy : ISchedulePolicy
{
    private readonly int _delayTimeLowerBound;
    private readonly int _delayTimeUpperBound;
    private int _lastDelayTime;

    public ExponentialSchedulePolicy(int delayTimeLowerBound, int delayTimeUpperBound)
    {
        _delayTimeLowerBound = delayTimeLowerBound;
        _delayTimeUpperBound = delayTimeUpperBound;
    }

    public int Fail()
    {
        var delayTime = _lastDelayTime;

        if (delayTime == 0)
        {
            delayTime = _delayTimeLowerBound;
        }
        else
        {
            delayTime = Math.Min(_lastDelayTime << 1, _delayTimeUpperBound);
        }

        _lastDelayTime = delayTime;

        return delayTime;
    }

    public void Success() => _lastDelayTime = 0;
}


text:
'use strict';

var _ = require('lodash');

// constants
var MIME = {
    standard: ['application/vnd.api+json', 'application/json'],
    patch: ['application/json-patch+json']
};

var errorMessages = {
    400: 'Request was malformed.',
    403: 'Access forbidden.',
    404: 'Resource not found.',
    405: 'Method not permitted.',
    412: 'Request header "Content-Type" must be one of: ' + MIME.standard.join(', '),
    500: 'Oops, something went wrong.',
    501: 'Feature not implemented.'
};

function JSONAPI_Error(error) {
    this.name = 'JSONAPI_Error';
    if (!error) {
        error = {};
    }

    var status = error.status ? error.status : 500;

    var errorWithDefaults = _.merge({}, error, {
        status: status,
        href: error.href ? error.href : 'about:blank',
        title: error.title ? error.title : errorMessages[status],
        detail: error.detail ? error.detail : ''
    });

    this.error = errorWithDefaults;
}
JSONAPI_Error.prototype = new Error();
JSONAPI_Error.prototype.constructor = JSONAPI_Error;

module.exports = JSONAPI_Error;


text:
#pragma once

#include "LearningModelOutputs.g.h"

namespace WINML_EXPERIMENTALP {

struct LearningModelOutputs : LearningModelOutputsT<LearningModelOutputs>
{
    LearningModelOutputs(winml_experimental::LearningModelBuilder builder);

    winml_experimental::LearningModelBuilder Add(winml::ILearningModelFeatureDescriptor const& output);

    private:
    wfc::IVector<winml::ILearningModelFeatureDescriptor> output_descriptors_;
    winml_experimental::LearningModelBuilder builder_;

};

}  // namespace WINML_EXPERIMENTALP


text:
class User < ActiveRecord::Base
  attr_accessible :email, :name, :password, :password_confirmation
  has_secure_password

  before_save { |user| user.email = email.downcase }

  validates :name, presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true,
  					format: { with: VALID_EMAIL_REGEX },
  					uniqueness: { case_sensitive: false }
  validates :password, presence: true, length: { minimum: 6 }
  validates :password_confirmation, presence: true
end


text:
@echo off
rem M102 Final
rem Script to make a test replica set. See problem #1.

rem if you need to start over try:
rem rmdir data /s
rem (careful that deletes that everything under data/ recursively!)

rem we expect nothing to be running.
rem you might have a mongo shell running which is ok...but
rem no mongod or mongos processes.

echo make / reset dirs
mkdir data
mkdir data\z1
mkdir data\z2
mkdir data\z3

echo running mongod processes...

start mongod --smallfiles --oplogSize 50 --port 27001 --dbpath data/z1 --replSet z
start mongod --smallfiles --oplogSize 50 --port 27002 --dbpath data/z2 --replSet z
start mongod --smallfiles --oplogSize 50 --port 27003 --dbpath data/z3 --replSet z

rem give them time to start. note this might not be enough time!
rem sleep 1

echo "Now run:"
echo "  mongo --shell --port 27003 a.js"

rem Tip: in powershell, list all mongo processes with:
rem        ps mongo*
rem      and you can terminate them all with:
rem        ps mongo* | kill


text:
using UnityEngine;
using wHiteRabbiT.Unity.Extensions;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System;

namespace wHiteRabbiT.Unity.UI
{
	public class GUIHelper
	{
		protected static Texture2D _wHiteTex;
		public static Texture2D wHiteTex
		{
			get {
//#if UNITY_EDITOR
//				return UnityEditor.EditorGUIUtility.whiteTexture; // Bad texture ! 4x4
//#else
				if (_wHiteTex == null)
				{
					_wHiteTex = new Texture2D(1,1,TextureFormat.ARGB32, false);
					_wHiteTex.SetPixel(0,0,new Color(1,1,1,1));
					_wHiteTex.Apply();
				}

				return _wHiteTex;
//#endif
			}
		}

		public static void DrawRectFillAlpha(Rect rect, Color color, float alpha)
		{
			Color guiColor = GUI.color;

			GUI.color = color.Alpha(alpha);
			GUI.DrawTexture(rect, wHiteTex);

			GUI.color = color.Alpha(1);
			GUI.DrawTexture(new Rect(rect.x, rect.y, rect.width, 1+0*rect.height), wHiteTex);
			GUI.DrawTexture(new Rect(rect.x, rect.y, 1+0*rect.width, rect.height), wHiteTex);
			GUI.DrawTexture(new Rect(rect.x + rect.width, rect.y + rect.height, -rect.width, -1+0*rect.height), wHiteTex);
			GUI.DrawTexture(new Rect(rect.x + rect.width, rect.y + rect.height, -1+0*rect.width, -rect.height), wHiteTex);

			GUI.color = guiColor;
		}

		public static void DrawRectFillPCAlpha(Rect rect, Color color, float alpha, float pc)
		{
			Color guiColor = GUI.color;

			float w = rect.width * pc;
			float iw = rect.width - w;

			GUI.color = color.Alpha(alpha);
			GUI.DrawTexture(new Rect(rect.x + w, rect.y, iw, rect.height), wHiteTex);

			GUI.color = color.Alpha(1);

			GUI.DrawTexture(new Rect(rect.x, rect.y, w, rect.height), wHiteTex);

			GUI.DrawTexture(new Rect(rect.x, rect.y, rect.width, 1+0*rect.height), wHiteTex);
			GUI.DrawTexture(new Rect(rect.x, rect.y, 1+0*rect.width, rect.height), wHiteTex);
			GUI.DrawTexture(new Rect(rect.x + rect.width, rect.y + rect.height, -rect.width, -1+0*rect.height), wHiteTex);
			GUI.DrawTexture(new Rect(rect.x + rect.width, rect.y + rect.height, -1+0*rect.width, -rect.height), wHiteTex);

			GUI.color = guiColor;
		}

		public static void DrawCenteredRect3D(Vector3 p, Vector2 size, Color color) { DrawCenteredRect3D(p, size, color, Camera.main); }
		public static void DrawCenteredRect3D(Vector3 p, Vector2 size, Color color, Camera camera)
		{
			if (camera == null)
				return;

			GUI.color = color;

			Vector3 p2D = camera.WorldToScreenPoint(p);
			if (p2D.z < 0)
				return;

			GUI.DrawTexture(new Rect(p2D.x - size.x*0.5f,
									 Screen.height - p2D.y - size.y*0.5f,
									 size.x, size.y), wHiteTex);
		}

		public static void Label3D(Transform transform, string str) { Label3D(transform, str, Vector2.zero, Vector2.zero, Camera.current); }
		public static void Label3D(Transform transform, string str, Vector2 decal) { Label3D(transform, str, decal, Vector2.zero, Camera.current); }
		public static void Label3D(Transform transform, string str, Vector2 decal, Vector2 size) { Label3D(transform, str, decal, size, Camera.current); }
		public static void Label3D(Transform transform, string str, Vector2 decal, Vector2 size, Camera cam)
		{
			if (cam == null)
				return;

			GUIStyle gs = new GUIStyle(GUIStyle.none);
			gs.normal.textColor = Color.white;
			gs.clipping = TextClipping.Overflow;
			gs.alignment = TextAnchor.MiddleCenter;

			Vector3 p2D = cam.WorldToScreenPoint(transform.position);
			if (p2D.z > 0)
			{
				GUI.Label(new Rect(p2D.x + decal.x, Screen.height - p2D.y - decal.y, size.x, size.y), str, gs);
			}
		}

		public static void Hyperlink(string Label, string Url, GUIStyle gsBase)
		{
			if (GUILayout.Button(Label, gsBase))
				Application.OpenURL(Url);

			Rect r = GUILayoutUtility.GetLastRect();

			float mw, Mw;
			float h = gsBase.CalcHeight(new GUIContent(Label), r.width) - gsBase.padding.top - gsBase.padding.bottom;
			gsBase.CalcMinMaxWidth(new GUIContent(Label), out mw, out Mw);

			//Vector2 v = gsBase.CalcSize(new GUIContent(Label));

			Rect nr = new Rect(
				r.x + gsBase.padding.left,
				r.y + gsBase.padding.top + h,
				Mw - gsBase.padding.left - gsBase.padding.right,
				1);

			Color oldC = GUI.color;
			GUI.color = gsBase.normal.textColor;

			GUI.DrawTexture(nr, wHiteTex);

			GUI.color = oldC;

#if UNITY_EDITOR
			UnityEditor.EditorGUIUtility.AddCursorRect(r, UnityEditor.MouseCursor.Link);
#endif
		}

		public static void Separator()
		{
			GUILayout.BeginHorizontal();
			GUILayout.EndHorizontal();

			Rect R = GUILayoutUtility.GetLastRect();

			GUILayout.Space(10);
			GUI.DrawTexture(new Rect(R.x, R.y + R.height + 5, R.width, 1), wHiteTex);
		}

	}
}


text:
package us.codecraft.webmagic.model.samples;

import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.model.HasKey;
import us.codecraft.webmagic.model.OOSpider;
import us.codecraft.webmagic.model.annotation.ExprType;
import us.codecraft.webmagic.model.annotation.ExtractBy;
import us.codecraft.webmagic.model.annotation.TargetUrl;
import us.codecraft.webmagic.pipeline.JsonFilePageModelPipeline;

import java.util.List;

/**
 * @author code4crafter@gmail.com

 * Date: 13-8-2

 * Time: 上午7:52

 */
@TargetUrl("http://my.oschina.net/flashsword/blog/\\d+")
public class OschinaBlog implements HasKey{

    @ExtractBy("//title")
    private String title;

    @ExtractBy(value = "div.BlogContent",type = ExprType.CSS)
    private String content;

    @ExtractBy(value = "//div[@class='BlogTags']/a/text()", multi = true)
    private List<String> tags;

    public static void main(String[] args) {
        OOSpider.create(Site.me().addStartUrl("http://my.oschina.net/flashsword/blog")
                ,new JsonFilePageModelPipeline(), OschinaBlog.class).run();
    }

    @Override
    public String key() {
        return title;
    }

    public String getTitle() {
        return title;
    }

    public String getContent() {
        return content;
    }

    public List<String> getTags() {
        return tags;
    }
}


text:
package ca.uhn.fhir.rest.server.interceptor.auth;

import org.hl7.fhir.instance.model.api.IIdType;

import javax.annotation.Nonnull;

/**
 * @since 5.5.0
 */
public interface IAuthRuleBuilderRuleBulkExport {

	/**
	 * Allow/deny group-level export rule applies to the Group with the given resource ID, e.g. Group/123
	 *
	 * @since 5.5.0
	 */
	default IAuthRuleBuilderRuleBulkExportWithTarget groupExportOnGroup(@Nonnull IIdType theFocusResourceId) {
		return groupExportOnGroup(theFocusResourceId.getValue());
	}

	/**
	 * Allow/deny group-level export rule applies to the Group with the given resource ID, e.g. Group/123
	 *
	 * @since 5.5.0
	 */
	IAuthRuleBuilderRuleBulkExportWithTarget groupExportOnGroup(@Nonnull String theFocusResourceId);

	/**
	 * Allow/deny patient-level export rule applies to the Group with the given resource ID, e.g. Group/123
	 *
	 * @since 5.5.0
	 */
	default IAuthRuleBuilderRuleBulkExportWithTarget patientExportOnGroup(@Nonnull IIdType theFocusResourceId) {
		return patientExportOnGroup(theFocusResourceId.getValue());
	}

	/**
	 * Allow/deny patient-level export rule applies to the Group with the given resource ID, e.g. Group/123
	 *
	 * @since 5.5.0
	 */
	IAuthRuleBuilderRuleBulkExportWithTarget patientExportOnGroup(@Nonnull String theFocusResourceId);

	/**
	 * Allow/deny system-level export rule applies to the Group with the given resource ID, e.g. Group/123
	 *
	 * @since 5.5.0
	 */
	IAuthRuleBuilderRuleBulkExportWithTarget systemExport();

	/**
	 * Allow/deny any bulk export operation
	 */
	IAuthRuleBuilderRuleBulkExportWithTarget any();
}