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

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

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

            testContext.UseController<WorkItemsController>();
        }

        [Fact]
        public async Task Can_clear_OneToMany_relationship()
        {
            // 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 = Array.Empty<object>()
            };

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

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

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

            responseDocument.Should().BeEmpty();

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

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

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

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

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

            responseDocument.Should().BeEmpty();

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

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

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

            UserAccount existingSubscriber = _fakers.UserAccount.Generate();

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

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

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

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

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

            responseDocument.Should().BeEmpty();

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

                workItemInDatabase.Subscribers.Should().HaveCount(2);
                workItemInDatabase.Subscribers.Should().ContainSingle(userAccount => userAccount.Id == existingWorkItem.Subscribers.ElementAt(1).Id);
                workItemInDatabase.Subscribers.Should().ContainSingle(userAccount => userAccount.Id == existingSubscriber.Id);
            });
        }

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

            List<WorkTag> existingTags = _fakers.WorkTag.Generate(2);

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

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

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

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

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

            responseDocument.Should().BeEmpty();

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

                workItemInDatabase.Tags.Should().HaveCount(3);
                workItemInDatabase.Tags.Should().ContainSingle(workTag => workTag.Id == existingWorkItem.Tags.ElementAt(0).Id);
                workItemInDatabase.Tags.Should().ContainSingle(workTag => workTag.Id == existingTags[0].Id);
                workItemInDatabase.Tags.Should().ContainSingle(workTag => workTag.Id == existingTags[1].Id);
            });
        }

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

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

            string requestBody = string.Empty;

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

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

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

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

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

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

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

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

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

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

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

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

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

        [Fact]
        public async Task Cannot_replace_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.ExecutePatchAsync<Document>(route, requestBody);

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

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

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

        [Fact]
        public async Task Cannot_replace_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.ExecutePatchAsync<Document>(route, requestBody);

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

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

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

        [Fact]
        public async Task Cannot_replace_with_unknown_IDs_in_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.ExecutePatchAsync<Document>(route, requestBody);

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

            responseDocument.Errors.Should().HaveCount(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.");

            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.");
        }

        [Fact]
        public async Task Cannot_replace_with_unknown_IDs_in_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.ExecutePatchAsync<Document>(route, requestBody);

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

            responseDocument.Errors.Should().HaveCount(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.");

            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.");
        }

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

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

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

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

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

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

            responseDocument.Should().BeEmpty();
        }

        [Fact]
        public async Task Cannot_replace_on_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 = Array.Empty<object>()
            };

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            UserAccount existingSubscriber = _fakers.UserAccount.Generate();

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

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

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

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

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

            responseDocument.Should().BeEmpty();

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

                workItemInDatabase.Subscribers.Should().HaveCount(1);
                workItemInDatabase.Subscribers.Single().Id.Should().Be(existingSubscriber.Id);
            });
        }

        [Fact]
        public async Task Cannot_replace_with_null_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
            {
                data = (object)null
            };

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

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

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

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

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

        [Fact]
        public async Task Cannot_replace_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.ExecutePatchAsync<Document>(route, requestBody);

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

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

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

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

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

                existingWorkItem.Children = new List<WorkItem>
                {
                    existingWorkItem
                };

                await dbContext.SaveChangesAsync();
            });

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

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

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

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

            responseDocument.Should().BeEmpty();

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

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

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

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

                existingWorkItem.RelatedFrom = ArrayFactory.Create(existingWorkItem);
                await dbContext.SaveChangesAsync();
            });

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

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

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

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

            responseDocument.Should().BeEmpty();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                // @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.Should().BeEmpty();
                workItemInDatabase.RelatedTo.Should().BeEmpty();
            });
        }

        [Fact]
        public async Task Can_assign_cyclic_OneToMany_relationship()
        {
            // 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 = "workItems",
                        id = existingWorkItem.StringId
                    }
                }
            };

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

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

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

            responseDocument.Should().BeEmpty();

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

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

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

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

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

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

            responseDocument.Should().BeEmpty();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                // @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.Should().HaveCount(1);
                workItemInDatabase.RelatedFrom[0].Id.Should().Be(existingWorkItem.Id);

                workItemInDatabase.RelatedTo.Should().HaveCount(1);
                workItemInDatabase.RelatedTo[0].Id.Should().Be(existingWorkItem.Id);
            });
        }
    }
}


text:
package effect

import (
	"github.com/ambientsound/wirelight/labpanel/colorizer/panel"
	"github.com/lucasb-eyer/go-colorful"
)

// The distributor's job is to translate Panel messages to individual bulb colors.
type Distributor struct {
	Colorizers []Colorizer
	C          chan panel.Panel
}

const MAX_ADJUST_ANGLE = 360.0

func floattoangle(f float64) float64 {
	return f * MAX_ADJUST_ANGLE
}

func (d *Distributor) Run() {
	numBulbs := float64(len(d.Colorizers))

	for p := range d.C {
		// starting color
		c := p.Color()
		h, s, l := c.Clamped().Hsl()

		// we will draw colors within a subset of the color circle.
		// angle represents the hue range.
		angle := floattoangle(p.Adjust)

		// color distance from one bulb to the next
		distance := angle / numBulbs

		// adjust start hue so that target hue is in the middle
		h -= distance * 2

		for _, colorizer := range d.Colorizers {
			c = colorful.Hsl(h, s, l)
			colorizer.C <- c
			h += distance
			if h > 360.0 {
				h -= 360.0
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php
error_reporting(E_ALL ^ (E_NOTICE | E_WARNING | E_DEPRECATED));
$examp = $_GET["q"]; //query number
$page = $_GET['page']; // get the requested page
$limit = $_GET['rows']; // get how many rows we want to have into the grid
$sidx = $_GET['sidx']; // get index row - i.e. user click to sort
$sord = $_GET['sord']; // get the direction
$id = $_GET['id'];
if(!$sidx) $sidx =1;
// connect to the database

include("../server/connection.php");
$conn = mysql_connect("localhost", $connection['user'], $connection['password']);

mysql_select_db("shop") or die("Error connecting to db.");
mysql_set_charset('utf8');
switch ($examp) {
    case 1:
		$result = mysql_query("SELECT COUNT(*) AS count FROM linea_pedido");
		$row = mysql_fetch_array($result,MYSQL_ASSOC);
		$count = $row['count'];
		if( $count >0 ) {
			$total_pages = ceil($count/$limit);
		} else {
			$total_pages = 0;
		}
        if ($page > $total_pages) $page=$total_pages;
		$start = $limit*$page - $limit; // do not put $limit*($page - 1)
		if ($start<0) $start = 0;
        $SQL = "SELECT d.idPedido ,d.idArticulo ,a.nombre , d.unidad  ,d.precioTotal  FROM linea_pedido d ,articulo a WHERE  d.idPedido=".$id." and d.idArticulo=a.idArticulo ORDER BY $sidx $sord LIMIT $start , $limit";

		$result = mysql_query( $SQL ) or die("Couldn't execute query.".mysql_error());
        $i=0;
		while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
			$responce->rows[$i]['id']=$row['idPedido'];
            $responce->rows[$i]['cell']=array($row['idArticulo'],$row['nombre'],$row['unidad'],$row['precioTotal']);
            $i++;
		}
        echo json_encode($responce);
        break;
}
?>


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>at.irian.ankor.ref Class Hierarchy (Ankor - Project 0.1 API)</title>
<meta name="date" content="2014-02-27">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package at.irian.ankor.ref

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

at.irian.ankor.ref.RefContextFactoryProvider

Interface Hierarchy

at.irian.ankor.ref.RefContext

at.irian.ankor.ref.RefContextFactory

at.irian.ankor.ref.RefFactory

at.irian.ankor.ref.TypedRef<T>

at.irian.ankor.ref.Ref

at.irian.ankor.ref.CollectionRef

at.irian.ankor.ref.MapRef

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2014. All rights reserved.


text:
.class public abstract Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel;
.super Ljava/lang/Object;
.source "BaseModel.java"

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel$TA_TYPE_CODE;,
        Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel$USB_CLASS_CODE;
    }
.end annotation

# static fields
.field private static final TAG:Ljava/lang/String;

# instance fields
.field private mContext:Landroid/content/Context;

.field protected final mTATypeMap:Ljava/util/HashMap;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/HashMap",
            "<",
            "Ljava/lang/Integer;",
            "Ljava/lang/String;",
            ">;"
        }
    .end annotation
.end field

.field private final mUsbClassMap:Ljava/util/HashMap;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/HashMap",
            "<",
            "Ljava/lang/Integer;",
            "Ljava/lang/String;",
            ">;"
        }
    .end annotation
