text:
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using FluentAssertions;
using JsonApiDotNetCore.Serialization.Objects;
using Microsoft.EntityFrameworkCore;
using TestBuildingBlocks;
using Xunit;

namespace JsonApiDotNetCoreTests.IntegrationTests.ReadWrite.Updating.Relationships
{
    public sealed class UpdateToOneRelationshipTests : IClassFixture<IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext>>
    {
        private readonly IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> _testContext;
        private readonly ReadWriteFakers _fakers = new();

        public UpdateToOneRelationshipTests(IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> testContext)
        {
            _testContext = testContext;

            testContext.UseController<WorkItemsController>();
            testContext.UseController<WorkItemGroupsController>();
            testContext.UseController<RgbColorsController>();
        }

        [Fact]
        public async Task Can_clear_ManyToOne_relationship()
        {
            // Arrange
            WorkItem existingWorkItem = _fakers.WorkItem.Generate();
            existingWorkItem.Assignee = _fakers.UserAccount.Generate();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                dbContext.WorkItems.Add(existingWorkItem);
                await dbContext.SaveChangesAsync();
            });

            var requestBody = new
            {
                data = (object)null
            };

            string route = $"/workItems/{existingWorkItem.StringId}/relationships/assignee";

            // Act
            (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody);

            // Assert
            httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);

            responseDocument.Should().BeEmpty();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Assignee).FirstWithIdAsync(existingWorkItem.Id);

                workItemInDatabase.Assignee.Should().BeNull();
            });
        }

        [Fact]
        public async Task Can_clear_OneToOne_relationship()
        {
            // Arrange
            WorkItemGroup existingGroup = _fakers.WorkItemGroup.Generate();
            existingGroup.Color = _fakers.RgbColor.Generate();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                dbContext.Groups.AddRange(existingGroup);
                await dbContext.SaveChangesAsync();
            });

            var requestBody = new
            {
                data = (object)null
            };

            string route = $"/workItemGroups/{existingGroup.StringId}/relationships/color";

            // Act
            (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody);

            // Assert
            httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);

            responseDocument.Should().BeEmpty();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                WorkItemGroup groupInDatabase = await dbContext.Groups.Include(group => group.Color).FirstWithIdOrDefaultAsync(existingGroup.Id);

                groupInDatabase.Color.Should().BeNull();
            });
        }

        [Fact]
        public async Task Can_create_OneToOne_relationship_from_dependent_side()
        {
            // Arrange
            WorkItemGroup existingGroup = _fakers.WorkItemGroup.Generate();
            existingGroup.Color = _fakers.RgbColor.Generate();

            RgbColor existingColor = _fakers.RgbColor.Generate();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                dbContext.AddInRange(existingGroup, existingColor);
                await dbContext.SaveChangesAsync();
            });

            var requestBody = new
            {
                data = new
                {
                    type = "workItemGroups",
                    id = existingGroup.StringId
                }
            };

            string route = $"/rgbColors/{existingColor.StringId}/relationships/group";

            // Act
            (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody);

            // Assert
            httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);

            responseDocument.Should().BeEmpty();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                List<RgbColor> colorsInDatabase = await dbContext.RgbColors.Include(rgbColor => rgbColor.Group).ToListAsync();

                RgbColor colorInDatabase1 = colorsInDatabase.Single(color => color.Id == existingGroup.Color.Id);
                colorInDatabase1.Group.Should().BeNull();

                RgbColor colorInDatabase2 = colorsInDatabase.Single(color => color.Id == existingColor.Id);
                colorInDatabase2.Group.Should().NotBeNull();
                colorInDatabase2.Group.Id.Should().Be(existingGroup.Id);
            });
        }

        [Fact]
        public async Task Can_replace_OneToOne_relationship_from_principal_side()
        {
            // Arrange
            List<WorkItemGroup> existingGroups = _fakers.WorkItemGroup.Generate(2);
            existingGroups[0].Color = _fakers.RgbColor.Generate();
            existingGroups[1].Color = _fakers.RgbColor.Generate();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                dbContext.Groups.AddRange(existingGroups);
                await dbContext.SaveChangesAsync();
            });

            var requestBody = new
            {
                data = new
                {
                    type = "rgbColors",
                    id = existingGroups[0].Color.StringId
                }
            };

            string route = $"/workItemGroups/{existingGroups[1].StringId}/relationships/color";

            // Act
            (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody);

            httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);

            responseDocument.Should().BeEmpty();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                List<WorkItemGroup> groupsInDatabase = await dbContext.Groups.Include(group => group.Color).ToListAsync();

                WorkItemGroup groupInDatabase1 = groupsInDatabase.Single(group => group.Id == existingGroups[0].Id);
                groupInDatabase1.Color.Should().BeNull();

                WorkItemGroup groupInDatabase2 = groupsInDatabase.Single(group => group.Id == existingGroups[1].Id);
                groupInDatabase2.Color.Should().NotBeNull();
                groupInDatabase2.Color.Id.Should().Be(existingGroups[0].Color.Id);

                List<RgbColor> colorsInDatabase = await dbContext.RgbColors.Include(color => color.Group).ToListAsync();

                RgbColor colorInDatabase1 = colorsInDatabase.Single(color => color.Id == existingGroups[0].Color.Id);
                colorInDatabase1.Group.Should().NotBeNull();
                colorInDatabase1.Group.Id.Should().Be(existingGroups[1].Id);

                RgbColor colorInDatabase2 = colorsInDatabase.SingleOrDefault(color => color.Id == existingGroups[1].Color.Id);
                colorInDatabase1.Should().NotBeNull();
                colorInDatabase2!.Group.Should().BeNull();
            });
        }

        [Fact]
        public async Task Can_replace_ManyToOne_relationship()
        {
            // Arrange
            List<UserAccount> existingUserAccounts = _fakers.UserAccount.Generate(2);
            existingUserAccounts[0].AssignedItems = _fakers.WorkItem.Generate(2).ToHashSet();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                dbContext.UserAccounts.AddRange(existingUserAccounts);
                await dbContext.SaveChangesAsync();
            });

            var requestBody = new
            {
                data = new
                {
                    type = "userAccounts",
                    id = existingUserAccounts[1].StringId
                }
            };

            string route = $"/workItems/{existingUserAccounts[0].AssignedItems.ElementAt(1).StringId}/relationships/assignee";

            // Act
            (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody);

            httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);

            responseDocument.Should().BeEmpty();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                int workItemId = existingUserAccounts[0].AssignedItems.ElementAt(1).Id;

                WorkItem workItemInDatabase2 = await dbContext.WorkItems.Include(workItem => workItem.Assignee).FirstWithIdAsync(workItemId);

                workItemInDatabase2.Assignee.Should().NotBeNull();
                workItemInDatabase2.Assignee.Id.Should().Be(existingUserAccounts[1].Id);
            });
        }

        [Fact]
        public async Task Cannot_replace_for_missing_request_body()
        {
            // Arrange
            WorkItem existingWorkItem = _fakers.WorkItem.Generate();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                dbContext.WorkItems.Add(existingWorkItem);
                await dbContext.SaveChangesAsync();
            });

            string requestBody = string.Empty;

            string route = $"/workItems/{existingWorkItem.StringId}/relationships/assignee";

            // Act
            (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);

            // Assert
            httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest);

            responseDocument.Errors.Should().HaveCount(1);

            ErrorObject error = responseDocument.Errors[0];
            error.StatusCode.Should().Be(HttpStatusCode.BadRequest);
            error.Title.Should().Be("Missing request body.");
            error.Detail.Should().BeNull();
        }

        [Fact]
        public async Task Cannot_create_for_missing_type()
        {
            // Arrange
            WorkItem existingWorkItem = _fakers.WorkItem.Generate();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                dbContext.WorkItems.Add(existingWorkItem);
                await dbContext.SaveChangesAsync();
            });

            var requestBody = new
            {
                data = new
                {
                    id = Unknown.StringId.For<UserAccount, long>()
                }
            };

            string route = $"/workItems/{existingWorkItem.StringId}/relationships/assignee";

            // Act
            (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);

            // Assert
            httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);

            responseDocument.Errors.Should().HaveCount(1);

            ErrorObject error = responseDocument.Errors[0];
            error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
            error.Title.Should().Be("Failed to deserialize request body: Request body must include 'type' element.");
            error.Detail.Should().StartWith("Expected 'type' element in 'data' element. - Request body: <<");
        }

        [Fact]
        public async Task Cannot_create_for_unknown_type()
        {
            // Arrange
            WorkItem existingWorkItem = _fakers.WorkItem.Generate();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                dbContext.WorkItems.Add(existingWorkItem);
                await dbContext.SaveChangesAsync();
            });

            var requestBody = new
            {
                data = new
                {
                    type = Unknown.ResourceType,
                    id = Unknown.StringId.For<UserAccount, long>()
                }
            };

            string route = $"/workItems/{existingWorkItem.StringId}/relationships/assignee";

            // Act
            (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);

            // Assert
            httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);

            responseDocument.Errors.Should().HaveCount(1);

            ErrorObject error = responseDocument.Errors[0];
            error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
            error.Title.Should().Be("Failed to deserialize request body: Request body includes unknown resource type.");
            error.Detail.Should().StartWith($"Resource type '{Unknown.ResourceType}' does not exist. - Request body: <<");
        }

        [Fact]
        public async Task Cannot_create_for_missing_ID()
        {
            // Arrange
            WorkItem existingWorkItem = _fakers.WorkItem.Generate();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                dbContext.WorkItems.Add(existingWorkItem);
                await dbContext.SaveChangesAsync();
            });

            var requestBody = new
            {
                data = new
                {
                    type = "userAccounts"
                }
            };

            string route = $"/workItems/{existingWorkItem.StringId}/relationships/assignee";

            // Act
            (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);

            // Assert
            httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);

            responseDocument.Errors.Should().HaveCount(1);

            ErrorObject error = responseDocument.Errors[0];
            error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
            error.Title.Should().Be("Failed to deserialize request body: Request body must include 'id' element.");
            error.Detail.Should().StartWith("Request body: <<");
        }

        [Fact]
        public async Task Cannot_create_with_unknown_ID()
        {
            // Arrange
            WorkItem existingWorkItem = _fakers.WorkItem.Generate();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                dbContext.WorkItems.Add(existingWorkItem);
                await dbContext.SaveChangesAsync();
            });

            string userAccountId = Unknown.StringId.For<UserAccount, long>();

            var requestBody = new
            {
                data = new
                {
                    type = "userAccounts",
                    id = userAccountId
                }
            };

            string route = $"/workItems/{existingWorkItem.StringId}/relationships/assignee";

            // Act
            (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);

            // Assert
            httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound);

            responseDocument.Errors.Should().HaveCount(1);

            ErrorObject error = responseDocument.Errors[0];
            error.StatusCode.Should().Be(HttpStatusCode.NotFound);
            error.Title.Should().Be("A related resource does not exist.");
            error.Detail.Should().Be($"Related resource of type 'userAccounts' with ID '{userAccountId}' in relationship 'assignee' does not exist.");
        }

        [Fact]
        public async Task Cannot_create_on_unknown_resource_type_in_url()
        {
            // Arrange
            WorkItem existingWorkItem = _fakers.WorkItem.Generate();
            UserAccount existingUserAccount = _fakers.UserAccount.Generate();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                dbContext.AddInRange(existingWorkItem, existingUserAccount);
                await dbContext.SaveChangesAsync();
            });

            var requestBody = new
            {
                data = new
                {
                    type = "userAccounts",
                    id = existingUserAccount.StringId
                }
            };

            string route = $"/{Unknown.ResourceType}/{existingWorkItem.StringId}/relationships/assignee";

            // Act
            (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody);

            // Assert
            httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound);

            responseDocument.Should().BeEmpty();
        }

        [Fact]
        public async Task Cannot_create_on_unknown_resource_ID_in_url()
        {
            // Arrange
            UserAccount existingUserAccount = _fakers.UserAccount.Generate();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                dbContext.UserAccounts.Add(existingUserAccount);
                await dbContext.SaveChangesAsync();
            });

            var requestBody = new
            {
                data = new
                {
                    type = "userAccounts",
                    id = existingUserAccount.StringId
                }
            };

            string workItemId = Unknown.StringId.For<WorkItem, int>();

            string route = $"/workItems/{workItemId}/relationships/assignee";

            // Act
            (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);

            // Assert
            httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound);

            responseDocument.Errors.Should().HaveCount(1);

            ErrorObject error = responseDocument.Errors[0];
            error.StatusCode.Should().Be(HttpStatusCode.NotFound);
            error.Title.Should().Be("The requested resource does not exist.");
            error.Detail.Should().Be($"Resource of type 'workItems' with ID '{workItemId}' does not exist.");
        }

        [Fact]
        public async Task Cannot_create_on_unknown_relationship_in_url()
        {
            // Arrange
            WorkItem existingWorkItem = _fakers.WorkItem.Generate();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                dbContext.WorkItems.Add(existingWorkItem);
                await dbContext.SaveChangesAsync();
            });

            var requestBody = new
            {
                data = new
                {
                    type = "userAccounts",
                    id = Unknown.StringId.For<UserAccount, long>()
                }
            };

            string route = $"/workItems/{existingWorkItem.StringId}/relationships/{Unknown.Relationship}";

            // Act
            (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);

            // Assert
            httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound);

            responseDocument.Errors.Should().HaveCount(1);

            ErrorObject error = responseDocument.Errors[0];
            error.StatusCode.Should().Be(HttpStatusCode.NotFound);
            error.Title.Should().Be("The requested relationship does not exist.");
            error.Detail.Should().Be($"Resource of type 'workItems' does not contain a relationship named '{Unknown.Relationship}'.");
        }

        [Fact]
        public async Task Cannot_create_on_relationship_mismatch_between_url_and_body()
        {
            // Arrange
            WorkItem existingWorkItem = _fakers.WorkItem.Generate();
            RgbColor existingColor = _fakers.RgbColor.Generate();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                dbContext.AddInRange(existingWorkItem, existingColor);
                await dbContext.SaveChangesAsync();
            });

            var requestBody = new
            {
                data = new
                {
                    type = "rgbColors",
                    id = existingColor.StringId
                }
            };

            string route = $"/workItems/{existingWorkItem.StringId}/relationships/assignee";

            // Act
            (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);

            // Assert
            httpResponse.Should().HaveStatusCode(HttpStatusCode.Conflict);

            responseDocument.Errors.Should().HaveCount(1);

            ErrorObject error = responseDocument.Errors[0];
            error.StatusCode.Should().Be(HttpStatusCode.Conflict);
            error.Title.Should().Be("Resource type mismatch between request body and endpoint URL.");

            error.Detail.Should().Be("Expected resource of type 'userAccounts' in PATCH request body at endpoint " +
                $"'/workItems/{existingWorkItem.StringId}/relationships/assignee', instead of 'rgbColors'.");
        }

        [Fact]
        public async Task Cannot_create_with_data_array_in_relationship()
        {
            // Arrange
            WorkItem existingWorkItem = _fakers.WorkItem.Generate();
            UserAccount existingUserAccount = _fakers.UserAccount.Generate();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                dbContext.AddInRange(existingWorkItem, existingUserAccount);
                await dbContext.SaveChangesAsync();
            });

            var requestBody = new
            {
                data = new[]
                {
                    new
                    {
                        type = "userAccounts",
                        id = existingUserAccount.StringId
                    }
                }
            };

            string route = $"/workItems/{existingWorkItem.StringId}/relationships/assignee";

            // Act
            (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);

            // Assert
            httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);

            responseDocument.Errors.Should().HaveCount(1);

            ErrorObject error = responseDocument.Errors[0];
            error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
            error.Title.Should().Be("Failed to deserialize request body: Expected single data element for to-one relationship.");
            error.Detail.Should().StartWith("Expected single data element for 'assignee' relationship. - Request body: <<");
        }

        [Fact]
        public async Task Can_clear_cyclic_relationship()
        {
            // Arrange
            WorkItem existingWorkItem = _fakers.WorkItem.Generate();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                dbContext.WorkItems.Add(existingWorkItem);
                await dbContext.SaveChangesAsync();

                existingWorkItem.Parent = existingWorkItem;
                await dbContext.SaveChangesAsync();
            });

            var requestBody = new
            {
                data = (object)null
            };

            string route = $"/workItems/{existingWorkItem.StringId}/relationships/parent";

            // Act
            (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody);

            // Assert
            httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);

            responseDocument.Should().BeEmpty();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Parent).FirstWithIdAsync(existingWorkItem.Id);

                workItemInDatabase.Parent.Should().BeNull();
            });
        }

        [Fact]
        public async Task Can_assign_cyclic_relationship()
        {
            // Arrange
            WorkItem existingWorkItem = _fakers.WorkItem.Generate();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                dbContext.WorkItems.Add(existingWorkItem);
                await dbContext.SaveChangesAsync();
            });

            var requestBody = new
            {
                data = new
                {
                    type = "workItems",
                    id = existingWorkItem.StringId
                }
            };

            string route = $"/workItems/{existingWorkItem.StringId}/relationships/parent";

            // Act
            (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody);

            // Assert
            httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);

            responseDocument.Should().BeEmpty();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                WorkItem workItemInDatabase = await dbContext.WorkItems.Include(workItem => workItem.Parent).FirstWithIdAsync(existingWorkItem.Id);

                workItemInDatabase.Parent.Should().NotBeNull();
                workItemInDatabase.Parent.Id.Should().Be(existingWorkItem.Id);
            });
        }
    }
}


