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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>nz.co.senanque</groupId>
    <artifactId>madura-perspectives</artifactId>
    <version>3.4.0</version>
  </parent>
  <artifactId>madura-perspectives-pizzaorder</artifactId>
	<url>www.madurasoftware.com</url>
	<description>This is a rules-driven pizza configuration which lets you pick different pizza bases, toppings and sizes, except that only some combinations are allowed and the rules enforce this. The rules, UI and underlying domain objects are all delivered by this sub-application.</description>
	<organization>
		<name>Prometheus Consulting</name>
		<url>www.madurasoftware.com</url>
	</organization>
	<developers>
		<developer>
			<id>roger</id>
			<name>Roger J Parkinson</name>
			<email>roger.parkinson35 at gmail.com</email>
			<timezone>GMT+12</timezone>
			<roles>
			</roles>
		</developer>
	</developers>

	<dependencies>
		<dependency>
			<groupId>nz.co.senanque</groupId>
			<artifactId>madura-rules</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>nz.co.senanque</groupId>
			<artifactId>madura-vaadin-directed</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
		    <groupId>org.hibernate.javax.persistence</groupId>
		    <artifactId>hibernate-jpa-2.1-api</artifactId>
		    <version>1.0.0.Final</version>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<exclusions>
				<!-- Needs to be excluded because it pulls the wrong version -->
				<exclusion>
					<artifactId>slf4j-api</artifactId>
					<groupId>org.slf4j</groupId>
				</exclusion>
			</exclusions>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>nz.co.senanque</groupId>
			<artifactId>madura-vaadin</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>nz.co.senanque</groupId>
			<artifactId>madura-perspectives-library</artifactId>
			<scope>provided</scope>
		</dependency>
	</dependencies>
	<build>
      <pluginManagement>
        <plugins>
            <!--This plugin's configuration is used to store Eclipse
                m2e settings only. It has no influence on the Maven build itself. -->
            <plugin>
                <groupId>org.eclipse.m2e</groupId>
                <artifactId>lifecycle-mapping</artifactId>
                <version>1.0.0</version>
                <configuration>
                    <lifecycleMappingMetadata>
                        <pluginExecutions>
                            <pluginExecution>
                                <pluginExecutionFilter>
                                    <groupId>org.apache.maven.plugins</groupId>
                                    <artifactId>maven-dependency-plugin</artifactId>
                                    <versionRange>[1.0,)</versionRange>
                                    <goals>
                                        <goal>unpack-dependencies</goal>
                                    </goals>
                                </pluginExecutionFilter>
                                <action>
                                    <execute />
                                </action>
                            </pluginExecution>
                        </pluginExecutions>
                    </lifecycleMappingMetadata>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
		<resources>
			<resource>
				<directory>generated-sources/xjc</directory>
				<includes>
					<include>**/*.properties</include>
					<include>**/*.xml</include>
				</includes>
				<filtering>false</filtering>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
				<filtering>true</filtering>
			</resource>
		</resources>

		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-source-plugin</artifactId>
				<executions>
					<execution>
						<id>attach-sources</id>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-javadoc-plugin</artifactId>
				<executions>
					<execution>
						<id>attach-javadocs</id>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>nz.co.senanque</groupId>
				<artifactId>madura-objects-maven-plugin</artifactId>
				<executions>
					<execution>
						<goals>
							<goal>generate</goal>
						</goals>
						<configuration>
							<schemaIncludes>
								<include>PizzaOrder.xsd</include>
							</schemaIncludes>
						</configuration>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>nz.co.senanque</groupId>
				<artifactId>madura-rules-maven-plugin</artifactId>
				<executions>
					<execution>
						<goals>
							<goal>xjr</goal>
						</goals>
						<configuration>
							<rules>PizzaOrder.rul</rules>
							<schema>PizzaOrder.xsd</schema>
							<bufferSize>2000</bufferSize>
							<packageName>nz.co.senanque.pizzaorder.rules</packageName>
							<xsdpackageName>nz.co.senanque.pizzaorder.instances</xsdpackageName>
						</configuration>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<artifactId>maven-jar-plugin</artifactId>
				<executions>
					<execution>
						<id>default-jar</id>
						<phase>package</phase>
						<goals>
							<goal>jar</goal>
						</goals>
						<configuration>
							<archive>
								<index>false</index>
								<addMavenDescriptor>false</addMavenDescriptor>
								<manifest>
									<!-- use this to add a local list of dependencies -->
									<!--
									<addClasspath>true</addClasspath>
									<classpathPrefix>lib</classpathPrefix>
									 -->
								</manifest>
								<manifestEntries>
									<Built-By>${user.name}</Built-By>
									<Bundle-Activator>nz.co.senanque.madura.bundle.BundleRootImpl</Bundle-Activator>
									<Bundle-Description>project.description</Bundle-Description>
									<Bundle-Name>${project.artifactId}</Bundle-Name>
									<Bundle-Version>${project.version}</Bundle-Version>
				              		<Bundle-Context>bundle-spring.xml</Bundle-Context>
								</manifestEntries>
							</archive>
							<outputDirectory>../madura-perspectives-manager/src/main/webapp/WEB-INF/bundles/</outputDirectory>
						</configuration>
					</execution>
				</executions>
			</plugin>
			<plugin>
			    <groupId>org.codehaus.mojo</groupId>
			    <artifactId>build-helper-maven-plugin</artifactId>
			    <version>1.5</version>
			    <executions>
			        <execution>
			            <id>add-source1</id>
			            <phase>generate-sources</phase>
			            <goals>
			                <goal>add-source</goal>
			            </goals>
			            <configuration>
			                <sources>
			                    <source>generated-sources/xjc/</source>
			                </sources>
			            </configuration>
			        </execution>
			    </executions>
			</plugin>
 			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-dependency-plugin</artifactId>
				<version>2.8</version>
				<executions>
					<!-- Unpack header files and libraries for build -->
					<execution>
			            <id>copy-dependencies</id>
			            <phase>package</phase>
			            <goals>
			              <goal>copy-dependencies</goal>
			            </goals>
						<!-- use this to add a local list of dependencies -->
						<!--
						<configuration>
							<includeScope>runtime</includeScope>
							<excludeTransitive>false</excludeTransitive>
							<outputDirectory>${project.build.directory}/lib</outputDirectory>
						</configuration>
						-->
					</execution>
					<execution>
						<id>unpack-dependencies</id>
						<phase>compile</phase>
						<goals>
							<goal>unpack-dependencies</goal>
						</goals>
						<configuration>
							<includes>**/BundleRootImpl.class</includes>
							<outputDirectory>${project.build.directory}/classes</outputDirectory>
							<overWriteReleases>true</overWriteReleases>
							<overWriteSnapshots>true</overWriteSnapshots>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
	<profiles>
		<profile>
			<id>release</id>
			<build>
				<plugins>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-gpg-plugin</artifactId>
						<version>1.5</version>
						<executions>
							<execution>
								<id>sign-artifacts</id>
								<phase>verify</phase>
								<goals>
									<goal>sign</goal>
								</goals>
							</execution>
						</executions>
					</plugin>
					<plugin>
						<groupId>org.sonatype.plugins</groupId>
						<artifactId>nexus-staging-maven-plugin</artifactId>
						<version>1.6.3</version>
						<extensions>true</extensions>
						<configuration>
							<serverId>ossrh</serverId>
							<nexusUrl>https://oss.sonatype.org/</nexusUrl>
							<autoReleaseAfterClose>true</autoReleaseAfterClose>
						</configuration>
					</plugin>
				</plugins>
			</build>
		</profile>
	</profiles>
</project>


text:
#ifndef GRPCPP_SUPPORT_ERROR_DETAILS_H
#define GRPCPP_SUPPORT_ERROR_DETAILS_H

#include <grpcpp/support/error_details_impl.h>

namespace google {
namespace rpc {
class Status;
}  // namespace rpc
}  // namespace google

namespace grpc {

static inline Status ExtractErrorDetails(const Status& from,
                                         ::google::rpc::Status* to) {
  return ::grpc_impl::ExtractErrorDetails(from, to);
}

static inline Status SetErrorDetails(const ::google::rpc::Status& from,
                                     Status* to) {
  return ::grpc_impl::SetErrorDetails(from, to);
}

}  // namespace grpc

#endif  // GRPCPP_SUPPORT_ERROR_DETAILS_H

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.config.model;

import java.io.Serializable;

/**
 *

 * A logical container used for storing the configuration changes of an AWS
 * resource.
 *

 */
public class DeliveryChannel implements Serializable, Cloneable {

    /**
     *

     * The name of the delivery channel. By default, AWS Config automatically
     * assigns the name "default" when creating the delivery channel.
     * You cannot change the assigned name.
     *

     */
    private String name;
    /**
     *

     * The name of the Amazon S3 bucket used to store configuration history for
     * the delivery channel.
     *

     */
    private String s3BucketName;
    /**
     *

     * The prefix for the specified Amazon S3 bucket.
     *

     */
    private String s3KeyPrefix;
    /**
     *

     * The Amazon Resource Name (ARN) of the SNS topic that AWS Config delivers
     * notifications to.
     *

     */
    private String snsTopicARN;

    private ConfigSnapshotDeliveryProperties configSnapshotDeliveryProperties;

    /**
     *

     * The name of the delivery channel. By default, AWS Config automatically
     * assigns the name "default" when creating the delivery channel.
     * You cannot change the assigned name.
     *

     *
     * @param name
     *        The name of the delivery channel. By default, AWS Config
     *        automatically assigns the name "default" when creating
     *        the delivery channel. You cannot change the assigned name.
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     *

     * The name of the delivery channel. By default, AWS Config automatically
     * assigns the name "default" when creating the delivery channel.
     * You cannot change the assigned name.
     *

     *
     * @return The name of the delivery channel. By default, AWS Config
     *         automatically assigns the name "default" when creating
     *         the delivery channel. You cannot change the assigned name.
     */
    public String getName() {
        return this.name;
    }

    /**
     *

     * The name of the delivery channel. By default, AWS Config automatically
     * assigns the name "default" when creating the delivery channel.
     * You cannot change the assigned name.
     *

     *
     * @param name
     *        The name of the delivery channel. By default, AWS Config
     *        automatically assigns the name "default" when creating
     *        the delivery channel. You cannot change the assigned name.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public DeliveryChannel withName(String name) {
        setName(name);
        return this;
    }

    /**
     *

     * The name of the Amazon S3 bucket used to store configuration history for
     * the delivery channel.
     *

     *
     * @param s3BucketName
     *        The name of the Amazon S3 bucket used to store configuration
     *        history for the delivery channel.
     */
    public void setS3BucketName(String s3BucketName) {
        this.s3BucketName = s3BucketName;
    }

    /**
     *

     * The name of the Amazon S3 bucket used to store configuration history for
     * the delivery channel.
     *

     *
     * @return The name of the Amazon S3 bucket used to store configuration
     *         history for the delivery channel.
     */
    public String getS3BucketName() {
        return this.s3BucketName;
    }

