text:
using System.Net;
using FluentAssertions;
using JetBrains.Annotations;
using JsonApiDotNetCore;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Resources;
using JsonApiDotNetCore.Resources.Annotations;
using JsonApiDotNetCore.Serialization.Objects;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using TestBuildingBlocks;
using Xunit;

namespace JsonApiDotNetCoreTests.IntegrationTests.ReadWrite.Updating.Relationships;

public sealed class RemoveFromToManyRelationshipTests : IClassFixture<IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext>>
{
    private readonly IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> _testContext;
    private readonly ReadWriteFakers _fakers = new();

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

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

        testContext.ConfigureServicesAfterStartup(services =>
        {
            services.AddSingleton<IResourceDefinition<WorkItem, int>, RemoveExtraFromWorkItemDefinition>();
        });

        var workItemDefinition = (RemoveExtraFromWorkItemDefinition)testContext.Factory.Services.GetRequiredService<IResourceDefinition<WorkItem, int>>();
        workItemDefinition.Reset();
    }

    [Fact]
    public async Task Cannot_remove_from_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 = new
            {
                type = "userAccounts",
                id = existingWorkItem.Assignee.StringId
            }
        };

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

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

        // Assert
        httpResponse.ShouldHaveStatusCode(HttpStatusCode.Forbidden);

        responseDocument.Errors.ShouldHaveCount(1);

        ErrorObject error = responseDocument.Errors[0];
        error.StatusCode.Should().Be(HttpStatusCode.Forbidden);
        error.Title.Should().Be("Failed to deserialize request body: Only to-many relationships can be targeted through this endpoint.");
        error.Detail.Should().Be("Relationship 'assignee' is not a to-many relationship.");
        error.Source.Should().BeNull();
        error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
    }

    [Fact]
    public async Task Can_remove_from_OneToMany_relationship_with_unassigned_existing_resource()
    {
        // Arrange
        WorkItem existingWorkItem = _fakers.WorkItem.Generate();
        existingWorkItem.Subscribers = _fakers.UserAccount.Generate(2).ToHashSet();
        UserAccount existingSubscriber = _fakers.UserAccount.Generate();

        await _testContext.RunOnDatabaseAsync(async dbContext =>
        {
            await dbContext.ClearTableAsync<UserAccount>();
            dbContext.AddInRange(existingWorkItem, existingSubscriber);
            await dbContext.SaveChangesAsync();
        });

        var requestBody = new
        {
            data = new[]
            {
                new
                {
                    type = "userAccounts",
                    id = existingSubscriber.StringId
                },
                new
                {
                    type = "userAccounts",
                    id = existingWorkItem.Subscribers.ElementAt(0).StringId
                }
            }
        };

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

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

        // Assert
        httpResponse.ShouldHaveStatusCode(HttpStatusCode.NoContent);

        responseDocument.Should().BeEmpty();

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

            workItemInDatabase.Subscribers.ShouldHaveCount(1);
            workItemInDatabase.Subscribers.Single().Id.Should().Be(existingWorkItem.Subscribers.ElementAt(1).Id);

            List<UserAccount> userAccountsInDatabase = await dbContext.UserAccounts.ToListAsync();
            userAccountsInDatabase.ShouldHaveCount(3);
        });
    }

    [Fact]
    public async Task Can_remove_from_OneToMany_relationship_with_extra_removals_from_resource_definition()
    {
        // Arrange
        WorkItem existingWorkItem = _fakers.WorkItem.Generate();
        existingWorkItem.Subscribers = _fakers.UserAccount.Generate(3).ToHashSet();

        await _testContext.RunOnDatabaseAsync(async dbContext =>
        {
            await dbContext.ClearTableAsync<UserAccount>();
            dbContext.AddInRange(existingWorkItem);
            await dbContext.SaveChangesAsync();
        });

        var workItemDefinition = (RemoveExtraFromWorkItemDefinition)_testContext.Factory.Services.GetRequiredService<IResourceDefinition<WorkItem, int>>();
        workItemDefinition.ExtraSubscribersIdsToRemove.Add(existingWorkItem.Subscribers.ElementAt(2).Id);

        var requestBody = new
        {
            data = new[]
            {
                new
                {
                    type = "userAccounts",
                    id = existingWorkItem.Subscribers.ElementAt(0).StringId
                }
            }
        };

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

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

        // Assert
        httpResponse.ShouldHaveStatusCode(HttpStatusCode.NoContent);

        responseDocument.Should().BeEmpty();

        workItemDefinition.PreloadedSubscribers.ShouldHaveCount(1);

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

            workItemInDatabase.Subscribers.ShouldHaveCount(1);
            workItemInDatabase.Subscribers.Single().Id.Should().Be(existingWorkItem.Subscribers.ElementAt(1).Id);

            List<UserAccount> userAccountsInDatabase = await dbContext.UserAccounts.ToListAsync();
            userAccountsInDatabase.ShouldHaveCount(3);
        });
    }

    [Fact]
    public async Task Can_remove_from_ManyToMany_relationship_with_unassigned_existing_resource()
    {
        // Arrange
        WorkItem existingWorkItem = _fakers.WorkItem.Generate();
        existingWorkItem.Tags = _fakers.WorkTag.Generate(2).ToHashSet();

        WorkTag existingTag = _fakers.WorkTag.Generate();

        await _testContext.RunOnDatabaseAsync(async dbContext =>
        {
            await dbContext.ClearTableAsync<WorkTag>();
            dbContext.AddInRange(existingWorkItem, existingTag);
            await dbContext.SaveChangesAsync();
        });

        var requestBody = new
        {
            data = new[]
            {
                new
                {
                    type = "workTags",
                    id = existingWorkItem.Tags.ElementAt(1).StringId
                },
                new
                {
                    type = "workTags",
                    id = existingTag.StringId
                }
            }
        };

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

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

        // Assert
        httpResponse.ShouldHaveStatusCode(HttpStatusCode.NoContent);

        responseDocument.Should().BeEmpty();

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

            workItemInDatabase.Tags.ShouldHaveCount(1);
            workItemInDatabase.Tags.Single().Id.Should().Be(existingWorkItem.Tags.ElementAt(0).Id);

            List<WorkTag> tagsInDatabase = await dbContext.WorkTags.ToListAsync();
            tagsInDatabase.ShouldHaveCount(3);
        });
    }

    [Fact]
    public async Task Can_remove_from_ManyToMany_relationship_with_extra_removals_from_resource_definition()
    {
        // Arrange
        WorkItem existingWorkItem = _fakers.WorkItem.Generate();
        existingWorkItem.Tags = _fakers.WorkTag.Generate(3).ToHashSet();

        await _testContext.RunOnDatabaseAsync(async dbContext =>
        {
            await dbContext.ClearTableAsync<WorkTag>();
            dbContext.AddInRange(existingWorkItem);
            await dbContext.SaveChangesAsync();
        });

        var workItemDefinition = (RemoveExtraFromWorkItemDefinition)_testContext.Factory.Services.GetRequiredService<IResourceDefinition<WorkItem, int>>();
        workItemDefinition.ExtraTagIdsToRemove.Add(existingWorkItem.Tags.ElementAt(2).Id);

        var requestBody = new
        {
            data = new[]
            {
                new
                {
                    type = "workTags",
                    id = existingWorkItem.Tags.ElementAt(1).StringId
                }
            }
        };

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

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

        // Assert
        httpResponse.ShouldHaveStatusCode(HttpStatusCode.NoContent);

        responseDocument.Should().BeEmpty();

        workItemDefinition.PreloadedTags.ShouldHaveCount(1);

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

            workItemInDatabase.Tags.ShouldHaveCount(1);
            workItemInDatabase.Tags.Single().Id.Should().Be(existingWorkItem.Tags.ElementAt(0).Id);

            List<WorkTag> tagsInDatabase = await dbContext.WorkTags.ToListAsync();
            tagsInDatabase.ShouldHaveCount(3);
        });
    }

    [Fact]
    public async Task Cannot_remove_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/subscribers";

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

        // Assert
        httpResponse.ShouldHaveStatusCode(HttpStatusCode.BadRequest);

        responseDocument.Errors.ShouldHaveCount(1);

        ErrorObject error = responseDocument.Errors[0];
        error.StatusCode.Should().Be(HttpStatusCode.BadRequest);
        error.Title.Should().Be("Failed to deserialize request body: Missing request body.");
        error.Detail.Should().BeNull();
        error.Source.Should().BeNull();
        error.Meta.Should().NotContainKey("requestBody");
    }

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

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

        const string requestBody = "null";

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

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

        // Assert
        httpResponse.ShouldHaveStatusCode(HttpStatusCode.UnprocessableEntity);

        responseDocument.Errors.ShouldHaveCount(1);

        ErrorObject error = responseDocument.Errors[0];
        error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
        error.Title.Should().Be("Failed to deserialize request body: Expected an object, instead of 'null'.");
        error.Detail.Should().BeNull();
        error.Source.Should().BeNull();
        error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
    }

    [Fact]
    public async Task Cannot_remove_for_missing_type()
    {
        // Arrange
        WorkItem existingWorkItem = _fakers.WorkItem.Generate();
        existingWorkItem.Subscribers = _fakers.UserAccount.Generate(1).ToHashSet();

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

        var requestBody = new
        {
            data = new[]
            {
                new
                {
                    id = existingWorkItem.Subscribers.ElementAt(0).StringId
                }
            }
        };

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

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

        // Assert
        httpResponse.ShouldHaveStatusCode(HttpStatusCode.UnprocessableEntity);

        responseDocument.Errors.ShouldHaveCount(1);

        ErrorObject error = responseDocument.Errors[0];
        error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
        error.Title.Should().Be("Failed to deserialize request body: The 'type' element is required.");
        error.Detail.Should().BeNull();
        error.Source.ShouldNotBeNull();
        error.Source.Pointer.Should().Be("/data[0]");
        error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
    }

    [Fact]
    public async Task Cannot_remove_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[]
            {
                new
                {
                    type = Unknown.ResourceType,
                    id = Unknown.StringId.For<UserAccount, long>()
                }
            }
        };

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

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

        // Assert
        httpResponse.ShouldHaveStatusCode(HttpStatusCode.UnprocessableEntity);

        responseDocument.Errors.ShouldHaveCount(1);

        ErrorObject error = responseDocument.Errors[0];
        error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
        error.Title.Should().Be("Failed to deserialize request body: Unknown resource type found.");
        error.Detail.Should().Be($"Resource type '{Unknown.ResourceType}' does not exist.");
        error.Source.ShouldNotBeNull();
        error.Source.Pointer.Should().Be("/data[0]/type");
        error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
    }

    [Fact]
    public async Task Cannot_remove_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[]
            {
                new
                {
                    type = "userAccounts"
                }
            }
        };

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

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

        // Assert
        httpResponse.ShouldHaveStatusCode(HttpStatusCode.UnprocessableEntity);

        responseDocument.Errors.ShouldHaveCount(1);

        ErrorObject error = responseDocument.Errors[0];
        error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
        error.Title.Should().Be("Failed to deserialize request body: The 'id' element is required.");
        error.Detail.Should().BeNull();
        error.Source.ShouldNotBeNull();
        error.Source.Pointer.Should().Be("/data[0]");
        error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
    }

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

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

        string userAccountId1 = Unknown.StringId.For<UserAccount, long>();
        string userAccountId2 = Unknown.StringId.AltFor<UserAccount, long>();

        var requestBody = new
        {
            data = new[]
            {
                new
                {
                    type = "userAccounts",
                    id = userAccountId1
                },
                new
                {
                    type = "userAccounts",
                    id = userAccountId2
                }
            }
        };

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

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

        // Assert
        httpResponse.ShouldHaveStatusCode(HttpStatusCode.NotFound);

        responseDocument.Errors.ShouldHaveCount(2);

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

        ErrorObject error2 = responseDocument.Errors[1];
        error2.StatusCode.Should().Be(HttpStatusCode.NotFound);
        error2.Title.Should().Be("A related resource does not exist.");
        error2.Detail.Should().Be($"Related resource of type 'userAccounts' with ID '{userAccountId2}' in relationship 'subscribers' does not exist.");
        error2.Meta.Should().NotContainKey("requestBody");
    }

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

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

        string tagId1 = Unknown.StringId.For<WorkTag, int>();
        string tagId2 = Unknown.StringId.AltFor<WorkTag, int>();

        var requestBody = new
        {
            data = new[]
            {
                new
                {
                    type = "workTags",
                    id = tagId1
                },
                new
                {
                    type = "workTags",
                    id = tagId2
                }
            }
        };

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

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

        // Assert
        httpResponse.ShouldHaveStatusCode(HttpStatusCode.NotFound);

        responseDocument.Errors.ShouldHaveCount(2);

        ErrorObject error1 = responseDocument.Errors[0];
        error1.StatusCode.Should().Be(HttpStatusCode.NotFound);
        error1.Title.Should().Be("A related resource does not exist.");
        error1.Detail.Should().Be($"Related resource of type 'workTags' with ID '{tagId1}' in relationship 'tags' does not exist.");
        error1.Meta.Should().NotContainKey("requestBody");

        ErrorObject error2 = responseDocument.Errors[1];
        error2.StatusCode.Should().Be(HttpStatusCode.NotFound);
        error2.Title.Should().Be("A related resource does not exist.");
        error2.Detail.Should().Be($"Related resource of type 'workTags' with ID '{tagId2}' in relationship 'tags' does not exist.");
        error2.Meta.Should().NotContainKey("requestBody");
    }

    [Fact]
    public async Task Cannot_remove_from_unknown_resource_type_in_url()
    {
        // Arrange
        WorkItem existingWorkItem = _fakers.WorkItem.Generate();
        existingWorkItem.Subscribers = _fakers.UserAccount.Generate(1).ToHashSet();

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

        var requestBody = new
        {
            data = new[]
            {
                new
                {
                    type = "userAccounts",
                    id = existingWorkItem.Subscribers.ElementAt(0).StringId
                }
            }
        };

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

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

        // Assert
        httpResponse.ShouldHaveStatusCode(HttpStatusCode.NotFound);

        responseDocument.Should().BeEmpty();
    }

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

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

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

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

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

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

        // Assert
        httpResponse.ShouldHaveStatusCode(HttpStatusCode.NotFound);

        responseDocument.Errors.ShouldHaveCount(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.");
        error.Source.Should().BeNull();
        error.Meta.Should().NotContainKey("requestBody");
    }

    [Fact]
    public async Task Cannot_remove_from_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[]
            {
                new
                {
                    type = "userAccounts",
                    id = Unknown.StringId.For<UserAccount, long>()
                }
            }
        };

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

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

        // Assert
        httpResponse.ShouldHaveStatusCode(HttpStatusCode.NotFound);

        responseDocument.Errors.ShouldHaveCount(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}'.");
        error.Source.Should().BeNull();
        error.Meta.Should().NotContainKey("requestBody");
    }

    [Fact]
    public async Task Cannot_remove_for_relationship_mismatch_between_url_and_body()
    {
        // Arrange
        WorkItem existingWorkItem = _fakers.WorkItem.Generate();
        existingWorkItem.Subscribers = _fakers.UserAccount.Generate(1).ToHashSet();

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

        var requestBody = new
        {
            data = new[]
            {
                new
                {
                    type = "userAccounts",
                    id = existingWorkItem.Subscribers.ElementAt(0).StringId
                }
            }
        };

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

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

        // Assert
        httpResponse.ShouldHaveStatusCode(HttpStatusCode.Conflict);

        responseDocument.Errors.ShouldHaveCount(1);

        ErrorObject error = responseDocument.Errors[0];
        error.StatusCode.Should().Be(HttpStatusCode.Conflict);
        error.Title.Should().Be("Failed to deserialize request body: Incompatible resource type found.");
        error.Detail.Should().Be("Type 'userAccounts' is not convertible to type 'workTags' of relationship 'tags'.");
        error.Source.ShouldNotBeNull();
        error.Source.Pointer.Should().Be("/data[0]/type");
        error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
    }

    [Fact]
    public async Task Can_remove_with_duplicates()
    {
        // Arrange
        WorkItem existingWorkItem = _fakers.WorkItem.Generate();
        existingWorkItem.Subscribers = _fakers.UserAccount.Generate(2).ToHashSet();

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

        var requestBody = new
        {
            data = new[]
            {
                new
                {
                    type = "userAccounts",
                    id = existingWorkItem.Subscribers.ElementAt(0).StringId
                },
                new
                {
                    type = "userAccounts",
                    id = existingWorkItem.Subscribers.ElementAt(0).StringId
                }
            }
        };

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

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

        // Assert
        httpResponse.ShouldHaveStatusCode(HttpStatusCode.NoContent);

        responseDocument.Should().BeEmpty();

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

            workItemInDatabase.Subscribers.ShouldHaveCount(1);
            workItemInDatabase.Subscribers.Single().Id.Should().Be(existingWorkItem.Subscribers.ElementAt(1).Id);
        });
    }

    [Fact]
    public async Task Can_remove_with_empty_list()
    {
        // Arrange
        WorkItem existingWorkItem = _fakers.WorkItem.Generate();
        existingWorkItem.Subscribers = _fakers.UserAccount.Generate(1).ToHashSet();

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

        var requestBody = new
        {
            data = Array.Empty<object>()
        };

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

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

        // Assert
        httpResponse.ShouldHaveStatusCode(HttpStatusCode.NoContent);

        responseDocument.Should().BeEmpty();

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

            workItemInDatabase.Subscribers.ShouldHaveCount(1);
            workItemInDatabase.Subscribers.Single().Id.Should().Be(existingWorkItem.Subscribers.ElementAt(0).Id);
        });
    }

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

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

        var requestBody = new
        {
        };

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

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

        // Assert
        httpResponse.ShouldHaveStatusCode(HttpStatusCode.UnprocessableEntity);

        responseDocument.Errors.ShouldHaveCount(1);

        ErrorObject error = responseDocument.Errors[0];
        error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
        error.Title.Should().Be("Failed to deserialize request body: The 'data' element is required.");
        error.Detail.Should().BeNull();
        error.Source.Should().BeNull();
        error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
    }

    [Fact]
    public async Task Cannot_remove_with_null_data_in_ManyToMany_relationship()
    {
        // Arrange
        WorkItem existingWorkItem = _fakers.WorkItem.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/tags";

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

        // Assert
        httpResponse.ShouldHaveStatusCode(HttpStatusCode.UnprocessableEntity);

        responseDocument.Errors.ShouldHaveCount(1);

        ErrorObject error = responseDocument.Errors[0];
        error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
        error.Title.Should().Be("Failed to deserialize request body: Expected an array, instead of 'null'.");
        error.Detail.Should().BeNull();
        error.Source.ShouldNotBeNull();
        error.Source.Pointer.Should().Be("/data");
        error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
    }

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

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

        var requestBody = new
        {
            data = new
            {
            }
        };

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

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

        // Assert
        httpResponse.ShouldHaveStatusCode(HttpStatusCode.UnprocessableEntity);

        responseDocument.Errors.ShouldHaveCount(1);

        ErrorObject error = responseDocument.Errors[0];
        error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
        error.Title.Should().Be("Failed to deserialize request body: Expected an array, instead of an object.");
        error.Detail.Should().BeNull();
        error.Source.ShouldNotBeNull();
        error.Source.Pointer.Should().Be("/data");
        error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
    }

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

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

            existingWorkItem.Children.Add(existingWorkItem);
            await dbContext.SaveChangesAsync();
        });

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

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

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

        // Assert
        httpResponse.ShouldHaveStatusCode(HttpStatusCode.NoContent);

        responseDocument.Should().BeEmpty();

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

            workItemInDatabase.Children.ShouldHaveCount(1);
            workItemInDatabase.Children[0].Id.Should().Be(existingWorkItem.Children[0].Id);
        });
    }

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

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

            existingWorkItem.RelatedFrom.Add(existingWorkItem);
            await dbContext.SaveChangesAsync();
        });

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

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

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

        // Assert
        httpResponse.ShouldHaveStatusCode(HttpStatusCode.NoContent);

        responseDocument.Should().BeEmpty();

        await _testContext.RunOnDatabaseAsync(async dbContext =>
        {
            // @formatter:wrap_chained_method_calls chop_always
            // @formatter:keep_existing_linebreaks true

            WorkItem workItemInDatabase = await dbContext.WorkItems
                .Include(workItem => workItem.RelatedFrom)
                .Include(workItem => workItem.RelatedTo)
                .FirstWithIdAsync(existingWorkItem.Id);

            // @formatter:keep_existing_linebreaks restore
            // @formatter:wrap_chained_method_calls restore

            workItemInDatabase.RelatedFrom.ShouldHaveCount(1);
            workItemInDatabase.RelatedFrom[0].Id.Should().Be(existingWorkItem.RelatedFrom[0].Id);

            workItemInDatabase.RelatedTo.Should().BeEmpty();
        });
    }

    [Fact]
    public async Task Cannot_remove_with_blocked_capability()
    {
        // Arrange
        WorkItemGroup existingWorkItemGroup = _fakers.WorkItemGroup.Generate();

        await _testContext.RunOnDatabaseAsync(async dbContext =>
        {
            dbContext.Groups.Add(existingWorkItemGroup);
            await dbContext.SaveChangesAsync();
        });

        var requestBody = new
        {
            data = new[]
            {
                new
                {
                    type = "workItems",
                    id = Unknown.StringId.For<WorkItem, int>()
                }
            }
        };

        string route = $"/workItemGroups/{existingWorkItemGroup.StringId}/relationships/items";

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

        // Assert
        httpResponse.ShouldHaveStatusCode(HttpStatusCode.UnprocessableEntity);

        responseDocument.Errors.ShouldHaveCount(1);

        ErrorObject error = responseDocument.Errors[0];
        error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
        error.Title.Should().Be("Failed to deserialize request body: Relationship cannot be removed from.");
        error.Detail.Should().Be("The relationship 'items' on resource type 'workItemGroups' cannot be removed from.");
        error.Source.Should().BeNull();
        error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
    }

    [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)]
    private sealed class RemoveExtraFromWorkItemDefinition : JsonApiResourceDefinition<WorkItem, int>
    {
        // Enables to verify that not the full relationship was loaded upfront.
        public ISet<UserAccount> PreloadedSubscribers { get; } = new HashSet<UserAccount>(IdentifiableComparer.Instance);
        public ISet<WorkTag> PreloadedTags { get; } = new HashSet<WorkTag>(IdentifiableComparer.Instance);

        // Enables to verify that adding extra IDs for removal from ResourceDefinition works correctly.
        public ISet<long> ExtraSubscribersIdsToRemove { get; } = new HashSet<long>();
        public ISet<int> ExtraTagIdsToRemove { get; } = new HashSet<int>();

        public RemoveExtraFromWorkItemDefinition(IResourceGraph resourceGraph)
            : base(resourceGraph)
        {
        }

        public void Reset()
        {
            PreloadedSubscribers.Clear();
            PreloadedTags.Clear();

            ExtraSubscribersIdsToRemove.Clear();
            ExtraTagIdsToRemove.Clear();
        }

        public override Task OnRemoveFromRelationshipAsync(WorkItem workItem, HasManyAttribute hasManyRelationship, ISet<IIdentifiable> rightResourceIds,
            CancellationToken cancellationToken)
        {
            if (hasManyRelationship.Property.Name == nameof(WorkItem.Subscribers))
            {
                RemoveFromSubscribers(workItem, rightResourceIds);
            }
            else if (hasManyRelationship.Property.Name == nameof(WorkItem.Tags))
            {
                RemoveFromTags(workItem, rightResourceIds);
            }

            return Task.CompletedTask;
        }

        private void RemoveFromSubscribers(WorkItem workItem, ISet<IIdentifiable> rightResourceIds)
        {
            if (!workItem.Subscribers.IsNullOrEmpty())
            {
                PreloadedSubscribers.UnionWith(workItem.Subscribers);
            }

            foreach (long subscriberId in ExtraSubscribersIdsToRemove)
            {
                rightResourceIds.Add(new UserAccount
                {
                    Id = subscriberId
                });
            }
        }

        private void RemoveFromTags(WorkItem workItem, ISet<IIdentifiable> rightResourceIds)
        {
            if (!workItem.Tags.IsNullOrEmpty())
            {
                PreloadedTags.UnionWith(workItem.Tags);
            }

            foreach (int tagId in ExtraTagIdsToRemove)
            {
                rightResourceIds.Add(new WorkTag
                {
                    Id = tagId
                });
            }
        }
    }
}