.end field

.field private final mUsbDeviceReceiver:Landroid/content/BroadcastReceiver;

# direct methods
.method static constructor <clinit>()V
    .locals 1

    const-class v0, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel;

    invoke-virtual {v0}, Ljava/lang/Class;->getSimpleName()Ljava/lang/String;

    move-result-object v0

    sput-object v0, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel;->TAG:Ljava/lang/String;

    return-void
.end method

.method constructor <init>(Landroid/content/Context;)V
    .locals 1

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    const/4 v0, 0x0

    iput-object v0, p0, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel;->mContext:Landroid/content/Context;

    new-instance v0, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel$1;

    invoke-direct {v0, p0}, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel$1;-><init>(Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel;)V

    iput-object v0, p0, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel;->mUsbClassMap:Ljava/util/HashMap;

    new-instance v0, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel$2;

    invoke-direct {v0, p0}, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel$2;-><init>(Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel;)V

    iput-object v0, p0, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel;->mTATypeMap:Ljava/util/HashMap;

    new-instance v0, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel$3;

    invoke-direct {v0, p0}, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel$3;-><init>(Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel;)V

    iput-object v0, p0, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel;->mUsbDeviceReceiver:Landroid/content/BroadcastReceiver;

    iput-object p1, p0, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel;->mContext:Landroid/content/Context;

    invoke-direct {p0}, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel;->init()V

    return-void
.end method

.method static synthetic access$000(Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel;Landroid/hardware/usb/UsbDevice;)V
    .locals 0

    invoke-direct {p0, p1}, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel;->updateUsbClassInfo(Landroid/hardware/usb/UsbDevice;)V

    return-void
.end method

.method static synthetic access$100()Ljava/lang/String;
    .locals 1

    sget-object v0, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel;->TAG:Ljava/lang/String;

    return-object v0
.end method

.method private init()V
    .locals 0

    invoke-direct {p0}, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel;->registerUsbReceiver()V

    return-void
.end method

.method private registerUsbReceiver()V
    .locals 3

    new-instance v0, Landroid/content/IntentFilter;

    const-string/jumbo v1, "android.hardware.usb.action.USB_DEVICE_ATTACHED"

    invoke-direct {v0, v1}, Landroid/content/IntentFilter;-><init>(Ljava/lang/String;)V

    iget-object v1, p0, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel;->mContext:Landroid/content/Context;

    iget-object v2, p0, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel;->mUsbDeviceReceiver:Landroid/content/BroadcastReceiver;

    invoke-virtual {v1, v2, v0}, Landroid/content/Context;->registerReceiver(Landroid/content/BroadcastReceiver;Landroid/content/IntentFilter;)Landroid/content/Intent;

    return-void
.end method

.method private updateUsbClassInfo(Landroid/hardware/usb/UsbDevice;)V
    .locals 4

    const/4 v2, 0x0

    invoke-virtual {p1}, Landroid/hardware/usb/UsbDevice;->getInterfaceCount()I

    move-result v1

    if-gtz v1, :cond_0

    :goto_0
    return-void

    :cond_0
    invoke-virtual {p1, v2}, Landroid/hardware/usb/UsbDevice;->getInterface(I)Landroid/hardware/usb/UsbInterface;

    move-result-object v1

    invoke-virtual {v1}, Landroid/hardware/usb/UsbInterface;->getInterfaceClass()I

    move-result v0

    invoke-virtual {p1}, Landroid/hardware/usb/UsbDevice;->getProductId()I

    move-result v2

    iget-object v1, p0, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel;->mUsbClassMap:Ljava/util/HashMap;

    invoke-static {v0}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v3

    invoke-virtual {v1, v3}, Ljava/util/HashMap;->get(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Ljava/lang/String;

    invoke-virtual {p0, v2, v1}, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel;->usbDeviceChanged(ILjava/lang/String;)V

    goto :goto_0
.end method

# virtual methods
.method destroy()V
    .locals 1

    invoke-virtual {p0}, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel;->unregisterReceiver()V

    const/4 v0, 0x0

    iput-object v0, p0, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel;->mContext:Landroid/content/Context;

    return-void
.end method

.method protected getContext()Landroid/content/Context;
    .locals 1

    iget-object v0, p0, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel;->mContext:Landroid/content/Context;

    return-object v0
.end method

.method unregisterReceiver()V
    .locals 2

    invoke-virtual {p0}, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel;->getContext()Landroid/content/Context;

    move-result-object v0

    iget-object v1, p0, Lcom/samsung/android/lib/dexcontrol/model/common/BaseModel;->mUsbDeviceReceiver:Landroid/content/BroadcastReceiver;

    invoke-virtual {v0, v1}, Landroid/content/Context;->unregisterReceiver(Landroid/content/BroadcastReceiver;)V

    return-void
.end method

.method protected abstract usbDeviceChanged(ILjava/lang/String;)V
.end method


text:
package vm

import (
	"context"
	"flag"
	"fmt"
	"io"
	"net/url"
	"os"

	"github.com/vmware/govmomi/govc/cli"
	"github.com/vmware/govmomi/govc/flags"
	"github.com/vmware/govmomi/object"
	"github.com/vmware/govmomi/session"
	"github.com/vmware/govmomi/vim25/soap"
	"github.com/vmware/govmomi/vim25/types"
)

type console struct {
	*flags.VirtualMachineFlag

	h5      bool
	wss     bool
	capture string
}

func init() {
	cli.Register("vm.console", &console{})
}

func (cmd *console) Register(ctx context.Context, f *flag.FlagSet) {
	cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
	cmd.VirtualMachineFlag.Register(ctx, f)

	f.BoolVar(&cmd.h5, "h5", false, "Generate HTML5 UI console link")
	f.BoolVar(&cmd.wss, "wss", false, "Generate WebSocket console link")
	f.StringVar(&cmd.capture, "capture", "", "Capture console screen shot to file")
}

func (cmd *console) Process(ctx context.Context) error {
	if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
		return err
	}
	return nil
}

func (cmd *console) Usage() string {
	return "VM"
}

func (cmd *console) Description() string {
	return `Generate console URL or screen capture for VM.

One of VMRC, VMware Player, VMware Fusion or VMware Workstation must be installed to
open VMRC console URLs.

Examples:
  govc vm.console my-vm
  govc vm.console -capture screen.png my-vm  # screen capture
  govc vm.console -capture - my-vm | display # screen capture to stdout
  open $(govc vm.console my-vm)              # MacOSX VMRC
  open $(govc vm.console -h5 my-vm)          # MacOSX H5
  xdg-open $(govc vm.console my-vm)          # Linux VMRC
  xdg-open $(govc vm.console -h5 my-vm)      # Linux H5`
}

