text:
An adorable little framework and command line tool for interacting with [SourceKit][uncovering-sourcekit].

SourceKitten links and communicates with `sourcekitd.framework` to parse the Swift AST, extract comment docs for Swift or Objective-C projects, get syntax data for a Swift file and lots more!

[![Test Status](https://travis-ci.org/jpsim/SourceKitten.svg?branch=master)](https://travis-ci.org/jpsim/SourceKitten)

## Installation

Building SourceKitten on macOS requires Xcode 8.3 or later or a Swift 3.1
toolchain or later with the Swift Package Manager.

Building SourceKitten on Linux requires:

* A Swift 3.1 or later compiler and Swift Package Manager to be installed.
* `libsourcekitdInProc.so` to be built and located in `/usr/lib`, or in another
  location specified by the `LINUX_SOURCEKIT_LIB_PATH` environment variable.

SourceKitten typically supports previous versions of SourceKit.

### Homebrew

Run `brew install sourcekitten`.

### Swift Package Manager

Run `swift build` in the root directory of this project.

### Xcode (via Make)

Run `make install` in the root directory of this project.

### Package

Download and open SourceKitten.pkg from the [releases tab](https://github.com/jpsim/SourceKitten/releases).

## Command Line Usage

Once SourceKitten is installed, you may use it from the command line.

```
$ sourcekitten help
Available commands:

   complete    Generate code completion options.
   doc         Print Swift docs as JSON or Objective-C docs as XML
   help        Display general or command-specific help
   structure   Print Swift structure information as JSON
   syntax      Print Swift syntax information as JSON
   version     Display the current version of SourceKitten
```

## How is SourceKit resolved?

SourceKitten searches for SourceKit in the following order:

* `$XCODE_DEFAULT_TOOLCHAIN_OVERRIDE`
* `$TOOLCHAIN_DIR`
* `xcrun -find swift`
* `/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain`
* `/Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain`
* `~/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain`
* `~/Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain`

On Linux, SourceKit is expected to be located in
`/usr/lib/libsourcekitdInProc.so` or specified by the `LINUX_SOURCEKIT_LIB_PATH`
environment variable.

## Complete

Running `sourcekitten complete --file file.swift --offset 123` or
`sourcekitten complete --text "0." --offset 2` will print out code completion
options for the offset in the file/text provided:

```json
[{
  "descriptionKey" : "advancedBy(n: Distance)",
  "associatedUSRs" : "s:FSi10advancedByFSiFSiSi s:FPSs21RandomAccessIndexType10advancedByuRq_S__Fq_Fqq_Ss16ForwardIndexType8Distanceq_ s:FPSs16ForwardIndexType10advancedByuRq_S__Fq_Fqq_S_8Distanceq_ s:FPSs10Strideable10advancedByuRq_S__Fq_Fqq_S_6Strideq_ s:FPSs11_Strideable10advancedByuRq_S__Fq_Fqq_S_6Strideq_",
  "kind" : "source.lang.swift.decl.function.method.instance",
  "sourcetext" : "advancedBy(<#T##n: Distance##Distance#>)",
  "context" : "source.codecompletion.context.thisclass",
  "typeName" : "Int",
  "moduleName" : "Swift",
  "name" : "advancedBy(n: Distance)"
},
{
  "descriptionKey" : "advancedBy(n: Self.Distance, limit: Self)",
  "associatedUSRs" : "s:FeRq_Ss21RandomAccessIndexType_SsS_10advancedByuRq_S__Fq_FTqq_Ss16ForwardIndexType8Distance5limitq__q_",
  "kind" : "source.lang.swift.decl.function.method.instance",
  "sourcetext" : "advancedBy(<#T##n: Self.Distance##Self.Distance#>, limit: <#T##Self#>)",
  "context" : "source.codecompletion.context.superclass",
  "typeName" : "Self",
  "moduleName" : "Swift",
  "name" : "advancedBy(n: Self.Distance, limit: Self)"
},
...
]
```

To use the iOS SDK, pass `-sdk` and `-target` arguments preceded by `--`:
```
sourcekitten complete --text "import UIKit ; UIColor." --offset 22 -- -target arm64-apple-ios9.0 -sdk /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.0.sdk
```

## Doc

Running `sourcekitten doc` will pass all arguments after what is parsed to
`xcodebuild` (or directly to the compiler, SourceKit/clang, in the
`--single-file` mode).

### Example usage

1. `sourcekitten doc -- -workspace SourceKitten.xcworkspace -scheme SourceKittenFramework`
2. `sourcekitten doc --single-file file.swift -- -j4 file.swift`
3. `sourcekitten doc --module-name Alamofire -- -project Alamofire.xcodeproj`
4. `sourcekitten doc -- -workspace Haneke.xcworkspace -scheme Haneke`
5. `sourcekitten doc --objc Realm/Realm.h -- -x objective-c -isysroot $(xcrun --show-sdk-path) -I $(pwd)`

## Structure

Running `sourcekitten structure --file file.swift` or `sourcekitten structure --text "struct A { func b() {} }"` will return a JSON array of structure information:

```json
{
  "key.substructure" : [
    {
      "key.kind" : "source.lang.swift.decl.struct",
      "key.offset" : 0,
      "key.nameoffset" : 7,
      "key.namelength" : 1,
      "key.bodyoffset" : 10,
      "key.bodylength" : 13,
      "key.length" : 24,
      "key.substructure" : [
        {
          "key.kind" : "source.lang.swift.decl.function.method.instance",
          "key.offset" : 11,
          "key.nameoffset" : 16,
          "key.namelength" : 3,
          "key.bodyoffset" : 21,
          "key.bodylength" : 0,
          "key.length" : 11,
          "key.substructure" : [

          ],
          "key.name" : "b()"
        }
      ],
      "key.name" : "A"
    }
  ],
  "key.offset" : 0,
  "key.diagnostic_stage" : "source.diagnostic.stage.swift.parse",
  "key.length" : 24
}
```

## Syntax

Running `sourcekitten syntax --file file.swift` or `sourcekitten syntax --text "import Foundation // Hello World"` will return a JSON array of syntax highlighting information:

```json
[
  {
    "offset" : 0,
    "length" : 6,
    "type" : "source.lang.swift.syntaxtype.keyword"
  },
  {
    "offset" : 7,
    "length" : 10,
    "type" : "source.lang.swift.syntaxtype.identifier"
  },
  {
    "offset" : 18,
    "length" : 14,
    "type" : "source.lang.swift.syntaxtype.comment"
  }
]
```

## Request

Running `sourcekitten request --yaml [FILE|TEXT]` will execute a sourcekit request with the given yaml. For example:

```yaml
key.request: source.request.cursorinfo
key.sourcefile: "/tmp/foo.swift"
key.offset: 8
key.compilerargs:
  - "/tmp/foo.swift"
```

## SourceKittenFramework

Most of the functionality of the `sourcekitten` command line tool is actually encapsulated in a framework named SourceKittenFramework.

If you're interested in using SourceKitten as part of another tool, or perhaps extending its functionality, take a look at the SourceKittenFramework source code to see if the API fits your needs.

*Note: SourceKitten is written entirely in Swift, and the SourceKittenFramework API is not designed to interface with Objective-C.*

## License

MIT licensed.

[uncovering-sourcekit]: http://jpsim.com/uncovering-sourcekit


text:
package com.bearchoke.platform.persistence.mongo.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.thoughtworks.xstream.XStream;
import com.bearchoke.platform.persistence.mongo.axon.AxonMongoTemplate;
import com.bearchoke.platform.persistence.mongo.axon.AxonSagaMongoTemplate;
import org.axonframework.commandhandling.AsynchronousCommandBus;
import org.axonframework.commandhandling.CommandDispatchInterceptor;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.axonframework.commandhandling.gateway.CommandGatewayFactoryBean;
import org.axonframework.commandhandling.gateway.IntervalRetryScheduler;
import org.axonframework.commandhandling.interceptors.BeanValidationInterceptor;
import org.axonframework.eventhandling.EventBus;
import org.axonframework.eventhandling.SimpleEventBus;
import org.axonframework.eventsourcing.Snapshotter;
import org.axonframework.eventsourcing.SpringAggregateSnapshotter;
import org.axonframework.eventstore.mongo.MongoEventStore;
import org.axonframework.repository.LockManager;
import org.axonframework.repository.PessimisticLockManager;
import org.axonframework.saga.SagaRepository;
import org.axonframework.saga.repository.mongo.MongoSagaRepository;
import org.axonframework.saga.spring.SpringResourceInjector;
import org.axonframework.serializer.xml.XStreamSerializer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.data.mongodb.MongoDbFactory;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

/**
 * Created by Bjorn Harvold
 * Date: 7/19/14
 * Time: 10:36 PM
 * Responsibility:
 */
@Configuration
public class AxonCQRSConfig {

    @Inject
    private ObjectMapper objectMapper;

    @Inject
    private XStream xStream;

    @Inject
    @Qualifier("taskExecutor")
    private TaskExecutor taskExecutor;

    @Inject
    @Qualifier("axonMongoDbFactory")
    private MongoDbFactory mongoDbFactory;

    @Bean(name = "commandBus", destroyMethod = "shutdown")
    public AsynchronousCommandBus commandBus() {
        AsynchronousCommandBus commandBus = new AsynchronousCommandBus();

        List<CommandDispatchInterceptor> interceptors = new ArrayList<>(1);
        interceptors.add(new BeanValidationInterceptor());
        commandBus.setDispatchInterceptors(interceptors);

        return commandBus;
    }

    @Bean(name = "commandGateway")
    public CommandGateway commandGateway() {
        CommandGateway commandGateway = null;
        CommandGatewayFactoryBean factory = new CommandGatewayFactoryBean();
        factory.setCommandBus(commandBus());

        // create a retry scheduler to re-run the command that failed with an exception
        // I put this in place to contend with concurrency exceptions [BH]
        ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
        factory.setRetryScheduler(new IntervalRetryScheduler(ses, 500, 2));
//        factory.setGatewayInterface();

        try {
            factory.afterPropertiesSet();
            commandGateway = (CommandGateway) factory.getObject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return commandGateway;
    }

    // In case we want something more robust
//    @Bean(name = "eventBus")
//    public SpringMessagingEventBus eventBus() {
//        SpringMessagingEventBus eventBus = new SpringMessagingEventBus();
//        eventBus.setChannel(defaultInputChannel);
//
//        return eventBus;
//    }

    @Bean(name = "eventBus")
    public EventBus eventBus() {
        EventBus eventBus = new SimpleEventBus();

        return eventBus;
    }

    @Bean(name = "lockManager")
    public LockManager lockManager() {
//        OptimisticLockManager lockManager = new OptimisticLockManager();
        PessimisticLockManager lockManager = new PessimisticLockManager(); // default Axon lock manager

        return lockManager;
    }

    @Bean(name = "axonMongoTemplate")
    public AxonMongoTemplate axonMongoTemplate() {
        return new AxonMongoTemplate(mongoDbFactory);
    }

    @Bean(name = "axonSagaMongoTemplate")
    public AxonSagaMongoTemplate mongoSagaTemplate() {
        return new AxonSagaMongoTemplate(mongoDbFactory);
    }

    @Bean(name = "eventStore")
    public MongoEventStore eventStore() {
//        JacksonSerializer jsonSerializer = new JacksonSerializer(objectMapper);
        XStreamSerializer xStreamSerializer = new XStreamSerializer(xStream);

        return new MongoEventStore(xStreamSerializer, axonMongoTemplate());
    }

    @Bean(name = "sagaRepository")
    public SagaRepository sagaRepository() {
        MongoSagaRepository sagaRepository = new MongoSagaRepository(mongoSagaTemplate());
        sagaRepository.setResourceInjector(new SpringResourceInjector());

        return sagaRepository;
    }

    @Bean(name = "snapshotter")
    public Snapshotter snapshotter() {
        SpringAggregateSnapshotter sas = new SpringAggregateSnapshotter();
        sas.setEventStore(eventStore());
        sas.setExecutor(taskExecutor);

        return sas;
    }

}

redpajama_set_name: RedPajamaGithub


text:
This directory contains different versions of Docker images for use with Bokeh. There are many ways to deploy Bokeh on Docker, each serving a different use-case and also dependent on personal preference. The containers provided here are experimental and supported on a best-effort basis. Feel free to submit a pull requested for new versions! Good starting points are:

* [Docker documentation](https://docs.docker.com/)
* [Itamar Turner-Trauring's article on choosing the best Docker base image at pythonspeed.com](https://pythonspeed.com/articles/base-image-python-docker-images/)

## Alpine vs Debian (and other Linux distributions)
As explained by [Itamar](https://pythonspeed.com/articles/base-image-python-docker-images/) the major difference between Alpine and Debian (or any other Linux distribution), is that __Alpine uses a different C library, musl, instead of the more common glibc__. As a result, binary wheels won't work on Alpine Linux, so many packages that 'just work' on other Linux distributions will need to be compiled from scratch. This means longer build times the first time you install a package.

Furthermore, while in theory musl and glibc are [mostly compatible](https://wiki.musl-libc.org/functional-differences-from-glibc.html), in practice the differences can cause problems. Particularly, when you are using Bokeh in combination with Numpy, Pandas and/or SciPy, you will need to do extra work to compile the C binaries from these libraries from yourself when using Alpine. This is do-able, with benefits on the users side (small image footprint) and the downsides mostly on the developers side (having to compile python packages from scratch).

These differences are shown in the table below, which compares the uncompressed image footprint for Alpine vs Debian slim, using pip vs. conda.

|  | Alpine | Debian slim |
|:---|:---|:---|
|pip | [jfloff/alpine-python:3.7-slim](https://hub.docker.com/r/jfloff/alpine-python): 82 MB | [python:3.7-slim](https://github.com/docker-library/python/blob/d2a2b4f7422aac78c7d5ea6aadc49d009d184a5f/3.7/buster/slim/Dockerfile) 143 MB |
|conda |[continuumio/miniconda3:alpine from GitHub](https://github.com/ContinuumIO/docker-images/blob/master/miniconda3/alpine/Dockerfile) 163 MB | [continuumio/miniconda3:debian-slim from GitHub](https://github.com/ContinuumIO/docker-images/blob/master/miniconda3/debian/Dockerfile) 245 MB |

While there is a difference, given that a modest Bokeh app (like demo.bokeh.org) quickly adds up to an image size of around 1 GB (uncompressed), the difference for production systems is around 10-15%. Besides the difference in image footprint between Alpine and Debian, the conda-based images are also larger as they include more libraries. Note that these conda images from ContinuumIO are already [optimised as described by Jim Crist](https://jcrist.github.io/conda-docker-tips.html).

## Building images
To build a docker image, choose to build with Alpine or Debian. All the commands below should be run from the root of bokeh's repository. Note the Alpine images build on [frolvlad's Alpine images](https://hub.docker.com/u/frolvlad), as [continuumio/miniconda3:alpine](https://github.com/ContinuumIO/docker-images/blob/master/miniconda3/alpine/Dockerfile) are not published on Docker Hub yet.

### using Alpine from source
The `docker-tools/alpine/Dockerfile-from-source` pulls bokeh from github and builds bokeh and bokehjs. Note that this will probably fail for old versions! The `BOKEH_VERSION` build arg is interpreted as the commit to fetch. To build:
``` shell
docker build --file docker-tools/alpine/Dockerfile-from-source --build-arg BOKEH_VERSION=master --tag bokeh:latest .
```

You can test this image by running one of the examples:
```shell
docker run -p 5006:5006 -it bokeh:latest bokeh serve /bokeh_examples/app/sliders.py
```

Note that some examples require additional Python modules and hence will result in an error.

### using Alpine with conda
Choose a bokeh version to install from the available versions on anaconda.
Run `conda search bokeh` for the available versions. Then, build the image using, for example, version 1.4.0:
``` shell
docker build -t bokeh:dev-py3 --build-arg PYTHON=3.6 -f docker-tools/Dockerfile-from-travis .
```

Also here, you can test the image by `docker run -it`
```
docker run -p 5006:5006 -it bokeh:1.4.0 bokeh serve /bokeh_examples/app/sliders.py
```

For older versions the tornado version might need to be pinned. If so, specify `TORNADO_VERSION`
``` shell
sudo docker build --file docker-tools/debian/Dockerfile-from-conda --build-arg BOKEH_VERSION=0.12.7 --build-arg TORNADO_VERSION=4.5 --tag bokeh:0.12.7 docker-tools/alpine
```

### using debian-slim with conda
In this example we use `docker-tools/debian/environment.yml` to specify the conda environment for the Docker container.
```shell
docker build --file docker-tools/debian/Dockerfile --tag demo-bokeh-conda docker-tools/debian
```

To run the container:
```shell
docker run --rm -p 8080:8080 -it demo-bokeh-conda
```

### using debian-slim with pip
Here we use `docker-tools/debian/requirements.txt` to specify pip packages for the Docker container.
```shell
docker build -f docker-tools/debian/Dockerfile-pip --tag demo-bokeh-pip docker-tools/debian
```

To run:
```
docker run -it -p 8080:8080 --rm demo-bokeh-pip
```

### development image
TO DO

## Deploying on Google App Engine
One way to deploy Bokeh apps on Google App Engine (GAE) is to use [GAE Python Flexible Environment](https://cloud.google.com/appengine/docs/flexible/python). Make sure to read at least the [the instructions on custom runtimes](https://cloud.google.com/appengine/docs/flexible/custom-runtimes/how-to). At the time of writing (January 2020), Google App Engine only supports [websockets on the Flex environment](https://cloud.google.com/blog/products/application-development/introducing-websockets-support-for-app-engine-flexible-environment). Once you have setup the project and `gcloud` SDK, you can deploying to GAE with

```shell
cd docker-tools/debian
gcloud app deploy
```

Note this is just a bare-bones deployment, using the default `Dockerfile` with no SSL or any security measures. Using a load-balancer is recommended as described in the GAE documentation.

TO DO: add more details on how to configure GAE more robustly.


text:
namespace rocksdb {

class Cache;

// Create a new cache with a fixed size capacity. The cache is sharded
// to 2^num_shard_bits shards, by hash of the key. The total capacity
// is divided and evenly assigned to each shard. If strict_capacity_limit
// is set, insert to the cache will fail when cache is full. User can also
// set percentage of the cache reserves for high priority entries via
// high_pri_pool_pct.
extern std::shared_ptr<Cache> NewLRUCache(size_t capacity,
                                          int num_shard_bits = 6,
                                          bool strict_capacity_limit = false,
                                          double high_pri_pool_ratio = 0.0);

// Similar to NewLRUCache, but create a cache based on CLOCK algorithm with
// better concurrent performance in some cases. See util/clock_cache.cc for
// more detail.
//
// Return nullptr if it is not supported.
extern std::shared_ptr<Cache> NewClockCache(size_t capacity,
                                            int num_shard_bits = 6,
                                            bool strict_capacity_limit = false);

class Cache {
 public:
  // Depending on implementation, cache entries with high priority could be less
  // likely to get evicted than low priority entries.
  enum class Priority { HIGH, LOW };

  Cache() {}

  // Destroys all existing entries by calling the "deleter"
  // function that was passed via the Insert() function.
  //
  // @See Insert
  virtual ~Cache() {}

  // Opaque handle to an entry stored in the cache.
  struct Handle {};

  // The type of the Cache
  virtual const char* Name() const = 0;

  // Insert a mapping from key->value into the cache and assign it
  // the specified charge against the total cache capacity.
  // If strict_capacity_limit is true and cache reaches its full capacity,
  // return Status::Incomplete.
  //
  // If handle is not nullptr, returns a handle that corresponds to the
  // mapping. The caller must call this->Release(handle) when the returned
  // mapping is no longer needed. In case of error caller is responsible to
  // cleanup the value (i.e. calling "deleter").
  //
  // If handle is nullptr, it is as if Release is called immediately after
  // insert. In case of error value will be cleanup.
  //
  // When the inserted entry is no longer needed, the key and
  // value will be passed to "deleter".
  virtual Status Insert(const Slice& key, void* value, size_t charge,
                        void (*deleter)(const Slice& key, void* value),
                        Handle** handle = nullptr,
                        Priority priority = Priority::LOW) = 0;

  // If the cache has no mapping for "key", returns nullptr.
  //
  // Else return a handle that corresponds to the mapping.  The caller
  // must call this->Release(handle) when the returned mapping is no
  // longer needed.
  // If stats is not nullptr, relative tickers could be used inside the
  // function.
  virtual Handle* Lookup(const Slice& key, Statistics* stats = nullptr) = 0;

  // Release a mapping returned by a previous Lookup().
  // REQUIRES: handle must not have been released yet.
  // REQUIRES: handle must have been returned by a method on *this.
  virtual void Release(Handle* handle) = 0;

  // Return the value encapsulated in a handle returned by a
  // successful Lookup().
  // REQUIRES: handle must not have been released yet.
  // REQUIRES: handle must have been returned by a method on *this.
  virtual void* Value(Handle* handle) = 0;

  // If the cache contains entry for key, erase it.  Note that the
  // underlying entry will be kept around until all existing handles
  // to it have been released.
  virtual void Erase(const Slice& key) = 0;
  // Return a new numeric id.  May be used by multiple clients who are
  // sharding the same cache to partition the key space.  Typically the
  // client will allocate a new id at startup and prepend the id to
  // its cache keys.
  virtual uint64_t NewId() = 0;

  // sets the maximum configured capacity of the cache. When the new
  // capacity is less than the old capacity and the existing usage is
  // greater than new capacity, the implementation will do its best job to
  // purge the released entries from the cache in order to lower the usage
  virtual void SetCapacity(size_t capacity) = 0;

  // Set whether to return error on insertion when cache reaches its full
  // capacity.
  virtual void SetStrictCapacityLimit(bool strict_capacity_limit) = 0;

  // Get the flag whether to return error on insertion when cache reaches its
  // full capacity.
  virtual bool HasStrictCapacityLimit() const = 0;

  // returns the maximum configured capacity of the cache
  virtual size_t GetCapacity() const = 0;

  // returns the memory size for the entries residing in the cache.
  virtual size_t GetUsage() const = 0;

  // returns the memory size for a specific entry in the cache.
  virtual size_t GetUsage(Handle* handle) const = 0;

  // returns the memory size for the entries in use by the system
  virtual size_t GetPinnedUsage() const = 0;

  // Call this on shutdown if you want to speed it up. Cache will disown
  // any underlying data and will not free it on delete. This call will leak
  // memory - call this only if you're shutting down the process.
  // Any attempts of using cache after this call will fail terribly.
  // Always delete the DB object before calling this method!
  virtual void DisownData(){
      // default implementation is noop
  };

  // Apply callback to all entries in the cache
  // If thread_safe is true, it will also lock the accesses. Otherwise, it will
  // access the cache without the lock held
  virtual void ApplyToAllCacheEntries(void (*callback)(void*, size_t),
                                      bool thread_safe) = 0;

  // Remove all entries.
  // Prerequisit: no entry is referenced.
  virtual void EraseUnRefEntries() = 0;

 private:
  // No copying allowed
  Cache(const Cache&);
  Cache& operator=(const Cache&);
};

}  // namespace rocksdb


text:
describe TreeBuilderVmsAndTemplates do
  before do
    ems     = FactoryGirl.create(:ems_vmware, :zone => FactoryGirl.create(:zone))
    folder  = FactoryGirl.create(:ems_folder, :ext_management_system => ems)
    subfolder1 = FactoryGirl.create(:ems_folder)
    subfolder2 = FactoryGirl.create(:ems_folder)
    subfolder3 = FactoryGirl.create(:datacenter)

    folder.with_relationship_type("ems_metadata") { folder.add_child(subfolder1) }
    folder.with_relationship_type("ems_metadata") { folder.add_child(subfolder2) }
    folder.with_relationship_type("ems_metadata") { folder.add_child(subfolder3) }

    @vandt_tree = TreeBuilderVmsAndTemplates.new(ems, {})
    @tree = {ems => {folder => {subfolder1 => {}, subfolder2 => {}, subfolder3 => {}}}}
  end

  context "#sort_tree" do
    it "making sure sort_tree was successful for mixed ems_folder types" do
      expect { @vandt_tree.send(:sort_tree, @tree) }.not_to raise_error
    end
  end
end


text:
import os
import sys

import requests

from .alpineobject import AlpineObject
from .job import Job
from .user import User
from .workfile import Workfile
from .workspace import Workspace
from .datasource import DataSource
from .exception import *

class APIClient(AlpineObject):
    """
    The main entry point for the Alpine API. Most of the functions require a logged-in user. Begin a session by
    creating an instance of the :class:`APIClient` class.

    Example::

        >>> import alpine as AlpineAPI
        >>> session = alpine.APIClient(host, port, username, password)

    """

    user = None
    datasource = None
    workspace = None
    workfile = None
    job = None

    def __init__(self, host=None, port=None, username=None, password=None, is_secure=False, validate_certs=False,
                 ca_certs=None, token=None, logging_level='WARN'):
        """
        Sets internal values for Alpine API session. If username and password are supplied then a login is
        attempted. This is useful to check Alpine URL and user login parameters.

        :param str host: Hostname or IP address of the Alpine server.
        :param str port: Port number for Alpine.
        :param str username: Username to log in with.
        :param str password: Password to log in with.
        :param bool is_secure: True for HTTPS, else false.
        :param bool validate_certs:
        :param ca_certs:
        :param str token: Alpine API authentication token.
        :param str logging_level: Use to set the logging level.
        See https://docs.python.org/2/howto/logging.html#logging-levels.
        :return: None.
        """

        super(APIClient, self).__init__(token=token)
        self._setup_logging(default_level=logging_level)
        self.is_secure = is_secure

        if is_secure:
            self.protocol = 'https'
        else:
            self.protocol = 'http'

        if not port:
            self.host = host
        if port == 80:
            self.host = host
        else:
            self.host = "{0}:{1}".format(host, port)

        self.session = requests.Session()  # instantiate a session for requests

        self.base_url = "{0}://{1}/api".format(self.protocol, self.host)

        self.ca_certs = ca_certs
        self.validate_certs = validate_certs
        self.user_id = None
        if username and password:
            self.login(username, password)

    def login(self, username, password):
        """
        Attempts to log in to Alpine with provided username and password. Typically login is handled at
        session creation time.

        :param str username: Username to log in with.
        :param str password: Password to log in with.
        :return: Logged-in user's metadata.
        :rtype: dict

        Example::

            >>> user_info = session.login(username, password)

        """
        # build the url string and body payload
        url = "{0}/sessions?session_id=NULL".format(self.base_url)
        # url = self.base_url + "/sessions?session_id=NULL"
        body = {"username": username, "password": password}
        # TODO login with cert.
        cert_path = os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),
                                 "../host_deploy/resource/ssl/certificates/test.crt")

        key_path = os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),
                                "../host_deploy/resource/ssl/certificates/test.key")

        self.session.headers.update({"Content-Type": "application/x-www-form-urlencoded"})

        if self.protocol == 'http':
            login_response = self.session.post(url, data=body)
        else:
            login_response = self.session.post(url, data=body,
                                               verify=self.validate_certs, cert=(cert_path, key_path),
                                               headers={'Connection': 'close'})
        if login_response.status_code == 201:
            response = login_response.json()
            self.token = response['response']['session_id']
            self.user_id = response['response']['user']['id']
            self.logger.debug("Successfully logged in with username '{0}'".format(username))
            self.logger.debug("Token ID is: <{0}>".format(self.token))
            self.user = User(self.base_url, self.session, self.token)
            self.datasource = DataSource(self.base_url, self.session, self.token)
            self.workspace = Workspace(self.base_url, self.session, self.token)
            self.workfile = Workfile(self.base_url, self.session, self.token)
            self.job = Job(self.base_url, self.session, self.token)
            return login_response.json()['response']['user']

        else:
            raise LoginFailureException("Login failed with status code: <{0}>.".format(login_response.status_code))

    def logout(self):
        """
        Attempts to log out the current user.

        :return: Request response.
        :rtype: requests.models.Response

        Example::

            >>> session.logout()
            <Response [200]>

        """
        url = "{0}/sessions?session_id={1}".format(self.base_url, self.token)
        logout_response = self.session.delete(url)
        self.logger.debug("Received response code {0} with reason {1}".format(logout_response.status_code,
                                                                              logout_response.reason))
        self.user = None
        self.datasource = None
        self.workspace = None
        self.workfile = None
        self.user = None
        self.datasource = None

        # parse status codes here:
        status = logout_response.status_code
        if logout_response.status_code == 200:
            self.logger.debug("Successfully logged out.")
            return logout_response
        elif logout_response.status_code == 401:
            self.logger.debug("No user is logged in.")
            return logout_response
        else:
            self.logger.debug("Failure with status code: {0}".format(status))
            return logout_response

    def get_status(self):
        """
        Returns information about the currently logged-in user. Or, if no user is logged in, returns an empty dict.

        :return: Logged-in user's metadata.
        :rtype: dict

        Example::

            >>> session.get_status()
            {u'admin': True,
             u'auth_method': u'internal',
             u'dept': u'Development',
             u'email': u'demoadmin@alpinenow.com',
             u'entity_type': u'user',
             u'first_name': u'Demo',
             u'id': 665,
             u'image': {u'complete_json': True,
              u'entity_type': u'image',
              u'icon': u'/users/665/image?style=icon&1483606634',
              u'original': u'/users/665/image?style=original&1483606634'},
             u'is_deleted': None,
             u'last_name': u'Admin',
             u'ldap_group_id': None,
             u'notes': u'',
             u'roles': [u'admin'],
             u'subscribed_to_emails': True,
             u'tags': [],
             u'title': u'Assistant to the Regional Manager',
             u'user_type': u'analytics_developer',
             u'username': u'demoadmin',
             u'using_default_image': True}

        """
        url = "{0}/sessions".format(self.base_url)
        self.logger.debug("Checking to see if the user is still logged in....")
        response = self.session.get(url)
        self.logger.debug("Received response code {0} with reason {1}".format(response.status_code, response.reason))

        try:
            return response.json()['response']['user']
        except:
            return {}

    def get_version(self):
        """
        Returns the Alpine version.

        :return: Alpine version.
        :rtype: str

        Example::

            >>> session.get_version()
            '6.2.0.0.1-b8c02ca46'

        """
        url = "{0}/VERSION".format(self.base_url)
        response = self.session.get(url)
        return response.content.strip().decode('utf-8')

    def get_license(self):
        """
        Get the the current license information for Alpine.

        :return: Summary of Alpine license information - expiration, user limits, add-ons, etc.
        :rtype: dict

        Example::

            >>> license_info = session.get_license()

        """
        url = self.base_url + "/license"
        response = self.session.get(url)
        try:
            return response.json()['response']
        except:
            return {}


text:
var mark_names = [
    '',
    '1',
    'abc',
];

var measures = [
    [''],
    ['2', 1],
    ['aaa', 'navigationStart', ''],
];

function test_method_exists(method, method_name, properties)
{
    var msg;
    if (typeof method === 'function')
        msg = 'performance.' + method.name + ' is supported!';
    else
        msg = 'performance.' + method_name + ' is supported!';
    wp_test(function() { assert_equals(typeof method, 'function', msg); }, msg, properties);
}

function test_method_throw_exception(func_str, exception, msg)
{
    let exception_name;
    let test_func;
    if (typeof exception == "function") {
        exception_name = exception.name;
        test_func = assert_throws_js;
    } else {
        exception_name = exception;
        test_func = assert_throws_dom;
    }
    var msg = 'Invocation of ' + func_str + ' should throw ' + exception_name  + ' Exception.';
    wp_test(function() { test_func(exception, function() {eval(func_str)}, msg); }, msg);
}

function test_noless_than(value, greater_than, msg, properties)
{
    wp_test(function () { assert_true(value >= greater_than, msg); }, msg, properties);
}

function test_fail(msg, properties)
{
    wp_test(function() { assert_unreached(); }, msg, properties);
}

function test_resource_entries(entries, expected_entries)
{
    // This is slightly convoluted so that we can sort the output.
    var actual_entries = {};
    var origin = window.location.protocol + "//" + window.location.host;

    for (var i = 0; i < entries.length; ++i) {
        var entry = entries[i];
        var found = false;
        for (var expected_entry in expected_entries) {
            if (entry.name == origin + expected_entry) {
                found = true;
                if (expected_entry in actual_entries) {
                    test_fail(expected_entry + ' is not expected to have duplicate entries');
                }
                actual_entries[expected_entry] = entry;
                break;
            }
        }
        if (!found) {
            test_fail(entries[i].name + ' is not expected to be in the Resource Timing buffer');
        }
    }

    sorted_urls = [];
    for (var i in actual_entries) {
        sorted_urls.push(i);
    }
    sorted_urls.sort();
    for (var i in sorted_urls) {
        var url = sorted_urls[i];
        test_equals(actual_entries[url].initiatorType,
                    expected_entries[url],
                    origin + url + ' is expected to have initiatorType ' + expected_entries[url]);
    }
    for (var j in expected_entries) {
        if (!(j in actual_entries)) {
            test_fail(origin + j + ' is expected to be in the Resource Timing buffer');
        }
    }
}

function performance_entrylist_checker(type)
{
    const entryType = type;

    function entry_check(entry, expectedNames, testDescription = '')
    {
        const msg = testDescription + 'Entry \"' + entry.name + '\" should be one that we have set.';
        wp_test(function() { assert_in_array(entry.name, expectedNames, msg); }, msg);
        test_equals(entry.entryType, entryType, testDescription + 'entryType should be \"' + entryType + '\".');
        if (type === "measure") {
            test_true(isFinite(entry.startTime), testDescription + 'startTime should be a number.');
            test_true(isFinite(entry.duration), testDescription + 'duration should be a number.');
        } else if (type === "mark") {
            test_greater_than(entry.startTime, 0, testDescription + 'startTime should greater than 0.');
            test_equals(entry.duration, 0, testDescription + 'duration of mark should be 0.');
        }
    }

    function entrylist_order_check(entryList)
    {
        let inOrder = true;
        for (let i = 0; i < entryList.length - 1; ++i)
        {
            if (entryList[i + 1].startTime < entryList[i].startTime) {
                inOrder = false;
                break;
            }
        }
        return inOrder;
    }

    function entrylist_check(entryList, expectedLength, expectedNames, testDescription = '')
    {
        test_equals(entryList.length, expectedLength, testDescription + 'There should be ' + expectedLength + ' entries.');
        test_true(entrylist_order_check(entryList), testDescription + 'Entries in entrylist should be in order.');
        for (let i = 0; i < entryList.length; ++i)
        {
            entry_check(entryList[i], expectedNames, testDescription + 'Entry_list ' + i + '. ');
        }
    }

    return{"entrylist_check":entrylist_check};
}

function PerformanceContext(context)
{
    this.performanceContext = context;
}

PerformanceContext.prototype =
{

    initialMeasures: function(item, index, array)
    {
        this.performanceContext.measure.apply(this.performanceContext, item);
    },

    mark: function()
    {
        this.performanceContext.mark.apply(this.performanceContext, arguments);
    },

    measure: function()
    {
        this.performanceContext.measure.apply(this.performanceContext, arguments);
    },

    clearMarks: function()
    {
        this.performanceContext.clearMarks.apply(this.performanceContext, arguments);
    },

    clearMeasures: function()
    {
        this.performanceContext.clearMeasures.apply(this.performanceContext, arguments);

    },

    getEntries: function()
    {
        return this.performanceContext.getEntries.apply(this.performanceContext, arguments);
    },

    getEntriesByType: function()
    {
        return this.performanceContext.getEntriesByType.apply(this.performanceContext, arguments);
    },

    getEntriesByName: function()
    {
        return this.performanceContext.getEntriesByName.apply(this.performanceContext, arguments);
    },

    setResourceTimingBufferSize: function()
    {
        return this.performanceContext.setResourceTimingBufferSize.apply(this.performanceContext, arguments);
    },

    registerResourceTimingBufferFullCallback: function(func)
    {
        this.performanceContext.onresourcetimingbufferfull = func;
    },

    clearResourceTimings: function()
    {
        this.performanceContext.clearResourceTimings.apply(this.performanceContext, arguments);
    }

};


text:
/*
 * has-meta.js: Stream for filtering events with a given meta key (or set of keys).
 *
 * (C) 2012, Nodejitsu Inc.
 *
 */

var util = require('util'),
    ReadWriteStream = require('../common/read-write-stream');

//
// ### function HasMeta ([type], keys|key0, key, ..., keyN)
// #### @type {any|all} Type of tag filtering to perform: any or all.
// #### @keys|key0..keyN {Array|arguments} Full set of keys to filter over.
// Constructor function of the HasMeta stream responsible for filtering
// events with a given meta key (or set of keys).
//
var HasMeta = module.exports = function (type) {
  ReadWriteStream.call(this);

  var keys = Array.prototype.slice.call(arguments);

  if (type === 'any' || type === 'all') {
    this.type = type;
    keys.splice(0, 1);
  }
  else {
    this.type === 'any';
  }

  //
  // Create a lookup table of any values provided.
  // If no value is provided set the key to `null`
  // since we will be checking for `undefined`.
  //
  this.lookup = keys.reduce(function (all, key) {
    if (Array.isArray(key)) {
      key.forEach(function (kkey) {
        all[kkey] = null;
      });
    }
    else if (typeof key === 'object') {
      Object.keys(key).forEach(function (kkey) {
        all[kkey] = key[kkey];
      });
    }
    else {
      all[key] = null;
    }

    return all;
  }, {});

  //
  // Store the list of keys for iterating over later.
  //
  this.keys = Object.keys(this.lookup);
};

//
// Inherit from ReadWriteStream
//
util.inherits(HasMeta, ReadWriteStream);

//
// ### function write (data)
// #### @data {Object} JSON to rollup.
// Only filters `data` according to `this.keys`.
//
HasMeta.prototype.write = function (data) {
  var self = this;

  //
  // If there are no tags on the data return
  //
  if (!data.meta) {
    return;
  }

  //
  // Helper function for checking a given `key`.
  //
  function hasKey(key) {
    return data.meta[key] !== undefined
      && (self.lookup[key] === null ||
      self.lookup[key] === data.meta[key]);
  }

  var valid = this.type === 'all'
    ? this.keys.every(hasKey)
    : this.keys.some(hasKey);

  if (!valid) {
    return;
  }

  this.emit('data', data);
};


text:
package internal

import (
	"strings"

	dns "google.golang.org/api/dns/v1"
	"k8s.io/apimachinery/pkg/util/uuid"
	"k8s.io/kops/dnsprovider/pkg/dnsprovider/providers/google/clouddns/internal/interfaces"
)

// Compile time check for interface adherence
var _ interfaces.ManagedZonesService = &ManagedZonesService{}

type ManagedZonesService struct{ impl *dns.ManagedZonesService }

func (m *ManagedZonesService) Create(project string, managedzone interfaces.ManagedZone) interfaces.ManagedZonesCreateCall {
	return &ManagedZonesCreateCall{m.impl.Create(project, managedzone.(*ManagedZone).impl)}
}

func (m *ManagedZonesService) Delete(project, managedZone string) interfaces.ManagedZonesDeleteCall {
	return &ManagedZonesDeleteCall{m.impl.Delete(project, managedZone)}
}

func (m *ManagedZonesService) Get(project, managedZone string) interfaces.ManagedZonesGetCall {
	return &ManagedZonesGetCall{m.impl.Get(project, managedZone)}
}

func (m *ManagedZonesService) List(project string) interfaces.ManagedZonesListCall {
	return &ManagedZonesListCall{m.impl.List(project)}
}

func (m *ManagedZonesService) NewManagedZone(dnsName string) interfaces.ManagedZone {
	name := "x" + strings.Replace(string(uuid.NewUUID()), "-", "", -1)[0:30] // Unique name, strip out the "-" chars to shorten it, start with a lower case alpha, and truncate to Cloud DNS 32 character limit
	return &ManagedZone{impl: &dns.ManagedZone{Name: name, Description: "Kubernetes Federated Service", DnsName: dnsName}}
}


text:
/*
A zero-indexed array A consisting of N integers is given. An inversion is a pair of indexes (P, Q) such that P < Q and A[Q] < A[P].
Write a function:

  int solution(const vector<int> &A);

that computes the number of inversions in A, or returns −1 if it exceeds 1,000,000,000.
Assume that:
  N is an integer within the range [0..100,000];
  each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].

For example, in the following array:
  A[0] = -1 A[1] = 6 A[2] = 3
  A[3] =  4 A[4] = 7 A[5] = 4

there are four inversions:
  (1,2)  (1,3)  (1,5)  (4,5)

so the function should return 4.

Complexity:
  expected worst-case time complexity is O(N*log(N));
  expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).

*/

#include <fstream>
#include <iostream>
#include <sstream>
//-----------------------------------------------------------------------------------
#include <vector>
#include <algorithm>
#include <stdlib.h>
using namespace std;

/*
def mergesort( aList, first, last ):
    ''' Modified merge sort algorithm.
        Record the inversion count during sort.
    '''
    mid = ( first + last ) / 2
    if first < last:
        # Recursive calling
        left_inver = mergesort( aList, first, mid )
        right_inver = mergesort( aList, mid + 1, last )
    else:
        # Terminate condition
        return 0

    first_index = first     # The index for the left part
    second_index = mid + 1  # The index for the right part
    temp = [0] * (last-first+1)     # To hold the sorted content
    temp_index = 0
    merge_inver = 0         # Number of inversion in merging

    while first_index <= mid and second_index <= last:
        if aList[first_index] <= aList[second_index]:
            # Less index indicates less value. No inversion.
            temp[temp_index] = aList[first_index]
            first_index += 1
        else:
            # Greater index has less value. Inversion exists.
            # For exampe:
            #       [     4,   5,   2,   3     ]
            #       | Left part |  |Right Part|
            # and first_index = 1, second_index = 3, mid = 2
            # We need the item "2" to be the position 0. So it
            # has to pass all the unwritten items in left part.
            # Here these unwritten items are "4" and "5". So
            # two more inversions are involved.
            # In general, the left part is sorted. So all the
            # elements, being and after first_index, are greater
            # than element in position second_index. AND all of
            # them have less indexes. As the result,
            # there are mid-first_index+1 new reversions.
            temp[temp_index] = aList[second_index]
            second_index += 1
            merge_inver += mid - first_index + 1
        temp_index += 1

    if first_index != mid+1:
        # Some element in the left part left. They have less
        # indexes, but greater values. Inversion involves.
        # BUT these inversions have already been counted.
        while first_index <= mid:
            temp[temp_index] = aList[first_index]
            first_index += 1
            temp_index += 1

    if second_index != last+1:
        # Some element in the right part left. They have both
        # greater indexes and values than all in the left part.
        # No inversion is involved.
        while second_index <= last:
            temp[temp_index] = aList[second_index]
            second_index += 1
            temp_index += 1

    # Rewrite the sorted content into the original array
    aList[first:last+1] = temp[:]

    return merge_inver + left_inver + right_inver

def solution(A):
    return mergesort( A * 1, 0, len(A)-1)
*/

// Modified merge sort algorithm.
// Record the inversion count during sort.
int mergesort(vector<int> & aList, int first, int last){
  cout << "first1: " << first << endl;
  cout << "last1: " << last << endl;
  int mid = (int)(first + last) / 2;
  int left_inver;
  int right_inver;
  if (first < last){
    // Recursive calling
    left_inver = mergesort(aList, first, mid);
    right_inver = mergesort(aList, mid + 1, last);
  }
  else
      // Terminate condition
    return 0;

  int first_index = first;            // The index for the left part
  int second_index = mid + 1;         // The index for the right part
  cout << "last-first+1: " << last-first+1 << endl;
  vector<int>  temp(last-first+1, 0); // To hold the sorted content
  int temp_index = 0;
  int merge_inver = 0;                // Number of inversion in merging

  while ((first_index <= mid) && (second_index <= last)){
    if (aList[first_index] <= aList[second_index]){
      // Less index indicates less value. No inversion.
      temp[temp_index] = aList[first_index];
      first_index += 1;
    } else {
      // Greater index has less value. Inversion exists.
      // For exampe:
      //       [     4,   5,   2,   3     ]
      //       | Left part |  |Right Part|
      // and first_index = 1, second_index = 3, mid = 2
      // We need the item "2" to be the position 0. So it
      // has to pass all the unwritten items in left part.
      // Here these unwritten items are "4" and "5". So
      // two more inversions are involved.
      // In general, the left part is sorted. So all the
      // elements, being and after first_index, are greater
      // than element in position second_index. AND all of
      // them have less indexes. As the result,
      // there are mid-first_index+1 new reversions.
      temp[temp_index] = aList[second_index];
      second_index += 1;
      merge_inver += mid - first_index + 1;
      temp_index += 1;
    }
    temp_index += 1;
  }

  if (first_index != mid+1)
    // Some element in the left part left. They have less
    // indexes, but greater values. Inversion involves.
    // BUT these inversions have already been counted.
    while (first_index <= mid){
      temp[temp_index] = aList[first_index];
      first_index += 1;
      temp_index += 1;
    }

  if (second_index != last+1)
    // Some element in the right part left. They have both
    // greater indexes and values than all in the left part.
    // No inversion is involved.
    while (second_index <= last){
      temp[temp_index] = aList[second_index];
      second_index += 1;
      temp_index += 1;
    }

  // Rewrite the sorted content into the original array
  cout << "first2: " << first << endl;
  cout << "last2: " << last << endl;
  for (int i = first; i <= last;i++) aList[i] = temp[i];

  cout << "ok"  << endl;
  return merge_inver + left_inver + right_inver;
}

int solution(vector<int> &A) {
  return mergesort(A, 0, A.size()-1);
}

// 80%, O(N**2)
int solution2(vector<int> &A) {
  int R = 0;
  int N = A.size();

  for(int i = 0; i<N-1; i++)
    for (int k = i+1; k<N; k++){
      if (A[i] > A[k]) R++;
      if (R > 1000000000) return -1;
    }

  return R;
}

//-----------------------------------------------------------------------------------

void print_v(vector<int> &A){
  int N = A.size();
  cout << "Size: " << N << endl;
  for(int i=0;i<N;i++){
    cout << A[i] << " ";
  }
  cout << endl;
}

int main(int argc,char *argv[]){
  if(argc < 2) {
    printf("You must provide at least one argument\n");
    exit(0);
  }
  string line;
  ifstream file;
  file.open(argv[1]);
  while(getline(file, line)){

    int i;
    vector<int> P;
    istringstream issP(line);
    while (issP >> i)
      P.push_back(i);
    print_v(P);
    cout << "solution: " << solution(P) << endl << endl;
  }
  return 0;
}


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Transactions;
using Abp.Application.Features;
using Abp.Auditing;
using Abp.Authorization.Roles;
using Abp.Configuration;
using Abp.Configuration.Startup;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Domain.Services;
using Abp.Domain.Uow;
using Abp.Extensions;
using Abp.IdentityFramework;
using Abp.Localization;
using Abp.MultiTenancy;
using Abp.Organizations;
using Abp.Runtime.Caching;
using Abp.Runtime.Security;
using Abp.Runtime.Session;
using Abp.Timing;
using Abp.Zero;
using Abp.Zero.Configuration;
using Microsoft.AspNet.Identity;

namespace Abp.Authorization.Users
{
    /// <summary>
    /// Extends <see cref="UserManager{TUser,TKey}"/> of ASP.NET Identity Framework.
    /// </summary>
    public abstract class AbpUserManager<TTenant, TRole, TUser>
        : UserManager<TUser, long>,
        IDomainService
        where TTenant : AbpTenant<TTenant, TUser>
        where TRole : AbpRole<TTenant, TUser>, new()
        where TUser : AbpUser<TTenant, TUser>
    {
        private IUserPermissionStore<TTenant, TUser> UserPermissionStore
        {
            get
            {
                if (!(Store is IUserPermissionStore<TTenant, TUser>))
                {
                    throw new AbpException("Store is not IUserPermissionStore");
                }

                return Store as IUserPermissionStore<TTenant, TUser>;
            }
        }

        public ILocalizationManager LocalizationManager { get; set; }

        public IAbpSession AbpSession { get; set; }

        public IAuditInfoProvider AuditInfoProvider { get; set; }

        public FeatureDependencyContext FeatureDependencyContext { get; set; }

        protected AbpRoleManager<TTenant, TRole, TUser> RoleManager { get; private set; }

        protected ISettingManager SettingManager { get; private set; }

        protected AbpUserStore<TTenant, TRole, TUser> AbpStore { get; private set; }

        private readonly IPermissionManager _permissionManager;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly IUserManagementConfig _userManagementConfig;
        private readonly IIocResolver _iocResolver;
        private readonly IRepository<TTenant> _tenantRepository;
        private readonly IMultiTenancyConfig _multiTenancyConfig;
        private readonly ICacheManager _cacheManager;
        private readonly IRepository<OrganizationUnit, long> _organizationUnitRepository;
        private readonly IRepository<UserOrganizationUnit, long> _userOrganizationUnitRepository;
        private readonly IOrganizationUnitSettings _organizationUnitSettings;
        private readonly IRepository<UserLoginAttempt, long> _userLoginAttemptRepository;

        protected AbpUserManager(
            AbpUserStore<TTenant, TRole, TUser> userStore,
            AbpRoleManager<TTenant, TRole, TUser> roleManager,
            IRepository<TTenant> tenantRepository,
            IMultiTenancyConfig multiTenancyConfig,
            IPermissionManager permissionManager,
            IUnitOfWorkManager unitOfWorkManager,
            ISettingManager settingManager,
            IUserManagementConfig userManagementConfig,
            IIocResolver iocResolver,
            ICacheManager cacheManager,
            IRepository<OrganizationUnit, long> organizationUnitRepository,
            IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository,
            IOrganizationUnitSettings organizationUnitSettings,
            IRepository<UserLoginAttempt, long> userLoginAttemptRepository)
            : base(userStore)
        {
            AbpStore = userStore;
            RoleManager = roleManager;
            SettingManager = settingManager;
            _tenantRepository = tenantRepository;
            _multiTenancyConfig = multiTenancyConfig;
            _permissionManager = permissionManager;
            _unitOfWorkManager = unitOfWorkManager;
            _userManagementConfig = userManagementConfig;
            _iocResolver = iocResolver;
            _cacheManager = cacheManager;
            _organizationUnitRepository = organizationUnitRepository;
            _userOrganizationUnitRepository = userOrganizationUnitRepository;
            _organizationUnitSettings = organizationUnitSettings;
            _userLoginAttemptRepository = userLoginAttemptRepository;

            LocalizationManager = NullLocalizationManager.Instance;
            AbpSession = NullAbpSession.Instance;
        }

        public override async Task<IdentityResult> CreateAsync(TUser user)
        {
            var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress);
            if (!result.Succeeded)
            {
                return result;
            }

            if (AbpSession.TenantId.HasValue)
            {
                user.TenantId = AbpSession.TenantId.Value;
            }

            return await base.CreateAsync(user);
        }

        /// <summary>
        /// Check whether a user is granted for a permission.
        /// </summary>
        /// <param name="userId">User id</param>
        /// <param name="permissionName">Permission name</param>
        public virtual async Task<bool> IsGrantedAsync(long userId, string permissionName)
        {
            return await IsGrantedAsync(
                userId,
                _permissionManager.GetPermission(permissionName)
                );
        }

        /// <summary>
        /// Check whether a user is granted for a permission.
        /// </summary>
        /// <param name="user">User</param>
        /// <param name="permission">Permission</param>
        public virtual Task<bool> IsGrantedAsync(TUser user, Permission permission)
        {
            return IsGrantedAsync(user.Id, permission);
        }

        /// <summary>
        /// Check whether a user is granted for a permission.
        /// </summary>
        /// <param name="userId">User id</param>
        /// <param name="permission">Permission</param>
        public virtual async Task<bool> IsGrantedAsync(long userId, Permission permission)
        {
            //Check for multi-tenancy side
            if (!permission.MultiTenancySides.HasFlag(AbpSession.MultiTenancySide))
            {
                return false;
            }

            //Check for depended features
            if (permission.FeatureDependency != null && AbpSession.MultiTenancySide == MultiTenancySides.Tenant)
            {
                if (!await permission.FeatureDependency.IsSatisfiedAsync(FeatureDependencyContext))
                {
                    return false;
                }
            }

            //Get cached user permissions
            var cacheItem = await GetUserPermissionCacheItemAsync(userId);

            //Check for user-specific value
            if (cacheItem.GrantedPermissions.Contains(permission.Name))
            {
                return true;
            }

            if (cacheItem.ProhibitedPermissions.Contains(permission.Name))
            {
                return false;
            }

            //Check for roles
            foreach (var roleId in cacheItem.RoleIds)
            {
                if (await RoleManager.IsGrantedAsync(roleId, permission))
                {
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// Gets granted permissions for a user.
        /// </summary>
        /// <param name="user">Role</param>
        /// <returns>List of granted permissions</returns>
        public virtual async Task<IReadOnlyList<Permission>> GetGrantedPermissionsAsync(TUser user)
        {
            var permissionList = new List<Permission>();

            foreach (var permission in _permissionManager.GetAllPermissions())
            {
                if (await IsGrantedAsync(user.Id, permission))
                {
                    permissionList.Add(permission);
                }
            }

            return permissionList;
        }

        /// <summary>
        /// Sets all granted permissions of a user at once.
        /// Prohibits all other permissions.
        /// </summary>
        /// <param name="user">The user</param>
        /// <param name="permissions">Permissions</param>
        public virtual async Task SetGrantedPermissionsAsync(TUser user, IEnumerable<Permission> permissions)
        {
            var oldPermissions = await GetGrantedPermissionsAsync(user);
            var newPermissions = permissions.ToArray();

            foreach (var permission in oldPermissions.Where(p => !newPermissions.Contains(p)))
            {
                await ProhibitPermissionAsync(user, permission);
            }

            foreach (var permission in newPermissions.Where(p => !oldPermissions.Contains(p)))
            {
                await GrantPermissionAsync(user, permission);
            }
        }

        /// <summary>
        /// Prohibits all permissions for a user.
        /// </summary>
        /// <param name="user">User</param>
        public async Task ProhibitAllPermissionsAsync(TUser user)
        {
            foreach (var permission in _permissionManager.GetAllPermissions())
            {
                await ProhibitPermissionAsync(user, permission);
            }
        }

        /// <summary>
        /// Resets all permission settings for a user.
        /// It removes all permission settings for the user.
        /// User will have permissions according to his roles.
        /// This method does not prohibit all permissions.
        /// For that, use <see cref="ProhibitAllPermissionsAsync"/>.
        /// </summary>
        /// <param name="user">User</param>
        public async Task ResetAllPermissionsAsync(TUser user)
        {
            await UserPermissionStore.RemoveAllPermissionSettingsAsync(user);
        }

        /// <summary>
        /// Grants a permission for a user if not already granted.
        /// </summary>
        /// <param name="user">User</param>
        /// <param name="permission">Permission</param>
        public virtual async Task GrantPermissionAsync(TUser user, Permission permission)
        {
            await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, false));

            if (await IsGrantedAsync(user.Id, permission))
            {
                return;
            }

            await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, true));
        }

        /// <summary>
        /// Prohibits a permission for a user if it's granted.
        /// </summary>
        /// <param name="user">User</param>
        /// <param name="permission">Permission</param>
        public virtual async Task ProhibitPermissionAsync(TUser user, Permission permission)
        {
            await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, true));

            if (!await IsGrantedAsync(user.Id, permission))
            {
                return;
            }

            await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, false));
        }

        public virtual async Task<TUser> FindByNameOrEmailAsync(string userNameOrEmailAddress)
        {
            return await AbpStore.FindByNameOrEmailAsync(userNameOrEmailAddress);
        }

        public virtual Task<List<TUser>> FindAllAsync(UserLoginInfo login)
        {
            return AbpStore.FindAllAsync(login);
        }

        [UnitOfWork]
        public virtual async Task<AbpLoginResult> LoginAsync(UserLoginInfo login, string tenancyName = null)
        {
            var result = await LoginAsyncInternal(login, tenancyName);
            await SaveLoginAttempt(result, tenancyName, login.ProviderKey + "@" + login.LoginProvider);
            return result;
        }

        private async Task<AbpLoginResult> LoginAsyncInternal(UserLoginInfo login, string tenancyName)
        {
            if (login == null || login.LoginProvider.IsNullOrEmpty() || login.ProviderKey.IsNullOrEmpty())
            {
                throw new ArgumentException("login");
            }

            //Get and check tenant
            TTenant tenant = null;
            if (!_multiTenancyConfig.IsEnabled)
            {
                tenant = await GetDefaultTenantAsync();
            }
            else if (!string.IsNullOrWhiteSpace(tenancyName))
            {
                tenant = await _tenantRepository.FirstOrDefaultAsync(t => t.TenancyName == tenancyName);
                if (tenant == null)
                {
                    return new AbpLoginResult(AbpLoginResultType.InvalidTenancyName);
                }

                if (!tenant.IsActive)
                {
                    return new AbpLoginResult(AbpLoginResultType.TenantIsNotActive, tenant);
                }
            }

            using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.MayHaveTenant))
            {
                var user = await AbpStore.FindAsync(tenant == null ? (int?)null : tenant.Id, login);
                if (user == null)
                {
                    return new AbpLoginResult(AbpLoginResultType.UnknownExternalLogin, tenant);
                }

                return await CreateLoginResultAsync(user, tenant);
            }
        }

        [UnitOfWork]
        public virtual async Task<AbpLoginResult> LoginAsync(string userNameOrEmailAddress, string plainPassword, string tenancyName = null)
        {
            var result = await LoginAsyncInternal(userNameOrEmailAddress, plainPassword, tenancyName);
            await SaveLoginAttempt(result, tenancyName, userNameOrEmailAddress);
            return result;
        }

        private async Task<AbpLoginResult> LoginAsyncInternal(string userNameOrEmailAddress, string plainPassword, string tenancyName = null)
        {
            if (userNameOrEmailAddress.IsNullOrEmpty())
            {
                throw new ArgumentNullException("userNameOrEmailAddress");
            }

            if (plainPassword.IsNullOrEmpty())
            {
                throw new ArgumentNullException("plainPassword");
            }

            //Get and check tenant
            TTenant tenant = null;
            if (!_multiTenancyConfig.IsEnabled)
            {
                tenant = await GetDefaultTenantAsync();
            }
            else if (!string.IsNullOrWhiteSpace(tenancyName))
            {
                tenant = await _tenantRepository.FirstOrDefaultAsync(t => t.TenancyName == tenancyName);
                if (tenant == null)
                {
                    return new AbpLoginResult(AbpLoginResultType.InvalidTenancyName);
                }

                if (!tenant.IsActive)
                {
                    return new AbpLoginResult(AbpLoginResultType.TenantIsNotActive, tenant);
                }
            }

            using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.MayHaveTenant))
            {
                var loggedInFromExternalSource = await TryLoginFromExternalAuthenticationSources(userNameOrEmailAddress, plainPassword, tenant);

                var user = await AbpStore.FindByNameOrEmailAsync(tenant == null ? (int?)null : tenant.Id, userNameOrEmailAddress);
                if (user == null)
                {
                    return new AbpLoginResult(AbpLoginResultType.InvalidUserNameOrEmailAddress, tenant);
                }

                if (!loggedInFromExternalSource)
                {
                    var verificationResult = new PasswordHasher().VerifyHashedPassword(user.Password, plainPassword);
                    if (verificationResult != PasswordVerificationResult.Success)
                    {
                        return new AbpLoginResult(AbpLoginResultType.InvalidPassword, tenant, user);
                    }
                }

                return await CreateLoginResultAsync(user, tenant);
            }
        }

        private async Task<AbpLoginResult> CreateLoginResultAsync(TUser user, TTenant tenant = null)
        {
            if (!user.IsActive)
            {
                return new AbpLoginResult(AbpLoginResultType.UserIsNotActive);
            }

            if (await IsEmailConfirmationRequiredForLoginAsync(user.TenantId) && !user.IsEmailConfirmed)
            {
                return new AbpLoginResult(AbpLoginResultType.UserEmailIsNotConfirmed);
            }

            user.LastLoginTime = Clock.Now;

            await Store.UpdateAsync(user);

            await _unitOfWorkManager.Current.SaveChangesAsync();

            return new AbpLoginResult(tenant, user, await CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie));
        }

        private async Task SaveLoginAttempt(AbpLoginResult loginResult, string tenancyName, string userNameOrEmailAddress)
        {
            using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.Suppress))
            {
                var loginAttempt = new UserLoginAttempt
                {
                    TenantId = loginResult.Tenant != null ? loginResult.Tenant.Id : (int?)null,
                    TenancyName = tenancyName,

                    UserId = loginResult.User != null ? loginResult.User.Id : (long?)null,
                    UserNameOrEmailAddress = userNameOrEmailAddress,

                    Result = loginResult.Result,
                };

                //TODO: We should replace this workaround with IClientInfoProvider when it's implemented in ABP (https://github.com/aspnetboilerplate/aspnetboilerplate/issues/926)
                if (AuditInfoProvider != null)
                {
                    var auditInfo = new AuditInfo();
                    AuditInfoProvider.Fill(auditInfo);
                    loginAttempt.BrowserInfo = auditInfo.BrowserInfo;
                    loginAttempt.ClientIpAddress = auditInfo.ClientIpAddress;
                    loginAttempt.ClientName = auditInfo.ClientName;
                }

                await _userLoginAttemptRepository.InsertAsync(loginAttempt);

                await _unitOfWorkManager.Current.SaveChangesAsync();
                await uow.CompleteAsync();
            }
        }

        private async Task<bool> TryLoginFromExternalAuthenticationSources(string userNameOrEmailAddress, string plainPassword, TTenant tenant)
        {
            if (!_userManagementConfig.ExternalAuthenticationSources.Any())
            {
                return false;
            }

            foreach (var sourceType in _userManagementConfig.ExternalAuthenticationSources)
            {
                using (var source = _iocResolver.ResolveAsDisposable<IExternalAuthenticationSource<TTenant, TUser>>(sourceType))
                {
                    if (await source.Object.TryAuthenticateAsync(userNameOrEmailAddress, plainPassword, tenant))
                    {
                        var tenantId = tenant == null ? (int?)null : tenant.Id;

                        var user = await AbpStore.FindByNameOrEmailAsync(tenantId, userNameOrEmailAddress);
                        if (user == null)
                        {
                            user = await source.Object.CreateUserAsync(userNameOrEmailAddress, tenant);

                            user.Tenant = tenant;
                            user.AuthenticationSource = source.Object.Name;
                            user.Password = new PasswordHasher().HashPassword(Guid.NewGuid().ToString("N").Left(16)); //Setting a random password since it will not be used

                            user.Roles = new List<UserRole>();
                            foreach (var defaultRole in RoleManager.Roles.Where(r => r.TenantId == tenantId && r.IsDefault).ToList())
                            {
                                user.Roles.Add(new UserRole { RoleId = defaultRole.Id });
                            }

                            await Store.CreateAsync(user);
                        }
                        else
                        {
                            await source.Object.UpdateUserAsync(user, tenant);

                            user.AuthenticationSource = source.Object.Name;

                            await Store.UpdateAsync(user);
                        }

                        await _unitOfWorkManager.Current.SaveChangesAsync();

                        return true;
                    }
                }
            }

            return false;
        }

        /// <summary>
        /// Gets a user by given id.
        /// Throws exception if no user found with given id.
        /// </summary>
        /// <param name="userId">User id</param>
        /// <returns>User</returns>
        /// <exception cref="AbpException">Throws exception if no user found with given id</exception>
        public virtual async Task<TUser> GetUserByIdAsync(long userId)
        {
            var user = await FindByIdAsync(userId);
            if (user == null)
            {
                throw new AbpException("There is no user with id: " + userId);
            }

            return user;
        }

        public async override Task<ClaimsIdentity> CreateIdentityAsync(TUser user, string authenticationType)
        {
            var identity = await base.CreateIdentityAsync(user, authenticationType);
            if (user.TenantId.HasValue)
            {
                identity.AddClaim(new Claim(AbpClaimTypes.TenantId, user.TenantId.Value.ToString(CultureInfo.InvariantCulture)));
            }

            return identity;
        }

        public async override Task<IdentityResult> UpdateAsync(TUser user)
        {
            var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress);
            if (!result.Succeeded)
            {
                return result;
            }

            var oldUserName = (await GetUserByIdAsync(user.Id)).UserName;
            if (oldUserName == AbpUser<TTenant, TUser>.AdminUserName && user.UserName != AbpUser<TTenant, TUser>.AdminUserName)
            {
                return AbpIdentityResult.Failed(string.Format(L("CanNotRenameAdminUser"), AbpUser<TTenant, TUser>.AdminUserName));
            }

            return await base.UpdateAsync(user);
        }

        public async override Task<IdentityResult> DeleteAsync(TUser user)
        {
            if (user.UserName == AbpUser<TTenant, TUser>.AdminUserName)
            {
                return AbpIdentityResult.Failed(string.Format(L("CanNotDeleteAdminUser"), AbpUser<TTenant, TUser>.AdminUserName));
            }

            return await base.DeleteAsync(user);
        }

        public virtual async Task<IdentityResult> ChangePasswordAsync(TUser user, string newPassword)
        {
            var result = await PasswordValidator.ValidateAsync(newPassword);
            if (!result.Succeeded)
            {
                return result;
            }

            await AbpStore.SetPasswordHashAsync(user, PasswordHasher.HashPassword(newPassword));
            return IdentityResult.Success;
        }

        public virtual async Task<IdentityResult> CheckDuplicateUsernameOrEmailAddressAsync(long? expectedUserId, string userName, string emailAddress)
        {
            var user = (await FindByNameAsync(userName));
            if (user != null && user.Id != expectedUserId)
            {
                return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateName"), userName));
            }

            user = (await FindByEmailAsync(emailAddress));
            if (user != null && user.Id != expectedUserId)
            {
                return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateEmail"), emailAddress));
            }

            return IdentityResult.Success;
        }

        public virtual async Task<IdentityResult> SetRoles(TUser user, string[] roleNames)
        {
            //Remove from removed roles
            foreach (var userRole in user.Roles.ToList())
            {
                var role = await RoleManager.FindByIdAsync(userRole.RoleId);
                if (roleNames.All(roleName => role.Name != roleName))
                {
                    var result = await RemoveFromRoleAsync(user.Id, role.Name);
                    if (!result.Succeeded)
                    {
                        return result;
                    }
                }
            }

            //Add to added roles
            foreach (var roleName in roleNames)
            {
                var role = await RoleManager.GetRoleByNameAsync(roleName);
                if (user.Roles.All(ur => ur.RoleId != role.Id))
                {
                    var result = await AddToRoleAsync(user.Id, roleName);
                    if (!result.Succeeded)
                    {
                        return result;
                    }
                }
            }

            return IdentityResult.Success;
        }

        public virtual async Task<bool> IsInOrganizationUnitAsync(long userId, long ouId)
        {
            return await IsInOrganizationUnitAsync(
                await GetUserByIdAsync(userId),
                await _organizationUnitRepository.GetAsync(ouId)
                );
        }

        public virtual async Task<bool> IsInOrganizationUnitAsync(TUser user, OrganizationUnit ou)
        {
            return await _userOrganizationUnitRepository.CountAsync(uou =>
                uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id
                ) > 0;
        }

        public virtual async Task AddToOrganizationUnitAsync(long userId, long ouId)
        {
            await AddToOrganizationUnitAsync(
                await GetUserByIdAsync(userId),
                await _organizationUnitRepository.GetAsync(ouId)
                );
        }

        public virtual async Task AddToOrganizationUnitAsync(TUser user, OrganizationUnit ou)
        {
            var currentOus = await GetOrganizationUnitsAsync(user);

            if (currentOus.Any(cou => cou.Id == ou.Id))
            {
                return;
            }

            await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, currentOus.Count + 1);

            await _userOrganizationUnitRepository.InsertAsync(new UserOrganizationUnit(user.TenantId, user.Id, ou.Id));
        }

        public virtual async Task RemoveFromOrganizationUnitAsync(long userId, long ouId)
        {
            await RemoveFromOrganizationUnitAsync(
                await GetUserByIdAsync(userId),
                await _organizationUnitRepository.GetAsync(ouId)
                );
        }

        public virtual async Task RemoveFromOrganizationUnitAsync(TUser user, OrganizationUnit ou)
        {
            await _userOrganizationUnitRepository.DeleteAsync(uou => uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id);
        }

        public virtual async Task SetOrganizationUnitsAsync(long userId, params long[] organizationUnitIds)
        {
            await SetOrganizationUnitsAsync(
                await GetUserByIdAsync(userId),
                organizationUnitIds
                );
        }

        private async Task CheckMaxUserOrganizationUnitMembershipCountAsync(int? tenantId, int requestedCount)
        {
            var maxCount = await _organizationUnitSettings.GetMaxUserMembershipCountAsync(tenantId);
            if (requestedCount > maxCount)
            {
                throw new AbpException(string.Format("Can not set more than {0} organization unit for a user!", maxCount));
            }
        }

        public virtual async Task SetOrganizationUnitsAsync(TUser user, params long[] organizationUnitIds)
        {
            if (organizationUnitIds == null)
            {
                organizationUnitIds = new long[0];
            }

            await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, organizationUnitIds.Length);

            var currentOus = await GetOrganizationUnitsAsync(user);

            //Remove from removed OUs
            foreach (var currentOu in currentOus)
            {
                if (!organizationUnitIds.Contains(currentOu.Id))
                {
                    await RemoveFromOrganizationUnitAsync(user, currentOu);
                }
            }

            //Add to added OUs
            foreach (var organizationUnitId in organizationUnitIds)
            {
                if (currentOus.All(ou => ou.Id != organizationUnitId))
                {
                    await AddToOrganizationUnitAsync(
                        user,
                        await _organizationUnitRepository.GetAsync(organizationUnitId)
                        );
                }
            }
        }

        [UnitOfWork]
        public virtual Task<List<OrganizationUnit>> GetOrganizationUnitsAsync(TUser user)
        {
            var query = from uou in _userOrganizationUnitRepository.GetAll()
                        join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id
                        where uou.UserId == user.Id
                        select ou;

            return Task.FromResult(query.ToList());
        }

        [UnitOfWork]
        public virtual Task<List<TUser>> GetUsersInOrganizationUnit(OrganizationUnit organizationUnit, bool includeChildren = false)
        {
            if (!includeChildren)
            {
                var query = from uou in _userOrganizationUnitRepository.GetAll()
                            join user in AbpStore.Users on uou.UserId equals user.Id
                            where uou.OrganizationUnitId == organizationUnit.Id
                            select user;

                return Task.FromResult(query.ToList());
            }
            else
            {
                var query = from uou in _userOrganizationUnitRepository.GetAll()
                            join user in AbpStore.Users on uou.UserId equals user.Id
                            join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id
                            where ou.Code.StartsWith(organizationUnit.Code)
                            select user;

                return Task.FromResult(query.ToList());
            }
        }

        private async Task<bool> IsEmailConfirmationRequiredForLoginAsync(int? tenantId)
        {
            if (tenantId.HasValue)
            {
                return await SettingManager.GetSettingValueForTenantAsync<bool>(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin, tenantId.Value);
            }

            return await SettingManager.GetSettingValueForApplicationAsync<bool>(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin);
        }

        private async Task<TTenant> GetDefaultTenantAsync()
        {
            var tenant = await _tenantRepository.FirstOrDefaultAsync(t => t.TenancyName == AbpTenant<TTenant, TUser>.DefaultTenantName);
            if (tenant == null)
            {
                throw new AbpException("There should be a 'Default' tenant if multi-tenancy is disabled!");
            }

            return tenant;
        }

        private async Task<UserPermissionCacheItem> GetUserPermissionCacheItemAsync(long userId)
        {
            return await _cacheManager.GetUserPermissionCache().GetAsync(userId, async () =>
            {
                var newCacheItem = new UserPermissionCacheItem(userId);

                foreach (var roleName in await GetRolesAsync(userId))
                {
                    newCacheItem.RoleIds.Add((await RoleManager.GetRoleByNameAsync(roleName)).Id);
                }

                foreach (var permissionInfo in await UserPermissionStore.GetPermissionsAsync(userId))
                {
                    if (permissionInfo.IsGranted)
                    {
                        newCacheItem.GrantedPermissions.Add(permissionInfo.Name);
                    }
                    else
                    {
                        newCacheItem.ProhibitedPermissions.Add(permissionInfo.Name);
                    }
                }

                return newCacheItem;
            });
        }

        private string L(string name)
        {
            return LocalizationManager.GetString(AbpZeroConsts.LocalizationSourceName, name);
        }

        public class AbpLoginResult
        {
            public AbpLoginResultType Result { get; private set; }

            public TTenant Tenant { get; private set; }

            public TUser User { get; private set; }

            public ClaimsIdentity Identity { get; private set; }

            public AbpLoginResult(AbpLoginResultType result, TTenant tenant = null, TUser user = null)
            {
                Result = result;
                Tenant = tenant;
                User = user;
            }

            public AbpLoginResult(TTenant tenant, TUser user, ClaimsIdentity identity)
                : this(AbpLoginResultType.Success, tenant)
            {
                User = user;
                Identity = identity;
            }
        }
    }
}