    /**
     *

     * The name of the Amazon S3 bucket used to store configuration history for
     * the delivery channel.
     *

     *
     * @param s3BucketName
     *        The name of the Amazon S3 bucket used to store configuration
     *        history for the delivery channel.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public DeliveryChannel withS3BucketName(String s3BucketName) {
        setS3BucketName(s3BucketName);
        return this;
    }

    /**
     *

     * The prefix for the specified Amazon S3 bucket.
     *

     *
     * @param s3KeyPrefix
     *        The prefix for the specified Amazon S3 bucket.
     */
    public void setS3KeyPrefix(String s3KeyPrefix) {
        this.s3KeyPrefix = s3KeyPrefix;
    }

    /**
     *

     * The prefix for the specified Amazon S3 bucket.
     *

     *
     * @return The prefix for the specified Amazon S3 bucket.
     */
    public String getS3KeyPrefix() {
        return this.s3KeyPrefix;
    }

    /**
     *

     * The prefix for the specified Amazon S3 bucket.
     *

     *
     * @param s3KeyPrefix
     *        The prefix for the specified Amazon S3 bucket.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public DeliveryChannel withS3KeyPrefix(String s3KeyPrefix) {
        setS3KeyPrefix(s3KeyPrefix);
        return this;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the SNS topic that AWS Config delivers
     * notifications to.
     *

     *
     * @param snsTopicARN
     *        The Amazon Resource Name (ARN) of the SNS topic that AWS Config
     *        delivers notifications to.
     */
    public void setSnsTopicARN(String snsTopicARN) {
        this.snsTopicARN = snsTopicARN;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the SNS topic that AWS Config delivers
     * notifications to.
     *

     *
     * @return The Amazon Resource Name (ARN) of the SNS topic that AWS Config
     *         delivers notifications to.
     */
    public String getSnsTopicARN() {
        return this.snsTopicARN;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the SNS topic that AWS Config delivers
     * notifications to.
     *

     *
     * @param snsTopicARN
     *        The Amazon Resource Name (ARN) of the SNS topic that AWS Config
     *        delivers notifications to.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public DeliveryChannel withSnsTopicARN(String snsTopicARN) {
        setSnsTopicARN(snsTopicARN);
        return this;
    }

    /**
     * @param configSnapshotDeliveryProperties
     */
    public void setConfigSnapshotDeliveryProperties(
            ConfigSnapshotDeliveryProperties configSnapshotDeliveryProperties) {
        this.configSnapshotDeliveryProperties = configSnapshotDeliveryProperties;
    }

    /**
     * @return
     */
    public ConfigSnapshotDeliveryProperties getConfigSnapshotDeliveryProperties() {
        return this.configSnapshotDeliveryProperties;
    }

    /**
     * @param configSnapshotDeliveryProperties
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public DeliveryChannel withConfigSnapshotDeliveryProperties(
            ConfigSnapshotDeliveryProperties configSnapshotDeliveryProperties) {
        setConfigSnapshotDeliveryProperties(configSnapshotDeliveryProperties);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getName() != null)
            sb.append("Name: " + getName() + ",");
        if (getS3BucketName() != null)
            sb.append("S3BucketName: " + getS3BucketName() + ",");
        if (getS3KeyPrefix() != null)
            sb.append("S3KeyPrefix: " + getS3KeyPrefix() + ",");
        if (getSnsTopicARN() != null)
            sb.append("SnsTopicARN: " + getSnsTopicARN() + ",");
        if (getConfigSnapshotDeliveryProperties() != null)
            sb.append("ConfigSnapshotDeliveryProperties: "
                    + getConfigSnapshotDeliveryProperties());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DeliveryChannel == false)
            return false;
        DeliveryChannel other = (DeliveryChannel) obj;
        if (other.getName() == null ^ this.getName() == null)
            return false;
        if (other.getName() != null
                && other.getName().equals(this.getName()) == false)
            return false;
        if (other.getS3BucketName() == null ^ this.getS3BucketName() == null)
            return false;
        if (other.getS3BucketName() != null
                && other.getS3BucketName().equals(this.getS3BucketName()) == false)
            return false;
        if (other.getS3KeyPrefix() == null ^ this.getS3KeyPrefix() == null)
            return false;
        if (other.getS3KeyPrefix() != null
                && other.getS3KeyPrefix().equals(this.getS3KeyPrefix()) == false)
            return false;
        if (other.getSnsTopicARN() == null ^ this.getSnsTopicARN() == null)
            return false;
        if (other.getSnsTopicARN() != null
                && other.getSnsTopicARN().equals(this.getSnsTopicARN()) == false)
            return false;
        if (other.getConfigSnapshotDeliveryProperties() == null
                ^ this.getConfigSnapshotDeliveryProperties() == null)
            return false;
        if (other.getConfigSnapshotDeliveryProperties() != null
                && other.getConfigSnapshotDeliveryProperties().equals(
                        this.getConfigSnapshotDeliveryProperties()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode
                + ((getName() == null) ? 0 : getName().hashCode());
        hashCode = prime
                * hashCode
                + ((getS3BucketName() == null) ? 0 : getS3BucketName()
                        .hashCode());
        hashCode = prime
                * hashCode
                + ((getS3KeyPrefix() == null) ? 0 : getS3KeyPrefix().hashCode());
        hashCode = prime
                * hashCode
                + ((getSnsTopicARN() == null) ? 0 : getSnsTopicARN().hashCode());
        hashCode = prime
                * hashCode
                + ((getConfigSnapshotDeliveryProperties() == null) ? 0
                        : getConfigSnapshotDeliveryProperties().hashCode());
        return hashCode;
    }

    @Override
    public DeliveryChannel clone() {
        try {
            return (DeliveryChannel) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                            + "even though we're Cloneable!", e);
        }
    }
}


text:
/*
 * Created on Nov 16, 2006
 * @author
 *
 */
package edu.common.dynamicextensions.processor;

import edu.common.dynamicextensions.domain.DomainObjectFactory;
import edu.common.dynamicextensions.domaininterface.EntityGroupInterface;
import edu.common.dynamicextensions.entitymanager.EntityManager;
import edu.common.dynamicextensions.entitymanager.EntityManagerInterface;
import edu.common.dynamicextensions.exception.DynamicExtensionsApplicationException;
import edu.common.dynamicextensions.exception.DynamicExtensionsSystemException;
import edu.common.dynamicextensions.ui.interfaces.GroupUIBeanInterface;
import edu.common.dynamicextensions.util.DynamicExtensionsUtility;

/**
 * @author preeti_munot
 *
 * To change the template for this generated type comment go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
public class GroupProcessor extends BaseDynamicExtensionsProcessor
{
	/**
	 *
	 *
	 */
	private GroupProcessor()
	{

	}
	/**
	 *
	 * @return new instance of GroupProcessor
	 */
	public static GroupProcessor getInstance()
	{
		return new GroupProcessor();
	}
	/**
	 *
	 * @return new object of entity group
	 */
	public EntityGroupInterface createEntityGroup()
	{
		return DomainObjectFactory.getInstance().createEntityGroup();
	}
	/**
	 *
	 * @param entityGroup : Entity Group object to be populated
	 * @param groupUIBean : Group UI Bean containing information entered by the user
	 * @throws DynamicExtensionsSystemException
	 * @throws DynamicExtensionsApplicationException
	 */
	public void populateEntityGroupDetails(EntityGroupInterface entityGroup,GroupUIBeanInterface groupUIBean) throws DynamicExtensionsApplicationException, DynamicExtensionsSystemException
	{
		if((entityGroup!=null)&&(groupUIBean!=null))
		{
			entityGroup.setName(groupUIBean.getGroupNameText());
			entityGroup.setDescription(groupUIBean.getGroupDescription());
			entityGroup.setIsSystemGenerated(new Boolean(false));
			EntityManager.getInstance().checkForDuplicateEntityGroupName(entityGroup);
		}
	}
	/**
	 *
	 * @param groupUIBean : Group UI Bean object to be populated
	 * @param entityGroup : Entity Group object containing group details
	 */
	public void populategroupUIBeanDetails(GroupUIBeanInterface groupUIBean,EntityGroupInterface entityGroup)
	{
		if((entityGroup!=null)&&(groupUIBean!=null))
		{
			groupUIBean.setGroupNameText(entityGroup.getName());
			groupUIBean.setGroupDescription(entityGroup.getDescription());
		}
	}
	/**
	 * Create entity group object, populate its details and save to DB
	 * @param groupUIBean  : Bean containing group information added by user on UI
	 * @return
	 * @throws DynamicExtensionsApplicationException
	 * @throws DynamicExtensionsSystemException
	 */
	public EntityGroupInterface createAndSaveGroup(GroupUIBeanInterface groupUIBean) throws DynamicExtensionsSystemException, DynamicExtensionsApplicationException
	{
		EntityGroupInterface entityGroup = createEntityGroup();
		populateEntityGroupDetails(entityGroup, groupUIBean);
		entityGroup = saveEntityGroup(entityGroup);
		return entityGroup;
	}
	/**
	 *
	 * @param entityGroup Entity group to be saved to the DB
	 * @return
	 * @throws DynamicExtensionsApplicationException
	 * @throws DynamicExtensionsSystemException
	 */
	public EntityGroupInterface saveEntityGroup(EntityGroupInterface entityGroupInterface) throws DynamicExtensionsSystemException, DynamicExtensionsApplicationException
	{
		EntityManagerInterface entityManagerInterface = EntityManager.getInstance();
		EntityGroupInterface savedEntityGroupInterface = entityManagerInterface.persistEntityGroup(entityGroupInterface);
		return savedEntityGroupInterface;

	}
	/**
	 *
	 * @param groupName Name of the group
	 * @return EntityGroup with given name
	 * @throws DynamicExtensionsApplicationException
	 * @throws DynamicExtensionsSystemException
	 */
	public EntityGroupInterface getEntityGroupByIdentifier(String entityGroupIdentifier) throws DynamicExtensionsSystemException, DynamicExtensionsApplicationException
	{
		return DynamicExtensionsUtility.getEntityGroupByIdentifier(entityGroupIdentifier);

	}
}


text:
package armpolicyinsights

import (
	"context"
	"errors"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
	armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
	"net/http"
	"net/url"
	"strings"
)

// PolicyRestrictionsClient contains the methods for the PolicyRestrictions group.
// Don't use this type directly, use NewPolicyRestrictionsClient() instead.
type PolicyRestrictionsClient struct {
	host           string
	subscriptionID string
	pl             runtime.Pipeline
}

// NewPolicyRestrictionsClient creates a new instance of PolicyRestrictionsClient with the specified values.
// subscriptionID - Microsoft Azure subscription ID.
// credential - used to authorize requests. Usually a credential from azidentity.
// options - pass nil to accept the default values.
func NewPolicyRestrictionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*PolicyRestrictionsClient, error) {
	if options == nil {
		options = &arm.ClientOptions{}
	}
	ep := cloud.AzurePublic.Services[cloud.ResourceManager].Endpoint
	if c, ok := options.Cloud.Services[cloud.ResourceManager]; ok {
		ep = c.Endpoint
	}
	pl, err := armruntime.NewPipeline(moduleName, moduleVersion, credential, runtime.PipelineOptions{}, options)
	if err != nil {
		return nil, err
	}
	client := &PolicyRestrictionsClient{
		subscriptionID: subscriptionID,
		host:           ep,
		pl:             pl,
	}
	return client, nil
}

// CheckAtManagementGroupScope - Checks what restrictions Azure Policy will place on resources within a management group.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-03-01
// managementGroupID - Management group ID.
// parameters - The check policy restrictions parameters.
// options - PolicyRestrictionsClientCheckAtManagementGroupScopeOptions contains the optional parameters for the PolicyRestrictionsClient.CheckAtManagementGroupScope
// method.
func (client *PolicyRestrictionsClient) CheckAtManagementGroupScope(ctx context.Context, managementGroupID string, parameters CheckManagementGroupRestrictionsRequest, options *PolicyRestrictionsClientCheckAtManagementGroupScopeOptions) (PolicyRestrictionsClientCheckAtManagementGroupScopeResponse, error) {
	req, err := client.checkAtManagementGroupScopeCreateRequest(ctx, managementGroupID, parameters, options)
	if err != nil {
		return PolicyRestrictionsClientCheckAtManagementGroupScopeResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return PolicyRestrictionsClientCheckAtManagementGroupScopeResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return PolicyRestrictionsClientCheckAtManagementGroupScopeResponse{}, runtime.NewResponseError(resp)
	}
	return client.checkAtManagementGroupScopeHandleResponse(resp)
}

// checkAtManagementGroupScopeCreateRequest creates the CheckAtManagementGroupScope request.
func (client *PolicyRestrictionsClient) checkAtManagementGroupScopeCreateRequest(ctx context.Context, managementGroupID string, parameters CheckManagementGroupRestrictionsRequest, options *PolicyRestrictionsClientCheckAtManagementGroupScopeOptions) (*policy.Request, error) {
	urlPath := "/providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/checkPolicyRestrictions"
	urlPath = strings.ReplaceAll(urlPath, "{managementGroupsNamespace}", url.PathEscape("Microsoft.Management"))
	if managementGroupID == "" {
		return nil, errors.New("parameter managementGroupID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{managementGroupId}", url.PathEscape(managementGroupID))
	req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-03-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, runtime.MarshalAsJSON(req, parameters)
}

// checkAtManagementGroupScopeHandleResponse handles the CheckAtManagementGroupScope response.
func (client *PolicyRestrictionsClient) checkAtManagementGroupScopeHandleResponse(resp *http.Response) (PolicyRestrictionsClientCheckAtManagementGroupScopeResponse, error) {
	result := PolicyRestrictionsClientCheckAtManagementGroupScopeResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.CheckRestrictionsResult); err != nil {
		return PolicyRestrictionsClientCheckAtManagementGroupScopeResponse{}, err
	}
	return result, nil
}

// CheckAtResourceGroupScope - Checks what restrictions Azure Policy will place on a resource within a resource group. Use
// this when the resource group the resource will be created in is already known.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-03-01
// resourceGroupName - The name of the resource group. The name is case insensitive.
// parameters - The check policy restrictions parameters.
// options - PolicyRestrictionsClientCheckAtResourceGroupScopeOptions contains the optional parameters for the PolicyRestrictionsClient.CheckAtResourceGroupScope
// method.
func (client *PolicyRestrictionsClient) CheckAtResourceGroupScope(ctx context.Context, resourceGroupName string, parameters CheckRestrictionsRequest, options *PolicyRestrictionsClientCheckAtResourceGroupScopeOptions) (PolicyRestrictionsClientCheckAtResourceGroupScopeResponse, error) {
	req, err := client.checkAtResourceGroupScopeCreateRequest(ctx, resourceGroupName, parameters, options)
	if err != nil {
		return PolicyRestrictionsClientCheckAtResourceGroupScopeResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return PolicyRestrictionsClientCheckAtResourceGroupScopeResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return PolicyRestrictionsClientCheckAtResourceGroupScopeResponse{}, runtime.NewResponseError(resp)
	}
	return client.checkAtResourceGroupScopeHandleResponse(resp)
}

// checkAtResourceGroupScopeCreateRequest creates the CheckAtResourceGroupScope request.
func (client *PolicyRestrictionsClient) checkAtResourceGroupScopeCreateRequest(ctx context.Context, resourceGroupName string, parameters CheckRestrictionsRequest, options *PolicyRestrictionsClientCheckAtResourceGroupScopeOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/checkPolicyRestrictions"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-03-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, runtime.MarshalAsJSON(req, parameters)
}

// checkAtResourceGroupScopeHandleResponse handles the CheckAtResourceGroupScope response.
func (client *PolicyRestrictionsClient) checkAtResourceGroupScopeHandleResponse(resp *http.Response) (PolicyRestrictionsClientCheckAtResourceGroupScopeResponse, error) {
	result := PolicyRestrictionsClientCheckAtResourceGroupScopeResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.CheckRestrictionsResult); err != nil {
		return PolicyRestrictionsClientCheckAtResourceGroupScopeResponse{}, err
	}
	return result, nil
}