func (cmd *console) Run(ctx context.Context, f *flag.FlagSet) error {
	vms, err := cmd.VirtualMachines(f.Args())
	if err != nil {
		return err
	}

	if len(vms) != 1 {
		return flag.ErrHelp
	}

	vm := vms[0]

	state, err := vm.PowerState(ctx)
	if err != nil {
		return err
	}

	if state != types.VirtualMachinePowerStatePoweredOn {
		return fmt.Errorf("vm is not powered on (%s)", state)
	}

	c := vm.Client()

	u := c.URL()

	if cmd.capture != "" {
		u.Path = "/screen"
		query := url.Values{"id": []string{vm.Reference().Value}}
		u.RawQuery = query.Encode()

		param := soap.DefaultDownload

		if cmd.capture == "-" {
			w, _, derr := c.Download(ctx, u, &param)
			if derr != nil {
				return derr
			}

			_, err = io.Copy(os.Stdout, w)
			if err != nil {
				return err
			}

			return w.Close()
		}

		return c.DownloadFile(ctx, cmd.capture, u, &param)
	}

	if cmd.wss {
		ticket, err := vm.AcquireTicket(ctx, string(types.VirtualMachineTicketTypeWebmks))
		if err != nil {
			return err
		}

		link := fmt.Sprintf("wss://%s:%d/ticket/%s", ticket.Host, ticket.Port, ticket.Ticket)
		fmt.Fprintln(cmd.Out, link)
		return nil
	}

	m := session.NewManager(c)
	ticket, err := m.AcquireCloneTicket(ctx)
	if err != nil {
		return err
	}

	var link string

	if cmd.h5 {
		m := object.NewOptionManager(c, *c.ServiceContent.Setting)

		opt, err := m.Query(ctx, "VirtualCenter.FQDN")
		if err != nil {
			return err
		}

		fqdn := opt[0].GetOptionValue().Value.(string)

		var info object.HostCertificateInfo
		err = info.FromURL(u, nil)
		if err != nil {
			return err
		}

		u.Path = "/ui/webconsole.html"

		u.RawQuery = url.Values{
			"vmId":          []string{vm.Reference().Value},
			"vmName":        []string{vm.Name()},
			"serverGuid":    []string{c.ServiceContent.About.InstanceUuid},
			"host":          []string{fqdn},
			"sessionTicket": []string{ticket},
			"thumbprint":    []string{info.ThumbprintSHA1},
		}.Encode()

		link = u.String()
	} else {
		link = fmt.Sprintf("vmrc://clone:%s@%s/?moid=%s", ticket, u.Hostname(), vm.Reference().Value)
	}

	fmt.Fprintln(cmd.Out, link)

	return nil
}


text:
> Vós fostes integrados no edifício que tem como fundamento os apóstolos.

**Leitura da Carta de São Paulo aos Efésios 2,19-22**

Irmãos:
19 Já não sois mais estrangeiros nem migrantes,
 mas concidadãos dos santos.
 Sois da família de Deus.
20 Vós fostes integrados no edifício
 que tem como fundamento os apóstolos e os profetas,
 e o próprio Jesus Cristo como pedra principal.
21 É nele que toda a construção se ajusta e se eleva
 para formar um templo santo no Senhor.
22 E vós também sois integrados nesta construção,
 para vos tornardes morada de Deus pelo Espírito.
 Palavra do Senhor.

## Salmo - Sl 18(19A),2-3.4-5 (R. 5a)

R. Seu som ressoa e se espalha em toda terra.  2 Os céus proclamam a glória do Senhor, *   e o firmamento, a obra de suas mãos;  3 o dia ao dia transmite esta mensagem, *   a noite à noite publica esta notícia.  R.  4 Não são discursos nem frases ou palavras, *   nem são vozes que possam ser ouvidas;  5 seu som ressoa e se espalha em toda a terra, *   chega aos confins do universo a sua voz.  R.

## Evangelho - Lc 6,12-19

> Passou a noite toda em oração. Escolheu doze dentre os discípulos, aos quais deu o nome de apóstolos.

**+ Proclamação do Evangelho de Jesus Cristo segundo São Lucas   6,12-19**

12 Naqueles dias, Jesus foi à montanha para rezar.
 E passou a noite toda em oração a Deus.
13 Ao amanhecer, chamou seus discípulos
 e escolheu doze dentre eles,
 aos quais deu o nome de apóstolos:
14 Simão, a quem impôs o nome de Pedro, e seu irmão André;
 Tiago e João;
 Filipe e Bartolomeu;
15 Mateus e Tomé;
 Tiago, filho de Alfeu, e Simão, chamado Zelota;
16 Judas, filho de Tiago,
 e Judas Iscariotes, aquele que se tornou traidor.
17 Jesus desceu da montanha com eles
 e parou num lugar plano.
 Ali estavam muitos dos seus discípulos
 e grande multidão de gente de toda a Judéia e de Jerusalém,
 do litoral de Tiro e Sidônia.
18 Vieram para ouvir Jesus
 e serem curados de suas doenças.
 E aqueles que estavam atormentados por espíritos maus
 também foram curados.
19 A multidão toda procurava tocar em Jesus,
 porque uma força saía dele, e curava a todos.
 Palavra da Salvação.

## Reflexão - Lc 6, 12-19

Jesus não quis realizar sozinho a obra do Reino, mas chamou apóstolos e discípulos para serem seus colaboradores. Nós, ao contrário, muitas vezes queremos fazer tudo sozinhos e afirmamos que os outros mais atrapalham que ajudam. Com isso, negamos a principal característica da obra evangelizadora que é a sua dimensão comunitário-participativa, além de nos fazermos auto-suficientes, perfeccionistas e maquiavélicos, pois em nome do resultado do trabalho evangelizador, excluímos os próprios evangelizadores, fazendo com que os fins justifiquem os meios e vivendo a mentalidade do mundo moderno da política de resultados, isto porque muitas vezes não somos evangelizadores, mas adoradores de nós mesmos.

