text:
Directives
==========

Directives are Laika's extension hook for both, templates and text markup.
They allow to add new tag-like constructs without touching the existing parsers.

Each directive expects a configurable combination of attributes or body elements,
where some of them may be required, while others may be optional. Laika takes care
of parsing and validating these directive parts based on your declarations
and then passes these values to your directive function (in a type-safe way)
that produces a node element to add to the document tree result.

Directive Types
---------------

Due to subtle differences in the node types they produce, there is a
distinction between three directive types:

* Template directives, which produce `TemplateSpan` elements (or alternatively simple strings
  if you do not mind that your directive can only be used with one output format)
* Directives for block elements in markup, which produce `Block` elements
* Directives for inline elements in markup, which produce `Span` elements

If you want to create a directive that can be used in all three locations
you can usually easily reuse parts of your logic. If your directive version
for inline elements generates a simple `ExternalLink` node for example,
you can simply wrap that same node in a `Paragraph` node for a block-level
directive.

Directive Syntax
----------------

A very minimal example is the `toc` directive for inserting a table of contents.
Since all its attributes are optional, it can simply be used like this:

    @:toc.

A directive always starts with `@:` followed by the name of the
directive. When there are no further attributes or body elements
you can close it with a `.`

A more complete example is the use of the `for` directive:

    @:for "document.sections": {

{{title.content}}

    }

Here `for` is the name of the directive, `"document.sections"` is an unnamed
attribute (where in this case the value is interpreted as a variable reference),
and finally, enclosed in curly braces the body of the directive. The opening
declaration with directive name and attributes ends with a `:` and not with `.`
if it is followed by body elements.

Example Implementation
----------------------

You can browse the source of the built-in directives here: [directive-api]
But the logic required for the `toc` or `for` directives is probably much
more complicated than what you would usually do for a little custom
helper tag that you need to unclutter your templates.

Therefore we'll show and explain a very simple example here that
should be sufficient to get you started.

Our `ticket` directive constructs an external link to our
bugtracker. Since the base URL is always the same, we want to
only write:

    @:ticket 456.

to get the output:

    #456

Or optionally specify a different project than the main one:

    @:ticket 456 project=pineapple.

to get the output:

    #456

The following sections explain how to implement the tag
and then how to add it either to the Markdown or reStructuredText
parser or to the template parser.

[directive-api]: https://github.com/planet42/Laika/blob/master/core/src/main/scala/laika/directive/StandardDirectives.scala

### Directive Implementation

    val directive = Spans.create("ticket") {
      (attribute(Default) ~ attribute("project").optional) {
        (ticketNo, project) =>
          val base = "http://tickets.cloud42.com/"
          val url = base + project.getOrElse("main-project") + "/" + ticketNo
          val linkText = Seq(Text("#"+ticketNo))
          ExternalLink(linkText, url, options = Styles("ticket"))
      }
    }

Let's examine the code:

With `Spans.create("ticket")` we specify the name of the directive (`ticket`)
which is also the name we are going to use in markup files (`@:ticket`).

The `Spans` object let's us create a directive for an inline element
as that has a different node type as the final result of the directive
and the API is typesafe. For block level markup directives you'd use
the `Blocks` object, for template directives the `Templates` object.
The features and APIs are identical, but there are subtle differences
in return types.

With `attribute(Default)` we specify that we expect a default (unnamed)
attribute which is required. When a required attribute is missing
our directive function will never be invoked. Instead Laika inserts
a node of type `InvalidSpan` into the document tree (which we may
then choose to render or not).

With `attribute("project").optional` we specify that we expect an
attribute with the name `project` which is optional. In case it is
missing our directive function will still be invoked.

The `~` method chains our declarations together. This operator is fairly
common in Scala lands, you've very likely seen it in other APIs already.

`(ticketNo, project)` are the parameters that the parser will pass
to our function after parsing and validating the directive. They
have a type corresponding to our configuration. `ticketNo` is of
type `String` (you can also specify converters to other types, but
that is not needed here). `project` is of type `Option[String]` since
we declared it as optional.

The rest is just plain Scala code. The result is of type `ExternalLink`
which is one type of Laika's rich tree model. It mixes in the `Span`
trait and thus satisfies the requirement of an inline directive.

### Directive Registration

Finally all we need to do is register our directive before parsing.
All the examples below refer to the `directive` variable we declared
in the example in the previous section.

**sbt Plugin**:

    import LaikaKeys._

    // ... your standard build stuff

    LaikaPlugin.defaults

    spanDirectives in Laika += directive

This registers the directive for both Markdown and reStructuredText
parsers.

The directive implementation itself usually requires some
amount of logic, so is usually best kept separately in a `.scala`
file in the `project` directory and then referenced from your
`build.sbt`. Reusable directives are best packaged as a library
and then added as a dependency of your build.

**Markdown**:

    Transform from Markdown.withSpanDirectives(directive) to
      HTML fromFile "hello.md" toFile "hello.html"

The `directive` variable refers to the instance we created above.
We can now use our `ticket` directive in Markdown files!

**reStructuredText**:

    Transform from ReStructuredText.withLaikaSpanDirectives(directive) to
      HTML fromFile "hello.md" toFile "hello.html"

The only difference here is that the method name is `withLaikaSpanDirectives`
as reStructuredText comes with its own concept of directives which is only
supported in the reStructuredText parser.

**Templates**:

    Transform from Markdown to HTML fromDirectory
      "source" withTemplateDirectives directive toDirectory "target"