// CheckAtSubscriptionScope - Checks what restrictions Azure Policy will place on a resource within a subscription.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-03-01
// parameters - The check policy restrictions parameters.
// options - PolicyRestrictionsClientCheckAtSubscriptionScopeOptions contains the optional parameters for the PolicyRestrictionsClient.CheckAtSubscriptionScope
// method.
func (client *PolicyRestrictionsClient) CheckAtSubscriptionScope(ctx context.Context, parameters CheckRestrictionsRequest, options *PolicyRestrictionsClientCheckAtSubscriptionScopeOptions) (PolicyRestrictionsClientCheckAtSubscriptionScopeResponse, error) {
	req, err := client.checkAtSubscriptionScopeCreateRequest(ctx, parameters, options)
	if err != nil {
		return PolicyRestrictionsClientCheckAtSubscriptionScopeResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return PolicyRestrictionsClientCheckAtSubscriptionScopeResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return PolicyRestrictionsClientCheckAtSubscriptionScopeResponse{}, runtime.NewResponseError(resp)
	}
	return client.checkAtSubscriptionScopeHandleResponse(resp)
}

// checkAtSubscriptionScopeCreateRequest creates the CheckAtSubscriptionScope request.
func (client *PolicyRestrictionsClient) checkAtSubscriptionScopeCreateRequest(ctx context.Context, parameters CheckRestrictionsRequest, options *PolicyRestrictionsClientCheckAtSubscriptionScopeOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/checkPolicyRestrictions"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-03-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, runtime.MarshalAsJSON(req, parameters)
}

// checkAtSubscriptionScopeHandleResponse handles the CheckAtSubscriptionScope response.
func (client *PolicyRestrictionsClient) checkAtSubscriptionScopeHandleResponse(resp *http.Response) (PolicyRestrictionsClientCheckAtSubscriptionScopeResponse, error) {
	result := PolicyRestrictionsClientCheckAtSubscriptionScopeResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.CheckRestrictionsResult); err != nil {
		return PolicyRestrictionsClientCheckAtSubscriptionScopeResponse{}, err
	}
	return result, nil
}


text:
from xmlrpc.client import ServerProxy as RpcServer
from xmlrpc.client import ProtocolError
from http.client import RemoteDisconnected
import re

class Monitor(object):
    _server = None
    def __init__(self, url, username, password):
        self.url = getUrl(url, username, password)
        print(self.url)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(exc_type, exc_val, exc_tb)
        if exc_type is None:
            return
        if issubclass(exc_type, (ProtocolError,)):
            raise PermissionError
        if issubclass(exc_type, (RemoteDisconnected,)):
            raise ConnectionRefusedError

    def reload(self):
        with self:
            return self.getRpcServer().supervisor.reloadConfig()

    def getRpcServer(self):
        if self._server is None:
            self._server = RpcServer(self.url)
        return self._server

    def shutdown(self):
        self.getRpcServer().supervisor.shutdown()

    def reboot(self):
        self.getRpcServer().supervisor.restart()

    def getIdentification(self):
        with self:
            return self.getRpcServer().supervisor.getIdentification()

    def getStatus(self):
        try:
            return self.getRpcServer().supervisor.getState()['statecode']
        except:
            return -100

    def getPid(self):
        try:
            return self.getRpcServer().supervisor.getPid()
        except:
            return 0

    def getProcessStatus(self, name):
            return self.getRpcServer().supervisor.getProcessInfo(name)

    def getServiceIter(self):
        try:
            with self:
                for service in self.getRpcServer().supervisor.getAllProcessInfo():
                    print(service)
                    res = {
                        'name': service['name'],
                        'group': service['group'],
                        'pid': service['pid'],
                        'state': service['state'],
                        'now': service['now'],
                        'start': service['start'],
                        'stop': service['stop'],
                        'exit_status': service['exitstatus']
                    }
                    yield res
        except PermissionError:
            pass

    def start(self, name=None, wait=True):
        if name is None:
            self.getRpcServer().supervisor.startAllProcesses()
        self.getRpcServer().supervisor.startProcess(name)

    def stop(self, name=None, wait=True):
        if name is None:
            self.getRpcServer().supervisor.stopAllProcesses()
        self.getRpcServer().supervisor.stopProcess(name)

    def restart(self, name=None):
        if name is None:
            self.stop()
            self.start()
        self.stop(name)
        self.start(name)

    def sendChars(self, name, chars):
        self.getRpcServer().supervisor.sendProcessStdin(name, chars)

def getUrl(url, username=None, password=None):
    if username:
        url_freg_res = re.match(r'(?:(?P<proto>http|https)://)?'
                                r'(?:'
                                r'(?P<username>[^\:@]*)'
                                r'(?:\:(?P<password>[^@]*))?'
                                r'@)?(?P<domain>[^/@]+)(?P<path>/.*)?', url, flags=re.I)
        if url_freg_res:
            url_freg = url_freg_res.groupdict(default='')
            url_freg['username'] = username
            url_freg['password'] = password
            url_freg['proto'] = url_freg['proto'] or 'https'
            uri = "{proto}://{username}:{password}@{domain}{path}".format(
                **url_freg
            )
        else:
            raise SyntaxError(url)
    else:
        uri = url
    return uri

def getIdentification(url, username=None, password=None):
    with RpcServer(getUrl(url, username, password)) as client:
        identification = client.supervisor.getIdentification()
    return identification