Veja mais no [Liturgia Diária - CNBB](http://liturgiadiaria.cnbb.org.br/app/user/user/UserView.php?ano=2016&mes=10&dia=28)


text:
using namespace std;
using namespace triagens::basics;
using namespace triagens::arango;
using namespace triagens::rest;

////////////////////////////////////////////////////////////////////////////////
/// @brief slot for a "collection"
////////////////////////////////////////////////////////////////////////////////

static int const SLOT_COLLECTION = 2;

////////////////////////////////////////////////////////////////////////////////
/// @brief free a coordinator collection
////////////////////////////////////////////////////////////////////////////////

void FreeCoordinatorCollection (TRI_vocbase_col_t* collection) {
  TRI_DestroyReadWriteLock(&collection->_lock);
  TRI_Free(TRI_UNKNOWN_MEM_ZONE, collection);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief releases a collection
////////////////////////////////////////////////////////////////////////////////

void ReleaseCollection (TRI_vocbase_col_t const* collection) {
  TRI_ReleaseCollectionVocBase(collection->_vocbase, const_cast<TRI_vocbase_col_t*>(collection));
}

////////////////////////////////////////////////////////////////////////////////
/// @brief convert a collection info into a TRI_vocbase_col_t
////////////////////////////////////////////////////////////////////////////////

TRI_vocbase_col_t* CoordinatorCollection (TRI_vocbase_t* vocbase,
                                          CollectionInfo const& ci) {
  TRI_vocbase_col_t* c = static_cast<TRI_vocbase_col_t*>(TRI_Allocate(TRI_UNKNOWN_MEM_ZONE, sizeof(TRI_vocbase_col_t), false));

  if (c == nullptr) {
    return nullptr;
  }

  c->_internalVersion = 0;
  c->_isLocal         = false;
  c->_vocbase         = vocbase;
  c->_type            = ci.type();
  c->_cid             = ci.id();
  c->_planId          = ci.id();
  c->_status          = ci.status();
  c->_collection      = nullptr;

  std::string const name = ci.name();

  memset(c->_name, 0, TRI_COL_NAME_LENGTH + 1);
  memcpy(c->_name, name.c_str(), name.size());
  memset(c->_path, 0, TRI_COL_PATH_LENGTH + 1);

  memset(c->_dbName, 0, TRI_COL_NAME_LENGTH + 1);
  memcpy(c->_dbName, vocbase->_name, strlen(vocbase->_name));

  c->_canDrop   = true;
  c->_canUnload = true;
  c->_canRename = true;

  if (TRI_IsSystemNameCollection(c->_name)) {
    // a few system collections have special behavior
    if (TRI_EqualString(c->_name, TRI_COL_NAME_USERS) ||
        TRI_IsPrefixString(c->_name, TRI_COL_NAME_STATISTICS)) {
      // these collections cannot be dropped or renamed
      c->_canDrop   = false;
      c->_canRename = false;
    }
  }

  TRI_InitReadWriteLock(&c->_lock);

  return c;
}

///////////////////////////////////////////////////////////////////////////////
/// @brief check if a name belongs to a collection
////////////////////////////////////////////////////////////////////////////////

bool EqualCollection (CollectionNameResolver const* resolver,
                      string const& collectionName,
                      TRI_vocbase_col_t const* collection) {
  if (collectionName == StringUtils::itoa(collection->_cid)) {
    return true;
  }

  if (collectionName == string(collection->_name)) {
    return true;
  }

  if (ServerState::instance()->isCoordinator()) {
    if (collectionName == resolver->getCollectionNameCluster(collection->_cid)) {
      return true;
    }
    return false;
  }

  if (collectionName == resolver->getCollectionName(collection->_cid)) {
    return true;
  }

  return false;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief create a v8 collection id value from the internal collection id
////////////////////////////////////////////////////////////////////////////////

static inline v8::Handle<v8::Value> V8CollectionId (v8::Isolate* isolate, TRI_voc_cid_t cid) {
  char buffer[21];
  size_t len = TRI_StringUInt64InPlace((uint64_t) cid, (char*) &buffer);

  return TRI_V8_PAIR_STRING((const char*) buffer, (int) len);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief weak reference callback for collections
////////////////////////////////////////////////////////////////////////////////

static void WeakCollectionCallback (const v8::WeakCallbackData<v8::External, v8::Persistent<v8::External>>& data) {
  auto isolate      = data.GetIsolate();
  auto persistent   = data.GetParameter();
  auto myCollection = v8::Local<v8::External>::New(isolate, *persistent);
  auto collection   = static_cast<TRI_vocbase_col_t*>(myCollection->Value());
  TRI_GET_GLOBALS();

  v8g->decreaseActiveExternals();

  // decrease the reference-counter for the database
  TRI_ReleaseVocBase(collection->_vocbase);

  // find the persistent handle
#if TRI_ENABLE_MAINTAINER_MODE
  auto const& it = v8g->JSCollections.find(collection);
  TRI_ASSERT(it != v8g->JSCollections.end())
#endif
  if (! collection->_isLocal) {
    FreeCoordinatorCollection(collection);
  }
  // dispose and clear the persistent handle
  v8g->JSCollections[collection].Reset();
  v8g->JSCollections.erase(collection);
}

/////////////////////////////////////////////////////////////////////////////////
/// @brief wraps a TRI_vocbase_col_t
////////////////////////////////////////////////////////////////////////////////

v8::Handle<v8::Object> WrapCollection (v8::Isolate* isolate,
                                       TRI_vocbase_col_t const* collection) {
  v8::EscapableHandleScope scope(isolate);

  TRI_GET_GLOBALS();
  TRI_GET_GLOBAL(VocbaseColTempl, v8::ObjectTemplate);
  v8::Handle<v8::Object> result = VocbaseColTempl->NewInstance();

  if (! result.IsEmpty()) {
    TRI_vocbase_col_t* nonconstCollection = const_cast<TRI_vocbase_col_t*>(collection);

    result->SetInternalField(SLOT_CLASS_TYPE, v8::Integer::New(isolate, WRP_VOCBASE_COL_TYPE));
    result->SetInternalField(SLOT_CLASS, v8::External::New(isolate, nonconstCollection));

    auto const& it = v8g->JSCollections.find(nonconstCollection);

    if (it == v8g->JSCollections.end()) {
      // increase the reference-counter for the database
      TRI_UseVocBase(collection->_vocbase);
      auto externalCollection = v8::External::New(isolate, nonconstCollection);

      result->SetInternalField(SLOT_COLLECTION, externalCollection);

      v8g->JSCollections[nonconstCollection].Reset(isolate, externalCollection);
      v8g->JSCollections[nonconstCollection].SetWeak(&v8g->JSCollections[nonconstCollection],  WeakCollectionCallback);
      v8g->increaseActiveExternals();
    }
    else {
      auto myCollection = v8::Local<v8::External>::New(isolate, it->second);

      result->SetInternalField(SLOT_COLLECTION, myCollection);
    }
    TRI_GET_GLOBAL_STRING(_IdKey);
    TRI_GET_GLOBAL_STRING(_DbNameKey);
    TRI_GET_GLOBAL_STRING(VersionKeyHidden);
    result->ForceSet(_IdKey, V8CollectionId(isolate, collection->_cid), v8::ReadOnly);
    result->Set(_DbNameKey, TRI_V8_STRING(collection->_dbName));
    result->ForceSet(VersionKeyHidden, v8::Integer::NewFromUnsigned(isolate, collection->_internalVersion), v8::DontEnum);
  }

  return scope.Escape<v8::Object>(result);
}


text:
class TestNetworkChangeNotifier : public net::NetworkChangeNotifier {
 public:
  TestNetworkChangeNotifier()
      : net::NetworkChangeNotifier(),
        connection_type_to_return_(
            net::NetworkChangeNotifier::CONNECTION_UNKNOWN) {
  }

  // Simulates a change of the connection type to |type|. This will notify any
  // objects that are NetworkChangeNotifiers.
  void SimulateNetworkConnectionChange(
      net::NetworkChangeNotifier::ConnectionType type) {
    connection_type_to_return_ = type;
    net::NetworkChangeNotifier::NotifyObserversOfConnectionTypeChange();
    MessageLoop::current()->RunUntilIdle();
  }

 private:
  virtual ConnectionType GetCurrentConnectionType() const OVERRIDE {
    return connection_type_to_return_;
  }

  // The currently simulated network connection type. If this is set to
  // CONNECTION_NONE, then NetworkChangeNotifier::IsOffline will return true.
  net::NetworkChangeNotifier::ConnectionType connection_type_to_return_;

  DISALLOW_COPY_AND_ASSIGN(TestNetworkChangeNotifier);
};

// A test fixture class for ResourceRequestAllowedNotifier tests that require
// network state simulations. This also acts as the service implementing the
// ResourceRequestAllowedNotifier::Observer interface.
class ResourceRequestAllowedNotifierTest
    : public testing::Test,
      public ResourceRequestAllowedNotifier::Observer {
 public:
  ResourceRequestAllowedNotifierTest()
    : ui_thread(content::BrowserThread::UI, &message_loop),
      was_notified_(false) {
#if defined(OS_CHROMEOS)
    // Set this flag to true so the Init call sets up the wait on the EULA.
    SetNeedsEulaAcceptance(true);
#endif
    resource_request_allowed_notifier_.Init(this);
  }
  virtual ~ResourceRequestAllowedNotifierTest() { }

  bool was_notified() const { return was_notified_; }

  // ResourceRequestAllowedNotifier::Observer override:
  virtual void OnResourceRequestsAllowed() OVERRIDE {
    was_notified_ = true;
  }

  // Network manipulation methods:
  void SetWasWaitingForNetwork(bool waiting) {
    resource_request_allowed_notifier_.
        SetWasWaitingForNetworkForTesting(waiting);
  }

  void SimulateNetworkConnectionChange(
      net::NetworkChangeNotifier::ConnectionType type) {
    network_notifier.SimulateNetworkConnectionChange(type);
  }

  // Simulate a resource request from the test service.
  void SimulateResourceRequest() {
    resource_request_allowed_notifier_.ResourceRequestsAllowed();
  }

#if defined(OS_CHROMEOS)
  // Eula manipulation methods:
  void SetNeedsEulaAcceptance(bool needs_acceptance) {
    resource_request_allowed_notifier_.SetNeedsEulaAcceptance(needs_acceptance);
  }

  void SetWasWaitingForEula(bool waiting) {
    resource_request_allowed_notifier_.SetWasWaitingForEulaForTesting(waiting);
  }

  void SimulateEulaAccepted() {
    SetNeedsEulaAcceptance(false);
    content::NotificationService::current()->Notify(
        chrome::NOTIFICATION_WIZARD_EULA_ACCEPTED,
        content::NotificationService::AllSources(),
        content::NotificationService::NoDetails());
  }

  // Used in tests involving the EULA. Disables both the EULA accepted state
  // and the network.
  void DisableEulaAndNetwork() {
    SetWasWaitingForNetwork(true);
    SimulateNetworkConnectionChange(
        net::NetworkChangeNotifier::CONNECTION_NONE);
    SetWasWaitingForEula(true);
    SetNeedsEulaAcceptance(true);
  }
#endif

  virtual void SetUp() OVERRIDE {
    // Assume the test service has already requested permission, as all tests
    // just test that criteria changes notify the server.
#if defined(OS_CHROMEOS)
    // Set default EULA state to done (not waiting and EULA accepted) to
    // simplify non-ChromeOS tests.
    SetWasWaitingForEula(false);
    SetNeedsEulaAcceptance(false);
#endif
  }

 private:
  MessageLoopForUI message_loop;
  content::TestBrowserThread ui_thread;
  TestNetworkChangeNotifier network_notifier;
  TestRequestAllowedNotifier resource_request_allowed_notifier_;
  bool was_notified_;

  DISALLOW_COPY_AND_ASSIGN(ResourceRequestAllowedNotifierTest);
};

TEST_F(ResourceRequestAllowedNotifierTest, DoNotNotifyIfOffline) {
  SimulateResourceRequest();
  SetWasWaitingForNetwork(true);
  SimulateNetworkConnectionChange(net::NetworkChangeNotifier::CONNECTION_NONE);
  EXPECT_FALSE(was_notified());
}

TEST_F(ResourceRequestAllowedNotifierTest, DoNotNotifyIfOnlineToOnline) {
  SimulateResourceRequest();
  SetWasWaitingForNetwork(false);
  SimulateNetworkConnectionChange(
      net::NetworkChangeNotifier::CONNECTION_ETHERNET);
  EXPECT_FALSE(was_notified());
}

TEST_F(ResourceRequestAllowedNotifierTest, NotifyOnReconnect) {
  SimulateResourceRequest();
  SetWasWaitingForNetwork(true);
  SimulateNetworkConnectionChange(
      net::NetworkChangeNotifier::CONNECTION_ETHERNET);
  EXPECT_TRUE(was_notified());
}

TEST_F(ResourceRequestAllowedNotifierTest, NoNotifyOnWardriving) {
  SimulateResourceRequest();
  SetWasWaitingForNetwork(false);
  SimulateNetworkConnectionChange(
      net::NetworkChangeNotifier::CONNECTION_WIFI);
  EXPECT_FALSE(was_notified());
  SimulateNetworkConnectionChange(
      net::NetworkChangeNotifier::CONNECTION_3G);
  EXPECT_FALSE(was_notified());
  SimulateNetworkConnectionChange(
      net::NetworkChangeNotifier::CONNECTION_4G);
  EXPECT_FALSE(was_notified());
  SimulateNetworkConnectionChange(
      net::NetworkChangeNotifier::CONNECTION_WIFI);
  EXPECT_FALSE(was_notified());
}

TEST_F(ResourceRequestAllowedNotifierTest, NoNotifyOnFlakyConnection) {
  SimulateResourceRequest();
  SetWasWaitingForNetwork(false);
  SimulateNetworkConnectionChange(
      net::NetworkChangeNotifier::CONNECTION_WIFI);
  EXPECT_FALSE(was_notified());
  SimulateNetworkConnectionChange(
      net::NetworkChangeNotifier::CONNECTION_NONE);
  EXPECT_FALSE(was_notified());
  SimulateNetworkConnectionChange(
      net::NetworkChangeNotifier::CONNECTION_WIFI);
  EXPECT_FALSE(was_notified());
}

TEST_F(ResourceRequestAllowedNotifierTest, NoRequestNoNotify) {
  // Ensure that if the observing service does not request access, it does not
  // get notified, even if the criteria is met. Note that this is done by not
  // calling SimulateResourceRequest here.
  SetWasWaitingForNetwork(true);
  SimulateNetworkConnectionChange(
      net::NetworkChangeNotifier::CONNECTION_ETHERNET);
  EXPECT_FALSE(was_notified());
}

#if defined(OS_CHROMEOS)
TEST_F(ResourceRequestAllowedNotifierTest, EulaOnlyNetworkOffline) {
  SimulateResourceRequest();
  DisableEulaAndNetwork();

  SimulateEulaAccepted();
  EXPECT_FALSE(was_notified());
}

TEST_F(ResourceRequestAllowedNotifierTest, EulaFirst) {
  SimulateResourceRequest();
  DisableEulaAndNetwork();

  SimulateEulaAccepted();
  EXPECT_FALSE(was_notified());

  SimulateNetworkConnectionChange(
      net::NetworkChangeNotifier::CONNECTION_WIFI);
  EXPECT_TRUE(was_notified());
}

TEST_F(ResourceRequestAllowedNotifierTest, NetworkFirst) {
  SimulateResourceRequest();
  DisableEulaAndNetwork();

  SimulateNetworkConnectionChange(
      net::NetworkChangeNotifier::CONNECTION_WIFI);
  EXPECT_FALSE(was_notified());

  SimulateEulaAccepted();
  EXPECT_TRUE(was_notified());
}

TEST_F(ResourceRequestAllowedNotifierTest, NoRequestNoNotifyEula) {
  // Ensure that if the observing service does not request access, it does not
  // get notified, even if the criteria is met. Note that this is done by not
  // calling SimulateResourceRequest here.
  DisableEulaAndNetwork();

  SimulateNetworkConnectionChange(
      net::NetworkChangeNotifier::CONNECTION_WIFI);
  EXPECT_FALSE(was_notified());

  SimulateEulaAccepted();
  EXPECT_FALSE(was_notified());
}
#endif  // OS_CHROMEOS


text:
const crypto = require('crypto');
const mongoose = require('mongoose');

const ChallengeSchema = new mongoose.Schema({
  code: { type: String, unique: true },
  num: String,
  name: String,
  detail: String,
  points: Number,
  isValid : Number,
  teams: Array
}, { timestamps: true });

const Challenge = mongoose.model('Challenge', ChallengeSchema);

module.exports = Challenge;


text:
<?php
/**
 * BMBtnSkillPappy: Code specific to Pappy
 *
 * @author: james
 */

/**
 * This class currently allows Pappy to be re-enabled at
 * button selection.
 */
class BMBtnSkillPappy extends BMBtnSkillArtificialReenable {

}


text:
/*
 * Do not modify this file. This file is generated from the route53-2013-04-01.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;

using Amazon.Route53.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;

namespace Amazon.Route53.Model.Internal.MarshallTransformations
{
    /// <summary>
    /// Response Unmarshaller for DelegationSet Object
    /// </summary>
    public class DelegationSetUnmarshaller : IUnmarshaller<DelegationSet, XmlUnmarshallerContext>
    {
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public DelegationSet Unmarshall(XmlUnmarshallerContext context)
        {
            DelegationSet unmarshalledObject = new DelegationSet();
            int originalDepth = context.CurrentDepth;
            int targetDepth = originalDepth + 1;

            if (context.IsStartOfDocument)
               targetDepth += 2;

            while (context.Read())
            {
                if (context.IsStartElement || context.IsAttribute)
                {
                    if (context.TestExpression("Id", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        unmarshalledObject.Id = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("CallerReference", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        unmarshalledObject.CallerReference = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("NameServers/NameServer", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        unmarshalledObject.NameServers.Add(unmarshaller.Unmarshall(context));
                        continue;
                    }
                }
                else if (context.IsEndElement && context.CurrentDepth < originalDepth)
                {
                    return unmarshalledObject;
                }
            }
            return unmarshalledObject;
        }

        private static DelegationSetUnmarshaller _instance = new DelegationSetUnmarshaller();

        /// <summary>
        /// Gets the singleton.
        /// </summary>
        public static DelegationSetUnmarshaller Instance
        {
            get
            {
                return _instance;
            }
        }
    }
}


text:
#include "audio_device_utility_ios.h"
#include "audio_device_config.h"

#include "critical_section_wrapper.h"
#include "trace.h"

namespace webrtc {
AudioDeviceUtilityIPhone::AudioDeviceUtilityIPhone(const int32_t id)
:
    _critSect(*CriticalSectionWrapper::CreateCriticalSection()),
    _id(id),
    _lastError(AudioDeviceModule::kAdmErrNone) {
    WEBRTC_TRACE(kTraceMemory, kTraceAudioDevice, id,
                 "%s created", __FUNCTION__);
}

AudioDeviceUtilityIPhone::~AudioDeviceUtilityIPhone() {
    WEBRTC_TRACE(kTraceMemory, kTraceAudioDevice, _id,
                 "%s destroyed", __FUNCTION__);
    CriticalSectionScoped lock(&_critSect);

    delete &_critSect;
}

int32_t AudioDeviceUtilityIPhone::Init() {
    WEBRTC_TRACE(kTraceModuleCall, kTraceAudioDevice, _id,
                 "%s", __FUNCTION__);

    WEBRTC_TRACE(kTraceStateInfo, kTraceAudioDevice, _id,
                 "  OS info: %s", "iOS");

    return 0;
}

}  //  namespace webrtc


text:
<?php

use opensrs\domains\dnszone\DnsDelete;

/**
 * @group dnszone
 * @group DnsDelete
 */
class DnsDeleteTest extends PHPUnit_Framework_TestCase
{
    protected $func = 'dnsDelete';

    protected $validSubmission = array(
        'attributes' => array(
            /*
             * Required
             *
             * domain: the domain for which you want
             *   to delete DNS records
             */
            'domain' => '',
            ),
        );

    /**
     * Valid submission should complete with no
     * exception thrown.
     *
     *
     * @group validsubmission
     */
    public function testValidSubmission()
    {
        $data = json_decode(json_encode($this->validSubmission));
        $data->attributes->domain = 'phptest'.time().'.com';

        $ns = new DnsDelete('array', $data);

        $this->assertTrue($ns instanceof DnsDelete);
    }

    /**
     * Data Provider for Invalid Submission test.
     */
    public function submissionFields()
    {
        return array(
            'missing domain' => array('domain'),
            );
    }

    /**
     * Invalid submission should throw an exception.
     *
     *
     * @dataProvider submissionFields
     * @group invalidsubmission
     */
    public function testInvalidSubmissionFieldsMissing($field, $parent = 'attributes', $message = null)
    {
        $data = json_decode(json_encode($this->validSubmission));
        $data->attributes->domain = 'phptest'.time().'.com';

        if (is_null($message)) {
            $this->setExpectedExceptionRegExp(
              'opensrs\Exception',
              "/$field.*not defined/"
              );
        } else {
            $this->setExpectedExceptionRegExp(
              'opensrs\Exception',
              "/$message/"
              );
        }

        // clear field being tested
        if (is_null($parent)) {
            unset($data->$field);
        } else {
            unset($data->$parent->$field);
        }

        $ns = new DnsDelete('array', $data);
    }
}


text:
package explorviz.live_trace_processing.external.kieker.signatureConverters;

import kieker.common.record.flow.trace.operation.BeforeOperationEvent;

public class EPrintsSignatureConverter implements SignatureConverter {
	@Override
	public String convertSignatureToExplorViz(final BeforeOperationEvent kiekerBefore) {
		return "public void " + kiekerBefore.getOperationSignature() + "()";
	}
}


text:
<?php

abstract class AbstractObjectJSON
{
    protected $backend_instance = null;
    protected $generate_filename = null;

    protected $dependencyInjector;

    protected $content = [];

    /**
     * @param \Pimple\Container $dependencyInjector
     * @return static
     */
    public static function getInstance(\Pimple\Container $dependencyInjector): static
    {
        /**
         * @var array<string, static>
         */
        static $instances = array();

        /**
         * @var class-string<static>
         */
        $calledClass = get_called_class();

        if (!isset($instances[$calledClass])) {
            $instances[$calledClass] = new $calledClass($dependencyInjector);
        }

        return $instances[$calledClass];
    }

    protected function __construct(\Pimple\Container $dependencyInjector)
    {
        $this->dependencyInjector = $dependencyInjector;
        $this->backend_instance = Backend::getInstance($this->dependencyInjector);
    }

    public function reset()
    {
    }

    protected function writeFile($dir)
    {
        $full_file = $dir . '/' . $this->generate_filename;
        if ($handle = fopen($full_file, 'w')) {
            if (!fwrite($handle, $this->content)) {
                throw new RuntimeException('Cannot write to file "' . $full_file . '"');
            }
            fclose($handle);
        } else {
            throw new Exception("Cannot open file " . $full_file);
        }
    }

    protected function generateFile($object)
    {
        $this->content = json_encode(['centreonBroker' => $object], JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT);
    }
}


text:
#ifndef TUDOR_ENVIRONMENT_H
#define TUDOR_ENVIRONMENT_H
#include <string>

class Environment
{
    private:
        std::string prefix;
        std::string separator;
        std::string expand_variable_name(const std::string& name);
    public:
        explicit Environment(std::string prefix);
        std::string get_prefix();
        void set_prefix(const std::string& prefix);
        std::string get_separator();
        void set_separator(const std::string& separator);
        std::string get_str(const std::string& variable_name,
                            const std::string& default_value = "",
                            const bool use_prefix = true);
        int get_int(const std::string& variable_name,
                    const int& default_value,
                    const int& min=0, const int& max=0,
                    const bool use_prefix = true);
};

#endif /* TUDOR_VOLUMED_ENVIRONMENT_H */


text:
import { Directive } from '@angular/core';

@Directive({
  selector: 'gio-form-label',
})
export class GioFormLabelDirective {}

@Directive({
  selector: '[gioFormPrefix]',
})
export class GioFormPrefixDirective {}

@Directive({
  selector: '[gioFormSlideToggle]',
})
export class GioFormSlideToggleDirective {}


text:
layout: error_500
css_filename: morph.css
---


text:
import unittest

import numpy as np
import tensorboard
import torch

from monai.visualize import make_animated_gif_summary

class TestImg2Tensorboard(unittest.TestCase):
    def test_write_gray(self):
        nparr = np.ones(shape=(1, 32, 32, 32), dtype=np.float32)
        summary_object_np = make_animated_gif_summary(
            tag="test_summary_nparr.png", image=nparr, max_out=1, scale_factor=253.0
        )
        for s in summary_object_np:
            assert isinstance(
                s, tensorboard.compat.proto.summary_pb2.Summary
            ), "make_animated_gif_summary must return a tensorboard.summary object from numpy array"

        tensorarr = torch.tensor(nparr)
        summary_object_tensor = make_animated_gif_summary(
            tag="test_summary_tensorarr.png", image=tensorarr, max_out=1, frame_dim=-1, scale_factor=253.0
        )
        for s in summary_object_tensor:
            assert isinstance(
                s, tensorboard.compat.proto.summary_pb2.Summary
            ), "make_animated_gif_summary must return a tensorboard.summary object from tensor input"

if __name__ == "__main__":
    unittest.main()


text:
<?php

namespace Symfony\Bundle\FrameworkBundle\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Templating\EngineInterface;
use Twig\Environment;

/**
 * TemplateController.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 *
 * @final since version 3.4
 */
class TemplateController
{
    private $twig;
    private $templating;

    public function __construct(Environment $twig = null, EngineInterface $templating = null)
    {
        $this->twig = $twig;
        $this->templating = $templating;
    }

    /**
     * Renders a template.
     *
     * @param string    $template  The template name
     * @param int|null  $maxAge    Max age for client caching
     * @param int|null  $sharedAge Max age for shared (proxy) caching
     * @param bool|null $private   Whether or not caching should apply for client caches only
     */
    public function templateAction(string $template, int $maxAge = null, int $sharedAge = null, bool $private = null): Response
    {
        if ($this->templating) {
            $response = new Response($this->templating->render($template));
        } elseif ($this->twig) {
            $response = new Response($this->twig->render($template));
        } else {
            throw new \LogicException('You can not use the TemplateController if the Templating Component or the Twig Bundle are not available.');
        }

        if ($maxAge) {
            $response->setMaxAge($maxAge);
        }

        if ($sharedAge) {
            $response->setSharedMaxAge($sharedAge);
        }

        if ($private) {
            $response->setPrivate();
        } elseif (false === $private || (null === $private && ($maxAge || $sharedAge))) {
            $response->setPublic();
        }

        return $response;
    }
}


text:
using NBitcoin;
using System;

namespace NBXplorer.Backends
{
	public class SavedTransaction
	{
		public NBitcoin.Transaction Transaction
		{
			get; set;
		}
		public uint256 BlockHash
		{
			get; set;
		}
		public long? BlockHeight
		{
			get; set;
		}
		public DateTimeOffset Timestamp
		{
			get;
			set;
		}
	}
}


text:
<?php

declare(strict_types=1);

namespace Hostnet\Component\CssSniff\Sniff;

use Hostnet\Component\CssSniff\File;
use Hostnet\Component\CssSniff\SniffInterface;
use Yannickl88\Component\CSS\Token;

final class EmptySniff implements SniffInterface
{
    public function register(): array
    {
        return [
            Token::T_OPENCURLY,
        ];
    }

    public function process(File $file, int $stack_ptr): void
    {
        $next = $file->findNextNot(Token::T_WHITESPACE, $stack_ptr + 1);

        if (null === $next || $next->type !== Token::T_CLOSECURLY) {
            return;
        }

        $file->addViolation(
            self::class,
            'CSS block should not be empty.',
            $next->lines[0],
            $next->offsets[0],
            $next->offsets[0] + strlen($next->chars)
        );
    }
}


text:
require 'jasper/connection_adapters/connection_pool'
require 'jasper/connection_adapters/connection_specification'
require 'jasper/connection_handling'

module Jasper
  # Base class for Jasper Models.
  class Base
    include ::ActiveModel::Conversion
    include ::ActiveModel::Validations
    extend  ::ActiveModel::Naming
    extend  ::ActiveModel::Translation
    extend  ConnectionHandling  # Handles Configuration and the Jasper Connection.

    mattr_accessor :configurations, instance_writer: false
    self.configurations = {}

    class_attribute :connection_handler, instance_writer: false
    self.connection_handler = ConnectionAdapters::ConnectionHandler.new

    # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class,
    # which is then passed on to any new database connections made and which can be retrieved on both
    # a class and instance level by calling +logger+.
    cattr_accessor :logger, :instance_writer => false

    # ActiveModel likes a method that returns an attributes hash
    # this attributes hash happens to be based off parameters set
    # in the jasper report.
    # Also useful in serialization.
    def attributes
      @attributes = self.class.attributes.keys.inject({}) { |h,k| h.merge!( k => self.send(k) ) }
    end

    # Like ActiveRecord, allows you to pass a hash of attributes
    # on creation.
    def initialize(attributes = {})
      super()
      attributes.each do |k,v|
        # Clear out "" from attributes.
        v.reject! { |i| "#{i}".empty? } if v.respond_to?(:reject!)
        self.send(:"#{k}=", v)
      end
    end

    # This runs the report and returns the response
    # in the format specified.
    def run(fmt = 'HTML')
      response = Jasper::Base.connection.run_report(self.class.uri_string, fmt, self.attributes)
    end

    def self.attributes
      @attributes || {}
    end

    # TODO: This should really just become an attribute
    # and allow the activemodel attribute module
    # do the rest.
    def self.attribute_methods_generated?
      @attribute_methods_generated = false unless
      @attribute_methods_generated
    end

    # Naming is from active record, but I don't cache a schema since there
    # is no information_schema in Jasper, I could crawl through the repo,
    # but I currently do not see the need to do so, hence at this point
    # it asks for the JRXML file and reads the parameter list.
    # TODO: Right now I'll have it do the slow way of grabbing the jrxml.
    # But eventually I will cache it.
    def self.define_attribute_methods
      doc = Jasper::Base.connection.get(self.uri_string).first
      @attributes = doc.search('parameter').inject({}) do |h,i|
        h = if i['name']
              h.merge!(:"#{i['name']}" => nil)
            else
              h
            end
      end
      @attributes.keys.each do |a|
        self.send(:attr_accessor, a)
      end
      # Input Controls
      @attribute_methods_generated = true
    end

    # The repository URI for the report.
    # Able to be overridden.
    # Should translate namespace as directories.
    def self.uri_string(value = nil)
      self.prefix << ( @uri_string = value || @uri_string || self.name.underscore )
    end

    # Grabbed from Active Record.
     # If we haven't generated any methods yet, generate them, then
    # see if we've created the method we're looking for.
    # Might be a little slower than ActiveRecord's because I can't find
    # all the haxies they did, but its a bit clearer.
    def method_missing(method, *args, &block) # :nodoc:
      unless self.class.attribute_methods_generated?
        self.class.define_attribute_methods
        return self.send(method, *args, &block) if self.respond_to?(method)
      end
      super
    end

    # This also allows us to define attribute methods before checking
    # to see if the object responds to the method.
    def respond_to?(name, include_private = false)
      self.class.define_attribute_methods unless self.class.attribute_methods_generated?
      super
    end

    # Jasper models are not in a database.
    def persisted?
      false
    end

    protected
    # This sets the prefix for the report uri string, assuming Jasper is setup with
    # root -> organizations -> organization -> Reports.
    # If the prefix is different you will have to override it.
    def self.prefix
      "/organizations/#{self.connection_config[:organization]}/Reports/"
    end
  end
end


text:
@interface MaskTableCell : UITableViewCell {
    UILabel *_mask;
    UILabel *_setBy;
}
@property (readonly) UILabel *mask,*setBy;
@end

@implementation MaskTableCell

-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;

        _mask = [[UILabel alloc] init];
        _mask.font = [UIFont boldSystemFontOfSize:16];
        _mask.lineBreakMode = NSLineBreakByCharWrapping;
        _mask.numberOfLines = 0;
        [self.contentView addSubview:_mask];

        _setBy = [[UILabel alloc] init];
        _setBy.font = [UIFont systemFontOfSize:14];
        _setBy.textColor = [UIColor grayColor];
        _setBy.lineBreakMode = NSLineBreakByCharWrapping;
        _setBy.numberOfLines = 0;
        [self.contentView addSubview:_setBy];
    }
    return self;
}

-(void)layoutSubviews {
	[super layoutSubviews];

	CGRect frame = [self.contentView bounds];
    frame.origin.x = frame.origin.y = 6;
    frame.size.width -= 12;

    float maskHeight = [_mask.text sizeWithFont:_mask.font constrainedToSize:CGSizeMake(frame.size.width,INT_MAX) lineBreakMode:_mask.lineBreakMode].height + 2;
    _mask.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, maskHeight);
    _setBy.frame = CGRectMake(frame.origin.x, frame.origin.y + maskHeight - 2, frame.size.width, frame.size.height - maskHeight - 8);
}

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

@end

@implementation ChannelModeListTableViewController

-(id)initWithList:(int)list mode:(NSString *)mode param:(NSString *)param placeholder:(NSString *)placeholder bid:(int)bid {
    self = [super initWithStyle:UITableViewStylePlain];
    if (self) {
        _addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addButtonPressed)];
        _placeholder = [[UILabel alloc] initWithFrame:CGRectZero];
        _placeholder.text = placeholder;
        _placeholder.numberOfLines = 0;
        _placeholder.backgroundColor = [UIColor whiteColor];
        _placeholder.font = [UIFont systemFontOfSize:FONT_SIZE];
        _placeholder.textAlignment = NSTextAlignmentCenter;
        _placeholder.textColor = [UIColor selectedBlueColor];
        _placeholder.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

        _list = list;
        _bid = bid;
        _mode = mode;
        _param = param;
        _mask = @"mask";
    }
    return self;
}