text:
COMMAND_CACHE_INVALIDATION = 1
COMMAND_AUTH_SESSION = 10
COMMAND_LOGOFF_SESSION = 11
COMMAND_ONLINE = 20
COMMAND_OFFLINE = 21


text: Presentation given to HumanTalks Grenoble on 2013-02-12


text:
<?php

/**
 * This is the model class for table "review_entity_summary".
 *
 * The followings are the available columns in table 'review_entity_summary':
 * @property string $primary_id
 * @property string $entity_pk_value
 * @property integer $entity_type
 * @property integer $reviews_count
 * @property integer $rating_summary
 * @property integer $store_id
 */
class Mage1ReviewEntitySummaryPeer extends Mage1ActiveRecord
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{review_entity_summary}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('entity_type, reviews_count, rating_summary, store_id', 'numerical', 'integerOnly'=>true),
			array('entity_pk_value', 'length', 'max'=>20),
		);
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Mage1ReviewEntitySummaryPeer the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
}


text:
module Constants where

type Time = Double
delta_time = 0.05 :: Time

window_x = 800 :: Int
window_y = 600 :: Int

hit_dist_threshold = 15.0


text:
{% extends "siteTemplate.html" %} {% load staticfiles %}

{% block content %}

<form action="" method="post">{% csrf_token %}

        Email address
        <input type="email" class="form-control" id="email" name="email" placeholder="Used to send exclusive info">

        Username
        <input type="text" class="form-control" id="username" name="username" placeholder="Username">

        Password
        <input type="password" class="form-control" id="password" name="password" placeholder="Password">

    First name
    <input type="text" class="form-control" id="firstname" name="firstname" placeholder="First name">

    Last name
    <input type="text" class="form-control" id="lastname" name="lastname" placeholder="Last name">

    <button class="btn btn-success">Sign Up</button>
