text:
package engines

import (
	"bytes"
	"fmt"
	"image"
	"image/draw"
	"image/gif"
	"image/jpeg"
	"image/png"
	"io"
	"math"
	"strconv"
	"time"

	"github.com/disintegration/imaging"
	"github.com/imdario/mergo"
	imagefile "github.com/lizdeika/picfit/image"
	"golang.org/x/image/bmp"
	"golang.org/x/image/tiff"
)

type GoImageEngine struct {
	DefaultFormat  string
	Format         string
	DefaultQuality int
}

type ImageTransformation func(img image.Image) *image.NRGBA

var FlipTransformations = map[string]ImageTransformation{
	"h": imaging.FlipH,
	"v": imaging.FlipV,
}

var RotateTransformations = map[int]ImageTransformation{
	90:  imaging.Rotate90,
	270: imaging.Rotate270,
	180: imaging.Rotate180,
}

type Result struct {
	Paletted *image.Paletted
	Image    *image.NRGBA
	Position int
}

type Transformation func(img image.Image, width int, height int, filter imaging.ResampleFilter) *image.NRGBA

func scalingFactor(srcWidth int, srcHeight int, destWidth int, destHeight int) float64 {
	return math.Max(float64(destWidth)/float64(srcWidth), float64(destHeight)/float64(srcHeight))
}

func ImageSize(e image.Image) (int, int) {
	return e.Bounds().Max.X, e.Bounds().Max.Y
}

func (e *GoImageEngine) Scale(img image.Image, dstWidth int, dstHeight int, upscale bool, trans Transformation) *image.NRGBA {
	width, height := ImageSize(img)

	factor := scalingFactor(width, height, dstWidth, dstHeight)

	if factor < 1 || upscale {
		return trans(img, dstWidth, dstHeight, imaging.Lanczos)
	}

	return imaging.Clone(img)
}

func (e *GoImageEngine) TransformGIF(img *imagefile.ImageFile, width int, height int, options *Options, trans Transformation) ([]byte, error) {
	g, err := gif.DecodeAll(bytes.NewReader(img.Source))

	if err != nil {
		return nil, err
	}

	length := len(g.Image)
	done := make(chan *Result)
	images := make([]*image.Paletted, length)
	processed := 0

	for i := range g.Image {
		go func(paletted *image.Paletted, width int, height int, position int, trans Transformation, options *Options) {
			done <- &Result{
				Image:    e.Scale(paletted, width, height, options.Upscale, trans),
				Position: position,
				Paletted: image.NewPaletted(image.Rect(0, 0, width, height), paletted.Palette),
			}
		}(g.Image[i], width, height, i, trans, options)
	}

	for {
		select {
		case result := <-done:
			draw.Draw(result.Paletted, image.Rect(0, 0, width, height), result.Image, image.Pt(0, 0), draw.Src)

			images[result.Position] = result.Paletted

			processed++
		case <-time.After(time.Second * 5):
			break
		}

		if processed == length {
			break
		}
	}

	close(done)

	g.Image = images

	buf := &bytes.Buffer{}

	err = gif.EncodeAll(buf, g)

	if err != nil {
		return nil, err
	}

	return buf.Bytes(), nil
}

func (e *GoImageEngine) Resize(img *imagefile.ImageFile, width int, height int, options *Options) ([]byte, error) {
	if options.Format == imaging.GIF {
		content, err := e.TransformGIF(img, width, height, options, imaging.Resize)

		if err != nil {
			return nil, err
		}

		return content, nil
	}

	image, err := e.Source(img)

	if err != nil {
		return nil, err
	}

	return e.resize(image, width, height, options)
}

func (e *GoImageEngine) resize(img image.Image, width int, height int, options *Options) ([]byte, error) {
	return e.ToBytes(e.Scale(img, width, height, options.Upscale, imaging.Resize), options.Format, options.Quality)
}

func (e *GoImageEngine) Source(img *imagefile.ImageFile) (image.Image, error) {
	return imaging.Decode(bytes.NewReader(img.Source))
}

func (e *GoImageEngine) Rotate(img *imagefile.ImageFile, deg int, options *Options) ([]byte, error) {
	image, err := e.Source(img)

	if err != nil {
		return nil, err
	}

	transform, ok := RotateTransformations[deg]

	if !ok {
		return nil, fmt.Errorf("Invalid rotate transformation degree=%d is not supported", deg)
	}

	return e.ToBytes(transform(image), options.Format, options.Quality)
}

func (e *GoImageEngine) Flip(img *imagefile.ImageFile, pos string, options *Options) ([]byte, error) {
	image, err := e.Source(img)

	if err != nil {
		return nil, err
	}

	transform, ok := FlipTransformations[pos]

	if !ok {
		return nil, fmt.Errorf("Invalid flip transformation, %s is not supported", pos)
	}

	return e.ToBytes(transform(image), options.Format, options.Quality)
}

func (e *GoImageEngine) Thumbnail(img *imagefile.ImageFile, width int, height int, options *Options) ([]byte, error) {
	if options.Format == imaging.GIF {
		content, err := e.TransformGIF(img, width, height, options, imaging.Thumbnail)

		if err != nil {
			return nil, err
		}

		return content, nil
	}

	image, err := e.Source(img)

	if err != nil {
		return nil, err
	}

	return e.thumbnail(image, width, height, options)
}

func (e *GoImageEngine) thumbnail(img image.Image, width int, height int, options *Options) ([]byte, error) {
	return e.ToBytes(e.Scale(img, width, height, options.Upscale, imaging.Thumbnail), options.Format, options.Quality)
}

func (e *GoImageEngine) Fit(img *imagefile.ImageFile, width int, height int, options *Options) ([]byte, error) {
	if options.Format == imaging.GIF {
		content, err := e.TransformGIF(img, width, height, options, imaging.Thumbnail)

		if err != nil {
			return nil, err
		}

		return content, nil
	}

	image, err := e.Source(img)

	if err != nil {
		return nil, err
	}

	return e.fit(image, width, height, options)
}

func (e *GoImageEngine) fit(img image.Image, width int, height int, options *Options) ([]byte, error) {
	return e.ToBytes(e.Scale(img, width, height, options.Upscale, imaging.Fit), options.Format, options.Quality)
}

func (e *GoImageEngine) Transform(img *imagefile.ImageFile, operation *Operation, qs map[string]string) (*imagefile.ImageFile, error) {
	params := map[string]string{
		"upscale": "1",
		"h":       "0",
		"w":       "0",
		"deg":     "90",
	}

	err := mergo.Merge(&qs, params)

	if err != nil {
		return nil, err
	}

	var quality int
	var format string

	q, ok := qs["q"]

	if ok {
		quality, err := strconv.Atoi(q)

		if err != nil {
			return nil, err
		}

		if quality > 100 {
			return nil, fmt.Errorf("Quality should be <= 100")
		}
	} else {
		quality = e.DefaultQuality
	}

	format, ok = qs["fmt"]
	filepath := img.Filepath

	if ok {
		if _, ok := ContentTypes[format]; !ok {
			return nil, fmt.Errorf("Unknown format %s", format)
		}

	}

	if format == "" && e.Format != "" {
		format = e.Format
	}

	if format == "" {
		format = img.Format()
	}

	if format == "" {
		format = e.DefaultFormat
	}

	if format != img.Format() {
		index := len(filepath) - len(img.Format())

		filepath = filepath[:index] + format
	}

	file := &imagefile.ImageFile{
		Source:   img.Source,
		Key:      img.Key,
		Headers:  img.Headers,
		Filepath: filepath,
	}

	options := &Options{
		Quality: quality,
		Format:  Formats[format],
	}

	switch operation {
	case Flip:
		pos, ok := qs["pos"]

		if !ok {
			return nil, fmt.Errorf("Parameter \"pos\" not found in query string")
		}

		content, err := e.Flip(img, pos, options)

		if err != nil {
			return nil, err
		}

		file.Processed = content

		return file, err
	case Rotate:
		deg, err := strconv.Atoi(qs["deg"])

		if err != nil {
			return nil, err
		}

		content, err := e.Rotate(img, deg, options)

		if err != nil {
			return nil, err
		}

		file.Processed = content

		return file, err
	case Thumbnail, Resize, Fit:
		var upscale bool
		var w int
		var h int

		if upscale, err = strconv.ParseBool(qs["upscale"]); err != nil {
			return nil, err
		}

		if w, err = strconv.Atoi(qs["w"]); err != nil {
			return nil, err
		}

		if h, err = strconv.Atoi(qs["h"]); err != nil {
			return nil, err
		}

		options.Upscale = upscale

		switch operation {
		case Resize:
			content, err := e.Resize(img, w, h, options)

			if err != nil {
				return nil, err
			}

			file.Processed = content

			return file, err
		case Thumbnail:
			content, err := e.Thumbnail(img, w, h, options)

			if err != nil {
				return nil, err
			}

			file.Processed = content

			return file, err
		case Fit:
			content, err := e.Fit(img, w, h, options)

			if err != nil {
				return nil, err
			}

			file.Processed = content

			return file, err
		}
	}

	return nil, fmt.Errorf("Operation not found for %s", operation)
}

func (e *GoImageEngine) ToBytes(img image.Image, format imaging.Format, quality int) ([]byte, error) {
	buf := &bytes.Buffer{}

	var err error

	err = encode(buf, img, format, quality)

	if err != nil {
		return nil, err
	}

	return buf.Bytes(), nil
}

func encode(w io.Writer, img image.Image, format imaging.Format, quality int) error {
	var err error
	switch format {
	case imaging.JPEG:
		var rgba *image.RGBA
		if nrgba, ok := img.(*image.NRGBA); ok {
			if nrgba.Opaque() {
				rgba = &image.RGBA{
					Pix:    nrgba.Pix,
					Stride: nrgba.Stride,
					Rect:   nrgba.Rect,
				}
			}
		}
		if rgba != nil {
			err = jpeg.Encode(w, rgba, &jpeg.Options{Quality: quality})
		} else {
			err = jpeg.Encode(w, img, &jpeg.Options{Quality: quality})
		}

	case imaging.PNG:
		err = png.Encode(w, img)
	case imaging.GIF:
		err = gif.Encode(w, img, &gif.Options{NumColors: 256})
	case imaging.TIFF:
		err = tiff.Encode(w, img, &tiff.Options{Compression: tiff.Deflate, Predictor: true})
	case imaging.BMP:
		err = bmp.Encode(w, img)
	default:
		err = imaging.ErrUnsupportedFormat
	}
	return err
}


text:
@interface LinkedNode : NSObject

@property (nonatomic) NSInteger value;
@property (nonatomic,strong) LinkedNode *next;

@end

redpajama_set_name: RedPajamaGithub


text:
package org.apache.storm.topology;

import java.util.Map;

public interface ComponentConfigurationDeclarer<T extends ComponentConfigurationDeclarer> extends ResourceDeclarer<T> {
    /**
     * add in several configs to the component.
     * @param conf the configs to add
     * @return this for chaining.
     */
    T addConfigurations(Map<String, Object> conf);

    /**
     * Add in a single config.
     * @param config the key for the config
     * @param value the value of the config
     * @return this for chaining.
     */
    T addConfiguration(String config, Object value);