-(SupportedOrientationsReturnType)supportedInterfaceOrientations {
    return ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPhone)?UIInterfaceOrientationMaskAllButUpsideDown:UIInterfaceOrientationMaskAll;
}

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
    return YES;
}

-(void)viewDidLoad {
    [super viewDidLoad];
    if([[[[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."] objectAtIndex:0] intValue] >= 7) {
        [self.navigationController.navigationBar setBackgroundImage:[[UIImage imageNamed:@"navbar"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 1, 0)] forBarMetrics:UIBarMetricsDefault];
        self.navigationController.navigationBar.clipsToBounds = YES;
    }
    self.navigationItem.leftBarButtonItem = _addButton;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneButtonPressed)];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleEvent:) name:kIRCCloudEventNotification object:nil];
    _placeholder.frame = CGRectInset(self.tableView.frame, 12, 0);
    if(_data.count)
        [_placeholder removeFromSuperview];
    else
        [self.tableView.superview addSubview:_placeholder];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)handleEvent:(NSNotification *)notification {
    kIRCEvent event = [[notification.userInfo objectForKey:kIRCCloudEventKey] intValue];
    IRCCloudJSONObject *o = nil;
    Event *e = nil;

    if(event == _list) {
        o = notification.object;
        if(o.cid == _event.cid && [[o objectForKey:@"channel"] isEqualToString:[_event objectForKey:@"channel"]]) {
            _event = o;
            _data = [o objectForKey:_param];
            if(_data.count)
                [_placeholder removeFromSuperview];
            else
                [self.tableView.superview addSubview:_placeholder];
            [self.tableView reloadData];
        }
    } else if(event == kIRCEventBufferMsg) {
        e = notification.object;
        if(e.cid == _event.cid && e.bid == _bid) {
            [[NetworkConnection sharedInstance] mode:_mode chan:[_event objectForKey:@"channel"] cid:_event.cid];
        }
    }
}