</form>

{% endblock %}


text:
Ext.override(Ext.chart.axis.Axis, {

    drawHorizontalLabels: function() {
       var  me = this,
            labelConf = me.label,
            floor = Math.floor,
            max = Math.max,
            axes = me.chart.axes,
            position = me.position,
            inflections = me.inflections,
            ln = inflections.length,
            labels = me.labels,
            labelGroup = me.labelGroup,
            maxHeight = 0,
            ratio,
            gutterY = me.chart.maxGutter[1],
            ubbox, bbox, point, prevX, prevLabel,
            projectedWidth = 0,
            textLabel, attr, textRight, text,
            label, last, x, y, i, firstLabel;

        last = ln - 1;

        point = inflections[0];
        firstLabel = me.getOrCreateLabel(0, me.label.renderer(labels[0]));
        ratio = Math.floor(Math.abs(Math.sin(labelConf.rotate && (labelConf.rotate.degrees * Math.PI / 180) || 0)));

        for (i = 0; i < ln; i++) {
            point = inflections[i];
            text = me.label.renderer(labels[i]);
            textLabel = me.getOrCreateLabel(i, text);
            bbox = textLabel._bbox;
            maxHeight = max(maxHeight, bbox.height + me.dashSize + me.label.padding);
            x = floor(point[0] - (ratio? bbox.height : bbox.width) / 2);
            if (me.chart.maxGutter[0] == 0) {
                if (i == 0 && axes.findIndex('position', 'left') == -1) {
                    x = point[0];
                }
                else if (i == last && axes.findIndex('position', 'right') == -1) {
                    x = point[0] - bbox.width;
                }
            }
            if (position == 'top') {
                y = point[1] - (me.dashSize * 2) - me.label.padding - (bbox.height / 2);
            }
            else {
                y = point[1] + (me.dashSize * 2) + me.label.padding + (bbox.height / 2);
            }

            textLabel.setAttributes({
                hidden: false,
                x: x,
                y: y
            }, true);

            /*
            if (i != 0 && (me.intersect(textLabel, prevLabel)
                || me.intersect(textLabel, firstLabel))) {
                textLabel.hide(true);
                continue;
            }
            */

            prevLabel = textLabel;
        }

        return maxHeight;
    }

});