    /**
     * Turn on/off debug for this component.
     * @param debug true for debug on false for debug off
     * @return this for chaining
     */
    T setDebug(boolean debug);

    /**
     * Set the max task parallelism for this component.
     * @param val the maximum parallelism
     * @return this for chaining
     */
    T setMaxTaskParallelism(Number val);

    /**
     * Set the max spout pending config for this component.
     * @param val the value of max spout pending.
     * @return this for chaining
     */
    T setMaxSpoutPending(Number val);

    /**
     * Set the number of tasks for this component.
     * @param val the number of tasks
     * @return this for chaining.
     */
    T setNumTasks(Number val);

    /**
     * Add generic resources for this component.
     */
    T addResources(Map<String, Double> resources);

    /**
     * Add generic resource for this component.
     */
    T addResource(String resourceName, Number resourceValue);
}


text:
package opensearch

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// CreateModel invokes the opensearch.CreateModel API synchronously
func (client *Client) CreateModel(request *CreateModelRequest) (response *CreateModelResponse, err error) {
	response = CreateCreateModelResponse()
	err = client.DoAction(request, response)
	return
}

// CreateModelWithChan invokes the opensearch.CreateModel API asynchronously
func (client *Client) CreateModelWithChan(request *CreateModelRequest) (<-chan *CreateModelResponse, <-chan error) {
	responseChan := make(chan *CreateModelResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.CreateModel(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// CreateModelWithCallback invokes the opensearch.CreateModel API asynchronously
func (client *Client) CreateModelWithCallback(request *CreateModelRequest, callback func(response *CreateModelResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *CreateModelResponse
		var err error
		defer close(result)
		response, err = client.CreateModel(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// CreateModelRequest is the request struct for api CreateModel
type CreateModelRequest struct {
	*requests.RoaRequest
	AppGroupIdentity string `position:"Path" name:"appGroupIdentity"`
}

// CreateModelResponse is the response struct for api CreateModel
type CreateModelResponse struct {
	*responses.BaseResponse
	RequestId string                 `json:"requestId" xml:"requestId"`
	Result    map[string]interface{} `json:"result" xml:"result"`
}

// CreateCreateModelRequest creates a request to invoke CreateModel API
func CreateCreateModelRequest() (request *CreateModelRequest) {
	request = &CreateModelRequest{
		RoaRequest: &requests.RoaRequest{},
	}
	request.InitWithApiInfo("OpenSearch", "2017-12-25", "CreateModel", "/v4/openapi/app-groups/[appGroupIdentity]/algorithm/models", "opensearch", "openAPI")
	request.Method = requests.POST
	return
}

// CreateCreateModelResponse creates a response to parse from CreateModel response
func CreateCreateModelResponse() (response *CreateModelResponse) {
	response = &CreateModelResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
description: Manage keys for content trust
keywords:
- trust, security, root,  keys, repository
title: Manage keys for content trust
---

Trust for an image tag is managed through the use of keys. Docker's content
trust makes use of five different types of keys:

| Key                 | Description                                                                                |
|---------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| root key         | Root of content trust for an image tag. When content trust is enabled, you create the root key once. Also known as the offline key, because it should be kept offline. |
| targets          | This key allows you to sign image tags, to manage delegations including delegated keys or permitted delegation paths. Also known as the repository key, since this key determines what tags can be signed into an image repository. |
| snapshot         | This key signs the current collection of image tags, preventing mix and match attacks.
| timestamp        | This key allows Docker image repositories to have freshness security guarantees without requiring periodic content refreshes on the client's side. |
| delegation       | Delegation keys are optional tagging keys and allow you to delegate signing image tags to other publishers without having to share your targets key. |

When doing a `docker push` with Content Trust enabled for the first time, the
root, targets, snapshot, and timestamp keys are generated automatically for
the image repository:

- The root and targets key are generated and stored locally client-side.

- The timestamp and snapshot keys are safely generated and stored in a signing server
	that is deployed alongside the Docker registry. These keys are generated in a backend
	service that isn't directly exposed to the internet and are encrypted at rest.

Delegation keys are optional, and not generated as part of the normal `docker`
workflow.  They need to be
[manually generated and added to the repository](trust_delegation.md#generating-delegation-keys).

Note: Prior to Docker Engine 1.11, the snapshot key was also generated and stored
locally client-side. [Use the Notary CLI to manage your snapshot key locally
again](/notary/advanced_usage.md#rotate-keys) for
repositories created with newer versions of Docker.

## Choosing a passphrase

The passphrases you chose for both the root key and your repository key should
be randomly generated and stored in a password manager.  Having the repository key
allow users to sign image tags on a repository. Passphrases are used to encrypt
your keys at rest and ensures that a lost laptop or an unintended backup doesn't
put the private key material at risk.

## Back up your keys

All the Docker trust keys are stored encrypted using the passphrase you provide
on creation. Even so, you should still take care of the location where you back them up.
Good practice is to create two encrypted USB keys.

It is very important that you backup your keys to a safe, secure location. Loss
of the repository key is recoverable; loss of the root key is not.

The Docker client stores the keys in the `~/.docker/trust/private` directory.
Before backing them up, you should `tar` them into an archive:

```bash
$ umask 077; tar -zcvf private_keys_backup.tar.gz ~/.docker/trust/private; umask 022
```

## Hardware storage and signing

Docker Content Trust can store and sign with root keys from a Yubikey 4. The
Yubikey is prioritized over keys stored in the filesystem. When you initialize a
new repository with content trust, Docker Engine looks for a root key locally. If a
key is not found and the Yubikey 4 exists, Docker Engine creates a root key in the
Yubikey 4. Please consult the [Notary documentation](/notary/advanced_usage.md#use-a-yubikey) for more details.

Prior to Docker Engine 1.11, this feature was only in the experimental branch.

## Lost keys

If a publisher loses keys it means losing the ability to sign trusted content for
your repositories.  If you lose a key, contact [Docker
Support](https://support.docker.com) (support@docker.com) to reset the repository
state.

This loss also requires **manual intervention** from every consumer that pulled
the tagged image prior to the loss. Image consumers would get an error for
content that they already downloaded:

```
Warning: potential malicious behavior - trust data has insufficient signatures for remote repository docker.io/my/image: valid signatures did not meet threshold
```

To correct this, they need to download a new image tag with that is signed with
the new key.

## Related information

* [Content trust in Docker](content_trust.md)
* [Automation with content trust](trust_automation.md)
* [Delegations for content trust](trust_delegation.md)
* [Play in a content trust sandbox](trust_sandbox.md)


text:
FAQ
===

Why this project?
-----------------

The motivation for this project is an ever growing number of compilers for
Python out there. Pykit tries to provide a higher-level layer than LLVM
or C for typed Python code, focussing on numeric code, so that optimizations
and runtime improvements benefit everyone.

It aims to be reusable for projects including:

    * Numba
    * Parakeet
    * Pythran
    * Theano
    * NumbaPro
    * Your next awesome compiler

If something in pykit somehow precludes reuse in any of the above projects,
then pykit has failed and we need to fix that.

Why not LLVM IR?
----------------

Why not directly use LLVM IR for the internal format? There are pros and
cons to doing that, below are some reasons why not to:

    * Completeness, we can encode all high-level constructs directly in
      the way we wish, without naming schemes, LLVM metadata, or external
      data
    * Instruction polymorphism the way we want it
    * High-level types, such as arrays, complex numbers, objects, partial
      functions etc, without opague type mappings
    * Simple arbitrary metadata through a key/value mechanism
    * No aborting, ever


text:
var Course = require('mongoose').model('Course');
module.exports = {
    getAllCourses : function(req, res, next){
        Course.find({}).exec( function ( err, collection ) {
            if ( err ) {
                console.log( 'Courses could not be found: ' + err );
                return;
            }
            res.send( collection );
        });
    },
     getCourseById: function(req, res, next){
         Course.findOne({_id: req.params.id}).exec(function(err, course){
             if(err){
                 console.log('Course could not be loaded:' + err);
                 return;
             }
             else{
                 res.send(course);
             }
         });
     }
}


text:
import os
import sys
import types

import pytest
from _pytest.config import ExitCode
from _pytest.config import PytestPluginManager
from _pytest.config.exceptions import UsageError
from _pytest.main import Session

@pytest.fixture
def pytestpm():
    return PytestPluginManager()

class TestPytestPluginInteractions:
    def test_addhooks_conftestplugin(self, testdir, _config_for_test):
        testdir.makepyfile(
            newhooks="""
            def pytest_myhook(xyz):
                "new hook"
        """
        )
        conf = testdir.makeconftest(
            """
            import newhooks
            def pytest_addhooks(pluginmanager):
                pluginmanager.add_hookspecs(newhooks)
            def pytest_myhook(xyz):
                return xyz + 1
        """
        )
        config = _config_for_test
        pm = config.pluginmanager
        pm.hook.pytest_addhooks.call_historic(
            kwargs=dict(pluginmanager=config.pluginmanager)
        )
        config.pluginmanager._importconftest(conf)
        # print(config.pluginmanager.get_plugins())
        res = config.hook.pytest_myhook(xyz=10)
        assert res == [11]

    def test_addhooks_nohooks(self, testdir):
        testdir.makeconftest(
            """
            import sys
            def pytest_addhooks(pluginmanager):
                pluginmanager.add_hookspecs(sys)
        """
        )
        res = testdir.runpytest()
        assert res.ret != 0
        res.stderr.fnmatch_lines(["*did not find*sys*"])

    def test_do_option_postinitialize(self, testdir):
        config = testdir.parseconfigure()
        assert not hasattr(config.option, "test123")
        p = testdir.makepyfile(
            """
            def pytest_addoption(parser):
                parser.addoption('--test123', action="store_true",
                    default=True)
        """
        )
        config.pluginmanager._importconftest(p)
        assert config.option.test123

    def test_configure(self, testdir):
        config = testdir.parseconfig()
        values = []

        class A:
            def pytest_configure(self):
                values.append(self)

        config.pluginmanager.register(A())
        assert len(values) == 0
        config._do_configure()
        assert len(values) == 1
        config.pluginmanager.register(A())  # leads to a configured() plugin
        assert len(values) == 2
        assert values[0] != values[1]

        config._ensure_unconfigure()
        config.pluginmanager.register(A())
        assert len(values) == 2

    def test_hook_tracing(self, _config_for_test):
        pytestpm = _config_for_test.pluginmanager  # fully initialized with plugins
        saveindent = []

        class api1:
            def pytest_plugin_registered(self):
                saveindent.append(pytestpm.trace.root.indent)

        class api2:
            def pytest_plugin_registered(self):
                saveindent.append(pytestpm.trace.root.indent)
                raise ValueError()

        values = []
        pytestpm.trace.root.setwriter(values.append)
        undo = pytestpm.enable_tracing()
        try:
            indent = pytestpm.trace.root.indent
            p = api1()
            pytestpm.register(p)
            assert pytestpm.trace.root.indent == indent
            assert len(values) >= 2
            assert "pytest_plugin_registered" in values[0]
            assert "finish" in values[1]

            values[:] = []
            with pytest.raises(ValueError):
                pytestpm.register(api2())
            assert pytestpm.trace.root.indent == indent
            assert saveindent[0] > indent
        finally:
            undo()

    def test_hook_proxy(self, testdir):
        """Test the gethookproxy function(#2016)"""
        config = testdir.parseconfig()
        session = Session.from_config(config)
        testdir.makepyfile(**{"tests/conftest.py": "", "tests/subdir/conftest.py": ""})

        conftest1 = testdir.tmpdir.join("tests/conftest.py")
        conftest2 = testdir.tmpdir.join("tests/subdir/conftest.py")

        config.pluginmanager._importconftest(conftest1)
        ihook_a = session.gethookproxy(testdir.tmpdir.join("tests"))
        assert ihook_a is not None
        config.pluginmanager._importconftest(conftest2)
        ihook_b = session.gethookproxy(testdir.tmpdir.join("tests"))
        assert ihook_a is not ihook_b

    def test_hook_with_addoption(self, testdir):
        """Test that hooks can be used in a call to pytest_addoption"""
        testdir.makepyfile(
            newhooks="""
            import pytest
            @pytest.hookspec(firstresult=True)
            def pytest_default_value():
                pass
        """
        )
        testdir.makepyfile(
            myplugin="""
            import newhooks
            def pytest_addhooks(pluginmanager):
                pluginmanager.add_hookspecs(newhooks)
            def pytest_addoption(parser, pluginmanager):
                default_value = pluginmanager.hook.pytest_default_value()
                parser.addoption("--config", help="Config, defaults to %(default)s", default=default_value)
        """
        )
        testdir.makeconftest(
            """
            pytest_plugins=("myplugin",)
            def pytest_default_value():
                return "default_value"
        """
        )
        res = testdir.runpytest("--help")
        res.stdout.fnmatch_lines(["*--config=CONFIG*default_value*"])

def test_default_markers(testdir):
    result = testdir.runpytest("--markers")
    result.stdout.fnmatch_lines(["*tryfirst*first*", "*trylast*last*"])

def test_importplugin_error_message(testdir, pytestpm):
    """Don't hide import errors when importing plugins and provide
    an easy to debug message.

    See #375 and #1998.
    """
    testdir.syspathinsert(testdir.tmpdir)
    testdir.makepyfile(
        qwe="""\
        def test_traceback():
            raise ImportError('Not possible to import: ☺')
        test_traceback()
        """
    )
    with pytest.raises(ImportError) as excinfo:
        pytestpm.import_plugin("qwe")

    assert str(excinfo.value).endswith(
        'Error importing plugin "qwe": Not possible to import: ☺'
    )
    assert "in test_traceback" in str(excinfo.traceback[-1])

class TestPytestPluginManager:
    def test_register_imported_modules(self):
        pm = PytestPluginManager()
        mod = types.ModuleType("x.y.pytest_hello")
        pm.register(mod)
        assert pm.is_registered(mod)
        values = pm.get_plugins()
        assert mod in values
        pytest.raises(ValueError, pm.register, mod)
        pytest.raises(ValueError, lambda: pm.register(mod))
        # assert not pm.is_registered(mod2)
        assert pm.get_plugins() == values

    def test_canonical_import(self, monkeypatch):
        mod = types.ModuleType("pytest_xyz")
        monkeypatch.setitem(sys.modules, "pytest_xyz", mod)
        pm = PytestPluginManager()
        pm.import_plugin("pytest_xyz")
        assert pm.get_plugin("pytest_xyz") == mod
        assert pm.is_registered(mod)

    def test_consider_module(self, testdir, pytestpm):
        testdir.syspathinsert()
        testdir.makepyfile(pytest_p1="#")
        testdir.makepyfile(pytest_p2="#")
        mod = types.ModuleType("temp")
        mod.pytest_plugins = ["pytest_p1", "pytest_p2"]
        pytestpm.consider_module(mod)
        assert pytestpm.get_plugin("pytest_p1").__name__ == "pytest_p1"
        assert pytestpm.get_plugin("pytest_p2").__name__ == "pytest_p2"

    def test_consider_module_import_module(self, testdir, _config_for_test):
        pytestpm = _config_for_test.pluginmanager
        mod = types.ModuleType("x")
        mod.pytest_plugins = "pytest_a"
        aplugin = testdir.makepyfile(pytest_a="#")
        reprec = testdir.make_hook_recorder(pytestpm)
        testdir.syspathinsert(aplugin.dirpath())
        pytestpm.consider_module(mod)
        call = reprec.getcall(pytestpm.hook.pytest_plugin_registered.name)
        assert call.plugin.__name__ == "pytest_a"

        # check that it is not registered twice
        pytestpm.consider_module(mod)
        values = reprec.getcalls("pytest_plugin_registered")
        assert len(values) == 1

    def test_consider_env_fails_to_import(self, monkeypatch, pytestpm):
        monkeypatch.setenv("PYTEST_PLUGINS", "nonexisting", prepend=",")
        with pytest.raises(ImportError):
            pytestpm.consider_env()

    @pytest.mark.filterwarnings("always")
    def test_plugin_skip(self, testdir, monkeypatch):
        p = testdir.makepyfile(
            skipping1="""
            import pytest
            pytest.skip("hello", allow_module_level=True)
        """
        )
        p.copy(p.dirpath("skipping2.py"))
        monkeypatch.setenv("PYTEST_PLUGINS", "skipping2")
        result = testdir.runpytest("-p", "skipping1", syspathinsert=True)
        assert result.ret == ExitCode.NO_TESTS_COLLECTED
        result.stdout.fnmatch_lines(
            ["*skipped plugin*skipping1*hello*", "*skipped plugin*skipping2*hello*"]
        )

    def test_consider_env_plugin_instantiation(self, testdir, monkeypatch, pytestpm):
        testdir.syspathinsert()
        testdir.makepyfile(xy123="#")
        monkeypatch.setitem(os.environ, "PYTEST_PLUGINS", "xy123")
        l1 = len(pytestpm.get_plugins())
        pytestpm.consider_env()
        l2 = len(pytestpm.get_plugins())
        assert l2 == l1 + 1
        assert pytestpm.get_plugin("xy123")
        pytestpm.consider_env()
        l3 = len(pytestpm.get_plugins())
        assert l2 == l3

    def test_pluginmanager_ENV_startup(self, testdir, monkeypatch):
        testdir.makepyfile(pytest_x500="#")
        p = testdir.makepyfile(
            """
            import pytest
            def test_hello(pytestconfig):
                plugin = pytestconfig.pluginmanager.get_plugin('pytest_x500')
                assert plugin is not None
        """
        )
        monkeypatch.setenv("PYTEST_PLUGINS", "pytest_x500", prepend=",")
        result = testdir.runpytest(p, syspathinsert=True)
        assert result.ret == 0
        result.stdout.fnmatch_lines(["*1 passed*"])

    def test_import_plugin_importname(self, testdir, pytestpm):
        pytest.raises(ImportError, pytestpm.import_plugin, "qweqwex.y")
        pytest.raises(ImportError, pytestpm.import_plugin, "pytest_qweqwx.y")

        testdir.syspathinsert()
        pluginname = "pytest_hello"
        testdir.makepyfile(**{pluginname: ""})
        pytestpm.import_plugin("pytest_hello")
        len1 = len(pytestpm.get_plugins())
        pytestpm.import_plugin("pytest_hello")
        len2 = len(pytestpm.get_plugins())
        assert len1 == len2
        plugin1 = pytestpm.get_plugin("pytest_hello")
        assert plugin1.__name__.endswith("pytest_hello")
        plugin2 = pytestpm.get_plugin("pytest_hello")
        assert plugin2 is plugin1

    def test_import_plugin_dotted_name(self, testdir, pytestpm):
        pytest.raises(ImportError, pytestpm.import_plugin, "qweqwex.y")
        pytest.raises(ImportError, pytestpm.import_plugin, "pytest_qweqwex.y")

        testdir.syspathinsert()
        testdir.mkpydir("pkg").join("plug.py").write("x=3")
        pluginname = "pkg.plug"
        pytestpm.import_plugin(pluginname)
        mod = pytestpm.get_plugin("pkg.plug")
        assert mod.x == 3

    def test_consider_conftest_deps(self, testdir, pytestpm):
        mod = testdir.makepyfile("pytest_plugins='xyz'").pyimport()
        with pytest.raises(ImportError):
            pytestpm.consider_conftest(mod)

class TestPytestPluginManagerBootstrapming:
    def test_preparse_args(self, pytestpm):
        pytest.raises(
            ImportError, lambda: pytestpm.consider_preparse(["xyz", "-p", "hello123"])
        )

        # Handles -p without space (#3532).
        with pytest.raises(ImportError) as excinfo:
            pytestpm.consider_preparse(["-phello123"])
        assert '"hello123"' in excinfo.value.args[0]
        pytestpm.consider_preparse(["-pno:hello123"])

        # Handles -p without following arg (when used without argparse).
        pytestpm.consider_preparse(["-p"])

        with pytest.raises(UsageError, match="^plugin main cannot be disabled$"):
            pytestpm.consider_preparse(["-p", "no:main"])

    def test_plugin_prevent_register(self, pytestpm):
        pytestpm.consider_preparse(["xyz", "-p", "no:abc"])
        l1 = pytestpm.get_plugins()
        pytestpm.register(42, name="abc")
        l2 = pytestpm.get_plugins()
        assert len(l2) == len(l1)
        assert 42 not in l2

    def test_plugin_prevent_register_unregistered_alredy_registered(self, pytestpm):
        pytestpm.register(42, name="abc")
        l1 = pytestpm.get_plugins()
        assert 42 in l1
        pytestpm.consider_preparse(["xyz", "-p", "no:abc"])
        l2 = pytestpm.get_plugins()
        assert 42 not in l2

    def test_plugin_prevent_register_stepwise_on_cacheprovider_unregister(
        self, pytestpm
    ):
        """ From PR #4304 : The only way to unregister a module is documented at
        the end of https://docs.pytest.org/en/latest/plugins.html.

        When unregister cacheprovider, then unregister stepwise too
        """
        pytestpm.register(42, name="cacheprovider")
        pytestpm.register(43, name="stepwise")
        l1 = pytestpm.get_plugins()
        assert 42 in l1
        assert 43 in l1
        pytestpm.consider_preparse(["xyz", "-p", "no:cacheprovider"])
        l2 = pytestpm.get_plugins()
        assert 42 not in l2
        assert 43 not in l2

    def test_blocked_plugin_can_be_used(self, pytestpm):
        pytestpm.consider_preparse(["xyz", "-p", "no:abc", "-p", "abc"])

        assert pytestpm.has_plugin("abc")
        assert not pytestpm.is_blocked("abc")
        assert not pytestpm.is_blocked("pytest_abc")


text:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nest
{
	[JsonObject(MemberSerialization.OptIn)]
	public interface IShrinkIndexResponse : IAcknowledgedResponse
	{
		[JsonProperty("shards_acknowledged")]
		bool ShardsAcknowledged { get; }
	}

	public class ShrinkIndexResponse : AcknowledgedResponseBase, IShrinkIndexResponse
	{
		public bool ShardsAcknowledged { get; internal set; }
	}
}


text:
angular.module('orderCloud')
    .controller('CatalogCategoryCtrl', CatalogManagementCategoryController)
;

function CatalogManagementCategoryController($rootScope, $stateParams, $state, toastr, ocCatalog, SelectedCategory) {
    var vm = this;
    vm.category = SelectedCategory;
    $rootScope.$broadcast('CatalogViewManagement:CategoryIDChanged', vm.category.ID);

    vm.editCategory = function() {
        ocCatalog.EditCategory(vm.category, $stateParams.catalogid)
            .then(function(updatedCategory) {
                $rootScope.$broadcast('CatalogManagement:CategoryUpdated', {OriginalID: vm.category.ID, Category: updatedCategory});
                vm.category = updatedCategory;
                toastr.success(updatedCategory.Name + ' was updated.');
            });
    };

    vm.deleteCategory = function() {
        ocCatalog.DeleteCategory(vm.category, $stateParams.catalogid)
            .then(function() {
                $rootScope.$broadcast('CatalogManagement:CategoryDeleted', vm.category);
                $state.go('categories');
                toastr.success(vm.category.Name + ' was deleted.');
            });
    };
}


text:
namespace faint{

constexpr Precision EXPRESSION_FLOAT_PRECISION(2);

template<Optional<coord>(*func)(const ExpressionContext&)>
static coord or_throw(const utf8_string& unit, const ExpressionContext& c){
  return func(c).Visit(
    [](coord factor){
      return factor;
    },
    [&]() -> coord{
      throw ExpressionEvalError(space_sep("Coordinate system not calibrated,",
          unit, "not available."));
    });
}

static const Object* get_object_or_throw(const ExpressionContext& ctx,
  const utf8_string& name)
{
  const Object* obj = ctx.GetObject(name);
  if (obj == nullptr){
    throw ExpressionEvalError(space_sep("No object named",
      quoted(name) + "."));
  }
  return obj;

}

static void throw_if_wrong_arg_count(const utf8_string& command,
  size_t expected,
  const expr_list& args)
{
  size_t size = args.size();
  if (size != expected){
    size_t pos = 0; // Fixme: Use real command position
    throw ExpressionParseError(pos,
      space_sep(command, "expects", str_uint(expected), "arguments"));
  }
}

using MeasureFunc = const std::function<coord(const Object*,
  const ExpressionContext&)>;

template<typename T>
class MeasureExpression : public  TextExpression{
public:
  // Base for measurement expressions. Derived classes must specialize
  // some private virtuals.
  //
  // Templated on the derived type, to allow cloning.
  MeasureExpression(const utf8_string& name,
    const MeasureFunc& func,
    expr_list& args)
  : m_func(func),
    m_name(name)
  {
    throw_if_wrong_arg_count(name,
      2, args);
    m_object = std::move(args[0]);
    m_unit = std::move(args[1]);
  }

  TextExpression* Clone() const override{
    expr_list args;
    args.emplace_back(m_object->Clone());
    args.emplace_back(m_unit->Clone());
    return new T(m_name, m_func, args);
  }

  utf8_string Evaluate(const ExpressionContext& ctx) const override{
    const Object* object = get_object_or_throw(ctx, m_object->Evaluate(ctx));
    utf8_string wantedUnit = m_unit->Evaluate(ctx);
    coord pixels = m_func(object, ctx);

    if (wantedUnit.empty()){
      throw ExpressionEvalError(space_sep("No unit specified"));
    }
    const auto& conversions = length_conversions();
    CheckUnit(wantedUnit, conversions);

    const utf8_string intrinsicUnit(IntrinsicUnit(wantedUnit));

    const faint::coord value = intrinsicUnit == "px" ?
      pixels :
      ctx.GetCalibration().Visit(
        [&](const Calibration& c) -> coord{
          coord calibratedMeasure = pixels / AdjustConversion(c.Scale());

          auto it = conversions.find(intrinsicUnit);
          if (it == end(conversions)){
            throw ExpressionEvalError(space_sep("Unknown unit:",
              wantedUnit + "."));
          }
          else{
            return it->second[c.unit].Visit(
              [&](coord calibratedToWanted){
                return calibratedMeasure * calibratedToWanted;
              },
              [&]() -> coord{
                throw ExpressionEvalError(space_sep("No known conversion",
                    "from", wantedUnit, "to", c.unit));
              });
          }
        },

        [&]() -> coord{
          throw ExpressionEvalError(space_sep("Coordinate system not",
              "calibrated,", wantedUnit,
              "not available."));
        });

    return str(value, EXPRESSION_FLOAT_PRECISION);
  }

  MeasureExpression() = delete;

private:
  // Check that the unit is acceptable for the derived type (T).
  // Should throw ExpressionEvalError otherwise.
  virtual void CheckUnit(const utf8_string&,
    const conversions_map_t&) const = 0;

  // Returns the "intrinsic" unit that makes up unit, e.g. mm for mm2
  virtual utf8_string IntrinsicUnit(const utf8_string& unit) const = 0;

  // Adjust the conversion from pixels to calibrated measure,
  // allows squaring the measure for area measurements.
  virtual coord AdjustConversion(coord conversion) const = 0;

private:
  MeasureFunc m_func;
  const utf8_string& m_name;
  expr_ptr m_object;
  expr_ptr m_unit;
};

class AreaExpression : public MeasureExpression<AreaExpression>{
public:
  using MeasureExpression::MeasureExpression;

private:
  void CheckUnit(const utf8_string& unit,
    const conversions_map_t& c) const override
  {
    if (!ends(unit, with("2"))){
      if (unit != "px" && c.find(unit) == end(c)){
        throw ExpressionEvalError(space_sep("Unknown unit:", unit + "."));
      }
      else{
        throw ExpressionEvalError(space_sep("Length unit", unit,
            "specified for area. Use", no_sep(unit, "2"), "instead."));
      }
    }
  }

  utf8_string IntrinsicUnit(const utf8_string& unit) const override{
    // Strip "2" (for square)., e.g. mm2->mm
    return unit.substr(0, unit.size() - 1);
  }

  coord AdjustConversion(coord conversion) const override{
    // Use conversion^2 for area conversions
    return conversion * conversion;
  }
};

class LengthExpression : public MeasureExpression<LengthExpression>{
public:
  using MeasureExpression::MeasureExpression;
private:
  void CheckUnit(const utf8_string& unit,
    const conversions_map_t& c) const override
  {
    if (ends(unit, with("2"))){
      auto desquared(unit.substr(0, unit.size() - 1));
      if (desquared != "px" && c.find(desquared) == end(c)){
        throw ExpressionEvalError(space_sep("Unknown unit:", unit + "."));
      }
      else{
        throw ExpressionEvalError(space_sep("Area unit", unit,
            "specified for length. Use", desquared, "instead."));
      }
    }
  }

  utf8_string IntrinsicUnit(const utf8_string& unit) const override{
    // Unit used as is for looking up measurement conversions.
    return unit;
  }

  coord AdjustConversion(coord conversion) const override{
    // Used as is for lengths.
    return conversion;
  }
};

static unsigned int from_hex_str(const utf8_string& s){
  if (!is_ascii(s)){
    throw ExpressionEvalError(space_sep(s, "is not a hexadecimal value."));
  }
  std::istringstream ss(s.str());
  ss >> std::hex;
  unsigned int value = 0;
  if (!(ss >> value)){
    throw ExpressionEvalError(space_sep(s, "is not a hexadecimal value."));
  }
  return value;
}

class UnicodeExpression : public TextExpression{
public:
  UnicodeExpression(expr_list& args){
    throw_if_wrong_arg_count("u", // Fixme: Duplication
      1, args);
    m_arg = std::move(args[0]);
  }

  utf8_string Evaluate(const ExpressionContext& ctx) const override{
    utf8_string text = m_arg->Evaluate(ctx);
    unsigned int cp = from_hex_str(text);
    if (surrogate_codepoint(cp)){
      throw ExpressionEvalError(space_sep("Invalid code point:",
          text, "(UTF-16 surrogate pair)."));
    }
    else if (cp > 0x10ffff){
      throw ExpressionEvalError(space_sep("Invalid code point:",
          text, " > 10FFFF"));
    }
    return utf8_string(1, utf8_char(cp));
  }

  TextExpression* Clone() const override{
    expr_list args;
    args.emplace_back(m_arg->Clone());
    return new UnicodeExpression(args);
  }

private:
  expr_ptr m_arg;
};

class CommandExpressions{
  // Factory for commands (e.g. AreaExpression).
public:
  using creation_func = std::function<TextExpression*(expr_list& args)>;
  void Add(const utf8_string& s, const creation_func& f){
    m_creators[s] = f;
  }

  TextExpression* Create(const utf8_string& name, expr_list& args) const{
    auto it = m_creators.find(name);
    if (it == m_creators.end()){
      return nullptr;
    }
    return it->second(args);
  }

  std::vector<utf8_string> GetNames() const{
    std::vector<utf8_string> v;
    for (const auto& item : m_creators){
      v.emplace_back(item.first);
    }
    return v;
  }

private:
  std::map<utf8_string, creation_func> m_creators;
};

static CommandExpressions init_command_expressions(){
  CommandExpressions c;
  c.Add("perimeter",
    [](expr_list& args){
      return new LengthExpression("perimeter",
        [](const Object* obj, const ExpressionContext& ctx){
          if (is_text_object(obj)){
            // \ref(err1): Checking perimeter of self could lead to infinite
            // recursion, as ObjText::GetPath evaluates its
            // expression. Referring to other text objects should be
            // OK but I have no way to test this.
            return 0.0;
          }
          return perimeter(obj, ctx);
        }, args);
    });

  c.Add("width",
    [](expr_list& args){
      return new LengthExpression("width",
        [](const Object* obj, const ExpressionContext&){
          return obj->GetTri().Width();
        }, args);});

  c.Add("height",
    [](expr_list& args){
      return new LengthExpression("height",
        [](const Object* obj, const ExpressionContext&){
          return obj->GetTri().Height();
        }, args);});

  c.Add("area",
    [](expr_list& args){
      return new AreaExpression("area",
        [](const Object* obj, const ExpressionContext&){
          return object_area(obj);
        }, args);});

  c.Add("u",
    [](expr_list& args){
      return new UnicodeExpression(args);
    });
  return c;
}

const CommandExpressions& command_expressions(){
  static CommandExpressions c(init_command_expressions());
  return c;
}

std::vector<utf8_string> command_expr_names(){
  return command_expressions().GetNames();
}

TextExpression* create_command_expr(const utf8_string& name, expr_list& args){
  return command_expressions().Create(name, args);
}

} // namespace


text:
<ModuleInfoEntry>
    <Module Name="jsonbuilder" Type="StaticLibrary" Platform="All">
        <Dependencies>
            <Dependency Name="jsonparser" />
        </Dependencies>
    </Module>
</ModuleInfoEntry>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="personal website of Phoebe Abigail Stoye">
    <meta name="author" content="Phoebe Stoye">

    <title>Phoebe Stoye</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/stylish-portfolio.css" rel="stylesheet">

    <link href="https://fonts.googleapis.com/css?family=Heebo:100,300,100italic,300italic" rel="stylesheet">
    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

                Phoebe Stoye

                about

                photojournal

                crunchspace

                contact

Phoebe Stoye

Student. Entrepreneur. Science-Geek. Artist.

I aspire to find solutions to health inequities using social entrepreneurship.

some of the issues I care about >>

a few of my explorations.
<h10>
</h10>

A.B. Candidate in Neurobiology

Harvard College

Student Researcher at Boston Children's Hospital

researching the effects of adversity on early childhood brain development.

Business Development Intern at Little Sparrows Tech

developing business strategies for the first-ever portable, high-intensity
 newborn jaundice therapy device

Co-founder of Chirp

a social enterprise preventing children from being left in hot cars.

Coxswain

Kirkland House Crew and MIT Rowing Club

Visual Artist

colored pencil, photography, printmaking, ceramics.

Photojournal

Most people have heard about the "hot car baby deaths" plastered on the headlines, those tragic stories of healthy, smiling toddlers dying suddenly and unexpectedly.  I heard about it first when I was about 12 years old; that time, it was two little boys left in a heated car in the middle of winter in my town in western Colorado.  Now I am 21: and that statistic has not decreased, nor even plateaued—it has increased, both in 2016 and 2017.

Why?

                    When I started working on Chirp, we went around and asked parents what they thought. Everyone cared about the issue, felt truly saddened by the deaths.  But there was also always the looming question,

"How could the parents do that to their child?"

                    Here's the answer: parents are superheroes, but they're still human. When a parent is tired, stressed, trying to juggle several events for the afternoon, and suddenly a work emergency comes up, she might drive to work thinking that she already dropped off her little one at daycare, who is actually sleeping in the back. Or maybe a parent who usually doesn't take his toddler to daycare takes the child while is wife is home with a cold, and forgets to make the stop, taking his normal route to the train and parking the car outside.

In fact, these were real parents, and real children.  The first is a CEO of a Midwest hospital; the second, a near-miss, was a dad in the Boston area.  52% of cases are accidental, and there are no correlations with socioeconomic status.

It's easy to think that those tragedies always happen to the "other" - to think, "that would never happen to me."  But, the sad truth is, it can happen to anyone.

I want to make a safer world for my future children, and all future children. I want for parents to focus on their baby's first words, about the six events they have to juggle later in the day, about their work—not on the potential for little mistakes to become a tragedy.

That's why I believe it's important that we start to accept that vehicular heatstroke can happen to anyone.  A first step in that direction is the Hot Cars Act of 2017, a bi-partisan act which requires life-saving technology in every new vehicle.  To me, this is both about instituting a simple, low-cost, preventative measure in cars, and acknowledging it's a real safety issue that needs to be solved.

I'm working to get my local congressmen on board with this act.  A quick call or email to your local congressmen's office, or even telling your friends about the Act, would help to create a world where a child never dies in this preventable way.

in memory of William and Tyler Jensen, who died at ages 2 and 4 in their mother's car. 2009, Grand Junction, CO.

    <secion id="contact" class="contact">

Copyright © Phoebe Stoye 2017

    </secion>


text:
class Materi < ActiveRecord::Base
   belongs_to :semestre
   has_many :asignacion_docent
  has_many :matricula
  has_many :malla_curricular
    has_many :ficha_academica
    has_many :acta_exam
  attr_accessible :alias_mat, :cod_mat, :contenido_mat, :hs_mat, :nombre_mat, :semestre_id
  def completo
    "#{nombre_mat}"
  end
end


text:
package org.jetbrains.plugins.gradle.nativeplatform.tooling.model.impl;

import com.intellij.serialization.PropertyMapping;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.gradle.nativeplatform.tooling.model.MacroDirective;

public class MacroDirectiveImpl implements MacroDirective {
  private String name;
  private String value;

  @PropertyMapping({"name", "value"})
  public MacroDirectiveImpl(String name, String value) {
    this.name = name;
    this.value = value;
  }

  public MacroDirectiveImpl(MacroDirective directive) {
    this(directive.getName(), directive.getValue());
  }

  @Override
  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  @Nullable
  @Override
  public String getValue() {
    return value;
  }

  public void setValue(String value) {
    this.value = value;
  }
}


text:
package com.cognizant.cognizantits.ide.main.shr.mobile.android;

import com.cognizant.cognizantits.ide.main.shr.mobile.MobileUtil;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;

/**
 *
 *
 */
public class AndroidUtil extends MobileUtil {

    private static AndroidUtil androidUtil;

    public static AndroidUtil get() {
        if (androidUtil == null) {
            androidUtil = new AndroidUtil();
        }
        return androidUtil;
    }

    public void rotateScreenshot(File screenShotFile) {
        try {
            BufferedImage img = ImageIO.read(screenShotFile);
            BufferedImage target;
            switch (AndroidTree.get().getRotation()) {
                case "1":
                    target = rotate(img, Math.toRadians(90), 0);
                    target = rotate(target, Math.toRadians(180), 90);
                    break;
                case "2":
                    target = rotate(img, Math.toRadians(180), 90);
                    break;
                case "3":
                    target = rotate(img, Math.toRadians(90), 90);
                    target = rotate(target, Math.toRadians(180), 90);
                    target = rotate(target, Math.toRadians(180), 90);
                    break;
                default:
                    return;
            }
            if (target != null) {
                ImageIO.write(target, "png", screenShotFile);
            }
        } catch (IOException ex) {
            Logger.getLogger(AndroidUtil.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    /**
     * Affine transform only works with perfect squares. The following code is
     * used to take any rectangle image and rotate it correctly. To do this it
     * chooses a center point that is half the greater length and tricks the
     * library to think the image is a perfect square, then it does the rotation
     * and tells the library where to find the correct top left point. The
     * special cases in each orientation happen when the extra image that
     * doesn't exist is either on the left or on top of the image being rotated.
     * In both cases the point is adjusted by the difference in the longer side
     * and the shorter side to get the point at the correct top left corner of
     * the image. NOTE: the x and y axes also rotate with the image so where
     * width > height the adjustments always happen on the y axis and where the
     * height > width the adjustments happen on the x axis.
     *
     */
    private BufferedImage rotate(BufferedImage image, double theta, int thetaInDegrees) {

        AffineTransform xform = new AffineTransform();

        if (image.getWidth() > image.getHeight()) {
            xform.setToTranslation(0.5 * image.getWidth(), 0.5 * image.getWidth());
            xform.rotate(theta);

            int diff = image.getWidth() - image.getHeight();

            switch (thetaInDegrees) {
                case 90:
                    xform.translate(-0.5 * image.getWidth(), -0.5 * image.getWidth() + diff);
                    break;
                case 180:
                    xform.translate(-0.5 * image.getWidth(), -0.5 * image.getWidth() + diff);
                    break;
                default:
                    xform.translate(-0.5 * image.getWidth(), -0.5 * image.getWidth());
                    break;
            }
        } else if (image.getHeight() > image.getWidth()) {
            xform.setToTranslation(0.5 * image.getHeight(), 0.5 * image.getHeight());
            xform.rotate(theta);

            int diff = image.getHeight() - image.getWidth();

            switch (thetaInDegrees) {
                case 180:
                    xform.translate(-0.5 * image.getHeight() + diff, -0.5 * image.getHeight());
                    break;
                case 270:
                    xform.translate(-0.5 * image.getHeight() + diff, -0.5 * image.getHeight());
                    break;
                default:
                    xform.translate(-0.5 * image.getHeight(), -0.5 * image.getHeight());
                    break;
            }
        } else {
            xform.setToTranslation(0.5 * image.getWidth(), 0.5 * image.getHeight());
            xform.rotate(theta);
            xform.translate(-0.5 * image.getHeight(), -0.5 * image.getWidth());
        }

        AffineTransformOp op = new AffineTransformOp(xform, AffineTransformOp.TYPE_BILINEAR);

        return op.filter(image, null);
    }

}


text:
use std::str::FromStr;

use perlin_core::utils::seeking_iterator::{PeekableSeekable};

use language::CanApply;

use query::{Operand, ToOperands};

/// Numberfilter.
/// Takes an string as input and tries to convert it to usize
/// If this is possible it calls the `number_callback` with the resulting usize
/// Otherwise it calls the `string_callback` with the original input
pub struct NumberFilter<TStringCallback, TNumberCallback> {
    string_callback: TStringCallback,
    number_callback: TNumberCallback,
}

impl<TSCB, TNCB> NumberFilter<TSCB, TNCB> {
    pub fn create(number_callback: TNCB, string_callback: TSCB) -> Self {
        NumberFilter {
            string_callback: string_callback,
            number_callback: number_callback,
        }
    }
}

impl<'a, TStringCallback, TNumberCallback> CanApply<&'a str>
    for NumberFilter<TStringCallback, TNumberCallback>
    where TStringCallback: CanApply<&'a str>,
          TNumberCallback: CanApply<u64>
{
    type Output = TStringCallback::Output;
    fn apply(&mut self, input: &'a str) {
        if let Ok(number) = u64::from_str(input) {
            self.number_callback.apply(number);
        } else {
            self.string_callback.apply(input);
        }
    }
}

impl<'a, TStringCallback, TNumberCallback> ToOperands<'a>
    for NumberFilter<TStringCallback, TNumberCallback>
    where TStringCallback: ToOperands<'a>,
          TNumberCallback: ToOperands<'a>
{
    fn to_operands(self) -> Vec<PeekableSeekable<Operand<'a>>> {
        let mut result = self.number_callback.to_operands();
        result.append(&mut self.string_callback.to_operands());
        result
    }
}

pub struct ToUsize<TCallback> {
    callback: TCallback,
}

impl<TCallback> ToUsize<TCallback> {
    pub fn create(callback: TCallback) -> Self {
        ToUsize { callback: callback }
    }
}

impl<'a, TCallback> CanApply<&'a str> for ToUsize<TCallback>
    where TCallback: CanApply<usize>
{
    type Output = TCallback::Output;

    fn apply(&mut self, input: &'a str) {
        if let Ok(number) = usize::from_str(input) {
            self.callback.apply(number);
        }
    }
}


text:
<?php

/**
 * Alert renderer.
 */
class Contactlab_Commons_Block_Adminhtml_Events_Renderer_Alert extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract {

    /**
     * Renders grid column
     *
     * @param Varien_Object $row
     * @return string
     */
    public function render(Varien_Object $row) {
        return $row->getSendAlert()
                ? sprintf("%s",
                        Mage::helper('contactlab_commons')->__("Yes"))
                : sprintf("%s",
                        Mage::helper('contactlab_commons')->__("No"));
    }

}


text:
<?php
namespace Zeeye\Response;

use Zeeye\Response\Response;
use Zeeye\Response\RedirectResponseException;
use Zeeye\Util\Url\UrlGenerator;
/**
 * Class for redirections responses
 *
 * @author     Nicolas Hervé <nherve@gmail.com>
 * @license    http://opensource.org/licenses/mit-license.php
 */
class RedirectResponse extends Response {
    /**
     * Constructor
     *
     * @param mixed $url URL used for the redirection
     */
    protected function __construct($url) {
        parent::__construct();
        // Sets the default HTTP status code
        $this->setStatus(302);
        // Generate the url from the given source
        $location = UrlGenerator::generate($url);

        $this->setHeader('Location', $location);
    }

    /**
     * Return a new instance
     *
     * @param mixed $url URL used for the redirection
     */
    public static function create($url) {
    	return new RedirectResponse($url);
    }

    /**
     * Send the response headers
     */
    public function output() {
    	$this->_sendHeaders();
    }
}


text:
module Hayaml where

import Hayaml.Model.YamlNode
import Hayaml.Parser


text:
package org.apache.hadoop.hbase.replication;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.apache.yetus.audience.InterfaceAudience;
import org.apache.hadoop.hbase.ServerName;

/**
 * This class is responsible for the parsing logic for a znode representing a queue.
 * It will extract the peerId if it's recovered as well as the dead region servers
 * that were part of the queue's history.
 */
@InterfaceAudience.Private
public class ReplicationQueueInfo {
  private static final Log LOG = LogFactory.getLog(ReplicationQueueInfo.class);

  private final String peerId;
  private final String peerClusterZnode;
  private boolean queueRecovered;
  // List of all the dead region servers that had this queue (if recovered)
  private List<String> deadRegionServers = new ArrayList<>();

  /**
   * The passed znode will be either the id of the peer cluster or
   * the handling story of that queue in the form of id-servername-*
   */
  public ReplicationQueueInfo(String znode) {
    this.peerClusterZnode = znode;
    String[] parts = znode.split("-", 2);
    this.queueRecovered = parts.length != 1;
    this.peerId = this.queueRecovered ?
        parts[0] : peerClusterZnode;
    if (parts.length >= 2) {
      // extract dead servers
      extractDeadServersFromZNodeString(parts[1], this.deadRegionServers);
    }
  }

  /**
   * Parse dead server names from znode string servername can contain "-" such as
   * "ip-10-46-221-101.ec2.internal", so we need skip some "-" during parsing for the following
   * cases: 2-ip-10-46-221-101.ec2.internal,52170,1364333181125-<server name>-...
   */
  private static void
      extractDeadServersFromZNodeString(String deadServerListStr, List<String> result) {

    if(deadServerListStr == null || result == null || deadServerListStr.isEmpty()) return;

    // valid server name delimiter "-" has to be after "," in a server name
    int seenCommaCnt = 0;
    int startIndex = 0;
    int len = deadServerListStr.length();

    for (int i = 0; i < len; i++) {
      switch (deadServerListStr.charAt(i)) {
      case ',':
        seenCommaCnt += 1;
        break;
      case '-':
        if(seenCommaCnt>=2) {
          if (i > startIndex) {
            String serverName = deadServerListStr.substring(startIndex, i);
            if(ServerName.isFullServerName(serverName)){
              result.add(serverName);
            } else {
              LOG.error("Found invalid server name:" + serverName);
            }
            startIndex = i + 1;
          }
          seenCommaCnt = 0;
        }
        break;
      default:
        break;
      }
    }

    // add tail
    if(startIndex < len - 1){
      String serverName = deadServerListStr.substring(startIndex, len);
      if(ServerName.isFullServerName(serverName)){
        result.add(serverName);
      } else {
        LOG.error("Found invalid server name at the end:" + serverName);
      }
    }

    LOG.debug("Found dead servers:" + result);
  }

  public List<String> getDeadRegionServers() {
    return Collections.unmodifiableList(this.deadRegionServers);
  }

  public String getPeerId() {
    return this.peerId;
  }

  public String getPeerClusterZnode() {
    return this.peerClusterZnode;
  }

  public boolean isQueueRecovered() {
    return queueRecovered;
  }
}


text:
require 'savon'

module NoaaWeatherClient
  module SoapClientFactory
    WSDL = 'http://graphical.weather.gov/xml/DWMLgen/wsdl/ndfdXML.wsdl'

    def self.build_client(options = {})
      provider = options.fetch(:provider, Savon)
      wsdl = options.fetch(:wsdl, WSDL)
      provider.client(wsdl: wsdl,
                      log: false,
                      open_timeout: 10,
                      read_timeout: 30,
                      ssl_verify_mode: :none)
    end
  end
end


text:
<?php

namespace OrganizationsORM;

use OrganizationsORM\om\BaseAdvisorsPeer;

/**
 * Skeleton subclass for performing query and update operations on the 'advisors' table.
 *
 *
 *
 * You should add additional methods to this class to meet the
 * application requirements.  This class will only be generated as
 * long as it does not already exist in the output directory.
 *
 * @package    propel.generator.organizations
 */
class AdvisorsPeer extends BaseAdvisorsPeer {

} // AdvisorsPeer


text:
<link rel="import" href="../bower_components/polymer/polymer.html">

<dom-module id="footer-page">
	<template>

Handcrafted with love by Henry Lim

This site is built with Polymer

This site is licensed under the MIT License

	</template>

</dom-module>


text:
from setuptools import setup, find_packages
import sys, os

version = '0.3'

setup(name='py2json',
      version=version,
      description="Python to JSON-schema SMD translator",
      long_description="""\
== ABOUT ==""",
      classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
      keywords='json json-schema smd translator',
      author='Igor Guerrero',
      author_email='igfgt1@gmail.com',
      url='http://app.arat.us/',
      license='Apache License Version 2.0',
      packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
      include_package_data=True,
      zip_safe=False,
      install_requires=[
          # -*- Extra requirements: -*-
      ],
      entry_points="""
      # -*- Entry points: -*-
      """,
      )


text:
package org.apache.hadoop.yarn.server.resourcemanager.scheduler;

import static org.apache.hadoop.metrics2.lib.Interns.info;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.metrics2.MetricsCollector;
import org.apache.hadoop.metrics2.MetricsInfo;
import org.apache.hadoop.metrics2.MetricsSource;
import org.apache.hadoop.metrics2.MetricsSystem;
import org.apache.hadoop.metrics2.annotation.Metric;
import org.apache.hadoop.metrics2.annotation.Metrics;
import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
import org.apache.hadoop.metrics2.lib.MetricsRegistry;
import org.apache.hadoop.metrics2.lib.MutableCounterInt;
import org.apache.hadoop.metrics2.lib.MutableCounterLong;
import org.apache.hadoop.metrics2.lib.MutableGaugeInt;
import org.apache.hadoop.metrics2.lib.MutableRate;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState;
import org.apache.hadoop.yarn.server.utils.BuilderUtils;
import org.apache.hadoop.yarn.util.resource.Resources;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Splitter;

@InterfaceAudience.Private
@Metrics(context="yarn")
public class QueueMetrics implements MetricsSource {
  @Metric("# of apps submitted") MutableCounterInt appsSubmitted;
  @Metric("# of running apps") MutableGaugeInt appsRunning;
  @Metric("# of pending apps") MutableGaugeInt appsPending;
  @Metric("# of apps completed") MutableCounterInt appsCompleted;
  @Metric("# of apps killed") MutableCounterInt appsKilled;
  @Metric("# of apps failed") MutableCounterInt appsFailed;

  @Metric("Allocated memory in MB") MutableGaugeInt allocatedMB;
  @Metric("Allocated CPU in virtual cores") MutableGaugeInt allocatedVCores;
  @Metric("# of allocated containers") MutableGaugeInt allocatedContainers;
  @Metric("Aggregate # of allocated containers") MutableCounterLong aggregateContainersAllocated;
  @Metric("Aggregate # of released containers") MutableCounterLong aggregateContainersReleased;
  @Metric("Available memory in MB") MutableGaugeInt availableMB;
  @Metric("Available CPU in virtual cores") MutableGaugeInt availableVCores;
  @Metric("Pending memory allocation in MB") MutableGaugeInt pendingMB;
  @Metric("Pending CPU allocation in virtual cores") MutableGaugeInt pendingVCores;
  @Metric("# of pending containers") MutableGaugeInt pendingContainers;
  @Metric("# of reserved memory in MB") MutableGaugeInt reservedMB;
  @Metric("Reserved CPU in virtual cores") MutableGaugeInt reservedVCores;
  @Metric("# of reserved containers") MutableGaugeInt reservedContainers;
  @Metric("# of active users") MutableGaugeInt activeUsers;
  @Metric("# of active applications") MutableGaugeInt activeApplications;
  @Metric("App Attempt First Container Allocation Delay") MutableRate appAttemptFirstContainerAllocationDelay;
  private final MutableGaugeInt[] runningTime;
  private TimeBucketMetrics<ApplicationId> runBuckets;

  static final Logger LOG = LoggerFactory.getLogger(QueueMetrics.class);
  static final MetricsInfo RECORD_INFO = info("QueueMetrics",
      "Metrics for the resource scheduler");
  protected static final MetricsInfo QUEUE_INFO = info("Queue", "Metrics by queue");
  static final MetricsInfo USER_INFO = info("User", "Metrics by user");
  static final Splitter Q_SPLITTER =
      Splitter.on('.').omitEmptyStrings().trimResults();

  final MetricsRegistry registry;
  final String queueName;
  final QueueMetrics parent;
  final MetricsSystem metricsSystem;
  private final Map<String, QueueMetrics> users;
  private final Configuration conf;

  protected QueueMetrics(MetricsSystem ms, String queueName, Queue parent,
	       boolean enableUserMetrics, Configuration conf) {
    registry = new MetricsRegistry(RECORD_INFO);
    this.queueName = queueName;
    this.parent = parent != null ? parent.getMetrics() : null;
    this.users = enableUserMetrics ? new HashMap<String, QueueMetrics>()
                                   : null;
    metricsSystem = ms;
    this.conf = conf;
    runningTime = buildBuckets(conf);
  }

  protected QueueMetrics tag(MetricsInfo info, String value) {
    registry.tag(info, value);
    return this;
  }

  protected static StringBuilder sourceName(String queueName) {
    StringBuilder sb = new StringBuilder(RECORD_INFO.name());
    int i = 0;
    for (String node : Q_SPLITTER.split(queueName)) {
      sb.append(",q").append(i++).append('=').append(node);
    }
    return sb;
  }

  public synchronized
  static QueueMetrics forQueue(String queueName, Queue parent,
                               boolean enableUserMetrics,
			       Configuration conf) {
    return forQueue(DefaultMetricsSystem.instance(), queueName, parent,
                    enableUserMetrics, conf);
  }

  /**
   * Helper method to clear cache.
   */
  @Private
  public synchronized static void clearQueueMetrics() {
    queueMetrics.clear();
  }

  /**
   * Simple metrics cache to help prevent re-registrations.
   */
  protected final static Map<String, QueueMetrics> queueMetrics =
      new HashMap<String, QueueMetrics>();

  public synchronized
  static QueueMetrics forQueue(MetricsSystem ms, String queueName,
                                      Queue parent, boolean enableUserMetrics,
				      Configuration conf) {
    QueueMetrics metrics = queueMetrics.get(queueName);
    if (metrics == null) {
      metrics =
          new QueueMetrics(ms, queueName, parent, enableUserMetrics, conf).
          tag(QUEUE_INFO, queueName);

      // Register with the MetricsSystems
      if (ms != null) {
        metrics =
            ms.register(
                sourceName(queueName).toString(),
                "Metrics for queue: " + queueName, metrics);
      }
      queueMetrics.put(queueName, metrics);
    }

    return metrics;
  }

  public synchronized QueueMetrics getUserMetrics(String userName) {
    if (users == null) {
      return null;
    }
    QueueMetrics metrics = users.get(userName);
    if (metrics == null) {
      metrics = new QueueMetrics(metricsSystem, queueName, null, false, conf);
      users.put(userName, metrics);
      metricsSystem.register(
          sourceName(queueName).append(",user=").append(userName).toString(),
          "Metrics for user '"+ userName +"' in queue '"+ queueName +"'",
          metrics.tag(QUEUE_INFO, queueName).tag(USER_INFO, userName));
    }
    return metrics;
  }

  private ArrayList<Integer> parseInts(String value) {
    ArrayList<Integer> result = new ArrayList<Integer>();
    for(String s: value.split(",")) {
      result.add(Integer.parseInt(s.trim()));
    }
    return result;
  }

  private MutableGaugeInt[] buildBuckets(Configuration conf) {
    ArrayList<Integer> buckets =
      parseInts(conf.get(YarnConfiguration.RM_METRICS_RUNTIME_BUCKETS,
		        YarnConfiguration.DEFAULT_RM_METRICS_RUNTIME_BUCKETS));
    MutableGaugeInt[] result = new MutableGaugeInt[buckets.size() + 1];
    result[0] = registry.newGauge("running_0", "", 0);
    long[] cuts = new long[buckets.size()];
    for(int i=0; i < buckets.size(); ++i) {
      result[i+1] = registry.newGauge("running_" + buckets.get(i), "", 0);
      cuts[i] = buckets.get(i) * 1000L * 60; // covert from min to ms
    }
    this.runBuckets = new TimeBucketMetrics<ApplicationId>(cuts);
    return result;
  }

  private void updateRunningTime() {
    int[] counts = runBuckets.getBucketCounts(System.currentTimeMillis());
    for(int i=0; i < counts.length; ++i) {
      runningTime[i].set(counts[i]);
    }
  }

  public void getMetrics(MetricsCollector collector, boolean all) {
    updateRunningTime();
    registry.snapshot(collector.addRecord(registry.info()), all);
  }

  public void submitApp(String user) {
    appsSubmitted.incr();
    QueueMetrics userMetrics = getUserMetrics(user);
    if (userMetrics != null) {
      userMetrics.submitApp(user);
    }
    if (parent != null) {
      parent.submitApp(user);
    }
  }

  public void submitAppAttempt(String user) {
    appsPending.incr();
    QueueMetrics userMetrics = getUserMetrics(user);
    if (userMetrics != null) {
      userMetrics.submitAppAttempt(user);
    }
    if (parent != null) {
      parent.submitAppAttempt(user);
    }
  }

  public void runAppAttempt(ApplicationId appId, String user) {
    runBuckets.add(appId, System.currentTimeMillis());
    appsRunning.incr();
    appsPending.decr();
    QueueMetrics userMetrics = getUserMetrics(user);
    if (userMetrics != null) {
      userMetrics.runAppAttempt(appId, user);
    }
    if (parent != null) {
      parent.runAppAttempt(appId, user);
    }
  }

  public void finishAppAttempt(
      ApplicationId appId, boolean isPending, String user) {
    runBuckets.remove(appId);
    if (isPending) {
      appsPending.decr();
    } else {
      appsRunning.decr();
    }
    QueueMetrics userMetrics = getUserMetrics(user);
    if (userMetrics != null) {
      userMetrics.finishAppAttempt(appId, isPending, user);
    }
    if (parent != null) {
      parent.finishAppAttempt(appId, isPending, user);
    }
  }

  public void finishApp(String user, RMAppState rmAppFinalState) {
    switch (rmAppFinalState) {
      case KILLED: appsKilled.incr(); break;
      case FAILED: appsFailed.incr(); break;
      default: appsCompleted.incr();  break;
    }
    QueueMetrics userMetrics = getUserMetrics(user);
    if (userMetrics != null) {
      userMetrics.finishApp(user, rmAppFinalState);
    }
    if (parent != null) {
      parent.finishApp(user, rmAppFinalState);
    }
  }

  public void moveAppFrom(AppSchedulingInfo app) {
    if (app.isPending()) {
      appsPending.decr();
    } else {
      appsRunning.decr();
    }
    QueueMetrics userMetrics = getUserMetrics(app.getUser());
    if (userMetrics != null) {
      userMetrics.moveAppFrom(app);
    }
    if (parent != null) {
      parent.moveAppFrom(app);
    }
  }

  public void moveAppTo(AppSchedulingInfo app) {
    if (app.isPending()) {
      appsPending.incr();
    } else {
      appsRunning.incr();
    }
    QueueMetrics userMetrics = getUserMetrics(app.getUser());
    if (userMetrics != null) {
      userMetrics.moveAppTo(app);
    }
    if (parent != null) {
      parent.moveAppTo(app);
    }
  }

  /**
   * Set available resources. To be called by scheduler periodically as
   * resources become available.
   * @param limit resource limit
   */
  public void setAvailableResourcesToQueue(Resource limit) {
    availableMB.set(limit.getMemory());
    availableVCores.set(limit.getVirtualCores());
  }

  /**
   * Set available resources. To be called by scheduler periodically as
   * resources become available.
   * @param user
   * @param limit resource limit
   */
  public void setAvailableResourcesToUser(String user, Resource limit) {
    QueueMetrics userMetrics = getUserMetrics(user);
    if (userMetrics != null) {
      userMetrics.setAvailableResourcesToQueue(limit);
    }
  }

  /**
   * Increment pending resource metrics
   * @param user
   * @param containers
   * @param res the TOTAL delta of resources note this is different from
   *            the other APIs which use per container resource
   */
  public void incrPendingResources(String user, int containers, Resource res) {
    _incrPendingResources(containers, res);
    QueueMetrics userMetrics = getUserMetrics(user);
    if (userMetrics != null) {
      userMetrics.incrPendingResources(user, containers, res);
    }
    if (parent != null) {
      parent.incrPendingResources(user, containers, res);
    }
  }

  private void _incrPendingResources(int containers, Resource res) {
    pendingContainers.incr(containers);
    pendingMB.incr(res.getMemory() * containers);
    pendingVCores.incr(res.getVirtualCores() * containers);
  }

  public void decrPendingResources(String user, int containers, Resource res) {
    _decrPendingResources(containers, res);
    QueueMetrics userMetrics = getUserMetrics(user);
    if (userMetrics != null) {
      userMetrics.decrPendingResources(user, containers, res);
    }
    if (parent != null) {
      parent.decrPendingResources(user, containers, res);
    }
  }

  private void _decrPendingResources(int containers, Resource res) {
    pendingContainers.decr(containers);
    pendingMB.decr(res.getMemory() * containers);
    pendingVCores.decr(res.getVirtualCores() * containers);
  }

  public void allocateResources(String user, int containers, Resource res,
      boolean decrPending) {
    allocatedContainers.incr(containers);
    aggregateContainersAllocated.incr(containers);
    allocatedMB.incr(res.getMemory() * containers);
    allocatedVCores.incr(res.getVirtualCores() * containers);
    if (decrPending) {
      _decrPendingResources(containers, res);
    }
    QueueMetrics userMetrics = getUserMetrics(user);
    if (userMetrics != null) {
      userMetrics.allocateResources(user, containers, res, decrPending);
    }
    if (parent != null) {
      parent.allocateResources(user, containers, res, decrPending);
    }
  }

  public void releaseResources(String user, int containers, Resource res) {
    allocatedContainers.decr(containers);
    aggregateContainersReleased.incr(containers);
    allocatedMB.decr(res.getMemory() * containers);
    allocatedVCores.decr(res.getVirtualCores() * containers);
    QueueMetrics userMetrics = getUserMetrics(user);
    if (userMetrics != null) {
      userMetrics.releaseResources(user, containers, res);
    }
    if (parent != null) {
      parent.releaseResources(user, containers, res);
    }
  }

  public void reserveResource(String user, Resource res) {
    reservedContainers.incr();
    reservedMB.incr(res.getMemory());
    reservedVCores.incr(res.getVirtualCores());
    QueueMetrics userMetrics = getUserMetrics(user);
    if (userMetrics != null) {
      userMetrics.reserveResource(user, res);
    }
    if (parent != null) {
      parent.reserveResource(user, res);
    }
  }

  public void unreserveResource(String user, Resource res) {
    reservedContainers.decr();
    reservedMB.decr(res.getMemory());
    reservedVCores.decr(res.getVirtualCores());
    QueueMetrics userMetrics = getUserMetrics(user);
    if (userMetrics != null) {
      userMetrics.unreserveResource(user, res);
    }
    if (parent != null) {
      parent.unreserveResource(user, res);
    }
  }

  public void incrActiveUsers() {
    activeUsers.incr();
  }

  public void decrActiveUsers() {
    activeUsers.decr();
  }

  public void activateApp(String user) {
    activeApplications.incr();
    QueueMetrics userMetrics = getUserMetrics(user);
    if (userMetrics != null) {
      userMetrics.activateApp(user);
    }
    if (parent != null) {
      parent.activateApp(user);
    }
  }

  public void deactivateApp(String user) {
    activeApplications.decr();
    QueueMetrics userMetrics = getUserMetrics(user);
    if (userMetrics != null) {
      userMetrics.deactivateApp(user);
    }
    if (parent != null) {
      parent.deactivateApp(user);
    }
  }

  public void addAppAttemptFirstContainerAllocationDelay(long latency) {
    appAttemptFirstContainerAllocationDelay.add(latency);
  }

  public int getAppsSubmitted() {
    return appsSubmitted.value();
  }

  public int getAppsRunning() {
    return appsRunning.value();
  }

  public int getAppsPending() {
    return appsPending.value();
  }

  public int getAppsCompleted() {
    return appsCompleted.value();
  }

  public int getAppsKilled() {
    return appsKilled.value();
  }

  public int getAppsFailed() {
    return appsFailed.value();
  }

  public Resource getAllocatedResources() {
    return BuilderUtils.newResource(allocatedMB.value(), allocatedVCores.value());
  }

  public int getAllocatedMB() {
    return allocatedMB.value();
  }

  public int getAllocatedVirtualCores() {
    return allocatedVCores.value();
  }

  public int getAllocatedContainers() {
    return allocatedContainers.value();
  }

  public int getAvailableMB() {
    return availableMB.value();
  }

  public int getAvailableVirtualCores() {
    return availableVCores.value();
  }

  public int getPendingMB() {
    return pendingMB.value();
  }

  public int getPendingVirtualCores() {
    return pendingVCores.value();
  }

  public int getPendingContainers() {
    return pendingContainers.value();
  }

  public int getReservedMB() {
    return reservedMB.value();
  }

  public int getReservedVirtualCores() {
    return reservedVCores.value();
  }

  public int getReservedContainers() {
    return reservedContainers.value();
  }

  public int getActiveUsers() {
    return activeUsers.value();
  }

  public int getActiveApps() {
    return activeApplications.value();
  }

  public MetricsSystem getMetricsSystem() {
    return metricsSystem;
  }

  public long getAggregateAllocatedContainers() {
    return aggregateContainersAllocated.value();
  }

  public long getAggegatedReleasedContainers() {
    return aggregateContainersReleased.value();
  }
}


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="apple-touch-icon" href="apple-touch-icon.png">

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">
        <link rel="stylesheet" href="css/d2.css">
        <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,300' rel='stylesheet' type='text/css'>

                200 NTD

Payment Detail

                    <form>

                            Cardholder's Name
                            <input type="text" id="name" name="name" placeholder="Your name">

                            Card Number
                            <input type="text" id="number-1" name="number_1" placeholder="1234">

                            <input type="text" id="number-2" name="number_2" placeholder="5678">

                            <input type="text" id="number-3" name="number_3" placeholder="9012">

                            <input type="text" id="number-4" name="number_4" placeholder="3456">

                            Expiry Date
                            <input type="text" id="expiry-date" name="expiry_date" placeholder="MM / YY">

                            CVV
                            <input type="text" id="cvv" name="cvv" placeholder="000">

                            <input type="checkbox" id="save-as-default" name="save_as_default">

                            Save as default

                        <input class="hide-text" id="btn-submit" type="submit" value="Buy">
                    </form>

Congradualation!

                        Your order has has been

                        successfully processed.


text:
package org.apache.sis.referencing.cs;

import java.util.Map;
import javax.measure.Unit;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlRootElement;
import org.opengis.referencing.cs.LinearCS;
import org.opengis.referencing.cs.AxisDirection;
import org.opengis.referencing.cs.CoordinateSystemAxis;
import org.apache.sis.internal.metadata.AxisDirections;
import org.apache.sis.measure.Units;

/**
 * A 1-dimensional coordinate system for points that lie on a single axis (not necessarily a straight line).
 * Ordinate values are distances from the axis origin to the point along the axis.
 * A typical example is an axis for representing the points along a road.
 *
 *

 *
Permitted associations

 *

 *   Used with CRS
 *   Permitted axis names
 *

 *   {@linkplain org.apache.sis.referencing.crs.DefaultEngineeringCRS Engineering}
 *   unspecified
 *

 *
 *
Immutability and thread safety

 * This class is immutable and thus thread-safe if the property values (not necessarily the map itself)
 * and the {@link CoordinateSystemAxis} instances given to the constructor are also immutable. Unless otherwise
 * noted in the javadoc, this condition holds if all components were created using only SIS factories and static
 * constants.
 *
 * @author  Martin Desruisseaux (IRD, Geomatys)
 * @version 0.4
 * @since   0.4
 * @module
 */
@XmlType(name = "LinearCSType")
@XmlRootElement(name = "LinearCS")
public class DefaultLinearCS extends AbstractCS implements LinearCS {
    /**
     * Serial number for inter-operability with different versions.
     */
    private static final long serialVersionUID = -6890723478287625763L;

    /**
     * Creates a new coordinate system from an arbitrary number of axes. This constructor is for
     * implementations of the {@link #createForAxes(Map, CoordinateSystemAxis[])} method only,
     * because it does not verify the number of axes.
     */
    private DefaultLinearCS(final Map<String,?> properties, final CoordinateSystemAxis[] axes) {
        super(properties, axes);
    }

    /**
     * Constructs a coordinate system from a set of properties.
     * The properties map is given unchanged to the
     * {@linkplain AbstractCS#AbstractCS(Map,CoordinateSystemAxis[]) super-class constructor}.
     * The following table is a reminder of main (not all) properties:
     *
     *

     *
Recognized properties (non exhaustive list)

     *

     *     Property name
     *     Value type
     *     Returned by
     *

     *

     *     {@value org.opengis.referencing.IdentifiedObject#NAME_KEY}
     *     {@link org.opengis.metadata.Identifier} or {@link String}
     *     {@link #getName()}
     *

     *

     *     {@value org.opengis.referencing.IdentifiedObject#ALIAS_KEY}
     *     {@link org.opengis.util.GenericName} or {@link CharSequence} (optionally as array)
     *     {@link #getAlias()}
     *

     *

     *     {@value org.opengis.referencing.IdentifiedObject#IDENTIFIERS_KEY}
     *     {@link org.opengis.metadata.Identifier} (optionally as array)
     *     {@link #getIdentifiers()}
     *

     *

     *     {@value org.opengis.referencing.IdentifiedObject#REMARKS_KEY}
     *     {@link org.opengis.util.InternationalString} or {@link String}
     *     {@link #getRemarks()}
     *

     *

     *
     * @param  properties  the properties to be given to the identified object.
     * @param  axis        the axis.
     *
     * @see org.apache.sis.referencing.factory.GeodeticObjectFactory#createLinearCS(Map, CoordinateSystemAxis)
     */
    public DefaultLinearCS(final Map<String,?> properties, final CoordinateSystemAxis axis) {
        super(properties, axis);
    }

    /**
     * Creates a new coordinate system with the same values than the specified one.
     * This copy constructor provides a way to convert an arbitrary implementation into a SIS one
     * or a user-defined one (as a subclass), usually in order to leverage some implementation-specific API.
     *
     *
This constructor performs a shallow copy, i.e. the properties are not cloned.

     *
     * @param  cs  the coordinate system to copy.
     *
     * @see #castOrCopy(LinearCS)
     */
    protected DefaultLinearCS(final LinearCS cs) {
        super(cs);
    }

    /**
     * Returns a SIS coordinate system implementation with the same values than the given arbitrary implementation.
     * If the given object is {@code null}, then this method returns {@code null}.
     * Otherwise if the given object is already a SIS implementation, then the given object is returned unchanged.
     * Otherwise a new SIS implementation is created and initialized to the attribute values of the given object.
     *
     * @param  object  the object to get as a SIS implementation, or {@code null} if none.
     * @return a SIS implementation containing the values of the given object (may be the
     *         given object itself), or {@code null} if the argument was null.
     */
    public static DefaultLinearCS castOrCopy(final LinearCS object) {
        return (object == null) || (object instanceof DefaultLinearCS)
                ? (DefaultLinearCS) object : new DefaultLinearCS(object);
    }

    /**
     * Returns {@code VALID} if the given argument values are allowed for this coordinate system,
     * or an {@code INVALID_*} error code otherwise. This method is invoked at construction time.
     *
     *
The current implementation rejects all directions that are known to be non-spatial.
     * We conservatively accept custom axis directions because some of them are created from
     * strings like "South along 90°E".

     */
    @Override
    final int validateAxis(final AxisDirection direction, final Unit<?> unit) {
        if (!AxisDirections.isSpatialOrUserDefined(direction, false)) {
            return INVALID_DIRECTION;
        }
        if (!Units.isLinear(unit) && !Units.UNITY.equals(unit)) {
            return INVALID_UNIT;
        }
        return VALID;
    }

    /**
     * Returns the GeoAPI interface implemented by this class.
     * The SIS implementation returns {@code LinearCS.class}.
     *
     *
Note for implementors:
     * Subclasses usually do not need to override this method since GeoAPI does not define {@code LinearCS}
     * sub-interface. Overriding possibility is left mostly for implementors who wish to extend GeoAPI with
     * their own set of interfaces.

     *
     * @return {@code LinearCS.class} or a user-defined sub-interface.
     */
    @Override
    public Class<? extends LinearCS> getInterface() {
        return LinearCS.class;
    }

    /**
     * {@inheritDoc}
     *
     * @return {@inheritDoc}
     */
    @Override
    public DefaultLinearCS forConvention(final AxesConvention convention) {
        return (DefaultLinearCS) super.forConvention(convention);
    }

    /**
     * Returns a coordinate system with different axes.
     */
    @Override
    final AbstractCS createForAxes(final Map<String,?> properties, final CoordinateSystemAxis[] axes) {
        switch (axes.length) {
            case 1: return new DefaultLinearCS(properties, axes);
            default: throw unexpectedDimension(properties, axes, 1);
        }
    }

    //////////////////////////////////////////////////////////////////////////////////////////////////
    ////////                                                                                ////////
    ////////                               XML support with JAXB                              ////////
    ////////                                                                                ////////
    ////////        The following methods are invoked by JAXB using reflection (even if       ////////
    ////////        they are private) or are helpers for other methods invoked by JAXB.       ////////
    ////////        Those methods can be safely removed if Geographic Markup Language         ////////
    ////////        (GML) support is not needed.                                              ////////
    ////////                                                                                ////////
    //////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Constructs a new coordinate system in which every attributes are set to a null or empty value.
     * This is not a valid object. This constructor is strictly reserved to JAXB,
     * which will assign values to the fields using reflexion.
     */
    private DefaultLinearCS() {
    }
}


text:
package com.jerry.crm.coursetype.domain;

import java.util.HashSet;
import java.util.Set;

import com.jerry.crm.classes.domain.CrmClasses;

public class CrmCourseType {
	private String courseTypeId;
	// ·ÑÓÃ
	private Double courseCost;
	// ×Üѧʱ
	private Integer total;
	// ¿Î³ÌÀà±ðÃû³Æ
	private String courseName;
	// ÃèÊö
	private String remark;
	// Ò»¶Ô¶à£ºÒ»¸ö¿Î³ÌÀà±ð ¿ÉÒÔ ÓÐ ¡¾¶à¸ö°à¼¶¡¿
	private Set<CrmClasses> classesSet = new HashSet<CrmClasses>();

	// ²éѯÌõ¼þ -- Ò»°ã²éѯÌõ¼þ¶¼ÊÇ×Ö·û´®
	// 1 ×Üѧʱ
	private String totalStart;
	private String totalEnd;
	// 2¿Î³Ì·ÑÓÃ
	private String courseCostStart;
	private String courseCostEnd;

	public String getTotalStart() {
		return totalStart;
	}

	public void setTotalStart(String totalStart) {
		this.totalStart = totalStart;
	}

	public String getTotalEnd() {
		return totalEnd;
	}

	public void setTotalEnd(String totalEnd) {
		this.totalEnd = totalEnd;
	}

	public String getCourseCostStart() {
		return courseCostStart;
	}

	public void setCourseCostStart(String courseCostStart) {
		this.courseCostStart = courseCostStart;
	}

	public String getCourseCostEnd() {
		return courseCostEnd;
	}

	public void setCourseCostEnd(String courseCostEnd) {
		this.courseCostEnd = courseCostEnd;
	}

	public String getCourseTypeId() {
		return courseTypeId;
	}

	public void setCourseTypeId(String courseTypeId) {
		this.courseTypeId = courseTypeId;
	}

	public Double getCourseCost() {
		return courseCost;
	}

	public void setCourseCost(Double courseCost) {
		this.courseCost = courseCost;
	}

	public Integer getTotal() {
		return total;
	}

	public void setTotal(Integer total) {
		this.total = total;
	}

	public String getCourseName() {
		return courseName;
	}

	public void setCourseName(String courseName) {
		this.courseName = courseName;
	}

	public String getRemark() {
		return remark;
	}

	public void setRemark(String remark) {
		this.remark = remark;
	}

	public Set<CrmClasses> getClassesSet() {
		return classesSet;
	}

	public void setClassesSet(Set<CrmClasses> classesSet) {
		this.classesSet = classesSet;
	}
}


text:
namespace ControlFlowConditionalStatementsLoops.Cooking.Vegitables
{
    public class Potato : Vegetable
    {
        public Potato()
            : base()
        {
        }
    }
}