-(void)doneButtonPressed {
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)addButtonPressed {
    [self.view endEditing:YES];
    Server *s = [[ServersDataSource sharedInstance] getServer:_event.cid];
    _alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@ (%@:%i)", s.name, s.hostname, s.port] message:@"Add this hostmask" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Add", nil];
    _alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
    [_alertView textFieldAtIndex:0].delegate = self;
    [_alertView show];
}

-(void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    [_alertView dismissWithClickedButtonIndex:1 animated:YES];
    [self alertView:_alertView clickedButtonAtIndex:1];
    return NO;
}

-(NSString *)setByTextForRow:(NSDictionary *)row {
    NSString *msg = @"Set ";
    double seconds = [[NSDate date] timeIntervalSince1970] - [[row objectForKey:@"time"] doubleValue];
    double minutes = seconds / 60.0;
    double hours = minutes / 60.0;
    double days = hours / 24.0;
    if(days >= 1) {
        if(days - (int)days > 0.5)
            days++;

        if(days == 1)
            msg = [msg stringByAppendingFormat:@"%i day ago", (int)days];
        else
            msg = [msg stringByAppendingFormat:@"%i days ago", (int)days];
    } else if(hours >= 1) {
        if(hours - (int)hours > 0.5)
            hours++;

        if(hours < 2)
            msg = [msg stringByAppendingFormat:@"%i hour ago", (int)hours];
        else
            msg = [msg stringByAppendingFormat:@"%i hours ago", (int)hours];
    } else if(minutes >= 1) {
        if(minutes - (int)minutes > 0.5)
            minutes++;

        if(minutes == 1)
            msg = [msg stringByAppendingFormat:@"%i minute ago", (int)minutes];
        else
            msg = [msg stringByAppendingFormat:@"%i minutes ago", (int)minutes];
    } else {
        msg = [msg stringByAppendingString:@"less than a minute ago"];
    }
    return [msg stringByAppendingFormat:@" by %@", [row objectForKey:@"usermask"]];
}