text:
<?xml version="1.0" encoding="utf-8"?>
<HelpKI>
  <HelpKINode Title="Caption property" Url="html/1592066175.htm" />
  <HelpKINode Title="CaptionProperty field" Url="html/1302735821.htm" />
  <HelpKINode Title="ExGrip.AppBarControls namespace" Url="html/1459347224.htm" />
  <HelpKINode Title="ExGrip.AppBarControls.LeftAreaClicked delegate" Url="html/1639516178.htm" />
  <HelpKINode Title="ExGrip.AppBarControls.SplitButton class">
    <HelpKINode Title="SplitButton Class" Url="html/1379765127.htm" />
    <HelpKINode Title="SplitButton Members" Url="html/557206311.htm" />
  </HelpKINode>
  <HelpKINode Title="ExGrip.AppBarControls.ToggleAreaClicked delegate" Url="html/835877569.htm" />
  <HelpKINode Title="LeftAreaBackground property" Url="html/1293613885.htm" />
  <HelpKINode Title="LeftAreaBackgroundProperty field" Url="html/1689959138.htm" />
  <HelpKINode Title="LeftAreaButtonClicked event" Url="html/211292293.htm" />
  <HelpKINode Title="LeftAreaClicked delegate" Url="html/1639516178.htm" />
  <HelpKINode Title="LeftAreaMouseDownCommand property" Url="html/928835731.htm" />
  <HelpKINode Title="LeftAreaMouseDownCommandParameter property" Url="html/737973295.htm" />
  <HelpKINode Title="LeftAreaMouseDownCommandParameterProperty field" Url="html/650537963.htm" />
  <HelpKINode Title="LeftAreaMouseDownCommandProperty field" Url="html/724323698.htm" />
  <HelpKINode Title="RightAreaBackground property" Url="html/1808113426.htm" />
  <HelpKINode Title="RightAreaBackgroundProperty field" Url="html/1750246449.htm" />
  <HelpKINode Title="RightToggle property" Url="html/1620134041.htm" />
  <HelpKINode Title="RightToggleProperty field" Url="html/138143378.htm" />
  <HelpKINode Title="SplitButton class">
    <HelpKINode Title="SplitButton Class" Url="html/1379765127.htm" />
    <HelpKINode Title="SplitButton Members" Url="html/557206311.htm" />
    <HelpKINode Title="about SplitButton class" Url="html/1379765127.htm" />
    <HelpKINode Title="all members" Url="html/557206311.htm" />
    <HelpKINode Title="constructor" Url="html/847159561.htm" />
    <HelpKINode Title="events" Url="html/2076350526.htm" />
    <HelpKINode Title="fields" Url="html/1494403701.htm" />
    <HelpKINode Title="methods" Url="html/1504796115.htm" />
    <HelpKINode Title="properties" Url="html/1104862529.htm" />
  </HelpKINode>
  <HelpKINode Title="SplitButton.Caption property" Url="html/1592066175.htm" />
  <HelpKINode Title="SplitButton.CaptionProperty field" Url="html/1302735821.htm" />
  <HelpKINode Title="SplitButton.LeftAreaBackground property" Url="html/1293613885.htm" />
  <HelpKINode Title="SplitButton.LeftAreaBackgroundProperty field" Url="html/1689959138.htm" />
  <HelpKINode Title="SplitButton.LeftAreaButtonClicked event" Url="html/211292293.htm" />
  <HelpKINode Title="SplitButton.LeftAreaMouseDownCommand property" Url="html/928835731.htm" />
  <HelpKINode Title="SplitButton.LeftAreaMouseDownCommandParameter property" Url="html/737973295.htm" />
  <HelpKINode Title="SplitButton.LeftAreaMouseDownCommandParameterProperty field" Url="html/650537963.htm" />
  <HelpKINode Title="SplitButton.LeftAreaMouseDownCommandProperty field" Url="html/724323698.htm" />
  <HelpKINode Title="SplitButton.RightAreaBackground property" Url="html/1808113426.htm" />
  <HelpKINode Title="SplitButton.RightAreaBackgroundProperty field" Url="html/1750246449.htm" />
  <HelpKINode Title="SplitButton.RightToggle property" Url="html/1620134041.htm" />
  <HelpKINode Title="SplitButton.RightToggleProperty field" Url="html/138143378.htm" />
  <HelpKINode Title="SplitButton.SplitButton constructor" Url="html/847159561.htm" />
  <HelpKINode Title="SplitButton.ThumbFill property" Url="html/1269626752.htm" />
  <HelpKINode Title="SplitButton.ThumbFillProperty field" Url="html/192944959.htm" />
  <HelpKINode Title="SplitButton.ToggleAreaButtonClicked event" Url="html/755581088.htm" />
  <HelpKINode Title="SplitButton.ToggleAreaVisibility property" Url="html/1254187772.htm" />
  <HelpKINode Title="SplitButton.ToggleAreaVisibilityProperty field" Url="html/905649168.htm" />
  <HelpKINode Title="SplitButton.ToggleButtonClickedCommand property" Url="html/1950417740.htm" />
  <HelpKINode Title="SplitButton.ToggleButtonClickedCommandParameter property" Url="html/1282909984.htm" />
  <HelpKINode Title="SplitButton.ToggleButtonClickedCommandParameterProperty field" Url="html/636836907.htm" />
  <HelpKINode Title="SplitButton.ToggleButtonClickedCommandProperty field" Url="html/332514910.htm" />
  <HelpKINode Title="SplitButton.ToggleOnParentFocusChange property" Url="html/943674149.htm" />
  <HelpKINode Title="SplitButton.ToggleOnParentFocusChangeProperty field" Url="html/1466639590.htm" />
  <HelpKINode Title="SplitButton.TopImage property" Url="html/122606067.htm" />
  <HelpKINode Title="SplitButton.TopImageProperty field" Url="html/536035068.htm" />
  <HelpKINode Title="ThumbFill property" Url="html/1269626752.htm" />
  <HelpKINode Title="ThumbFillProperty field" Url="html/192944959.htm" />
  <HelpKINode Title="ToggleAreaButtonClicked event" Url="html/755581088.htm" />
  <HelpKINode Title="ToggleAreaClicked delegate" Url="html/835877569.htm" />
  <HelpKINode Title="ToggleAreaVisibility property" Url="html/1254187772.htm" />
  <HelpKINode Title="ToggleAreaVisibilityProperty field" Url="html/905649168.htm" />
  <HelpKINode Title="ToggleButtonClickedCommand property" Url="html/1950417740.htm" />
  <HelpKINode Title="ToggleButtonClickedCommandParameter property" Url="html/1282909984.htm" />
  <HelpKINode Title="ToggleButtonClickedCommandParameterProperty field" Url="html/636836907.htm" />
  <HelpKINode Title="ToggleButtonClickedCommandProperty field" Url="html/332514910.htm" />
  <HelpKINode Title="ToggleOnParentFocusChange property" Url="html/943674149.htm" />
  <HelpKINode Title="ToggleOnParentFocusChangeProperty field" Url="html/1466639590.htm" />
  <HelpKINode Title="TopImage property" Url="html/122606067.htm" />
  <HelpKINode Title="TopImageProperty field" Url="html/536035068.htm" />
</HelpKI>


text:
require 'spec_helper'

module ReplayApi
  describe EventProperties do
    subject(:properties) { EventProperties.new }

    describe '#event_category' do
      specify { expect(properties.event_category).to eq 'general' }
    end

    describe '#past_event' do
      specify { expect(properties.past_event).to eq 0 }
    end
  end
end


text:
package com.tobedevoured.modelcitizen.field;

import com.tobedevoured.modelcitizen.callback.internal.Getable;

/**
 * Callback for a Field when the Model is created
 * @deprecated for FieldCallback
 * @author Michael Guymon
 */
@Deprecated
public abstract class FieldCallback implements Getable {