text:
Phidgets Devices
================

Phidgets devices connect by USB (some connect via an InterfaceKit which is
itself connected by USB).

The Phidgets Drivers need to be installed - see doc/Installation - Phidgets

Use the protocols.phidgets.Phidget connection, which accepts the phidget
device ID as a parameter. N.B. You can use the Phidgets Control Panel software
(for windows, downloadable from phidgets.com) to determine the ID for each
device.

```python
connection = Phidget(1005)
```

For devices that connect via an InterfaceKit, use the `InterfaceKit.input()`,
`InterfaceKit.output()` and `InterfaceKit.sensor()` methods to get connection
objects.

```python
ifk = phidgets.InterfaceKit(Phidget(1005))
device = phidgets.PHSensor(ifk.sensor(2))
```

InterfaceKit
============

```python
phidgets.InterfaceKit(Phidget(id))
```

Methods
-------

 *	`input(id)`

	Access a connection to digital input `id`. The connection object has a
	method, `state()` that returns the input state.

 *	`output(id)`

	Access a connection to digital output `id`. The connection object has
	two methods: `state` returns the output state, and `set` which changes
	it.

 *	`sensor(positions)`

	Access a connection to analogue sensor `id`. The connection object has a
	method, `value()` that returns the current voltage detected by the sensor.