#pragma mark - Table view data source

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *row = [_data objectAtIndex:[indexPath row]];
    return [[row objectForKey:_mask] sizeWithFont:[UIFont boldSystemFontOfSize:16] constrainedToSize:CGSizeMake(self.tableView.frame.size.width - 12, CGFLOAT_MAX) lineBreakMode:NSLineBreakByCharWrapping].height + [[self setByTextForRow:row] sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(self.tableView.frame.size.width - 12, CGFLOAT_MAX) lineBreakMode:NSLineBreakByCharWrapping].height + 12;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if([_data count])
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    else
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    @synchronized(_data) {
        return [_data count];
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    @synchronized(_data) {
        MaskTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"maskcell"];
        if(!cell)
            cell = [[MaskTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"maskcell"];
        NSDictionary *row = [_data objectAtIndex:[indexPath row]];
        cell.mask.text = [row objectForKey:_mask];
        cell.setBy.text = [self setByTextForRow:row];
        return cell;
    }
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete && indexPath.row < _data.count) {
        NSDictionary *row = [_data objectAtIndex:indexPath.row];
        [[NetworkConnection sharedInstance] mode:[NSString stringWithFormat:@"-%@ %@", _mode, [row objectForKey:_mask]] chan:[_event objectForKey:@"channel"] cid:_event.cid];
    }
}