	/**
	 * Get the Field value
	 *
	 * @param referenceModel Object
	 * @return instance of Field class
	 */
	public abstract Object get( Object referenceModel );
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:jcr="http://www.jcp.org/jcr/1.0" xmlns:nt="http://www.jcp.org/jcr/nt/1.0"
    jcr:primaryType="nt:unstructured"
    jcr:title="Automatic Package Replication"
    jcr:description="Tooling to automatically replicate AEM packages."
    icon="archive"
    href="/miscadmin#/etc/acs-commons/automatic-package-replication"
    id="acs-commons__automatic-package-replication"
    target="_blank"/>


text:
class ConcreteTool
		: public ToolBase
{
	Q_OBJECT

public:
	ConcreteTool(int& argc, char *argv[])
		: ToolBase(argc, argv)
	{
	}

    // online calculator for HEXPLORER & HBOND scores: https://www2.hhu.de/rna/html/hexplorer_score.php
    // paper: https://academic.oup.com/nar/article/42/16/10681/2903056?login=true

	virtual void setup()
	{
        setDescription("Annotates a VCF with Hexplorer and HBond scores.");
        addOutfile("out", "Output VCF file containing HEXplorer and HBOND scores in the INFO column.", false);
		//optional
        addInfile("in", "Input VCF file. If unset, reads from STDIN.", true);
        addInfile("ref", "Reference genome FASTA file. If unset 'reference_genome' from the 'settings.ini' file is used.", true);

	}

    float calculateHZEIforSequence(const QString& sequence)
    {
        float hzei_sum = 0;

        // iterate over all undecamers
        for (int i = 5; i < sequence.length()-5; i++)
        {
            QString current_11nt = sequence.mid(i-5, 11);
            float current_hzei = calculateHZEIperNT(current_11nt);
            //qDebug() << current_11nt;
            //qDebug() << current_hzei;
            hzei_sum += current_hzei;
        }

        // normalize the total HZEI score by the number of nucleotides where the HZEI score was calculated
        float result = hzei_sum / (sequence.length()-10);

        return result;
    }

    // this function calculates the hexplorer score for one nucleotide
    // thus, the sequence which is input to this function should only be 11 bases long
    float calculateHZEIperNT(const QString& sequence)
    {
        // sequence is assumed to be valid at this point!

        float zscore_sum = 0;

        for (int i = 0; i < 6; i++)
        {
            QString current_hexamer = sequence.mid(i, 6);
            zscore_sum += hexplorer_zscores_.value(current_hexamer, 0);
            //qDebug() << current_hexamer;
            //qDebug() << hexplorer_zscores_.value(current_hexamer, 0);
        }

        float result = zscore_sum/6; // take the mean of all 6 hexamer z scores

        return result;
    }

    float getMaxHBondScores(const QString& sequence)
    {
        QRegularExpression rx(".{3}GT.{6}");

        float result = 0;

        QRegularExpressionMatchIterator i = rx.globalMatch(sequence);
        while (i.hasNext())
        {
            QRegularExpressionMatch match = i.next();
            if (match.hasMatch())
            {
                 QString curent_sequence = match.captured(0);
                 float current_hbond_score = hbond_scores_.value(curent_sequence, 0);
                 result = std::max(current_hbond_score, result);
            }
        }
        return result;
    }

    virtual void main()
    {
        // read in input vcf
        QString in_file = getInfile("in");
        QSharedPointer<QFile> reader = Helper::openFileForReading(in_file, true);

        // open output file
        QString out_file = getOutfile("out");
        QSharedPointer<QFile> writer = Helper::openFileForWriting(out_file, false);

        // read in reference genome
        QString ref_file = getInfile("ref");
        if (ref_file=="") ref_file = Settings::string("reference_genome", true);
        if (ref_file=="") THROW(CommandLineParsingException, "Reference genome FASTA unset in both command-line and settings.ini file!");
        //FastaFileIndex ref_index(ref_file);
        FastaFileIndex reference(ref_file);

        // parse hexplorer z scores table
        QStringList lines = Helper::loadTextFile(":/resources/HEXplorer_Z_scores.csv", true, '#', true);
        foreach(const QString& line, lines)
        {
            QByteArrayList parts = line.toUtf8().split(';');
            if (parts.count()==2)
            {
                QString hexamer = parts[0];
                float zscore = parts[1].toFloat();
                hexplorer_zscores_.insert(hexamer, zscore);
            }
        }

        // parse H-Bond scores table
        lines = Helper::loadTextFile(":/resources/H_Bond_score_table.csv", true, '#', true);
        foreach(const QString& line, lines)
        {
            QByteArrayList parts = line.toUtf8().split(';');
            if (parts.count()==2)
            {
                QString undecamer = parts[0];
                float score = parts[1].toFloat();
                hbond_scores_.insert(undecamer, score);
            }
        }

        bool new_info_head_added = false;
        bool add_hexplorer = true;
        bool add_hbond_score = true;

        while(!reader->atEnd())
        {
            QByteArray line = reader->readLine();

            //skip empty lines
            if(line.trimmed().isEmpty()) continue;

            //write out headers unchanged
            if(line.startsWith("##"))
            {
                writer->write(line);
                if (add_hexplorer && line.contains("hexplorer"))
                {
                    qWarning() << "WARNING: found hexplorer info header. Will skip calculation of hexplorer scores";
                    add_hexplorer = false;
                }
                if (add_hbond_score && line.contains("max_hbond"))
                {
                    qWarning() << "WARNING: found hbond score info header. Will skip calculation of hbond scores";
                    add_hbond_score = false;
                }
                continue;
            }

            //add the new info headers after all other header lines
            if(!new_info_head_added)
            {
                if (add_hexplorer)
                {
                    writer->write("##INFO=<ID=hexplorer_delta,Number=1,Type=Float,Description=\"This is the HEXplorer delta score (HZEI mutant - HZEI wildtype). HZEI scores were normalized by the total number of nucleotide positions which contribute to the score.\">\n");
                    writer->write("##INFO=<ID=hexplorer_mut,Number=1,Type=Float,Description=\"This is the HEXplorer score for the mutant sequence. HZEI scores were normalized by the total number of nucleotide positions which contribute to the score.\">\n");
                    writer->write("##INFO=<ID=hexplorer_wt,Number=1,Type=Float,Description=\"This is the HEXplorer score for the reference sequence. HZEI scores were normalized by the total number of nucleotide positions which contribute to the score.\">\n");
                    writer->write("##INFO=<ID=hexplorer_delta_rev,Number=1,Type=Float,Description=\"This is the HEXplorer delta score for the reverse complement of the original sequence (HZEI mutant rev - HZEI wildtype rev). HZEI scores were normalized by the total number of nucleotide positions which contribute to the score.\">\n");
                    writer->write("##INFO=<ID=hexplorer_mut_rev,Number=1,Type=Float,Description=\"This is the HEXplorer score for the reverse complement of the mutant sequence. HZEI scores were normalized by the total number of nucleotide positions which contribute to the score.\">\n");
                    writer->write("##INFO=<ID=hexplorer_wt_rev,Number=1,Type=Float,Description=\"This is the HEXplorer score for the reverse complement of the reference sequence. HZEI scores were normalized by the total number of nucleotide positions which contribute to the score.\">\n");
                }

                if (add_hbond_score)
                {
                    writer->write("##INFO=<ID=max_hbond_delta,Number=1,Type=Float,Description=\"This is the HBond delta score (max HBond mutant - max HBond wildtype).\">\n");
                    writer->write("##INFO=<ID=max_hbond_mut,Number=1,Type=Float,Description=\"This is the max HBond score for the mutant sequence.\">\n");
                    writer->write("##INFO=<ID=max_hbond_wt,Number=1,Type=Float,Description=\"This is the max HBond score for the reference sequence.\">\n");
                    writer->write("##INFO=<ID=max_hbond_delta_rev,Number=1,Type=Float,Description=\"This is the max HBond delta score for the reverse complement of the original sequence (HZEI mutant rev - HZEI wildtype rev).\">\n");
                    writer->write("##INFO=<ID=max_hbond_mut_rev,Number=1,Type=Float,Description=\"This is the max HBond score for the reverse complement of the mutant sequence.\">\n");
                    writer->write("##INFO=<ID=max_hbond_wt_rev,Number=1,Type=Float,Description=\"This is the max HBond score for the reverse complement of the reference sequence.\">\n");
                }

                new_info_head_added = true;
            }

            // write column header line
            if(line.startsWith("#"))
            {
                writer->write(line);
                continue;
            }

            line = line.trimmed();

            //split line and extract variant infos
            QList<QByteArray> parts = line.split('\t');
            if(parts.count() < 8) THROW(FileParseException, "VCF with too few columns: " + line);

            Chromosome chr = parts[0];
            int start = atoi(parts[1]);
            Sequence ref = parts[3].toUpper();
            Sequence alt = parts[4].toUpper();
            QByteArray info = parts[7];

            //write out multi-allelic and structural variants without annotation
            if(alt.contains(',') || alt.startsWith("<"))
            {
                writer->write(line);
                continue;
            }

            //qDebug() << chr.str() << ":" << start << " " << ref << ">" << alt;

            int wt_end = start + ref.length();
            int wt_seq_length = wt_end - start + 20;
            Sequence wt_seq = reference.seq(chr, start-10, wt_seq_length);
            //qDebug() << wt_seq;

            int mut_end = start + alt.length();
            Sequence mut_seq_prefix = reference.seq(chr, start-10, 10);
            Sequence mut_seq_postfix = reference.seq(chr, mut_end, 10);
            Sequence mut_seq = mut_seq_prefix + alt + mut_seq_postfix;
            //qDebug() << mut_seq;

            if (!(isValidSequence(wt_seq) && isValidSequence(mut_seq)))
            {
                qWarning() << "Skipping variant because it contains non ACGT letters: " << chr.str() << ":" << start << " " << ref << ">" << alt << " extended sequences: wt:" << wt_seq << ", mutant: " << mut_seq;
                writer->write(parts.join('\t')+'\n');
                continue;
            }

            if (add_hexplorer) {
                float hzei_wt = calculateHZEIforSequence(wt_seq);
                float hzei_mut = calculateHZEIforSequence(mut_seq);

                wt_seq.reverseComplement();
                mut_seq.reverseComplement();

                float hzei_wt_rev = calculateHZEIforSequence(wt_seq);
                float hzei_mut_rev = calculateHZEIforSequence(mut_seq);

                // recover original sequence in case we want to calculate hbond scores
                wt_seq.reverseComplement();
                mut_seq.reverseComplement();

                float delta_hzei = hzei_mut - hzei_wt;
                float delta_hzei_rev = hzei_mut_rev - hzei_wt_rev;

				info = collect_info(info, "hexplorer_delta=", QByteArray::number(delta_hzei, 'f', 2));
				info = collect_info(info, "hexplorer_mut=", QByteArray::number(hzei_mut, 'f', 2));
				info = collect_info(info, "hexplorer_wt=", QByteArray::number(hzei_wt, 'f', 2));
				info = collect_info(info, "hexplorer_delta_rev=", QByteArray::number(delta_hzei_rev, 'f', 2));
				info = collect_info(info, "hexplorer_mut_rev=", QByteArray::number(hzei_mut_rev, 'f', 2));
				info = collect_info(info, "hexplorer_wt_rev=", QByteArray::number(hzei_wt_rev, 'f', 2));
            }

            if (add_hbond_score) {
                float maxHbondScoreWT = getMaxHBondScores(wt_seq);
                float maxHbondScoreMUT = getMaxHBondScores(mut_seq);

                wt_seq.reverseComplement();
                mut_seq.reverseComplement();

                float maxHbondScoreWTRev = getMaxHBondScores(wt_seq);
                float maxHbondScoreMUTRev = getMaxHBondScores(mut_seq);

				float deltaHbondScore = maxHbondScoreMUT - maxHbondScoreWT;
                float deltaHbondScoreRev = maxHbondScoreMUTRev - maxHbondScoreWTRev;

                if (maxHbondScoreMUT > 0 || maxHbondScoreWT > 0) {
					info = collect_info(info, "max_hbond_delta=", QByteArray::number(deltaHbondScore, 'f', 2));
                }
                if (maxHbondScoreMUT > 0) {
					info = collect_info(info, "max_hbond_mut=", QByteArray::number(maxHbondScoreMUT, 'f', 2));
                }
                if (maxHbondScoreWT > 0) {
					info = collect_info(info, "max_hbond_wt=", QByteArray::number(maxHbondScoreWT, 'f', 2));
                }
                if (maxHbondScoreMUTRev > 0 || maxHbondScoreWTRev > 0) {
					info = collect_info(info, "max_hbond_delta_rev=", QByteArray::number(deltaHbondScoreRev, 'f', 2));
                }
                if (maxHbondScoreMUTRev > 0) {
					info = collect_info(info, "max_hbond_mut_rev=", QByteArray::number(maxHbondScoreMUTRev, 'f', 2));
                }
                if (maxHbondScoreWTRev > 0) {
					info = collect_info(info, "max_hbond_wt_rev=", QByteArray::number(maxHbondScoreWTRev, 'f', 2));
                }
            }

            parts[7] = info;
            writer->write(parts.join('\t')+'\n');

        }
    }

private:
    QHash<QString, float> hexplorer_zscores_;
    QHash<QString, float> hbond_scores_;

    QString curateSequence(QString sequence)
    {
        sequence = sequence.toUpper();
        return sequence;
    }

    bool isValidSequence(const QString& sequence)
    {
        return QRegExp("[ACGTacgt]*").exactMatch(sequence);
    }

    QByteArray collect_info(const QByteArray& old_info, const QByteArray& prefix, const QByteArray& new_info, const QByteArray& sep=";")
    {
        const QByteArray prefixed_new_info = prefix + new_info;
        if (old_info == "." || old_info.trimmed().isEmpty())
        {
            return prefixed_new_info;
        } else {
            return old_info + sep + prefixed_new_info;
        }
    }
};

#include "main.moc"

int main(int argc, char *argv[])
{
	ConcreteTool tool(argc, argv);
	return tool.execute();
}


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

package com.google.enterprise.policychecker;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import com.google.enterprise.supergsa.security.AclGroup;
import com.google.enterprise.supergsa.security.AclPrincipal;
import com.google.enterprise.supergsa.security.Domain;

import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.Nullable;

/**
 * Group is the compound form of Principal: a collection of Principals. A Group
 * may contain Users or Groups directly, if these Users or Groups or
 * indirectly (through containment in a sub-Group).
 */
public class Group implements Principal {
  private static final String DEFAULT_NAMESPACE = "Default";

