text:
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>no.cantara.emi</groupId>
        <artifactId>parent</artifactId>
        <version>8</version>
    </parent>

    <groupId>no.cantara</groupId>
    <artifactId>ratpack-echo-websockets-application</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <scm>
        <developerConnection>scm:git:git@github.com:Cantara/ratpack-echo-websockets-application.git
        </developerConnection>
        <connection>scm:git:git@github.com:Cantara/ratpack-echo-websockets-application.git</connection>
        <url>https://github.com/Cantara/ratpack-echo-websockets-application</url>
        <tag>HEAD</tag>
    </scm>

    <repositories>
        <repository>
            <id>sonatype-nexus-snapshots</id>
            <name>Sonatype Nexus Snapshots</name>
            <url>https://oss.jfrog.org/repo</url>
            <releases>
                <enabled>false</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>cantara-releases</id>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <name>Cantara Release Repository</name>
            <url>http://mvnrepo.cantara.no/content/repositories/releases/</url>
        </repository>
        <repository>
            <id>cantara-snapshots</id>
            <releases>
                <enabled>false</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
            <name>Cantara Release Repository</name>
            <url>http://mvnrepo.cantara.no/content/repositories/snapshots/</url>
        </repository>
    </repositories>

    <properties>
        <pac4j.version>1.8.0</pac4j.version>
        <ratpack.version>1.9.0</ratpack.version>
        <slf4j.version>1.7.36</slf4j.version>
        <freemarker.version>2.3.31</freemarker.version>
        <logback.version>1.4.5</logback.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>no.cantara</groupId>
            <artifactId>ratpack-freemarker</artifactId>
            <version>0.5.3</version>
        </dependency>
        <dependency>
            <groupId>no.cantara</groupId>
            <artifactId>ratpack-guice-config</artifactId>
            <version>0.7</version>
        </dependency>
        <dependency>
            <groupId>io.ratpack</groupId>
            <artifactId>ratpack-dropwizard-metrics</artifactId>
            <version>${ratpack.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.yaml</groupId>
                    <artifactId>snakeyaml</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.fasterxml.jackson.core</groupId>
                    <artifactId>jackson-databind</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.fasterxml.jackson.dataformat</groupId>
                    <artifactId>jackson-dataformat-xml</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.fasterxml.jackson.dataformat</groupId>
                    <artifactId>jackson-core</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.fasterxml.jackson.dataformat</groupId>
                    <artifactId>jackson-dataformat-yaml</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.fasterxml.jackson.datatype</groupId>
                    <artifactId>jackson-datatype-guava</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.fasterxml.jackson.datatype</groupId>
                    <artifactId>jackson-datatype-jsr310</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.fasterxml.jackson.datatype</groupId>
                    <artifactId>jackson-datatype-jdk8</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.fasterxml.jackson.datatype</groupId>
                    <artifactId>jackson-datatype-jdk7</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>io.netty</groupId>
                    <artifactId>netty-handler</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>io.netty</groupId>
                    <artifactId>netty-codec-http</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.google.inject</groupId>
                    <artifactId>guice</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.google.guava</groupId>
                    <artifactId>guava</artifactId>
                </exclusion>

            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>${freemarker.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
            <version>2.14.1</version>
        </dependency>

        <dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
            <version>5.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <configuration>
                    <createDependencyReducedPom>true</createDependencyReducedPom>
                    <filters>
                        <filter>
                            <artifact>*:*</artifact>
                            <excludes>
                                <exclude>META-INF/*.SF</exclude>
                                <exclude>META-INF/*.DSA</exclude>
                                <exclude>META-INF/*.RSA</exclude>
                            </excludes>
                        </filter>
                    </filters>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>no.cantara.ratpacksample.Main</mainClass>
                                </transformer>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                                    <resource>META-INF/spring.handlers</resource>
                                </transformer>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                                    <resource>META-INF/spring.schemas</resource>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

redpajama_set_name: RedPajamaGithub


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.ConvertAnonymousTypeToClass
{
    internal abstract class AbstractConvertAnonymousTypeToClassCodeRefactoringProvider<
        TExpressionSyntax,
        TNameSyntax,
        TIdentifierNameSyntax,
        TObjectCreationExpressionSyntax,
        TAnonymousObjectCreationExpressionSyntax,
        TNamespaceDeclarationSyntax>
        : CodeRefactoringProvider
        where TExpressionSyntax : SyntaxNode
        where TNameSyntax : TExpressionSyntax
        where TIdentifierNameSyntax : TNameSyntax
        where TObjectCreationExpressionSyntax : TExpressionSyntax
        where TAnonymousObjectCreationExpressionSyntax : TExpressionSyntax
        where TNamespaceDeclarationSyntax : SyntaxNode
    {
        protected abstract TObjectCreationExpressionSyntax CreateObjectCreationExpression(TNameSyntax nameNode, TAnonymousObjectCreationExpressionSyntax currentAnonymousObject);

        public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
        {
            var (document, textSpan, cancellationToken) = context;
            var (anonymousObject, anonymousType) = await TryGetAnonymousObjectAsync(document, textSpan, cancellationToken).ConfigureAwait(false);

            if (anonymousObject == null || anonymousType == null)
                return;

            // Check if the anonymous type actually references another anonymous type inside of it.
            // If it does, we can't convert this.  There is no way to describe this anonymous type
            // in the concrete type we create.
            var containsAnonymousType = anonymousType.GetMembers()
                                                     .OfType<IPropertySymbol>()
                                                     .Any(p => p.Type.ContainsAnonymousType());
            if (containsAnonymousType)
                return;

            var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
            if (syntaxFacts.SupportsRecord(anonymousObject.SyntaxTree.Options))
            {
                context.RegisterRefactoring(new MyCodeAction(
                    FeaturesResources.Convert_to_record,
                    c => ConvertAsync(document, textSpan, isRecord: true, c)),
                    anonymousObject.Span);
            }

            context.RegisterRefactoring(new MyCodeAction(
                    FeaturesResources.Convert_to_class,
                c => ConvertAsync(document, textSpan, isRecord: false, c)),
                anonymousObject.Span);
        }

        private static async Task<(TAnonymousObjectCreationExpressionSyntax?, INamedTypeSymbol?)> TryGetAnonymousObjectAsync(
            Document document, TextSpan span, CancellationToken cancellationToken)
        {
            // Gets a `TAnonymousObjectCreationExpressionSyntax` for current selection.
            // Due to the way `TryGetSelectedNodeAsync` works and how `TAnonymousObjectCreationExpressionSyntax` is e.g. for C# constructed
            // it matches even when caret is next to some tokens within the anonymous object creation node.
            // E.g.: `var a = new [||]{ b=1,[||] c=2 };` both match due to the caret being next to `,` and `{`.
            var anonymousObject = await document.TryGetRelevantNodeAsync<TAnonymousObjectCreationExpressionSyntax>(
                span, cancellationToken).ConfigureAwait(false);
            if (anonymousObject == null)
                return default;

            var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
            var anonymousType = semanticModel.GetTypeInfo(anonymousObject, cancellationToken).Type as INamedTypeSymbol;

            return (anonymousObject, anonymousType);
        }

        private async Task<Document> ConvertAsync(Document document, TextSpan span, bool isRecord, CancellationToken cancellationToken)
        {
            var (anonymousObject, anonymousType) = await TryGetAnonymousObjectAsync(document, span, cancellationToken).ConfigureAwait(false);

            Debug.Assert(anonymousObject != null);
            Debug.Assert(anonymousType != null);

            var position = span.Start;
            var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
            var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            // Generate a unique name for the class we're creating.  We'll also add a rename
            // annotation so the user can pick the right name for the type afterwards.
            var className = NameGenerator.GenerateUniqueName(
                isRecord ? "NewRecord" : "NewClass",
                n => semanticModel.LookupSymbols(position, name: n).IsEmpty);

            // First, create the set of properties this class will have based on the properties the
            // anonymous type has itself.  Also, get a mapping of the original anonymous type's
            // properties to the new name we generated for it (if we converted camelCase to
            // PascalCase).
            var (properties, propertyMap) = GenerateProperties(document, anonymousType);

            // Next, generate the full class that will be used to replace all instances of this
            // anonymous type.
            var namedTypeSymbol = await GenerateFinalNamedTypeAsync(
                document, className, isRecord, properties, cancellationToken).ConfigureAwait(false);

            var generator = SyntaxGenerator.GetGenerator(document);
            var editor = new SyntaxEditor(root, generator);

            var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
            var containingMember = anonymousObject.FirstAncestorOrSelf<SyntaxNode, ISyntaxFactsService>((node, syntaxFacts) => syntaxFacts.IsMethodLevelMember(node), syntaxFacts) ?? anonymousObject;

            // Next, go and update any references to these anonymous type properties to match
            // the new PascalCased name we've picked for the new properties that will go in
            // the named type.
            await ReplacePropertyReferencesAsync(
                document, editor, containingMember,
                propertyMap, cancellationToken).ConfigureAwait(false);

            // Next, go through and replace all matching anonymous types in this method with a call
            // to construct the new named type we've generated.
            await ReplaceMatchingAnonymousTypesAsync(
                document, editor, namedTypeSymbol,
                containingMember, anonymousObject,
                anonymousType, cancellationToken).ConfigureAwait(false);

            // Then, actually insert the new class in the appropriate container.
            var container = anonymousObject.GetAncestor<TNamespaceDeclarationSyntax>() ?? root;
            editor.ReplaceNode(container, (currentContainer, _) =>
            {
                var codeGenService = document.GetRequiredLanguageService<ICodeGenerationService>();
                var codeGenOptions = new CodeGenerationOptions(
                    generateMembers: true,
                    sortMembers: false,
                    autoInsertionLocation: false,
                    options: options,
                    parseOptions: root.SyntaxTree.Options);

                return codeGenService.AddNamedType(
                    currentContainer, namedTypeSymbol, codeGenOptions, cancellationToken);
            });

            var updatedDocument = document.WithSyntaxRoot(editor.GetChangedRoot());

            // Finally, format using the equals+getHashCode service so that our generated methods
            // follow any special formatting rules specific to them.
            var equalsAndGetHashCodeService = document.GetRequiredLanguageService<IGenerateEqualsAndGetHashCodeService>();
            return await equalsAndGetHashCodeService.FormatDocumentAsync(
                updatedDocument, cancellationToken).ConfigureAwait(false);
        }

        private static async Task ReplacePropertyReferencesAsync(
            Document document, SyntaxEditor editor, SyntaxNode containingMember,
            ImmutableDictionary<IPropertySymbol, string> propertyMap, CancellationToken cancellationToken)
        {
            var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
            var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
            var identifiers = containingMember.DescendantNodes().OfType<TIdentifierNameSyntax>();

            foreach (var identifier in identifiers)
            {
                if (!syntaxFacts.IsNameOfSimpleMemberAccessExpression(identifier) &&
                    !syntaxFacts.IsNameOfMemberBindingExpression(identifier))
                {
                    continue;
                }

                if (semanticModel.GetSymbolInfo(identifier, cancellationToken).GetAnySymbol() is not IPropertySymbol symbol)
                    continue;

                if (propertyMap.TryGetValue(symbol, out var newName))
                {
                    editor.ReplaceNode(
                        identifier,
                        (currentId, g) => g.IdentifierName(newName).WithTriviaFrom(currentId));
                }
            }
        }

        private async Task ReplaceMatchingAnonymousTypesAsync(
            Document document, SyntaxEditor editor, INamedTypeSymbol classSymbol,
            SyntaxNode containingMember, TAnonymousObjectCreationExpressionSyntax creationNode,
            INamedTypeSymbol anonymousType, CancellationToken cancellationToken)
        {
            // When invoked we want to fixup all creations of the "same" anonymous type within the
            // containing method.  We define same-ness as meaning "they have the type symbol".  this
            // means both have the same member names, in the same order, with the same member types.
            // We fix all these up in the method because the user may be creating several instances
            // of this anonymous type in that method and then combining them in interesting ways
            // (i.e. checking them for equality, using them in collections, etc.).  The language
            // guarantees within a method boundary that these will be the same type and can be used
            // together in this fashion.
            //
            // Note: we could consider expanding this in the future (potentially with another
            // lightbulb action).  Specifically, we could look in the containing type and replace
            // any matches in any methods.
            var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            var childCreationNodes = containingMember.DescendantNodesAndSelf()
                                                     .OfType<TAnonymousObjectCreationExpressionSyntax>();

            foreach (var childCreation in childCreationNodes)
            {
                var childType = semanticModel.GetTypeInfo(childCreation, cancellationToken).Type;
                if (childType == null)
                {
                    Debug.Fail("We should always be able to get an anonymous type for any anonymous creation node.");
                    continue;
                }

                if (anonymousType.Equals(childType))
                    ReplaceWithObjectCreation(editor, classSymbol, creationNode, childCreation);
            }
        }

        private void ReplaceWithObjectCreation(
            SyntaxEditor editor, INamedTypeSymbol classSymbol,
            TAnonymousObjectCreationExpressionSyntax startingCreationNode,
            TAnonymousObjectCreationExpressionSyntax childCreation)
        {
            // Use the callback form as anonymous types may be nested, and we want to
            // properly replace them even in that case.
            editor.ReplaceNode(
                childCreation,
                (currentNode, g) =>
                {
                    var currentAnonymousObject = (TAnonymousObjectCreationExpressionSyntax)currentNode;

                    // If we hit the node the user started on, then add the rename annotation here.
                    var className = classSymbol.Name;
                    var classNameToken = startingCreationNode == childCreation
                        ? g.Identifier(className).WithAdditionalAnnotations(RenameAnnotation.Create())
                        : g.Identifier(className);

                    var classNameNode = classSymbol.TypeParameters.Length == 0
                        ? (TNameSyntax)g.IdentifierName(classNameToken)
                        : (TNameSyntax)g.GenericName(classNameToken,
                            classSymbol.TypeParameters.Select(tp => g.IdentifierName(tp.Name)));

                    return CreateObjectCreationExpression(classNameNode, currentAnonymousObject)
                        .WithAdditionalAnnotations(Formatter.Annotation);
                });
        }

        private static async Task<INamedTypeSymbol> GenerateFinalNamedTypeAsync(
            Document document, string typeName, bool isRecord,
            ImmutableArray<IPropertySymbol> properties,
            CancellationToken cancellationToken)
        {
            var generator = SyntaxGenerator.GetGenerator(document);
            var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            // Next, see if any of the properties ended up using any type parameters from the
            // containing method/named-type.  If so, we'll need to generate a generic type so we can
            // properly pass these along.
            var capturedTypeParameters =
                properties.Select(p => p.Type)
                          .SelectMany(t => t.GetReferencedTypeParameters())
                          .Distinct()
                          .ToImmutableArray();

            using var _ = ArrayBuilder<ISymbol>.GetInstance(out var members);

            if (isRecord)
            {
                // Create a record with a single primary constructor, containing a parameter for all the properties
                // we're generating.
                var constructor = CodeGenerationSymbolFactory.CreateConstructorSymbol(
                    attributes: default,
                    Accessibility.Public,
                    modifiers: default,
                    typeName,
                    properties.SelectAsArray(prop => CodeGenerationSymbolFactory.CreateParameterSymbol(prop.Type, prop.Name)),
                    isPrimaryConstructor: true);

                members.Add(constructor);
            }
            else
            {
                // Now try to generate all the members that will go in the new class. This is a bit
                // circular.  In order to generate some of the members, we need to know about the type.
                // But in order to create the type, we need the members.  To address this we do two
                // passes. First, we create an empty version of the class.  This can then be used to
                // help create members like Equals/GetHashCode.  Then, once we have all the members we
                // create the final type.
                var namedTypeWithoutMembers = CreateNamedType(typeName, isRecord: false, capturedTypeParameters, members: default);

                var constructor = CreateClassConstructor(semanticModel, typeName, properties, generator);

                // Generate Equals/GetHashCode.  Only readonly properties are suitable for these
                // methods.  We can defer to our existing language service for this so that we
                // generate the same Equals/GetHashCode that our other IDE features generate.
                var readonlyProperties = ImmutableArray<ISymbol>.CastUp(
                    properties.WhereAsArray(p => p.SetMethod == null));

                var equalsAndGetHashCodeService = document.GetRequiredLanguageService<IGenerateEqualsAndGetHashCodeService>();

                var equalsMethod = await equalsAndGetHashCodeService.GenerateEqualsMethodAsync(
                    document, namedTypeWithoutMembers, readonlyProperties,
                    localNameOpt: SyntaxGeneratorExtensions.OtherName, cancellationToken).ConfigureAwait(false);
                var getHashCodeMethod = await equalsAndGetHashCodeService.GenerateGetHashCodeMethodAsync(
                    document, namedTypeWithoutMembers,
                    readonlyProperties, cancellationToken).ConfigureAwait(false);

                members.AddRange(properties);
                members.Add(constructor);
                members.Add(equalsMethod);
                members.Add(getHashCodeMethod);

            }

            return CreateNamedType(typeName, isRecord, capturedTypeParameters, members.ToImmutable());
        }

        private static INamedTypeSymbol CreateNamedType(
            string className, bool isRecord, ImmutableArray<ITypeParameterSymbol> capturedTypeParameters, ImmutableArray<ISymbol> members)
        {
            return CodeGenerationSymbolFactory.CreateNamedTypeSymbol(
                attributes: default, Accessibility.Internal, modifiers: default,
                isRecord, TypeKind.Class, className, capturedTypeParameters, members: members);
        }

        private static (ImmutableArray<IPropertySymbol> properties, ImmutableDictionary<IPropertySymbol, string> propertyMap) GenerateProperties(
            Document document, INamedTypeSymbol anonymousType)
        {
            var originalProperties = anonymousType.GetMembers().OfType<IPropertySymbol>().ToImmutableArray();
            var newProperties = originalProperties.SelectAsArray(p => GenerateProperty(document, p));

            // If we changed the names of any properties, record that name mapping.  We'll
            // use this to update reference to the old anonymous-type properties to the new
            // names.
            var builder = ImmutableDictionary.CreateBuilder<IPropertySymbol, string>();
            for (var i = 0; i < originalProperties.Length; i++)
            {
                var originalProperty = originalProperties[i];
                var newProperty = newProperties[i];

                if (originalProperty.Name != newProperty.Name)
                    builder[originalProperty] = newProperty.Name;
            }

            return (newProperties, builder.ToImmutable());
        }

        private static IPropertySymbol GenerateProperty(Document document, IPropertySymbol prop)
        {
            // The actual properties generated by C#/VB are not what we want.  For example, they
            // think of themselves as having real accessors that will read/write into a real field
            // in the type.  Instead, we just want to generate auto-props. So we effectively clone
            // the property, just throwing aways anything we don't need for that purpose.
            //
            // We also want to follow general .NET naming.  So that means converting to pascal
            // case from camel-case.

            var getMethod = prop.GetMethod != null ? CreateAccessorSymbol(prop, MethodKind.PropertyGet) : null;
            var setMethod = prop.SetMethod != null ? CreateAccessorSymbol(prop, MethodKind.PropertySet) : null;

            return CodeGenerationSymbolFactory.CreatePropertySymbol(
                attributes: default, Accessibility.Public, modifiers: default,
                prop.Type, refKind: default, explicitInterfaceImplementations: default,
                GetLegalName(prop.Name.ToPascalCase(trimLeadingTypePrefix: false), document),
                parameters: default, getMethod: getMethod, setMethod: setMethod);
        }

        private static string GetLegalName(string name, Document document)
        {
            var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
            return syntaxFacts.IsLegalIdentifier(name)
                ? name
                : "Item"; // Just a dummy name for the property.  Does not need to be localized.
        }

        private static IMethodSymbol CreateAccessorSymbol(IPropertySymbol prop, MethodKind kind)
            => CodeGenerationSymbolFactory.CreateMethodSymbol(
                   attributes: default, Accessibility.Public, DeclarationModifiers.Abstract,
                   prop.Type, refKind: default, explicitInterfaceImplementations: default,
                   name: "", typeParameters: default, parameters: default, methodKind: kind);

        private static IMethodSymbol CreateClassConstructor(
            SemanticModel semanticModel, string className,
            ImmutableArray<IPropertySymbol> properties, SyntaxGenerator generator)
        {
            // For every property, create a corresponding parameter, as well as an assignment
            // statement from that parameter to the property.
            var parameterToPropMap = new Dictionary<string, ISymbol>();
            var parameters = properties.SelectAsArray(prop =>
            {
                var parameter = CodeGenerationSymbolFactory.CreateParameterSymbol(
                    prop.Type, prop.Name.ToCamelCase(trimLeadingTypePrefix: false));

                parameterToPropMap[parameter.Name] = prop;

                return parameter;
            });

            var assignmentStatements = generator.CreateAssignmentStatements(
                semanticModel, parameters, parameterToPropMap, ImmutableDictionary<string, string>.Empty,
                addNullChecks: false, preferThrowExpression: false);

            var constructor = CodeGenerationSymbolFactory.CreateConstructorSymbol(
                attributes: default, Accessibility.Public, modifiers: default,
                className, parameters, assignmentStatements);

            return constructor;
        }

        private class MyCodeAction : CodeAction.DocumentChangeAction
        {
            public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument)
                : base(title, createChangedDocument)
            {
            }
        }
    }
}


text:
from __future__ import print_function
from __future__ import unicode_literals

from netmiko.cisco_base_connection import CiscoSSHConnection

class HPComwareSSH(CiscoSSHConnection):

    def session_preparation(self):
        """
        Prepare the session after the connection has been established.
        Extra time to read HP banners.
        """
        self._test_channel_read(pattern=r'[>\]]')
        self.set_base_prompt()
        self.disable_paging(command="\nscreen-length disable\n")

    def config_mode(self, config_command='system-view'):
        """Enter configuration mode."""
        return super(HPComwareSSH, self).config_mode(config_command=config_command)

    def exit_config_mode(self, exit_config='return'):
        """Exit config mode."""
        return super(HPComwareSSH, self).exit_config_mode(exit_config=exit_config)

    def check_config_mode(self, check_string=']'):
        """Check whether device is in configuration mode. Return a boolean."""
        return super(HPComwareSSH, self).check_config_mode(check_string=check_string)

    def set_base_prompt(self, pri_prompt_terminator='>', alt_prompt_terminator=']',
                        delay_factor=1):
        """
        Sets self.base_prompt

        Used as delimiter for stripping of trailing prompt in output.

        Should be set to something that is general and applies in multiple contexts. For Comware
        this will be the router prompt with < > or [ ] stripped off.

        This will be set on logging in, but not when entering system-view
        """
        prompt = super(HPComwareSSH, self).set_base_prompt(
            pri_prompt_terminator=pri_prompt_terminator,
            alt_prompt_terminator=alt_prompt_terminator,
            delay_factor=delay_factor)

        # Strip off leading character
        prompt = prompt[1:]
        prompt = prompt.strip()
        self.base_prompt = prompt
        return self.base_prompt

    def enable(self, cmd='system-view'):
        """enable mode on Comware is system-view."""
        return self.config_mode(config_command=cmd)

    def exit_enable_mode(self, exit_command='return'):
        """enable mode on Comware is system-view."""
        return self.exit_config_mode(exit_config=exit_command)

    def check_enable_mode(self, check_string=']'):
        """enable mode on Comware is system-view."""
        return self.check_config_mode(check_string=check_string)


text:
[![Build Status](https://secure.travis-ci.org/zendframework/zend-filter.svg?branch=master)](https://secure.travis-ci.org/zendframework/zend-filter)
[![Coverage Status](https://coveralls.io/repos/github/zendframework/zend-filter/badge.svg?branch=master)](https://coveralls.io/github/zendframework/zend-filter?branch=master)

The `Zend\Filter` component provides a set of commonly needed data filters. It
also provides a simple filter chaining mechanism by which multiple filters may
be applied to a single datum in a user-defined order.

- File issues at https://github.com/zendframework/zend-filter/issues
- Documentation is at https://docs.zendframework.com/zend-filter/


text:
package com.gazbert.bxbot.rest.api.security.service;

import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.junit.Assert.assertEquals;

import com.gazbert.bxbot.rest.api.security.jwt.JwtUser;
import com.gazbert.bxbot.rest.api.security.jwt.JwtUserFactory;
import com.gazbert.bxbot.rest.api.security.model.User;
import com.gazbert.bxbot.rest.api.security.repository.UserRepository;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * Tests the JWT User Details service behaves as expected.
 *
 * @author gazbert
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest({JwtUserFactory.class})
public class TestJwtUserDetailsService {

  private static final String KNOWN_USERNAME = "known-username";
  private static final String UNKNOWN_USERNAME = "unknown-username";

  private UserRepository userRepository;

  @Before
  public void setup() {
    userRepository = PowerMock.createMock(UserRepository.class);
  }

  @Test
  public void whenLoadByUsernameCalledWithKnownUsernameThenExpectUserDetailsToBeReturned() {
    PowerMock.mockStatic(JwtUserFactory.class);
    final User user = PowerMock.createMock(User.class);
    final JwtUser jwtUser = EasyMock.createMock(JwtUser.class);

    expect(userRepository.findByUsername(KNOWN_USERNAME)).andStubReturn(user);
    expect(JwtUserFactory.create(eq(user))).andStubReturn(jwtUser);
    PowerMock.replayAll();

    final JwtUserDetailsService jwtUserDetailsService = new JwtUserDetailsService(userRepository);
    final JwtUser userDetails = (JwtUser) jwtUserDetailsService.loadUserByUsername(KNOWN_USERNAME);
    assertEquals(jwtUser, userDetails);

    PowerMock.verifyAll();
  }

  @Test(expected = UsernameNotFoundException.class)
  public void whenLoadByUsernameCalledWithUnknownUsernameThenExpectUsernameNotFoundException() {
    expect(userRepository.findByUsername(UNKNOWN_USERNAME)).andStubReturn(null);
    PowerMock.replayAll();

    final JwtUserDetailsService jwtUserDetailsService = new JwtUserDetailsService(userRepository);
    jwtUserDetailsService.loadUserByUsername(UNKNOWN_USERNAME);

    PowerMock.verifyAll();
  }
}


text:
/*
Title: UVM Given Building Mechanical Master Plan
Description: L.N. Consulting is a mechanical, electrical, and energy services engineering design firm, with geothermal and renewable energy systems integration experience
*/

# Higher Education

UVM Given Building Mechanical Master Plan

   L.N. Consulting completed the mechanical master plan document for the UVM Given Building.  The Given building is a 225,000 sq.ft. laboratory research building with an extremely diverse occupancy.  This project encompassed a complete review of the entire buildings mechanical systems and occupant use with recommendations for future renovations and energy savings.  The master plan initiative included a LEED evaluation for the proposed project.

Burlington, VT

UVM College of Medicine, Sue Ligon (802) 656-5020

Black River Design, Keith Robinson, (802) 223-2044

NA

Completed 2009


text:
<?php

namespace Tests;

use Myerscode\Utilities\Strings\Utility;
use Tests\Support\StringConstructorTestCase;

class ValueTest extends BaseStringSuite
{
    public function __validData(): array
    {
        return [
            'string' => ['hello world', 'hello world'],
            'number' => ['123', 123],
            'true' => ['1', true],
            'false' => ['', false],
            'class with __toString()' => ['StringConstructorTestCase::class', new StringConstructorTestCase()],
            'Utility' => ['Hello World', new Utility('Hello World')],
        ];
    }

    /**
     * @dataProvider __validData
     */
    public function testGetValue($expected, $string): void
    {
        $this->assertEquals($expected, $this->utility($string)->value());
    }

    /**
     * @dataProvider __validData
     */
    public function testToString($expected, $string): void
    {
        $this->assertEquals($expected, $this->utility($string)->__toString());
    }
}


text:
<?php

namespace ZendTest\Form\View\Helper;

use PHPUnit\Framework\TestCase;
use Zend\Form\View\Helper\FormDateSelect as FormDateSelectHelper;
use Zend\Form\View\Helper\FormDateTimeSelect as FormDateTimeSelectHelper;
use Zend\Form\View\Helper\FormMonthSelect as FormMonthSelectHelper;

class MissingIntlExtensionTest extends TestCase
{
    public function setUp()
    {
        if (extension_loaded('intl')) {
            $this->markTestSkipped('ext/intl enabled');
        }
    }

    public function testFormDateSelectHelper()
    {
        $this->expectException('Zend\Form\Exception\ExtensionNotLoadedException');
        $this->expectExceptionMessage('Zend\Form\View\Helper component requires the intl PHP extension');

        $helper = new FormDateSelectHelper();
    }

    public function testFormDateTimeSelectHelper()
    {
        $this->expectException('Zend\Form\Exception\ExtensionNotLoadedException');
        $this->expectExceptionMessage('Zend\Form\View\Helper component requires the intl PHP extension');

        $helper = new FormDateTimeSelectHelper();
    }

    public function testFormMonthSelectHelper()
    {
        $this->expectException('Zend\Form\Exception\ExtensionNotLoadedException');
        $this->expectExceptionMessage('Zend\Form\View\Helper component requires the intl PHP extension');

        $helper = new FormMonthSelectHelper();
    }
}


text:
import * as io from "io-ts";

import WebAssemblyWrapper from "./WebAssemblyWrapper";

export const fs = new Map<string, File>();
export const handles = new Map<number, FHandle>();

const SEEK_SET = 0;
const SEEK_CUR = 1;
const SEEK_END = 2;

export const SeekOrigin = io.union([io.literal(SEEK_CUR), io.literal(SEEK_SET), io.literal(SEEK_END)]);
export type SeekOrigin = io.TypeOf<typeof SeekOrigin>;
// Const EOF = -1;
const EINVAL = 22;

class Mode {
    _binary: boolean;
    _write: boolean;
    _read: boolean;
    _append: boolean;
    _plus: boolean;
    _x: boolean;
    constructor(modeString: string) {
        this._binary = modeString.indexOf(`b`) >= 0;
        this._write = modeString.indexOf(`w`) >= 0;
        this._read = modeString.indexOf(`r`) >= 0;
        this._append = modeString.indexOf(`a`) >= 0;
        this._plus = modeString.indexOf(`+`) >= 0;
        this._x = modeString.indexOf(`x`) >= 0;
    }
}

class FHandle {
    _fileHandle: number;
    _position: number;
    _eof: boolean;
    _error: null | number;
    _mode: Mode;
    _size: number;
    _name: string;
    _type: string;
    _writePtr: number;
    _writeLength: number;
    _needFlush: boolean;
    constructor(fileHandle: number, file: File, mode: Mode, wasm: WebAssemblyWrapper) {
        this._fileHandle = fileHandle;
        this._position = 0;
        this._eof = false;
        this._error = null;
        this._mode = mode;
        this._size = file.size;
        this._name = file.name;
        this._type = file.type;
        this._writePtr = 0;
        this._writeLength = 0;
        this._needFlush = false;

        if (this.append && this._size > 0) {
            this._position = this._size;
            const length = (this._size * 1.5) | 0;
            this._writePtr = wasm.malloc(length);
            this._writeLength = length;
            //@ts-ignore
            const reader = new FileReaderSync();
            const src = reader.readAsArrayBuffer(file);
            const dst = wasm.u8view(this._writePtr, this._size);
            dst.set(new Uint8Array(src));
        }
    }

    get binary() {
        return this._mode._binary;
    }
    get write() {
        return this._mode._write;
    }
    get read() {
        return this._mode._read;
    }
    get append() {
        return this._mode._append;
    }
    get plus() {
        return this._mode._plus;
    }
    get x() {
        return this._mode._x;
    }

    get name() {
        return this._name;
    }

    get file() {
        return fs.get(this.name);
    }

    get type() {
        return this._type;
    }

    _fclose(wasm: WebAssemblyWrapper) {
        this._fflush(wasm);
        if (this._writePtr) {
            wasm.free(this._writePtr);
            this._writePtr = 0;
            this._writeLength = 0;
        }
        return 0;
    }

    _ftell() {
        return this._position;
    }

    _fseek(offset: number, origin: SeekOrigin) {
        if (this.append) return 0;
        if (!this.binary) {
            if (origin === SEEK_SET) {
                this._setValidPosition(offset);
            } else {
                this._error = EINVAL;
                return -1;
            }
        } else {
            if (origin === SEEK_SET) {
                this._setValidPosition(offset);
            } else if (origin === SEEK_CUR) {
                this._setValidPosition(this._position + offset);
            } else if (origin === SEEK_END) {
                this._setValidPosition(this._size + offset);
            } else {
                this._error = EINVAL;
                return -1;
            }
        }
        this._eof = false;
        return 0;
    }

    _setValidPosition(position: number) {
        if (position >= this._size) {
            position = this._size;
            this._eof = true;
        }
        this._position = position;
    }

    _fread(wasm: WebAssemblyWrapper, targetPtr: number, size: number, count: number) {
        if (!this.read && !this.plus) {
            return 0;
        }
        const length = size * count;
        const fileStart = this._position;
        this._setValidPosition(fileStart + length);
        const lengthToRead = this._position - fileStart;
        const { file } = this;
        if (!file) {
            return -1;
        }
        const slicedBlob = file.slice(fileStart, fileStart + lengthToRead, file.type);
        try {
            //@ts-ignore
            const reader = new FileReaderSync();
            const src = reader.readAsArrayBuffer(slicedBlob);
            const dst = wasm.u8view(targetPtr, lengthToRead);
            dst.set(new Uint8Array(src));
            return (lengthToRead / size) >>> 0;
        } catch (e) {
            return 0;
        }
    }

    _fwrite(wasm: WebAssemblyWrapper, sourcePtr: number, size: number, count: number) {
        const length = size * count;
        if (!length || (!this.write && !this.plus && !this.append)) {
            return 0;
        }
        const position = this._position;

        if (position + length >= this._writeLength) {
            const bufferLength = (position + length * 1.5) | 0;
            if (this._writePtr) {
                this._writePtr = wasm.realloc(this._writePtr, bufferLength);
            } else {
                this._writePtr = wasm.malloc(bufferLength);
            }
            this._writeLength = bufferLength;
        }
        this._position += length;
        this._size += length;

        wasm.memcpy(this._writePtr + position, sourcePtr, length);
        this._needFlush = true;
        return length / size;
    }

    _fflush(wasm: WebAssemblyWrapper) {
        if (this._writePtr && this._needFlush) {
            const length = Math.min(this._position, this._writeLength);
            const src = wasm.u8view(this._writePtr, length);
            fs.set(
                this.name,
                new File([src], this.name, {
                    type: this.type,
                    lastModified: Date.now(),
                })
            );
            this._needFlush = false;
        }
        return 0;
    }
}

export function createFs(wasm: WebAssemblyWrapper) {
    let nextHandle = 3;

    function fopen(fileNamePtr: number, flagsStrPtr: number, handle: number) {
        const fileName = wasm.convertCharPToAsciiString(fileNamePtr);
        const mode = new Mode(wasm.convertCharPToAsciiString(flagsStrPtr));

        if (mode._append && mode._plus) {
            return -1;
        }
        let file = fs.get(fileName);
        if (file) {
            if (mode._write) {
                if (mode._x) {
                    return -1;
                }
                file = new File([new ArrayBuffer(0)], fileName, {
                    lastModified: Date.now(),
                });
                fs.set(fileName, file);
            }

            handles.set(handle, new FHandle(handle, file, mode, wasm));
            return handle;
        } else {
            if (mode._read) {
                return -1;
            }
            file = new File([new ArrayBuffer(0)], fileName, {
                lastModified: Date.now(),
            });
            fs.set(fileName, file);
            handles.set(handle, new FHandle(handle, file, mode, wasm));
        }
        return 0;
    }

    function withHandle(handle: number, fn: (handle: FHandle) => number | void): number | void {
        const fhandle = handles.get(handle);
        if (!fhandle) return -1;
        return fn(fhandle);
    }

    return {
        fclose(handle: number) {
            withHandle(handle, fhandle => {
                fhandle._fflush(wasm);
                fhandle._fclose(wasm);
                handles.delete(handle);
            });
            return 0;
        },
        fflush(handle: number) {
            if (!handle) {
                for (const fhandle of handles.values()) {
                    fhandle._fflush(wasm);
                }
                return 0;
            }
            return withHandle(handle, fhandle => fhandle._fflush(wasm));
        },
        fopen(fileNamePtr: number, flagsStrPtr: number) {
            return fopen(fileNamePtr, flagsStrPtr, ++nextHandle);
        },
        fread(ptr: number, size: number, count: number, handle: number) {
            return withHandle(handle, fhandle => fhandle._fread(wasm, ptr, size, count));
        },
        /*freopen(fileNamePtr: number, flagsStrPtr: number, handle: number) {
            return withHandle(handle, () => {
                handles.delete(handle);
                return fopen(fileNamePtr, flagsStrPtr, handle);
            });
        },
        fwrite(ptr: number, size: number, count: number, handle: number) {
            return withHandle(handle, fhandle => fhandle._fwrite(wasm, ptr, size, count));
        },
        remove(fileNamePtr: number) {
            const fileName = wasm.convertCharPToAsciiString(fileNamePtr);
            fs.delete(fileName);
            return 0;
        },
        */
        js_fseek(handle: number, offset: number, whence: SeekOrigin) {
            return withHandle(handle, fhandle => fhandle._fseek(offset, whence));
        },
        js_ftell(handle: number) {
            const ret = withHandle(handle, fhandle => fhandle._ftell());
            return ret;
        },
        js_stat(fileNamePtr: number, mtimeDoublePtr: number) {
            const fileName = wasm.convertCharPToAsciiString(fileNamePtr);
            const file = fs.get(fileName);
            if (file) {
                wasm.setF64(mtimeDoublePtr, Math.floor(file.lastModified / 1000));
                return 0;
            }
            return -1;
        },
        /*
        js_utime() {
            return 0;
        },
        */
    };
}


text:
<?php

namespace App\Repositories;

use Illuminate\Database\Eloquent\Model;

abstract class AbstractRepository implements RepositoryInterface
{
	/**
	 * The default model for this repository.
	 *
	 * @var Model
	 */
	protected $model;

	/**
	 * AbstractRepository.
	 *
	 * @param Model $model
	 */
	public function __construct(Model $model)
	{
		$this->model = $model;
	}

	/**
	 * {@inheritDoc}
	 * @see \App\Repositories\RepositoryInterface::getAll()
	 */
	public function getAll(array $columns = ['*'])
	{
		return $this->model->all($columns);
	}

	/**
	 * {@inheritDoc}
	 * @see \App\Repositories\RepositoryInterface::getById()
	 */
	public function getById($id, array $columns = ['*'])
	{
		return $this->model->findOrFail($id, $columns);
	}

	/**
	 * {@inheritDoc}
	 * @see \App\Repositories\RepositoryInterface::deleteById()
	 */
	public function deleteById($id)
	{
		$entity = $this->getById($id);

		$entity->delete();

		return $entity;
	}
}


text:
package org.apache.maven.plugins.issues;

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

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.issues.AbstractIssueManagementSystem;

import junit.framework.TestCase;

/**
 * @author Alan Parkinson
 * @version $Id$
 * @since 2.7
 */
public class IssueManagementSystemTest
    extends TestCase
{

    private MockIssueManagementSystem ims;

    private class MockIssueManagementSystem
        extends AbstractIssueManagementSystem
    {

        @Override
        public String getName()
        {
            return "Mock IMS";
        }

    }

    @Override
    protected void setUp()
        throws Exception
    {
        ims = new MockIssueManagementSystem();
    }

    public void testApplyingValidCustomIssueTypes()
    {
        Map<String, String> issueTypes = new HashMap<String, String>();
        issueTypes.put( "add", "Story,Epic" );
        issueTypes.put( "fix", "Defect" );
        issueTypes.put( "update", "Improvement" );

        try
        {
            ims.applyConfiguration( issueTypes );
        }
        catch ( MojoExecutionException e )
        {
            fail();
        }
    }

    public void testApplyingInvalidCustomIssueTypes()
    {
        Map<String, String> issueTypes = new HashMap<String, String>();
        issueTypes.put( "new", "Story,Epic" );

        try
        {
            ims.applyConfiguration( issueTypes );
            fail( "Exception not thrown for invalid group name" );
        }
        catch ( MojoExecutionException e )
        {

        }
    }
}


text:
package com.linecorp.armeria.server.annotation;

import static com.linecorp.armeria.internal.server.ResponseConversionUtil.aggregateFrom;
import static java.util.Objects.requireNonNull;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.stream.Stream;

import org.reactivestreams.Publisher;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.linecorp.armeria.common.HttpData;
import com.linecorp.armeria.common.HttpHeaders;
import com.linecorp.armeria.common.HttpResponse;
import com.linecorp.armeria.common.MediaType;
import com.linecorp.armeria.common.ResponseHeaders;
import com.linecorp.armeria.common.annotation.Nullable;
import com.linecorp.armeria.common.util.Exceptions;
import com.linecorp.armeria.internal.common.JacksonUtil;
import com.linecorp.armeria.server.ServiceRequestContext;
import com.linecorp.armeria.server.streaming.JsonTextSequences;

/**
 * A response converter implementation which creates an {@link HttpResponse} with
 * {@code content-type: application/json; charset=utf-8} or {@code content-type: application/json-seq}.
 * The objects published from a {@link Publisher} or {@link Stream} would be converted into JSON Text Sequences
 * if a {@link ProducesJsonSequences} annotation is specified on an annotated service method.
 * Note that this {@link ResponseConverterFunction} is applied to an annotated service by default,
 * so you don't have to specify this converter explicitly unless you want to use your own {@link ObjectMapper}.
 *
 * @see JavaScript Object Notation (JSON) Text Sequences
 */
public final class JacksonResponseConverterFunction implements ResponseConverterFunction {

    private static final ObjectMapper defaultObjectMapper = JacksonUtil.newDefaultObjectMapper();

    private final ObjectMapper mapper;

    /**
     * Creates an instance with the default {@link ObjectMapper}.
     */
    public JacksonResponseConverterFunction() {
        this(defaultObjectMapper);
    }

    /**
     * Creates an instance with the specified {@link ObjectMapper}.
     */
    public JacksonResponseConverterFunction(ObjectMapper mapper) {
        this.mapper = requireNonNull(mapper, "mapper");
    }

    @Override
    public HttpResponse convertResponse(ServiceRequestContext ctx,
                                        ResponseHeaders headers,
                                        @Nullable Object result,
                                        HttpHeaders trailers) throws Exception {
        final MediaType mediaType = headers.contentType();
        if (mediaType != null) {
            // @Produces("application/json") or @ProducesJson is specified.
            // Any MIME type which ends with '+json' such as 'application/json-patch+json' can be also accepted.
            if (mediaType.isJson()) {
                final Charset charset = mediaType.charset(StandardCharsets.UTF_8);
                // Convert the object only if the charset supports UTF-8,
                // because ObjectMapper always writes JSON document as UTF-8.
                if (charset.contains(StandardCharsets.UTF_8)) {
                    if (result instanceof Publisher) {
                        return aggregateFrom((Publisher<?>) result, headers, trailers,
                                             this::toJsonHttpData, ctx);
                    }
                    if (result instanceof Stream) {
                        return aggregateFrom((Stream<?>) result, headers, trailers,
                                             this::toJsonHttpData, ctx.blockingTaskExecutor());
                    }
                    return HttpResponse.of(headers, toJsonHttpData(result), trailers);
                }
            }

            // @Produces("application/json-seq") or @ProducesJsonSequences is specified.
            if (mediaType.is(MediaType.JSON_SEQ)) {
                if (result instanceof Publisher) {
                    return JsonTextSequences.fromPublisher(headers, (Publisher<?>) result, trailers, mapper);
                }
                if (result instanceof Stream) {
                    return JsonTextSequences.fromStream(headers, (Stream<?>) result, trailers,
                                                        ctx.blockingTaskExecutor(), mapper);
                }
                return JsonTextSequences.fromObject(headers, result, trailers, mapper);
            }
        } else if (result instanceof JsonNode) {
            // No media type is specified, but the result is a JsonNode type.
            return HttpResponse.of(headers.toBuilder().contentType(MediaType.JSON_UTF_8).build(),
                                   toJsonHttpData(result), trailers);
        }

        return ResponseConverterFunction.fallthrough();
    }

    private HttpData toJsonHttpData(@Nullable Object value) {
        try {
            return HttpData.wrap(mapper.writeValueAsBytes(value));
        } catch (Exception e) {
            return Exceptions.throwUnsafely(e);
        }
    }
}


text:
package com.kskkbys.rate;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.util.Log;

import java.util.Date;

/**
 * RateThisApp

 * A library to show the app rate dialog
 * @author Keisuke Kobayashi <k.kobayashi.122@gmail.com>
 *
 */
public class RateThisApp {

	private static final String TAG = RateThisApp.class.getSimpleName();

	private static final String PREF_NAME = "RateThisApp";
	private static final String KEY_INSTALL_DATE = "rta_install_date";
	private static final String KEY_LAUNCH_TIMES = "rta_launch_times";
	private static final String KEY_OPT_OUT = "rta_opt_out";

	private static Date mInstallDate = new Date();
	private static int mLaunchTimes = 0;
	private static boolean mOptOut = false;

	/**
	 * Days after installation until showing rate dialog
	 */
	public static final int INSTALL_DAYS = 7;
	/**
	 * App launching times until showing rate dialog
	 */
	public static final int LAUNCH_TIMES = 10;

	/**
	 * If true, print LogCat
	 */
	public static final boolean DEBUG = false;

	/**
	 * Call this API when the launcher activity is launched.

	 * It is better to call this API in onStart() of the launcher activity.
	 */
	public static void onStart(Context context) {
		SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
		Editor editor = pref.edit();
		// If it is the first launch, save the date in shared preference.
		if (pref.getLong(KEY_INSTALL_DATE, 0) == 0L) {
			Date now = new Date();
			editor.putLong(KEY_INSTALL_DATE, now.getTime());
			log("First install: " + now.toString());
		}
		// Increment launch times
		int launchTimes = pref.getInt(KEY_LAUNCH_TIMES, 0);
		launchTimes++;
		editor.putInt(KEY_LAUNCH_TIMES, launchTimes);
		log("Launch times; " + launchTimes);

		editor.commit();

		mInstallDate = new Date(pref.getLong(KEY_INSTALL_DATE, 0));
		mLaunchTimes = pref.getInt(KEY_LAUNCH_TIMES, 0);
		mOptOut = pref.getBoolean(KEY_OPT_OUT, false);

		printStatus(context);
	}

	/**
	 * Show the rate dialog if the criteria is satisfied
	 * @param context
	 */
	public static void showRateDialogIfNeeded(final Context context) {
		if (shouldShowRateDialog()) {
			showRateDialog(context);
		}
	}

	/**
	 * Check whether the rate dialog shoule be shown or not
	 * @return
	 */
	private static boolean shouldShowRateDialog() {
		if (mOptOut) {
			return false;
		} else {
			if (mLaunchTimes >= LAUNCH_TIMES) {
				return true;
			}
			long threshold = INSTALL_DAYS * 24 * 60 * 60 * 1000L;	// msec
			if (new Date().getTime() - mInstallDate.getTime() >= threshold) {
				return true;
			}
			return false;
		}
	}

	/**
	 * Show the rate dialog
	 * @param context
	 */
	public static void showRateDialog(final Context context) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(R.string.rta_dialog_title);
		builder.setMessage(R.string.rta_dialog_message);
		builder.setPositiveButton(R.string.rta_dialog_ok, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String appPackage = context.getPackageName();
				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackage));
				context.startActivity(intent);
				setOptOut(context, true);
			}
		});
		builder.setNeutralButton(R.string.rta_dialog_cancel, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				clearSharedPreferences(context);
			}
		});
		builder.setNegativeButton(R.string.rta_dialog_no, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				setOptOut(context, true);
			}
		});
		builder.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				clearSharedPreferences(context);
			}
		});
		builder.create().show();
	}

	/**
	 * Clear data in shared preferences.

	 * This API is called when the rate dialog is approved or canceled.
	 * @param context
	 */
	private static void clearSharedPreferences(Context context) {
		SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
		Editor editor = pref.edit();
		editor.remove(KEY_INSTALL_DATE);
		editor.remove(KEY_LAUNCH_TIMES);
		editor.commit();
	}

	/**
	 * Set opt out flag. If it is true, the rate dialog will never shown unless app data is cleared.
	 * @param context
	 * @param optOut
	 */
	private static void setOptOut(final Context context, boolean optOut) {
		SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
		Editor editor = pref.edit();
		editor.putBoolean(KEY_OPT_OUT, optOut);
		editor.commit();
	}

	/**
	 * Print values in SharedPreferences (used for debug)
	 * @param context
	 */
	private static void printStatus(final Context context) {
		SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
		log("*** RateThisApp Status ***");
		log("Install Date: " + new Date(pref.getLong(KEY_INSTALL_DATE, 0)));
		log("Launch Times: " + pref.getInt(KEY_LAUNCH_TIMES, 0));
		log("Opt out: " + pref.getBoolean(KEY_OPT_OUT, false));
	}

	/**
	 * Print log if enabled
	 * @param message
	 */
	private static void log(String message) {
		if (DEBUG) {
			Log.v(TAG, message);
		}
	}
}