TemperatureSensor
=================

Tested with the four-thermocouple device.

```python
phidgets.TemperatureSensor(connection, inputs)
```

`inputs` is a list of the connected thermocouples:

```python
inputs = [{
	"index":      0,    # Which position the thermocouple is connected to (0-3).
	"type":       type, # What sort of thermocouple is attached.
	"min_change": 0.5,  # Minimum temperature change to record (default 0.5 deg).
}]
```

`type` can be a member of `phidgets.ThermocoupleType`:

 *  `phidgets.ThermocoupleType.E` (E-type)
 *  `phidgets.ThermocoupleType.J` (J-type)
 *  `phidgets.ThermocoupleType.K` (K-type)
 *  `phidgets.ThermocoupleType.T` (T-type)

TemperatureSensor is created with an list of attached thermocouples:

`TemperatureSensor.thermocouples[...]`

Each themocouple object has a `temperature` property (r, float) with units
degree C.

PHSensor
========

Only tested with USB model.

```python
phidgets.PHSensor(connection, min_change)
```

`min_change` is the minimum pH change that will be registered. Default: 0.5.

Properties
----------

 *	`temperature` (rw, float)

	Current temperature at probe (degree C).

 *	`ph` (r, float)

	The current measured pH value.

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"os"
	"path/filepath"
	"time"

	"github.com/cloudfoundry/dotnet-core-buildpack/src/dotnetcore/config"
	_ "github.com/cloudfoundry/dotnet-core-buildpack/src/dotnetcore/hooks"
	"github.com/cloudfoundry/dotnet-core-buildpack/src/dotnetcore/project"
	"github.com/cloudfoundry/dotnet-core-buildpack/src/dotnetcore/supply"

	"github.com/cloudfoundry/libbuildpack"
)

func main() {

	logger := libbuildpack.NewLogger(os.Stdout)

	buildpackDir, err := libbuildpack.GetBuildpackDir()
	if err != nil {
		logger.Error("Unable to determine buildpack directory: %s", err.Error())
		os.Exit(9)
	}

	manifest, err := libbuildpack.NewManifest(buildpackDir, logger, time.Now())
	if err != nil {
		logger.Error("Unable to load buildpack manifest: %s", err.Error())
		os.Exit(10)
	}
	installer := libbuildpack.NewInstaller(manifest)

	stager := libbuildpack.NewStager(os.Args[1:], logger, manifest)
	if err := stager.CheckBuildpackValid(); err != nil {
		os.Exit(11)
	}

	if err = installer.SetAppCacheDir(stager.CacheDir()); err != nil {
		logger.Error("Unable to setup appcache: %s", err)
		os.Exit(18)
	}

	if err = manifest.ApplyOverride(stager.DepsDir()); err != nil {
		logger.Error("Unable to apply override.yml files: %s", err)
		os.Exit(17)
	}

	err = libbuildpack.RunBeforeCompile(stager)
	if err != nil {
		logger.Error("Before Compile: %s", err.Error())
		os.Exit(12)
	}

	if err := os.MkdirAll(filepath.Join(stager.DepDir(), "bin"), 0755); err != nil {
		logger.Error("Unable to create bin directory: %s", err.Error())
		os.Exit(13)
	}

	err = stager.SetStagingEnvironment()
	if err != nil {
		logger.Error("Unable to setup environment variables: %s", err.Error())
		os.Exit(14)
	}

	cfg := &config.Config{}

	s := supply.Supplier{
		Stager:    stager,
		Installer: installer,
		Manifest:  manifest,
		Log:       logger,
		Command:   &libbuildpack.Command{},
		Config:    cfg,
		Project:   project.New(stager.BuildDir(), stager.DepDir(), stager.DepsIdx(), manifest, installer, logger),
	}

	err = supply.Run(&s)
	if err != nil {
		os.Exit(15)
	}

	if err := stager.WriteConfigYml(cfg); err != nil {
		logger.Error("Error writing config.yml: %s", err.Error())
		os.Exit(16)
	}
	if err = installer.CleanupAppCache(); err != nil {
		logger.Error("Unable to clean up app cache: %s", err)
		os.Exit(19)
	}
}