text:
<?php

if (!defined('_PS_VERSION_'))
	exit;

class StatsBestVouchers extends ModuleGrid
{
	private $_html;
	private $_query;
	private $_columns;
	private $_defaultSortColumn;
	private $_defaultSortDirection;
	private $_emptyMessage;
	private $_pagingMessage;

	public function __construct()
	{
		$this->name = 'statsbestvouchers';
		$this->tab = 'analytics_stats';
		$this->version = 1.0;
		$this->author = 'PrestaShop';
		$this->need_instance = 0;

		parent::__construct();

		$this->_defaultSortColumn = 'ca';
		$this->_defaultSortDirection = 'DESC';
		$this->_emptyMessage = $this->l('Empty recordset returned');
		$this->_pagingMessage = sprintf($this->l('Displaying %1$s of %2$s'), '{0} - {1}', '{2}');

		$this->_columns = array(
			array(
				'id' => 'name',
				'header' => $this->l('Name'),
				'dataIndex' => 'name',
				'align' => 'left',
				'width' => 300
			),
			array(
				'id' => 'ca',
				'header' => $this->l('Sales'),
				'dataIndex' => 'ca',
				'width' => 30,
				'align' => 'right'
			),
			array(
				'id' => 'total',
				'header' => $this->l('Total used'),
				'dataIndex' => 'total',
				'width' => 30,
				'align' => 'right'
			)
		);

		$this->displayName = $this->l('Best vouchers');
		$this->description = $this->l('A list of the best vouchers');
	}