text:
package org.jivesoftware.smackx.gcm.provider;

import org.jivesoftware.smackx.gcm.packet.GcmPacketExtension;
import org.jivesoftware.smackx.json.provider.AbstractJsonExtensionProvider;

public class GcmExtensionProvider extends AbstractJsonExtensionProvider<GcmPacketExtension> {

    @Override
    public GcmPacketExtension from(String json) {
        return new GcmPacketExtension(json);
    }
}


text:
<?php

// IMPORTANT!!! Require composer autoload
require_once 'vendor/autoload.php';
require_once 'vendor/taviroquai/architectphp/aliases.php';

// IMPORTANT!!! Give configuration file and run application
$config = "config/development.xml";
$arch = new \Arch\App();
$arch->getConfig()->load($config);
$arch->getLogger()->setFilename($arch->getConfig()->get('LOG_FILE'));
$arch->run();


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.zkp.healthbox.MainActivity">

        <item android:id="@+id/menu_refresh"
            android:checkable="false"
            android:orderInCategory="1"
            android:showAsAction="ifRoom"/>
        <item android:id="@+id/menu_scan"
            android:title="@string/menu_scan"
            android:orderInCategory="100"
            android:showAsAction="ifRoom|withText"/>
        <item android:id="@+id/menu_stop"
            android:title="@string/menu_stop"
            android:orderInCategory="101"
            android:showAsAction="ifRoom|withText"/>

