text:
package org.apache.hadoop.hbase.security.access;

import com.google.protobuf.RpcCallback;
import com.google.protobuf.RpcController;
import com.google.protobuf.Service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hbase.Coprocessor;
import org.apache.hadoop.hbase.CoprocessorEnvironment;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.DoNotRetryIOException;
import org.apache.hadoop.hbase.coprocessor.CoprocessorService;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import org.apache.hadoop.hbase.ipc.RequestContext;
import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
import org.apache.hadoop.hbase.protobuf.ResponseConverter;
import org.apache.hadoop.hbase.protobuf.generated.ClientProtos;
import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.SecureBulkLoadService;
import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.PrepareBulkLoadRequest;
import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.PrepareBulkLoadResponse;
import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.CleanupBulkLoadRequest;
import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.CleanupBulkLoadResponse;
import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.SecureBulkLoadHFilesRequest;
import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.SecureBulkLoadHFilesResponse;
import org.apache.hadoop.hbase.regionserver.HRegion;
import org.apache.hadoop.hbase.security.SecureBulkLoadUtil;
import org.apache.hadoop.hbase.security.User;
import org.apache.hadoop.hbase.security.UserProvider;
import org.apache.hadoop.hbase.security.token.FsDelegationToken;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.FSHDFSUtils;
import org.apache.hadoop.hbase.util.Methods;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.Token;

import java.io.IOException;
import java.math.BigInteger;
import java.security.PrivilegedAction;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;

/**
 * Coprocessor service for bulk loads in secure mode.
 * This coprocessor has to be installed as part of enabling
 * security in HBase.
 *
 * This service addresses two issues:
 *
 * 1. Moving files in a secure filesystem wherein the HBase Client
 * and HBase Server are different filesystem users.
 * 2. Does moving in a secure manner. Assuming that the filesystem
 * is POSIX compliant.
 *
 * The algorithm is as follows:
 *
 * 1. Create an hbase owned staging directory which is
 * world traversable (711): /hbase/staging
 * 2. A user writes out data to his secure output directory: /user/foo/data
 * 3. A call is made to hbase to create a secret staging directory
 * which globally rwx (777): /user/staging/averylongandrandomdirectoryname
 * 4. The user moves the data into the random staging directory,
 * then calls bulkLoadHFiles()
 *
 * Like delegation tokens the strength of the security lies in the length
 * and randomness of the secret directory.
 *
 */