	public function install()
	{
		return (parent::install() && $this->registerHook('AdminStatsModules'));
	}

	public function hookAdminStatsModules($params)
	{
		$engineParams = array(
			'id' => 'id_product',
			'title' => $this->displayName,
			'columns' => $this->_columns,
			'defaultSortColumn' => $this->_defaultSortColumn,
			'defaultSortDirection' => $this->_defaultSortDirection,
			'emptyMessage' => $this->_emptyMessage,
			'pagingMessage' => $this->_pagingMessage
		);

		if (Tools::getValue('export'))
				$this->csvExport($engineParams);

		$this->_html = '

name.'">'.$this->displayName.'

			'.$this->engine($engineParams).'

'.$this->l('CSV Export').'

';
		return $this->_html;
	}

	public function getData()
	{
		$this->_query = 'SELECT SQL_CALC_FOUND_ROWS ocr.name as name, COUNT(ocr.id_cart_rule) as total, ROUND(SUM(o.total_paid_real) / o.conversion_rate, 2) as ca
				FROM '._DB_PREFIX_.'order_cart_rule ocr
				LEFT JOIN '._DB_PREFIX_.'orders o ON o.id_order = ocr.id_order
				WHERE o.valid = 1
					'.Shop::addSqlRestriction(Shop::SHARE_ORDER, 'o').'
					AND o.invoice_date BETWEEN '.$this->getDate().'
				GROUP BY ocr.id_cart_rule';
		if (Validate::IsName($this->_sort))
		{
			$this->_query .= ' ORDER BY `'.$this->_sort.'`';
			if (isset($this->_direction) && (strtoupper($this->_direction) == 'ASC' || strtoupper($this->_direction) == 'DESC'))
				$this->_query .= ' '.pSQL($this->_direction);
		}
		if (($this->_start === 0 || Validate::IsUnsignedInt($this->_start)) && Validate::IsUnsignedInt($this->_limit))
			$this->_query .= ' LIMIT '.$this->_start.', '.($this->_limit);
		$this->_values = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($this->_query);
		$this->_totalCount = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('SELECT FOUND_ROWS()');
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.nebhale.jsonpath.internal.parser;

/**
 * Represents a problem found during the parsing of a JSONPath expression
 *

 *
 * Concurrent Semantics

 *
 * Thread-safe
 */
public final class ExpressionProblem {

    private final String message;

    private final String source;

    private final int startPosition;

    private final int endPosition;

    public ExpressionProblem(String source, int problemPosition, String message, Object... args) {
        this(source, problemPosition, problemPosition, message, args);
    }

    public ExpressionProblem(String source, int startPosition, int endPosition, String messageFormat, Object... args) {
        this.message = String.format(messageFormat, args);
        this.source = source;
        this.startPosition = startPosition;
        this.endPosition = endPosition;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();

        sb.append(this.message).append("\n");
        sb.append(this.source).append("\n");

        for (int i = 0; i < this.startPosition; i++) {
            sb.append('-');
        }

        sb.append('^');

        int problemWidth = this.endPosition - this.startPosition;
        if (problemWidth > 0) {
            for (int i = 0; i < (problemWidth - 1); i++) {
                sb.append('_');
            }

            sb.append('^');
        }

        sb.append('\n');

        return sb.toString();
    }
}


text: print("3rd level module __name__:"+__name__)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.10"/>
<title>GeoFeatures: GFLineStringAbstract Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

GeoFeatures

A lightweight, high performance geometry library for Objective-C

Main Page

Related Pages

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

List of all members

GFLineStringAbstract Class Reference

An Abstract LineString implementation.
 More...

#import <GeoFeatures/GFLineStringAbstract.h>

Inheritance diagram for GFLineStringAbstract:

<map name="_g_f_line_string_abstract_inherit__map" id="_g_f_line_string_abstract_inherit__map">
<area shape="rect" id="node2" href="interface_g_f_geometry.html" title="An abstract class that represents a geometric shape. " alt="" coords="170,79,268,104"/>
</map>
[legend]

Collaboration diagram for GFLineStringAbstract:

<map name="_g_f_line_string_abstract_coll__map" id="_g_f_line_string_abstract_coll__map">
<area shape="rect" id="node2" href="interface_g_f_geometry.html" title="An abstract class that represents a geometric shape. " alt="" coords="170,79,268,104"/>
</map>
[legend]

Additional Inherited Members

 Instance Methods inherited from GFGeometry

(BOOL) 	- isValid

(double) 	- area

(double) 	- length

(double) 	- perimeter

(GFPoint *) 	- centroid

(GFBox *) 	- boundingBox

(BOOL) 	- within:

(GFGeometry *) 	- union_:

(NSDictionary *) 	- toGeoJSONGeometry

(NSArray *) 	- mkMapOverlays

(NSString *) 	- toWKTString

 Class Methods inherited from GFGeometry

(instancetype) 	+ geometryWithGeoJSONGeometry:

(instancetype) 	+ geometryWithWKT:

Detailed Description

An Abstract LineString implementation.

An Abstract LineString implementation which should not be instantiated on it's own.

Warning

Do not instantiate this abstract class.

Deprecated:

This class will be removed in v2, please don't directly rely on it at this point.

Author

Tony Stone

Date

6/6/15

The documentation for this class was generated from the following file:

GeoFeatures/GFLineStringAbstract.h

<address class="footer">
Generated on Tue Sep 29 2015 11:29:01 for GeoFeatures by

 1.8.10
</address>


text:
/* nav module configuration */
angular.module('pt.nav', []);


text:
package com.siyeh.ig.junit;

import com.intellij.codeInsight.TestFrameworks;
import com.intellij.codeInspection.naming.NamingConvention;
import com.intellij.codeInspection.naming.NamingConventionBean;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiTypeParameter;
import com.intellij.testIntegration.JavaTestFramework;
import com.intellij.testIntegration.TestFramework;
import com.siyeh.InspectionGadgetsBundle;

public class TestSuiteNamingConvention extends NamingConvention<PsiClass> {

  private static final int DEFAULT_MIN_LENGTH = 8;
  private static final int DEFAULT_MAX_LENGTH = 64;
  public static final String TEST_SUITE_NAMING_CONVENTION_SHORT_NAME = "TestSuiteNamingConvention";

  @Override
  public NamingConventionBean createDefaultBean() {
    return new NamingConventionBean("[A-Z][A-Za-z\\d]*Suite", DEFAULT_MIN_LENGTH, DEFAULT_MAX_LENGTH);
  }

  @Override
  public boolean isApplicable(PsiClass member) {
    if (member instanceof PsiTypeParameter) return false;
    TestFramework framework = TestFrameworks.detectFramework(member);
    return framework instanceof JavaTestFramework && framework.isTestClass(member) && ((JavaTestFramework)framework).isSuiteClass(member);
  }

  @Override
  public String getShortName() {
    return TEST_SUITE_NAMING_CONVENTION_SHORT_NAME;
  }

  @Override
  public String getElementDescription() {
    return InspectionGadgetsBundle.message("junit.test.suite.naming.convention.element.description");
  }
}


text:
CREATE TABLE `users` (
	`id` INT NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(300) NULL DEFAULT '0',
	`password` VARCHAR(300) NULL DEFAULT '0',
	PRIMARY KEY (`id`)
);

CREATE TABLE `orders` (
	`id` INT NOT NULL AUTO_INCREMENT,
	`title` VARCHAR(50) NOT NULL,
	`author_user_id` INT NOT NULL,
	`created` DATETIME NOT NULL,
	`order_time` VARCHAR(50) NOT NULL,
	`description` VARCHAR(50) NULL DEFAULT NULL,
	`archived` TINYINT NULL DEFAULT '0',
	`status` VARCHAR(50) NULL,
	PRIMARY KEY (`id`)
);

CREATE TABLE `messages` (
	`id` INT NOT NULL AUTO_INCREMENT,
	`order_id` INT(11) NOT NULL DEFAULT '0',
	`author_user_id` INT NOT NULL DEFAULT '0',
	`created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
	`message` VARCHAR(10000) NOT NULL,
	PRIMARY KEY (`id`)
);

CREATE TABLE `positions` (
	`id` INT NOT NULL AUTO_INCREMENT,
	`user_id` INT NOT NULL,
	`order_id` INT NOT NULL,
	`meal` VARCHAR(4000) NOT NULL,
	`cost` FLOAT NOT NULL,
	`paid` TINYINT NOT NULL DEFAULT '0',
	PRIMARY KEY (`id`)
);

CREATE TABLE `notifications` (
	`id` INT NOT NULL AUTO_INCREMENT,
	`created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
	`user_id` INT NOT NULL,
	`order_id` INT NULL,
	`title` VARCHAR(200) NOT NULL,
	`message` VARCHAR(4000) NOT NULL,
	`reload_order` TINYINT NOT NULL DEFAULT '0',
	`reload_orders` TINYINT(4) NOT NULL DEFAULT '0',
	`downloaded` TINYINT(4) NOT NULL DEFAULT '0',
	PRIMARY KEY (`id`)
);


text:
@implementation contact_Delegate

- (contact_Delegate*) initWithTask:(ForgeTask *)initTask {
	if (self = [super init]) {
		task = initTask;
		// "retain"
		me = self;
	}
	return self;
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {
	NSDictionary *data = [contact_Util dictFrom:person withFields:@[@"name", @"nickname", @"phoneNumbers", @"emails", @"addresses", @"ims", @"organizations", @"birthday", @"note", @"photos", @"categories", @"urls"]];

	[[[ForgeApp sharedApp] viewController] dismissViewControllerHelper:^{
		[task success:data];
		me = nil;
	}];
	return NO;
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
	// This should never happen
	[[[ForgeApp sharedApp] viewController] dismissViewControllerHelper:^{
		me = nil;
	}];
	return NO;
}

- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker {
	[[[ForgeApp sharedApp] viewController] dismissViewControllerHelper:^{
		[task error:@"Contact selection cancelled" type:@"EXPECTED_FAILURE" subtype:nil];
		me = nil;
	}];
}

// On iOS 8.0, a selected person is returned with this method.
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person
{
    NSDictionary *data = [contact_Util dictFrom:person withFields:@[@"name", @"nickname", @"phoneNumbers", @"emails", @"addresses", @"ims", @"organizations", @"birthday", @"note", @"photos", @"categories", @"urls"]];

    [[[ForgeApp sharedApp] viewController] dismissViewControllerHelper:^{
        [task success:data];
        me = nil;
    }];
}

- (void)newPersonViewController:(ABNewPersonViewController *)unknownCardViewController didCompleteWithNewPerson:(ABRecordRef)person {
    if (person == NULL) {
        [[[ForgeApp sharedApp] viewController] dismissViewControllerHelper:^{
            [task error:@"Contact addition cancelled" type:@"EXPECTED_FAILURE" subtype:nil];
            me = nil;
        }];

    } else {
        NSDictionary *data = [contact_Util dictFrom:person withFields:@[@"name", @"nickname", @"phoneNumbers", @"emails", @"addresses", @"birthday", @"note"]];
        [[[ForgeApp sharedApp] viewController] dismissViewControllerHelper:^{
            [task success:data];
            me = nil;
        }];
    }
}

@end


text:
/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 4.0.2
 *
 * Do not make changes to this file unless you know what you are doing--modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */

package org.pjsip.pjsua2;

public class AudioDevInfoVector extends java.util.AbstractList<AudioDevInfo> implements java.util.RandomAccess {
  private transient long swigCPtr;
  protected transient boolean swigCMemOwn;

  protected AudioDevInfoVector(long cPtr, boolean cMemoryOwn) {
    swigCMemOwn = cMemoryOwn;
    swigCPtr = cPtr;
  }

  protected static long getCPtr(AudioDevInfoVector obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }

  @SuppressWarnings("deprecation")
  protected void finalize() {
    delete();
  }

  public synchronized void delete() {
    if (swigCPtr != 0) {
      if (swigCMemOwn) {
        swigCMemOwn = false;
        pjsua2JNI.delete_AudioDevInfoVector(swigCPtr);
      }
      swigCPtr = 0;
    }
  }

  public AudioDevInfoVector(AudioDevInfo[] initialElements) {
    this();
    reserve(initialElements.length);

    for (AudioDevInfo element : initialElements) {
      add(element);
    }
  }

  public AudioDevInfoVector(Iterable<AudioDevInfo> initialElements) {
    this();
    for (AudioDevInfo element : initialElements) {
      add(element);
    }
  }

  public AudioDevInfo get(int index) {
    return doGet(index);
  }

  public AudioDevInfo set(int index, AudioDevInfo e) {
    return doSet(index, e);
  }

  public boolean add(AudioDevInfo e) {
    modCount++;
    doAdd(e);
    return true;
  }

  public void add(int index, AudioDevInfo e) {
    modCount++;
    doAdd(index, e);
  }

  public AudioDevInfo remove(int index) {
    modCount++;
    return doRemove(index);
  }

  protected void removeRange(int fromIndex, int toIndex) {
    modCount++;
    doRemoveRange(fromIndex, toIndex);
  }

  public int size() {
    return doSize();
  }

  public AudioDevInfoVector() {
    this(pjsua2JNI.new_AudioDevInfoVector__SWIG_0(), true);
  }

  public AudioDevInfoVector(AudioDevInfoVector other) {
    this(pjsua2JNI.new_AudioDevInfoVector__SWIG_1(AudioDevInfoVector.getCPtr(other), other), true);
  }

  public long capacity() {
    return pjsua2JNI.AudioDevInfoVector_capacity(swigCPtr, this);
  }

  public void reserve(long n) {
    pjsua2JNI.AudioDevInfoVector_reserve(swigCPtr, this, n);
  }

  public boolean isEmpty() {
    return pjsua2JNI.AudioDevInfoVector_isEmpty(swigCPtr, this);
  }

  public void clear() {
    pjsua2JNI.AudioDevInfoVector_clear(swigCPtr, this);
  }

  public AudioDevInfoVector(int count, AudioDevInfo value) {
    this(pjsua2JNI.new_AudioDevInfoVector__SWIG_2(count, AudioDevInfo.getCPtr(value), value), true);
  }

  private int doSize() {
    return pjsua2JNI.AudioDevInfoVector_doSize(swigCPtr, this);
  }

  private void doAdd(AudioDevInfo x) {
    pjsua2JNI.AudioDevInfoVector_doAdd__SWIG_0(swigCPtr, this, AudioDevInfo.getCPtr(x), x);
  }

  private void doAdd(int index, AudioDevInfo x) {
    pjsua2JNI.AudioDevInfoVector_doAdd__SWIG_1(swigCPtr, this, index, AudioDevInfo.getCPtr(x), x);
  }

  private AudioDevInfo doRemove(int index) {
    long cPtr = pjsua2JNI.AudioDevInfoVector_doRemove(swigCPtr, this, index);
    return (cPtr == 0) ? null : new AudioDevInfo(cPtr, false);
  }

  private AudioDevInfo doGet(int index) {
    long cPtr = pjsua2JNI.AudioDevInfoVector_doGet(swigCPtr, this, index);
    return (cPtr == 0) ? null : new AudioDevInfo(cPtr, false);
  }

  private AudioDevInfo doSet(int index, AudioDevInfo val) {
    long cPtr = pjsua2JNI.AudioDevInfoVector_doSet(swigCPtr, this, index, AudioDevInfo.getCPtr(val), val);
    return (cPtr == 0) ? null : new AudioDevInfo(cPtr, false);
  }

  private void doRemoveRange(int fromIndex, int toIndex) {
    pjsua2JNI.AudioDevInfoVector_doRemoveRange(swigCPtr, this, fromIndex, toIndex);
  }

}


text:
Edit Staff

Dosen

Staff

Jabatan

		<form method='POST' <?php echo "action='$database?pilih=staff&untukdi=edit'";?>  name='editstaff' id='editstaff'  enctype="multipart/form-data">
		<?php
		$edit=mysql_query("SELECT * FROM sh_guru_staff, sh_jabatan WHERE sh_guru_staff.id_jabatan=sh_jabatan.id_jabatan AND id_gurustaff='$_GET[id]'");
		$r=mysql_fetch_array($edit);

		echo "<input type='hidden' name='id' value='$r[id_gurustaff]'";
		?>

Nama Staff	<input type="text" name="nama_staff" class="maksimal" value="<?php echo"$r[nama_gurustaff]";?>">

NIP	<input type="text" name="nip" class="pendek" value="<?php echo"$r[nip]";?>">

Foto	<img src="../images/foto/guru/<?php echo "$r[foto]";?>" width="200px">
				<?php if ($r[foto] !='no_photo.jpg'){?>

				<a href="<?php echo "$database?pilih=staff&untukdi=hapusgambar&id=$r[id_gurustaff]";?>">Hapus gambar

				<?php } ?>

Ganti Foto	<input type="file" name="fupload">

Jenis Kelamin

			<?php if ($r[jenkel]=='L'){ ?>
					<input type="radio" name="jk" value="L" checked/>Laki-laki
					<input type="radio" name="jk" value="P"/>Perempuan
			<?php }
			else { ?>
					<input type="radio" name="jk" value="L"/>Laki-laki
					<input type="radio" name="jk" value="P" checked/>Perempuan
			<?php } ?>

Tempat, Tanggal Lahir
			<input type="text" name="tempat_lahir" class="pendek" value="<?php echo"$r[tempat_lahir]";?>">,
			<input type="text" id="tanggal" name="tanggal_lahir" class="pendek" style="width:20%" value="<?php echo"$r[tanggal_lahir]";?>">

Jabatan

					<select name="jabatan">
						<option value="<?php echo "$r[id_jabatan]";?>" selected><?php echo "$r[nama_jabatan]";?></option>
						<?php
						$jabatan=mysql_query("SELECT * FROM sh_jabatan ORDER BY nama_jabatan ASC");
						while ($j=mysql_fetch_array($jabatan)){
						echo "<option value='$j[id_jabatan]'>$j[nama_jabatan]</option>"; }
						?>
					</select>

Alamat	<textarea name="alamat" style="height: 100px"><?php echo"$r[alamat]";?></textarea>

Pendidikan Terakhir

					<select name="pendidikan">
						<option value="<?php echo "$r[pendidikan_terakhir]";?>" selected><?php echo "$r[pendidikan_terakhir]";?></option>
						<option value="SMA sederajat">SMA sederajat</option>
						<option value="Diploma 1 (D1)">Diploma 1 (D1)</option>
						<option value="Diploma 2 (D2)">Diploma 2 (D2)</option>
						<option value="Diploma 3 (D3)">Diploma 3 (D3)</option>
						<option value="Strata 1 (S1)">Strata 1 (S1)</option>
						<option value="Magister (S2)">Magister (S2)</option>
						<option value="Doktor (S3)">Doktor (S3)</option>
					</select>

Tahun Masuk
			<?php
				$thn_skrg=date("Y");
				echo "<select name=tahun_masuk>
				<option value='$r[tahun_masuk]' selected>$r[tahun_masuk]</option>";
				for ($thn=1990;$thn<=$thn_skrg;$thn++){
				echo "<option value=$thn>$thn</option>";
				}
				echo "</select>"; ?>

Status Perkawinan

					<select name="status_kawin">
						<option value="<?php echo "$r[status_kawin]";?>" selected><?php echo "$r[status_kawin]";?></option>
						<option value="Menikah">Menikah</option>
						<option value="Belum Menikah">Belum menikah</option>
						<option value="Duda">Duda</option>
						<option value="Janda">Janda</option>
					</select>

Email	<input type="text" name="email" class="pendek" value="<?php echo"$r[email]";?>">

Telepon/ HP	<input type="text" name="telepon" class="pendek" value="<?php echo"$r[telepon]";?>">

			<input type="submit" class="pencet" value="Update">
			<input type="button" class="hapus" value="Batal" onclick="self.history.back()">

		</form>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="keyword"  content="">
    <link rel="shortcut icon" href="/img/favicon.ico">

    <title>Python magic methods (1) - Python consulting | Data structure | Algorithm | Python tutor | Python辅导</title>

    <link rel="canonical" href="http://localhost:4000/blog/2016/12/23/python-magic-methods-1/">

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

    <link rel="stylesheet" href="/css/hux-blog.min.css">

    <link rel="stylesheet" href="/css/syntax.css">

    <link href="http://cdn.staticfile.org/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">

            <button type="button" class="navbar-toggle">
                Toggle navigation

            </button>
            All about Python

                        Home

                        Tags

                        Python tutor service

                        Python

                        advanced features

Python magic methods (1)

                    Posted by All about Python on December 23, 2016

Python magic methods (1) : __new__() and __init__()

In Python, magic methods are special methods where you can define to add "magic" to classes. They're always surrounded by double underscores (called 'dunder'). We will look into these magic methods in Object construction and initialization and see how they add advantages to python object oriented programming.

Object construction and initialization

__new__(cls, […): the first method to get called in an object's instantiation

__init__(self, […): the method get called to create objects of class

From the definition above, we see that __new__() accepts cls as it's first parameter, while __init__() accepts self. __init__() is called after __new__() when object is initialized.

Let's take a look at example below.

class MyClass(object):

    def __new__(cls):
        print "MyClass.__new__ called"
        return super(MyClass, cls).__new__(cls) # here super is type

    def __init__(self):
        print "MyClass.__init__ called"

if __name__ == '__main__':
    c = MyClass()

Result:

MyClass.__new__ called
MyClass.__init__ called

As we can see, __new__() method took cls as the input to create self object, then when a new MyClass object is instantiated, __init__() is called thereafter.

Another thing to note: __new__() is called automatically when calling the class name, which is when we do MyClass(). On the other hand, __init__() is called every time an instance of the class is returned by __new__() passing the returned instance to __init__() as 'self'.

As such, __new__() will return the instance of cls, and then, this new instance will be picked up by __init__(). If we ommit calling super for __new__() and not return anything, then __init__() won't be executed.

When to use __new__()?

If you want to control the actual creation process, use the __new__() method. If you intend to alter something like the base classes or the attributes, you'll have to do it in __new__().

Below example is to help to create a customized list with a method , "add". By default, python list doesn't have add method, but in this example we can create this customized list by adding add to the attr of the metaclass in __new__() method.

class ListMetaclass(type):
    def __new__(cls, name, bases, attrs):
        attrs['add'] = lambda self, value: self.append(value)
        return type.__new__(cls, name, bases, attrs)

class MyList(list):
    __metaclass__ = ListMetaclass # use ListMetaclass to customize class

if __name__ == '__main__':
    #c = MyClass()
    l = MyList()
    l.add(1)
    print (l)

Result:

[1]

The result shows this MyList() instance has a method add which adds elements to the list.

                        ← Previous Post

                        Next Post →

FEATURED TAGS

                                    Python

                                    Data Structure

                                    Function

                                    advanced features

FRIENDS

My Blog

                    Copyright © All about Python 2019

                    Theme by Hux |


text:
package sagex.miniclient.util;

import sagex.miniclient.uibridge.RectangleF;

/**
 * Created by seans on 16/12/16.
 */

public class AspectHelper {
    public static final RectangleF RectF_4_3 = new RectangleF(0,0,4,3);
    public static final RectangleF RectF_16_9 = new RectangleF(0,0,16,9);

    public static final float ar_4_3=4f/3f;
    public static final float ar_16_9=16f/9f;
    public static final float ar_tolerance=0.075f;

    public static boolean is_4_3(float ar) {
        return Math.abs(ar - ar_4_3) < ar_tolerance;
    }

    public static boolean is_16_9(float ar) {
        return Math.abs(ar - ar_16_9) < ar_tolerance;
    }

    public static boolean is_ar_equals(float ar1, float ar2) {
        return Math.abs(ar1 - ar2) < ar_tolerance;
    }

    public static float minScale(RectangleF src, RectangleF dest) {
        return Math.min( dest.width/src.width, dest.height/src.height);
    }

    public static float maxScale(RectangleF src, RectangleF dest) {
        return Math.max( dest.width/src.width, dest.height/src.height);
    }

    /**
     * Will fit src inside of dest ensuring that the result rectangle is exactly the same
     * height or width, scaling accordingly
     *
     * @param src
     * @param dest
     * @return
     */
    public static RectangleF fitInside(RectangleF src, RectangleF dest) {
        return scaleAndCenterRect(src, dest, minScale(src, dest));
    }

    /**
     * Will create a rect whereby src completly covers dest
     *
     * @param src
     * @param dest
     * @return
     */
    public static RectangleF fitOutside(RectangleF src, RectangleF dest) {
        return scaleAndCenterRect(src, dest, maxScale(src, dest));
    }

    /**
     * Fits src inside of dest such that src width is exactly the same as dest.  The resulting
     * rectangle's height will likely be larger than the dest height.
     * @param src
     * @param dest
     * @return
     */
    public static RectangleF fitWidth(RectangleF src, RectangleF dest) {
        return scaleAndCenterRect(src, dest, dest.width/src.width);
    }

    /**
     * Fits src inside of dest such that src height is exactly the same as dest.  The resulting
     * rectangle's width will likely be larger than the dest height.
     * @param src
     * @param dest
     * @return
     */
    public static RectangleF fitHeight(RectangleF src, RectangleF dest) {
        return scaleAndCenterRect(src, dest, dest.height/src.height);
    }

    /**
     * Scales the src rectangle by the scale, and then centers it in the destination rectangle.
     * @param src
     * @param dest
     * @param scale
     * @return
     */
    public static RectangleF scaleAndCenterRect(RectangleF src, RectangleF dest, float scale) {
        return src.scaleImmutable(scale).center(dest);
    }

    /**
     * Given the AR return a Rectangle over the video as it should be stretched.
     *
     * @param src
     * @param ar
     * @return
     */
    public static RectangleF stretch(RectangleF src, float ar) {
        if (is_4_3(ar)) {
            // assumption is that if you stretching 4/3 content then there is nothing to do
            // it will be stretched during the translation phase
            // we don't ever want to return the actual src, but a copy, because it might be changed
            return src.copy();
        } else {
            // assumption is that if you are stretching 16/9 then the content must be 4/3
            return fitInside(RectF_4_3, src).aspectRatioScale(src).center(src);
        }
    }

    /**
     * Given the AR, return a rectangle over the video as it should be zoomed
     *
     * @param src
     * @param ar
     * @return
     */
    public static RectangleF zoom(RectangleF src, float ar) {
        if (is_4_3(ar)) {
            // assumption is that if you stretching 4/3 content then content is 16/9 inside 4/3 rect
            RectangleF r169 = fitInside(RectF_16_9, src);
            r169.height = r169.width * 9 / 16;
            return r169.center(src).aspectRatioScale(src).center(src);
        } else {
            // assumption is that if you are zooming 16/9 then the content must be 16/9 letterbox
            // need to create 4/3 box, and inside that get a 16/9 box
            RectangleF r43 = fitInside(RectF_4_3, src);
            RectangleF r169 = fitInside(RectF_16_9, r43);
            r169.height=r169.width*9/16;
            return r169.center(src).aspectRatioScale(src).center(src);
        }
    }

//    public static RectangleF source(RectangleF src, float ar) {
//        RectangleF vid = AspectHelper.fitInside(src, screen);
//        return vid;
//    }

}


text:
namespace BluffinMuffin.Protocol.Lobby.RegisteredMode
{
    /// <summary>
    ///
    /// </summary>
    public class CreateUserResponse : AbstractBluffinReponse<CreateUserCommand>
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="command"></param>
        public CreateUserResponse(CreateUserCommand command)
            : base(command)
        {
        }
    }
}


text:
#pragma once
#ifndef tagvalue_def
#define tagvalue_def

#include "shared_ptr.h"

#include <string>
#include <vector>

struct TagValue
{
	TagValue() {}
	TagValue(const std::string& p_tag, const std::string& p_value)
		: tag(p_tag), value(p_value)
	{}

	std::string tag;
	std::string value;
};

typedef ibapi::shared_ptr<TagValue> TagValueSPtr;
typedef std::vector<TagValueSPtr> TagValueList;
typedef ibapi::shared_ptr<TagValueList> TagValueListSPtr;

#endif


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('photoplaces_web', '0007_auto_20141110_1910'),
    ]

    operations = [
        migrations.AddField(
            model_name='photoclusterrun',
            name='comment',
            field=models.TextField(default=b''),
            preserve_default=True,
        ),
    ]


text:
require 'spec_helper'

describe User do

  let(:username){ "James" }
  let(:email){ "zhiqiangzhan@gmail.com" }
  let(:uid){ "123556" }
  let(:provider) { "github" }

  let(:omniauth){
    Hashie::Mash.new(
      uid: uid,
      provider: provider,
      info: {
        nickname: username
      }
    )
  }

  let(:omniauth_with_email){
    omniauth.merge(uid: "111111", info: {email: email})
  }
  context "Save user to database." do
    before(:each){ User.find_by_omniauth(omniauth).delete }
    it "new user" do
      expect {
        User.from_omniauth(omniauth)
      }.to change(User, :count).by(1)
    end

    it "existing user" do
      user = User.from_omniauth(omniauth)
      expect {
        user2 = User.from_omniauth(omniauth)
        user2.should == user
      }.to change(User, :count).by(0)
    end
  end

  context 'check user necessary field' do
    let(:user) { User.from_omniauth(omniauth) }
    let(:user_with_email) { User.from_omniauth(omniauth_with_email) }

    it "check email" do
      user.email.should be_blank
      user_with_email.email.should == email
    end

    it "check user.name" do
      user.name.should == username
    end

    it "check authentications" do
      user.authentications.should_not be_empty
      user.authentications.detect{|auth| auth.uid.eql?(uid) && auth.provider.eql?(provider)}.should_not be_nil
    end

  end

  context "help method find_by_omniauth" do
    it "should return user when there is a user in database." do
      User.from_omniauth(omniauth)
      User.find_by_omniauth(omniauth).should_not be_empty
    end
  end

end


text:
package net.cassite.pure.ioc.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import net.cassite.pure.ioc.ExtendingHandler;

/**
 * This annotations aims to simplify retrieving objects from other object
 * containers.

 * e.g. if you need to retrieve an object from spring, you need to (for example)
 * create a Spring annotation, then create
 * SetterSpringHandler and ParamSpringHandler to
 * finish the injection and object-retrieving.

 * However the only extension was retrieving an object from Spring.

 * Now you can use this to simplify your retrieving process.
 *
 * @author wkgcass
 *
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.PARAMETER, ElementType.FIELD, ElementType.METHOD, ElementType.TYPE })
public @interface Extend {
        /**
         * ExtendingHandler implement class. The handler would be retrieved
         * using {@link net.cassite.pure.ioc.AutoWire#get(Class)}
         *
         * @return
         * @see net.cassite.pure.ioc.AutoWire#get(Class)
         * @see ExtendingHandler
         */
        @SuppressWarnings("rawtypes")
        Class handler();

        /**
         * Arguments to fill into your handler
         *
         * @return
         */
        String[]args();
}


text:
/*!
 * Start Bootstrap - Business Frontpage HTML Template (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

body {
    padding-top: 50px; /* Required padding for .navbar-fixed-top. Remove if using .navbar-static-top. Change if height of navigation changes. */
}

/* Header Image Background - Change the URL below to your image path (example: ../images/background.jpg) */

.business-header {
    height: 300px;
    background: url('../images/sistemaFinanceiro1.jpg') no-repeat scroll;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    background-size: cover;
    -o-background-size: cover;
}

/* Customize the text color and shadow color and to optimize text legibility. */

.justified-text{
    text-align: justify;
}

.development-team {
    text-align: center;
}

.tagline {
    text-shadow: 0 0 10px #000;
    color: #fff;
}

.img-center {
    margin: 0 auto;
}

a:link
{
 text-decoration:none;
}

footer {
    background-color: #292929;
    color: #ffffff;
}


text:
require 'helper'
class DirtyTest < Test::Unit::TestCase
  context 'Dirty' do
    setup do
      @time = Time.now
      @args = {
        :first_field => 'foo',
        :second_field => true,
        :third_field => 100,
      }
      @test_model = WithDirty.create(@args)
    end