</menu>


text:
[![npm version](https://badge.fury.io/js/single-module-instance-webpack-plugin.svg)](https://www.npmjs.com/package/single-module-instance-webpack-plugin)

At runtime webpacked module [can be initialized more than once][webpack-1353] which is expected
behavior for Node. Nevertheless this behavior hurts a lot if you are used to RequireJS and even
may introduce unexpected singleton collisions.

`SingleModuleInstanceWebpackPlugin` plugin along with [`DedupePlugin`][dedupe-plugin] would force
`require` to serve only one instance of each requested module.

Update `webpack.config.js` with following snippet:

``` js
var SingleModuleInstancePlugin = require('single-module-instance-webpack-plugin');

module.exports = {
  plugins: [
    new webpack.optimize.DedupePlugin(),
    new SingleModuleInstancePlugin()
  ]
}
```

## TODO

- Add tests

## License

The code is available under [MIT licence](LICENSE.txt).

[dedupe-plugin]: https://webpack.github.io/docs/list-of-plugins.html#dedupeplugin
[webpack-1353]: https://github.com/webpack/webpack/pull/1353


text:
using System;
using System.Net;
using RestSharp;
using Newtonsoft.Json.Linq;

namespace Hvz.Api.Response
{
    public class TeamStatusResponse : ApiResponse
    {
        public static TeamStatusResponse BuildResponse(IRestResponse response)
        {
            var result = ApiResponse.BuildResponse<TeamStatusResponse>(response);
            if(result.StatusCode == HttpStatusCode.OK)
            {
                var json = JObject.Parse(response.Content);

                result.HumanCount = (int)json["humans"];
                result.ZombieCount = (int)json["zombies"];
            }

            return result;
        }

        public int HumanCount { get; set; }

        public int ZombieCount { get; set; }
    }
}


text:
package com.google.cloud.talent.v4;

import static com.google.cloud.talent.v4.TenantServiceClient.ListTenantsPagedResponse;

import com.google.api.gax.core.NoCredentialsProvider;
import com.google.api.gax.httpjson.GaxHttpJsonProperties;
import com.google.api.gax.httpjson.testing.MockHttpService;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.ApiExceptionFactory;
import com.google.api.gax.rpc.InvalidArgumentException;
import com.google.api.gax.rpc.StatusCode;
import com.google.api.gax.rpc.testing.FakeStatusCode;
import com.google.cloud.talent.v4.stub.HttpJsonTenantServiceStub;
import com.google.common.collect.Lists;
import com.google.protobuf.Empty;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Generated;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

@Generated("by gapic-generator-java")
public class TenantServiceClientHttpJsonTest {
  private static MockHttpService mockService;
  private static TenantServiceClient client;

  @BeforeClass
  public static void startStaticServer() throws IOException {
    mockService =
        new MockHttpService(
            HttpJsonTenantServiceStub.getMethodDescriptors(),
            TenantServiceSettings.getDefaultEndpoint());
    TenantServiceSettings settings =
        TenantServiceSettings.newHttpJsonBuilder()
            .setTransportChannelProvider(
                TenantServiceSettings.defaultHttpJsonTransportProviderBuilder()
                    .setHttpTransport(mockService)
                    .build())
            .setCredentialsProvider(NoCredentialsProvider.create())
            .build();
    client = TenantServiceClient.create(settings);
  }

  @AfterClass
  public static void stopServer() {
    client.close();
  }

  @Before
  public void setUp() {}

  @After
  public void tearDown() throws Exception {
    mockService.reset();
  }

  @Test
  public void createTenantTest() throws Exception {
    Tenant expectedResponse =
        Tenant.newBuilder()
            .setName(TenantName.of("[PROJECT]", "[TENANT]").toString())
            .setExternalId("externalId-1699764666")
            .build();
    mockService.addResponse(expectedResponse);

    ProjectName parent = ProjectName.of("[PROJECT]");
    Tenant tenant = Tenant.newBuilder().build();

    Tenant actualResponse = client.createTenant(parent, tenant);
    Assert.assertEquals(expectedResponse, actualResponse);

    List<String> actualRequests = mockService.getRequestPaths();
    Assert.assertEquals(1, actualRequests.size());

    String apiClientHeaderKey =
        mockService
            .getRequestHeaders()
            .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
            .iterator()
            .next();
    Assert.assertTrue(
        GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
            .matcher(apiClientHeaderKey)
            .matches());
  }

  @Test
  public void createTenantExceptionTest() throws Exception {
    ApiException exception =
        ApiExceptionFactory.createException(
            new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
    mockService.addException(exception);

    try {
      ProjectName parent = ProjectName.of("[PROJECT]");
      Tenant tenant = Tenant.newBuilder().build();
      client.createTenant(parent, tenant);
      Assert.fail("No exception raised");
    } catch (InvalidArgumentException e) {
      // Expected exception.
    }
  }

  @Test
  public void createTenantTest2() throws Exception {
    Tenant expectedResponse =
        Tenant.newBuilder()
            .setName(TenantName.of("[PROJECT]", "[TENANT]").toString())
            .setExternalId("externalId-1699764666")
            .build();
    mockService.addResponse(expectedResponse);

    String parent = "projects/project-2353";
    Tenant tenant = Tenant.newBuilder().build();

    Tenant actualResponse = client.createTenant(parent, tenant);
    Assert.assertEquals(expectedResponse, actualResponse);

    List<String> actualRequests = mockService.getRequestPaths();
    Assert.assertEquals(1, actualRequests.size());

    String apiClientHeaderKey =
        mockService
            .getRequestHeaders()
            .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
            .iterator()
            .next();
    Assert.assertTrue(
        GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
            .matcher(apiClientHeaderKey)
            .matches());
  }

  @Test
  public void createTenantExceptionTest2() throws Exception {
    ApiException exception =
        ApiExceptionFactory.createException(
            new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
    mockService.addException(exception);

    try {
      String parent = "projects/project-2353";
      Tenant tenant = Tenant.newBuilder().build();
      client.createTenant(parent, tenant);
      Assert.fail("No exception raised");
    } catch (InvalidArgumentException e) {
      // Expected exception.
    }
  }

  @Test
  public void getTenantTest() throws Exception {
    Tenant expectedResponse =
        Tenant.newBuilder()
            .setName(TenantName.of("[PROJECT]", "[TENANT]").toString())
            .setExternalId("externalId-1699764666")
            .build();
    mockService.addResponse(expectedResponse);

    TenantName name = TenantName.of("[PROJECT]", "[TENANT]");

    Tenant actualResponse = client.getTenant(name);
    Assert.assertEquals(expectedResponse, actualResponse);

    List<String> actualRequests = mockService.getRequestPaths();
    Assert.assertEquals(1, actualRequests.size());

    String apiClientHeaderKey =
        mockService
            .getRequestHeaders()
            .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
            .iterator()
            .next();
    Assert.assertTrue(
        GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
            .matcher(apiClientHeaderKey)
            .matches());
  }

  @Test
  public void getTenantExceptionTest() throws Exception {
    ApiException exception =
        ApiExceptionFactory.createException(
            new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
    mockService.addException(exception);

    try {
      TenantName name = TenantName.of("[PROJECT]", "[TENANT]");
      client.getTenant(name);
      Assert.fail("No exception raised");
    } catch (InvalidArgumentException e) {
      // Expected exception.
    }
  }

  @Test
  public void getTenantTest2() throws Exception {
    Tenant expectedResponse =
        Tenant.newBuilder()
            .setName(TenantName.of("[PROJECT]", "[TENANT]").toString())
            .setExternalId("externalId-1699764666")
            .build();
    mockService.addResponse(expectedResponse);

    String name = "projects/project-7691/tenants/tenant-7691";

    Tenant actualResponse = client.getTenant(name);
    Assert.assertEquals(expectedResponse, actualResponse);

    List<String> actualRequests = mockService.getRequestPaths();
    Assert.assertEquals(1, actualRequests.size());

    String apiClientHeaderKey =
        mockService
            .getRequestHeaders()
            .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
            .iterator()
            .next();
    Assert.assertTrue(
        GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
            .matcher(apiClientHeaderKey)
            .matches());
  }

  @Test
  public void getTenantExceptionTest2() throws Exception {
    ApiException exception =
        ApiExceptionFactory.createException(
            new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
    mockService.addException(exception);

    try {
      String name = "projects/project-7691/tenants/tenant-7691";
      client.getTenant(name);
      Assert.fail("No exception raised");
    } catch (InvalidArgumentException e) {
      // Expected exception.
    }
  }

  @Test
  public void updateTenantTest() throws Exception {
    Tenant expectedResponse =
        Tenant.newBuilder()
            .setName(TenantName.of("[PROJECT]", "[TENANT]").toString())
            .setExternalId("externalId-1699764666")
            .build();
    mockService.addResponse(expectedResponse);

    Tenant tenant =
        Tenant.newBuilder()
            .setName(TenantName.of("[PROJECT]", "[TENANT]").toString())
            .setExternalId("externalId-1699764666")
            .build();
    FieldMask updateMask = FieldMask.newBuilder().build();

    Tenant actualResponse = client.updateTenant(tenant, updateMask);
    Assert.assertEquals(expectedResponse, actualResponse);

    List<String> actualRequests = mockService.getRequestPaths();
    Assert.assertEquals(1, actualRequests.size());

    String apiClientHeaderKey =
        mockService
            .getRequestHeaders()
            .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
            .iterator()
            .next();
    Assert.assertTrue(
        GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
            .matcher(apiClientHeaderKey)
            .matches());
  }

  @Test
  public void updateTenantExceptionTest() throws Exception {
    ApiException exception =
        ApiExceptionFactory.createException(
            new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
    mockService.addException(exception);

    try {
      Tenant tenant =
          Tenant.newBuilder()
              .setName(TenantName.of("[PROJECT]", "[TENANT]").toString())
              .setExternalId("externalId-1699764666")
              .build();
      FieldMask updateMask = FieldMask.newBuilder().build();
      client.updateTenant(tenant, updateMask);
      Assert.fail("No exception raised");
    } catch (InvalidArgumentException e) {
      // Expected exception.
    }
  }

  @Test
  public void deleteTenantTest() throws Exception {
    Empty expectedResponse = Empty.newBuilder().build();
    mockService.addResponse(expectedResponse);

    TenantName name = TenantName.of("[PROJECT]", "[TENANT]");

    client.deleteTenant(name);

    List<String> actualRequests = mockService.getRequestPaths();
    Assert.assertEquals(1, actualRequests.size());

    String apiClientHeaderKey =
        mockService
            .getRequestHeaders()
            .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
            .iterator()
            .next();
    Assert.assertTrue(
        GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
            .matcher(apiClientHeaderKey)
            .matches());
  }

  @Test
  public void deleteTenantExceptionTest() throws Exception {
    ApiException exception =
        ApiExceptionFactory.createException(
            new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
    mockService.addException(exception);

    try {
      TenantName name = TenantName.of("[PROJECT]", "[TENANT]");
      client.deleteTenant(name);
      Assert.fail("No exception raised");
    } catch (InvalidArgumentException e) {
      // Expected exception.
    }
  }

  @Test
  public void deleteTenantTest2() throws Exception {
    Empty expectedResponse = Empty.newBuilder().build();
    mockService.addResponse(expectedResponse);

    String name = "projects/project-7691/tenants/tenant-7691";

    client.deleteTenant(name);

    List<String> actualRequests = mockService.getRequestPaths();
    Assert.assertEquals(1, actualRequests.size());

    String apiClientHeaderKey =
        mockService
            .getRequestHeaders()
            .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
            .iterator()
            .next();
    Assert.assertTrue(
        GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
            .matcher(apiClientHeaderKey)
            .matches());
  }

  @Test
  public void deleteTenantExceptionTest2() throws Exception {
    ApiException exception =
        ApiExceptionFactory.createException(
            new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
    mockService.addException(exception);

    try {
      String name = "projects/project-7691/tenants/tenant-7691";
      client.deleteTenant(name);
      Assert.fail("No exception raised");
    } catch (InvalidArgumentException e) {
      // Expected exception.
    }
  }

  @Test
  public void listTenantsTest() throws Exception {
    Tenant responsesElement = Tenant.newBuilder().build();
    ListTenantsResponse expectedResponse =
        ListTenantsResponse.newBuilder()
            .setNextPageToken("")
            .addAllTenants(Arrays.asList(responsesElement))
            .build();
    mockService.addResponse(expectedResponse);

    ProjectName parent = ProjectName.of("[PROJECT]");

    ListTenantsPagedResponse pagedListResponse = client.listTenants(parent);

    List<Tenant> resources = Lists.newArrayList(pagedListResponse.iterateAll());

    Assert.assertEquals(1, resources.size());
    Assert.assertEquals(expectedResponse.getTenantsList().get(0), resources.get(0));

    List<String> actualRequests = mockService.getRequestPaths();
    Assert.assertEquals(1, actualRequests.size());

    String apiClientHeaderKey =
        mockService
            .getRequestHeaders()
            .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
            .iterator()
            .next();
    Assert.assertTrue(
        GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
            .matcher(apiClientHeaderKey)
            .matches());
  }

  @Test
  public void listTenantsExceptionTest() throws Exception {
    ApiException exception =
        ApiExceptionFactory.createException(
            new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
    mockService.addException(exception);

    try {
      ProjectName parent = ProjectName.of("[PROJECT]");
      client.listTenants(parent);
      Assert.fail("No exception raised");
    } catch (InvalidArgumentException e) {
      // Expected exception.
    }
  }

  @Test
  public void listTenantsTest2() throws Exception {
    Tenant responsesElement = Tenant.newBuilder().build();
    ListTenantsResponse expectedResponse =
        ListTenantsResponse.newBuilder()
            .setNextPageToken("")
            .addAllTenants(Arrays.asList(responsesElement))
            .build();
    mockService.addResponse(expectedResponse);

    String parent = "projects/project-2353";

    ListTenantsPagedResponse pagedListResponse = client.listTenants(parent);

    List<Tenant> resources = Lists.newArrayList(pagedListResponse.iterateAll());

    Assert.assertEquals(1, resources.size());
    Assert.assertEquals(expectedResponse.getTenantsList().get(0), resources.get(0));

    List<String> actualRequests = mockService.getRequestPaths();
    Assert.assertEquals(1, actualRequests.size());

    String apiClientHeaderKey =
        mockService
            .getRequestHeaders()
            .get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
            .iterator()
            .next();
    Assert.assertTrue(
        GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
            .matcher(apiClientHeaderKey)
            .matches());
  }

  @Test
  public void listTenantsExceptionTest2() throws Exception {
    ApiException exception =
        ApiExceptionFactory.createException(
            new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
    mockService.addException(exception);

    try {
      String parent = "projects/project-2353";
      client.listTenants(parent);
      Assert.fail("No exception raised");
    } catch (InvalidArgumentException e) {
      // Expected exception.
    }
  }
}


text:
export default function(target, ...values) {
  function merge({ state, resolve }) {
    if (!resolve.isTag(target, 'state')) {
      throw new Error(
        'Cerebral operator.merge: You have to use the STATE TAG as first argument'
      )
    }

    state.merge(
      resolve.path(target),
      ...values.map(value => {
        if (resolve.isTag(value)) {
          return resolve.value(value)
        }

        return Object.keys(value).reduce((currentValue, key) => {
          currentValue[key] = resolve.value(value[key])

          return currentValue
        }, {})
      })
    )
  }

  merge.displayName = `operator.merge(${String(target)}, ${values
    .map(value => {
      return String(value)
    })
    .join(',')})`

  return merge
}


text:
package org.neo4j.kernel.impl.store.id;

import org.junit.Test;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.LockSupport;

import org.neo4j.function.Consumer;
import org.neo4j.function.Predicate;
import org.neo4j.function.Predicates;
import org.neo4j.function.Supplier;
import org.neo4j.helpers.Clock;
import org.neo4j.test.Race;
import static java.util.concurrent.ThreadLocalRandom.current;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.locks.LockSupport.parkNanos;

import static org.neo4j.function.Suppliers.singleton;
import static org.neo4j.unsafe.impl.batchimport.Utils.safeCastLongToInt;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoMoreInteractions;

public class DelayedBufferTest
{
    @Test
    public void shouldHandleTheWholeWorkloadShebang() throws Throwable
    {
        // GIVEN
        final int size = 1_000;
        final long bufferTime = 3;
        VerifyingConsumer consumer = new VerifyingConsumer( size );
        final Clock clock = Clock.SYSTEM_CLOCK;
        Supplier<Long> chunkThreshold = new Supplier<Long>()
        {
            @Override
            public Long get()
            {
                return clock.currentTimeMillis();
            }
        };
        Predicate<Long> safeThreshold = new Predicate<Long>()
        {
            @Override
            public boolean test( Long time )
            {
                return clock.currentTimeMillis() - bufferTime >= time;
            }
        };
        final DelayedBuffer<Long> buffer = new DelayedBuffer<>( chunkThreshold, safeThreshold, 10, consumer );
        MaintenanceThread maintenance = new MaintenanceThread( buffer, 5 );
        Race adders = new Race();
        final int numberOfAdders = 20;
        final byte[] offeredIds = new byte[size];
        for ( int i = 0; i < numberOfAdders; i++ )
        {
            final int finalI = i;
            adders.addContestant( new Runnable()
            {
                @Override
                public void run()
                {
                    for ( int j = 0; j < size; j++ )
                    {
                        if ( j % numberOfAdders == finalI )
                        {
                            buffer.offer( j );
                            offeredIds[j] = 1;
                            parkNanos( MILLISECONDS.toNanos( current().nextInt( 2 ) ) );
                        }
                    }
                }
            } );
        }

        // WHEN (multi-threadded) offering of ids
        adders.go();
        // ... ensuring the test is sane itself (did we really offer all these IDs?)
        for ( int i = 0; i < size; i++ )
        {
            assertEquals( "ID " + i, (byte) 1, offeredIds[i] );
        }
        maintenance.halt();
        buffer.close();

        // THEN
        consumer.assertHaveOnlySeenRange( 0, size-1 );
    }

    @Test
    public void shouldNotReleaseValuesUntilCrossedThreshold() throws Exception
    {
        // GIVEN
        VerifyingConsumer consumer = new VerifyingConsumer( 30 );
        final AtomicLong txOpened = new AtomicLong();
        final AtomicLong txClosed = new AtomicLong();
        Supplier<Long> chunkThreshold = new Supplier<Long>()
        {
            @Override
            public Long get()
            {
                return txOpened.get();
            }
        };
        Predicate<Long> safeThreshold = new Predicate<Long>()
        {
            @Override
            public boolean test( Long value )
            {
                return txClosed.get() >= value;
            }
        };
        DelayedBuffer<Long> buffer = new DelayedBuffer<>( chunkThreshold, safeThreshold, 100, consumer );

        // Transaction spans like these:
        //    1 |-1--------2-------3---|
        //    2   |4--5---------|
        //    3       |---------6----|
        //    4        |7--8-|
        //    5          |--------9-------10-|
        //    6                  |--11----|
        //    7                    |-12---13---14--|
        // TIME|1-2-3-4-5-6-7-8-9-a-b-c-d-e-f-g-h-i-j|
        //  POI     ^   ^     ^         ^     ^     ^
        //          A   B     C         D     E     F

        // A
        txOpened.incrementAndGet(); // <-- TX 1
        buffer.offer( 1 );
        txOpened.incrementAndGet(); // <-- TX 2
        buffer.offer( 4 );
        buffer.maintenance();
        assertEquals( 0, consumer.chunksAccepted() );

        // B
        buffer.offer( 5 );
        txOpened.incrementAndGet(); // <-- TX 3
        txOpened.incrementAndGet(); // <-- TX 4
        buffer.offer( 7 );
        buffer.maintenance();
        assertEquals( 0, consumer.chunksAccepted() );

        // C
        txOpened.incrementAndGet(); // <-- TX 5
        buffer.offer( 2 );
        buffer.offer( 8 );
        // TX 4 closes, but TXs with lower ids are still open
        buffer.maintenance();
        assertEquals( 0, consumer.chunksAccepted() );

        // D
        // TX 2 closes, but TXs with lower ids are still open
        buffer.offer( 6 );
        txOpened.incrementAndGet(); // <-- TX 6
        buffer.offer( 9 );
        buffer.offer( 3 );
        txOpened.incrementAndGet(); // <-- TX 7
        buffer.offer( 11 );
        // TX 3 closes, but TXs with lower ids are still open
        buffer.offer( 12 );
        txClosed.set( 4 ); // since 1-4 have now all closed
        buffer.maintenance();
        consumer.assertHaveOnlySeen( 1, 4, 5, 7 );

        // E
        buffer.offer( 10 );
        // TX 6 closes, but TXs with lower ids are still open
        buffer.offer( 13 );
        txClosed.set( 6 ); // since 1-6 have now all closed
        buffer.maintenance();
        consumer.assertHaveOnlySeen( 1, 2, 4, 5, 7, 8 );

        // F
        buffer.offer( 14 );
        txClosed.set( 7 ); // since 1-7 have now all closed
        buffer.maintenance();
        consumer.assertHaveOnlySeen( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 );
    }

    @Test
    public void shouldClearCurrentChunk() throws Exception
    {
        // GIVEN
        Consumer<long[]> consumer = mock( Consumer.class );
        DelayedBuffer<Long> buffer = new DelayedBuffer<>( singleton( 0L ), Predicates.<Long>alwaysTrue(),
                10, consumer );
        buffer.offer( 0 );
        buffer.offer( 1 );
        buffer.offer( 2 );

        // WHEN
        buffer.clear();
        buffer.maintenance();

        // THEN
        verifyNoMoreInteractions( consumer );
    }

    @Test
    public void shouldClearPreviousChunks() throws Exception
    {
        // GIVEN
        Consumer<long[]> consumer = mock( Consumer.class );
        final AtomicBoolean safeThreshold = new AtomicBoolean( false );
        DelayedBuffer<Long> buffer = new DelayedBuffer<>( singleton( 0L ), new Predicate<Long>()
        {
            @Override
            public boolean test( Long t )
            {
                return safeThreshold.get();
            }
        }, 10, consumer );
        // three chunks
        buffer.offer( 0 );
        buffer.maintenance();
        buffer.offer( 1 );
        buffer.maintenance();
        buffer.offer( 2 );
        buffer.maintenance();

        // WHEN
        safeThreshold.set( true );
        buffer.clear();
        buffer.maintenance();

        // THEN
        verifyNoMoreInteractions( consumer );
    }

    private static class MaintenanceThread extends Thread
    {
        private final DelayedBuffer buffer;
        private final long nanoInterval;
        private volatile boolean end;

        MaintenanceThread( DelayedBuffer buffer, long nanoInterval )
        {
            this.buffer = buffer;
            this.nanoInterval = nanoInterval;
            start();
        }

        @Override
        public void run()
        {
            while ( !end )
            {
                buffer.maintenance();
                LockSupport.parkNanos( nanoInterval );
            }
        }

        void halt() throws InterruptedException
        {
            end = true;
            while ( isAlive() )
            {
                Thread.sleep( 1 );
            }
        }
    }

    private static class VerifyingConsumer implements Consumer<long[]>
    {
        private final boolean[] seenIds;
        private int chunkCount;

        public VerifyingConsumer( int size )
        {
            seenIds = new boolean[size];
        }

        void assertHaveOnlySeenRange( long low, long high )
        {
            long[] values = new long[(int) (high - low + 1)];
            for ( long id = low, i = 0; id <= high; id++, i++ )
            {
                values[(int) i] = id;
            }
            assertHaveOnlySeen( values );
        }

        @Override
        public void accept( long[] chunk )
        {
            chunkCount++;
            for ( long id : chunk )
            {
                assertFalse( seenIds[safeCastLongToInt( id )] );
                seenIds[safeCastLongToInt( id )] = true;
            }
        }

        void assertHaveOnlySeen( long... values )
        {
            for ( int i = 0, vi = 0; i < seenIds.length && vi < values.length; i++ )
            {
                boolean expectedToBeSeen = values[vi] == i;
                if ( expectedToBeSeen && !seenIds[i] )
                {
                    fail( "Expected to have seen " + i + ", but hasn't" );
                }
                else if ( !expectedToBeSeen && seenIds[i] )
                {
                    fail( "Expected to NOT have seen " + i + ", but have" );
                }

                if ( expectedToBeSeen )
                {
                    vi++;
                }
            }
        }

        int chunksAccepted()
        {
            return chunkCount;
        }
    }
}


text:
<?php

/**
 * This class is an iterator that will iterate only over enabled resources
 *
 * @category   Zend
 * @package    Zend_Tool
 * @copyright  Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Tool_Project_Profile_Resource_SearchConstraints
{

    /**
     * @var array
     */
    protected $_constraints = array();

    /**
     * __construct()
     *
     * @param array|string $options
     */
    public function __construct($options = null)
    {
        if (is_string($options)) {
            $this->addConstraint($options);
        } elseif (is_array($options)) {
            $this->setOptions($options);
        }
    }

    /**
     * setOptions()
     *
     * @param array $option
     * @return Zend_Tool_Project_Profile_Resource_SearchConstraints
     */
    public function setOptions(Array $option)
    {
        foreach ($option as $optionName => $optionValue) {
            if (is_int($optionName)) {
                $this->addConstraint($optionValue);
            } elseif (is_string($optionName)) {
                $this->addConstraint(array('name' => $optionName, 'params' => $optionValue));
            }
        }

        return $this;
    }

    /**
     * addConstraint()
     *
     * @param string|array $constraint
     * @return Zend_Tool_Project_Profile_Resource_SearchConstraints
     */
    public function addConstraint($constraint)
    {
        if (is_string($constraint)) {
            $name   = $constraint;
            $params = array();
        } elseif (is_array($constraint)) {
            $name   = $constraint['name'];
            $params = $constraint['params'];
        }

        $constraint = $this->_makeConstraint($name, $params);

        array_push($this->_constraints, $constraint);
        return $this;
    }

    /**
     * getConstraint()
     *
     * @return ArrayObject
     */
    public function getConstraint()
    {
        return array_shift($this->_constraints);
    }

    /**
     * _makeConstraint
     *
     * @param string $name
     * @param mixed $params
     * @return ArrayObject
     */
    protected function _makeConstraint($name, $params)
    {
        $value = array('name' => $name, 'params' => $params);
        return new ArrayObject($value, ArrayObject::ARRAY_AS_PROPS);
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Victorian Nat. 6: 61 (1889)

#### Original name
Psoroma biatorinum F. Wilson

### Remarks
null


text:
<template>
  <require from="./filter-value-converter"></require>
  <require from="./filtered-items-value-converter"></require>
<require from="./remove-selected-items-value-converter"></require>
<require from="./display-value-value-converter"></require>

        ${item | displayValue:displayItem}

      <input type="text" click.trigger="toggle()" value.bind="filterText" keydown.trigger="filterTextKeyDown($event)">

      Input at least 3 characters to start a search

        ${item | displayValue:displayItem}

</template>