text:
"""Database module, including the SQLAlchemy database object and DB-related
utilities.
"""

from sqlalchemy.orm import relationship

from debut.extensions import db

# Export aliases for common SQLAlchemy names.
Column = db.Column
relationship = relationship

class CRUDMixin(object):  # TODO: Evaluate whether to keep or not.

    """Mixin that adds convenience methods for CRUD.

    Create, read, update, delete operations.
    """

    @classmethod
    def create(cls, **kwargs):
        """Create a new record and save it the database."""
        instance = cls(**kwargs)
        return instance.save()

    def update(self, commit=True, **kwargs):
        """Update specific fields of a record."""
        for attr, value in kwargs.iteritems():
            setattr(self, attr, value)
        return commit and self.save() or self

    def save(self, commit=True):
        """Save the record."""
        db.session.add(self)
        if commit:
            db.session.commit()
        return self

    def delete(self, commit=True):
        """Remove the record from the database."""
        db.session.delete(self)
        return commit and db.session.commit()


text:
import os
import sys
import shutil
import logging
import importlib

import django
from django.core.management import call_command, find_commands, load_command_class
from django.test import TestCase
from django.utils.six import StringIO, PY3

from django_extensions.management.modelviz import use_model, generate_graph_data
from . import force_color_support

class MockLoggingHandler(logging.Handler):
    """ Mock logging handler to check for expected logs. """

    def __init__(self, *args, **kwargs):
        self.reset()
        logging.Handler.__init__(self, *args, **kwargs)

    def emit(self, record):
        self.messages[record.levelname.lower()].append(record.getMessage())

    def reset(self):
        self.messages = {
            'debug': [],
            'info': [],
            'warning': [],
            'error': [],
            'critical': [],
        }

class CommandTest(TestCase):
    def test_error_logging(self):
        # Ensure command errors are properly logged and reraised
        from django_extensions.management.base import logger
        logger.addHandler(MockLoggingHandler())
        module_path = "tests.management.commands.error_raising_command"
        module = importlib.import_module(module_path)
        error_raising_command = module.Command()
        self.assertRaises(Exception, error_raising_command.execute)
        handler = logger.handlers[0]
        self.assertEqual(len(handler.messages['error']), 1)

class ShowTemplateTagsTests(TestCase):
    def test_some_output(self):
        out = StringIO()
        call_command('show_template_tags', stdout=out)
        output = out.getvalue()
        # Once django_extension is installed during tests it should appear with
        # its templatetags
        self.assertIn('django_extensions', output)
        # let's check at least one
        self.assertIn('truncate_letters', output)

class CreateAppTests(TestCase):
    def test_command(self):
        if django.VERSION[:2] >= (1, 10):
            return

        tmpname = "testapptest"
        # TODO better temp dir handling
        tmpdir = "/tmp"
        tmppath = os.path.join(tmpdir, tmpname)
        self.assertFalse(os.path.isdir(tmppath))

        out = StringIO()
        try:
            call_command('create_app', tmpname, parent_path=tmpdir, stdout=out)
        finally:
            if os.path.isdir(tmppath):
                shutil.rmtree(tmppath)

        output = out.getvalue()
        self.assertIn("Application '%s' created." % tmpname, output)

class AdminGeneratorTests(TestCase):
    def test_command(self):
        out = StringIO()
        call_command('admin_generator', 'django_extensions', stdout=out)
        output = out.getvalue()
        self.assertIn("class SecretAdmin(admin.ModelAdmin):", output)
        if PY3:
            self.assertIn("list_display = ('id', 'name', 'text')", output)
            self.assertIn("search_fields = ('name',)", output)
        else:
            self.assertIn("list_display = (u'id', u'name', u'text')", output)
            self.assertIn("search_fields = (u'name',)", output)

class DescribeFormTests(TestCase):
    def test_command(self):
        out = StringIO()
        call_command('describe_form', 'django_extensions.Secret', stdout=out)
        output = out.getvalue()
        self.assertIn("class SecretForm(forms.Form):", output)
        self.assertRegexpMatches(output, "name = forms.CharField\(.*max_length=255")
        self.assertRegexpMatches(output, "name = forms.CharField\(.*required=False")
        self.assertRegexpMatches(output, "name = forms.CharField\(.*label=u?'Name'")
        self.assertRegexpMatches(output, "text = forms.CharField\(.*required=False")
        self.assertRegexpMatches(output, "text = forms.CharField\(.*label=u?'Text'")

class UpdatePermissionsTests(TestCase):
    def test_works(self):
        from django.db import models

        class PermModel(models.Model):
            class Meta:
                app_label = 'django_extensions'
                permissions = (('test_permission', 'test_permission'),)

        original_stdout = sys.stdout
        out = sys.stdout = StringIO()
        call_command('update_permissions', stdout=out, verbosity=3)
        sys.stdout = original_stdout
        self.assertIn("Can change perm model", out.getvalue())

class CommandSignalTests(TestCase):
    pre = None
    post = None

    def test_works(self):
        from django_extensions.management.signals import post_command, \
            pre_command
        from django_extensions.management.commands.show_template_tags import \
            Command

        def pre(sender, **kwargs):
            CommandSignalTests.pre = dict(**kwargs)

        def post(sender, **kwargs):
            CommandSignalTests.post = dict(**kwargs)

        pre_command.connect(pre, Command)
        post_command.connect(post, Command)

        out = StringIO()
        call_command('show_template_tags', stdout=out)

        self.assertIn('args', CommandSignalTests.pre)
        self.assertIn('kwargs', CommandSignalTests.pre)

        self.assertIn('args', CommandSignalTests.post)
        self.assertIn('kwargs', CommandSignalTests.post)
        self.assertIn('outcome', CommandSignalTests.post)

class CommandClassTests(TestCase):
    def setUp(self):
        management_dir = os.path.join('django_extensions', 'management')
        self.commands = find_commands(management_dir)

    def test_load_commands(self):
        """Try to load every management command to catch exceptions."""
        try:
            for command in self.commands:
                load_command_class('django_extensions', command)
        except Exception as e:
            self.fail("Can't load command class of {0}\n{1}".format(command, e))

class GraphModelsTests(TestCase):
    """
    Tests for the `graph_models` management command.
    """
    def test_use_model(self):
        include_models = [
            'NoWildcardInclude',
            'Wildcard*InsideInclude',
            '*WildcardPrefixInclude',
            'WildcardSuffixInclude*',
            '*WildcardBothInclude*'
        ]
        exclude_models = [
            'NoWildcardExclude',
            'Wildcard*InsideExclude',
            '*WildcardPrefixExclude',
            'WildcardSuffixExclude*',
            '*WildcardBothExclude*'
        ]
        # Any model name should be used if neither include or exclude
        # are defined.
        self.assertTrue(use_model(
            'SomeModel',
            None,
            None
        ))
        # Any model name should be allowed if `*` is in `include_models`.
        self.assertTrue(use_model(
            'SomeModel',
            ['OtherModel', '*', 'Wildcard*Model'],
            None
        ))
        # No model name should be allowed if `*` is in `exclude_models`.
        self.assertFalse(use_model(
            'SomeModel',
            None,
            ['OtherModel', '*', 'Wildcard*Model']
        ))
        # Some tests with the `include_models` defined above.
        self.assertFalse(use_model(
            'SomeModel',
            include_models,
            None
        ))
        self.assertTrue(use_model(
            'NoWildcardInclude',
            include_models,
            None
        ))
        self.assertTrue(use_model(
            'WildcardSomewhereInsideInclude',
            include_models,
            None
        ))
        self.assertTrue(use_model(
            'MyWildcardPrefixInclude',
            include_models,
            None
        ))
        self.assertTrue(use_model(
            'WildcardSuffixIncludeModel',
            include_models,
            None
        ))
        self.assertTrue(use_model(
            'MyWildcardBothIncludeModel',
            include_models,
            None
        ))
        # Some tests with the `exclude_models` defined above.
        self.assertTrue(use_model(
            'SomeModel',
            None,
            exclude_models
        ))
        self.assertFalse(use_model(
            'NoWildcardExclude',
            None,
            exclude_models
        ))
        self.assertFalse(use_model(
            'WildcardSomewhereInsideExclude',
            None,
            exclude_models
        ))
        self.assertFalse(use_model(
            'MyWildcardPrefixExclude',
            None,
            exclude_models
        ))
        self.assertFalse(use_model(
            'WildcardSuffixExcludeModel',
            None,
            exclude_models
        ))
        self.assertFalse(use_model(
            'MyWildcardBothExcludeModel',
            None,
            exclude_models
        ))

    def test_no_models_dot_py(self):
        data = generate_graph_data(['testapp_with_no_models_file'])
        self.assertEqual(len(data['graphs']), 1)

        model_name = data['graphs'][0]['models'][0]['name']
        self.assertEqual(model_name, 'TeslaCar')