    context 'after initialize' do
      should 'be dirty' do
        @test_model = WithDirty.new(@args)

        assert @test_model.changed?
        assert_same_elements @args.keys, @test_model.changed

        @test_model.changes.each do |key,value|
          assert value[0].nil?
          assert_equal @args[key], value[1]
        end
      end
    end

    context 'after load' do
      should 'be clean' do
        @model = WithDirty.get(first_field: 'foo')

        refute @model.changed?
        refute @model.changed.any?
      end

      context '& after modifying' do
        setup do
          @model = WithDirty.get(first_field: 'foo')
          @model.first_field = 'bar'
        end

        should 'be dirty' do
          assert @model.changed?
          assert_equal ['first_field'], @model.changed
          assert @model.first_field_changed?
          assert_equal ['foo', 'bar'], @model.first_field_change
          assert_equal 'foo', @model.first_field_was
        end

        context ' & after save' do
          should 'be clean once again' do
            @model.save
            refute @model.changed?
            refute @model.changed.any?

            # just to be sure it successfully saved itself
            assert WithDirty.get(first_field: 'bar')
          end
        end
      end

    end
  end
end


text:
/**
 * Module dependencies.
 */
var path = require('path'),
  spawn = require('child_process').spawn,
  temp = require('temp'),
  which = require('which'),
  fs = require('fs'),
  fsExt = require('./deps/core_ext/fs-ext'),
  Graph = require('./deps/graph').Graph;

/**
 * Create a new undirected graph
 * @constructor
 * @param {String} id The graphID
 * @return {Graph}
 * @api public
 */
exports.graph = function(id) {
  var graph = new Graph(null, id);
  graph.type = 'graph';
  return graph;
};

/**
 * Create a new directed graph
 * @constructor
 * @param {String} id The graphID
 * @param {Boolean} isStrict if the Graph is strict
 * @return {Graph}
 * @api public
 */
exports.digraph = function(id, isStrict = false) {
  var graph = new Graph(null, id);
  graph.type = 'digraph';
  graph.isStrict = isStrict;
  return graph;
};

function _parse(file, callback, errback) {
  which('gvpr', function(err, cmdPath) {
    if (err) {
      if (errback) {
        errback(-1, '', 'Command gvpr not found');
      }
    } else {
      var gvprScript = path.join(__dirname, 'ext', 'gvpr', 'dot2js.g'),
        parameters = ['-f' + gvprScript, file],
        __graph_eval,
        err = '',
        out = '',
        graphviz = spawn(cmdPath, parameters);

      graphviz.stdout.on('data', function(data) {
        out += data;
      });
      graphviz.stderr.on('data', function(data) {
        err += data;
      });
      graphviz.stdin.end();
      graphviz.on('exit', function(code) {
        if (code !== 0) {
          if (errback) {
            errback(code, out, err);
          }
        } else {
          eval(out.toString());
          if (typeof __graph_eval == 'undefined') {
            if (errback) {
              errback(code, out, '__graph_eval is not defined in call to graphviz');
            }
          } else {
            callback(__graph_eval);
          }
        }
      });
    }
  });
}
/**
 * Create a new graph from a dot script
 * @constructor
 * @param {String} file_or_script The DOT script or file
 * @param {Function} callback
 * @param {Function} errback
 * @api public
 */
exports.parse = function(file_or_script, callback, errback) {
  if (fsExt.exist(file_or_script)) {
    _parse(file_or_script, callback, errback);
  } else {
    temp.open('node-graphviz', function(err, info) {
      if (err) {
        return errback(err);
      }
      fs.write(info.fd, file_or_script, function(err) {
        if (err) {
          return errback(err);
        }
        fs.close(info.fd, function(err) {
          if (err) {
            return errback(err);
          }
          _parse(info.path, callback, errback);
        });
      });
    });
  }
};


text:
// Type definitions for urlencode 1.1
// Project: https://github.com/node-modules/urlencode
// Definitions by: My Self <https://github.com/kimcoder>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

interface charsetParam {
	charset: string;
}

/**
 * Encode string
 * @param str The string for encoding.
 */
declare function urlencode(str: string, charset?: string): string;

declare namespace urlencode {
	/**
	 * Encode string
	 * @param str The string for encoding.
	 */
	function encode(str: string, charset?: string): string;