When you also want to use the directive in templates you need to create
a very similar declaration like the one above, just starting with `Templates.create`
instead and wrapping the `ExternalLink` node in a `TemplateElement`. You can extract
the rest of the logic into a shared function.

Therefore the type of the variable `directive` is `Templates.Directive`, and not
`Spans.Directive` like in the previous examples.

API Reference
-------------

The example implementation only showed a few options for declaring the
expected parts of your directive. Even though there is full scaladoc
for the API, the combinators and converters are a bit scattered over
different objects, so we assemble them here for easier reference.

### Default Attributes

A default attribute is an attribute without a name.
It has to be the first attribute before any named attributes.
It allows for more concise syntax in all the cases where usually only one
attribute is used and its meaning is obvious.

Markup example:

    @:name arg.

Combinator:

    attribute(Default)

### Named Attributes

A named attribute can appear after the default attribute or right
after the directory name in case there is no default attribute.
The order of attributes does not matter, it does not need to match
the order you declared them in (that's why they have names after all).

Markup example:

    @:name myAttr=value.

Combinator:

    attribute("myAttr")

### Default Bodies

A default body is a body element without a name.
It has to be the first body before any named body elements.

Markup example:

    @:name: {
      this is the content of the default body
    }

Combinator:

    body(Default)

### Named Bodies

A named body element usually appears after a default body (but it does not have
to). In the example below the second body has the name `empty`.

Markup example:

    @:for "documents.sections": {

{{title.content}}

    } ~empty: {

no sections

    }

Combinator:

    body("empty")

### Optional Elements

All the element types shown above, default and named attributes as well
as default and named bodies can be marked as optional.

Combinator:

    body("empty").optional

The parameter type of your directive function changes accordingly,
from `T` to `Option[T]` where `T` is either the type returned by
your converter (see below) or the default type (which is different
for body and attribute elements (again see next section).

### Converters

For any attribute or body element a converter can be specified.
If it is left out the default types are as follows:

* `String` for attributes in all directive types
* `Seq[Block]` for body elements in block directives
* `Seq[Span]` for body elements in inline directives
* `Seq[TemplateSpan]` for body elements in template directives

This means that for body elements they are already parsed by default,
as this is the most likely requirement for a directive.

The object `Converters` in the `Directives` object contains several
pre-built converters, like `positiveInt`:

    attribute("depth", Converters.positiveInt).optional

It will validate the attribute value and only invoke your directive
function if it succeeds. The parameter type in your function changes
to `Option[Int]` accordingly.

If you want to implement your own converter, it simply has to
be a function of type `(Parser, String) => Result[T]` for which
a type alias `Converter[T]` exists.

### Access to the Parser

For block elements the default is to pre-parse the content for you,
so there is rarely a need to parse something yourself. But if you need to,
it wouldn't be a good idea to instantiate your own parser. Because it
would not have access to any of the directives or other configuration
options active for this operation (unless you manually duplicate it which
is brittle). Therefore you can request a parser for your function in
addition to the other values:

    attribute(Default) ~ parser { (attrValue, parser) =>
      val parsedSpans = parser("["+attrValue+"]")
      SpanSequence(parsedSpans)
    }

In this contrived example the attribute value is modified before being passed
to the parser and then wrapped inside a sequence.

### Access to the Document Context

Finally you can also request access to the document context. This gives
you access to the structure, the title, sections and parent and root
trees, in short, the full API for the AST built by the parser.

It is, for example, required for a directive like the `toc` directive,
because for building a table of contents you have to look beyond your
particular directive node.

    attribute(Default) ~ context { (attrValue, context) =>
      val spans = Text("The title is: ") +: context.document.title
      SpanSequence(spans)
    }

### Differences between Directive Types

[Directive Types] already gave a quick overview over the available types.
The sections [Directive Implementation] and [Directive Registration] showed
a simple example for a span directive. Since there are three different directive
types and different ways to register them depending on whether you use the
sbt plugin or Laika embedded, this section gives a final overview over the
API differences.

### Span Directives

Use: in inline elements in text markup files

Implementation:

    import laika.directive.Directives.Spans
    import laika.util.Builders._
    import laika.tree.Elements._
    import Spans.Combinators._
    import Spans.Converters._

    val directive = Spans.create("name") {
      // implementation producing a `Span` element
    }

Registration:

    // for Markdown and reStructuredText with sbt plugin:
    spanDirectives in Laika += directive // in build.sbt

    // for Markdown with Transform API or Parse API:
    Transform from Markdown.withSpanDirectives(directive) to ...
    Parse as Markdown.withSpanDirectives(directive) from ...

    // for reStructuredText with Transform API or Parse API:
    Transform from ReStructuredText.withLaikaSpanDirectives(directive) to ...
    Parse as ReStructuredText.withLaikaSpanDirectives(directive) from ...

### Block Directives

Use: in block elements in text markup files

Implementation:

    import laika.directive.Directives.Blocks
    import laika.util.Builders._
    import laika.tree.Elements._
    import Blocks.Combinators._
    import Blocks.Converters._

    val directive = Blocks.create("name") {
      // implementation producing a `Block` element
    }

Registration:

    // for Markdown and reStructuredText with sbt plugin:
    blockDirectives in Laika += directive // in build.sbt

    // for Markdown with Transform API or Parse API:
    Transform from Markdown.withBlockDirectives(directive) to ...
    Parse as Markdown.withBlockDirectives(directive) from ...

    // for reStructuredText with Transform API or Parse API:
    Transform from ReStructuredText.withLaikaBlockDirectives(directive) to ...
    Parse as ReStructuredText.withLaikaBlockDirectives(directive) from ...

### Template Directives

Use: in template files

Implementation:

    import laika.directive.Directives.Templates
    import laika.util.Builders._
    import laika.tree.Templates._
    import Templates.Combinators._
    import Templates.Converters._

    val directive = Templates.create("name") {
      // implementation producing a `TemplateSpan` element
    }

Registration:

    // for templates with sbt plugin:
    templateDirectives in Laika += directive // in build.sbt

    // for Markdown in Transform API:
    Transform from Markdown to HTML fromDirectory
      "source" withTemplateDirectives directive toDirectory "target"

    // for reStructuredText in Transform API:
    Transform from ReStructuredText to PDF fromDirectory
      "source" withTemplateDirectives directive toFile "out.pdf"


text:
class OpenWeixin::WechatsController < ActionController::Base

	def authorize_handler

		render json: {success: true}
	end

end

redpajama_set_name: RedPajamaGithub


text:
/**
 * PhotoGrid Web App (2014)
 *
 * @author Bruno Magalhães <bfmags@gmail.com>
 * @dependency html2canvas JS library for downloading images
 */

/**
 * @global
 * @desc Mapping of DOM Elements into global variables
 */
var DOM_GRID = document.getElementById('grid');
var GRID_IMAGES = DOM_GRID.getElementsByTagName('img');
var BOTTOM_GRID = document.getElementById('bottom-nav');
var BOTTOM_GRID_IMAGES = document.getElementById('bottom-grid').getElementsByTagName('img');
var SCROLL_RIGHT_BUTTON = document.getElementById('scroll-right');
var SCROLL_LEFT_BUTTON = document.getElementById('scroll-left');
var REROLL_BUTTON = document.getElementById('reroll');
var DOWNLOAD_BUTTON = document.getElementById('download');
var ZOOM_IN_BUTTON = document.getElementById('zoom-in');
var ZOOM_OUT_BUTTON = document.getElementById('zoom-out');
var SUCCESS_LABEL = document.getElementById('success-label');
var CLICK_TO_CHANGE_BUTTONS = document.getElementsByClassName('click-to-change');

/**
 * @global
 * @desc Number of images to be loaded
 */
NUMBER_OF_IMAGES = 21;

/**
 * Load Images from user folder
 * @namespace loadImages
 */
var loadImages = {
	    /**
		 * An object for storing image references
         * @memberof loadImages
         * @property {{image[].src: string}}
         */
		images : {},
	    /**
         * A method for loading images from folder
         * @memberof loadImages
         * @method loadImage
		 * @arg {!number} n number of images
         */
        loadImage : function (n) {
                        "use strict";
                        var url_to_image = '/img/user-images/' + n + '.jpg';
                        this.images[n] = new Image();
                        //images[n].onload = function() {};
                        this.images[n].src = url_to_image;
                    },
		/**
         * A method for initializing image loading
         * @memberof loadImages
         * @method initialize
		 * @arg {!number} number_of_images
         */
        initialize : function (number_of_images) {
                        "use strict";
                        for (var i = 1; i <= number_of_images; i++) {
                            this.loadImage("" + i);
                        }
                    }
};

/**
 * Picks random images and places them in grid
 * @namespace imageRandom
 */
var imageRandom = {
	    /**
		 * An object for storing image references
         * @memberof loadImages
         * @property {{image[].src: string}}
         */
		images : {},
		/**
		 * A method for getting a random int between min and max values
         * @memberof imageRandom
		 * @method getRandomInt
		 * @arg {!number} min value
		 * @arg {!number} max value
         */
        getRandomInt : function (min,max) { return Math.floor(Math.random() * (max - min + 1) + min); },
    	/**
		 * A method for testing if value exists in an array
         * @memberof imageRandom
		 * @method inArray
		 * @arg {!array} array
		 * @arg {!value} value
		 * @returns {boolean} Returns true if value found, false if not
         */
        inArray : function (array, value) {
                    for (var i = 0; i < array.length; i++) {
                    if (array[i] === value) { return true; } }
                    return false;
                },
    	/**
		 * A method for picking random images and place them in the grid
         * @memberof imageRandom
		 * @method sortImages
         */
        sortImages : function () {
                        var image_array = [];
                        var random_int = this.getRandomInt(1, NUMBER_OF_IMAGES);

                        for (var i=0; i < GRID_IMAGES.length; i++){
                            while (this.inArray(image_array, random_int)){
                                random_int = this.getRandomInt(1, NUMBER_OF_IMAGES);
                            }
                        image_array[i] = random_int;
                        GRID_IMAGES[i].src = this.images[random_int].src;
                        }

            },
		/**
         * A method for initializing image randomization
		 * Assigns a callback to re-roll button
         * @memberof imageRandom
         * @method initialize
		 * @arg {{image[].src: string}} images Object with image references
         */
        initialize : function (images) {
						this.images = images;
                        this.sortImages();
                        REROLL_BUTTON.setAttribute('onclick', 'imageRandom.sortImages()');
                }
};

/**
 * Downloads the photo grid
 * @namespace downloadImage
 * @dependency html2canvas JS library
 */
var downloadImage = {
    	/**
		 * A method for downloading image using html2canvas library
		 * Writes images to local disk saveToDisk() and calls showSuccessLabel()
         * @memberof downloadImage
		 * @method download
         */
        download : function () {
                            html2canvas(DOM_GRID, {
                                onrendered: function (canvas) {
                                    var dataURL = canvas.toDataURL('image/jpeg');
                                    downloadImage.saveToDisk(dataURL, 'autogrid' +
															 imageRandom.getRandomInt(500,900) + '.jpg');
                                    downloadImage.showSuccessLabel();
                                }
                            });
                        },
	    /**
		 * A method for writing images to local disk
         * @memberof downloadImage
		 * @method saveToDisk
		 * @arg {!string} fileURL file url
		 * @arg {!string} fileName filename to save
         */
        saveToDisk : function (fileURL, fileName) { //IE not supported

								var save = document.createElement('a');
								save.href = fileURL;
								save.target = '_blank';
								save.download = fileName || 'unknown';

								var event = document.createEvent('MouseEvent');
								event.initEvent('click', true, true);
								save.dispatchEvent(event);
								(window.URL || window.webkitURL).revokeObjectURL(save.href);

                    },
		/**
		* A method for showing a success label to the user
		* @memberof downloadImage
		* @method showSuccessLabel
		*/
        showSuccessLabel : function () {

                                SUCCESS_LABEL.className = 'transition';
                                SUCCESS_LABEL.style.opacity = 1;

                                setTimeout(
                                    function () {
                                        SUCCESS_LABEL.style.opacity = 0;
                                        console.log(this);
                                        this.clearTimeout();
                                    }, 2000);
                            },

		/**
         * A method for initializing image download
         * @memberof downloadImage
         * @method initialize
         */
        initialize : function () {
                        DOWNLOAD_BUTTON.setAttribute('onclick', 'downloadImage.download()');
                    }
};

/**
 * Takes care of bottom photo grid functionality (animation, scrolling and selection)
 * @namespace bottomgrid
 */
var bottomGrid = {
		/**
		 * A number defining the offset in the interval of images shown
         * @memberof bottomGrid
         * @property {number}
         */
		gridOffset : BOTTOM_GRID_IMAGES.length,
		/**
		 * An object for storing image references
         * @memberof bottomGrid
         * @property {{image[].src: string}}
         */
		images : {},
		/**
		 * A method for hiding the photo grid
         * @memberof bottomGrid
		 * @method hide
         */
    	hide : function () { BOTTOM_GRID.style.bottom = '-92px'; },
		/**
		 * A method for showing the photo grid
         * @memberof bottomGrid
		 * @method show
         */
		show : function () { BOTTOM_GRID.style.bottom = '13px'; },
		/**
		 * A method for assigning images to the photo grid
         * @memberof bottomGrid
		 * @method assignImages
         */
        assignImages: function () {
                        for (var i = 1; i < BOTTOM_GRID_IMAGES.length+1; i++){
                        	BOTTOM_GRID_IMAGES[i-1].src = this.images[this.gridOffset + i].src;
							console.log(this.gridOffset);
						}
					 },
		/**
		 * A method for scrolling the photo grid
         * @memberof bottomGrid
		 * @method scroll
		 * @arg {!string: right || left} option scrolling direction
         */
        scroll: function (option) {
                        if (option === "right") {
                            (this.gridOffset < 12) ? this.gridOffset += 1 : this.gridOffset = 12;
                        }
                        if (option === "left") { (
                            this.gridOffset > 1) ? this.gridOffset -= 1 : this.gridOffset = 0;
                        }
                        this.assignImages();
                },
		/**
         * A method for initializing the bottom photo grid
		 * Assigns callbacks to scrolling left and right buttons
         * @memberof bottomGrid
         * @method initialize
		 * @arg {{image[].src: string}} images Object with image references
         */
        initialize: function (images) {
						this.images = images;
                        this.assignImages();
                        SCROLL_LEFT_BUTTON.setAttribute('onclick', 'bottomGrid.scroll("left")');
                        SCROLL_RIGHT_BUTTON.setAttribute('onclick', 'bottomGrid.scroll("right")');
                   }
};

/**
 * Logic for swapping images between photo grid and bottom photo roll
 * @namespace swapImage
 */
var swapImage = {
		/**
		 * A number defining the image to be replaced
		 * If negative, no image selected
		 * @memberof swapImage
		 * @property {number} selected_image
		 */
		selected_image: -1,
		/**
		 * A method for selecting images in the photo grid
		 * Only allows one image at a time
		 * @memberof swapImage
		 * @method selectImage
		 * @arg {!number} n GridPhoto index number
		 */
		selectImage : function (n) {
						for (var i=0; i < GRID_IMAGES.length; i++){
							GRID_IMAGES[i].style.opacity = 1;
						}
						if (this.selected_image !== n){
							GRID_IMAGES[n].style.opacity = .2;
							bottomGrid.show();
							this.selected_image = n;
						} else {
							this.selected_image = -1;
							bottomGrid.hide();
						}
					},
		/**
		 * A method for swaping the image in the photo grid with image in bottom roll
		 * @memberof swapImage
		 * @method swap
		 * @arg {!number} n Index of photo in bottom roll
		 */
		swap : function(n){
					if (this.selected_image >= 0){
						GRID_IMAGES[this.selected_image].src = BOTTOM_GRID_IMAGES[n].src;
						GRID_IMAGES[this.selected_image].style.opacity = 1;
						this.selected_image = -1;
						bottomGrid.hide();
					}
				},
		/**
		 * Assigns callback functions to photos bottom photo grid for click'n'swap
		 * @memberof swapImage
		 * @method initialize
		 */
		initialize : function() {
						for (var i=0; i < CLICK_TO_CHANGE_BUTTONS.length; i++){
							CLICK_TO_CHANGE_BUTTONS[i].setAttribute('onclick',
																	'swapImage.selectImage(' + i +')');
						}
						for (var i=0; i < BOTTOM_GRID_IMAGES.length; i++){
							BOTTOM_GRID_IMAGES[i].setAttribute('onclick', 'swapImage.swap(' + i +')');
						}
					},

};

/**
 * Logic for image zoom feature
 * @namespace zoomImage
 */
var zoomImage = {
	images_zoom : 110,
    zoomIn : function () { if ( this.images_zoom < 350 ) { this.images_zoom += 2; this.applyZoom();} },
    zoomOut: function () { if ( this.images_zoom > 110 ) { this.images_zoom -= 5; this.applyZoom();} },
    applyZoom: function () {
                    for (var i=0; i < GRID_IMAGES.length; i++){
                        if ( this.images_zoom < 110) { this.images_zoom = 110; }
                        GRID_IMAGES[i].style.width = '' + this.images_zoom + '%';
                    }
                },
    initialize: function () {
                    ZOOM_IN_BUTTON.setAttribute('onclick', 'zoomImage.zoomIn();');
                    ZOOM_OUT_BUTTON.setAttribute('onclick', 'zoomImage.zoomOut();');
                }
};

/**
 * @desc Starts loading images
 */
loadImages.initialize(NUMBER_OF_IMAGES);
/**
 * @desc Places random images in the image grid
 * @desc and assigns callback function to re-roll button
 */
imageRandom.initialize(loadImages.images);
/**
 * @desc Assigns callback function to download button
 */
downloadImage.initialize();
/**
 * @desc bottom photo grid functionality (animation, scrolling and selection)
 */
bottomGrid.initialize(loadImages.images);
/**
 * @desc Logic for click'n'swap photos
 */
 swapImage.initialize();
/**
 * @desc Logic for image zoom feature
 */
zoomImage.initialize();


text:
using System;
using System.Threading;
using GoogleApi.Entities.Common.Enums;
using GoogleApi.Entities.Maps.Roads.Common;
using GoogleApi.Entities.Maps.Roads.SnapToRoads.Request;
using NUnit.Framework;

namespace GoogleApi.Test.Maps.Roads.SnapToRoad;

[TestFixture]
public class SnapToRoadTests : BaseTest
{
    [Test]
    public void SnapToRoadTest()
    {
        var request = new SnapToRoadsRequest
        {
            Key = this.Settings.ApiKey,
            Path = new[]
            {
                new Coordinate(60.170880, 24.942795),
                new Coordinate(60.170879, 24.942796),
                new Coordinate(60.170877, 24.942796)
            }
        };
        var result = GoogleMaps.Roads.SnapToRoad.Query(request);

        Assert.IsNotNull(result);
        Assert.AreEqual(Status.Ok, result.Status);
    }

    [Test]
    public void SnapToRoadWhenAsyncTest()
    {
        var request = new SnapToRoadsRequest
        {
            Key = this.Settings.ApiKey,
            Path = new[]
            {
                new Coordinate(60.170880, 24.942795),
                new Coordinate(60.170879, 24.942796),
                new Coordinate(60.170877, 24.942796)
            }
        };
        var result = GoogleMaps.Roads.SnapToRoad.QueryAsync(request).Result;

        Assert.IsNotNull(result);
        Assert.AreEqual(Status.Ok, result.Status);
    }

    [Test]
    public void SnapToRoadWhenAsyncAndCancelledTest()
    {
        var request = new SnapToRoadsRequest
        {
            Key = this.Settings.ApiKey,
            Path = new[] { new Coordinate(0, 0) }
        };
        var cancellationTokenSource = new CancellationTokenSource();
        var task = GoogleMaps.Roads.SnapToRoad.QueryAsync(request, cancellationTokenSource.Token);
        cancellationTokenSource.Cancel();

        var exception = Assert.Throws<OperationCanceledException>(() => task.Wait(cancellationTokenSource.Token));
        Assert.IsNotNull(exception);
        Assert.AreEqual(exception.Message, "The operation was canceled.");
    }
}


text:
package org.springframework.jdbc.support;

import java.sql.*;

/**
 * Class to generate Java 6 SQLException subclasses for testing purposes.
 *
 * @author trisberg
 */
public class SQLExceptionSubclassFactory {

	public static SQLException newSQLDataException(String reason, String SQLState, int vendorCode) {
		return new SQLDataException(reason, SQLState, vendorCode);
	}

	public static SQLException newSQLFeatureNotSupportedException(String reason, String SQLState, int vendorCode) {
		return new SQLFeatureNotSupportedException(reason, SQLState, vendorCode);
	}

	public static SQLException newSQLIntegrityConstraintViolationException(String reason, String SQLState, int vendorCode) {
		return new SQLIntegrityConstraintViolationException(reason, SQLState, vendorCode);
	}

	public static SQLException newSQLInvalidAuthorizationSpecException(String reason, String SQLState, int vendorCode) {
		return new SQLInvalidAuthorizationSpecException(reason, SQLState, vendorCode);
	}

	public static SQLException newSQLNonTransientConnectionException(String reason, String SQLState, int vendorCode) {
		return new SQLNonTransientConnectionException(reason, SQLState, vendorCode);
	}

	public static SQLException newSQLSyntaxErrorException(String reason, String SQLState, int vendorCode) {
		return new SQLSyntaxErrorException(reason, SQLState, vendorCode);
	}

	public static SQLException newSQLTransactionRollbackException(String reason, String SQLState, int vendorCode) {
		return new SQLTransactionRollbackException(reason, SQLState, vendorCode);
	}

	public static SQLException newSQLTransientConnectionException(String reason, String SQLState, int vendorCode) {
		return new SQLTransientConnectionException(reason, SQLState, vendorCode);
	}

	public static SQLException newSQLTimeoutException(String reason, String SQLState, int vendorCode) {
		return new SQLTimeoutException(reason, SQLState, vendorCode);
	}

	public static SQLException newSQLRecoverableException(String reason, String SQLState, int vendorCode) {
		return new SQLRecoverableException(reason, SQLState, vendorCode);
	}

}


text:
BEGIN_THUNLP_NAMESPACE
class LinearBigramChineseTextClassifier : public thunlp::LiblinearTextClassifier {
protected:
    thunlp::WordSegment* initWordSegment() { return new thunlp::BigramWordSegment(); }
public:
    LinearBigramChineseTextClassifier(int nclasses):thunlp::LiblinearTextClassifier(nclasses, initWordSegment()) {}
    LinearBigramChineseTextClassifier(int nclasses, thunlp::WordSegment* seg):thunlp::LiblinearTextClassifier(nclasses, seg) {}
};
END_THUNLP_NAMESPACE

#endif //CLASSIFIERLIB_LINEARBIGRAMCHINESETEXTCLASSIFIER_H


text:
class KCompressor
{
public:
	KCompressor(void);
	~KCompressor(void);
	int Update(const char* source,int inputSize,char* dest,int outMaxSize);
private:
	LZ4_stream_t* m_lz4;
};


text:
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
using UnityEngine;

namespace Microsoft.MixedReality.Toolkit.UI
{
    /// <summary>
    /// Component that plays sounds to communicate the state of a pinch slider
    /// </summary>
    [RequireComponent(typeof(PinchSlider))]
    [AddComponentMenu("Scripts/MRTK/SDK/SliderSounds")]
    public class SliderSounds : MonoBehaviour
    {
        [SerializeField]
        private bool playSoundsOnlyOnInteract = false;

        [Header("Audio Clips")]
        [SerializeField]
        [Tooltip("Sound to play when interaction with slider starts")]
        private AudioClip interactionStartSound = null;
        [SerializeField]
        [Tooltip("Sound to play when interaction with slider ends")]
        private AudioClip interactionEndSound = null;

        [Header("Tick Notch Sounds")]

        [SerializeField]
        [Tooltip("Whether to play 'tick tick' sounds as the slider passes notches")]
        private bool playTickSounds = true;

        [SerializeField]
        [Tooltip("Whether to line up the 'tick tick' sounds with slider step divisions when those are in use")]
        private bool alignWithStepSlider = true;

        [SerializeField]
        [Tooltip("Sound to play when slider passes a notch")]
        private AudioClip passNotchSound = null;

        [Range(0, 1)]
        [SerializeField]
        private float tickEvery = 0.1f;

        [SerializeField]
        private float startPitch = 0.75f;

        [SerializeField]
        private float endPitch = 1.25f;

        [SerializeField]
        private float minSecondsBetweenTicks = 0.01f;

        #region Private members
        private PinchSlider slider;

        // Check to see if the slider is being interacted with
        private bool isInteracting;

        // Play sound when passing through slider notches
        private float accumulatedDeltaSliderValue = 0;
        private float lastSoundPlayTime;

        private AudioSource grabReleaseAudioSource = null;
        private AudioSource passNotchAudioSource = null;
        #endregion

        private void Start()
        {
            if (grabReleaseAudioSource == null)
            {
                grabReleaseAudioSource = gameObject.AddComponent<AudioSource>();
            }
            if (passNotchAudioSource == null)
            {
                passNotchAudioSource = gameObject.AddComponent<AudioSource>();
            }

            slider = GetComponent<PinchSlider>();
            if (alignWithStepSlider && slider.UseSliderStepDivisions)
            {
                tickEvery = 1.0f / slider.SliderStepDivisions;
            }
            slider.OnInteractionStarted.AddListener(OnInteractionStarted);
            slider.OnInteractionEnded.AddListener(OnInteractionEnded);
            slider.OnValueUpdated.AddListener(OnValueUpdated);
        }

        private void OnValueUpdated(SliderEventData eventData)
        {
            if (!(playSoundsOnlyOnInteract && !isInteracting) && playTickSounds && passNotchAudioSource != null && passNotchSound != null)
            {
                float delta = eventData.NewValue - eventData.OldValue;
                accumulatedDeltaSliderValue += Mathf.Abs(delta);
                var now = Time.timeSinceLevelLoad;
                if (accumulatedDeltaSliderValue >= tickEvery && now - lastSoundPlayTime > minSecondsBetweenTicks)
                {
                    passNotchAudioSource.pitch = Mathf.Lerp(startPitch, endPitch, eventData.NewValue);
                    if (passNotchAudioSource.isActiveAndEnabled)
                    {
                        passNotchAudioSource.PlayOneShot(passNotchSound);
                    }

                    accumulatedDeltaSliderValue = 0;
                    lastSoundPlayTime = now;
                }
            }
        }

        private void OnInteractionEnded(SliderEventData arg0)
        {
            isInteracting = false;
            if (interactionEndSound != null && grabReleaseAudioSource != null && grabReleaseAudioSource.isActiveAndEnabled)
            {
                grabReleaseAudioSource.PlayOneShot(interactionEndSound);
            }
        }

        private void OnInteractionStarted(SliderEventData arg0)
        {
            isInteracting = true;
            if (interactionStartSound != null && grabReleaseAudioSource != null && grabReleaseAudioSource.isActiveAndEnabled)
            {
                grabReleaseAudioSource.PlayOneShot(interactionStartSound);
            }
        }
    }

}


text:
def extractNanoDesuHaitoGensounoGrimgal(item):
	"""

	"""
	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol or frag) or 'preview' in item['title'].lower():
		return None
	return False


text:
//  ----------------------------------------------------
//  AIMP DotNet SDK
//
//  Copyright (c) 2014 - 2022 Evgeniy Bogdan
//  https://github.com/martin211/aimp_dotnet
//
//  Mail: mail4evgeniy@gmail.com
//  ----------------------------------------------------

namespace AIMP.SDK.Playlist
{
    /// <summary>
    /// Class Constants.
    /// </summary>
    public static class Constants
    {
        /// <summary>
        /// Class PreimageFactory.
        /// </summary>
        public static class PreimageFactory
        {
            /// <summary>
            /// The folders identifier
            /// </summary>
            public static readonly string FoldersId = "TAIMPPlaylistFoldersPreimage";

            /// <summary>
            /// The music library identifier
            /// </summary>
            public static readonly string MusicLibraryId = "TAIMPMLPlaylistPreimage";

            /// <summary>
            /// The playlist identifier
            /// </summary>
            public static readonly string PlaylistId = "TAIMPPlaylistBasedPreimage";
        }
    }
}


text:
using System;
using System.Globalization;
using System.Text;
using Xunit;

namespace System.Text.EncodingTests
{
    public class EncodingTest
    {
        private static byte[] s_UTF32LEBom = new byte[] { 0xFF, 0xFE, 0x0, 0x0 };
        private static byte[] s_UTF32BEBom = new byte[] { 0x0, 0x0, 0xFE, 0xFF, };
        private static byte[] s_UTF8Bom = new byte[] { 0xEF, 0xBB, 0xBF };
        private static byte[] s_UTF16LEBom = new byte[] { 0xFF, 0xFE };
        private static byte[] s_UTF8BEBom = new byte[] { 0xFE, 0xFF };

        [Fact]
        public static void TestGetEncoding()
        {
            Encoding encoding = Encoding.GetEncoding("UTF-32LE");
            Assert.Equal<byte>(encoding.GetPreamble(), s_UTF32LEBom);

            encoding = Encoding.UTF32;
            Assert.Equal<byte>(encoding.GetPreamble(), s_UTF32LEBom);

            encoding = Encoding.GetEncoding("UTF-32BE");
            Assert.Equal<byte>(encoding.GetPreamble(), s_UTF32BEBom);

            encoding = Encoding.UTF8;
            Assert.Equal<byte>(encoding.GetPreamble(), s_UTF8Bom);

            encoding = Encoding.GetEncoding("UTF-16BE");
            Assert.Equal<byte>(encoding.GetPreamble(), s_UTF8BEBom);

            encoding = Encoding.GetEncoding("UTF-16LE");
            Assert.Equal<byte>(encoding.GetPreamble(), s_UTF16LEBom);

            encoding = Encoding.Unicode;
            Assert.Equal<byte>(encoding.GetPreamble(), s_UTF16LEBom);
        }

        private static byte[] s_asciiBytes = new byte[] { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', };
        private static string s_asciiString = "ABCDEFGH";

        [Fact]
        public static void TestEncodingDecoding()
        {
            Encoding encoding = Encoding.ASCII;
            byte[] bytes = encoding.GetBytes(s_asciiString);
            Assert.Equal<byte>(bytes, s_asciiBytes);
            string s = encoding.GetString(bytes, 0, bytes.Length);
            Assert.True(s.Equals(s_asciiString));
            s = encoding.GetString(bytes);
            Assert.True(s.Equals(s_asciiString));

            encoding = Encoding.GetEncoding("us-ascii");
            bytes = encoding.GetBytes(s_asciiString);
            Assert.Equal<byte>(bytes, s_asciiBytes);
            s = encoding.GetString(bytes, 0, bytes.Length);
            Assert.True(s.Equals(s_asciiString));
            s = encoding.GetString(bytes);
            Assert.True(s.Equals(s_asciiString));

            encoding = Encoding.GetEncoding("latin1");
            bytes = encoding.GetBytes(s_asciiString);
            Assert.Equal<byte>(bytes, s_asciiBytes);
            s = encoding.GetString(bytes, 0, bytes.Length);
            Assert.True(s.Equals(s_asciiString));
            s = encoding.GetString(bytes);
            Assert.True(s.Equals(s_asciiString));
        }

        public class CodePageMapping
        {
            public CodePageMapping(string name, int codepage)
            {
                Name = name;
                CodePage = codepage;
            }
            public string Name { set; get; }
            public int CodePage { set; get; }
        }

        private static CodePageMapping[] s_mapping = new CodePageMapping[] {
        new CodePageMapping("ANSI_X3.4-1968", 20127 ),
        new CodePageMapping("ANSI_X3.4-1986", 20127 ),
        new CodePageMapping("ascii", 20127 ),
        new CodePageMapping("cp367", 20127 ),
        new CodePageMapping("cp819", 28591 ),
        new CodePageMapping("csASCII", 20127 ),
        new CodePageMapping("csISOLatin1", 28591 ),
        new CodePageMapping("csUnicode11UTF7", 65000 ),
        new CodePageMapping("IBM367", 20127 ),
        new CodePageMapping("ibm819", 28591 ),
        new CodePageMapping("ISO-10646-UCS-2", 1200),
        new CodePageMapping("iso-8859-1", 28591),
        new CodePageMapping("iso-ir-100", 28591),
        new CodePageMapping("iso-ir-6", 20127),
        new CodePageMapping("ISO646-US", 20127),
        new CodePageMapping("iso8859-1", 28591),
        new CodePageMapping("ISO_646.irv:1991", 20127),
        new CodePageMapping("iso_8859-1", 28591),
        new CodePageMapping("iso_8859-1:1987", 28591),
        new CodePageMapping("l1", 28591),
        new CodePageMapping("latin1", 28591),
        new CodePageMapping("ucs-2", 1200),
        new CodePageMapping("unicode", 1200),
        new CodePageMapping("unicode-1-1-utf-7", 65000),
        new CodePageMapping("unicode-1-1-utf-8", 65001),
        new CodePageMapping("unicode-2-0-utf-7", 65000),
        new CodePageMapping("unicode-2-0-utf-8", 65001),
        new CodePageMapping("unicodeFFFE", 1201),
        new CodePageMapping("us", 20127),
        new CodePageMapping("us-ascii", 20127),
        new CodePageMapping("utf-16", 1200),
        new CodePageMapping("UTF-16BE", 1201),
        new CodePageMapping("UTF-16LE", 1200),
        new CodePageMapping("utf-32", 12000),
        new CodePageMapping("UTF-32BE", 12001),
        new CodePageMapping("UTF-32LE", 12000),
        new CodePageMapping("utf-7", 65000),
        new CodePageMapping("utf-8", 65001),
        new CodePageMapping("x-unicode-1-1-utf-7", 65000),
        new CodePageMapping("x-unicode-1-1-utf-8", 65001),
        new CodePageMapping("x-unicode-2-0-utf-7", 65000),
        new CodePageMapping("x-unicode-2-0-utf-8", 65001)
    };

        [Fact]
        public static void TestEncodingNameAndCopdepageNumber()
        {
            foreach (var map in s_mapping)
            {
                Encoding encoding = Encoding.GetEncoding(map.Name);
                Assert.True(encoding.CodePage == map.CodePage);
            }
        }

        [Fact]
        public static void TestEncodingDisplayNames()
        {
            CultureInfo originalUICulture = CultureInfo.CurrentUICulture;
            try
            {
                CultureInfo.CurrentCulture = new CultureInfo("en-US");

                foreach (var map in s_mapping)
                {
                    Encoding encoding = Encoding.GetEncoding(map.Name);

                    string name = encoding.EncodingName;

                    if (string.IsNullOrEmpty(name))
                    {
                        Assert.False(true, "failed to get the display name of the encoding: " + encoding.WebName);
                    }

                    for (int i = 0; i < name.Length; ++i)
                    {
                        int ch = (int)name[i];

                        if (ch > 127)
                        {
                            Assert.False(true,
                                string.Format("English name '{0}' for encoding '{1}' contains non-ASCII character: {2}",
                                    name, encoding.WebName, ch));
                        }
                    }
                }
            }
            finally
            {
                CultureInfo.CurrentUICulture = originalUICulture;
            }
        }

        [Fact]
        public static void TestCodePageToWebNameMappings()
        {
            foreach (var mapping in s_codePageToWebNameMappings)
            {
                Encoding encoding = Encoding.GetEncoding(mapping.CodePage);
                Assert.True(string.Equals(mapping.WebName, encoding.WebName, StringComparison.OrdinalIgnoreCase));
            }
        }

        internal class CodePageToWebNameMapping
        {
            public CodePageToWebNameMapping(int codePage, string webName)
            {
                _codePage = codePage;
                _webName = webName;
            }

            public int CodePage { get { return _codePage; } }
            public string WebName { get { return _webName; } }

            private int _codePage;
            private string _webName;
        }

        private static readonly CodePageToWebNameMapping[] s_codePageToWebNameMappings = new[]
    {
        new CodePageToWebNameMapping(1200, "utf-16"),
        new CodePageToWebNameMapping(1201, "utf-16be"),
        new CodePageToWebNameMapping(12000, "utf-32"),
        new CodePageToWebNameMapping(12001, "utf-32be"),
        new CodePageToWebNameMapping(20127, "us-ascii"),
        new CodePageToWebNameMapping(28591, "iso-8859-1"),
        new CodePageToWebNameMapping(65000, "utf-7"),
        new CodePageToWebNameMapping(65001, "utf-8")
    };
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="EntryPointsManager">
    <entry_points version="2.0" />
  </component>
  <component name="FrameworkDetectionExcludesConfiguration">
    <file type="web" url="file://$PROJECT_DIR$" />
  </component>
  <component name="IdProvider" IDEtalkID="0F9A76D83228B59F7AF0BA14AA53FF6F" />
  <component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" assert-keyword="true" jdk-15="true" project-jdk-name="1.7" project-jdk-type="JavaSDK">
    <output url="file://$PROJECT_DIR$/build/classes" />
  </component>
</project>