text:
This set of playbooks will turn a general Ubuntu LTS (14.04) or Centos 7 (and possibly RHEL 7) host into a jump box. This is a box that acts as an SSH gateway for users to your network, and also provides an OpenVPN server (with CA) to allow non-SSH access.

As a general rule, you should *not* run any other unneeded services on a host like this, and you should use something more secure than passwords for authentication.

The approach implemented here requires that users have SSH keys present on the server, and OpenVPN authentication is done using keys generated by the easy-rsa CA solution.

There are two ansible roles here:

   * jumpbox - sets up SSH and creates users and groups
   * vpn_with_ca - OpenVPN with Easy RSA certificate authority

The firewall component is currently part of the vpn_with_ca role, but may be split out into a separate role soon.

---

## Requirements
The Ansible controller should be running the latest version from https://github.com/ansible/ansible and the target must be an Ubuntu 14.04 LTS or Centos 7 host. RedHat Enterprise Linux 7 will be tested in the coming weeks.

You should also have one existing user who is able to ssh to the host using a key to authenticate, and be able to sudo to root. This role will disable login for root over SSH and also disable password logins unless you make some changes.

---

## Basic Usage
This assumes that all variables and templates are already exactly as you would like them. **This is not likely to be true!** For more information about customization and options available, *please* read the rest of ths README.