	/**
	 * Decode string
	 * @param encodedString The encoded string.
	 */
	function decode(encodedString: string, charset?: string): string;

	/**
	 * Parse querystring
	 * @param queryString Querystring
	 * @param charsetParam The charset for parsing
	 */
	function parse(queryString: string, charsetParam: charsetParam): any;
	interface charsetParam {
		charset: string;
	}
	/**
	 * Stringify object
	 * @param obj Query Object
	 * @param charsetParam The charset for parsing
	 */
	function stringify(obj: any, prefix?: charsetParam, charsetParam?: charsetParam): string;
}

export = urlencode;


text:
Ng Emoji Picker
======================

Ng Emoji Picker is an angular directive for [Emoji Picker](https://github.com/OneSignal/emoji-picker), with the following modifications:

* **Removing wysiwyg editor Support**
* **Dynamic location for picker menu**
* **Moving Emoji images to /assets/images/ng-emoji-picker**

Installation
------------

### Bower
using [Bower](http://bower.io/).

```bash
bower install ng-emoji-picker --save
```

This will install the latest release.

Usage
-----
```javascript
angular.module('myApp', ['ngEmojiPicker']);
```
#### Copy Assets:
clone the img folder and place it in /assets/images/ng-emoji-picker

#### Basic Example:
```
<input emoji-picker type="text" ng-model="chat.message"/>
```

#### Full Example
```
<textarea emoji-picker ng-model="chat.message" emoji-attachment-location="bottom right" emoji-menu-location="top left" ng-keydown='handleKeyDown($event)'></textarea>
```
#### Style the emoji picker
Just add the following css
```
 .emoji-picker-icon{
    font-size:20px;
    right: 86px;
    top: 17px;
  }
```

#### Options:
* **emoji-attachment-location**
* **emoji-menu-location**
* --check [Tether.js](http://tether.io/) to know all the aligment tricks

### Bugs and feature requests
If you found a bug or have an idea feel free [to open a new issue](https://github.com/kimooz/ng-emoji-picker/issues/new).

### License
ng-emoji-picker is released under the MIT license.
```


text:
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle">
    <channel>
        <title>S3 Browser Changelog</title>
        <link>http://people.no-distance.net/ol/software/s3/</link>
        <description>Most recent changes with links to updates.</description>
        <language>en</language>
        <item>
            <guid>http://people.no-distance.net/ol/software/s3/S3-Browser-1.0.7.zip</guid>
            <title>Version 1.0.7</title>
            <description>

 Improved data display in operation inspector (#32)

 Fixed a potential crasher on time-out errors, and improve error reporting

 Bucket windows can be closed and reopened and have correct state shown (#36), contributed by mledford

 Number of maximum concurrent operations can be set in preferences (might help on very fast connections), please consider this feature as experimental

 Mime-type is now correctly set for css files (#34)

 Fixed a crash on an OS not released yet when opening the connection (#33)

 Improved handling of special characters and better date display (#30), contributed by Matt Johnston

			</description>
            <pubDate>20 May 2007 20:13:11 +0000</pubDate>
            <enclosure sparkle:version="109" sparkle:shortVersionString="1.0.7" url="http://people.no-distance.net/ol/software/s3/S3-Browser-1.0.7.zip" length="432559"
		type="application/octet-stream"/>
        </item>
        <item>
        	<guid>http://people.no-distance.net/ol/software/s3/S3-Browser-1.0.6.zip</guid>
            <title>Version 1.0.6</title>
            <description>

 Deleting access key ID in login box was crashing the application (#21)

 Fixes crashers on operation completion (#20, #24)

 Operations finishing in error should stay in the operation console (#27)

 Code reorganization

 (many fixes in this release contributed by mledford. Thanks!)

			</description>
            <pubDate>23 Jan 2007 12:46:11 +0000</pubDate>
            <enclosure sparkle:version="85" sparkle:shortVersionString="1.0.6" url="http://people.no-distance.net/ol/software/s3/S3-Browser-1.0.6.zip" length="425560"
type="application/octet-stream"/>
        </item>
        <item>
        	<guid>http://people.no-distance.net/ol/software/s3/S3-Browser-1.0.4.zip</guid>
            <title>Version 1.0.4</title>
            <description>

 Added support for auto-login (#17)

 Remember operation console visibility across launches (#18)

 Fixed a bug introduced in bucket name validation (#15): '.' is a valid character in buckets.

			</description>
            <pubDate>1 Jan 2007 20:39:11 +0000</pubDate>
            <enclosure sparkle:version="72" sparkle:shortVersionString="1.0.4" url="http://people.no-distance.net/ol/software/s3/S3-Browser-1.0.4.zip" length="414891"
type="application/octet-stream"/>
        </item>
        <item>
        	<guid>http://people.no-distance.net/ol/software/s3/S3-Browser-1.0.3.zip</guid>
            <title>Version 1.0.3</title>
            <description>

Fixed #15: should filter invalid characters in bucket names

            </description>
            <pubDate>31 Dec 2006 15:20:11 +0000</pubDate>
            <enclosure sparkle:version="66" sparkle:shortVersionString="1.0.3" url="http://people.no-distance.net/ol/software/s3/S3-Browser-1.0.3.zip" length="412773"
type="application/octet-stream"/>
        </item>
        <item>
        	<guid>http://people.no-distance.net/ol/software/s3/S3-Browser-1.0.2.zip</guid>
            <title>Version 1.0.2</title>
            <description>

Now uses Sparkle framework for application upgrade

Minor fix on operation failure

Better URL canonicalization

            </description>
            <pubDate>31 Dec 2006 02:20:11 +0000</pubDate>
            <enclosure sparkle:version="63" sparkle:shortVersionString="1.0.2" url="http://people.no-distance.net/ol/software/s3/S3-Browser-1.0.2.zip" length="411757"
type="application/octet-stream"/>
        </item>
    </channel>
</rss>


text:
#
# Copyright 2006-2008 Appcelerator, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

module Appcelerator
  module Update
    class Patch
      def Patch.crc32(c)
          r = 0xFFFFFFFF
          c.each_byte do |b|
              r ^= b
              8.times do
                r = (r>>1) ^ (0xEDB88320 * (r & 1))
              end
          end
          r ^ 0xFFFFFFFF
      end

      def Patch.install
        from_dir = $Installer[:to_dir]

            STDOUT.puts
            STDOUT.print "+ Performing self-update patch ... one moment \n"
            STDOUT.flush

        require 'digest/md5'

        # these are files that can't be patched
        excludes = %W(#{from_dir}/build.yml #{from_dir}/pre_flight.rb)

        if defined? SYSTEMDIR
            system_dir = SYSTEMDIR
        else
            system_dir = SCRIPTDIR
        end

        is_win32 = !(RUBY_PLATFORM =~ /(windows|win32)/).nil?
        files_to_copy = []

        Dir["#{from_dir}/**/**"].each do |file|
          next if excludes.include? file
          next if File.directory? file
          target = file.gsub("#{from_dir}/",'')
          target = File.join(system_dir, target)
          overwrite = File.exists? target

          if overwrite
            old_checksum = crc32( File.read(file) )
            new_checksum = crc32( File.read(target) )
            overwrite = old_checksum!=new_checksum
          end

          puts "!!! #{target}, overwrite=#{overwrite}"

          if overwrite
            if not File.writable? target
              person = is_win32 ? 'Administrator' : 'root'
              die "Can't write to file: #{target}. You must re-run this command as #{person}.  Sorry!"
            end

          end

          # attempt to create the directory now
          # to trigger any exceptions before file copies
          FileUtils.mkdir_p(File.dirname(target))
          files_to_copy << [file, target]
        end

        # do the actual copy in another step
        # once we know we can write all these
        # files without persmissions issues
        files_to_copy.each do |pair|
            source = pair[0]
            target = pair[1]
            FileUtils.cp_r(source, target)
        end

        STDOUT.puts 'Update patch complete...'
      end
    end
  end
end

Appcelerator::Update::Patch.install


text:
<?php echo __('Schedules fetched from Google are saved and updated in this SNS.') ?>

<?php echo __('If the public flag was set to [All Members], those schedules are public to SNS members.') ?>

<?php echo __('If the public flag was set to [Participants only scheduled public], those schedules can see the members that have the mail address related to Google Calendar and invited to schedules on Google Calendar. Thus, the all SNS member cannot those schedules.') ?>

<?php echo __('Then, the schedules you create are the only target of convert.') ?>

<?php
$options = array(
  'button' => __('Update'),
  'title' => __('Select to fetch Google Calendar'),
  'url' => url_for('calendar_api_import')
);

op_include_form('googleCalendarImportForm', $form, $options);
?>