  private AclPrincipal principal;

  protected final Map<AclPrincipal, User> users;
  protected final Map<AclPrincipal, Group> groups;

  /**
   * Build a group from an AclGroup protocol buffer.  Note that in this version the references to
   * groups and users will not be canonicalized.
   * @param group the group to convert from
   * @return the Group equivalent of the protocol buffer version of this group.  The
   * statement group.equals(AclGroup.fromAclGroup(group).toAclGroup()) will be true.
   */
  public static Group fromAclGroup(final AclGroup group) {
    AclPrincipal newGroup = group.getPrincipal();

    if (newGroup.getScope() != AclPrincipal.SCOPE.GROUP) {
      throw new IllegalArgumentException("AclGroup not well-formed: " + group);
    }
    Group grp = new Group(newGroup.getName(),
        newGroup.getNameSpace(),
        newGroup.getDomain());
    for (AclPrincipal principal : group.getMembersList()) {
      if (principal.getScope() == AclPrincipal.SCOPE.USER) {
        grp.addUser(new User(principal.getName(),
            principal.getNameSpace(),
            principal.getDomain()));
      } else {
        grp.addGroup(new Group(principal.getName(),
            principal.getNameSpace(),
            principal.getDomain()));
      }
    }
    return grp;
  }

  @SuppressWarnings("unused")
  protected Group() {
    throw new IllegalArgumentException();
    // prevents use of the default constructor
  }

  /**
   * Construct a group from the given name, with default namespace and no domain set.
   *
   * @param name The Group's name.
   * @throws IllegalArgumentException if the name is null.
   */
  public Group(final String name) {
    Preconditions.checkNotNull(name);
    principal = AclPrincipal.newBuilder()
        .setName(name)
        .setScope(AclPrincipal.SCOPE.GROUP)
        .setCaseSensitive(AclPrincipal.CaseSensitivity.EVERYTHING_CASE_SENSITIVE)
        .setNameSpace(DEFAULT_NAMESPACE)
        .build();
    this.groups = new ConcurrentHashMap<AclPrincipal, Group>();
    this.users = new ConcurrentHashMap<AclPrincipal, User>();
  }

  /**
   * Construct a group from the given name, namespace and domain.
   *
   * @param name The Group's name.
   * @param namespace The Group's namespace.
   * @param domain The Group's domain.
   * @throws IllegalArgumentException if the name is null or empty string.
   */
  public Group(final String name, final String namespace, final Domain domain)
      throws IllegalArgumentException {
    if (name == null || name.isEmpty()) {
      // A Group must have a non-null, non-empty name
      throw new IllegalArgumentException();
    }
    AclPrincipal.Builder builder = AclPrincipal.newBuilder();
    builder.setName(name);
    builder.setScope(AclPrincipal.SCOPE.GROUP);
    if (namespace == null || namespace.isEmpty()) {
      builder.setNameSpace(DEFAULT_NAMESPACE);
    } else {
      builder.setNameSpace(namespace);
    }
    // Do not assign domain if it is null or not default value.
    // Currently we only support domain type as NETBIOS.
    if (domain != null
        && !(domain.getName().isEmpty()
        && domain.getType() == Domain.DomainType.NETBIOS)) {
      builder.setDomain(Domain.newBuilder()
          .setName(domain.getName())
          .setType(domain.getType())
          .build());
    }
    builder.setCaseSensitive(AclPrincipal.CaseSensitivity.EVERYTHING_CASE_SENSITIVE);
    principal = builder.build();
    this.groups = new ConcurrentHashMap<AclPrincipal, Group>();
    this.users = new ConcurrentHashMap<AclPrincipal, User>();
  }

  /**
   * Construct a group from the given principal.
   *
   * @param principal The principal to identify the group
   * @throws IllegalArgumentException if the name is null
   */
  public Group(final AclPrincipal principal) {
    Preconditions.checkNotNull(principal);
    if (principal.getScope() != AclPrincipal.SCOPE.GROUP) {
      throw new IllegalArgumentException();
    }
    this.principal = principal;
    this.groups = new ConcurrentHashMap<AclPrincipal, Group>();
    this.users = new ConcurrentHashMap<AclPrincipal, User>();
  }

  /**
   * Returns a sorted, immutable list of all users contained in this group or sub-groups with no
   * duplicates. This function handles the cyclic groups scenario.
   */
  public ImmutableList<AclPrincipal> getUsers() {
    ImmutableSortedSet.Builder<AclPrincipal> builder = ImmutableSortedSet.orderedBy(
        new AclPrincipalComparator());
    List<Group> cachedSubGroups = Lists.<Group>newLinkedList();
    Set<Group> allSubGroups = Sets.<Group>newHashSet();
    builder.addAll(users.keySet());
    for (Group group : groups.values()) {
      cachedSubGroups.add(group);
      allSubGroups.add(group);
    }

    while (!cachedSubGroups.isEmpty()) {
      Group currentGroup = cachedSubGroups.remove(0);
      builder.addAll(currentGroup.getDirectAclPrincipalUsers());
      for (Group group : currentGroup.getDirectGroups()) {
        if (allSubGroups.contains(group)) {
          continue;
        }
        cachedSubGroups.add(group);
        allSubGroups.add(group);
      }
    }

    return builder.build().asList();
  }

  /**
   * Returns a sorted, immutable list of all groups contained in this group or sub-groups with no
   * duplicates. This function handles the cyclic groups scenario.
   */
  public ImmutableList<AclPrincipal> getGroups() {
    ImmutableSortedSet.Builder<AclPrincipal> builder = ImmutableSortedSet.orderedBy(
        new AclPrincipalComparator());
    List<Group> cachedSubGroups = Lists.<Group>newLinkedList();
    Set<Group> allSubGroups = Sets.<Group>newHashSet();
    builder.addAll(groups.keySet());
    for (Group group : groups.values()) {
      cachedSubGroups.add(group);
      allSubGroups.add(group);
    }

    while (!cachedSubGroups.isEmpty()) {
      Group currentGroup = cachedSubGroups.remove(0);
      builder.addAll(currentGroup.getDirectAclPrincipalGroups());
      for (Group group : currentGroup.getDirectGroups()) {
        if (allSubGroups.contains(group)) {
          continue;
        }
        cachedSubGroups.add(group);
        allSubGroups.add(group);
      }
    }
    return builder.build().asList();
  }

  /**
   * Returns true if this Group equals the given AclPrincipal,
   * or if this Group contains the parameter either directly or indirectly.
   * Note: two different Groups with the same name do not contain each other.
   *
   * @param principal the AclPrincipal identifier that may be a member of this Principal
   * @return true if the parameter is a member of this Group
   */
  public boolean contains(@Nullable AclPrincipal principal) {
    // If this is us, then we reflexively contain ourselves.
    if (this.principal.equals(principal)) {
      return true;
    }
    // If we directly contain the principal, then sweet.
    if (users.containsKey(principal) || groups.containsKey(principal)) {
      return true;
    }
    // Otherwise, we look to see if any of our groups contains this principal.
    for (Group group : groups.values()) {
      if (group.contains(principal)) {
        return true;
      }
    }
    return false;
  }

  /**
   * Returns the Principal's AclPrincipal identifier, which may not be null or
   * empty.
   *
   * @return the Principal's AclPrincipal identifier
   */
  @Override
  public AclPrincipal getAclPrincipal() {
    return principal;
  }

  /**
   * Converts this group into the protocol buffer format convenient for serialization.
   *
   * @return the AclGroup equivalent of the protocol buffer version of this group.  The
   * statement group.equals(AclGroup.fromAclGroup(group).toAclGroup()) will be true for any group
   * returned from this function.  Note it may not be the case that
   * this.equals(AclGroup.fromAclGroup(this.toAclGroup())) because object references are not
   * canonicalized in fromAclGroup().
   */
  public AclGroup toAclGroup() {
    return AclGroup.newBuilder()
        .setPrincipal(getAclPrincipal())
        .addAllMembers(getDirectAclPrincipalUsers())
        .addAllMembers(getDirectAclPrincipalGroups())
        .build();
  }

  /**
   * Returns a short string representation of the Principal.
   *
   * @return a short string representation of the Principal.
   */
  public String getShortString() {
    StringBuilder sb = new StringBuilder();
    appendShortName(sb);
    return new String(sb);
  }

  private void appendShortName(StringBuilder sb) {
    sb.append("group:");
    sb.append(principal.getName());
  }

  /**
   * Returns a string representation of the Group which includes the group name, the names of its
   * subgroups / users, and the contents of its subgroups.
   *
   * @return a string representation of the Principal.
   */
  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    appendGroupContents(sb);
    sb.append("\n");
    TreeMap<AclPrincipal, Group> map = new TreeMap<AclPrincipal, Group>(
        new AclPrincipalComparator());
    map.putAll(groups);
    for (Entry<AclPrincipal, Group> e : map.entrySet()) {
      e.getValue().appendGroupContents(sb);
      sb.append("\n");
    }
    return new String(sb);
  }

  /**
   * Returns a string representation of the Group which includes the names of
   * its subgroups / users.
   *
   * @return a string representation of the Principal.
   */
  public String toSerializedString() {
    StringBuilder sb = new StringBuilder();
    appendGroupContents(sb);
    return new String(sb);
  }

  private void appendGroupContents(StringBuilder sb) {
    appendShortName(sb);
    Comparator<AclPrincipal> comparator = new AclPrincipalComparator();
    TreeMap<AclPrincipal, Principal> groupsMap = new TreeMap<AclPrincipal, Principal>(comparator);
    TreeMap<AclPrincipal, Principal> usersMap = new TreeMap<AclPrincipal, Principal>(comparator);
    groupsMap.putAll(groups);
    usersMap.putAll(users);
    appendPrincipals(sb, groupsMap);
    appendPrincipals(sb, usersMap);
  }

  private void appendPrincipals(StringBuilder sb, SortedMap<AclPrincipal, Principal> s) {
    for (Entry<AclPrincipal, Principal> e : s.entrySet()) {
      sb.append(" ");
      sb.append(e.getValue().getShortString());
    }
  }

  public String dumpToString() {
    StringBuilder sb = new StringBuilder();
    Comparator<AclPrincipal> comparator = new AclPrincipalComparator();
    TreeMap<AclPrincipal, Group> groupsMap = new TreeMap<AclPrincipal, Group>(comparator);
    groupsMap.putAll(groups);
    for (Entry<AclPrincipal, Group> e : groupsMap.entrySet()) {
      e.getValue().appendGroupContents(sb);
      sb.append("\n");
    }
    return new String(sb);
  }
  /**
   * Returns true if this Group directly contains the parameter Principal. This
   * means that the parameter was added directly to this Group, as opposed to
   * being a member of a sub-Group of one of the Groups directly contained in
   * this Group. Note: a Group never directly contains itself.
   *
   * @param principal the Principal that may be a member of this Group
   * @return true if the parameter is a direct member of this Group
   * @throws IllegalArgumentException if the Principal is neither a User nor
   *           Group
   */
  public boolean directlyContains(Principal principal) throws IllegalArgumentException {
    AclPrincipal name = principal.getAclPrincipal();
    if (principal instanceof User) {
      return users.containsKey(name);
    } else if (principal instanceof Group) {
      if (this.principal.equals(name)) { return false; }
      return groups.containsKey(name);
    } else {
      // User and Group are the only permitted kinds of Principal
      throw new IllegalArgumentException();
    }
  }