#### Host to deploy to
You need to either edit your ansible inventory and create a new group named `jumpbox` that includes all hosts that you want to run this against *or* you need to edit `jumpbox.yml` and change the `jumpbox` in the hosts line to the name of the host that you wish to use.

#### Deployment
Simply run `ansible-playbook jumpbox.yml` and watch the output.

#### Generating individual client ovpn config files
To generate an ovpn config for a client, you'll use the `create_vpn_key.yml` playbook. You need to supply the name of the VPN host that you want to use and also the name of the client to create on the commandline:

```ansible-playbook --extra-vars '{"vpnhost": "<yourvpnhost>", "client": "<clienttocreate>"}' create_vpn_key.yml```

For example, if I wanted to create an ovpn config with on a host named jumpbox for my ipad, I might use

```ansible-playbook --extra-vars '{"vpnhost": "jumpbox", "client": "anonymouslemming-ipad"}' create_vpn_key.yml```

Once you've run this, you'll find the device key, certificate, csr and ovpn config under `/etc/openvpn/easy-rsa/keys` prefixed with the client value you set above. In my example, I would have
   * anonymouslemming-ipad.crt
   * anonymouslemming-ipad.csr
   * anonymouslemming-ipad.key
   * anonymouslemming-ipad.ovpn

You can then provide whichever of these files is needed for your OpenVPN client application to your users.