class ShowUrlsTests(TestCase):
    """
    Tests for the `show_urls` management command.
    """
    def test_color(self):
        with force_color_support:
            out = StringIO()
            call_command('show_urls', stdout=out)
            self.output = out.getvalue()
            self.assertIn('\x1b', self.output)

    def test_no_color(self):
        with force_color_support:
            out = StringIO()
            call_command('show_urls', '--no-color', stdout=out)
            self.output = out.getvalue()
            self.assertNotIn('\x1b', self.output)


text:
@interface FSSlimSwitchCell()
@property (nonatomic, copy) SwitchDidChanged switchDidChangedInner;
@end

@implementation FSSlimSwitchCell
{
    NSIndexPath *_indexPath;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    self.vLine.backgroundColor = [UIColor vcBackgroundColor];
    self.lblTitle.textColor = [UIColor blackColor];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)configureCellWithTitle:(NSString *)title swStatus:(NSArray<NSNumber *> *)statusArr indexPath:(NSIndexPath *)indexPath isOn:(SwitchDidChanged)isOn {
    self.switchDidChangedInner = isOn;
    self->_indexPath = indexPath;
    self.lblTitle.text = title;
    self.sw.on = [statusArr[indexPath.row] boolValue];
    [self.sw addTarget:self action:@selector(fs_switchDidChanged) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - private action

- (void)fs_switchDidChanged {
    if (self.switchDidChangedInner) {
        self.switchDidChangedInner(self->_indexPath, self.sw.isOn);
    }
}

@end


text:
package org.openntf.domino.graph;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import javolution.text.TextBuilder;
import javolution.util.FastMap;
import javolution.util.FastSet;

import org.openntf.domino.Document;
import org.openntf.domino.graph.DominoGraph.DominoGraphException;

import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.VertexQuery;
import com.tinkerpop.blueprints.util.DefaultVertexQuery;
import com.tinkerpop.blueprints.util.MultiIterable;
import com.tinkerpop.blueprints.util.VerticesFromEdgesIterable;

public class DominoVertex extends DominoElement implements IDominoVertex, Serializable {
	private static final Logger log_ = Logger.getLogger(DominoVertex.class.getName());
	public static final String GRAPH_TYPE_VALUE = "OpenVertex";
	//	public static final String IN_NAME = "_OPEN_IN";
	//	public static final String OUT_NAME = "_OPEN_OUT";
	// public static final String IN_LABELS = "_OPEN_LABELS_IN";
	// public static final String OUT_LABELS = "_OPEN_LABELS_OUT";
	public static final String IN_PREFIX = "_OPEN_IN_";
	public static final String OUT_PREFIX = "_OPEN_OUT_";

	private static final long serialVersionUID = 1L;

	private FastMap<String, Boolean> inDirtyMap_;
	private FastMap<String, Boolean> outDirtyMap_;
	private FastMap<String, FastSet<String>> inEdgesMap_;
	private FastMap<String, FastSet<String>> outEdgesMap_;
	private transient FastMap<String, FastSet<Edge>> inEdgeCache_;
	private transient FastMap<String, FastSet<Edge>> outEdgeCache_;

	public DominoVertex(final DominoGraph parent, final org.openntf.domino.Document doc) {
		super(parent, doc);
	}

	Map<String, Boolean> getInDirtyMap() {
		if (inDirtyMap_ == null) {
			inDirtyMap_ = new FastMap<String, Boolean>().atomic();
		}
		return inDirtyMap_;
	}

	Map<String, Boolean> getOutDirtyMap() {
		if (outDirtyMap_ == null) {
			outDirtyMap_ = new FastMap<String, Boolean>().atomic();
		}
		return outDirtyMap_;
	}

	Map<String, FastSet<String>> getInEdgesMap() {
		if (inEdgesMap_ == null) {
			inEdgesMap_ = new FastMap<String, FastSet<String>>().atomic();
		}
		return inEdgesMap_;
	}

	Map<String, FastSet<String>> getOutEdgesMap() {
		if (outEdgesMap_ == null) {
			outEdgesMap_ = new FastMap<String, FastSet<String>>().atomic();
		}
		return outEdgesMap_;
	}

	@Override
	public int getInEdgeCount(final String label) {
		Set<String> edgeIds = getInEdgesMap().get(label);
		if (edgeIds == null) {
			return getProperty("_COUNT" + DominoVertex.IN_PREFIX + label, Integer.class, false);
		} else {
			return edgeIds.size();
		}
	}

	@SuppressWarnings("unchecked")
	Set<String> getInEdgesSet(final String label) {
		FastSet<String> edgeIds = getInEdgesMap().get(label);
		if (edgeIds == null) {
			Object o = getProperty(DominoVertex.IN_PREFIX + label, java.util.Collection.class);
			if (o != null) {
				if (o instanceof FastSet) {
					edgeIds = ((FastSet<String>) o).atomic();
				} else if (o instanceof java.util.Collection) {
					FastSet<String> result = new FastSet<String>();
					result.addAll((Collection<String>) o);
					edgeIds = result.atomic();
				} else {
					log_.log(Level.SEVERE, "ALERT! InEdges returned something other than a Collection " + o.getClass().getName()
							+ ". We are clearing the values and rebuilding the edges.");
					edgeIds = new FastSet<String>().atomic();
				}
			} else {
				edgeIds = new FastSet<String>().atomic();
			}
			Map<String, FastSet<String>> map = getInEdgesMap();
			//			synchronized (map) {
			map.put(label, edgeIds);
			//			}
		}
		return edgeIds;
	}

	@Override
	public int getOutEdgeCount(final String label) {
		Set<String> edgeIds = getOutEdgesMap().get(label);
		if (edgeIds == null) {
			return getProperty("_COUNT" + DominoVertex.OUT_PREFIX + label, Integer.class, false);
		} else {
			return edgeIds.size();
		}
	}

	@SuppressWarnings("unchecked")
	FastSet<String> getOutEdgesSet(final String label) {
		FastSet<String> edgeIds = getOutEdgesMap().get(label);
		if (edgeIds == null) {
			Object o = getProperty(DominoVertex.OUT_PREFIX + label, java.util.Collection.class);
			if (o != null) {
				if (o instanceof FastSet) {
					edgeIds = ((FastSet<String>) o).atomic();
				} else if (o instanceof java.util.Collection) {
					FastSet<String> result = new FastSet<String>();
					result.addAll((Collection<String>) o);
					edgeIds = result.atomic();
				} else {
					log_.log(Level.SEVERE, "ALERT! OutEdges returned something other than a Collection " + o.getClass().getName()
							+ ". We are clearing the values and rebuilding the edges.");
					edgeIds = new FastSet<String>().atomic();
				}
			} else {
				edgeIds = new FastSet<String>().atomic();
			}
			Map<String, FastSet<String>> map = getOutEdgesMap();
			//			synchronized (map) {
			map.put(label, edgeIds);
			//			}
		}
		return edgeIds;
	}

	@Override
	public Edge addEdge(final String label, final Vertex vertex) {
		return parent_.addEdge(null, this, vertex, label);
	}

	@Override
	public void addInEdge(final Edge edge) {
		String label = edge.getLabel();

		Set<String> ins = getInEdgesSet(label);
		if (!ins.contains(edge.getId())) {
			getParent().startTransaction(this);
			Map<String, Boolean> map = getInDirtyMap();
			map.put(label, true);
			Set<Edge> inLabelObjs = getInEdgeCache(label);
			inLabelObjs.add(edge);
			ins.add((String) edge.getId());
		}
	}

	@Override
	public void addOutEdge(final Edge edge) {
		String label = edge.getLabel();

		Set<String> outs = getOutEdgesSet(label);
		if (!outs.contains(edge.getId())) {
			getParent().startTransaction(this);
			Map<String, Boolean> map = getOutDirtyMap();
			map.put(label, true);
			Set<Edge> outLabelObjs = getOutEdgeCache(label);
			outLabelObjs.add(edge);
			outs.add((String) edge.getId());
		}
	}

	public java.util.Set<String> getBothEdges() {
		FastSet<String> result = new FastSet<String>();
		result.addAll(getInEdges());
		result.addAll(getOutEdges());
		return result.unmodifiable();
	}

	@Override
	public Set<Edge> getEdges(final String... labels) {
		FastSet<Edge> result = new FastSet<Edge>();
		result.addAll(getInEdgeObjects(labels));
		result.addAll(getOutEdgeObjects(labels));
		return result.unmodifiable();
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public Iterable<Edge> getEdges(final Direction direction, final String... labels) {
		if (direction == Direction.IN) {
			if (labels == null || labels.length == 0) {
				return getInEdgeObjects().unmodifiable();
			} else {
				return getInEdgeObjects(labels);
			}
		} else if (direction == Direction.OUT) {
			if (labels == null || labels.length == 0) {
				return getOutEdgeObjects().unmodifiable();
			} else {
				return getOutEdgeObjects(labels);
			}
		} else {
			FastSet result = new FastSet<Edge>();
			if (labels == null || labels.length == 0) {
				result.addAll(getInEdgeObjects());
				result.addAll(getOutEdgeObjects());
			} else {
				result.addAll(getInEdgeObjects(labels));
				result.addAll(getOutEdgeObjects(labels));
			}
			return result.unmodifiable();
		}
	}

	private Map<String, FastSet<Edge>> getInEdgeCache() {
		if (inEdgeCache_ == null) {
			inEdgeCache_ = new FastMap<String, FastSet<Edge>>().atomic();
		}
		return inEdgeCache_;
	}

	private FastSet<Edge> getInEdgeCache(final String label) {
		Map<String, FastSet<Edge>> inCache = getInEdgeCache();
		FastSet<Edge> result = null;
		//		synchronized (inCache) {
		result = inCache.get(label);
		if (result == null) {
			result = new FastSet<Edge>().atomic();
			inCache.put(label, result);
		}
		//		}
		return result;
	}

	private FastSet<Edge> getOutEdgeCache(final String label) {
		Map<String, FastSet<Edge>> outCache = getOutEdgeCache();
		FastSet<Edge> result = null;
		//		synchronized (outCache) {
		result = outCache.get(label);
		if (result == null) {
			result = new FastSet<Edge>().atomic();
			outCache.put(label, result);
		}
		//		}
		return result;
	}

	private FastMap<String, FastSet<Edge>> getOutEdgeCache() {
		if (outEdgeCache_ == null) {
			outEdgeCache_ = new FastMap<String, FastSet<Edge>>().atomic();
		}
		return outEdgeCache_;
	}

	protected FastSet<Edge> getInEdgeObjects(final String... labels) {
		Map<String, FastSet<Edge>> inCache = getInEdgeCache();
		FastSet<Edge> result = null;
		if (labels == null || labels.length == 0) {
			result = new FastSet<Edge>().atomic();
			Set<String> labelSet = this.getInEdgeLabels();
			//			System.out.println("INFO: Getting all IN edges for a vertex across " + labelSet.size() + " labels.");
			for (String label : labelSet) {
				result.addAll(getInEdgeObjects(label));
			}
			//			System.out.println("INFO: Found " + result.size() + " IN edges.");
		} else if (labels.length == 1) {
			String label = labels[0];
			//			System.out.println("Getting in edges from " + getClass().getName() + " with label: " + label + " ...");
			//			synchronized (inCache) {
			result = inCache.get(label);
			//			}
			if (result == null) {
				// result = Collections.synchronizedSet(new LinkedHashSet<Edge>());
				Set<String> edgeIds = getInEdgesSet(label);
				FastSet<Edge> edges = getParent().getEdgesFromIds(edgeIds);
				if (edges != null) {
					result = edges.atomic();
				}

				// Set<Edge> allEdges = Collections.unmodifiableSet(getInEdgeObjects());
				// for (Edge edge : allEdges) {
				// if (label.equals(edge.getLabel())) {
				// result.add(edge);
				// }
				// }

				//				synchronized (inCache) {
				inCache.put(label, result);
				//				}
			}
		} else {
			result = new FastSet<Edge>();
			for (String label : labels) {
				result.addAll(getInEdgeObjects(label));
			}
		}
		//		System.out.println("Returning " + (result == null ? "null" : result.size()) + " edges");
		return result == null ? null : result.unmodifiable();
	}

	protected FastSet<Edge> getOutEdgeObjects(final String... labels) {
		FastMap<String, FastSet<Edge>> outCache = getOutEdgeCache();
		FastSet<Edge> result = null;

		if (labels == null || labels.length == 0) {
			result = new FastSet<Edge>();
			FastSet<String> labelSet = this.getOutEdgeLabels();
			//			System.out.println("INFO: Getting all OUT edges for a vertex across " + labelSet.size() + " labels.");
			for (String label : labelSet) {
				FastSet<Edge> curEdges = getOutEdgeObjects(label);
				//				System.out.println("INFO: Found " + curEdges.size() + " OUT edges for label " + label);
				result.addAll(curEdges);
			}
			//			System.out.println("INFO: Found " + result.size() + " OUT edges.");
		} else if (labels.length == 1) {
			String label = labels[0];
			if (label == null) {
				return getOutEdgeObjects().unmodifiable();
			}
			//			synchronized (outCache) {
			result = outCache.get(label);
			//			}
			if (result == null) {
				FastSet<String> edgeIds = getOutEdgesSet(label);
				FastSet<Edge> edges = getParent().getEdgesFromIds(edgeIds);
				if (edges != null) {
					result = edges.atomic();
				}

				// result = Collections.synchronizedSet(new LinkedHashSet<Edge>());
				// Set<Edge> allEdges = Collections.unmodifiableSet(getOutEdgeObjects());
				// if (!allEdges.isEmpty()) {
				// for (Edge edge : allEdges) {
				// if (edge == null) {
				//
				// } else {
				// String curLabel = edge.getLabel();
				// if (label.equals(curLabel)) {
				// result.add(edge);
				// }
				// }
				// }
				// }

				//				synchronized (outCache) {
				outCache.put(label, result);
				//				}
			}
		} else {
			result = new FastSet<Edge>();
			for (String label : labels) {
				result.addAll(getOutEdgeObjects(label));
			}
		}
		return result == null ? null : result.unmodifiable();
	}

	// @SuppressWarnings({ "unchecked", "rawtypes" })
	// protected Set<Edge> getInEdgeObjects() {
	// if (inEdgesObjects_ == null) {
	// Set<String> ins = getInEdges();
	// Iterable<Edge> edges = getParent().getEdgesFromIds(ins);
	// if (edges != null) {
	// inEdgesObjects_ = Collections.synchronizedSet((LinkedHashSet) edges);
	// }
	// }
	// return inEdgesObjects_;
	// }

	// @SuppressWarnings({ "unchecked", "rawtypes" })
	// protected Set<Edge> getOutEdgeObjects() {
	// if (outEdgesObjects_ == null) {
	// Set<String> outs = getOutEdges();
	// Iterable<Edge> edges = getParent().getEdgesFromIds(outs);
	// if (edges != null) {
	// outEdgesObjects_ = Collections.synchronizedSet((LinkedHashSet) edges);
	// }
	// }
	// return outEdgesObjects_;
	// }

	// @SuppressWarnings("unchecked")
	// public Set<String> getInEdges() {
	// if (inEdges_ == null) {
	// Object o = getProperty(DominoVertex.IN_NAME, java.util.Collection.class);
	// if (o != null) {
	// if (o instanceof LinkedHashSet) {
	// inEdges_ = Collections.synchronizedSet((LinkedHashSet) o);
	// } else if (o instanceof java.util.Collection) {
	// inEdges_ = Collections.synchronizedSet(new LinkedHashSet<String>((Collection<String>) o));
	// } else {
	// log_.log(Level.WARNING, "ALERT! InEdges returned something other than a Collection " + o.getClass().getName());
	// }
	// } else {
	// inEdges_ = Collections.synchronizedSet(new LinkedHashSet<String>());
	// }
	// }
	//
	// return inEdges_;
	// }

	@Override
	public FastSet<String> getInEdgeLabels() {
		FastSet<String> result = new FastSet<String>();
		Set<String> rawKeys = getRawDocument().keySet();
		for (String key : rawKeys) {
			if (key.startsWith(IN_PREFIX)) {
				result.add(key.substring(IN_PREFIX.length()));
			}
		}
		return result;
	}

	private FastSet<String> getInEdges() {
		FastSet<String> result = new FastSet<String>();
		for (String label : getInEdgeLabels()) {
			result.addAll(getInEdgesSet(label));
		}
		return result;
	}

	@Override
	public FastSet<String> getOutEdgeLabels() {
		FastSet<String> result = new FastSet<String>();
		Set<String> rawKeys = getRawDocument().keySet();
		for (String key : rawKeys) {
			if (key.startsWith(OUT_PREFIX)) {
				result.add(key.substring(OUT_PREFIX.length()));
			}
		}
		return result;
	}

	private FastSet<String> getOutEdges() {
		FastSet<String> result = new FastSet<String>();
		for (String label : getOutEdgeLabels()) {
			result.addAll(getOutEdgesSet(label));
		}
		return result;
	}

	// @SuppressWarnings("unchecked")
	// public Set<String> getOutEdges() {
	// if (outEdges_ == null) {
	// Object o = getProperty(DominoVertex.OUT_NAME, java.util.Collection.class);
	// if (o != null) {
	// if (o instanceof LinkedHashSet) {
	// outEdges_ = Collections.synchronizedSet((LinkedHashSet) o);
	// } else if (o instanceof java.util.Collection) {
	// outEdges_ = Collections.synchronizedSet(new LinkedHashSet<String>((Collection<String>) o));
	// } else {
	// log_.log(Level.WARNING, "ALERT! OutEdges returned something other than a Collection " + o.getClass().getName());
	// }
	// } else {
	// outEdges_ = Collections.synchronizedSet(new LinkedHashSet<String>());
	// }
	// }
	// return outEdges_;
	// }

	@Override
	public Iterable<Vertex> getVertices(final Direction direction, final String... labels) {
		if (direction == Direction.BOTH) {
			List<Iterable<Vertex>> list = new ArrayList<Iterable<Vertex>>();
			list.add(new VerticesFromEdgesIterable(this, Direction.IN, labels));
			list.add(new VerticesFromEdgesIterable(this, Direction.OUT, labels));
			return new MultiIterable<Vertex>(list);
		} else {
			return new VerticesFromEdgesIterable(this, direction, labels);
		}
	}

	@Override
	public VertexQuery query() {
		return new DefaultVertexQuery(this);
	}

	@Override
	public void remove() {
		getParent().removeVertex(this);
	}

	public void removeEdge(final Edge edge) {
		getParent().startTransaction(this);
		String label = edge.getLabel();

		boolean inChanged = false;
		Set<String> ins = getInEdgesSet(label);
		if (ins != null) {
			//			System.out.println("Removing an in edge from " + label + " with id " + edge.getId() + " from a vertex of type "
			//					+ getProperty("Form"));
			//			synchronized (ins) {
			inChanged = ins.remove(edge.getId());
			//			}
		} else {
			//			System.out.println("in edges were null from a vertex of type " + getProperty("Form") + ": " + getId());
		}
		// Set<Edge> inObjs = getInEdgeObjects();
		// synchronized (inObjs) {
		// inObjs.remove(edge);
		// }
		if (inChanged) {
			//			System.out.println("Ins were changed so recording cache invalidation...");
			Set<Edge> inObjsLabel = getInEdgeCache(label);
			//			synchronized (inObjsLabel) {
			inObjsLabel.remove(edge);
			//			}
			Map<String, Boolean> inDirtyMap = getInDirtyMap();
			//			synchronized (inDirtyMap) {
			inDirtyMap.put(label, true);
			//			}
		}

		boolean outChanged = false;
		Set<String> outs = getOutEdgesSet(label);
		if (outs != null) {
			//			System.out.println("Removing an out edge from " + label + " with id " + edge.getId() + " from a vertex of type "
			//					+ getProperty("Form"));
			//			synchronized (outs) {
			outChanged = outs.remove(edge.getId());
			//			}
		} else {
			//			System.out.println("out edges were null from a vertex of type " + getProperty("Form") + ": " + getId());
		}
		if (outChanged) {
			//			System.out.println("Out were changed so recording cache invalidation...");
			Set<Edge> outObjsLabel = getOutEdgeCache(label);
			//			synchronized (outObjsLabel) {
			outObjsLabel.remove(edge);
			//			}
			Map<String, Boolean> outDirtyMap = getOutDirtyMap();
			//			synchronized (outDirtyMap) {
			outDirtyMap.put(label, true);
			//			}
		}
	}

	boolean writeEdges() {
		return writeEdges(false);
	}

	@Override
	protected void reapplyChanges() {
		// validateEdges();
		writeEdges(false);
		super.reapplyChanges();
	}

	boolean writeEdges(final boolean force) {
		boolean result = false;
		Map<String, FastSet<String>> inMap = getInEdgesMap();
		Map<String, Boolean> inDirtyMap = getInDirtyMap();
		if (!inDirtyMap.isEmpty()) {
			for (String key : inDirtyMap.keySet()) {
				if (inDirtyMap.get(key) || force) {
					Set<String> edgeIds = inMap.get(key);
					if (edgeIds != null) {
						setProperty(DominoVertex.IN_PREFIX + key, edgeIds);
						setProperty("_COUNT" + DominoVertex.IN_PREFIX + key, edgeIds.size());
						result = true;
					}
					//					synchronized (inDirtyMap) {
					inDirtyMap.put(key, Boolean.FALSE);
					//					}
				}
			}
		}

		Map<String, FastSet<String>> outMap = getOutEdgesMap();
		Map<String, Boolean> outDirtyMap = getOutDirtyMap();
		if (!outDirtyMap.isEmpty()) {
			for (String key : outDirtyMap.keySet()) {
				if (outDirtyMap.get(key) || force) {
					Set<String> edgeIds = outMap.get(key);
					if (edgeIds != null) {
						setProperty(DominoVertex.OUT_PREFIX + key, edgeIds);
						setProperty("_COUNT" + DominoVertex.OUT_PREFIX + key, edgeIds.size());
						result = true;
					}
					//					synchronized (outDirtyMap) {
					outDirtyMap.put(key, Boolean.FALSE);
					//					}
				}
			}
		}

		// if (inDirty_ || force) {
		// if (inEdges_ != null) {
		// setProperty(DominoVertex.IN_NAME, inEdges_);
		// // getRawDocument().replaceItemValue(DominoVertex.IN_NAME, inEdges_);
		// setProperty(DominoVertex.IN_NAME + "_COUNT", inEdges_.size());
		// // getRawDocument().replaceItemValue(DominoVertex.IN_NAME + "_COUNT", inEdges_.size());
		// // System.out.println("Updating " + inEdges_.size() + " inEdges to vertex: " + getRawDocument().getFormName());
		// result = true;
		// }
		// inDirty_ = false;
		// }
		// if (outDirty_ || force) {
		// if (outEdges_ != null) {
		// setProperty(DominoVertex.OUT_NAME, outEdges_);
		// // getRawDocument().replaceItemValue(DominoVertex.OUT_NAME, outEdges_);
		// setProperty(DominoVertex.OUT_NAME + "_COUNT", outEdges_.size());
		// // getRawDocument().replaceItemValue(DominoVertex.OUT_NAME + "_COUNT", outEdges_.size());
		// // System.out.println("Updating " + outEdges_.size() + " outEdges to vertex: " + getRawDocument().getFormName());
		// result = true;
		// }
		// outDirty_ = false;
		// }
		return result;
	}

	@Override
	public String validateEdges() {
		TextBuilder sb = new TextBuilder();
		Set<String> inIds = getInEdges();
		for (String id : inIds.toArray(new String[inIds.size()])) {
			Document chk = getParent().getRawDatabase().getDocumentByUNID(id);
			if (chk == null) {
				inIds.remove(id);
				sb.append("IN: ");
				sb.append(id);
				sb.append(",");
			}
		}

		Set<String> outIds = getOutEdges();
		for (String id : outIds.toArray(new String[outIds.size()])) {
			Document chk = getParent().getRawDatabase().getDocumentByUNID(id);
			if (chk == null) {
				outIds.remove(id);
				sb.append("OUT: ");
				sb.append(id);
				sb.append(",");
			}
		}
		return sb.toString();
	}

	public IEdgeHelper getHelper(final IDominoEdgeType edgeType) {
		return getParent().getHelper(edgeType);
	}

	public Set<IEdgeHelper> findHelpers(final Vertex other) {
		return getParent().findHelpers(this, other);
	}

	public static class MultipleDefinedEdgeHelpers extends DominoGraphException {
		private static final long serialVersionUID = 1L;

		public MultipleDefinedEdgeHelpers(final DominoVertex element1, final DominoVertex element2) {
			super("Multiple EdgeHelpers found for vertexes of type " + element1.getClass().getName() + " and "
					+ element2.getClass().getName(), element1, element2);
		}
	}

	public static class UndefinedEdgeHelpers extends DominoGraphException {
		private static final long serialVersionUID = 1L;

		public UndefinedEdgeHelpers(final DominoVertex element1, final DominoVertex element2) {
			super("No EdgeHelpers found for vertexes of type " + element1.getClass().getName() + " and " + element2.getClass().getName(),
					element1, element2);
		}
	}

	public Edge relate(final DominoVertex other) throws MultipleDefinedEdgeHelpers {
		Set<IEdgeHelper> helpers = findHelpers(other);
		if (helpers.size() == 1) {
			for (IEdgeHelper helper : helpers) {
				return helper.makeEdge(other, this);
			}
			return null;
		} else if (helpers.size() == 0) {
			throw new UndefinedEdgeHelpers(this, other);

		} else {
			throw new MultipleDefinedEdgeHelpers(this, other);
		}

	}

	@Override
	public Set<IEdgeHelper> getEdgeHelpers() {
		Set<IEdgeHelper> result = new FastSet<IEdgeHelper>();
		for (String in : getInEdgeLabels()) {
			IEdgeHelper helper = getParent().getHelper(in);
			if (helper != null) {
				result.add(helper);
			}
		}
		for (String out : getOutEdgeLabels()) {
			IEdgeHelper helper = getParent().getHelper(out);
			if (helper != null) {
				result.add(helper);
			}
		}
		return result;
	}
}


text:
function require(name) {
    //if(name.match(/^\.\//).length > 0) {
    //Local file
    //For now we just handle a single level of indirection, in the future we should handle multiple

    var realName = name.match(/([^\\./]*)(.js)?$/)[1];
    if (this[realName]) {
        return this[realName];
    } else if (self[realName]) {
        return this[realName];
    } else if (realName == "underscore") {
        //Strange stuff for underscore, not done for jQuery as that is currently only for the browser,
        //while underscore may also be used in node.js
        return this["_"];
    } else {
        debugger;
        throw "Cannot handle a require for '" + name + "' (as I cannot find it).";
    }
    //} else {
    //    //Nodejs file... we can't support this
    //    debugger;
    //    throw "Cannot handle a require for '" + name + "' .";
    //}
}


text:
package com.creditease.uav.util;

import java.util.concurrent.ConcurrentHashMap;

/**
 *
 * LimitConcurrentHashMap description: limit the capacity of K-V pairs for ConcurrentHashMap
 *
 * @param <K>
 * @param <V>
 */
public class LimitConcurrentHashMap<K, V> extends ConcurrentHashMap<K, V> {

    private static final long serialVersionUID = -7573867171798556834L;

    protected volatile int limitCapacity;

    public LimitConcurrentHashMap(int limit) {
        this.limitCapacity = limit;
    }

    @Override
    public V put(K key, V value) {

        if (this.size() >= this.limitCapacity) {
            return value;
        }

        V tv = super.put(key, value);

        return tv;
    }

    @Override
    public V putIfAbsent(K key, V value) {

        if (this.size() >= this.limitCapacity) {
            return value;
        }

        V tv = super.putIfAbsent(key, value);

        return tv;
    }
}


text:
Port of my custom WordPress theme for the static site generator [Hugo](http://http://hugo.spf13.com).

## PostCSS + Babel + Gulp

To make my life easier, I created a `source` directory that contains PostCSS and ES2015-syntax JS. I'm using Gulp to run PostCSS and Babel to process those files.

To modify the static assets, run `gulp watch` from the theme root and edit files in the `source` directory.

This also handles image optimization, file revisioning, and concat/minification.

## Contributing

Please clone this repository and create pull-requests for any features that could have a more general use and that fit within the vision of this theme.


text:
package io.zerodi.server.handler;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doReturn;

import java.util.Date;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;

import io.zerodi.environment.service.CurrentClock;
import io.zerodi.ping.PingMessage;

@RunWith(MockitoJUnitRunner.class)
public class PingHandlerTest {

    @InjectMocks
    private PingHandler handler;

    @Spy
    private CurrentClock currentClock;

    private PingMessage pingMessage = new PingMessage("test", new Date());

    @Test
    public void itShouldProduceResponseToPingMessage() throws Exception {
        // given
        Date responseDate = new Date();

        // when
        doReturn(responseDate).when(currentClock).getCurrentDate();
        PingMessage response = handler.handleMessage(pingMessage);

        // then
        assertThat(response).isNotNull();
        assertThat(response.getPayload()).isEqualTo("response to: test");
        assertThat(response.getDate()).isEqualTo(responseDate);
    }
}