text:
Msb4 Maven skin utilises content delivery networks (CDN) for a number of CSS and JavaScript
resources. These include Bootstrap files, themes, the jQuery library, etc. The reuse of
popular resources via CDN provides better performance. However, such resources may not be
accessible when the site is used in an offline/intranet setting.

To support such deployments of Msb4 skin, the configuration allows using local resources.
Furthermore, custom resources can also be easily added to the generated website.
These include newer versions of the used libraries as well as arbitrary scripts.

## Local Bootstrap & jQuery

To force the generated site use only local CSS/JavaScript resources, use the `<localResources>`
flag:

```xml
<localResources>true|false</localResources>
```

-   **true** - Locally provided Bootstrap and jQuery files will be used in the generated site,
    not the CDN versions. This forces [`site` Bootstrap theme][bootstrap-theme], which
    uses local Bootstrap files. Furthermore, other non-local resources such as _highlight.js_
    are disabled and their [local versions need to be added manually][local-css].
    See below for the list of files that need to be available locally.

-   **false (default)** - CDN delivered resources are used, where available.

Note that when using `<localResources>`, you need to provide the necessary local versions of
Bootstrap and jQuery files. Msb4 skin does not package the default files at the moment, mainly
because overriding packaged files is not possible at the moment (see [issue MSITE-702][msite-702]).
Therefore it is easier to get appropriate Bootstrap files directly from the
[customiser][bootstrap-cust] or [Bootswatch][bootswatch2] and use them with the Msb4 skin.
Furthermore, such approach allows you to customise the Bootstrap and jQuery versions used.
Use at your own risk, however, as major version changes are likely to break the website!

When using `<localResources>`, the following files need to be available in the corresponding
directories within your project's `src/site/resources` folder:

-   **`css/bootstrap.min.css`** - Msb4 skin currently uses Bootstrap 4.0.0
-   **`js/bootstrap.min.js`** - Bootstrap 4.0.0
-   **`js/jquery.min.js`** - jQuery 1.11.3
-   **`js/html5.js`** - HTML5 support for IE6-8, get it from [here][html5shiv].

For multi-module site, remember to enable [resource reuse flag][resource-reuse], otherwise
these files will have to be repeated for each sub-module.

[bootstrap-theme]: themes/
[local-css]: #Additional_CSS_files
[msite-702]: https://jira.codehaus.org/browse/MSITE-702
[bootstrap-cust]: http://getbootstrap.com/customize/
[bootswatch2]: http://bootswatch.com/2/
[html5shiv]: http://html5shim.googlecode.com/svn/trunk/html5.js

## Additional CSS files

Additional CSS files (or other resources) can be added to the page head using [`<body><head>`
configuration][body-head-config] in the `site.xml` site descriptor.
This configuration is available to all Maven site skins and is part of the standard
site descriptor configuration.

The `<head>` element allows arbitrary XHTML, which will be injected in the generated page.
Also, it can be used for custom (local or remote) versions of hard-coded Msb4 skin resources.
For example, to use a custom version of [highlight.js syntax highlighting][highlight-js-config],
you can disable the default configuration (`<highlightJs>false</highlightJs>`) and
add the relevant CSS and JavaScript manually:

```xml
<project>
  ...
  <body>
    ...
    <head>
      <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.0.0/styles/default.min.css">
      <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.0.0/highlight.min.js"></script>
    </head>
    ...
  </body>
  ...
</project>
```

Note: the `<head>` element is within `<body>`, not `<custom>` element of `site.xml` site
descriptor.

Furthermore, the injected XHTML allows using Velocity variables. Therefore you can [reuse
a local version of the library][resource-reuse] by indicating its path with a `$resourcePath`
variable, e.g.:

```xml
<head>
  <link rel="stylesheet" href="$resourcePath/css/default.min.css">
</head>
```

[body-head-config]: http://maven.apache.org/plugins/maven-site-plugin/examples/sitedescriptor.html#Inject_xhtml_into_head
[highlight-js-config]: misc.html#Code_highlight
[resource-reuse]: multi-module.html#Reuse_resources

## Additional JavaScript files

JavaScript files can be added to the page head together with CSS files. However, for performance
reasons, it can be better to reference JavaScript files at the end of the document.
To place custom XHTML at the end of the page (before the `</body>` tag), use the `<endContent>`
element, which also supports Velocity variables, e.g.:

```xml
<custom>
  <msb4Skin>
    ...
    <endContent>
      <script src="$resourcePath/js/highlight.min.js"></script>
    </endContent>
    ...
  </msb4Skin>
</custom>
```

Note: the `<endContent>` element is specific to Msb4 skin and needs to be placed within the
`<custom><msb4Skin>` element.


text:
'use strict';
var nodeunit = require('nodeunit')
var r = require('nodeunit/lib/reporters/browser.js')
window.nodeunit = nodeunit
var files = require('./tests/**/*-test.js',  {mode: 'hash'})
console.log('Test files:', files)
nodeunit.reporters.browser = r
nodeunit.reporters.browser.run(files)

redpajama_set_name: RedPajamaGithub


text:
package cmd

import (
	"testing"

	"github.com/openshift/origin/tools/depcheck/pkg/graph"
)

func newGraphOptions() *graph.GraphOptions {
	opts := &graph.GraphOptions{
		Packages: &graph.PackageList{
			Packages: []graph.Package{
				{
					ImportPath: "foo.com/bar/baz",
					Imports: []string{
						"foo.com/bar/baz/one",
						"foo.com/bar/baz/two",
					},
				},
				{
					ImportPath: "foo.com/bar/baz/one",
					Imports: []string{
						"foo.com/bar/baz/vendor/vendor.com/one",
						"foo.com/bar/baz/vendor/vendor.com/mine",
					},
				},
				{
					ImportPath: "foo.com/bar/baz/two",
					Imports: []string{
						"foo.com/bar/baz/vendor/vendor.com/ours",
					},
				},
				{
					ImportPath: "foo.com/bar/baz/vendor/vendor.com/one",
					Imports: []string{
						"foo.com/bar/baz/vendor/vendor.com/two",
						"foo.com/bar/baz/vendor/vendor.com/three",
					},
				},
				{
					ImportPath: "foo.com/bar/baz/vendor/vendor.com/two",
					Imports: []string{
						"fmt",
					},
				},
				{
					ImportPath: "foo.com/bar/baz/vendor/vendor.com/three",
					Imports: []string{
						"foo.com/bar/baz/vendor/vendor.com/ours",
						"foo.com/bar/baz/vendor/vendor.com/transitive_ours",
					},
				},
				{
					ImportPath: "foo.com/bar/baz/vendor/vendor.com/ours",
					Imports: []string{
						"foo.com/bar/baz/vendor/vendor.com/transitive_ours",
					},
				},
				{
					ImportPath: "foo.com/bar/baz/vendor/vendor.com/mine",
					Imports: []string{
						"fmt",
					},
				},
			},
		},
	}

	// add roots
	opts.Roots = []string{
		"foo.com/bar/baz",
		"foo.com/bar/baz/one",
		"foo.com/bar/baz/two",
	}

	return opts
}

func TestGraphAnalyzisCalculatesYoursMineOurs(t *testing.T) {
	opts := &AnalyzeOptions{
		GraphOptions: newGraphOptions(),
		Dependencies: []string{
			"foo.com/bar/baz/vendor/vendor.com/one",
		},
	}

	g, err := opts.GraphOptions.BuildGraph()
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	yours, mine, ours, err := opts.calculateDependencies(g)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	expectedYours := []string{
		"vendor.com/two",
		"vendor.com/three",
	}
	expectedMine := []string{
		"vendor.com/one",
		"vendor.com/mine",
	}
	expectedOurs := []string{
		"vendor.com/ours",
	}

	// transitive dependencies (that are also not unique to the vendor dep we are analyzing)
	expectedMissing := []string{
		"vendor.com/transitive_ours",
	}

	if len(yours) != len(expectedYours) {
		t.Errorf("node count mismatch; expecting %v \"yours\" dependencies, but got %v", len(expectedYours), len(yours))
	}
	if len(ours) != len(expectedOurs) {
		t.Errorf("node count mismatch; expecting %v \"ours\" dependencies, but got %v", len(expectedOurs), len(ours))
	}
	if len(mine) != len(expectedMine) {
		t.Errorf("node count mismatch; expecting %v \"mine\" dependencies, but got %v", len(expectedMine), len(mine))
	}

	for _, expected := range expectedOurs {
		found := false
		for _, actualOurs := range ours {
			if expected == actualOurs.String() {
				found = true
				break
			}
		}
		if !found {
			t.Errorf("expected \"ours\" dependency %q was not found", expected)
		}
	}

	for _, expectedNode := range expectedYours {
		found := false
		for _, actualNode := range yours {
			if actualNode.String() == expectedNode {
				found = true
				break
			}
		}
		if !found {
			t.Errorf("expected \"yours\" dependency %q was not found", expectedNode)
		}
	}

	for _, expected := range expectedMine {
		found := false
		for _, actualMine := range mine {
			if expected == actualMine.String() {
				found = true
				break
			}
		}
		if !found {
			t.Errorf("expected \"ours\" dependency %q was not found", expected)
		}
	}

	for _, missing := range expectedMissing {
		found := false
		for _, actual := range append(yours, append(mine, ours...)...) {
			if missing == actual.String() {
				found = true
				break
			}
		}

		if found {
			t.Errorf("expecting %q to be missing, but was found in yours, mine, ours set", missing)
		}
	}
}


text:
var objectPrototype = Object.prototype
var enumBugProperties = [
  "constructor",
  "hasOwnProperty",
  "isPrototypeOf",
  "propertyIsEnumerable",
  "toLocaleString",
  "toString",
  "valueOf"
]
var hasEnumBug = !objectPrototype.propertyIsEnumerable.call(
  {constructor : 1},
  "constructor"
)
var _hasOwnProperty = objectPrototype.hasOwnProperty
var hasObjectKeys = typeof Object.keys == "function"
var objectKeys = Object.keys