@InterfaceAudience.Private
public class SecureBulkLoadEndpoint extends SecureBulkLoadService
    implements CoprocessorService, Coprocessor {

  public static final long VERSION = 0L;

  //320/5 = 64 characters
  private static final int RANDOM_WIDTH = 320;
  private static final int RANDOM_RADIX = 32;

  private static Log LOG = LogFactory.getLog(SecureBulkLoadEndpoint.class);

  private final static FsPermission PERM_ALL_ACCESS = FsPermission.valueOf("-rwxrwxrwx");
  private final static FsPermission PERM_HIDDEN = FsPermission.valueOf("-rwx--x--x");

  private SecureRandom random;
  private FileSystem fs;
  private Configuration conf;

  //two levels so it doesn't get deleted accidentally
  //no sticky bit in Hadoop 1.0
  private Path baseStagingDir;

  private RegionCoprocessorEnvironment env;

  private UserProvider userProvider;

  @Override
  public void start(CoprocessorEnvironment env) {
    this.env = (RegionCoprocessorEnvironment)env;
    random = new SecureRandom();
    conf = env.getConfiguration();
    baseStagingDir = SecureBulkLoadUtil.getBaseStagingDir(conf);
    this.userProvider = UserProvider.instantiate(conf);

    try {
      fs = FileSystem.get(conf);
      fs.mkdirs(baseStagingDir, PERM_HIDDEN);
      fs.setPermission(baseStagingDir, PERM_HIDDEN);
      //no sticky bit in hadoop-1.0, making directory nonempty so it never gets erased
      fs.mkdirs(new Path(baseStagingDir,"DONOTERASE"), PERM_HIDDEN);
      FileStatus status = fs.getFileStatus(baseStagingDir);
      if(status == null) {
        throw new IllegalStateException("Failed to create staging directory");
      }
      if(!status.getPermission().equals(PERM_HIDDEN)) {
        throw new IllegalStateException(
            "Directory already exists but permissions aren't set to '-rwx--x--x' ");
      }
    } catch (IOException e) {
      throw new IllegalStateException("Failed to get FileSystem instance",e);
    }
  }

  @Override
  public void stop(CoprocessorEnvironment env) throws IOException {
  }

  @Override
  public void prepareBulkLoad(RpcController controller,
                                                 PrepareBulkLoadRequest request,
                                                 RpcCallback<PrepareBulkLoadResponse> done){
    try {
      getAccessController().prePrepareBulkLoad(env);
      String bulkToken = createStagingDir(baseStagingDir,
          getActiveUser(), ProtobufUtil.toTableName(request.getTableName())).toString();
      done.run(PrepareBulkLoadResponse.newBuilder().setBulkToken(bulkToken).build());
    } catch (IOException e) {
      ResponseConverter.setControllerException(controller, e);
    }
    done.run(null);
  }

  @Override
  public void cleanupBulkLoad(RpcController controller,
                              CleanupBulkLoadRequest request,
                              RpcCallback<CleanupBulkLoadResponse> done) {
    try {
      getAccessController().preCleanupBulkLoad(env);
      fs.delete(createStagingDir(baseStagingDir,
          getActiveUser(),
          env.getRegion().getTableDesc().getTableName(),
          new Path(request.getBulkToken()).getName()),
          true);
      done.run(CleanupBulkLoadResponse.newBuilder().build());
    } catch (IOException e) {
      ResponseConverter.setControllerException(controller, e);
    }
    done.run(null);
  }

  @Override
  public void secureBulkLoadHFiles(RpcController controller,
                                   SecureBulkLoadHFilesRequest request,
                                   RpcCallback<SecureBulkLoadHFilesResponse> done) {
    final List<Pair<byte[], String>> familyPaths = new ArrayList<Pair<byte[], String>>();
    for(ClientProtos.BulkLoadHFileRequest.FamilyPath el : request.getFamilyPathList()) {
      familyPaths.add(new Pair(el.getFamily().toByteArray(),el.getPath()));
    }
    final Token userToken =
        new Token(request.getFsToken().getIdentifier().toByteArray(),
                  request.getFsToken().getPassword().toByteArray(),
                  new Text(request.getFsToken().getKind()),
                  new Text(request.getFsToken().getService()));
    final String bulkToken = request.getBulkToken();
    User user = getActiveUser();
    final UserGroupInformation ugi = user.getUGI();
    if(userToken != null) {
      ugi.addToken(userToken);
    } else if (userProvider.isHadoopSecurityEnabled()) {
      //we allow this to pass through in "simple" security mode
      //for mini cluster testing
      ResponseConverter.setControllerException(controller,
          new DoNotRetryIOException("User token cannot be null"));
      return;
    }

    HRegion region = env.getRegion();
    boolean bypass = false;
    if (region.getCoprocessorHost() != null) {
      try {
        bypass = region.getCoprocessorHost().preBulkLoadHFile(familyPaths);
      } catch (IOException e) {
        ResponseConverter.setControllerException(controller, e);
        done.run(null);
        return;
      }
    }
    boolean loaded = false;
    if (!bypass) {
      // Get the target fs (HBase region server fs) delegation token
      // Since we have checked the permission via 'preBulkLoadHFile', now let's give
      // the 'request user' necessary token to operate on the target fs.
      // After this point the 'doAs' user will hold two tokens, one for the source fs
      // ('request user'), another for the target fs (HBase region server principal).
      FsDelegationToken targetfsDelegationToken = new FsDelegationToken(userProvider, "renewer");
      try {
        targetfsDelegationToken.acquireDelegationToken(fs);
      } catch (IOException e) {
        ResponseConverter.setControllerException(controller, e);
        done.run(null);
        return;
      }
      Token<?> targetFsToken = targetfsDelegationToken.getUserToken();
      if (targetFsToken != null && (userToken == null
          || !targetFsToken.getService().equals(userToken.getService()))) {
        ugi.addToken(targetFsToken);
      }

      loaded = ugi.doAs(new PrivilegedAction<Boolean>() {
        @Override
        public Boolean run() {
          FileSystem fs = null;
          try {
            Configuration conf = env.getConfiguration();
            fs = FileSystem.get(conf);
            for(Pair<byte[], String> el: familyPaths) {
              Path p = new Path(el.getSecond());
              LOG.trace("Setting permission for: " + p);
              fs.setPermission(p, PERM_ALL_ACCESS);

              Path stageFamily = new Path(bulkToken, Bytes.toString(el.getFirst()));
              if(!fs.exists(stageFamily)) {
                fs.mkdirs(stageFamily);
                fs.setPermission(stageFamily, PERM_ALL_ACCESS);
              }
            }
            //We call bulkLoadHFiles as requesting user
            //To enable access prior to staging
            return env.getRegion().bulkLoadHFiles(familyPaths, true,
                new SecureBulkLoadListener(fs, bulkToken, conf));
          } catch (Exception e) {
            LOG.error("Failed to complete bulk load", e);
          }
          return false;
        }
      });
    }
    if (region.getCoprocessorHost() != null) {
      try {
        loaded = region.getCoprocessorHost().postBulkLoadHFile(familyPaths, loaded);
      } catch (IOException e) {
        ResponseConverter.setControllerException(controller, e);
        done.run(null);
        return;
      }
    }
    done.run(SecureBulkLoadHFilesResponse.newBuilder().setLoaded(loaded).build());
  }

  private AccessController getAccessController() {
    return (AccessController) this.env.getRegion()
        .getCoprocessorHost().findCoprocessor(AccessController.class.getName());
  }

  private Path createStagingDir(Path baseDir,
                                User user,
                                TableName tableName) throws IOException {
    String randomDir = user.getShortName()+"__"+ tableName +"__"+
        (new BigInteger(RANDOM_WIDTH, random).toString(RANDOM_RADIX));
    return createStagingDir(baseDir, user, tableName, randomDir);
  }

  private Path createStagingDir(Path baseDir,
                                User user,
                                TableName tableName,
                                String randomDir) throws IOException {
    Path p = new Path(baseDir, randomDir);
    fs.mkdirs(p, PERM_ALL_ACCESS);
    fs.setPermission(p, PERM_ALL_ACCESS);
    return p;
  }

  private User getActiveUser() {
    User user = RequestContext.getRequestUser();
    if (!RequestContext.isInRequestContext()) {
      return null;
    }

    //this is for testing
    if("simple".equalsIgnoreCase(conf.get(User.HBASE_SECURITY_CONF_KEY))) {
      return User.createUserForTesting(conf, user.getShortName(), new String[]{});
    }

    return user;
  }

  @Override
  public Service getService() {
    return this;
  }

  private static class SecureBulkLoadListener implements HRegion.BulkLoadListener {
    // Target filesystem
    private FileSystem fs;
    private String stagingDir;
    private Configuration conf;
    // Source filesystem
    private FileSystem srcFs = null;

    public SecureBulkLoadListener(FileSystem fs, String stagingDir, Configuration conf) {
      this.fs = fs;
      this.stagingDir = stagingDir;
      this.conf = conf;
    }

    @Override
    public String prepareBulkLoad(final byte[] family, final String srcPath) throws IOException {
      Path p = new Path(srcPath);
      Path stageP = new Path(stagingDir, new Path(Bytes.toString(family), p.getName()));
      if (srcFs == null) {
        srcFs = FileSystem.get(p.toUri(), conf);
      }

      if(!isFile(p)) {
        throw new IOException("Path does not reference a file: " + p);
      }

      // Check to see if the source and target filesystems are the same
      if (!FSHDFSUtils.isSameHdfs(conf, srcFs, fs)) {
        LOG.debug("Bulk-load file " + srcPath + " is on different filesystem than " +
            "the destination filesystem. Copying file over to destination staging dir.");
        FileUtil.copy(srcFs, p, fs, stageP, false, conf);
      }
      else {
        LOG.debug("Moving " + p + " to " + stageP);
        if(!fs.rename(p, stageP)) {
          throw new IOException("Failed to move HFile: " + p + " to " + stageP);
        }
      }
      return stageP.toString();
    }

    @Override
    public void doneBulkLoad(byte[] family, String srcPath) throws IOException {
      LOG.debug("Bulk Load done for: " + srcPath);
    }

    @Override
    public void failedBulkLoad(final byte[] family, final String srcPath) throws IOException {
      Path p = new Path(srcPath);
      Path stageP = new Path(stagingDir,
          new Path(Bytes.toString(family), p.getName()));
      LOG.debug("Moving " + stageP + " back to " + p);
      if(!fs.rename(stageP, p))
        throw new IOException("Failed to move HFile: " + stageP + " to " + p);
    }

    /**
     * Check if the path is referencing a file.
     * This is mainly needed to avoid symlinks.
     * @param p
     * @return true if the p is a file
     * @throws IOException
     */
    private boolean isFile(Path p) throws IOException {
      FileStatus status = srcFs.getFileStatus(p);
      boolean isFile = !status.isDir();
      try {
        isFile = isFile && !(Boolean)Methods.call(FileStatus.class, status, "isSymlink", null, null);
      } catch (Exception e) {
      }
      return isFile;
    }
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
J Protozool 39 (1): 245.

#### Original name
Tricornia Pell & E.U. Canning

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
external help file: Microsoft.Azure.Commands.Network.dll-Help.xml
Module Name: AzureRM.Network
online version: https://docs.microsoft.com/en-us/powershell/module/azurerm.network/add-azurermloadbalanceroutboundruleconfig
schema: 2.0.0
---

# Add-AzureRmLoadBalancerOutboundRuleConfig

## SYNOPSIS
Adds an outbound rule configuration to a load balancer.

## SYNTAX

### SetByResource (Default)
```
Add-AzureRmLoadBalancerOutboundRuleConfig -LoadBalancer <PSLoadBalancer> -Name <String>
 [-AllocatedOutboundPort <Int32>] -Protocol <String> [-EnableTcpReset] [-IdleTimeoutInMinutes <Int32>]
 -FrontendIpConfiguration <System.Collections.Generic.List`1[Microsoft.Azure.Commands.Network.Models.PSResourceId]>
 -BackendAddressPool <PSBackendAddressPool> [-DefaultProfile <IAzureContextContainer>] [-WhatIf] [-Confirm]
 [<CommonParameters>]
```

### SetByResourceId
```
Add-AzureRmLoadBalancerOutboundRuleConfig -LoadBalancer <PSLoadBalancer> -Name <String>
 [-AllocatedOutboundPort <Int32>] -Protocol <String> [-EnableTcpReset] [-IdleTimeoutInMinutes <Int32>]
 -FrontendIpConfiguration <System.Collections.Generic.List`1[Microsoft.Azure.Commands.Network.Models.PSResourceId]>
 -BackendAddressPoolId <String> [-DefaultProfile <IAzureContextContainer>] [-WhatIf] [-Confirm]
 [<CommonParameters>]
```

## DESCRIPTION
The **Add-AzureRmLoadBalancerOutboundRuleConfig** cmdlet adds an outbound rule configuration to an Azure load balancer.

## EXAMPLES

### Example 1: Add an outbound rule configuration to a load balancer
```powershell
PS C:\>$slb = Get-AzureRmLoadBalancer -ResourceGroupName "MyResourceGroup" -Name "MyLoadBalancer"
PS C:\>$slb | Add-AzureRmLoadBalancerOutboundRuleConfig -Name "NewRule" -Protocol "Tcp" -FrontendIPConfiguration $slb.FrontendIpConfigurations[0] -BackendAddressPool $slb.BackendAddressPools[0]
```

The first command gets the load balancer named MyLoadBalancer, and then stores it in the variable $slb.
The second command uses the pipeline operator to pass the load balancer in $slb to **Add-AzureRmLoadBalancerOutboundRuleConfig**, which adds an outbound rule configuration to the load balancer.

## PARAMETERS

### -AllocatedOutboundPort
The number of outbound ports to be used for NAT.

```yaml
Type: System.Int32
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -BackendAddressPool
A reference to a pool of DIPs.
Outbound traffic is randomly load balanced across IPs in the backend IPs.

```yaml
Type: Microsoft.Azure.Commands.Network.Models.PSBackendAddressPool
Parameter Sets: SetByResource
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -BackendAddressPoolId
A reference to a pool of DIPs.
Outbound traffic is randomly load balanced across IPs in the backend IPs.

```yaml
Type: System.String
Parameter Sets: SetByResourceId
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -DefaultProfile
The credentials, account, tenant, and subscription used for communication with Azure.

```yaml
Type: Microsoft.Azure.Commands.Common.Authentication.Abstractions.IAzureContextContainer
Parameter Sets: (All)
Aliases: AzureRmContext, AzureCredential

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -EnableTcpReset
Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination.
This element is only used when the protocol is set to TCP.

```yaml
Type: System.Management.Automation.SwitchParameter
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -FrontendIpConfiguration
The Frontend IP addresses of the load balancer.

```yaml
Type: System.Collections.Generic.List`1[Microsoft.Azure.Commands.Network.Models.PSResourceId]
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -IdleTimeoutInMinutes
The timeout for the TCP idle connection

```yaml
Type: System.Int32
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -LoadBalancer
The reference of the load balancer resource.

```yaml
Type: Microsoft.Azure.Commands.Network.Models.PSLoadBalancer
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```

### -Name
Name of the outbound rule.

```yaml
Type: System.String
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -Protocol
Protocol - TCP, UDP or All

```yaml
Type: System.String
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -Confirm
Prompts you for confirmation before running the cmdlet.

```yaml
Type: System.Management.Automation.SwitchParameter
Parameter Sets: (All)
Aliases: cf

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -WhatIf
Shows what would happen if the cmdlet runs.
The cmdlet is not run.

```yaml
Type: System.Management.Automation.SwitchParameter
Parameter Sets: (All)
Aliases: wi

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

### Microsoft.Azure.Commands.Network.Models.PSLoadBalancer
System.Int32
System.String
System.Collections.Generic.List\`1[[Microsoft.Azure.Commands.Network.Models.PSResourceId, Microsoft.Azure.Commands.Network, Version=6.5.0.0, Culture=neutral, PublicKeyToken=null]]
Microsoft.Azure.Commands.Network.Models.PSBackendAddressPool

## OUTPUTS

### Microsoft.Azure.Commands.Network.Models.PSLoadBalancer

## NOTES

## RELATED LINKS


text:
namespace Carto.Ui {
    using System;
    using Carto.Renderers;

    // WinPhone-specific implementation of RedrawRequestListener.
    internal class MapViewRedrawRequestListener : RedrawRequestListener {
        private readonly WeakReference<MapView> _mapViewRef;

        public MapViewRedrawRequestListener(MapView mapView) {
            _mapViewRef = new WeakReference<MapView>(mapView);
        }

        public override void OnRedrawRequested() {
            MapView mapView = null;
            if (_mapViewRef.TryGetTarget(out mapView)) {
                if (mapView != null) { // check probably not needed
                    mapView.Redraw();
                }
            }
        }
    }
}


text:
import { bootstrap } from "angular2/platform/browser";
import { RootComponent } from "./root.component";
import { ROUTER_PROVIDERS, ROUTER_DIRECTIVES, LocationStrategy, HashLocationStrategy} from "angular2/router";
import { PLATFORM_DIRECTIVES, provide, enableProdMode } from "angular2/core";
import { HTTP_PROVIDERS } from "angular2/http";
import { FirebaseService } from "./shared/firebase.service";
import { Environment } from "./config/environment";

if (Environment === "production") {
  enableProdMode();
}

bootstrap(RootComponent, [
  FirebaseService,
  ROUTER_PROVIDERS,
  HTTP_PROVIDERS,
  provide(
    PLATFORM_DIRECTIVES, {useValue: [ROUTER_DIRECTIVES], multi: true}),
  provide(
    LocationStrategy, {useClass: HashLocationStrategy})
])
  .catch(err => console.error(err));


text:
package org.aludratest.log4testing.engine;

import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.aludratest.log4testing.TestCaseLog;
import org.aludratest.log4testing.TestStepFilter;
import org.aludratest.log4testing.TestSuiteLog;
import org.aludratest.log4testing.config.AbbreviatorConfiguration;
import org.aludratest.log4testing.config.InvalidConfigurationException;
import org.aludratest.log4testing.config.Log4TestingConfiguration;
import org.aludratest.log4testing.config.TestLogWriterConfiguration;
import org.aludratest.log4testing.config.TestStepFilterConfiguration;
import org.aludratest.log4testing.config.impl.XmlBasedLog4TestingConfiguration;
import org.aludratest.log4testing.output.LogWriterException;
import org.aludratest.log4testing.output.TestLogWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Main entry point for Test Frameworks or Adapter packages to use Log4Testing. To use Log4Testing, call one of the
 * newEngine() methods, and call {@link #applyTo(TestFramework)} on the created engine with your Test Framework
 * implementation.
 *
 * @author falbrech
 *
 */
public final class Log4TestingEngine implements TestFrameworkListener {

	private static final Logger LOG = LoggerFactory.getLogger(Log4TestingEngine.class);

	private List<TestLogWriter> writers = new ArrayList<TestLogWriter>();

	private List<WriterSpecificTestFrameworkListener> writerListeners = new ArrayList<WriterSpecificTestFrameworkListener>();

	private Log4TestingEngine(Log4TestingConfiguration configuration) {
		for (TestLogWriterConfiguration writerConfig : configuration.getTestLogWriterConfigurations()) {
			try {
				Class<?> writerClass = Class.forName(writerConfig.getWriterClassName());
				TestLogWriter writer = (TestLogWriter) writerClass.newInstance();
				writer.init(writerConfig.getWriterProperties());
				writers.add(writer);
				writerListeners.add(new WriterSpecificTestFrameworkListener(writer, configuration.getAbbreviatorConfiguration(),
						writerConfig));
			}
			catch (ClassNotFoundException e) {
				LOG.warn("TestLogWriter class " + writerConfig.getWriterClassName() + " not found", e);
			}
			catch (InstantiationException e) {
				LOG.warn("Could not instantiate TestLogWriter of class " + writerConfig.getWriterClassName(), e);
			}
			catch (IllegalAccessException e) {
				LOG.warn("Could not access empty constructor of TestLogWriter class " + writerConfig.getWriterClassName(), e);
			}
			catch (InvalidConfigurationException e) {
				LOG.warn("Could not configure TestLogWriter of class " + writerConfig.getWriterClassName(), e);
			}
		}
	}

	/**
	 * Creates a new engine which looks in the following locations for a log4testing.xml file to take its
	 * configuration from:
	 *

	 *
In the current Context Classloader's root

	 *
In the Classloader's root which was used to load Log4Testing

	 *
In the current working directory

	 *

	 * If no configuration file is found, the engine starts up with an "empty" configuration, i.e. no writer configured and thus
	 * no log to be written.
	 *
	 * @return A newly created Log4Testing engine a Test Framework can be hooked into.
	 */
	public static Log4TestingEngine newEngine() {
		return new Log4TestingEngine(new XmlBasedLog4TestingConfiguration());
	}

	/**
	 * Creates a new engine which first looks in the given location for its configuration, afterwards (if not found there) in its
	 * default locations (see {@link #newEngine()}).

	 * If no configuration file is found, the engine starts up with an "empty" configuration, i.e. no writer configured and thus
	 * no log to be written.
	 *
	 * @param xmlConfigurationLocation
	 *            Additional location to first scan for a configuration. Must be the full URL to the configuration XML file (not
	 *            to a directory).
	 * @return A newly created Log4Testing engine a Test Framework can be hooked into.
	 */
	public static Log4TestingEngine newEngine(URL xmlConfigurationLocation) {
		return new Log4TestingEngine(new XmlBasedLog4TestingConfiguration(xmlConfigurationLocation));
	}

	/**
	 * Creates a new engine with the given configuration to use.
	 *
	 * @param configuration
	 *            Configuration to use for the new engine, must not be null.
	 *
	 * @return A newly created Log4Testing engine a Test Framework can be hooked into.
	 */
	public static Log4TestingEngine newEngine(Log4TestingConfiguration configuration) {
		return new Log4TestingEngine(configuration);
	}

	/**
	 * Hooks this engine into the given Test Framework. The engine will add itself as a {@link TestFrameworkListener} to the given
	 * framework via its {@link TestFramework#addTestFrameworkListener(TestFrameworkListener)} method.
	 *
	 * @param framework
	 *            Framework to hook the engine into, must not be null.
	 */
	public void applyTo(TestFramework framework) {
		framework.addTestFrameworkListener(this);
	}

	@Override
	public void startingTestProcess(TestSuiteLog rootSuite) {
		for (WriterSpecificTestFrameworkListener listener : writerListeners) {
			listener.startingTestProcess(rootSuite);
		}
	}

	@Override
	public void startingTestSuite(TestSuiteLog suite) {
		for (WriterSpecificTestFrameworkListener listener : writerListeners) {
			listener.startingTestSuite(suite);
		}
	}

	@Override
	public void startingTestCase(TestCaseLog testCase) {
		for (WriterSpecificTestFrameworkListener listener : writerListeners) {
			listener.startingTestCase(testCase);
		}
	}

	@Override
	public void finishedTestCase(TestCaseLog testCase) {
		for (WriterSpecificTestFrameworkListener listener : writerListeners) {
			listener.finishedTestCase(testCase);
		}
	}

	@Override
	public void finishedTestSuite(TestSuiteLog suite) {
		for (WriterSpecificTestFrameworkListener listener : writerListeners) {
			listener.finishedTestSuite(suite);
		}
	}

	@Override
	public void finishedTestProcess(TestSuiteLog rootSuite) {
		for (WriterSpecificTestFrameworkListener listener : writerListeners) {
			listener.finishedTestProcess(rootSuite);
		}
	}

	private static class WriterSpecificTestFrameworkListener implements TestFrameworkListener {

		private TestLogWriter writer;

		private LogContext context;

		public WriterSpecificTestFrameworkListener(TestLogWriter writer, AbbreviatorConfiguration abbreviationConfig,
				TestLogWriterConfiguration writerConfig) {
			this.writer = writer;

			// create filters for writer
			List<TestStepFilter> filters;
			if (writerConfig.getTestStepFilters().isEmpty()) {
				filters = Collections.emptyList();
			}
			else {
				filters = new ArrayList<TestStepFilter>();
				for (TestStepFilterConfiguration filterConfig : writerConfig.getTestStepFilters()) {
					try {
						TestStepFilter filter = (TestStepFilter) Class.forName(filterConfig.getClassName()).newInstance();
						filter.init(filterConfig.getProperties());
						filters.add(filter);
					}
					catch (ClassNotFoundException e) {
						LOG.warn("Test Step Filter class not found: " + filterConfig.getClassName(), e);
					}
					catch (InstantiationException e) {
						LOG.warn("Could not instantiate Test Step Filter Class " + filterConfig.getClassName(), e);
					}
					catch (IllegalAccessException e) {
						LOG.warn("Could not access empty constructor of Test Step Filter Class " + filterConfig.getClassName(), e);
					}
					catch (InvalidConfigurationException e) {
						LOG.warn("Invalid configuration for Test Step Filter of Class " + filterConfig.getClassName(), e);
					}
				}
			}

			context = new LogContext(abbreviationConfig.getAbbreviations(), filters);
		}

		@Override
		public void startingTestProcess(TestSuiteLog rootSuite) {
			try {
				writer.startingTestProcess(new FilteringTestSuiteLog(rootSuite, context));
			}
			catch (LogWriterException e) {
				LOG.warn("Exception when logging to log writer", e);
			}
		}

		@Override
		public void startingTestSuite(TestSuiteLog suite) {
			try {
				writer.startingTestSuite(new FilteringTestSuiteLog(suite, context));
			}
			catch (LogWriterException e) {
				LOG.warn("Exception when logging to log writer", e);
			}
		}

		@Override
		public void startingTestCase(TestCaseLog testCase) {
			try {
				writer.startingTestCase(new FilteringTestCaseLog(testCase, context));
			}
			catch (LogWriterException e) {
				LOG.warn("Exception when logging to log writer", e);
			}
		}

		@Override
		public void finishedTestCase(TestCaseLog testCase) {
			try {
				writer.finishedTestCase(new FilteringTestCaseLog(testCase, context));
			}
			catch (LogWriterException e) {
				LOG.warn("Exception when logging to log writer", e);
			}
		}

		@Override
		public void finishedTestSuite(TestSuiteLog suite) {
			try {
				writer.finishedTestSuite(new FilteringTestSuiteLog(suite, context));
			}
			catch (LogWriterException e) {
				LOG.warn("Exception when logging to log writer", e);
			}
		}

		@Override
		public void finishedTestProcess(TestSuiteLog rootSuite) {
			try {
				writer.finishedTestProcess(new FilteringTestSuiteLog(rootSuite, context));
			}
			catch (LogWriterException e) {
				LOG.warn("Exception when logging to log writer", e);
			}
		}
	}

}


text:
package page;

import no.utgdev.sparkly.annotations.wsrs.Get;
import no.utgdev.sparkly.annotations.wsrs.Page;
import spark.Request;
import spark.Response;

import javax.inject.Inject;

@Page("/test")
public class TestPage {

    @Inject
    private TestDAO dao;

    @Get
    public Object handle(Request request, Response response) {
        return dao.getResp();
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.avs.fluent.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.management.ProxyResource;
import com.azure.resourcemanager.avs.models.WorkloadNetworkPublicIpProvisioningState;
import com.fasterxml.jackson.annotation.JsonProperty;

/** NSX Public IP Block. */
@Fluent
public final class WorkloadNetworkPublicIpInner extends ProxyResource {
    /*
     * Public IP Block properties
     */
    @JsonProperty(value = "properties")
    private WorkloadNetworkPublicIpProperties innerProperties;

    /** Creates an instance of WorkloadNetworkPublicIpInner class. */
    public WorkloadNetworkPublicIpInner() {
    }

    /**
     * Get the innerProperties property: Public IP Block properties.
     *
     * @return the innerProperties value.
     */
    private WorkloadNetworkPublicIpProperties innerProperties() {
        return this.innerProperties;
    }

    /**
     * Get the displayName property: Display name of the Public IP Block.
     *
     * @return the displayName value.
     */
    public String displayName() {
        return this.innerProperties() == null ? null : this.innerProperties().displayName();
    }

    /**
     * Set the displayName property: Display name of the Public IP Block.
     *
     * @param displayName the displayName value to set.
     * @return the WorkloadNetworkPublicIpInner object itself.
     */
    public WorkloadNetworkPublicIpInner withDisplayName(String displayName) {
        if (this.innerProperties() == null) {
            this.innerProperties = new WorkloadNetworkPublicIpProperties();
        }
        this.innerProperties().withDisplayName(displayName);
        return this;
    }

    /**
     * Get the numberOfPublicIPs property: Number of Public IPs requested.
     *
     * @return the numberOfPublicIPs value.
     */
    public Long numberOfPublicIPs() {
        return this.innerProperties() == null ? null : this.innerProperties().numberOfPublicIPs();
    }

    /**
     * Set the numberOfPublicIPs property: Number of Public IPs requested.
     *
     * @param numberOfPublicIPs the numberOfPublicIPs value to set.
     * @return the WorkloadNetworkPublicIpInner object itself.
     */
    public WorkloadNetworkPublicIpInner withNumberOfPublicIPs(Long numberOfPublicIPs) {
        if (this.innerProperties() == null) {
            this.innerProperties = new WorkloadNetworkPublicIpProperties();
        }
        this.innerProperties().withNumberOfPublicIPs(numberOfPublicIPs);
        return this;
    }

    /**
     * Get the publicIpBlock property: CIDR Block of the Public IP Block.
     *
     * @return the publicIpBlock value.
     */
    public String publicIpBlock() {
        return this.innerProperties() == null ? null : this.innerProperties().publicIpBlock();
    }

    /**
     * Get the provisioningState property: The provisioning state.
     *
     * @return the provisioningState value.
     */
    public WorkloadNetworkPublicIpProvisioningState provisioningState() {
        return this.innerProperties() == null ? null : this.innerProperties().provisioningState();
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (innerProperties() != null) {
            innerProperties().validate();
        }
    }
}


text:
Manualsidor

Med denna modul kan du söka igenom manualsidorna för ditt system på
samma sätt som om du använde <tt>man</tt>-kommandot. Skriv in det
kommando eller den funktion du vill söka efter, välj om du vill söka
efter exakt detta kommandonamn eller om du vill söka efter ord i
beskrivningen, välj avsnitt att söka i och tryck på <tt>Sök</tt>-knappen.

Om du väljer att söka efter exakt detta kommandonamn kommer manualsidan
för kommandot eller funktionen att visas om den finns. Om du söker i
beskrivningarna kommer du att få upp en lista över manualsidor där du
kan välja vilken sida du vill titta på.


text:
import json
import sys

def write_wikilinks_cont_person():
	try:
		f_json = open('data_extracted/person_lookup.json','r',encoding="utf8")
	except IOError:
		print('Need to create person_lookup.json first. (Execute write_personlist_by_type.py)')

	# Load person lookup created by write_personlist_by_type.py (Maps: *page of person* -> True, if it is a Person)
	person_lookup = json.load(f_json)
	print("Load complete: person_lookup.json")
	f_json.close()

	f_in = open('data_raw/wikipedia_links_en.ttl','r', encoding="utf8")
	f_out = open('data_extracted/filtered_wikilinks.txt','w+', encoding="utf8")

	wikilinks_assignment=dict()

	next(f_in) #First Line is comment with date
	for line in f_in:
		# Read wikilinks
		splits=line.split()
		subject=splits[0]
		value=splits[2]
		if person_lookup.get(subject)==True:
			#If it belongs to a person entitly keep it
			f_out.write(line)
			wikilinks_assignment[subject[1:-1]]=value[1:-1]

	f_in.close()
	f_out.close()

	with open('data_extracted/wikilinks_assignment.json','w+', encoding='utf8') as f_json:
		json.dump(wikilinks_assignment, f_json, ensure_ascii=False)

	print('write_wikilinks_cont_person - DONE')

if __name__ == "__main__":
	if len(sys.argv)>1:
		raise IOError("Overspecified")
	write_wikilinks_cont_person()


text:
/**
 * @constructor
 * @extends {WebInspector.RequestContentView}
 * @param {!WebInspector.NetworkRequest} request
 * @param {!WebInspector.View} responseView
 */
WebInspector.RequestPreviewView = function(request, responseView)
{
    WebInspector.RequestContentView.call(this, request);
    this._responseView = responseView;
}

WebInspector.RequestPreviewView.prototype = {
    contentLoaded: function()
    {
        if (!this.request.content && !this.request.contentError()) {
            if (!this._emptyView) {
                this._emptyView = this._createEmptyView();
                this._emptyView.show(this.element);
                this.innerView = this._emptyView;
            }
        } else {
            if (this._emptyView) {
                this._emptyView.detach();
                delete this._emptyView;
            }

            if (!this._previewView)
                this._previewView = this._createPreviewView();
            this._previewView.show(this.element);
            this.innerView = this._previewView;
        }
    },

    _createEmptyView: function()
    {
        return this._createMessageView(WebInspector.UIString("This request has no preview available."));
    },

    /**
     * @param {string} message
     * @return {!WebInspector.EmptyView}
     */
    _createMessageView: function(message)
    {
        return new WebInspector.EmptyView(message);
    },

    /**
     * @return {string}
     */
    _requestContent: function()
    {
        var content = this.request.content;
        return this.request.contentEncoded ? window.atob(content || "") : (content || "");
    },

    /**
     * @return {?WebInspector.RequestJSONView}
     */
    _jsonView: function()
    {
        var content = this._requestContent();
        var parsedJSON = WebInspector.RequestJSONView.parseJSON(content);
        return parsedJSON ? new WebInspector.RequestJSONView(this.request, parsedJSON) : null;
    },

    /**
     * @return {?WebInspector.XMLView}
     */
    _xmlView: function()
    {
        var content = this._requestContent();
        var parsedXML = WebInspector.XMLView.parseXML(content, this.request.mimeType);
        return parsedXML ? new WebInspector.XMLView(parsedXML) : null;
    },

    /**
     * @return {?WebInspector.RequestHTMLView}
     */
    _htmlErrorPreview: function()
    {
        var whitelist = ["text/html", "text/plain", "application/xhtml+xml"];
        if (whitelist.indexOf(this.request.mimeType) === -1)
            return null;

        var dataURL = this.request.asDataURL();
        if (dataURL === null)
            return null;

        return new WebInspector.RequestHTMLView(this.request, dataURL);
    },

    _createPreviewView: function()
    {
        if (this.request.contentError())
            return this._createMessageView(WebInspector.UIString("Failed to load response data"));

        var mimeType = this.request.mimeType || "";
        if (mimeType === "application/json" || mimeType.endsWith("+json")) {
            var jsonView = this._jsonView();
            if (jsonView)
                return jsonView;
        }

        if (this.request.hasErrorStatusCode()) {
            var htmlErrorPreview = this._htmlErrorPreview();
            if (htmlErrorPreview)
                return htmlErrorPreview;
        }

        var xmlView = this._xmlView();
        if (xmlView)
            return xmlView;

        if (this.request.resourceType() === WebInspector.resourceTypes.XHR) {
            var jsonView = this._jsonView();
            if (jsonView)
                return jsonView;
            var htmlErrorPreview = this._htmlErrorPreview();
            if (htmlErrorPreview)
                return htmlErrorPreview;
        }

        if (this._responseView.sourceView)
            return this._responseView.sourceView;

        if (this.request.resourceType() === WebInspector.resourceTypes.Other)
            return this._createEmptyView();

        return WebInspector.RequestView.nonSourceViewForRequest(this.request);
    },

    __proto__: WebInspector.RequestContentView.prototype
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Pap. 33: 105 (1951)

#### Original name
Cercospora sebastianiae R.E.D. Baker & W.T. Dale

### Remarks
null


text:
package org.odata4j.producer.inmemory;

import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.core4j.Enumerable;
import org.core4j.Func;
import org.core4j.Func1;
import org.core4j.Predicate1;
import org.odata4j.core.OAtomStreamEntity;
import org.odata4j.core.OCollection;
import org.odata4j.core.OCollections;
import org.odata4j.core.OComplexObject;
import org.odata4j.core.OComplexObjects;
import org.odata4j.core.OEntities;
import org.odata4j.core.OEntity;
import org.odata4j.core.OEntityId;
import org.odata4j.core.OEntityKey;
import org.odata4j.core.OExtension;
import org.odata4j.core.OFunctionParameter;
import org.odata4j.core.OLink;
import org.odata4j.core.OLinks;
import org.odata4j.core.OObject;
import org.odata4j.core.OProperties;
import org.odata4j.core.OProperty;
import org.odata4j.core.OSimpleObject;
import org.odata4j.core.OSimpleObjects;
import org.odata4j.core.OStructuralObject;
import org.odata4j.edm.EdmCollectionType;
import org.odata4j.edm.EdmComplexType;
import org.odata4j.edm.EdmDataServices;
import org.odata4j.edm.EdmDecorator;
import org.odata4j.edm.EdmEntitySet;
import org.odata4j.edm.EdmEntityType;
import org.odata4j.edm.EdmFunctionImport;
import org.odata4j.edm.EdmMultiplicity;
import org.odata4j.edm.EdmNavigationProperty;
import org.odata4j.edm.EdmProperty;
import org.odata4j.edm.EdmSimpleType;
import org.odata4j.edm.EdmStructuralType;
import org.odata4j.edm.EdmType;
import org.odata4j.exceptions.NotFoundException;
import org.odata4j.exceptions.NotImplementedException;
import org.odata4j.expression.BoolCommonExpression;
import org.odata4j.expression.OrderByExpression;
import org.odata4j.expression.OrderByExpression.Direction;
import org.odata4j.producer.BaseResponse;
import org.odata4j.producer.ContextStream;
import org.odata4j.producer.CountResponse;
import org.odata4j.producer.EntitiesResponse;
import org.odata4j.producer.EntityIdResponse;
import org.odata4j.producer.EntityQueryInfo;
import org.odata4j.producer.EntityResponse;
import org.odata4j.producer.InlineCount;
import org.odata4j.producer.ODataContext;
import org.odata4j.producer.ODataProducer;
import org.odata4j.producer.PropertyPathHelper;
import org.odata4j.producer.QueryInfo;
import org.odata4j.producer.Responses;
import org.odata4j.producer.edm.MetadataProducer;
import org.odata4j.producer.inmemory.InMemoryProducer.RequestContext.RequestType;

/**
 * An in-memory implementation of an ODATA Producer.  Uses the standard Java bean
 * and property model to access information within entities.
 */
public class InMemoryProducer implements ODataProducer {
  private static final boolean DUMP = false;

  private static void dump(String msg) {
    if (DUMP) System.out.println(msg);
  }

  public static final String ID_PROPNAME = "EntityId";

  private final String namespace;
  private final String containerName;
  private final int maxResults;
  // preserve the order of registration
  private final Map<String, InMemoryEntityInfo<?>> eis = new LinkedHashMap<String, InMemoryEntityInfo<?>>();
  private final Map<String, InMemoryComplexTypeInfo<?>> complexTypes = new LinkedHashMap<String, InMemoryComplexTypeInfo<?>>();
  private EdmDataServices metadata;
  private final EdmDecorator decorator;
  private final MetadataProducer metadataProducer;
  private final InMemoryTypeMapping typeMapping;

  private boolean includeNullPropertyValues = true;
  private final boolean flattenEdm;

  private static final int DEFAULT_MAX_RESULTS = 100;

  /**
   * Creates a new instance of an in-memory POJO producer.
   *
   * @param namespace  the namespace of the schema registrations
   */
  public InMemoryProducer(String namespace) {
    this(namespace, DEFAULT_MAX_RESULTS);
  }

  /**
   * Creates a new instance of an in-memory POJO producer.
   *
   * @param namespace  the namespace of the schema registrations
   * @param maxResults  the maximum number of entities to return in a single call
   */
  public InMemoryProducer(String namespace, int maxResults) {
    this(namespace, null, maxResults, null, null);
  }

  /**
   * Creates a new instance of an in-memory POJO producer.
   *
   * @param namespace  the namespace of the schema registrations
   * @param containerName  the container name for generated metadata
   * @param maxResults  the maximum number of entities to return in a single call
   * @param decorator  a decorator to use for edm customizations
   * @param typeMapping  optional mapping between java types and edm types, null for default
   */
  public InMemoryProducer(String namespace, String containerName, int maxResults, EdmDecorator decorator, InMemoryTypeMapping typeMapping) {
    this(namespace, containerName, maxResults, decorator, typeMapping,
        true); // legacy: flatten edm
  }

  public InMemoryProducer(String namespace, String containerName, int maxResults, EdmDecorator decorator, InMemoryTypeMapping typeMapping,
      boolean flattenEdm) {
    this.namespace = namespace;
    this.containerName = containerName != null && !containerName.isEmpty() ? containerName : "Container";
    this.maxResults = maxResults;
    this.decorator = decorator;
    this.metadataProducer = new MetadataProducer(this, decorator);
    this.typeMapping = typeMapping == null ? InMemoryTypeMapping.DEFAULT : typeMapping;
    this.flattenEdm = flattenEdm;
  }

  @Override
  public EdmDataServices getMetadata() {
    if (metadata == null) {
      metadata = newEdmGenerator(namespace, typeMapping, ID_PROPNAME, eis, complexTypes).generateEdm(decorator).build();
    }
    return metadata;
  }

  public String getContainerName() {
    return containerName;
  }

  protected InMemoryEdmGenerator newEdmGenerator(String namespace, InMemoryTypeMapping typeMapping, String idPropName, Map<String, InMemoryEntityInfo<?>> eis,
      Map<String, InMemoryComplexTypeInfo<?>> complexTypesInfo) {
    return new InMemoryEdmGenerator(namespace, containerName, typeMapping, ID_PROPNAME, eis, complexTypesInfo, this.flattenEdm);
  }

  @Override
  public MetadataProducer getMetadataProducer() {
    return metadataProducer;
  }

  @Override
  public void close() {

  }

  public void setIncludeNullPropertyValues(boolean value) {
    this.includeNullPropertyValues = value;
  }

  /**
   * Registers a POJO class as an EdmComplexType.
   *
   * @param complexTypeClass    The POJO Class
   * @param typeName            The name of the EdmComplexType
   */
  public <TEntity> void registerComplexType(Class<TEntity> complexTypeClass, String typeName) {
    registerComplexType(complexTypeClass, typeName,
        new EnumsAsStringsPropertyModelDelegate(new BeanBasedPropertyModel(complexTypeClass, this.flattenEdm)));
  }

  public <TEntity> void registerComplexType(Class<TEntity> complexTypeClass, String typeName, PropertyModel propertyModel) {
    InMemoryComplexTypeInfo<TEntity> i = new InMemoryComplexTypeInfo<TEntity>();
    i.typeName = (typeName == null) ? complexTypeClass.getSimpleName() : typeName;
    i.entityClass = complexTypeClass;
    i.propertyModel = propertyModel;

    complexTypes.put(i.typeName, i);
    metadata = null;
  }

  /**
   * Registers a new entity based on a POJO, with support for composite keys.
   *
   * @param entityClass  the class of the entities that are to be stored in the set
   * @param entitySetName  the alias the set will be known by; this is what is used in the OData url
   * @param get  a function to iterate over the elements in the set
   * @param keys  one or more keys for the entity
   */
  public <TEntity> void register(Class<TEntity> entityClass, String entitySetName, Func<Iterable<TEntity>> get, String... keys) {
    register(entityClass, entitySetName, entitySetName, get, keys);
  }

  /**
   * Registers a new entity based on a POJO, with support for composite keys.
   *
   * @param entityClass  the class of the entities that are to be stored in the set
   * @param entitySetName  the alias the set will be known by; this is what is used in the OData url
   * @param entityTypeName  type name of the entity
   * @param get  a function to iterate over the elements in the set
   * @param keys  one or more keys for the entity
   */
  public <TEntity> void register(Class<TEntity> entityClass, String entitySetName, String entityTypeName, Func<Iterable<TEntity>> get, String... keys) {
    PropertyModel model = new BeanBasedPropertyModel(entityClass, this.flattenEdm);
    model = new EnumsAsStringsPropertyModelDelegate(model);
    register(entityClass, model, entitySetName, entityTypeName, get, keys);
  }

  /**
   * Registers a new entity set based on a POJO type using the default property model.
   */
  public <TEntity, TKey> void register(Class<TEntity> entityClass, Class<TKey> keyClass, String entitySetName, Func<Iterable<TEntity>> get, Func1<TEntity, TKey> id) {
    PropertyModel model = new BeanBasedPropertyModel(entityClass, this.flattenEdm);
    model = new EnumsAsStringsPropertyModelDelegate(model);
    model = new EntityIdFunctionPropertyModelDelegate<TEntity, TKey>(model, ID_PROPNAME, keyClass, id);
    register(entityClass, model, entitySetName, get, ID_PROPNAME);
  }

  /**
   * Registers a new entity set based on a POJO type and a property model.
   *
   * @param entityClass  the class of the entities that are to be stored in the set
   * @param propertyModel a way to get/set properties on the POJO
   * @param entitySetName  the alias the set will be known by; this is what is used in the ODATA URL
   * @param get  a function to iterate over the elements in the set
   * @param keys  one or more keys for the entity
   */
  public <TEntity, TKey> void register(
      Class<TEntity> entityClass,
      PropertyModel propertyModel,
      String entitySetName,
      Func<Iterable<TEntity>> get,
      String... keys) {
    register(entityClass, propertyModel, entitySetName, entitySetName, get, keys);
  }

  public <TEntity> void register(
      final Class<TEntity> entityClass,
      final PropertyModel propertyModel,
      final String entitySetName,
      final String entityTypeName,
      final Func<Iterable<TEntity>> get,
      final String... keys) {
    register(entityClass, propertyModel, entitySetName, entityTypeName,
        get, null, keys);
  }

  public <TEntity> void register(
      final Class<TEntity> entityClass,
      final PropertyModel propertyModel,
      final String entitySetName,
      final String entityTypeName,
      final Func<Iterable<TEntity>> get,
      final Func1<RequestContext, Iterable<TEntity>> getWithContext,
      final String... keys) {

    InMemoryEntityInfo<TEntity> ei = new InMemoryEntityInfo<TEntity>();
    ei.entitySetName = entitySetName;
    ei.entityTypeName = entityTypeName;
    ei.properties = propertyModel;
    ei.get = get;
    ei.getWithContext = getWithContext;
    ei.keys = keys;
    ei.entityClass = entityClass;
    ei.hasStream = OAtomStreamEntity.class.isAssignableFrom(entityClass);

    ei.id = new Func1<Object, HashMap<String, Object>>() {
      @Override
      public HashMap<String, Object> apply(Object input) {
        HashMap<String, Object> values = new HashMap<String, Object>();
        for (String key : keys) {
          values.put(key, eis.get(entitySetName).properties.getPropertyValue(input, key));
        }
        return values;
      }
    };

    eis.put(entitySetName, ei);
    metadata = null;
  }

  protected InMemoryComplexTypeInfo<?> findComplexTypeInfoForClass(Class<?> clazz) {
    // drill down the hierarchy as far as we can go.
    InMemoryComplexTypeInfo<?> found = null;

    for (InMemoryComplexTypeInfo<?> typeInfo : this.complexTypes.values()) {
      if (typeInfo.entityClass.equals(clazz)) {
        return typeInfo; // as far down as we can go
      } else if (typeInfo.entityClass.isAssignableFrom(clazz)) {
        // somewhere in the ancestors of clazz
        if (null == found || found.entityClass.isAssignableFrom(typeInfo.entityClass)) {
          // we found a lower ancestor
          found = typeInfo;
        }
      }
    }

    return found;
  }

  protected InMemoryEntityInfo<?> findEntityInfoForClass(Class<?> clazz) {
    // drill down the hierarchy as far as we can go.
    InMemoryEntityInfo<?> found = null;

    for (InMemoryEntityInfo<?> typeInfo : this.eis.values()) {
      if (typeInfo.entityClass.equals(clazz)) {
        return typeInfo; // as far down as we can go
      } else if (typeInfo.entityClass.isAssignableFrom(clazz)) {
        // somewhere in the ancestors of clazz
        if (null == found || found.entityClass.isAssignableFrom(typeInfo.entityClass)) {
          // we found a lower ancestor
          found = typeInfo;
        }
      }
    }

    return found;
  }

  /**
   * Transforms a POJO into a list of OProperties based on a given
   * EdmStructuralType.
   *
   * @param obj the POJO to transform
   * @param propertyModel the PropertyModel to use to access POJO class
   * structure and values.
   * @param structuralType the EdmStructuralType
   * @param properties put properties into this list.
   */
  protected void addPropertiesFromObject(Object obj, PropertyModel propertyModel, EdmStructuralType structuralType, List<OProperty<?>> properties, PropertyPathHelper pathHelper) {
    dump("addPropertiesFromObject: " + obj.getClass().getName());
    for (Iterator<EdmProperty> it = structuralType.getProperties().iterator(); it.hasNext();) {
      EdmProperty property = it.next();

      // $select projections not allowed for complex types....hmmh...why?
      if (structuralType instanceof EdmEntityType && !pathHelper.isSelected(property.getName())) {
        continue;
      }

      Object value = propertyModel.getPropertyValue(obj, property.getName());
      dump("  prop: " + property.getName() + " val: " + value);
      if (value == null && !this.includeNullPropertyValues) {
        // this is not permitted by the spec but makes debugging wide entity types
        // much easier.
        continue;
      }

      if (property.getCollectionKind() == EdmProperty.CollectionKind.NONE) {
        if (property.getType().isSimple()) {
          properties.add(OProperties.simple(property.getName(), (EdmSimpleType<? extends Object>) property.getType(), value));
        } else {
          // complex.
          if (value == null) {
            properties.add(OProperties.complex(property.getName(), (EdmComplexType) property.getType(), null));
          } else {
            Class<?> propType = propertyModel.getPropertyType(property.getName());
            InMemoryComplexTypeInfo<?> typeInfo = findComplexTypeInfoForClass(propType);
            if (typeInfo == null) {
              continue;
            }
            List<OProperty<?>> cprops = new ArrayList<OProperty<?>>();
            addPropertiesFromObject(value, typeInfo.getPropertyModel(), (EdmComplexType) property.getType(), cprops, pathHelper);
            properties.add(OProperties.complex(property.getName(), (EdmComplexType) property.getType(), cprops));
          }
        }
      } else {
        // collection.
        Iterable<?> values = propertyModel.getCollectionValue(obj, property.getName());
        OCollection.Builder<OObject> b = OCollections.newBuilder(property.getType());
        if (values != null) {
          Class<?> propType = propertyModel.getCollectionElementType(property.getName());
          InMemoryComplexTypeInfo<?> typeInfo = property.getType().isSimple() ? null : findComplexTypeInfoForClass(propType);
          if ((!property.getType().isSimple()) && typeInfo == null) {
            continue;
          }
          for (Object v : values) {
            if (property.getType().isSimple()) {
              b.add(OSimpleObjects.create((EdmSimpleType<?>) property.getType(), v));
            } else {
              List<OProperty<?>> cprops = new ArrayList<OProperty<?>>();
              addPropertiesFromObject(v, typeInfo.getPropertyModel(), (EdmComplexType) property.getType(), cprops, pathHelper);
              b.add(OComplexObjects.create((EdmComplexType) property.getType(), cprops));
            }
          }
        }
        properties.add(OProperties.collection(property.getName(),
            // hmmmh...is something is wrong here if I have to create a new EdmCollectionType?
            new EdmCollectionType(EdmProperty.CollectionKind.Collection,
                property.getType()), b.build()));
      }
    }
    dump("done addPropertiesFromObject: " + obj.getClass().getName());
  }

  protected OEntity toOEntity(EdmEntitySet ees, Object obj, PropertyPathHelper pathHelper) {

    InMemoryEntityInfo<?> ei = eis.get(ees.getName());
    final List<OLink> links = new ArrayList<OLink>();
    final List<OProperty<?>> properties = new ArrayList<OProperty<?>>();

    Map<String, Object> keyKVPair = new HashMap<String, Object>();
    for (String key : ei.getKeys()) {
      Object keyValue = ei.getPropertyModel().getPropertyValue(obj, key);
      keyKVPair.put(key, keyValue);
    }

    // the entity set being queried may contain objects of subtypes of the entity set's type
    EdmEntityType edmEntityType = (EdmEntityType) this.getMetadata().findEdmEntityType(namespace + "." + ei.getEntityTypeName());

    // "regular" properties
    addPropertiesFromObject(obj, ei.getPropertyModel(), edmEntityType, properties, pathHelper);

    // navigation properties

    for (final EdmNavigationProperty navProp : edmEntityType.getNavigationProperties()) {

      if (!pathHelper.isSelected(navProp.getName())) {
        continue;
      }

      if (!pathHelper.isExpanded(navProp.getName())) {
        // defer
        if (navProp.getToRole().getMultiplicity() == EdmMultiplicity.MANY) {
          links.add(OLinks.relatedEntities(null, navProp.getName(), null));
        } else {
          links.add(OLinks.relatedEntity(null, navProp.getName(), null));
        }
      } else {
        // inline
        pathHelper.navigate(navProp.getName());
        if (navProp.getToRole().getMultiplicity() == EdmMultiplicity.MANY) {
          List<OEntity> relatedEntities = new ArrayList<OEntity>();

          EdmEntitySet relEntitySet = null;

          for (final Object entity : getRelatedPojos(navProp, obj, ei)) {
            if (relEntitySet == null) {
              InMemoryEntityInfo<?> oei = this.findEntityInfoForClass(entity.getClass());
              relEntitySet = getMetadata().getEdmEntitySet(oei.getEntitySetName());
            }

            relatedEntities.add(toOEntity(relEntitySet, entity, pathHelper));
          }

          // relation and href will be filled in later for atom or json
          links.add(OLinks.relatedEntitiesInline(null, navProp.getName(), null, relatedEntities));
        } else {
          final Object entity = ei.getPropertyModel().getPropertyValue(obj, navProp.getName());
          OEntity relatedEntity = null;

          if (entity != null) {
            InMemoryEntityInfo<?> oei = this.findEntityInfoForClass(entity.getClass());
            EdmEntitySet relEntitySet = getMetadata().getEdmEntitySet(oei.getEntitySetName());
            relatedEntity = toOEntity(relEntitySet, entity, pathHelper);
          }
          links.add(OLinks.relatedEntityInline(null, navProp.getName(), null, relatedEntity));
        }

        pathHelper.popPath();
      }
    }

    return OEntities.create(ees, edmEntityType, OEntityKey.create(keyKVPair), properties, links, obj);
  }

  protected Iterable<?> getRelatedPojos(EdmNavigationProperty navProp, Object srcObject, InMemoryEntityInfo<?> srcInfo) {
    if (navProp.getToRole().getMultiplicity() == EdmMultiplicity.MANY) {
      Iterable<?> i = srcInfo.getPropertyModel().getCollectionValue(srcObject, navProp.getName());
      return i == null ? Collections.EMPTY_LIST : i;
    } else {
      // can be null
      return Collections.singletonList(srcInfo.getPropertyModel().getPropertyValue(srcObject, navProp.getName()));
    }
  }

  private static Predicate1<Object> filterToPredicate(final BoolCommonExpression filter, final PropertyModel properties) {
    return new Predicate1<Object>() {
      public boolean apply(Object input) {
        return InMemoryEvaluation.evaluate(filter, input, properties);
      }
    };
  }

  @Override
  public EntitiesResponse getEntities(ODataContext context, String entitySetName, final QueryInfo queryInfo) {

    final RequestContext rc = RequestContext.newBuilder(RequestType.GetEntities)
        .entitySetName(entitySetName)
        .entitySet(getMetadata().getEdmEntitySet(entitySetName))
        .queryInfo(queryInfo)
        .odataContext(context)
        .pathHelper(new PropertyPathHelper(queryInfo)).build();

    final InMemoryEntityInfo<?> ei = eis.get(entitySetName);

    Enumerable<Object> objects = ei.getWithContext == null
        ? Enumerable.create(ei.get.apply()).cast(Object.class)
        : Enumerable.create(ei.getWithContext.apply(rc)).cast(Object.class);

    return getEntitiesResponse(rc, rc.getEntitySet(), objects, ei.getPropertyModel());
  }

  protected EntitiesResponse getEntitiesResponse(final RequestContext rc, final EdmEntitySet targetEntitySet, Enumerable<Object> objects, PropertyModel propertyModel) {
    // apply filter
    final QueryInfo queryInfo = rc.getQueryInfo();
    if (queryInfo != null && queryInfo.filter != null) {
      objects = objects.where(filterToPredicate(queryInfo.filter, propertyModel));
    }

    // compute inlineCount, must be done after applying filter
    Integer inlineCount = null;
    if (queryInfo != null && queryInfo.inlineCount == InlineCount.ALLPAGES) {
      objects = Enumerable.create(objects.toList()); // materialize up front, since we're about to count
      inlineCount = objects.count();
    }

    // apply ordering
    if (queryInfo != null && queryInfo.orderBy != null) {
      objects = orderBy(objects, queryInfo.orderBy, propertyModel);
    }

    // work with oentities
    Enumerable<OEntity> entities = objects.select(new Func1<Object, OEntity>() {
      @Override
      public OEntity apply(Object input) {
        return toOEntity(targetEntitySet, input, rc.getPathHelper());
      }
    });

    // skip records by $skipToken
    if (queryInfo != null && queryInfo.skipToken != null) {
      final Boolean[] skipping = new Boolean[] { true };
      entities = entities.skipWhile(new Predicate1<OEntity>() {
        @Override
        public boolean apply(OEntity input) {
          if (skipping[0]) {
            String inputKey = input.getEntityKey().toKeyString();
            if (queryInfo.skipToken.equals(inputKey)) skipping[0] = false;
            return true;
          }
          return false;
        }
      });
    }

    // skip records by $skip amount
    if (queryInfo != null && queryInfo.skip != null) {
      entities = entities.skip(queryInfo.skip);
    }

    // apply limit
    int limit = this.maxResults;
    if (queryInfo != null && queryInfo.top != null && queryInfo.top < limit) {
      limit = queryInfo.top;
    }
    entities = entities.take(limit + 1);

    // materialize OEntities
    List<OEntity> entitiesList = entities.toList();

    // determine skipToken if necessary
    String skipToken = null;
    if (entitiesList.size() > limit) {
      entitiesList = Enumerable.create(entitiesList).take(limit).toList();
      skipToken = entitiesList.size() == 0 ? null : Enumerable.create(entitiesList).last().getEntityKey().toKeyString();
    }

    return Responses.entities(entitiesList, targetEntitySet, inlineCount, skipToken);

  }

  @Override
  public CountResponse getEntitiesCount(ODataContext context, String entitySetName, final QueryInfo queryInfo) {

    final RequestContext rc = RequestContext.newBuilder(RequestType.GetEntitiesCount)
        .entitySetName(entitySetName)
        .entitySet(getMetadata().getEdmEntitySet(entitySetName))
        .queryInfo(queryInfo)
        .odataContext(context)
        .build();

    final InMemoryEntityInfo<?> ei = eis.get(entitySetName);

    final PropertyPathHelper pathHelper = new PropertyPathHelper(queryInfo);

    Enumerable<Object> objects = ei.getWithContext == null
        ? Enumerable.create(ei.get.apply()).cast(Object.class)
        : Enumerable.create(ei.getWithContext.apply(rc)).cast(Object.class);

    // apply filter
    if (queryInfo != null && queryInfo.filter != null) {
      objects = objects.where(filterToPredicate(queryInfo.filter, ei.properties));
    }

    // inlineCount is not applicable to $count queries
    if (queryInfo != null && queryInfo.inlineCount == InlineCount.ALLPAGES) {
      throw new UnsupportedOperationException("$inlinecount cannot be applied to the resource segment '$count'");
    }

    // ignore ordering for count

    // work with oentities.
    Enumerable<OEntity> entities = objects.select(new Func1<Object, OEntity>() {
      @Override
      public OEntity apply(Object input) {
        return toOEntity(rc.getEntitySet(), input, pathHelper);
      }
    });

    // skipToken is not applicable to $count queries
    if (queryInfo != null && queryInfo.skipToken != null) {
      throw new UnsupportedOperationException("Skip tokens can only be provided for requests that return collections of entities.");
    }

    // skip records by $skip amount
    // http://services.odata.org/Northwind/Northwind.svc/Customers/$count/?$skip=5
    if (queryInfo != null && queryInfo.skip != null) {
      entities = entities.skip(queryInfo.skip);
    }

    // apply $top.  maxResults is not applicable to $count but $top is.
    // http://services.odata.org/Northwind/Northwind.svc/Customers/$count/?$top=55
    int limit = Integer.MAX_VALUE;
    if (queryInfo != null && queryInfo.top != null && queryInfo.top < limit) {
      limit = queryInfo.top;
    }
    entities = entities.take(limit);

    return Responses.count(entities.count());
  }

  private Enumerable<Object> orderBy(Enumerable<Object> iter, List<OrderByExpression> orderBys, final PropertyModel properties) {
    for (final OrderByExpression orderBy : Enumerable.create(orderBys).reverse())
      iter = iter.orderBy(new Comparator<Object>() {
        @SuppressWarnings({ "unchecked", "rawtypes" })
        public int compare(Object o1, Object o2) {
          Comparable lhs = (Comparable) InMemoryEvaluation.evaluate(orderBy.getExpression(), o1, properties);
          Comparable rhs = (Comparable) InMemoryEvaluation.evaluate(orderBy.getExpression(), o2, properties);
          return (orderBy.getDirection() == Direction.ASCENDING ? 1 : -1) * lhs.compareTo(rhs);
        }
      });
    return iter;
  }

  @Override
  public EntityResponse getEntity(ODataContext context, final String entitySetName, final OEntityKey entityKey, final EntityQueryInfo queryInfo) {

    PropertyPathHelper pathHelper = new PropertyPathHelper(queryInfo);

    RequestContext rc = RequestContext.newBuilder(RequestType.GetEntity)
        .entitySetName(entitySetName)
        .entitySet(getMetadata()
            .getEdmEntitySet(entitySetName))
        .entityKey(entityKey)
        .queryInfo(queryInfo)
        .pathHelper(pathHelper)
        .odataContext(context).build();

    final Object rt = getEntityPojo(rc);
    if (rt == null)
      throw new NotFoundException("No entity found in entityset " + entitySetName
          + " for key " + entityKey.toKeyStringWithoutParentheses()
          + " and query info " + queryInfo);

    OEntity oe = toOEntity(rc.getEntitySet(), rt, rc.getPathHelper());

    return Responses.entity(oe);
  }

  @Override
  public void mergeEntity(ODataContext context, String entitySetName, OEntity entity) {
    throw new NotImplementedException();
  }

  @Override
  public void updateEntity(ODataContext context, String entitySetName, OEntity entity) {
    throw new NotImplementedException();
  }

  @Override
  public void deleteEntity(ODataContext context, String entitySetName, OEntityKey entityKey) {
    throw new NotImplementedException();
  }

  @Override
  public EntityResponse createEntity(ODataContext context, String entitySetName, OEntity entity) {
    throw new NotImplementedException();
  }

  @Override
  public EntityResponse createEntity(ODataContext context, String entitySetName, OEntityKey entityKey, String navProp, OEntity entity) {
    throw new NotImplementedException();
  }

  @Override
  public BaseResponse getNavProperty(ODataContext context, String entitySetName, OEntityKey entityKey, String navProp, QueryInfo queryInfo) {

    RequestContext rc = RequestContext.newBuilder(RequestType.GetNavProperty)
        .entitySetName(entitySetName)
        .entitySet(getMetadata().getEdmEntitySet(entitySetName))
        .entityKey(entityKey)
        .navPropName(navProp)
        .queryInfo(queryInfo)
        .pathHelper(new PropertyPathHelper(queryInfo))
        .odataContext(context)
        .build();

    EdmNavigationProperty navProperty = rc.getEntitySet().getType().findNavigationProperty(navProp);
    if (navProperty != null) {
      return getNavProperty(navProperty, rc);
    }

    // not a NavigationProperty:

    EdmProperty edmProperty = rc.getEntitySet().getType().findProperty(navProp);
    if (edmProperty == null)
      throw new NotFoundException("Property " + navProp + " is not found");
    // currently only simple types are supported
    EdmType edmType = edmProperty.getType();

    if (!edmType.isSimple())
      throw new NotImplementedException("Only simple types are supported. Property type is '" + edmType.getFullyQualifiedTypeName() + "'");

    // get property value...
    InMemoryEntityInfo<?> entityInfo = eis.get(entitySetName);
    Object target = getEntityPojo(rc);
    Object propertyValue = entityInfo.properties.getPropertyValue(target, navProp);
    // ... and create OProperty
    OProperty<?> property = OProperties.simple(navProp, (EdmSimpleType<?>) edmType, propertyValue);

    return Responses.property(property);
  }

  protected EdmEntitySet findEntitySetForNavProperty(EdmNavigationProperty navProp) {
    EdmEntityType et = navProp.getToRole().getType();
    // assumes one set per type...
    for (EdmEntitySet set : this.getMetadata().getEntitySets()) {
      if (set.getType().equals(et)) {
        return set;
      }
    }
    return null;
  }

  /**
   * Gets the entity(s) on the target end of a NavigationProperty.
   *
   * @param navProp  the navigation property
   * @param rc  the request context
   * @return a BaseResponse with either a single Entity (can be null) or a set of entities.
   */
  protected BaseResponse getNavProperty(EdmNavigationProperty navProp, RequestContext rc) {

    // First, get the source POJO.
    Object obj = getEntityPojo(rc);
    Iterable relatedPojos = this.getRelatedPojos(navProp, obj, this.findEntityInfoForClass(obj.getClass()));

    EdmEntitySet targetEntitySet = findEntitySetForNavProperty(navProp);

    if (navProp.getToRole().getMultiplicity() == EdmMultiplicity.MANY) {
      // apply filter, orderby, etc.
      return getEntitiesResponse(rc, targetEntitySet, Enumerable.create(relatedPojos), eis.get(targetEntitySet.getName()).getPropertyModel());
    } else {
      return Responses.entity(this.toOEntity(targetEntitySet, relatedPojos.iterator().next(), rc.getPathHelper()));
    }
  }

  @Override
  public CountResponse getNavPropertyCount(ODataContext context, String entitySetName, OEntityKey entityKey, String navProp, QueryInfo queryInfo) {
    throw new NotImplementedException();
  }

  @Override
  public EntityIdResponse getLinks(ODataContext context, OEntityId sourceEntity, String targetNavProp) {
    throw new NotImplementedException();
  }

  @Override
  public void createLink(ODataContext context, OEntityId sourceEntity, String targetNavProp, OEntityId targetEntity) {
    throw new NotImplementedException();
  }

  @Override
  public void updateLink(ODataContext context, OEntityId sourceEntity, String targetNavProp, OEntityKey oldTargetEntityKey, OEntityId newTargetEntity) {
    throw new NotImplementedException();
  }

  @Override
  public void deleteLink(ODataContext context, OEntityId sourceEntity, String targetNavProp, OEntityKey targetEntityKey) {
    throw new NotImplementedException();
  }

  @Override
  public BaseResponse callFunction(ODataContext context, EdmFunctionImport name, java.util.Map<String, OFunctionParameter> params, QueryInfo queryInfo) {
    throw new NotImplementedException();
  }

  @Override
  public <TExtension extends OExtension<ODataProducer>> TExtension findExtension(Class<TExtension> clazz) {
    return null;
  }

  public static class RequestContext {

    public enum RequestType {
      GetEntity, GetEntities, GetEntitiesCount, GetNavProperty
    };

    public final RequestType requestType;
    private final String entitySetName;
    private EdmEntitySet entitySet;
    private final String navPropName;
    private final OEntityKey entityKey;
    private final QueryInfo queryInfo;
    private final PropertyPathHelper pathHelper;
    private ODataContext odataContext;

    public RequestType getRequestType() {
      return requestType;
    }

    public String getEntitySetName() {
      return entitySetName;
    }

    public EdmEntitySet getEntitySet() {
      return entitySet;
    }

    public String getNavPropName() {
      return navPropName;
    }

    public OEntityKey getEntityKey() {
      return entityKey;
    }

    public QueryInfo getQueryInfo() {
      return queryInfo;
    }

    public PropertyPathHelper getPathHelper() {
      return pathHelper;
    }

    public ODataContext getODataContext() {
      return odataContext;
    }

    public static Builder newBuilder(RequestType requestType) {
      return new Builder().requestType(requestType);
    }

    public static class Builder {

      private RequestType requestType;
      private String entitySetName;
      private EdmEntitySet entitySet;
      private String navPropName;
      private OEntityKey entityKey;
      private QueryInfo queryInfo;
      private PropertyPathHelper pathHelper;
      private ODataContext odataContext;

      public Builder requestType(RequestType value) {
        this.requestType = value;
        return this;
      }

      public Builder entitySetName(String value) {
        this.entitySetName = value;
        return this;
      }

      public Builder entitySet(EdmEntitySet value) {
        this.entitySet = value;
        return this;
      }

      public Builder navPropName(String value) {
        this.navPropName = value;
        return this;
      }

      public Builder entityKey(OEntityKey value) {
        this.entityKey = value;
        return this;
      }

      public Builder queryInfo(QueryInfo value) {
        this.queryInfo = value;
        return this;
      }

      public Builder pathHelper(PropertyPathHelper value) {
        this.pathHelper = value;
        return this;
      }

      public Builder odataContext(ODataContext value) {
        this.odataContext = value;
        return this;
      }

      public RequestContext build() {
        return new RequestContext(requestType, entitySetName, entitySet, navPropName, entityKey, queryInfo, pathHelper, odataContext);
      }
    }

    private RequestContext(RequestType requestType, String entitySetName, EdmEntitySet entitySet,
        String navPropName, OEntityKey entityKey, QueryInfo queryInfo, PropertyPathHelper pathHelper,
        ODataContext odataContext) {
      this.requestType = requestType;
      this.entitySetName = entitySetName;
      this.entitySet = entitySet;
      this.navPropName = navPropName;
      this.entityKey = entityKey;
      this.queryInfo = queryInfo;
      this.pathHelper = pathHelper;
      this.odataContext = odataContext;
    }
  }

  /**
   * Given an entity set and an entity key, returns the pojo that is that entity instance.
   * The default implementation iterates over the entire set of pojos to find the
   * desired instance.
   *
   * @param rc  the current ReqeustContext, may be valuable to the ei.getWithContext impl
   * @return the pojo
   */
  @SuppressWarnings("unchecked")
  protected Object getEntityPojo(final RequestContext rc) {
    final InMemoryEntityInfo<?> ei = eis.get(rc.getEntitySetName());

    final String[] keyList = ei.keys;

    Iterable<Object> iter = ei.getWithContext == null ? ((Iterable<Object>) ei.get.apply())
        : ((Iterable<Object>) ei.getWithContext.apply(rc));

    final Object rt = Enumerable.create(iter).firstOrNull(new Predicate1<Object>() {
      public boolean apply(Object input) {
        HashMap<String, Object> idObjectMap = ei.id.apply(input);

        if (keyList.length == 1) {
          Object idValue = rc.getEntityKey().asSingleValue();
          return idObjectMap.get(keyList[0]).equals(idValue);
        } else if (keyList.length > 1) {
          for (String key : keyList) {
            Object curValue = null;
            Iterator<OProperty<?>> keyProps = rc.getEntityKey().asComplexProperties().iterator();
            while (keyProps.hasNext()) {
              OProperty<?> keyProp = keyProps.next();
              if (keyProp.getName().equalsIgnoreCase(key)) {
                curValue = keyProp.getValue();
              }
            }
            if (curValue == null) {
              return false;
            } else if (!idObjectMap.get(key).equals(curValue)) {
              return false;
            }
          }
          return true;
        } else {
          return false;
        }
      }
    });
    return rt;
  }

  private enum TriggerType {
    Before, After
  };

  protected void fireUnmarshalEvent(Object pojo, OStructuralObject sobj, TriggerType ttype)
      throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    try {
      Method m = pojo.getClass().getMethod(ttype == TriggerType.Before ? "beforeOEntityUnmarshal" : "afterOEntityUnmarshal", OStructuralObject.class);
      if (m != null) {
        m.invoke(pojo, sobj);
      }
    } catch (NoSuchMethodException ex) {}
  }

  /**
   * Transforms an OComplexObject into a POJO of the given class
   */
  public <T> T toPojo(OComplexObject entity, Class<T> pojoClass) throws InstantiationException,
      IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    InMemoryComplexTypeInfo<?> e = this.findComplexTypeInfoForClass(pojoClass);

    T pojo = fillInPojo(entity, this.getMetadata().findEdmComplexType(
        this.namespace + "." + e.getTypeName()), e.getPropertyModel(), pojoClass);

    fireUnmarshalEvent(pojo, entity, TriggerType.After);
    return pojo;
  }

  /**
   * Populates a new POJO instance of type pojoClass using data from the given structural object.
   */
  protected <T> T fillInPojo(OStructuralObject sobj, EdmStructuralType stype, PropertyModel propertyModel,
      Class<T> pojoClass) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    T pojo = pojoClass.newInstance();
    fireUnmarshalEvent(pojo, sobj, TriggerType.Before);

    for (Iterator<EdmProperty> it = stype.getProperties().iterator(); it.hasNext();) {
      EdmProperty property = it.next();
      Object value = null;
      try {
        value = sobj.getProperty(property.getName()).getValue();
      } catch (Exception ex) {
        // property not define on object
        if (property.isNullable()) {
          continue;
        } else {
          throw new RuntimeException("missing required property " + property.getName());
        }
      }

      if (property.getCollectionKind() == EdmProperty.CollectionKind.NONE) {
        if (property.getType().isSimple()) {
          // call the setter.
          propertyModel.setPropertyValue(pojo, property.getName(), value);
        } else {
          // complex.
          // hmmh, value is a Collection<OProperty<?>>...why is it not an OComplexObject.

          propertyModel.setPropertyValue(
              pojo,
              property.getName(),
              value == null
                  ? null
                  : toPojo(
                      OComplexObjects.create((EdmComplexType) property.getType(), (List<OProperty<?>>) value),
                      propertyModel.getPropertyType(property.getName())));
        }
      } else {
        // collection.
        OCollection<? extends OObject> collection = (OCollection<? extends OObject>) value;
        List<Object> pojos = new ArrayList<Object>();
        for (OObject item : collection) {
          if (collection.getType().isSimple()) {
            pojos.add(((OSimpleObject<?>) item).getValue());
          } else {
            // turn OComplexObject into a pojo
            pojos.add(toPojo((OComplexObject) item, propertyModel.getCollectionElementType(property.getName())));
          }
        }
        propertyModel.setCollectionValue(pojo, property.getName(), pojos);
      }
    }

    return pojo;
  }

  /*
   * Design note:
   * toPojo is functionality that is useful on both the producer and consumer side.
   * I'm putting it in the producer class for now although I suspect there is a
   * more elegant design that factors out POJO Classes and PropertyModels into
   * some kind of "PojoModelDefinition" class.  The producer side would then
   * layer and extended definition that defined how the PojoModelDefinition maps
   * to entity sets and such.
   *
   * with all that said, hopefully this start is useful.  I'm going to use it on
   * our producer side for now to handle createEntity payloads.
   */

  /**
   * Transforms the given entity into a POJO of type pojoClass.
   */
  public <T> T toPojo(OEntity entity, Class<T> pojoClass) throws InstantiationException,
      IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    InMemoryEntityInfo<?> e = this.findEntityInfoForClass(pojoClass);

    // so, how is this going to work?
    // we have the PropertyModel available.  We can lookup the EdmStructuredType if necessary.

    EdmEntitySet entitySet = this.getMetadata().findEdmEntitySet(e.getEntitySetName());

    T pojo = fillInPojo(entity, entitySet.getType(), e.getPropertyModel(), pojoClass);

    // nav props
    for (Iterator<EdmNavigationProperty> it = entitySet.getType().getNavigationProperties().iterator(); it.hasNext();) {
      EdmNavigationProperty np = it.next();
      OLink link = null;
      try {
        link = entity.getLink(np.getName(), OLink.class);
      } catch (IllegalArgumentException nolinkex) {
        continue;
      }

      if (link.isInline()) {
        if (link.isCollection()) {
          List<Object> pojos = new ArrayList<Object>();
          for (OEntity relatedEntity : link.getRelatedEntities()) {
            pojos.add(toPojo(relatedEntity, e.getPropertyModel().getCollectionElementType(np.getName())));
          }
          e.getPropertyModel().setCollectionValue(pojo, np.getName(), pojos);
        } else {
          e.getPropertyModel().setPropertyValue(pojo, np.getName(),
              toPojo(link.getRelatedEntity(), e.getPropertyModel().getPropertyType(np.getName())));
        }
      } // else ignore deferred links.
    }

    fireUnmarshalEvent(pojo, entity, TriggerType.After);
    return pojo;
  }

@Override
public void beginChangeSetBoundary() {
	// TODO Auto-generated method stub

}

@Override
public void commitChangeSetBoundary() {
	// TODO Auto-generated method stub

}

@Override
public void rollbackChangeSetBoundary() {
	// TODO Auto-generated method stub

}

@Override
public EntityResponse createResponseForBatchPostOperation(String entitySetName,
		OEntity entity) {
	// TODO Auto-generated method stub
	return null;
}

@Override
public InputStream getInputStreamForMediaLink(String entitySetName,
		OEntityKey entityKey, EntityQueryInfo queryInfo) {
	// TODO Auto-generated method stub
	return null;
}

@Override
public void updateEntityWithStream(String entitySetName, OEntity entity) {
	// TODO Auto-generated method stub

}

@Override
public ContextStream getInputStreamForNamedStream(String entitySetName,
		OEntityKey entityKey, String columnName, QueryInfo queryInfo) {
	// TODO Auto-generated method stub
	return null;
}

@Override
public void updateEntityWithNamedStream(String entitySetName,
		OEntityKey entityKey, String columnName, ContextStream streamContext) {
	// TODO Auto-generated method stub

}
}


text:
//
//  LZCollectionViewDelegate.h
//  CustomControl
//
//  Created by liww on 14-9-30.
//  Copyright (c) 2014年 liww. All rights reserved.
//

#import <Foundation/Foundation.h>

@class LZCollectionView;
@class LZCollectionViewCell;
@class LZCollectionReusableView;

@protocol LZCollectionViewDelegate <NSObject>

@optional
/*!
 * @discription Tells the delegate that the specified cell is about to be displayed in the collection view.

 * @param collectionView The collection view object that is adding the cell.

 * @param cell The cell object being added.

 * @param indexPath The index path of the data item that the cell represents.
 */
- (void)collectionView:(LZCollectionView *)collectionView
       willDisplayCell:(LZCollectionViewCell *)cell
    forItemAtIndexPath:(NSIndexPath *)indexPath;

/*!
 * @discription Tells the delegate that the specified supplementary view is about to be displayed in the collection view.

 * @param collectionView The collection view object that is adding the supplementary view.

 * @param view The view being added.

 * @param elementKind: The type of the supplementary view. This string is defined by the layout that presents the view.

 * @param indexPath The index path of the data item that the supplementary view represents.

 */
- (void)collectionView:(LZCollectionView *)collectionView
willDisplaySupplementaryView:(LZCollectionReusableView *)view
        forElementKind:(NSString *)elementKind
           atIndexPath:(NSIndexPath *)indexPath;

- (BOOL)collectionView:(LZCollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath;
- (void)collectionView:(LZCollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath;
- (void)collectionView:(LZCollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath;

- (BOOL)collectionView:(LZCollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath;
- (BOOL)collectionView:(LZCollectionView *)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath *)indexPath;
- (void)collectionView:(LZCollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath;
- (void)collectionView:(LZCollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath;

- (void)collectionViewWillDeselectAllItems:(LZCollectionView *)collectionView;
- (void)collectionViewDidDeselectAllItems:(LZCollectionView *)collectionView;

- (void)collectionView:(LZCollectionView *)collectionView didClickItemAtIndexPath:(NSIndexPath *)indexPath;
- (void)collectionView:(LZCollectionView *)collectionView didDoubleClickItemAtIndexPath:(NSIndexPath *)indexPath;

- (void)collectionView:(LZCollectionView *)collectionView didActivateContextMenuWithIndexPaths:(NSArray *)indexPaths;
@end


text:
package com.devteam.sistrans.repositories.impl;

import com.devteam.sistrans.dto.SistransDto;
import com.devteam.sistrans.entities.Transaccion;
import com.devteam.sistrans.repositories.ArchivoDao;
import com.devteam.sistrans.utils.SistransUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.util.List;

@Repository
public class ArchivoDaoImpl implements ArchivoDao{

    private DataSource dataSource;

    @Autowired
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public Transaccion guardarTransacion(Transaccion transaccion) throws DataAccessException{
        long id;
        // Output format date and time ..
        SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(dataSource)
                .withFunctionName("USP_GUARDAR_TRANSACCION_FUC");
        SqlParameterSource sqlParameterSourceIn = new MapSqlParameterSource()
                .addValue("IN_FECHA", SistransUtils.dateToDbFormat(transaccion.getFecha())) //Pasar a formato de DB
                .addValue("IN_HORA", SistransUtils.hourToDbFormat(transaccion.getHora())) //Pasar a formato de DB
                .addValue("IN_TARJETA", transaccion.getTarjeta())
                .addValue("IN_MONTO",transaccion.getMonto())
                .addValue("IN_CANAL",transaccion.getCanal())
                .addValue("IN_ADQUIRIENTE",transaccion.getAdquiriente())
                .addValue("IN_AUTORIZADOR", transaccion.getAutorizador());

        id = simpleJdbcCall.executeFunction(Long.class, sqlParameterSourceIn);
        transaccion.setCodigo(id);
        return transaccion;
    }

    @Override
    public SistransDto guardarTransaciones(List<Transaccion> transaccions) {
        SistransDto sistransDto = new SistransDto();
        try {
            transaccions.forEach(this::guardarTransacion); //Todo está por referencia?
            sistransDto.setErrorCod(0);
            sistransDto.setErrorDesc("Todas las filas correctamente guardadas");
            sistransDto.setData(transaccions);
            return sistransDto;
        }catch (DataAccessException dae){
            sistransDto.setErrorCod(1);
            sistransDto.setErrorDesc("Errores al guardar las fila");
            sistransDto.setData(transaccions);
            return sistransDto;
        }
    }
}


text:
class AuthorizationException(Exception):
    """Raised when authorization verification failed.
       Contains details about the authentication rules that have been checked.
    """

    def __init__(self, msg):
        self.msg = msg
        super().__init__()

    def __str__(self):
        return 'authorization failed: {}'.format(self.msg)


text:
package com.me.diankun.toolbarthemedemo;

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.annotation.ArrayRes;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Created by diank on 2015/9/18.
 */
public class ButtonItemAdapter extends BaseAdapter implements View.OnClickListener {

    private Toast mToast;
    private final Context mContext;
    private final CharSequence[] mItems;

    public ButtonItemAdapter(Context context, @ArrayRes int arrayResId) {
        this(context, context.getResources().getTextArray(arrayResId));
    }

    private ButtonItemAdapter(Context context, CharSequence[] items) {
        this.mContext = context;
        this.mItems = items;
    }

    @Override
    public int getCount() {
        return mItems.length;
    }

    @Override
    public CharSequence getItem(int position) {
        return mItems[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @SuppressLint("ViewHolder")
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null)
            convertView = View.inflate(mContext, R.layout.dialog_customlistitem, null);
        ((TextView) convertView.findViewById(R.id.title)).setText(mItems[position] + " (" + position + ")");
        Button button = (Button) convertView.findViewById(R.id.button);
        button.setTag(position);
        button.setOnClickListener(this);
        return convertView;
    }

    @Override
    public void onClick(View v) {
        Integer index = (Integer) v.getTag();
        if (mToast != null) mToast.cancel();
        mToast = Toast.makeText(mContext, "Clicked button " + index, Toast.LENGTH_SHORT);
        mToast.show();
    }
}


text:
"""Copyright 2015 Roger R Labbe Jr.

FilterPy library.
http://github.com/rlabbe/filterpy

Documentation at:
https://filterpy.readthedocs.org

Supporting book at:
https://github.com/rlabbe/Kalman-and-Bayesian-Filters-in-Python

This is licensed under an MIT license. See the readme.MD file
for more information.
"""

#pylint: disable=invalid-name
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import math
from numpy.random import randn

def get_radar(dt):
    """ Simulate radar range to object at 1K altidue and moving at 100m/s.
    Adds about 5% measurement noise. Returns slant range to the object.
    Call once for each new measurement at dt time from last call.
    """

    if not hasattr(get_radar, "posp"):
        get_radar.posp = 0

    vel = 100  + .5 * randn()
    alt = 1000 + 10 * randn()
    pos = get_radar.posp + vel*dt

    v = 0 + pos* 0.05*randn()
    slant_range = math.sqrt(pos**2 + alt**2) + v
    get_radar.posp = pos

    return slant_range

if __name__ == "__main__":
    for i in range(100):
        print(get_radar(0.1))


text:
<?php

namespace Magento\ThemeSampleData\Plugin\View\Page;

use Magento\Framework\UrlInterface;
use Magento\Framework\View\Page\Config as PageConfig;

class Config
{
    /**
     * Url configuration
     *
     * @var \Magento\Framework\UrlInterface
     */
    protected $baseUrl;

    /**
     * @param UrlInterface $baseUrl
     */
    public function __construct(
        \Magento\Framework\UrlInterface $baseUrl
    ) {
        $this->baseUrl = $baseUrl;
    }

    /**
     * @param PageConfig $subject
     * @param string $result
     * @return string
     *
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function afterGetIncludes(PageConfig $subject, $result)
    {
        $pattern = '{{MEDIA_URL}}';
        if (strpos($result, $pattern) !== false) {
            $url = $this->baseUrl->getBaseUrl(['_type' => \Magento\Framework\UrlInterface::URL_TYPE_MEDIA]);
            $result = str_replace($pattern, $url, $result);
        }
        return $result;
    }
}