  /**
   * Add a Principal to this Group.
   *
   * @param principal the Principal to add
   * @throws IllegalArgumentException if the Principal is neither a User nor
   *           Group
   */
  public Principal addPrincipal(Principal principal) throws IllegalArgumentException {
    return addPrincipal(principal.getAclPrincipal());
  }

  public Principal addPrincipal(AclPrincipal principal) throws IllegalArgumentException {
    if (principal == null) {
      return null;
    }
    if (principal.getScope() == AclPrincipal.SCOPE.USER) {
      return addUser(principal);
    } else {
      return addGroup(principal);
    }
  }

  /**
   * Add a Collection of Principals to this Group.
   *
   * @param principals the Collection of Principals to add
   */
  public void addPrincipals(final Collection<Principal> principals) {
    if (principals == null) { return; }
    for (Principal principal : principals) {
      addPrincipal(principal);
    }
  }

  /**
   * Remove a principal from this group.  The principal to remove must be
   * directly contained in this group (i.e. directlyContains(principal) must
   * return true for the provided principal.
   *
   * @param principal the principal to remove
   * @return true on success; false if this group does not directly contain
   * the given principal
   */
  public boolean removePrincipal(Principal principal) {
    if (!directlyContains(principal)) {
      return false;
    }
    if (principal instanceof Group) {
      groups.remove(principal.getAclPrincipal());
    } else if (principal instanceof User) {
      users.remove(principal.getAclPrincipal());
    }
    return true;
  }

  /**
   * Get a User from this Group by name.
   *
   * @param principal The principal of the User to get
   * @return the User of the specified principal that is a member of this Group, or
   *         null if there is no such User
   * @throws IllegalArgumentException if the name is null or
   *           empty
   */
  public User getUser(AclPrincipal principal) throws IllegalArgumentException {
    if (principal == null || principal.getName().length() < 1) {
      // A User must have a non-null, non-empty name
      throw new IllegalArgumentException();
    }
    User user = users.get(principal);
    if (user != null) {
      return user;
    }
    for (Group grp : groups.values()) {
      user = grp.getUser(principal);
      if (user != null) {
        return user;
      }
    }
    return user;
  }

  /**
   * Add a User to this Group by identifier. If there already is a User with this
   * name, then it is returned. If not, a new User with the specified name is
   * created and added to the Group.
   *
   * @param name The identifier of the User to add
   * @return a new User with the specified identifier, that is a direct member of this
   *         Group
   */
  public User addUser(AclPrincipal name) {
    User user = getUser(name);
    if (user == null) {
      user = new User(name);
      putUser(user);
    }
    return user;
  }

  public User addUser(User user) {
    return addUser(user.getAclPrincipal());
  }

  public User addUser(String name) {
    return addUser(new User(name));
  }

  /**
   * Get a Group from this Group by name.
   *
   * @param principal The AclPrincipal identifier of the Group to get
   * @return the Group of the specified AclPrincipal identifier that is a member of this Group, or
   *         null if there is no such Group
   * @throws IllegalArgumentException if the principal is null or
   *           empty
   */
  public Group getGroup(AclPrincipal principal) throws IllegalArgumentException {
    if (principal == null || principal.getName().length() < 1) {
      // A Group must have a non-null, non-empty name
      throw new IllegalArgumentException();
    }
    if (principal.equals(this.principal)) { return this; }
    Group group = groups.get(principal);
    if (group != null) {
      return group;
    }
    for (Group grp : groups.values()) {
      group = grp.getGroup(principal);
      if (group != null) {
        return group;
      }
    }
    return group;
  }

  /**
   * Return the unique reference to the named group in this group if it exists and is a direct
   * member of this group.
   *
   * @param principal the AclPrincipal identifier of the group to be returned
   * @return a reference to that Group if it exists and is a direct member of this group, or null if
   * no such group exists.
   */
  public Group getDirectGroup(@Nullable AclPrincipal principal) throws IllegalArgumentException {
    if (principal == null || principal.getName().length() < 1) {
      // A Group must have a non-null, non-empty name
      throw new IllegalArgumentException();
    }
    if (principal.equals(this.principal)) { return this; }
    return groups.get(principal);
  }

  /**
   * Add a Group to this Group by AclPrincipal identifier. If there already is a Group with this
   * AclPrincipal identifier, then it is returned. If not, an empty Group with the specified
   * AclPrincipal identifier is created and added to the Group.
   *
   * @param name The identifier of the Group to add
   * @return a new User with the specified identifier, that is a direct member of this Group
   */
  public Group addGroup(AclPrincipal name) {
    return addGroup(new Group(name));
  }

  public Group addGroup(String name) {
    return addGroup(new Group(name));
  }

  /**
   * Adds a group to this group and returns a canonicalized reference to the group.  Thus, all
   * references to the group from this group will be the same.
   *
   * @param group the group to be returned after being canonicalized.  Cannot be null.
   * @return a reference to the canonicalized reference to that Group.
   */
  public Group addGroup(Group group) {
    group.canonicalizeGroup(this);
    Group existingGroup = getGroup(group.getAclPrincipal());
    if (existingGroup != null) {
      existingGroup.mergeFrom(group);
    }
    if (null == getDirectGroup(group.getAclPrincipal())) {
      if (existingGroup != null) {
        putGroup(existingGroup);
      } else {
        putGroup(group);
      }
    }
    return existingGroup != null ? existingGroup : group;
  }

  void mergeFrom(Group group) {
    for (AclPrincipal name : group.users.keySet()) {
      addUser(name);
    }

    for (Group subgroup : group.groups.values()) {
      addGroup(subgroup);
    }
  }

  /**
   * Return the number of users directly contained (listed as top-level members).
   * @return the number of users directly contained (listed as top-level members).
   */
  public int getDirectUserCount() {
    return users.size();
  }

  /**
   * Return the number of groups directly contained (listed as top-level members).
   * @return the number of groups directly contained (listed as top-level members).
   */
  public int getDirectGroupCount() {
    return groups.size();
  }

  /**
   * Return all Groups contained in this group.
   * @return all Groups contained in this group.
   */
  public ImmutableList<AclPrincipal> getDirectAclPrincipalGroups() {
    return Ordering.from(new AclPrincipalComparator()).immutableSortedCopy(groups.keySet());
  }

  /**
   * Return all Users contained in this group.
   * @return all Users contained in this group.
   */
  public ImmutableList<AclPrincipal> getDirectAclPrincipalUsers() {
    return Ordering.from(new AclPrincipalComparator()).immutableSortedCopy(users.keySet());
  }

  /**
   * Return all Principal Groups contained in this group.
   * @return all Principal Groups contained in this group.
   */
  public ImmutableList<Group> getDirectGroups() {
    return ImmutableList.copyOf(groups.values());
  }

  /**
   * Return all Principal Users contained in this group.
   * @return all Principal Users contained in this group.
   */
  public ImmutableList<User> getDirectUsers() {
    return ImmutableList.copyOf(users.values());
  }

  @Override
  public boolean equals(Object o) {
    if (!(o instanceof Group)) {
      return false;
    }
    Group g = (Group) o;
    return getAclPrincipal().equals(g.getAclPrincipal()) &&
        getDirectAclPrincipalUsers().equals(g.getDirectAclPrincipalUsers()) &&
        getDirectAclPrincipalGroups().equals(g.getDirectAclPrincipalGroups());
  }

  @Override
  public int hashCode() {
    return toString().hashCode();
  }

  public boolean removeGroup(AclPrincipal groupname) {
    boolean result = false;
    for (Group g : groups.values()) {
      result = g.removeGroup(groupname) || result;
    }
    Group g = groups.remove(groupname);
    result = (g != null) || result;
    return result;
  }

  public void removeAllGroups() {
    for (AclPrincipal groupname : groups.keySet()) {
      removeGroup(groupname);
    }
  }

  public void clear() {
    users.clear();
    groups.clear();
  }

  protected void putUser(User principal) {
    users.put(principal.getAclPrincipal(), principal);
  }

  protected void putGroup(Group principal) {
    groups.put(principal.getAclPrincipal(), principal);
  }

  /**
   * Replaces all internal references to users and groups with the references to those same users
   * and groups from the parameter, if they exist in that group.
   */
  private void canonicalizeGroup(Group group) {
    if (principal.equals(group.getAclPrincipal())) {
      throw new IllegalArgumentException();
    }
    for (User user : users.values()) {
      User canonicalUser = group.getUser(user.getAclPrincipal());
      if (canonicalUser != null) {
        putUser(canonicalUser);
      }
    }
    for (Group grp : groups.values()) {
      Group canonicalGroup = group.getGroup(grp.getAclPrincipal());
      if (canonicalGroup != null) {
        canonicalGroup.mergeFrom(grp);
        putGroup(canonicalGroup);
      }
    }
  }

}


text:
Third gen of the developer.rackspace.com Portal

This repo represents a refactor of the developer.rackspace.com site.

The dev site currently builds from rackerlabs/devsite but only accepts new blog posts as of March 1 2014.

We are migrating to this repo by June-ish 2014. The areas now building are:
- `/src/docs/`: Getting Started Guides, built using Sphinx
- `/src/site_source`: Rest of the web site layout and content, built using Jekyll

In progress:
- /api/: maven, content maintained in rackerlabs/docs-api-reference
- elastic search

To do:
- assets to CDN
- feeds

## Full Site Setup

__Note__: You should use this setup if you work on the entire d.r.c. site, its infrastructure, etc.