##### Client entry for iOS vs Tunnelblick
In a generated .ovpn file, you'll note that the first line is `tls-client`. This works out of the box for iOS clients, but does not work with [Tunnelblick](https://tunnelblick.net/).

If you want to use a .ovpn file with Tunnelblick, please change `tls-client` to `client` before adding the VPN connection.

---

## Variable files and templates
### jumpbox
#### variables - roles/jumpbox/vars/default.yml
There are two sections here - unixgroups and unixusers. These are each a list of dictionaries of values that will be used when creating these users and groups.

The idea here is that instead of manually creating users on the box in the future, you simply rerun the playbook. This will create any new users, and you'll have consistent uid and gids for each object.

#### variables - roles/jumpbox/vars/RedHat.yml
This vars file will be used if the target ansible_os_family is RedHat. The main difference is that the wheel group is used instead of sudo for admin users.

#### templates - roles/jumpbox/templates
##### etc_ssh_sshd_config.Debian.j2
This is the SSH server config that will be deployed to the jump box if you're running Ubuntu. It's close to the Ubuntu default, with the following changes:
   * PermitRootLogin no
   * PasswordAuthentication no
   * LoginGraceTime 30
   * MaxStartups 3:50:10

If you still want root ssh access via key after running this playbook, change 'PermitRootLogin no' to 'PermitRootLogin without-password'