#pragma mark - Table view delegate

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];

    if([title isEqualToString:@"Add"]) {
        [[NetworkConnection sharedInstance] mode:[NSString stringWithFormat:@"+%@ %@", _mode, [alertView textFieldAtIndex:0].text] chan:[_event objectForKey:@"channel"] cid:_event.cid];
    }

    _alertView = nil;
}

-(BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView {
    if(alertView.alertViewStyle == UIAlertViewStylePlainTextInput && [alertView textFieldAtIndex:0].text.length == 0)
        return NO;
    else
        return YES;
}

@end


text:
"""Auto-generated file, do not edit by hand. AF metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata

PHONE_METADATA_AF = PhoneMetadata(id='AF', country_code=None, international_prefix=None,
    general_desc=PhoneNumberDesc(national_number_pattern='[14]\\d{2,4}', possible_length=(3, 5)),
    emergency=PhoneNumberDesc(national_number_pattern='1(?:02|19)', example_number='119', possible_length=(3,)),
    short_code=PhoneNumberDesc(national_number_pattern='1(?:02|19)|40404', example_number='119', possible_length=(3, 5)),
    carrier_specific=PhoneNumberDesc(national_number_pattern='40404', example_number='40404', possible_length=(5,)),
    short_data=True)


text:
1. Download zip then upload to reSlim server to the **modules/**
2. Extract zip then you will get new folder like **reSlim-modules-packager-master**
3. Rename foldername **reSlim-modules-packager-master** to **packager**
4. Done


text:
          {{content.title}}

          <video thumbid="_video" width="100" height="100" poster="images/play.jpg">
            <source src="{{url}}" type="video/mp4"></source>
          </video>

                  ... {{content.description}}

                  ...

                       {{text}} {{formatData(content.context.highlight)[$index]}}

          {{content.url}}

{{content.score}}%

        {{getLastModified(content.lastmodified)}}

        {{content.size}}


text:
tags: zoo
image_path: /assets/imgs/zoo/1.jpg
original_path: https://www.loc.gov/item/mpc2010002810/PP/
title: "Sudan. Khartoum. Khartoum Zoo. Hippo yawning"
year: 1936
---