module.exports = function(object){
  var index
  var keys
  var length
  var enumKey

  if(object == null) {
    return []
  }
  if(hasObjectKeys) {
    return objectKeys(object)
  }
  keys = []
  for(index in object) {
    if(_hasOwnProperty.call(object, index)) {
      keys.push(index)
    }
  }
  if(hasEnumBug) {
    index = -1
    length = enumBugProperties.length
    while(++index < length) {
      enumKey = enumBugProperties[index]
      if(_hasOwnProperty.call(object, enumKey)) {
        keys.push(enumKey)
      }
    }
  }
  return keys
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.machinelearningservices.models;

import com.azure.core.annotation.Immutable;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;

/** Settings for a Python environment. */
@Immutable
public final class ModelEnvironmentDefinitionPython extends ModelPythonSection {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(ModelEnvironmentDefinitionPython.class);

    /** {@inheritDoc} */
    @Override
    public ModelEnvironmentDefinitionPython withInterpreterPath(String interpreterPath) {
        super.withInterpreterPath(interpreterPath);
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public ModelEnvironmentDefinitionPython withUserManagedDependencies(Boolean userManagedDependencies) {
        super.withUserManagedDependencies(userManagedDependencies);
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public ModelEnvironmentDefinitionPython withCondaDependencies(Object condaDependencies) {
        super.withCondaDependencies(condaDependencies);
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public ModelEnvironmentDefinitionPython withBaseCondaEnvironment(String baseCondaEnvironment) {
        super.withBaseCondaEnvironment(baseCondaEnvironment);
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    @Override
    public void validate() {
        super.validate();
    }
}


text:
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Shapes;

namespace TestAppUWP.View.CanvasDraw
{
    public class DrawRectangleOnCanvas
    {
        private readonly Canvas _canvas;
        private Rectangle _rectangle;
        private TaskCompletionSource<Rectangle> _tcs;

        public DrawRectangleOnCanvas(Canvas canvas)
        {
            _canvas = canvas;
        }

        #region Properties
        public SolidColorBrush Stroke { get; set; }
        public SolidColorBrush Fill { get; set; }

        #endregion

        public async Task<Rectangle> DrawRectangle()
        {
            _tcs = new TaskCompletionSource<Rectangle>();
            _canvas.PointerPressed += CanvasOnPointerPressed;
            return await _tcs.Task;
        }

        public void Close()
        {
            _canvas.PointerPressed -= CanvasOnPointerPressed;
            _canvas.PointerReleased -= CanvasOnPointerReleased;
            _canvas.PointerExited -= CanvasOnPointerReleased;
            _canvas.PointerMoved -= CanvasOnPointerMoved;
        }

        private void CanvasOnPointerReleased(object sender, PointerRoutedEventArgs e)
        {
            Close();
            _tcs.SetResult(_rectangle);
        }

        private void CanvasOnPointerPressed(object sender, PointerRoutedEventArgs e)
        {
            _canvas.PointerReleased += CanvasOnPointerReleased;
            _canvas.PointerExited += CanvasOnPointerReleased;
            _canvas.PointerMoved += CanvasOnPointerMoved;

            Point currentPoint = e.GetCurrentPoint(_canvas).Position;
            _rectangle = new Rectangle {Fill = Fill, Stroke = Stroke, StrokeThickness = 2};
            Canvas.SetLeft(_rectangle, currentPoint.X);
            Canvas.SetTop(_rectangle, currentPoint.Y);
            _canvas.Children.Add(_rectangle);
        }

        private void CanvasOnPointerMoved(object sender, PointerRoutedEventArgs e)
        {
            if (_rectangle == null) return;
            Point currentPoint = e.GetCurrentPoint(_canvas).Position;
            double nextWidth = currentPoint.X - Canvas.GetLeft(_rectangle);
            if (nextWidth > 10)_rectangle.Width = nextWidth;
            double nextHeight = currentPoint.Y - Canvas.GetTop(_rectangle);
            if (nextHeight > 10) _rectangle.Height = nextHeight;
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace EdmondsCommerce\DoctrineStaticMeta\Tests\Small\CodeGeneration;

use EdmondsCommerce\DoctrineStaticMeta\CodeGeneration\NamespaceHelper;
use EdmondsCommerce\DoctrineStaticMeta\Entity\Embeddable\Interfaces\Objects\Financial\MoneyEmbeddableInterface;
use EdmondsCommerce\DoctrineStaticMeta\Entity\Embeddable\Interfaces\Objects\Geo\AddressEmbeddableInterface;
use EdmondsCommerce\DoctrineStaticMeta\Entity\Embeddable\Interfaces\Objects\Identity\FullNameEmbeddableInterface;
use EdmondsCommerce\DoctrineStaticMeta\Entity\Embeddable\Objects\Financial\MoneyEmbeddable;
use EdmondsCommerce\DoctrineStaticMeta\Entity\Embeddable\Objects\Geo\AddressEmbeddable;
use EdmondsCommerce\DoctrineStaticMeta\Entity\Embeddable\Objects\Identity\FullNameEmbeddable;
use EdmondsCommerce\DoctrineStaticMeta\Tests\Assets\AbstractTest;
use PHPUnit\Framework\TestCase;
use ts\Reflection\ReflectionClass;

/**
 * @covers \EdmondsCommerce\DoctrineStaticMeta\CodeGeneration\NamespaceHelper
 * @small
 * @SuppressWarnings(PHPMD.TooManyPublicMethods)
 */
class NamespaceHelperTest extends TestCase
{
    /**
     * @var NamespaceHelper
     */
    private static $helper;

    public static function setUpBeforeClass()
    {
        self::$helper = new NamespaceHelper();
    }

    /**
     * @test
     */
    public function itCanGetAllTheArchetypeFieldFqns(): void
    {
        $actual = self::$helper->getAllArchetypeFieldFqns();
        foreach ($actual as $fqn) {
            $reflection = new ReflectionClass($fqn);
            self::assertTrue($reflection->isTrait());
        }
        self::assertGreaterThan(10, count($actual));
    }

    /**
     * @test
     */
    public function itCanGetTheEmbeddableObjectFqnFromTheInterfaceFqn(): void
    {
        $expectedToInterface = [
            MoneyEmbeddable::class    => MoneyEmbeddableInterface::class,
            AddressEmbeddable::class  => AddressEmbeddableInterface::class,
            FullNameEmbeddable::class => FullNameEmbeddableInterface::class,
        ];
        foreach ($expectedToInterface as $expected => $interface) {
            $this->assertSame(
                $expected,
                self::$helper->getEmbeddableObjectFqnFromEmbeddableObjectInterfaceFqn($interface)
            );
        }
    }

    /**
     * @test
     */
    public function itCanGetTheEntityFqnFromTheEntityInterfaceFqn(): void
    {
        $expected = AbstractTest::TEST_PROJECT_ROOT_NAMESPACE . '\\Entities\\Foo\\BlahEntity';
        $actual   = self::$helper->getEntityFqnFromEntityInterfaceFqn(
            AbstractTest::TEST_PROJECT_ROOT_NAMESPACE . '\\Entity\\Interfaces\\Foo\\BlahEntityInterface'
        );
        self::assertSame($expected, $actual);
    }

    /**
     * @test
     */
    public function itCanGetTheEntityFactoryFqnFromEntityFqn(): void
    {
        $expected = AbstractTest::TEST_PROJECT_ROOT_NAMESPACE . '\\Entity\\Factories\\Blah\\FooFactory';
        $actual   = self::$helper->getFactoryFqnFromEntityFqn(
            AbstractTest::TEST_PROJECT_ROOT_NAMESPACE . '\\Entities\\Blah\\Foo'
        );
        self::assertSame($expected, $actual);
    }

    /**
     * @test
     */
    public function itCanGetTheEntityFqnFromEntityFactoryFqn(): void
    {
        $factory  = AbstractTest::TEST_PROJECT_ROOT_NAMESPACE . '\\Entity\\Factories\\Blah\\FooFactory';
        $expected = AbstractTest::TEST_PROJECT_ROOT_NAMESPACE . '\\Entities\\Blah\\Foo';
        $actual   = self::$helper->getEntityFqnFromEntityFactoryFqn($factory);
        self::assertSame($expected, $actual);
    }

    /**
     * @test
     */
    public function itCanGetTheEntityDtoFactoryFqnFromEntityFqn(): void
    {
        $expected = AbstractTest::TEST_PROJECT_ROOT_NAMESPACE . '\\Entity\\Factories\\Blah\\FooDtoFactory';
        $actual   = self::$helper->getDtoFactoryFqnFromEntityFqn(
            AbstractTest::TEST_PROJECT_ROOT_NAMESPACE . '\\Entities\\Blah\\Foo'
        );
        self::assertSame($expected, $actual);
    }

    /**
     * @test
     */
    public function itCanGetTheEntityFqnFromEntityDtoFactoryFqn(): void
    {
        $factory  = AbstractTest::TEST_PROJECT_ROOT_NAMESPACE . '\\Entity\\Factories\\Blah\\FooDtoFactory';
        $expected = AbstractTest::TEST_PROJECT_ROOT_NAMESPACE . '\\Entities\\Blah\\Foo';
        $actual   = self::$helper->getEntityFqnFromEntityDtoFactoryFqn($factory);
        self::assertSame($expected, $actual);
    }

    /**
     * @test
     * @large
     */
    public function getFixtureFqnFromEntityFqn(): void
    {
        $expected = AbstractTest::TEST_PROJECT_ROOT_NAMESPACE . '\\Assets\\Entity\\Fixtures\\Blah\\FooFixture';
        $actual   = self::$helper->getFixtureFqnFromEntityFqn(
            AbstractTest::TEST_PROJECT_ROOT_NAMESPACE . '\\Entities\\Blah\\Foo'
        );
        self::assertSame($expected, $actual);
    }

    /**
     * @test
     */
    public function cropSuffix(): void
    {
        $fqn      = 'FooBar';
        $suffix   = 'Bar';
        $expected = 'Foo';
        $actual   = self::$helper->cropSuffix($fqn, $suffix);
        self::assertSame($expected, $actual);
    }

    /**
     * @test
     * @large
     *      */
    public function swapSuffix(): void
    {
        $fqn           = 'FooBar';
        $currentSuffix = 'Bar';
        $newSuffix     = 'Baz';
        $expected      = 'FooBaz';
        $actual        = self::$helper->swapSuffix($fqn, $currentSuffix, $newSuffix);
        self::assertSame($expected, $actual);
    }

    /**
     * @test
     * @large
     *      */
    public function cropSuffixWhereSuffixNotInThere(): void
    {
        $fqn      = 'FooBar';
        $suffix   = 'Cheese';
        $expected = 'FooBar';
        $actual   = self::$helper->cropSuffix($fqn, $suffix);
        self::assertSame($expected, $actual);
    }

    /**
     * @test
     */
    public function tidy(): void
    {
        $namespaceToExpected = [
            'Test\\\\Multiple\\\\\\\Separators' => 'Test\\Multiple\\Separators',
            'No\\Changes\\Required'             => 'No\\Changes\\Required',
        ];
        foreach ($namespaceToExpected as $namespace => $expected) {
            self::assertSame($expected, self::$helper->tidy($namespace));
        }
    }

    /**
     * @test
     */
    public function root(): void
    {
        $namespaceToExpected = [
            '\\Test\\\\Multiple\\\\\\\Separators' => 'Test\\Multiple\\Separators',
            'No\\Changes\\Required'               => 'No\\Changes\\Required',
        ];
        foreach ($namespaceToExpected as $namespace => $expected) {
            self::assertSame($expected, self::$helper->root($namespace));
        }
    }

    /**
     * @test
     */
    public function itCanGetADtoFqnFromAnEntityFqn(): void
    {
        $expected = '\\Test\\Project\\Entity\\DataTransferObjects\\Foo\\BarDto';
        $actual   = self::$helper->getEntityDtoFqnFromEntityFqn(
            '\\Test\\Project\\Entities\\Foo\\Bar'
        );
        self::assertSame($expected, $actual);
    }

    /**
     * @test
     */
    public function itCanGetAnUpsertFqnFromAnEntityFqn(): void
    {
        $expected = '\\Test\\Project\\Entity\\Savers\\Foo\\BarUpserter';
        $actual   = self::$helper->getEntityUpserterFqnFromEntityFqn(
            '\\Test\\Project\\Entities\\Foo\\Bar'
        );
        self::assertSame($expected, $actual);
    }

    /**
     * @test
     */
    public function itCanGetAnEntityFqnFromAnUpsertFqn(): void
    {
        $expected = '\\Test\\Project\\Entities\\Foo\\Bar';
        $actual   = self::$helper->getEntityFqnFromEntityUpserterFqn(
            '\\Test\\Project\\Entity\\Savers\\Foo\\BarUpserter'
        );
        self::assertSame($expected, $actual);
    }

    /**
     * @test
     */
    public function itCanGetAnUnitOfWorkHelperFqnFromAnEntityFqn(): void
    {
        $expected = '\\Test\\Project\\Entity\\Savers\\Foo\\BarUnitOfWorkHelper';
        $actual   = self::$helper->getEntityUnitOfWorkHelperFqnFromEntityFqn(
            '\\Test\\Project\\Entities\\Foo\\Bar'
        );
        self::assertSame($expected, $actual);
    }

    /**
     * @test
     */
    public function itCanGetAnEntityFqnFromAnUnitOfWorkHelperFqn(): void
    {
        $expected = '\\Test\\Project\\Entities\\Foo\\Bar';
        $actual   = self::$helper->getEntityFqnFromEntityUnitOfWorkHelperFqn(
            '\\Test\\Project\\Entity\\Savers\\Foo\\BarUnitOfWorkHelper'
        );
        self::assertSame($expected, $actual);
    }
}


text:
package sync

import (
	"sync"

	ds "github.com/ipfs/go-blocks/Godeps/_workspace/src/github.com/jbenet/go-datastore"
	dsq "github.com/ipfs/go-blocks/Godeps/_workspace/src/github.com/jbenet/go-datastore/query"
)

// MutexDatastore contains a child datastire and a mutex.
// used for coarse sync
type MutexDatastore struct {
	sync.RWMutex

	child ds.Datastore
}

// MutexWrap constructs a datastore with a coarse lock around
// the entire datastore, for every single operation
func MutexWrap(d ds.Datastore) ds.ThreadSafeDatastore {
	return &MutexDatastore{child: d}
}

// Children implements Shim
func (d *MutexDatastore) Children() []ds.Datastore {
	return []ds.Datastore{d.child}
}

// IsThreadSafe implements ThreadSafeDatastore
func (d *MutexDatastore) IsThreadSafe() {}

// Put implements Datastore.Put
func (d *MutexDatastore) Put(key ds.Key, value interface{}) (err error) {
	d.Lock()
	defer d.Unlock()
	return d.child.Put(key, value)
}

// Get implements Datastore.Get
func (d *MutexDatastore) Get(key ds.Key) (value interface{}, err error) {
	d.RLock()
	defer d.RUnlock()
	return d.child.Get(key)
}

// Has implements Datastore.Has
func (d *MutexDatastore) Has(key ds.Key) (exists bool, err error) {
	d.RLock()
	defer d.RUnlock()
	return d.child.Has(key)
}

// Delete implements Datastore.Delete
func (d *MutexDatastore) Delete(key ds.Key) (err error) {
	d.Lock()
	defer d.Unlock()
	return d.child.Delete(key)
}

// KeyList implements Datastore.KeyList
func (d *MutexDatastore) Query(q dsq.Query) (dsq.Results, error) {
	d.RLock()
	defer d.RUnlock()
	return d.child.Query(q)
}


text:
"""
Backward compatibity with bridgesupport files
"""
__all__ = ('initFrameworkWrapper', 'parseBridgeSupport')

import sys
import xml.etree.ElementTree as ET
import ctypes
import objc
import re
import warnings
import functools
import pkg_resources
import os

from objc import registerMetaDataForSelector, error

for method in (b'alloc', b'copy', b'copyWithZone:', b'mutableCopy', b'mutableCopyWithZone:'):
    registerMetaDataForSelector(b'NSObject', method,
            {
                'retval': { 'already_retained': True },
            })

#
# The rest of this file contains support for bridgesupport
# XML files.
#
# TODO: parseBridgeSupport (and its support class) is a
#       basic port from C, check if it can be simplified.

# NOTE: This search path only contains system locations to
# avoid accidently reiying on system-specific functionality.
BRIDGESUPPORT_DIRECTORIES = [
    '/System/Library/BridgeSupport',
]

_SENTINEL=object()
_DEFAULT_SUGGESTION="don't use this method"
_BOOLEAN_ATTRIBUTES=[
    "already_retained",
    "already_cfretained",
    "c_array_length_in_result",
    "c_array_delimited_by_null",
    "c_array_of_variable_length",
    "printf_format",
    "free_result",
]

if sys.version_info[0] == 2:
    _unicode = unicode

    def _as_bytes(value):
        return value

else: # pragma: no cover (py3k)

    _unicode = str

    def _as_bytes(value):
        if isinstance(value, bytes):
            return value
        return value.encode('ascii')

class _BridgeSupportParser (object):
    """
    Parser for the bridge support file format.

    Instances of this class will not update the bridge state,
    this makes it easier to test the class.
    """
    TAG_MAP={}

    def __init__(self, xmldata, frameworkName):
        self.frameworkName = frameworkName

        self.cftypes = []
        self.constants = []
        self.func_aliases = []
        self.functions = []
        self.informal_protocols = []
        self.meta = {}
        self.opaque = []
        self.structs = []
        self.values = {}

        self.process_data(xmldata)

    def process_data(self, xmldata):
        root = ET.fromstring(xmldata.strip())

        if root.tag != 'signatures':
            raise error("invalid root node in bridgesupport file")

        for node in root:
            method = getattr(self, 'do_%s'%(node.tag,), None)
            if method is None:
                continue

            method(node)

    def typestr2typestr(self, typestr):
        typestr = _as_bytes(typestr)

        result = []
        for item in objc.splitSignature(typestr):
            if item == objc._C_BOOL:
                result.append(objc._C_NSBOOL)

            elif item == objc._C_NSBOOL:
                result.append(objc._C_BOOL)

            elif item.startswith(objc._C_STRUCT_B) or item.startswith(objc._C_UNION_B):
                # unions and structs have the same structure
                start, stop = item[:1], item[-1:]

                name, fields = objc.splitStructSignature(objc._C_STRUCT_B + _as_bytes(item[1:-1]) + objc._C_STRUCT_E)
                result.append(start)
                result.append(_as_bytes(name))
                result.append(b'=')
                for nm, tp in fields:
                    if nm is not None:
                        result.append(b'"')
                        result.append(_as_bytes(nm))
                        result.append(b'"')

                    result.append(self.typestr2typestr(tp))
                result.append(stop)

            elif item.startswith(objc._C_ARY_B):
                m = re.match(b'^.(\d*)(.*).$', item)
                result.append(objc._C_ARY_B)
                result.append(m.group(1))
                result.append(self.typestr2typestr(m.group(2)))
                result.append(objc._C_ARY_E)

            else:
                result.append(item)

        result = b''.join(result)
        return result

    if sys.maxsize > 2**32:
        def attribute_string(self, node, name, name64):
            if name64 is not None:
                value = node.get(name64)
                if value is not None:
                    return value

            return node.get(name)

    else:
        def attribute_string(self, node, name, name64):
            return node.get(name)

    def attribute_bool(self, node, name, name64, dflt):
        value = self.attribute_string(node, name, name64)
        if value is None:
            return dflt

        if value == "true":
            return True

        return False

    def import_name(self, name):
        module, field = name.rsplit('.', 1)
        m = __import__(module)
        try:
            for nm in module.split('.')[1:]:
                m = getattr(m, nm)

            return getattr(m, field)

        except AttributeError:
            raise ImportError(name)

    def xml_to_arg(self, node, is_method, is_arg):
        argIdx = None
        result = {}

        if is_arg and is_method:
            argIdx = self.attribute_string(node, "index", None)
            if argIdx is None:
                return None, None
            argIdx = int(argIdx)

        s = self.attribute_string(node, "type", "type64")
        if s:
            s = self.typestr2typestr(s)
            result["type"] = s

        s = self.attribute_string(node, "type_modifier", None)
        if s:
            result["type_modifier"] = _as_bytes(s)

        s = self.attribute_string(node, "sel_of_type", "sel_of_type64")
        if s:
            result["sel_of_type"] = self.typestr2typestr(s)

        s = self.attribute_string(node, "c_array_of_fixed_length", None)
        if s:
            result["c_array_of_fixed_length"] = int(s)

        for attr in _BOOLEAN_ATTRIBUTES:
            if attr == 'c_array_length_in_result' and not is_arg:
                continue
            s = self.attribute_bool(node, attr, None, False)
            if s:
                result[attr] = True

        s = self.attribute_bool(node, "null_accepted", None, True)
        if not s:
            result["null_accepted"] = False

        s = self.attribute_string(node, "c_array_length_in_arg", None)
        if s:
            if ',' in s:
                start, stop = map(int, s.split(','))
                if is_method:
                    start += 2
                    stop  += 2

                result["c_array_length_in_arg"] = (start, stop)

            else:
                s = int(s)
                if is_method:
                    s += 2

                result["c_array_length_in_arg"] = s

        if self.attribute_bool(node, "function_pointer", None, False) \
           or self.attribute_bool(node, "block", None, False):

            v = self.attribute_bool(node, "function_pointer_retained", None, True)
            result["callable_retained"] = v

            meta = result["callable"] = {}
            arguments = meta["arguments"] = {}
            idx = 0

            if self.attribute_bool(node, "block", None, False):
                # Blocks have an implicit first argument
                arguments[idx] = {
                    "type": b"^v",
                }
                idx += 1

            for al in node:
                if al.tag == "arg":
                    _, d = self.xml_to_arg(al, False, False)
                    arguments[idx] = d
                    idx += 1

                elif al.tag == "retval":
                    _, d = self.xml_to_arg(al, False, False)
                    meta["retval"] = d

        return argIdx, result

    def do_cftype(self, node):
        name    = self.attribute_string(node, "name", None)
        typestr = self.attribute_string(node, "type", "type64")
        funcname = self.attribute_string(node, "gettypeid_func", None)
        tollfree = self.attribute_string(node, "tollfree", None)

        if not name or not typestr:
            return

        typestr = self.typestr2typestr(typestr)

        if tollfree:
            self.cftypes.append((name, typestr, None, tollfree))

        else:
            if funcname is None:
                funcname = name[:-3] + 'GetTypeID'

            try:
                dll = ctypes.CDLL(None)
                gettypeid = getattr(dll, funcname)
                gettypeid.restype = ctypes.c_long
            except AttributeError:
                self.cftypes.append((name, typestr, None, "NSCFType"))
                return

            self.cftypes.append((name, typestr, gettypeid()))

    def do_constant(self, node):
        name    = self.attribute_string(node, "name", None)
        typestr = self.attribute_string(node, "type", "type64")

        if name is None or not typestr:
            return

        typestr = self.typestr2typestr(typestr)

        if typestr.startswith(objc._C_STRUCT_B):
            # Look for structs with embbeded function pointers
            # and ignore those

            def has_embedded_function(typestr):
                nm, fields = objc.splitStructSignature(_as_bytes(typestr))
                for nm, tp in fields:
                    if tp == b'?':
                        return True
                    elif tp == b'^?':
                        return True
                    elif tp.startswith(objc._C_STRUCT_B):
                        return has_embedded_function(tp)

                return False

            if has_embedded_function(typestr):
                return

        magic = self.attribute_bool(node, "magic_cookie", None, False)
        self.constants.append((name, typestr, magic))

    def do_class(self, node):
        class_name = self.attribute_string(node, "name", None)
        if not class_name:
            return

        for method in node:
            if method.tag != "method":
                continue

            sel_name = self.attribute_string(method, "selector", None)
            if sel_name is None:
                continue

            sel_name = _as_bytes(sel_name)
            variadic = self.attribute_bool(  method, "variadic", None, False)
            c_array  = self.attribute_bool(  method, "c_array_delimited_by_null", None, False)
            c_length = self.attribute_string(method, "c_array_length_in_arg", None)
            ignore   = self.attribute_bool(  method, "ignore", None, False)

            is_class = self.attribute_bool(method, "classmethod", None, _SENTINEL)
            if is_class is _SENTINEL:
                # Manpage says 'class_method', older PyObjC used 'classmethod'
                is_class = self.attribute_bool(method, "class_method", None, False)

            metadata = {}
            if ignore:
                suggestion = self.attribute_string(method, "suggestion", None)
                if not suggestion:
                    suggestion = _DEFAULT_SUGGESTION

                metadata['suggestion'] = suggestion

                # Force minimal metadata for ignored methods
                self.meta[(_as_bytes(class_name), _as_bytes(sel_name), is_class)] = metadata
                continue

            if variadic:
                metadata['variadic'] = True
                if c_array:
                    metadata['c_array_delimited_by_null'] = c_array

                if c_length:
                    metadata['c_array_length_in_arg'] = int(c_length) + 2;

            arguments = metadata['arguments'] = {}

            for al in method:
                if al.tag == "arg":
                    arg_idx, meta = self.xml_to_arg(al, True, True)
                    if arg_idx is not None and meta:
                        arguments[arg_idx+2] = meta

                elif al.tag == "retval":
                    _, meta = self.xml_to_arg(al, True, False)
                    if meta:
                        metadata['retval'] = meta

            if not arguments:
                # No argument metadata after all.
                del metadata['arguments']

            if metadata:
                self.meta[(_as_bytes(class_name), _as_bytes(sel_name), is_class)] = metadata

    def do_enum(self, node):
        name  = self.attribute_string(node, "name", None)
        value = self.attribute_string(node, "value", "value64")

        if value is None:
            if sys.byteorder == 'little':
                value = self.attribute_string(node, "le_value", None)

            else:
                value = self.attribute_string(node, "be_value", None)

        if not name or not value:
            return

        if value.lower() in ('+inf', '-inf', 'nan'):
            value = float(value)

        elif '.' in value:
            if value.endswith('f') or value.endswith('F'):
                value = value[:-1]
            if value.endswith('l') or value.endswith('L'):
                value = value[:-1]
            if value.startswith('0x') or value.startswith('0X'):
                value = float.fromhex(value)

            else:
                value = float(value)

        else:
            value = int(value, 10)

        self.values[name] = value

    def do_function(self, node):
        name = self.attribute_string(node, "name", None)
        if not name:
            return

        if self.attribute_bool(node, "ignore", None, False):
            return

        meta = {}
        siglist = [b"v"]
        arguments = meta["arguments"] = {}

        variadic = self.attribute_bool(node, "variadic", None, False)
        if variadic:
            meta["variadic"] = True
            v = self.attribute_bool(node, "c_array_delimited_by_null", None, False)
            if v:
                meta["c_array_delimited_by_null"] = True

            v = self.attribute_string(node, "c_array_length_in_arg", None)
            if v:
                meta["c_array_length_in_arg"] = int(v)

        for al in node:
            if al.tag == "arg":
                _, d = self.xml_to_arg(al, False, True)
                if "type" not in d:
                    # Ignore functions without type info
                    return
                siglist.append(d["type"])

                arguments[len(siglist)-2] = d

            elif al.tag == "retval":
                _, d = self.xml_to_arg(al, False, False)
                if "type" not in d:
                    # Ignore functions without type info
                    return
                siglist[0] = d["type"]
                meta["retval"] = d

        if not meta['arguments']:
            del meta['arguments']

        self.functions.append((name, b"".join(siglist), "", meta))

    def do_function_pointer(self, node):
        name = self.attribute_string(node, "name", None)
        original = self.attribute_string(node, "original", None)
        if not name or not original:
            return

        self.func_aliases.append((name, original))

    def do_informal_protocol(self, node):
        name = self.attribute_string(node, "name", None)
        if not name:
            return

        method_list = []
        for method in node:
            sel_name = self.attribute_string(method, "selector", None)
            typestr  = self.attribute_string(method, "type", "type64")
            is_class = self.attribute_bool(method, "classmethod", None, _SENTINEL)
            if is_class is _SENTINEL:
                # Manpage says 'class_method', older PyObjC used 'classmethod'
                is_class = self.attribute_bool(method, "class_method", None, False)

            if not sel_name or not typestr:
                continue

            typestr = self.typestr2typestr(typestr)
            sel = objc.selector(None, selector=_as_bytes(sel_name),
                    signature=_as_bytes(typestr), isClassMethod=is_class)
            method_list.append(sel)

        if method_list:
            self.informal_protocols.append((name, method_list))

    def do_null_const(self, node):
        name = self.attribute_string(node, "name", None)
        if not name:
            return

        self.values[name] = None

    def do_opaque(self, node):
        name    = self.attribute_string(node, "name", None)
        typestr = self.attribute_string(node, "type", "type64")

        if name is None or not typestr:
            return

        typestr = self.typestr2typestr(typestr)

        self.opaque.append((name, typestr))

    def do_struct(self, node):
        name    = self.attribute_string(node, "name", None)
        typestr = self.attribute_string(node, "type", "type64")
        alias   = self.attribute_string(node, "alias", None)

        if not name or not typestr:
            return

        # Apple's bridgesupport files contain nice encoding like this:
        # {tag="field"a"NSImage"}, that is not only are field names encoded
        # but also class names. This is obviously completely undocumented,
        # and not backward compatible (and it is not easily possible to detect
        # if class names are present.
        typestr = re.sub(r'@"[^"]*"', '@', typestr)

        typestr = self.typestr2typestr(typestr)

        if alias:
            try:
                value = self.import_name(alias)
            except ImportError:
                # Fall through to regular handling
                pass

            else:
                self.structs.append((name, typestr, value))
                return

        self.structs.append((name, typestr, None))

    def do_string_constant(self, node):
        name  = self.attribute_string(node, "name", None)
        value = self.attribute_string(node, "value", "value64")
        nsstring = self.attribute_bool(node, "nsstring", None, False)

        if not name or not value:
            return

        if sys.version_info[0] == 2:
            if nsstring:
                if not isinstance(value, unicode):
                    value = value.decode('utf-8')
            else:
                if not isinstance(value, bytes):
                    try:
                        value = value.encode('latin1')
                    except UnicodeError as e:
                        warnings.warn("Error parsing BridgeSupport data for constant %s: %s" % (name, e), RuntimeWarning)
                        return
        else: # pragma: no cover (py3k)
            if not nsstring:
                try:
                    value = value.encode('latin1')
                except UnicodeError as e:
                    warnings.warn("Error parsing BridgeSupport data for constant %s: %s" % (name, e), RuntimeWarning)
                    return

        if nsstring:
            assert isinstance(value, _unicode)
        else:
            assert isinstance(value, bytes)

        self.values[name] = value

_libraries = []

def parseBridgeSupport(xmldata, globals, frameworkName, dylib_path=None, inlineTab=None):

    if dylib_path:
        lib = ctypes.cdll.LoadLibrary(dylib_path)
        _libraries.append(lib)

    objc._updatingMetadata(True)
    try:
        prs = _BridgeSupportParser(xmldata, frameworkName)

        globals.update(prs.values)
        for entry in prs.cftypes:
            tp = objc.registerCFSignature(*entry)

            globals[entry[0]] = tp

        for name, typestr in prs.opaque:
            globals[name] = objc.createOpaquePointerType(name, typestr)

        for name, typestr, alias in prs.structs:
            if alias is not None:
                globals[name] = alias
                objc.createStructAlias(name, typestr, alias)
            else:
                globals[name] = value = objc.createStructType(name, typestr, None)

        for name, typestr, magic in prs.constants:
            try:
                value = objc._loadConstant(name, typestr, magic)
            except AttributeError:
                continue

            globals[name] = value

        for class_name, sel_name, is_class in prs.meta:
            objc.registerMetaDataForSelector(class_name, sel_name, prs.meta[(class_name, sel_name, is_class)])

        for name, method_list in prs.informal_protocols:
            proto = objc.informal_protocol(name, method_list)

            # XXX: protocols submodule should be deprecated
            if "protocols" not in globals:
                mod_name = "%s.protocols"%(frameworkName,)
                m = globals["protocols"] = type(objc)(mod_name)
                sys.modules[mod_name] = m

            else:
                m = globals["protocols"]

            setattr(m, name, proto)

        if prs.functions:
            objc.loadBundleFunctions(None, globals, prs.functions)

            if inlineTab is not None:
                objc.loadFunctionList(inlineTab, globals, prs.functions)

        for name, orig in prs.func_aliases:
            try:
                globals[name] = globals[orig]
            except KeyError:
                pass

    finally:
        objc._updatingMetadata(False)

def _parseBridgeSupport(data, globals, frameworkName, *args, **kwds):
    try:
        try:
            objc.parseBridgeSupport(data, globals, frameworkName, *args, **kwds)
        except objc.internal_error as e:
            import warnings
            warnings.warn("Error parsing BridgeSupport data for %s: %s" % (frameworkName, e), RuntimeWarning)
    finally:
        # Add formal protocols to the protocols submodule, for backward
        # compatibility with earlier versions of PyObjC
        if 'protocols' in globals:
            for p in objc.protocolsForProcess():
                setattr(globals['protocols'], p.__name__, p)

def safe_resource_exists(package, resource):
    try:
        return  pkg_resources.resource_exists(package, resource)
    except ImportError:
        # resource_exists raises ImportError when it cannot find
        # the first argument.
        return False

def initFrameworkWrapper(frameworkName,
        frameworkPath, frameworkIdentifier, globals, inlineTab=None,
        scan_classes=None, frameworkResourceName=None):
    """
    Load the named framework, using the identifier if that has result otherwise
    using the path. Also loads the information in the bridgesupport file (
    either one embedded in the framework or one in a BrigeSupport library
    directory).
    """
    if frameworkResourceName is None:
        frameworkResourceName = frameworkName

    if frameworkIdentifier is None:
        if scan_classes is None:
            bundle = objc.loadBundle(
                frameworkName,
                globals,
                bundle_path=frameworkPath)
        else:
            bundle = objc.loadBundle(
                frameworkName,
                globals,
                bundle_path=frameworkPath,
                scan_classes=scan_classes)

    else:
        try:
            if scan_classes is None:
                bundle = objc.loadBundle(
                    frameworkName,
                    globals,
                    bundle_identifier=frameworkIdentifier)

            else:
                bundle = objc.loadBundle(
                    frameworkName,
                    globals,
                    bundle_identifier=frameworkIdentifier,
                    scan_classes=scan_classes)

        except ImportError:
            if scan_classes is None:
                bundle = objc.loadBundle(
                    frameworkName,
                    globals,
                    bundle_path=frameworkPath)
            else:
                bundle = objc.loadBundle(
                    frameworkName,
                    globals,
                    bundle_path=frameworkPath,
                    scan_classes=scan_classes)

    # Make the objc module available, because it contains a lot of useful
    # functionality.
    globals['objc'] = objc

    # Explicitly push objc.super into the globals dict, that way super
    # calls will behave as expected in all cases.
    globals['super'] = objc.super

    # Look for metadata in the Python wrapper and prefer that over the
    # data in the framework or in system locations.
    # Needed because the system bridgesupport files are buggy.
    if safe_resource_exists(frameworkResourceName, "PyObjC.bridgesupport"):
        data = pkg_resources.resource_string(frameworkResourceName,
            "PyObjC.bridgesupport")
        if data:
            _parseBridgeSupport(data, globals, frameworkName, inlineTab=inlineTab)
        return bundle

    # Look for metadata in the framework bundle
    path = bundle.pathForResource_ofType_inDirectory_(frameworkName, 'bridgesupport', 'BridgeSupport')
    if path is not None:
        dylib_path = bundle.pathForResource_ofType_inDirectory_(frameworkName, 'dylib', 'BridgeSupport')
        with open(path, 'rb') as fp:
            data = fp.read()
        if dylib_path is not None:
            _parseBridgeSupport(data, globals, frameworkName, dylib_path=dylib_path)
        else:
            _parseBridgeSupport(data, globals, frameworkName)

        # Check if we have additional metadata bundled with PyObjC
        if safe_resource_exists(frameworkResourceName, "PyObjCOverrides.bridgesupport"):
            data = pkg_resources.resource_string(frameworkResourceName,
                "PyObjCOverrides.bridgesupport")
            if data:
                _parseBridgeSupport(data, globals, frameworkName, inlineTab=inlineTab)

        return bundle

    # If there is no metadata there look for metadata in the standard Library
    # locations
    fn = frameworkName + '.bridgesupport'
    for dn in BRIDGESUPPORT_DIRECTORIES:
        path = os.path.join(dn, fn)
        if os.path.exists(path):
            with open(path, 'rb') as fp:
                data = fp.read()

            dylib_path = os.path.join(dn, frameworkName + '.dylib')
            if os.path.exists(dylib_path):
                _parseBridgeSupport(data, globals, frameworkName, dylib_path=dylib_path)
            else:
                _parseBridgeSupport(data, globals, frameworkName)

            # Check if we have additional metadata bundled with PyObjC
            if safe_resource_exists(frameworkResourceName, "PyObjCOverrides.bridgesupport"):
                data = pkg_resources.resource_string(frameworkResourceName,
                    "PyObjCOverrides.bridgesupport")
                if data:
                    _parseBridgeSupport(data, globals, frameworkName, inlineTab=inlineTab)

            return bundle

    return bundle

_ivar_dict = objc._objc._ivar_dict()
if hasattr(objc, '_ivar_dict'):
    del objc._ivar_dict
def _structConvenience(structname, structencoding):
    def makevar(self, name=None):
        if name is None:
            return objc.ivar(type=structencoding)
        else:
            return objc.ivar(name=name, type=structencoding)
    _ivar_dict[structname] = classmethod(makevar)

# Fake it for basic C types
_structConvenience("bool", objc._C_BOOL)
_structConvenience("char", objc._C_CHR)
_structConvenience("int", objc._C_INT)
_structConvenience("short", objc._C_SHT)
_structConvenience("long", objc._C_LNG)
_structConvenience("long_long", objc._C_LNG_LNG)
_structConvenience("unsigned_char", objc._C_UCHR)
_structConvenience("unsigned_int", objc._C_UINT)
_structConvenience("unsigned_short", objc._C_USHT)
_structConvenience("unsigned_long", objc._C_ULNG)
_structConvenience("unsigned_long_long", objc._C_ULNG_LNG)
_structConvenience("float", objc._C_FLT)
_structConvenience("double", objc._C_DBL)
_structConvenience("BOOL", objc._C_NSBOOL)
_structConvenience("UniChar", objc._C_UNICHAR)
_structConvenience("char_text", objc._C_CHAR_AS_TEXT)
_structConvenience("char_int", objc._C_CHAR_AS_INT)

_orig_createStructType = objc.createStructType

@functools.wraps(objc.createStructType)
def createStructType(name, typestr, fieldnames, doc=None, pack=-1):
    result = _orig_createStructType(name, typestr, fieldnames, doc, pack)
    _structConvenience(name, result.__typestr__)
    return result

objc.createStructType = createStructType

_orig_registerStructAlias = objc.registerStructAlias
@functools.wraps(objc.registerStructAlias)
def registerStructAlias(typestr, structType):
    warnings.warn("use createStructAlias instead", DeprecationWarning)
    return _orig_registerStructAlias(typestr, structType)

def createStructAlias(name, typestr, structType):
    result = _orig_registerStructAlias(typestr, structType)
    _structConvenience(name, result.__typestr__)
    return result

objc.createStructAlias = createStructAlias
objc.registerStructAlias = registerStructAlias


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>UI2D</title>
<meta name="date" content="2015-02-25">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

call.game.geom

Class UI2D

java.lang.Object

call.game.geom.UI2D

public class UI2D
extends java.lang.Object

Constructor Summary

Constructors

Constructor and Description

UI2D()

Method Summary

Methods

Modifier and Type
Method and Description

static void
line(double x1,
    double y1,
    double x2,
    double y2,
    float width)

static void
line(double x1,
    double y1,
    double x2,
    double y2,
    float width,
    int col)

static void
outlineRect(double x,
           double y,
           double width,
           double height,
           int col)

static void
polygon(double x,
       double y,
       java.awt.Point[] verts)

static void
polygon(double x,
       double y,
       java.awt.Point[] verts,
       int col)

static void
rect(double x,
    double y,
    double width,
    double height)

static void
rect(double x,
    double y,
    double width,
    double height,
    int col)

static void
renderText(java.lang.String text,
          int x,
          int y)

static void
renderText(java.lang.String text,
          int x,
          int y,
          java.awt.Font font)

static void
square(double x,
      double y,
      double size)

static void
square(double x,
      double y,
      double size,
      int col)

static void
triangle(double x,
        double y,
        double width,
        double height)

static void
triangle(double x,
        double y,
        double width,
        double height,
        int col)

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

UI2D

public UI2D()

Method Detail

rect

public static void rect(double x,
        double y,
        double width,
        double height)

rect

public static void rect(double x,
        double y,
        double width,
        double height,
        int col)

outlineRect

public static void outlineRect(double x,
               double y,
               double width,
               double height,
               int col)

square

public static void square(double x,
          double y,
          double size)

square

public static void square(double x,
          double y,
          double size,
          int col)

triangle

public static void triangle(double x,
            double y,
            double width,
            double height)

triangle

public static void triangle(double x,
            double y,
            double width,
            double height,
            int col)

polygon

public static void polygon(double x,
           double y,
           java.awt.Point[] verts)

polygon

public static void polygon(double x,
           double y,
           java.awt.Point[] verts,
           int col)

line

public static void line(double x1,
        double y1,
        double x2,
        double y2,
        float width)

line

public static void line(double x1,
        double y1,
        double x2,
        double y2,
        float width,
        int col)

renderText

public static void renderText(java.lang.String text,
              int x,
              int y)

renderText

public static void renderText(java.lang.String text,
              int x,
              int y,
              java.awt.Font font)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package example.repo;

import example.model.Customer56;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

public interface Customer56Repository extends CrudRepository<Customer56, Long> {

	List<Customer56> findByLastName(String lastName);
}


text:
REM build swarm and cleanup to minimize image layer size

REM install golang, git, godep
choco install golang -y
if errorlevel 1 exit 1
SET PATH=%PATH%;%GOROOT%\bin;%GOPATH%\bin
choco install git -y
if errorlevel 1 exit 1
SET PATH=%PATH%;c:\program files\git\cmd
go get github.com/tools/godep
if errorlevel 1 exit 1

REM build swarm
mkdir %GOPATH%
mkdir %GOPATH%\src\github.com\docker
cd %GOPATH%\src\github.com\docker
git clone https://github.com/docker/swarm
if errorlevel 1 exit 1
cd swarm
git checkout %SWARM_VERSION%
if errorlevel 1 exit 1

godep go install .
if errorlevel 1 exit 1
cd \
mkdir bin
copy %GOPATH%\bin\swarm.exe bin\swarm.exe

REM cleanup to reduce image layer size
choco uninstall golang -y
if exist %GOROOT% rmdir /s /q %GOROOT%
if exist %GOPATH% rmdir /s /q %GOPATH%
choco uninstall git -y
if exist "c:\program files\git" rmdir /s /q "c:\program files\git"


text:
<?php

namespace MediaConchOnlineBundle\Lib\XslPolicy;

class XslPolicyGetPoliciesCount extends XslPolicyBase
{
    public function getPoliciesCount()
    {
        $this->response = $this->mc->policyGetPoliciesCount($this->user->getId());
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 338104 $ -->

<refentry xml:id="function.mongodb.bson-tojson" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
 <refnamediv>
  <refname>MongoDB\BSON\toJSON</refname>
  <refpurpose>Returns the JSON representation of a BSON value</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <type>string</type><methodname>MongoDB\BSON\toJSON</methodname>
   <methodparam><type>string</type><parameter>bson</parameter></methodparam>
  </methodsynopsis>
  <para>
   Converts a BSON string to its
   <link xlink:href="&url.mongodb.docs.extendedjson;">extended JSON</link>
   representation.
  </para>
 </refsect1>

 <refsect1 role="parameters">
  &reftitle.parameters;
  <variablelist>
   <varlistentry>
    <term><parameter>bson</parameter> (<type>string</type>)</term>
    <listitem>
     <para>
      BSON value to be converted.
     </para>
    </listitem>
   </varlistentry>
  </variablelist>
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   The converted JSON value.
  </para>
 </refsect1>

 <refsect1 role="errors">
  &reftitle.errors;
  <para>
   Throws
   <classname>MongoDB\Driver\Exception\UnexpectedValueException</classname> if
   the input did not contain exactly one BSON document. Possible reasons
   include, but are not limited to, invalid BSON, extra data (after reading one
   BSON document), or an unexpected
   <link xlink:href="&url.mongodb.libbson;">libbson</link> error.
  </para>
 </refsect1>

 <refsect1 role="examples">
  &reftitle.examples;
  <example>
   <title><function>MongoDB\BSON\toJSON</function> example</title>
   <programlisting role="php">
<![CDATA[
<?php

$document = ['_id' => new MongoDB\BSON\ObjectId('56315a7c6118fd1b920270b1')];
$bson = MongoDB\BSON\fromPHP($document);
echo MongoDB\BSON\toJSON($bson), "\n";

?>
]]>
   </programlisting>
   &example.outputs;
   <screen>
<![CDATA[
{ "_id" : { "$oid" : "56315a7c6118fd1b920270b1" } }
]]>
   </screen>
  </example>
 </refsect1>

 <refsect1 role="seealso">
  &reftitle.seealso;
  <simplelist>
   <member><function>MongoDB\BSON\fromJSON</function></member>
   <member><link xlink:href="&url.mongodb.docs.extendedjson;">MongoDB Extended JSON</link></member>
   <member><link xlink:href="&url.mongodb.docs.bson;">MongoDB BSON</link></member>
  </simplelist>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
package org.jpasecurity.contacts.annotationbased;

import static org.jpasecurity.contacts.annotationbased.ContactType.CUSTOMER;

import java.io.Serializable;

import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;

import org.jpasecurity.AccessType;
import org.jpasecurity.security.Permit;
import org.jpasecurity.security.PermitAny;

/**
 * @author Arne Limburg
 */
@Entity
@NamedQuery(name = Contact.FIND_ALL, query = "SELECT contact FROM Contact contact")
@PermitAny({
    @Permit(access = { AccessType.CREATE, AccessType.READ }, where = "'admin' IN CURRENT_ROLES"),
    @Permit(access = AccessType.UPDATE, where = "'updater' IN CURRENT_ROLES"),
    @Permit(access = AccessType.READ, where = "EXISTS (SELECT contact FROM Contact contact "
            + "WHERE this = contact "
            + " AND (contact.owner = CURRENT_PRINCIPAL OR contact.owner = 'public'))"
            + " AND this.type = org.jpasecurity.contacts.annotationbased.ContactType.CUSTOMER")
    })
public class Contact implements Serializable {

    public static final String FIND_ALL = "Contact.findAll";

    @Id @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    @Basic
    private String owner;
    @Basic
    private String text;

    @Enumerated
    private ContactType type;

    public Contact() {
    }

    public Contact(String user, String text) {
        this(user, text, CUSTOMER);
    }

    public Contact(String user, String text, ContactType type) {
        setOwner(user);
        setText(text);
        setType(CUSTOMER);
    }

    public Integer getId() {
        return id;
    }

    protected void setId(int id) {
        this.id = id;
    }

    public String getOwner() {
        return owner;
    }

    public void setOwner(String user) {
        this.owner = user;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public ContactType getType() {
        return type;
    }

    public void setType(ContactType type) {
        this.type = type;
    }

    public String toString() {
        return getText();
    }

    public boolean equals(Object object) {
        if (!(object instanceof Contact)) {
            return false;
        }
        Contact contact = (Contact)object;
        if (getId() != null && contact.getId() != null) {
            return getId().equals(contact.getId());
        } else if (getId() == null && contact.getId() == null) {
            return this == contact;
        } else {
            return false;
        }
    }

    public int hashCode() {
        return getId() == null? System.identityHashCode(this): getId().hashCode();
    }
}


text:
package edu.cuny.qc.speech.AuToBI.util;

import java.util.*;
import java.io.File;
import java.io.FilenameFilter;

import de.bwaldvogel.liblinear.SolverType;
import edu.cuny.qc.speech.AuToBI.AuToBI;
import edu.cuny.qc.speech.AuToBI.classifier.LibLinearClassifier;
import edu.cuny.qc.speech.AuToBI.core.AuToBIException;
import edu.cuny.qc.speech.AuToBI.core.AuToBIParameters;
import edu.cuny.qc.speech.AuToBI.core.AuToBITask;
import edu.cuny.qc.speech.AuToBI.core.Word;
import edu.cuny.qc.speech.AuToBI.featureset.*;
import org.apache.oro.io.GlobFilenameFilter;

import org.apache.log4j.Logger;

/**
 * Stores general utility functions for AuToBI.
 *

 * Currently handles the resolution of filenames, an interface to log4j logging and string manipulation functions.
 */
public class AuToBIUtils {

  // Utility classes cannot be constructed.
  private AuToBIUtils() {
    throw new AssertionError();
  }

  // A log4j logger
  private static Logger logger = Logger.getLogger(AuToBIUtils.class);

  /**
   * Logs a message to the logger.
   *
   * @param s the message
   */
  public static void log(String s) {
    logger.info(s);
  }

  /**
   * Sends a debug message to the logger.
   *
   * @param s the message
   */
  public static void debug(String s) {
    logger.debug(s);
  }

  /**
   * Sends a warning message to the logger.
   *
   * @param s the message
   */
  public static void warn(String s) {
    logger.warn(s);
  }

  /**
   * Sends an error message to the logger.
   *
   * @param s the message
   */
  public static void error(String s) {
    logger.error(s);
  }

  /**
   * Sends an information message to the logger.
   *
   * @param s the message
   */
  public static void info(String s) {
    logger.info(s);
  }

  /**
   * Globs a file pattern into a list of full path names that match the pattern.
   *
   * @param pattern The file pattern
   * @return a list of matching files.
   */
  public static List<String> glob(String pattern) {
    File dir;

    ArrayList<String> filenames = new ArrayList<String>();
    if (pattern != null) {
      for (String file_pattern : pattern.split(",")) {
        file_pattern = file_pattern.replaceAll("~", System.getProperty("user.home"));
        if (!file_pattern.startsWith("/")) {
          file_pattern = System.getProperty("user.dir") + "/" + file_pattern;
        }
        file_pattern = file_pattern.substring(1, file_pattern.length());
        dir = new File("/");

        for (String file_name : getFileList(dir, file_pattern))
          filenames.add(file_name);
      }
    }
    return filenames;
  }

  /**
   * Globs a single file from a list of full path names that match the pattern.
   *

   * Throws an error if the pattern matches multiple files.
   *
   * @param pattern The file pattern.
   * @return the matching file
   * @throws edu.cuny.qc.speech.AuToBI.core.AuToBIException if the pattern matches multiple files
   */
  public static String globSingleFile(String pattern) throws AuToBIException {
    if (pattern.contains(",")) {
      throw new AuToBIException("Pattern, " + pattern + ", matches multiple files");
    }

    ArrayList<String> filenames = new ArrayList<String>();
    String file_pattern = pattern.replaceAll("~", System.getProperty("user.home"));
    if (!file_pattern.startsWith("/")) {
      file_pattern = System.getProperty("user.dir") + "/" + file_pattern;
    }
    file_pattern = file_pattern.substring(1, file_pattern.length());
    File dir = new File("/");

    for (String file_name : getFileList(dir, file_pattern))
      filenames.add(file_name);

    if (filenames.size() > 1) {
      throw new AuToBIException("Pattern, " + pattern + ", matches multiple files");
    }
    if (filenames.size() == 0) {
      throw new AuToBIException("Pattern, " + pattern + ", does not match any files");
    }
    return filenames.get(0);
  }

  /**
   * Convert a collection to a string with elements joined by a delimiter.
   *

   * e.g. ["a" "b" "c"] -> "a,b,c"
   *
   * @param collection the collection
   * @param delimiter  the delimiter
   * @return a string containing the elements of the collection
   */
  public static String join(Collection<?> collection, String delimiter) {
    if (collection.isEmpty()) return "";
    Iterator<?> iter = collection.iterator();
    StringBuilder buffer = new StringBuilder(iter.next().toString());
    while (iter.hasNext()) buffer.append(delimiter).append(iter.next().toString());
    return buffer.toString();
  }

  /**
   * Recursively generates the list of files within directory that match the file_pattern
   *
   * @param dir          The directory
   * @param file_pattern The filename pattern
   * @return A list of file names  in the directory that match the patter
   */
  public static List<String> getFileList(File dir, String file_pattern) {
    ArrayList<String> file_names = new ArrayList<String>();
    String[] path_elements = file_pattern.split("/");

    if (path_elements[0].equals(".")) {
      String next_file_pattern = construct_path_string(path_elements);
      file_names.addAll(getFileList(dir, next_file_pattern));
    } else if (path_elements[0].equals("..")) {// traverse up one directory
      String next_file_pattern = construct_path_string(path_elements);
      file_names.addAll(getFileList(dir.getParentFile(), next_file_pattern));
    } else {
      GlobFilenameFilter filter = new GlobFilenameFilter(path_elements[0]);
      File[] files = dir.listFiles((FilenameFilter) filter);
      for (File f : files) {
        if (path_elements.length > 1) {// traverse sub directories
          if (f.exists() && f.isDirectory()) {
            String next_file_pattern = construct_path_string(path_elements);
            file_names.addAll(getFileList(f, next_file_pattern));
          }
        } else {
          if (f.exists()) {
            file_names.add(f.getAbsolutePath());
          }
        }
      }
    }
    return file_names;
  }

  /**
   * Constructs a string representation of a path from an array of path elements
   *

   * e.g.
   *

   * ["" "usr" "local" "bin"] -> "/usr/local/bin"
   *
   * @param path_elements an array of path components
   * @return a string representation of the path
   */
  private static String construct_path_string(String[] path_elements) {
    String next_file_pattern = "";
    for (int i = 1; i < path_elements.length; ++i) {
      next_file_pattern += path_elements[i] + "/";
    }
    next_file_pattern = next_file_pattern.substring(0, next_file_pattern.length() - 1);
    return next_file_pattern;
  }

  /**
   * Parses a feature name into its moniker and paramers.
   *

   * The format of a feature name is moniker[param1,...,paramN], where params can themselves be features
   *
   * @param feature the feature name
   * @return a list containing the moniker followed by its parameters.
   */
  public static List<String> parseFeatureName(String feature) throws AuToBIException {
    if (feature.contains("[") && !feature.endsWith("]")) {
      throw new AuToBIException("Invalid feature name format: " + feature);
    }
    if (feature.replaceAll("\\[", "").length() != feature.replaceAll("\\]", "").length()) {
      throw new AuToBIException("Invalid feature name format: " + feature);
    }

    // Note: I'm sure there's a way to do this with a regular expression, but dealing with
    // matching brackets is frustrating
    ArrayList<String> ret = new ArrayList<String>();
    if (!feature.contains("[")) {
      ret.add(feature);
    } else {
      int openBracket = feature.indexOf('[');
      String moniker = feature.substring(0, openBracket);
      ret.add(moniker);

      // Parameters will keep the final closing bracket to allow the for loop below to recognize the
      // end of string.
      String parameters = feature.substring(openBracket + 1, feature.length());
      if (parameters.length() == 0) {
        throw new AuToBIException("Invalid feature name format: " + feature);
      }
      //ret.add(parameters);
      int start = 0;
      int open = 0;
      int close = 0;
      for (int i = 0; i < parameters.length(); ++i) {
        if (open == close && (parameters.charAt(i) == ',' || parameters.charAt(i) == ']')) {
          String f = parameters.substring(start, i);
          if (f.length() == 0) {
            throw new AuToBIException("Invalid feature name format: " + feature);
          }
          ret.add(f);
          start = i + 1;
        }
        if (parameters.charAt(i) == '[') {
          open++;
        }
        if (parameters.charAt(i) == ']') {
          close++;
        }
      }
    }
    return ret;
  }

  /**
   * Constructs merged hypotheses for phrase ending tones and pitch accents by merging hypotheses from the six detection
   * and classification tasks.
   *
   * @param autobi an AuToBI object to manage the task variables
   * @param words  the words to analyse
   */
  public static void mergeAuToBIHypotheses(AuToBI autobi, List<Word> words) throws AuToBIException {
    // TODO: deprecate this function and move the behavior into smaller utility functions
    // Convert each word to the desired string, one at a time.  Call these utilities from writeTextGridString
    // instead of using this as a pre-processing step.
    for (Word word : words) {
      // Assigns pitch accents to words.  If only accent detection is available, a binary True/False hypothesis
      // will be assigned.  If location and type hypotheses are available, the hypothesized type will be assigned.
      // Finally, if only type information is available, every word will be assigned its best guess for accent type.

      //TODO: make sure this works even if getHypothesizeFeature doesn't have a feature for this.
      if (autobi.getTasks().containsKey("pitch_accent_detection") &&
          word.hasAttribute(autobi.getHypothesizedFeature("pitch_accent_detection"))) {
        if (word.hasAttribute(autobi.getConfidenceFeature("pitch_accent_detection"))) {
          Double conf = (Double) word.getAttribute(autobi.getConfidenceFeature("pitch_accent_detection"));
          if (!word.getAttribute(autobi.getHypothesizedFeature("pitch_accent_detection")).equals("ACCENTED")) {
            conf = 1 - conf;
          }
          word.setAttribute("hyp_pitch_accent", "ACCENTED: " + conf);
        } else {
          word.setAttribute("hyp_pitch_accent", word.getAttribute(autobi.getHypothesizedFeature(
              "pitch_accent_detection")));
        }
      }
      if (autobi.getTasks().containsKey("pitch_accent_classification") &&
          word.hasAttribute(autobi.getHypothesizedFeature("pitch_accent_classification"))) {
        if (!word.hasAttribute("hyp_pitch_accent") || word.getAttribute("hyp_pitch_accent").equals("ACCENTED")) {
          word.setAttribute("hyp_pitch_accent", word.getAttribute(autobi.getHypothesizedFeature(
              "pitch_accent_classification")));
        }
      }

      // Assigns phrase ending tones.
      if (autobi.getTasks().containsKey("intonational_phrase_boundary_detection") &&
          word.hasAttribute(autobi.getHypothesizedFeature("intonational_phrase_boundary_detection"))) {
        if (word.hasAttribute(autobi.getConfidenceFeature("intonational_phrase_boundary_detection"))) {
          Double conf =
              (Double) word.getAttribute(autobi.getConfidenceFeature("intonational_phrase_boundary_detection"));
          if (!word.getAttribute(autobi.getHypothesizedFeature("intonational_phrase_boundary_detection"))
              .equals("INTONATIONAL_BOUNDARY")) {
            conf = 1 - conf;
          }
          word.setAttribute("hyp_phrase_boundary", "BOUNDARY: " + conf);
        } else {
          word.setAttribute("hyp_phrase_boundary",
              word.getAttribute(autobi.getHypothesizedFeature("intonational_phrase_boundary_detection")));
        }
      }

      if (autobi.getTasks().containsKey("intermediate_phrase_boundary_detection") &&
          word.hasAttribute(autobi.getHypothesizedFeature("intermediate_phrase_boundary_detection"))) {
        if (!word.hasAttribute("hyp_phrase_boundary") ||
            word.getAttribute("hyp_phrase_boundary").equals("NONBOUNDARY")) {
          word.setAttribute("hyp_phrase_boundary",
              word.getAttribute(autobi.getHypothesizedFeature("intermediate_phrase_boundary_detection")));
        }
      }

      if (autobi.getTasks().containsKey("phrase_accent_boundary_tone_classification") &&
          word.hasAttribute(autobi.getHypothesizedFeature("phrase_accent_boundary_tone_classification"))) {
        if (!word.hasAttribute("hyp_phrase_boundary") ||
            word.getAttribute("hyp_phrase_boundary").equals("INTONATIONAL_BOUNDARY")) {
          word.setAttribute("hyp_phrase_boundary",
              word.getAttribute(
                  autobi.getHypothesizedFeature("phrase_accent_boundary_tone_classification").replace("x", "%")));
        }
      }

      if (autobi.getTasks().containsKey("phrase_accent_classification") &&
          word.hasAttribute(autobi.getHypothesizedFeature("phrase_accent_classification"))) {
        if (!word.hasAttribute("hyp_phrase_boundary") ||
            word.getAttribute("hyp_phrase_boundary").equals("INTERMEDIATE_BOUNDARY")) {
          word.setAttribute("hyp_phrase_boundary",
              word.getAttribute(autobi.getHypothesizedFeature("phrase_accent_classification")));
        }
      }
    }
  }

  /**
   * Constructs a hash of AuToBITasks associating a task identifier from AuToBIParameters with an AuToBITask describing
   * the necessary FeatureSet and AuToBIClassifier to use in training a classifier for this task.
   *

   * The parameters are:
   *

   * pitch_accent_detector
   *

   * pitch_accent_classifier
   *

   * intonational_phrase_detector
   *

   * intermediate_phrase_detector
   *

   * phrase_accent_classifier
   *

   * phrase_accent_boundary_tone_classifier
   *
   * @param params     AuToBIParameter that hold the parameters for the current execution of AuToBI
   * @param serialized if true, try to read serialized classifiers, else, initialize default classifiers
   * @return a hash associating parameters with AuToBITask objects
   */
  public static HashMap<String, AuToBITask> createTaskListFromParameters(AuToBIParameters params,
                                                                         boolean serialized) {
    HashMap<String, AuToBITask> map = new HashMap<String, AuToBITask>();

    try {
      if (params.hasParameter("pitch_accent_detector")) {
        map.put("pitch_accent_detection",
            getPitchAccentDetectionTask(serialized ? params.getParameter("pitch_accent_detector") : null));
        params.setParameter("pitch_accent_detection",
            params.getParameter("pitch_accent_detector"));
      }
      if (params.hasParameter("pitch_accent_classifier")) {
        map.put("pitch_accent_classification",
            getPitchAccentClassificationTask(serialized ? params.getParameter("pitch_accent_classifier") : null));
        params.setParameter("pitch_accent_classification",
            params.getParameter("pitch_accent_classifier"));
      }
      if (params.hasParameter("intonational_phrase_boundary_detector")) {
        map.put("intonational_phrase_boundary_detection", getIntonationalPhraseDetectionTask(
            serialized ? params.getParameter("intonational_phrase_boundary_detector") : null));
        params.setParameter("intonational_phrase_boundary_detection",
            params.getParameter("intonational_phrase_boundary_detector"));

        // Use rhapsodie specific feature set.
        if (params.booleanParameter("rhapsodie", false)) {
          map.get("intonational_phrase_boundary_detection")
              .setFeatureSet(new RhapIntonationalPhraseBoundaryDetectionFeatureSet());
        }
      }
      if (params.hasParameter("intermediate_phrase_boundary_detector")) {
        map.put("intermediate_phrase_boundary_detection", getIntermediatePhraseDetectionTask(
            serialized ? params.getParameter("intermediate_phrase_boundary_detector") : null));
        params.setParameter("intermediate_phrase_boundary_detection",
            params.getParameter("intermediate_phrase_boundary_detector"));
      }
      if (params.hasParameter("phrase_accent_classifier")) {
        map.put("phrase_accent_classification",
            getPhraseAccentClassificationTask(serialized ? params.getParameter("phrase_accent_classifier") : null));
        params.setParameter("phrase_accent_classification",
            params.getParameter("phrase_accent_classifier"));
      }
      if (params.hasParameter("phrase_accent_boundary_tone_classifier")) {
        map.put("phrase_accent_boundary_tone_classification", getPABTClassificationTask(
            serialized ? params.getParameter("phrase_accent_boundary_tone_classifier") : null));
        params.setParameter("phrase_accent_boundary_tone_classification",
            params.getParameter("phrase_accent_boundary_tone_classifier"));
      }

    } catch (AuToBIException e) {
      AuToBIUtils.error("Unexpected Exception thrown: " + e.getMessage());
    }

    return map;
  }

  /**
   * Gets an AuToBITask containing the standard configuration of featureset, classifier, and true and hypothesized
   * feature name for pitch accent detection.
   *
   * @param filename a serialized filename.  If null, construct a default classifier.
   * @return an appropriate AuToBITask
   */
  public static AuToBITask getPitchAccentDetectionTask(String filename) {
    AuToBITask task = new AuToBITask();
    if (filename != null) {
      task.setClassifier(ClassifierUtils.readAuToBIClassifier(filename));
    } else {
      // Formerly class weighted weka logistic.
      task.setClassifier(new LibLinearClassifier(true));
    }
    String hyp = "hyp_pitch_accent_location";
    task.setHypFeature(hyp);
    task.setConfFeature(hyp + "_conf");
    task.setDistFeature(hyp + "_dist");
    task.setTrueFeature("nominal_PitchAccent");
    task.setFeatureSet(new PitchAccentDetectionFeatureSet());
    return task;
  }

  /**
   * Gets an AuToBITask containing the standard configuration of featureset, classifier, and true and hypothesized
   * feature name for pitch accent classification.
   *
   * @param filename the filename to read a serialized classifier from. if null a default untrained classifier is
   *                 allocated
   * @return an appropriate AuToBITask
   */
  public static AuToBITask getPitchAccentClassificationTask(String filename) {
    AuToBITask task = new AuToBITask();
    if (filename != null) {
      task.setClassifier(ClassifierUtils.readAuToBIClassifier(filename));
    } else {
      // Formerly class weighted weka Ada Boost.
      task.setClassifier(new LibLinearClassifier(SolverType.L2R_LR, false));
    }
    String hyp = "hyp_pitch_accent_type";
    task.setHypFeature(hyp);
    task.setConfFeature(hyp + "_conf");
    task.setDistFeature(hyp + "_dist");
    task.setTrueFeature("nominal_PitchAccentType");
    task.setFeatureSet(new PitchAccentClassificationFeatureSet());
    return task;
  }

  /**
   * Gets an AuToBITask containing the standard configuration of featureset, classifier, and true and hypothesized
   * feature name for intonational phrase boundary detection.
   *
   * @return an appropriate AuToBITask
   */
  public static AuToBITask getIntonationalPhraseDetectionTask(String filename) {
    AuToBITask task = new AuToBITask();
    if (filename != null) {
      task.setClassifier(ClassifierUtils.readAuToBIClassifier(filename));
    } else {
      // Formerly weka logistic
      task.setClassifier(new LibLinearClassifier());
    }
    String hyp = "hyp_intonational_phrase_boundary";
    task.setHypFeature(hyp);
    task.setConfFeature(hyp + "_conf");
    task.setDistFeature(hyp + "_dist");
    task.setTrueFeature("nominal_IntonationalPhraseBoundary");
    task.setFeatureSet(new IntonationalPhraseBoundaryDetectionFeatureSet());
    return task;
  }

  /**
   * Gets an AuToBITask containing the standard configuration of featureset, classifier, and true and hypothesized
   * feature name for intermediate phrase boundary detection.
   *
   * @return an appropriate AuToBITask
   */
  public static AuToBITask getIntermediatePhraseDetectionTask(String filename) {
    AuToBITask task = new AuToBITask();
    if (filename != null) {
      task.setClassifier(ClassifierUtils.readAuToBIClassifier(filename));
    } else {
      // Formerly class weighted weka logistic
      task.setClassifier(new LibLinearClassifier());
    }
    String hyp = "hyp_intermediate_phrase_boundary";
    task.setHypFeature(hyp);
    task.setConfFeature(hyp + "_conf");
    task.setDistFeature(hyp + "_dist");
    task.setTrueFeature("nominal_IntermediatePhraseBoundary");
    task.setFeatureSet(new IntermediatePhraseBoundaryDetectionFeatureSet());
    return task;
  }

  /**
   * Gets an AuToBITask containing the standard configuration of featureset, classifier, and true and hypothesized
   * feature name for phrase accent classification.
   *
   * @return an appropriate AuToBITask
   */
  public static AuToBITask getPhraseAccentClassificationTask(String filename) {
    AuToBITask task = new AuToBITask();
    if (filename != null) {
      task.setClassifier(ClassifierUtils.readAuToBIClassifier(filename));
    } else {
      // formerly weka class weighted random forest
      task.setClassifier(new LibLinearClassifier());
    }
    String hyp = "hyp_phrase_accent";
    task.setHypFeature(hyp);
    task.setConfFeature(hyp + "_conf");
    task.setDistFeature(hyp + "_dist");
    task.setTrueFeature("nominal_PhraseAccent");
    task.setFeatureSet(new PhraseAccentClassificationFeatureSet());
    return task;
  }

  /**
   * Gets an AuToBITask containing the standard configuration of featureset, classifier, and true and hypothesized
   * feature name for classification of phrase accent boundary tone pairs.
   *
   * @return an appropriate AuToBITask
   */
  public static AuToBITask getPABTClassificationTask(String filename) {
    AuToBITask task = new AuToBITask();
    if (filename != null) {
      task.setClassifier(ClassifierUtils.readAuToBIClassifier(filename));
    } else {
      // formerly weka random forest
      task.setClassifier(new LibLinearClassifier());
    }
    String hyp = "hyp_phrase_accent_boundary_tone";
    task.setHypFeature(hyp);
    task.setConfFeature(hyp + "_conf");
    task.setDistFeature(hyp + "_dist");
    task.setTrueFeature("nominal_PhraseAccentBoundaryTone");
    task.setFeatureSet(new PhraseAccentBoundaryToneClassificationFeatureSet());
    return task;
  }

  /**
   * Makes an AuToBI feature name from String parameters.
   *

   * This is a utility function to support loops over feature types and and names.
   *

   * makeFeatureName("f0") = "f0"
   * makeFeatureName("log", "f0") = "log[f0]"
   * makeFeatureName("minus", "A", "B") = "minus[A,B]"
   *
   * @param params the parameters
   * @return an AuToBI formatted set of feature names.
   */
  public static String makeFeatureName(String... params) {
    if (params.length == 0) {
      return "";
    }
    if (params.length == 1) {
      return params[0];
    }

    // This allows the coherence of makeFeatureName("log", "f0) and makeFeatureName("", "f0")
    if (params.length == 2 && params[0].isEmpty()) {
      return params[1];
    }

    StringBuilder sb = new StringBuilder(params[0]);
    sb.append("[");
    for (int i = 1; i < params.length; ++i) {
      if (i > 1) {
        sb.append(',');
      }
      sb.append(params[i]);
    }
    sb.append("]");
    return sb.toString();
  }
}


text:
#include <aws/migrationhuborchestrator/model/CreateWorkflowRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

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

CreateWorkflowRequest::CreateWorkflowRequest() :
    m_nameHasBeenSet(false),
    m_descriptionHasBeenSet(false),
    m_templateIdHasBeenSet(false),
    m_applicationConfigurationIdHasBeenSet(false),
    m_inputParametersHasBeenSet(false),
    m_stepTargetsHasBeenSet(false),
    m_tagsHasBeenSet(false)
{
}

Aws::String CreateWorkflowRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_nameHasBeenSet)
  {
   payload.WithString("name", m_name);

  }

  if(m_descriptionHasBeenSet)
  {
   payload.WithString("description", m_description);

  }

  if(m_templateIdHasBeenSet)
  {
   payload.WithString("templateId", m_templateId);

  }

  if(m_applicationConfigurationIdHasBeenSet)
  {
   payload.WithString("applicationConfigurationId", m_applicationConfigurationId);

  }

  if(m_inputParametersHasBeenSet)
  {
   JsonValue inputParametersJsonMap;
   for(auto& inputParametersItem : m_inputParameters)
   {
     inputParametersJsonMap.WithObject(inputParametersItem.first, inputParametersItem.second.Jsonize());
   }
   payload.WithObject("inputParameters", std::move(inputParametersJsonMap));

  }

  if(m_stepTargetsHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> stepTargetsJsonList(m_stepTargets.size());
   for(unsigned stepTargetsIndex = 0; stepTargetsIndex < stepTargetsJsonList.GetLength(); ++stepTargetsIndex)
   {
     stepTargetsJsonList[stepTargetsIndex].AsString(m_stepTargets[stepTargetsIndex]);
   }
   payload.WithArray("stepTargets", std::move(stepTargetsJsonList));

  }

  if(m_tagsHasBeenSet)
  {
   JsonValue tagsJsonMap;
   for(auto& tagsItem : m_tags)
   {
     tagsJsonMap.WithString(tagsItem.first, tagsItem.second);
   }
   payload.WithObject("tags", std::move(tagsJsonMap));

  }

  return payload.View().WriteReadable();
}


text:
package meritorder.messages;

import akka.basicMessages.AnswerContent;

public class Offer implements AnswerContent{

	public String type = "Offer";
	public Accepted accepted = Accepted.none;
	public double price;
	public double volume;

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>AC2000TrajectorySchemeWithDrift</title>
<meta name="date" content="2016-10-06">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.drip.execution.generator

Class AC2000TrajectorySchemeWithDrift

java.lang.Object

org.drip.execution.generator.OptimalTrajectoryScheme

org.drip.execution.generator.AC2000TrajectorySchemeWithDrift

public class AC2000TrajectorySchemeWithDrift
extends OptimalTrajectoryScheme

AC2000TrajectorySchemeWithDrift generates the Trade/Holdings List of Optimal Execution Schedule for the
  Equally Spaced Trading Intervals based on the Linear Impact Evolution Walk Parameters with Drift
  specified. The References are:

        - Almgren, R., and N. Chriss (1999): Value under Liquidation, Risk 12 (12).

        - Almgren, R., and N. Chriss (2000): Optimal Execution of Portfolio Transactions, Journal of Risk 3 (2)
                5-39.

        - Bertsimas, D., and A. W. Lo (1998): Optimal Control of Execution Costs, Journal of Financial Markets,
                1, 1-50.

        - Chan, L. K. C., and J. Lakonishak (1995): The Behavior of Stock Prices around Institutional Trades,
                Journal of Finance, 50, 1147-1174.

        - Keim, D. B., and A. Madhavan (1997): Transaction Costs and Investment Style: An Inter-exchange
                Analysis of Institutional Equity Trades, Journal of Financial Economics, 46, 265-292.

Author:

Lakshmi Krishnamurthy

Method Summary

All Methods Static Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

EfficientTradingTrajectory
generate()

Invoke the Optimizer, and generate/return the Optimal Trading Trajectory Instance

static AC2000TrajectorySchemeWithDrift
Standard(double dblStartHoldings,
        double dblFinishTime,
        int iNumInterval,
        LinearExpectationParameters lep,
        double dblRiskAversion)

Create the Standard AC2000TrajectorySchemeWithDrift Instance

Methods inherited from class org.drip.execution.generator.OptimalTrajectoryScheme

control, objectiveUtility, priceWalkParameters

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

Standard

public static final AC2000TrajectorySchemeWithDrift Standard(double dblStartHoldings,
                                                             double dblFinishTime,
                                                             int iNumInterval,
                                                             LinearExpectationParameters lep,
                                                             double dblRiskAversion)

Create the Standard AC2000TrajectorySchemeWithDrift Instance

Parameters:

dblStartHoldings - Trajectory Start Holdings

dblFinishTime - Trajectory Finish Time

iNumInterval - The Number of Fixed Intervals

lep - Linear Impact Price Walk Parameters

dblRiskAversion - The Risk Aversion Parameter

Returns:

The AC2000TrajectorySchemeWithDrift Instance

generate

public EfficientTradingTrajectory generate()

Description copied from class: OptimalTrajectoryScheme

Invoke the Optimizer, and generate/return the Optimal Trading Trajectory Instance

Overrides:

generate in class OptimalTrajectoryScheme

Returns:

The Optimal Trading Trajectory Instance

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
@implementation LQYQuickLoginButton

- (void)awakeFromNib
{
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    // 图片的frame
    self.imageView.y = 0;
    self.imageView.centerX = self.width * 0.5;

    // w文字的 fram
    self.titleLabel.x = 0;
    self.titleLabel.y = self.imageView.height;
    self.titleLabel.width = self.width;
    self.titleLabel.height = self.height - self.imageView.y;

}
@end