##### etc_ssh_sshd_config.RedHat.j2
This template does the same as the above one, but for RedHat / Centos systems. All other statements above apply to this as well.

### vpn_with_ca
#### variables - roles/vpn_with_ca/vars/main.yml
Here, you'll define your VPN network (not your private network - the network range to be used by OpenVPN) and your key details that will be used for both the OpenVPN server and also individual device or user vpn keys.

#### variables - roles/vpn_with_ca/vars/default.yml , Debian.yml and RedHat.yml
Package and service names may differ between Ubuntu and RedHat. The default.yml should work for Ubuntu, but RedHat.yml is used for Centos and RedHat systems. The key differences here are
    * OpenVPN service name is openvpn@server.service instead of just openvpn
	* Group to run as is nobody instead of nogroup on Ubuntu

#### templates - roles/vpn_with_ca/templates
##### etc_openvpn_server.conf.j2
This is the OpenVPN server config and will be deployed to /etc/openvpn/server.conf. Sensible defailts have been used and you shouldn't need to edit this for basic usage.

Ansible will use some information from your host when populating this template, specifically the nameservers and search entries from the ansible_dns section. If you're having problem with DNS lookups after deploying this, check that these are populated by running `ansible -m setup <yourvpnhost>` and look for the ansible_dns section.

##### etc_openvpn_easy-rsa_vars.j2
Deployed to /etc/openvpn/easy-rsa/vars and used by all Easy RSA scripts. The variables from roles/vpn_with_ca/vars/main.yml are used here.

##### etc_iptables_rules.v4.j2
We'll be using the iptables-persistent package to load and save rules. This template
   * sets up masquerading for VPN connections
   * allows established connections
   * allows all connections from jump box's network
   * allows traffic tcp/22 and udp/1194 from any location

##### etc_openvpn_sample.ovpn.j2
Last, but not least, we have the template used to create ovpn files once the vpn is deployed. This will not be copied to the server, but instead used each time you use the `create_vpn_key.yml` playbook.

There is one change that is likely to be needed here, and that's the `remote` line. This should be changed to something that clients can reach from outside your network.