1. Download and install [Vagrant 1.6 or higher](http://www.vagrantup.com/downloads.html).

2. Download and install [VirtualBox](https://www.virtualbox.org/wiki/Downloads).

3. Download and install [Ansible 1.6.3 or higher](http://docs.ansible.com/intro_installation.html#installing-the-control-machine).
    * On Mac OSX machines with [Homebrew](http://brew.sh/) installed, you can simply run:

        ```bash
        brew update && brew install ansible
        ```
    * To check your Ansible version, you can run:

        ```bash
        ansible --version
        ```
    * If the version of Ansible from your package manager is too out of date, you can always find the most recent version from `pip`:

        ```bash
        sudo pip install --upgrade ansible
        ```

4. Ensure that you are in the root directory of this repo; e.g., `cd ~/src/developer.rackspace.com` (or wherever you've cloned it). If you haven't cloned the repo, fork it via the Github web interface and then

    ```bash
    $ git clone {your-repo-path}/developer.rackspace.com
    ```

5. Then, fetch the git submodules if you haven't already.

    ```bash
    $ git submodule update --init
    ```

6. Run Vagrant to set up a VirtualBox VM running a development environment and automatically publish changes to local files to the development VM. **Note: This command will run in the foreground and will not allow this terminal window to be used for anything else. If you need to do more commandline work, please open a new window and continue there.**

    ```bash
    $ vagrant up && vagrant rsync-auto
    ```

7. That's it! Your development environment is setup in a VirtualBox VM! It's contents are:
    * A web server running Nginx, accessible at [http://localhost:8000](http://localhost:8000).
        * To access the Getting Started Guides, go to http://localhost:8000/docs/
    * If you have problems with the watcher process, view the logs with:
        ```bash
        sudo tail -F /var/log/upstart/watcher.log
        ```

## Blog Contributor Setup

Please see [here](/src/site_source/CONTRIBUTING.md).


text:
using System;

namespace Genocs.Core.Domain.Entities.Auditing
{
    /// <summary>
    /// This interface is implemented by entities which wanted to store deletion information (who and when deleted).
    /// </summary>
    public interface IDeletionAudited : ISoftDelete
    {
        /// <summary>
        /// Which user deleted this entity?
        /// </summary>
        long? DeleterUserId { get; set; }

        /// <summary>
        /// Deletion time of this entity.
        /// </summary>
        DateTime? DeletionTime { get; set; }
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.msu.nscl.olog;

import edu.msu.nscl.olog.entity.State;
import edu.msu.nscl.olog.entity.Tag;
import edu.msu.nscl.olog.entity.Tags;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.ws.rs.core.Response;
import java.util.Iterator;
import java.util.List;

/**
 *
 * @author berryman
 */
public class TagManagerTest {
    private static EntityManager em = null;

    private TagManagerTest() {
    }
    /**
     * Returns the list of tags in the database.
     *
     * @return Tags
     * @throws edu.msu.nscl.olog.OlogException wrapping an SQLException
     */
    public static Tags findAll() throws OlogException {
        em = JPAUtilTest.getEntityManagerFactory().createEntityManager();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Tag> cq = cb.createQuery(Tag.class);
        Root<Tag> from = cq.from(Tag.class);
        CriteriaQuery<Tag> select = cq.select(from);
        Predicate statusPredicate = cb.equal(from.get("state"), State.Active);
        select.where(statusPredicate);
        select.orderBy(cb.asc(from.get("name")));
        TypedQuery<Tag> typedQuery = em.createQuery(select);
        JPAUtilTest.startTransaction(em);
        try {
            Tags result = new Tags();
            List<Tag> rs = typedQuery.getResultList();
            if (rs != null) {
                Iterator<Tag> iterator = rs.iterator();
                while (iterator.hasNext()) {
                    result.addTag(iterator.next());
                }
            }

            return result;
        } catch (Exception e) {
            throw new OlogException(Response.Status.INTERNAL_SERVER_ERROR,
                    "JPA exception: " + e);
        } finally {
           JPAUtilTest.finishTransacton(em);
        }
    }

    /**
     * Finds a tag in the database by name.
     *
     * @return Tag
     * @throws edu.msu.nscl.olog.OlogException wrapping an SQLException
     */
    public static Tag findTag(String name) throws OlogException {
        em = JPAUtilTest.getEntityManagerFactory().createEntityManager();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Tag> cq = cb.createQuery(Tag.class);
        Root<Tag> from = cq.from(Tag.class);
        CriteriaQuery<Tag> select = cq.select(from);
        Predicate namePredicate = cb.equal(from.get("name"), name);
        //Predicate statusPredicate = cb.equal(from.get("state"), State.Active);
        select.where(namePredicate);
        select.orderBy(cb.asc(from.get("name")));
        TypedQuery<Tag> typedQuery = em.createQuery(select);
        JPAUtilTest.startTransaction(em);
        try {
            Tag result = null;
            List<Tag> rs = typedQuery.getResultList();
            if (rs != null) {
                Iterator<Tag> iterator = rs.iterator();
                while (iterator.hasNext()) {
                    result = iterator.next();
                }
            }

            return result;
        } catch (Exception e) {
            throw new OlogException(Response.Status.INTERNAL_SERVER_ERROR,
                    "JPA exception: " + e);
        } finally {
          JPAUtilTest.finishTransacton(em);
        }
    }
            /**
     * Creates a tag in the database.
     *
     * @param name name of tag
     * @param owner owner of tag
     * @throws edu.msu.nscl.olog.OlogException wrapping an SQLException
     */
    public static Tag create(String name) throws OlogException {

        try {
            Tag xmlTag = new Tag();
            Tag tag = findTag(name);
            if (tag != null) {
                tag.setState(State.Active);
                tag = (Tag)JPAUtilTest.update(tag);
                return tag;
            } else {
                xmlTag.setName(name);
                xmlTag.setState(State.Active);
                JPAUtilTest.save(xmlTag);
                return xmlTag;
            }
        } catch (Exception e) {

            throw new OlogException(Response.Status.INTERNAL_SERVER_ERROR,
                    "JPA exception: " + e);
        }
    }

    /**
     * Remove a tag (mark as Inactive).
     *
     * @param name tag name
     */
     public static void remove(String name) throws OlogException {

        try {
                Tag tag = findTag(name);
                tag.setState(State.Inactive);
                JPAUtilTest.update(tag);
        } catch (Exception e) {
            throw new OlogException(Response.Status.INTERNAL_SERVER_ERROR,
                    "JPA exception: " + e);

        }
    }
}


text:
class ChangeProjectOfEnvironment < ActiveRecord::Migration[4.2]
  include Gitlab::Database::MigrationHelpers

  # When using the methods "add_concurrent_index" or "add_column_with_default"
  # you must disable the use of transactions as these methods can not run in an
  # existing transaction. When using "add_concurrent_index" make sure that this
  # method is the _only_ method called in the migration, any other changes
  # should go in a separate migration. This ensures that upon failure _only_ the
  # index creation fails and can be retried or reverted easily.
  #
  # To disable transactions uncomment the following line and remove these
  # comments:
  # disable_ddl_transaction!

  def change
    change_column_null :environments, :project_id, true
  end
end


text:
<?php
/** @api-call createAccident */
namespace methods;

use db\ApkDb;
use errors\Codes;
use notifications\FireBase;
use user\User;

class CreateAccident extends MethodWithAuth
{
    const TEST = false;

    const MODERATOR_TIMEOUT = 30;
    const STANDARD_TIMEOUT  = 1800;
    private static $timeoutSql    = 'SELECT IFNULL(UNIX_TIMESTAMP(MAX(created)), 0) FROM entities WHERE `owner`=:owner';
    private static $addSql        = 'INSERT INTO entities
                              (starttime, modified, `owner`, lat, lon, address, description, `status`, is_test, acc_type, medicine)
                              VALUES
                              (NOW(), NOW(), :owner, :lat, :lon, :address, :description, :status, :is_test, :acc_type, :medicine)';
    private static $logSql        = 'INSERT INTO httplog (request) VALUES (:request)';
    private static $history       = 'INSERT INTO history (id_ent, id_user, action) VALUES (:id, :user, "create_mc_acc")';
    private        $prerequisites = ['a', 'd', 'y', 'x', 't', 'dm'];
    private static $typesList     = ['b' => 'acc_b', 'm' => 'acc_m', 'ma' => 'acc_m_a', 'mm' => 'acc_m_m', 'mp' => 'acc_m_p', 'o' => 'acc_o', 's' => 'acc_s'];
    private static $damageList    = ['d' => 'mc_m_d', 'h' => 'mc_m_h', 'l' => 'mc_m_l', 'wo' => 'mc_m_wo', 'na' => 'mc_m_na'];

    private $data;
    private $id = 0;

    /*
                'a'  => $row['address'],
                'd'  => $row['description'],
                's'  => $row['statistics'],       ????????
                'y'  => (float) $row['lat'],
                'x'  => (float) $row['lon'],
                't'  => $row['type'],
                'm'  => $row['medicine'],
     */
    public function __construct($data)
    {
        parent::__construct($data);
        if (User::isReadOnly()) throw new \InvalidArgumentException("Read only", Codes::READ_ONLY);
        foreach ($this->prerequisites as $param) {
            if (!isset($data[$param])) throw new \InvalidArgumentException("Invalid arguments", Codes::INVALID_ARGUMENTS);
        }
        $this->checkTimeout();
        $this->data = $data;
    }

    private function checkTimeout()
    {
        $stmt = ApkDb::getInstance()->prepare(self::$timeoutSql);
        $stmt->bindValue(':owner', User::$id);
        $stmt->execute();
        $result  = (int)$stmt->fetchColumn(0);
        $timeout = User::isModerator() ? self::MODERATOR_TIMEOUT : self::STANDARD_TIMEOUT;
        if ((time() - $result) < $timeout) throw new \Exception($timeout - time() + $result, Codes::CREATE_TIMEOUT);
    }

    /**
     * @return array
     * @throws \Exception
     */
    public function __invoke()
    {
        $this->insertAccident();
        $this->log();
        $this->saveHistory();
        $this->push();
        $this->share();
        return ['id' => $this->id];
    }

    private function insertAccident()
    {
        $stmt = ApkDb::getInstance()->prepare(self::$addSql);
        $stmt->bindValue(':owner', User::$id);
        $stmt->bindValue(':lat', $this->data['y']);
        $stmt->bindValue(':lon', $this->data['x']);
        $stmt->bindValue(':address', $this->data['a']);
        $stmt->bindValue(':description', $this->data['d']);
        $stmt->bindValue(':acc_type', self::$typesList[$this->data['t']]);
        $stmt->bindValue(':medicine', self::$damageList[$this->data['dm']]);
        $stmt->bindValue(':is_test', self::TEST || isset($this->data['test']) ? 1 : 0);
        $stmt->bindValue(':status', isset($this->data['s']) ? "acc_status_end" : "acc_status_act");
        $stmt->execute();
        $this->id = ApkDb::getInstance()->lastInsertId();

    }

    private function log()
    {
        $stmt = ApkDb::getInstance()->prepare(self::$logSql);
        $stmt->bindValue(':request', json_encode($this->data, true));
        $stmt->execute();
    }

    private function saveHistory()
    {
        $stmt = ApkDb::getInstance()->prepare(self::$history);
        $stmt->bindValue(':id', $this->id);
        $stmt->bindValue(':user', User::$id);
        $stmt->execute();
    }

    private function push()
    {
        if ($this->id === 0 || isset($this->data['s'])) return;
        FireBase::sendBroadcast(['id' => (string)$this->id], isset($this->data['test']));
    }

    private function share()
    {
        //todo
    }
}


text:
<?php

return (new Stack\Builder())
    ->push('Negotiation\Stack\Negotiation',
        $app['format.negotiator'],
        $app['language.negotiator']
    )
    ->resolve($app);