text:
var socket = chrome.socket;

var CRLF = "\r\n";

var Server = function(port, callback){

  var self = this;
  var address = "0.0.0.0"

  socket.create('tcp', {}, function(socketInfo){

    console.log(socketInfo);
    self.sid = socketInfo.socketId;

    socket.listen(self.sid, address, port, function(res){
      chrome.socket.getInfo(self.sid, function(e){
        console.log(e);
        this.localAddress = e.localAddress;
        this.localPort = e.localPort;
        self.socketInfo = e.socketInfo;
      });

      var accept_ = function(sid){
        chrome.socket.accept(sid, function(e){
          console.log(e)
          //if(e.resultCode > 0){
            callback(e.socketId, self);
          //}
          //else{
            accept_(sid);
          //}
        });
      }
      accept_(self.sid);

    });
  })
}

Server.prototype.t2ab = function(str /* String */) {
    var buffer = new ArrayBuffer(str.length);
    var view = new DataView(buffer);
    for(var i = 0, l = str.length; i < l; i++) {
      view.setInt8(i, str.charAt(i).charCodeAt());
    }
    return buffer;
}

Server.prototype.ab2t = function(buffer /* ArrayBuffer */) {
  var arr = new Int8Array(buffer);
  var str = "";
  for(var i = 0, l = arr.length; i < l; i++) {
    str += String.fromCharCode.call(this, arr[i]);
  }
  return str;
}

Server.prototype.extractParams = function(header){
  var escaped = escape(header);
  var pairs = unescape(escaped.substring(escaped.search(escape("?")))).substring(1).split(" ")[0].split('&');
  var params = {}
  pairs.map(function(pair){
    key = pair.split('=')[0]
    val = pair.split('=')[1]
    params[key] = val;
  })

  return params;
}

Server.prototype.extractHeader = function(request){
  headers = [];
  headers['requestLine'] = request.split(/\r\n/)[0];
  var splitted = request.split(/\r\n/).slice(1).map(function(v){
    var key = v.split(/: |:/)[0];
    var val = v.split(/: |:/)[1];
    headers[key] = val;
  });

  return headers;
}

Server.prototype.createHeader = function(headers){

  var headersKey = Object.keys(headers);
  var newHeaders = [];

  headersKey.map(function(key){
    if(key != 'requestLine' && key != ''){
      var val = headers[key];
      var h = key + ': ' + val;
      newHeaders.push(h);
    }
  })

  newHeader = newHeaders.join(CRLF) + CRLF;

  return newHeader;
}


text:
module Workers
  class HttpsWorker < HttpWorker
    set_default_params rport: 443

    def worker_name
      'Https'
    end

    def prefix
      "https"
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.containers;

import com.intellij.reference.SoftReference;
import com.intellij.util.DeprecatedMethodException;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import java.lang.ref.ReferenceQueue;

/**
 * Soft keys hash map.
 * Null keys are NOT allowed
 * Null values are allowed
 *
 * @deprecated use {@link ContainerUtil#createSoftMap()} instead
 */
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public final class SoftHashMap<K,V> extends RefHashMap<K,V> {
  /**
   * Soft keys hash map.
   * Null keys are NOT allowed
   * Null values are allowed
   *
   * @deprecated use {@link ContainerUtil#createSoftMap()} instead
   */
  @Deprecated
  @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
  public SoftHashMap() {
    DeprecatedMethodException.report("Use ContainerUtil.createSoftMap() instead");
  }

  SoftHashMap(int initialCapacity) {
    super(initialCapacity);
  }

  SoftHashMap(@NotNull HashingStrategy<? super K> hashingStrategy) {
    super(hashingStrategy);
  }

  @Override
  protected @NotNull <T> Key<T> createKey(@NotNull T k, @NotNull HashingStrategy<? super T> strategy, @NotNull ReferenceQueue<? super T> q) {
    return new SoftKey<>(k, strategy, q);
  }

  private static final class SoftKey<T> extends SoftReference<T> implements Key<T> {
    private final int myHash;  /* Hash code of key, stored here since the key may be tossed by the GC */
    @NotNull private final HashingStrategy<? super T> myStrategy;

    private SoftKey(@NotNull T k, @NotNull HashingStrategy<? super T> strategy, @NotNull ReferenceQueue<? super T> q) {
      super(k, q);
      myStrategy = strategy;
      myHash = strategy.hashCode(k);
    }

    @Override
    public boolean equals(Object o) {
      if (this == o) return true;
      if (!(o instanceof Key)) return false;
      if (myHash != o.hashCode()) return false;
      T t = get();
      T u = ((Key<T>)o).get();
      if (t == null || u == null) return false;
      return keyEqual(t, u, myStrategy);
    }

    @Override
    public int hashCode() {
      return myHash;
    }

    @NonNls
    @Override
    public String toString() {
      return "SoftHashMap.SoftKey(" + get() + ")";
    }
  }
}


text:
import java.util.Random;

public class WiseStrategy implements Strategy {
    private Random random;
    private int lastValueHand = 0;
    private int nowValueHand = 0;
    private int[][] history = {
            {1, 1, 1,},
            {1, 1, 1,},
            {1, 1, 1,}
    };

    public WiseStrategy(int seed) {
        random = new Random(seed);
    }

    public Hand nextHand() {
        int bet = random.nextInt(getSum(nowValueHand));
        int valueHand = 0;
        if (bet < history[nowValueHand][0]) {
            valueHand = 0;
        } else if (bet < history[nowValueHand][0] + history[nowValueHand][1]) {
            valueHand = 1;
        } else {
            valueHand = 2;
        }
        lastValueHand = nowValueHand;
        nowValueHand = valueHand;
        return Hand.getHand(valueHand);
    }

    public void study(boolean win) {
        if (win) {
            history[lastValueHand][nowValueHand]++;
        } else {
            history[lastValueHand][(nowValueHand + 1) % 3]++;
            history[lastValueHand][(nowValueHand + 2) % 3]++;
        }
    }

    public int getSum(int value) {
        int sum = 0;
        for (int i = 0; i < 3; i++) {
            sum += history[value][i];
        }
        return sum;
    }
}


text:
UITextField subclass that allows numeric input in a predefined format.

<img src="https://github.com/romaonthego/REFormattedNumberField/raw/master/Screenshot.png?3" alt="REFormattedNumberField Screenshot" width="320" height="568" />

## Requirements
* Xcode 6 or higher
* Apple LLVM compiler
* iOS 7.0 or higher
* ARC

## Demo

Build and run the `REFormattedNumberFieldExample` project in Xcode to see `REFormattedNumberField` in action.

## Installation

### CocoaPods

The recommended approach for installating `REFormattedNumberField` is via the [CocoaPods](http://cocoapods.org/) package manager, as it provides flexible dependency management and dead simple installation.
For best results, it is recommended that you install via CocoaPods >= **0.28.0** using Git >= **1.8.0** installed via Homebrew.

Install CocoaPods if not already available:

``` bash
$ [sudo] gem install cocoapods
$ pod setup
```

Change to the directory of your Xcode project:

``` bash
$ cd /path/to/MyProject
$ touch Podfile
$ edit Podfile
```

Edit your Podfile and add REFormattedNumberField:

``` bash
platform :ios, '7.0'
pod 'REFormattedNumberField', '~> 1.1.5'
```

Install into your Xcode project:

``` bash
$ pod install
```

Open your project in Xcode from the .xcworkspace file (not the usual project file)

``` bash
$ open MyProject.xcworkspace
```

Please note that if your installation fails, it may be because you are installing with a version of Git lower than CocoaPods is expecting. Please ensure that you are running Git >= **1.8.0** by executing `git --version`. You can get a full picture of the installation details by executing `pod install --verbose`.

### Manual Install

All you need to do is drop `REFormattedNumberField` files into your project, and add `#include "REFormattedNumberField.h"` to the top of classes that will use it.

## Example Usage

Pretty much all you need is just to specify `format` NSString, where `X` are digits and all other characters are separators.

``` objective-c
REFormattedNumberField *phoneField1 = [[REFormattedNumberField alloc] initWithFrame:CGRectMake(20, 20, 280, 30)];
phoneField1.format = @"(XXX) XXX-XXXX";
[self.view addSubview:phoneField1];

REFormattedNumberField *phoneField2 = [[REFormattedNumberField alloc] initWithFrame:CGRectMake(20, 80, 280, 30)];
phoneField2.format = @"+X (XXX) XXX-XXXX";
[self.view addSubview:phoneField2];

REFormattedNumberField *ccField = [[REFormattedNumberField alloc] initWithFrame:CGRectMake(20, 140, 280, 30)];
ccField.format = @"XXXX XXXX XXXX XXXX";
[self.view addSubview:ccField];

REFormattedNumberField *ccExpirationField = [[REFormattedNumberField alloc] initWithFrame:CGRectMake(20, 200, 280, 30)];
ccExpirationField.format = @"XX/XX";
[self.view addSubview:ccExpirationField];
```

## Contact

Roman Efimov

- https://github.com/romaonthego
- https://twitter.com/romaonthego
- romefimov@gmail.com

## License

REFormattedNumberField is available under the MIT license.

Copyright © 2013 Roman Efimov.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
// Copyright (c) 2012 Markus Alexander Kuppe. All rights reserved.
package tlc2.tool.fp;

@SuppressWarnings("serial")
public class DummyFPSetConfiguration extends FPSetConfiguration {

	/* (non-Javadoc)
	 * @see tlc2.tool.fp.FPSetConfiguration#getMemoryInBytes()
	 */
	public long getMemoryInBytes() {
		// Override super.getMemoryInBytes() to allow unit tests to pass an
		// explicit value by bypassing util.TLCRuntime.getFPMemSize(double).
		// getFPMemSize(double) sets a lower limit for the DiskFPSet size,
		// which unit tests might have to tear down.
		return memoryInBytes;
	}

	public void setMemoryInFingerprintCnt(long length) {
		this.memoryInBytes = length * FPSet.LongSize;
	}
}


text:
require File.expand_path('../spec_helper', __FILE__)
require 'activo/rails/helper'
require 'nokogiri'
require 'active_support/dependencies/autoload'
require 'action_view'
require 'action_view/base'
require 'action_view/template/handlers/erb'

class View < ActionView::Base
  include Activo::Rails::Helper
  include ActionView::Helpers::TagHelper
end

describe Activo::Rails::Helper do
  let(:view) { View.new }
  subject { view }

  describe "setting the page title" do
    it { should respond_to(:page_title) }

    it "sets the title attribute when #page_title is called with an argument" do
      view.page_title "Example"
      view.instance_variable_get("@title").should eq("Example")
    end

    it "returns the title when #page_title is called with no arguments" do
      view.page_title "A Title"
      view.page_title.should eq("A Title")
    end
  end

  describe "#icon" do
    it { should respond_to(:icon) }

    it "returns an empty string when called with nil" do
      view.icon(nil).should eq("")
    end

    it "creates an image tag containing the appropriate icon when called" do
      view.should_receive(:image_tag).with("/images/icons/16x16/add.png", instance_of(Hash))
      view.icon("add")
    end

    it "creates the icon at 16x16 when size is small" do
      view.should_receive(:image_tag).with("/images/icons/16x16/add.png", instance_of(Hash))
      view.icon("add", :small)
    end

    it "creates the icon at 32x32 when size is small" do
      view.should_receive(:image_tag).with("/images/icons/32x32/add.png", instance_of(Hash))
      view.icon("add", :large)
    end

    it "sets the alt attribute to the icon name by default" do
      view.should_receive(:image_tag).with(duck_type(:to_s), {
        :alt => "Add"
      })
      view.icon("add", :small)
    end

    it "sets the alt attribute to the provided value if provided" do
      view.should_receive(:image_tag).with(duck_type(:to_s), {
        :alt => "An icon"
      })
      view.icon("add", :small, :alt => "An icon")
    end
  end

  describe "#secondary-navigation" do
    it { should respond_to(:secondary_navigation) }

    it "yields an instance of NavigationBuilder" do
      view.secondary_navigation do |nav|
        nav.should be_instance_of(Activo::Rails::Helper::NavigationBuilder)
      end
    end
  end

  describe "creating a control set" do
    it { should respond_to(:controls) }

    it "should yield a navigation builder" do
      view.controls do |c|
        c.should be_instance_of(Activo::Rails::Helper::NavigationBuilder)
      end
    end
  end

  describe "#breadcrumbs" do
    it { should respond_to(:breadcrumbs) }

    it "should yield a navigation builder" do
      view.breadcrumbs do |b|
        b.should be_instance_of(Activo::Rails::Helper::NavigationBuilder)
      end
    end
  end
end


text:
JettyJerseyWeldExample
======================

An example project to be used to help figure out issues with DeltaSpike/Weld in JavaSE with Jetty and Jersey


text:
/** \file
 * Serial implementation of scalar, vector and tensor fields for 3D data analysis.
 * -- header file
 */

#ifndef ATOMIC_CONTAINER_BLOCK_3D_H
#define ATOMIC_CONTAINER_BLOCK_3D_H

#include "core/globalDefs.h"
#include "atomicBlock/atomicBlock3D.h"
#include "atomicBlock/atomicContainerBlock2D.h"

namespace plb {

class AtomicContainerDataTransfer3D : public BlockDataTransfer3D {
public:
    AtomicContainerDataTransfer3D() { }
    virtual void setBlock(AtomicBlock3D& block_) { }
    virtual void setConstBlock(AtomicBlock3D const& block_) { }
    virtual AtomicContainerDataTransfer3D* clone() const {
        return new AtomicContainerDataTransfer3D(*this);
    }
    virtual plint staticCellSize() const { return 0; }
    virtual void send(Box3D domain, std::vector<char>& buffer, modif::ModifT kind) const { }
    virtual void receive(Box3D domain, std::vector<char> const& buffer, modif::ModifT kind) { }
    virtual void receive( Box3D domain, std::vector<char> const& buffer,
                          modif::ModifT kind, std::map<int,std::string> const& foreignIds ) { }
    virtual void receive(Box3D domain, std::vector<char> const& buffer, modif::ModifT kind, Dot3D absoluteOffset) {
        receive(domain, buffer, kind);
    }
    virtual void attribute(Box3D toDomain, plint deltaX, plint deltaY, plint deltaZ,
                           AtomicBlock3D const& from, modif::ModifT kind) { }
    virtual void attribute(Box3D toDomain, plint deltaX, plint deltaY, plint deltaZ,
                           AtomicBlock3D const& from, modif::ModifT kind, Dot3D absoluteOffset)
    {
        attribute(toDomain, deltaX, deltaY, deltaZ, from, kind);
    }
};

class AtomicContainerBlock3D : public AtomicBlock3D {
public:
    AtomicContainerBlock3D(plint nx_, plint ny_, plint nz_);
    ~AtomicContainerBlock3D();
    AtomicContainerBlock3D& operator=(AtomicContainerBlock3D const& rhs);
    AtomicContainerBlock3D(AtomicContainerBlock3D const& rhs);
    void swap(AtomicContainerBlock3D& rhs);
public:
    void setData(ContainerBlockData* data_);
    ContainerBlockData* getData();
    ContainerBlockData const* getData() const;
    virtual identifiers::BlockId getBlockId() const;
private:
    ContainerBlockData* data;
};

}  // namespace plb

#endif  // ATOMIC_CONTAINER_BLOCK_3D_H


text:
import os
import io
from inspect import getsource

# for custom indexes
import maras
from maras.storage import Storage, IU_Storage
from maras.hash_index import (IU_UniqueHashIndex,
                                    IU_HashIndex,
                                    HashIndex,
                                    UniqueHashIndex)
# normal imports

from maras.index import (ElemNotFound,
                               DocIdNotFound,
                               IndexException,
                               Index,
                               TryReindexException,
                               ReindexException,
                               IndexNotFoundException,
                               IndexConflict)

from maras.misc import NONE

from maras.env import menv

from random import randrange

import warnings

def header_for_indexes(index_name, index_class, db_custom="", ind_custom="", classes_code=""):
    return """# %s
# %s

# inserted automatically
import os
import msgpack

import struct
import shutil

from hashlib import sha1

# custom db code start
# db_custom
%s

# custom index code start
# ind_custom
%s

# source of classes in index.classes_code
# classes_code
%s

# index code start

""" % (index_name, index_class, db_custom, ind_custom, classes_code)

class DatabaseException(Exception):
    pass

class PreconditionsException(DatabaseException):
    pass

class RecordDeleted(DatabaseException):
    pass

class RecordNotFound(DatabaseException):
    pass

class RevConflict(DatabaseException):
    pass

class DatabaseConflict(DatabaseException):
    pass

class DatabasePathException(DatabaseException):
    pass

class DatabaseIsNotOpened(PreconditionsException):
    pass

class Database(object):
    """
    A default single thread database object.
    """

    custom_header = ""  # : use it for imports required by your database

    def __init__(self, path):
        self.path = path
        self.storage = None
        self.indexes = []
        self.id_ind = None
        self.indexes_names = {}
        self.opened = False

    def create_new_rev(self, old_rev=None):
        """
        Creates new revision number based on previous one.
        Increments it + random bytes. On overflow starts from 0 again.
        """
        if old_rev:
            try:
                rev_num = int(old_rev[:4], 16)
            except:
                raise RevConflict()
            rev_num += 1
            if rev_num > 65025:
            # starting the counter from 0 again
                rev_num = 0
            rnd = randrange(65536)
            return "%04x%04x" % (rev_num, rnd)
        else:
            # new rev
            rnd = randrange(256 ** 2)
            return '0001%04x' % rnd

    def __not_opened(self):
        if not self.opened:
            raise DatabaseIsNotOpened("Database is not opened")

    def set_indexes(self, indexes=[]):
        """
        Set indexes using ``indexes`` param

        :param indexes: indexes to set in db
        :type indexes: iterable of :py:class:`maras.index.Index` objects.

        """
        for ind in indexes:
            self.add_index(ind, create=False)

    def _add_single_index(self, p, i, index):
        """
        Adds single index to a database.
        It will use :py:meth:`inspect.getsource` to get class source.
        Then it will build real index file, save it in ``_indexes`` directory.
        """
        code = getsource(index.__class__)
        if not code.startswith('c'):  # fix for indented index codes
            import textwrap
            code = textwrap.dedent(code)
        index._order = i
        cls_code = getattr(index, 'classes_code', [])
        classes_code = ""
        for curr in cls_code:
            classes_code += getsource(curr) + '\n\n'
        with io.FileIO(os.path.join(p, "%.2d%s" % (i, index.name) + '.py'), 'w') as f:
            f.write(header_for_indexes(index.name,
                                       index.__class__.__name__,
                                       getattr(self, 'custom_header', ''),
                                       getattr(index, 'custom_header', ''),
                                       classes_code))
            f.write(code)
        return True

    def _read_index_single(self, p, ind, ind_kwargs={}):
        """
        It will read single index from index file (ie. generated in :py:meth:`._add_single_index`).
        Then it will perform ``exec`` on that code

        If error will occur the index file will be saved with ``_broken`` suffix

        :param p: path
        :param ind: index name (will be joined with *p*)
        :returns: new index object
        """
        with io.FileIO(os.path.join(p, ind), 'r') as f:
            name = f.readline()[2:].strip()
            _class = f.readline()[2:].strip()
            code = f.read()
        try:
            obj = compile(code, '<Index: %s' % os.path.join(p, ind), 'exec')
            exec obj in globals()
            ind_obj = globals()[_class](self.path, name, **ind_kwargs)
            ind_obj._order = int(ind[:2])
        except:
            ind_path = os.path.join(p, ind)
            os.rename(ind_path, ind_path + '_broken')  # rename it instead of removing
#            os.unlink(os.path.join(p, ind))
            warnings.warn("Fatal error in index, saved as %s" % (ind_path + '_broken', ))
            raise
        else:
            return ind_obj

    def __check_if_index_unique(self, name, num):
        indexes = os.listdir(os.path.join(self.path, '_indexes'))
        if any((x for x in indexes if x[2:-3] == name and x[:2] != str(num))):
            raise IndexConflict("Already exists")

    def __write_index(self, new_index, number=0, edit=False, ind_kwargs=None):
        # print new_index
        if ind_kwargs is None:
            ind_kwargs = {}
        p = os.path.join(self.path, '_indexes')
        if isinstance(new_index, basestring) and not new_index.startswith("path:"):
            if len(new_index.splitlines()) < 4 or new_index.splitlines()[3] != '# inserted automatically':
                from indexcreator import Parser
                par = Parser()
                custom_imports, s = par.parse(new_index)
                s = s.splitlines()
                name = s[0][2:]
                c = s[1][2:]
                comented = ['\n\n#SIMPLIFIED CODE']
                map(lambda x: comented.append("#" + x), new_index.splitlines())
                comented.append('#SIMPLIFIED CODE END\n\n')

                s = header_for_indexes(
                    name, c, ind_custom=custom_imports) + "\n".join(s[2:]) + "\n".join(comented)
                new_index = s
            else:
                name = new_index.splitlines()[0][2:]
                name = name.strip()

            if name in self.indexes_names and not edit:
                raise IndexConflict("Already exists")
            if edit:
                previous_index = filter(lambda x: x.endswith(
                    '.py') and x[2:-3] == name, os.listdir(p))
                if not previous_index:
                    raise PreconditionsException(
                        "Can't edit index that's not yet in database")
                number = int(previous_index[0][:2])
            if number == 0 and not edit and not name == 'id':
                raise PreconditionsException(
                    "Id index must be the first added")
            ind_path = "%.2d%s" % (number, name)
            if not edit:
                self.__check_if_index_unique(name, number)

            ind_path_f = os.path.join(p, ind_path + '.py')
            if os.path.exists(ind_path_f):
                os.rename(ind_path_f, ind_path_f + '_last')  # save last working index code
            with io.FileIO(ind_path_f, 'w') as f:
                f.write(new_index)

            ind_obj = self._read_index_single(p, ind_path + '.py')

        elif isinstance(new_index, basestring) and new_index.startswith("path:"):
            path = new_index[5:]
            if not path.endswith('.py'):
                path += '.py'
            ind_obj = self._read_index_single(p, path, ind_kwargs)
            name = ind_obj.name
            if name in self.indexes_names and not edit:
                raise IndexConflict("Already exists")
        elif isinstance(new_index, Index):
            # it will first save index as a string, and then compile it
            # it will allow to control the index object on the DB side
            ind = new_index
            init_arguments = new_index.__class__.__init__.im_func.func_code.co_varnames[
                3:]  # ignore self, path and name
            for curr in init_arguments:
                if curr not in ('args', 'kwargs'):
                    v = getattr(ind, curr, NONE())
                    if not isinstance(v, NONE):
                        ind_kwargs[curr] = v
            if edit:
                # code duplication...
                previous_index = filter(lambda x: x.endswith(
                    '.py') and x[2:-3] == ind.name, os.listdir(p))
                if not previous_index:
                    raise PreconditionsException(
                        "Can't edit index that's not yet in database")
                number = int(previous_index[0][:2])
            if ind.name in self.indexes_names and not edit:
                raise IndexConflict("Already exists")
            if number == 0 and not edit and not ind.name == 'id':
                raise PreconditionsException(
                    "Id index must be the first added")
            if not edit:
                self.__check_if_index_unique(ind.name, number)
            self._add_single_index(p, number, ind)
            ind_path = "%.2d%s" % (number, ind.name)
            ind_obj = self._read_index_single(p, ind_path + '.py', ind_kwargs)
            name = ind_obj.name
        else:
            raise PreconditionsException("Argument must be Index instance, path to index_file or valid string index format")
        return ind_obj, name

    def add_index(self, new_index, create=True, ind_kwargs=None):
        """

        :param new_index: New index to add, can be Index object, index valid string or path to file with index code
        :type new_index: string
        :param create: Create the index after add or not
        :type create: bool

        :returns: new index name
        """

        if ind_kwargs is None:
            ind_kwargs = {}
        p = os.path.join(self.path, '_indexes')
        if not os.path.exists(p):
            self.initialize()
        current = sorted(filter(lambda x: x.endswith('.py'), os.listdir(p)))
        if current:
            last = int(current[-1][:2])  # may crash... ignore
            _next = last + 1
        else:
            _next = 0
        ind_obj, name = self.__write_index(new_index, _next, edit=False)
        # add the new index to objects
        self.indexes.append(ind_obj)
        self.indexes_names[name] = ind_obj
        if create:
            if self.exists():  # no need te create if database doesn't exists'
                ind_obj.create_index()
        if name == 'id':
            self.__set_main_storage()
            self.__compat_things()
        for patch in getattr(ind_obj, 'patchers', ()):  # index can patch db object
            patch(self)
        return name

    def edit_index(self, index, reindex=False, ind_kwargs=None):
        """
        Allows to edit existing index.
        Previous working version will be saved with ``_last`` suffix (see :py:meth:`.revert_index`

        :param bool reindex: should be the index reindexed after change

        :returns: index name
        """
        if ind_kwargs is None:
            ind_kwargs = {}
        ind_obj, name = self.__write_index(index, -1, edit=True)
        old = next(x for x in self.indexes if x.name == name)
        old.close_index()
        index_of_index = self.indexes.index(old)
        ind_obj.open_index()
        self.indexes[index_of_index] = ind_obj
        self.indexes_names[name] = ind_obj
        if reindex:
            self.reindex_index(name)
        return name

    def revert_index(self, index_name, reindex=False, ind_kwargs=None):
        """
        Tries to revert index code from copy.
        It calls :py:meth:`.edit_index` with previous working.

        :param string index_name: index name to restore
        """
        ind_path = os.path.join(self.path, '_indexes')
        if index_name in self.indexes_names:  # then it's working index.
            ind = self.indexes_names[index_name]
            full_name = '%.2d%s.py' % (ind._order, index_name)
        else:
            indexes = os.listdir(ind_path)
            full_name = next((x for x in indexes if x[2:-3] == index_name))
        if not full_name:
            raise DatabaseException("%s index not found" % index_name)
        last_path = os.path.join(ind_path, full_name + "_last")
        if not os.path.exists(last_path):
            raise DatabaseException("No previous copy found for %s" % index_name)
        correct_last_path = last_path[:-5]  # remove _last from name
        os.rename(last_path, correct_last_path)
#        ind_data = open(last_path, 'r')
        p = 'path:%s' % os.path.split(correct_last_path)[1]
        return self.edit_index(p, reindex, ind_kwargs)

    def get_index_code(self, index_name, code_switch='All'):
        """
        It will return full index code from index file.

        :param index_name: the name of index to look for code
        """
        if not index_name in self.indexes_names:
            self.__not_opened()
            raise IndexNotFoundException(
                "Index `%s` doesn't exists" % index_name)
        ind = self.indexes_names[index_name]
        name = "%.2d%s" % (ind._order, index_name)
        name += '.py'
        with io.FileIO(os.path.join(self.path, '_indexes', name), 'r') as f:
            co = f.read()
            if code_switch == 'All':
                return co

            if code_switch == 'S':
                try:
                    ind = co.index('#SIMPLIFIED CODE')
                except ValueError:
                    return " "
                else:
                    s = co[ind:]
                    l = s.splitlines()[1:-2]
                    ll = map(lambda x: x[1:], l)
                    return '\n'.join(ll)
            if code_switch == 'P':
                try:
                    ind = co.index('#SIMPLIFIED CODE')
                except ValueError:
                    return co
                else:
                    return co[:ind]

        return ""  # shouldn't happen

    def __set_main_storage(self):
        """
        Sets database main storage (from the **id** index)
        """
        try:
            self.storage = self.indexes_names['id'].storage
            self.id_ind = self.indexes_names['id']
        except KeyError:
            # when opening / initializing DB without `id` index
            # happens mostly on server side
            pass

    def initialize(self, path=None, makedir=True):
        """
        Initialize new database

        :param path: Path to a database (allows delayed path configuration), if not provided self.path will be used
        :param makedir: Make the ``_indexes`` directory or not

        :returns: the database path
        """
        if self.opened is True:
            raise DatabaseConflict("Already opened")
        if not path:
            path = self.path
        else:
            self.path = path
        if makedir:
            if not self.path:
                raise PreconditionsException("No path specified")
            p = os.path.join(self.path, '_indexes')
            if os.path.exists(p):
                raise DatabaseConflict("Cant't create because already exists")
            os.makedirs(p)

        return self.path

    def __open_new(self, with_id_index=True, index_kwargs={}):
        """
        Will open new database (works like create),
        if not self.path provided will call initialize()
        """
        if self.path:
            if not os.path.exists(self.path):
                self.initialize(self.path)
        if not 'id' in self.indexes_names and with_id_index:
            import maras.hash_index
            if not 'db_path' in index_kwargs:
                index_kwargs['db_path'] = self.path
            index_kwargs['name'] = 'id'
            id_ind = maras.hash_index.UniqueHashIndex(**index_kwargs)
            self.add_index(id_ind, create=False)
            # del maras.index
        for index in self.indexes:
            try:
                index.create_index()
            except IndexException:
                raise DatabaseConflict(
                    "Already exists (detected on index=%s)" % index.name)
        return True

    def _read_indexes(self):
        """
        Read all known indexes from ``_indexes``
        """
        p = os.path.join(self.path, '_indexes')
        for ind in os.listdir(p):
            if ind.endswith('.py'):
                self.add_index('path:' + ind, create=False)

    def __compat_things(self):
        """
        Things for compatibility.
        """
        # patch for rev size change
        if not self.id_ind:
            return
        if self.id_ind.entry_line_format[4:6] == '4s':
            # rev compatibility...
            warnings.warn("Your database is using old rev mechanizm \
for ID index. You should update that index \
(maras.migrate.migrate).")
            from misc import random_hex_4
            self.create_new_rev = random_hex_4

    def create(self, path=None, **kwargs):
        """
        Create database

        :param path: path where to create the database

        :returns: database path
        """
        if path:
            self.initialize(path)
        if not self.path:
            raise PreconditionsException("No path specified")
        if self.opened is True:
            raise DatabaseConflict("Already opened")
        self.__open_new(**kwargs)
        self.__set_main_storage()
        self.__compat_things()
        self.opened = True
        return self.path

    def exists(self, path=None):
        """
        Checks if database in given path exists

        :param path: path to look for database
        """
        if not path:
            path = self.path
        if not path:
            return False
        if os.path.exists(path):
            return os.path.exists(os.path.join(path, '_indexes'))
        return False

    def open(self, path=None):
        """
        Will open already existing database

        :param path: path with database to open
        """
        if self.opened is True:
            raise DatabaseConflict("Already opened")
#        else:
        if path:
            self.path = path
        if not self.path:
            raise PreconditionsException("No path specified")
        if not os.path.exists(self.path):
            raise DatabasePathException("Can't open database")
        self.indexes = []
        self.id_ind = None
        self.indexes_names = {}
        self._read_indexes()
        if not 'id' in self.indexes_names:
            raise PreconditionsException("There must be `id` index!")
        for index in self.indexes:
            index.open_index()
        self.indexes.sort(key=lambda ind: ind._order)
        self.__set_main_storage()
        self.__compat_things()
        self.opened = True
        return True

    def close(self):
        """
        Closes the database
        """
        if not self.opened:
            raise DatabaseConflict("Not opened")
        self.id_ind = None
        self.indexes_names = {}
        self.storage = None
        for index in self.indexes:
            index.close_index()
        self.indexes = []
        self.opened = False
        return True

    def destroy(self):
        """
        Allows to destroy database.

        **not reversable** operation!
        """
        # destroy all but *id*
        if not self.exists():
            raise DatabaseConflict("Doesn't exists'")
        for index in reversed(self.indexes[1:]):
            try:
                self.destroy_index(index)
            except:
                pass
        if getattr(self, 'id_ind', None) is not None:
            self.id_ind.destroy()  # now destroy id index
        # remove all files in db directory
        for root, dirs, files in os.walk(self.path, topdown=False):
            for name in files:
                os.remove(os.path.join(root, name))
            for name in dirs:
                os.rmdir(os.path.join(root, name))
        os.rmdir(self.path)
        self.close()
        return True

    def _single_update_index(self, index, data, db_data, doc_id):
        """
        Performs update operation on single index

        :param index: the index to perform operation
        :param data: new data
        :param db_data: database data
        :param doc_id: the id of document
        """
        try:
            old_should_index = index.make_key_value(db_data)
        except Exception as ex:
            warnings.warn("""Problem during update for `%s`, ex = `%s`, \
uou should check index code.""" % (index.name, ex), RuntimeWarning)
            old_should_index = None
        if old_should_index:
            old_key, old_value = old_should_index
            try:
                new_should_index = index.make_key_value(data)
            except Exception as ex:
                warnings.warn("""Problem during update for `%s`, ex = `%r`, \
you should check index code.""" % (index.name, ex), RuntimeWarning)
                new_should_index = None
            if new_should_index:
                new_key, new_value = new_should_index
                if new_key != old_key:
                    index.delete(doc_id, old_key)
                    index.insert_with_storage(doc_id, new_key, new_value)
                elif new_value != old_value:
                    try:
                        index.update_with_storage(doc_id, new_key, new_value)
                    except (ElemNotFound, DocIdNotFound):
                        # element should be in index but isn't
                        #(propably added new index without reindex)
                        warnings.warn("""Reindex might be required for index %s""" % index.name)
            else:
                index.delete(doc_id, old_key)
        else:  # not previously indexed
            self._single_insert_index(index, data, doc_id)

    def _update_id_index(self, _rev, data):
        """
        Performs update on **id** index
        """
        _id, value = self.id_ind.make_key_value(data)
        db_data = self.get('id', _id)
        if db_data['_rev'] != _rev:
            raise RevConflict()
        new_rev = self.create_new_rev(_rev)
        # storage = self.storage
        # start, size = storage.update(value)
        # self.id_ind.update(_id, new_rev, start, size)
        self.id_ind.update_with_storage(_id, new_rev, value)
        return _id, new_rev, db_data

    def _update_indexes(self, _rev, data):
        """
        Performs update operation on all indexes in order
        """
        _id, new_rev, db_data = self._update_id_index(_rev, data)
        for index in self.indexes[1:]:
            self._single_update_index(index, data, db_data, _id)
        return _id, new_rev

    def _single_insert_index(self, index, data, doc_id):
        """
        Performs insert operation on single index

        :param index: index to perform operation
        :param data: new data
        :param doc_id: document id
        """
        try:
            should_index = index.make_key_value(data)
        except Exception as ex:
            warnings.warn("""Problem during insert for `%s`, ex = `%r`, \
you should check index code.""" % (index.name, ex), RuntimeWarning)
            should_index = None
        if should_index:
            key, value = should_index
            index.insert_with_storage(doc_id, key, value)
            # if value:
            #     storage = index.storage
            #     start, size = storage.insert(value)
            # else:
            #     start = 1
            #     size = 0
            # index.insert(doc_id, key, start, size)

    def _insert_id_index(self, _rev, data):
        """
        Performs insert on **id** index.
        """
        _id, value = self.id_ind.make_key_value(data)  # may be improved
#        storage = self.storage
        # start, size = storage.insert(value)
        # self.id_ind.insert(_id, _rev, start, size)
        self.id_ind.insert_with_storage(_id, _rev, value)
        return _id

    def _insert_indexes(self, _rev, data):
        """
        Performs insert operation on all indexes in order
        """
        _id = self._insert_id_index(_rev, data)
        for index in self.indexes[1:]:
            self._single_insert_index(index, data, _id)

    def _single_delete_index(self, index, data, doc_id, old_data):
        """
        Performs single delete operation on single index.
        It's very similar to update functions (that's why data is in arguments)

        :param index: index to perform operation
        :param data: not important (because of update operations)
        :param doc_id: document id
        :param old_data: current data in database
        """
        index_data = index.make_key_value(old_data)
        if not index_data:
            return
        key, value = index_data
        try:
            index.delete(doc_id, key)
        except TryReindexException:
            return

    def _delete_id_index(self, _id, _rev, data):
        """
        Performs delete from **id** index
        """
        # key, value = self.id_ind.make_key_value(data)
        # key = data['_id']
        key = self.id_ind.make_key(_id)
        self.id_ind.delete(key)

    def _delete_indexes(self, _id, _rev, data):
        """
        Performs delete operation on all indexes in order
        """
        old_data = self.get('id', _id)
        if old_data['_rev'] != _rev:
            raise RevConflict()
        for index in self.indexes[1:]:
            self._single_delete_index(index, data, _id, old_data)
        self._delete_id_index(_id, _rev, data)

    def destroy_index(self, index):
        """
        Destroys index

        :param index: the index to destroy
        :type index: :py:class:`maras.index.Index`` instance, or string
        """
        if isinstance(index, basestring):
            if not index in self.indexes_names:
                raise PreconditionsException("No index named %s" % index)
            index = self.indexes_names[index]
        elif not index in self.indexes:
            self.__not_opened()
            raise PreconditionsException("Argument must be Index instance or valid string index format")
        if index.name == 'id':
            self.__not_opened()
            raise PreconditionsException("Id index cannot be destroyed")
        full_file = "%.2d%s" % (index._order, index.name) + '.py'
        p = os.path.join(self.path, '_indexes', full_file)
        os.unlink(p)
        index.destroy()
        del self.indexes_names[index.name]
        self.indexes.remove(index)

    def compact_index(self, index):
        """
        Compacts index
        Used for better utilization of index metadata.
        The deleted documents will be not more in structure.

        :param index: the index to destroy
        :type index: :py:class:`maras.index.Index`` instance, or string
        """
        if isinstance(index, basestring):
            if not index in self.indexes_names:
                raise PreconditionsException("No index named %s" % index)
            index = self.indexes_names[index]
        elif not index in self.indexes:
            self.__not_opened()
            raise PreconditionsException("Argument must be Index instance or valid string index format")
        if getattr(index, 'compacting', False):
            raise ReindexException(
                "The index=%s is still compacting" % index.name)
        index.compacting = True
        index.compact()
        del index.compacting

    def _compact_indexes(self):
        """
        Runs compact on all indexes
        """
        for index in self.indexes:
            self.compact_index(index)

    def _single_reindex_index(self, index, data):
        doc_id, rev, start, size, status = self.id_ind.get(
            data['_id'])  # it's cached so it's ok
        if status != 'd' and status != 'u':
            self._single_insert_index(index, data, doc_id)

    def reindex_index(self, index):
        """
        Performs reindex on index. Optimizes metadata and storage informations for given index.

        You can't reindex **id** index.

        :param index: the index to reindex
        :type index: :py:class:`maras.index.Index`` instance, or string
        """
        if isinstance(index, basestring):
            if not index in self.indexes_names:
                raise PreconditionsException("No index named %s" % index)
            index = self.indexes_names[index]
        elif not index in self.indexes:
            self.__not_opened()
            raise PreconditionsException("Argument must be Index instance or valid string index format")
        if index.name == 'id':
            self.__not_opened()
            raise PreconditionsException("Id index cannot be reindexed")
        if getattr(index, 'reindexing', False):
            raise ReindexException(
                "The index=%s is still reindexing" % index.name)

        all_iter = self.all('id')
        index.reindexing = True
        index.destroy()
        index.create_index()

        while True:
            try:
                curr = all_iter.next()
            except StopIteration:
                break
            else:
                self._single_reindex_index(index, curr)
        del index.reindexing

    def _reindex_indexes(self):
        for index in self.indexes[1:]:
            self.reindex_index(index)

    def insert(self, data):
        """
        It's using **reference** on the given data dict object,
        to avoid it copy it before inserting!

        If data **will not** have ``_id`` field,
        it will be generated (random 32 chars string)

        :param data: data to insert
        """
        if '_rev' in data:
            self.__not_opened()
            raise PreconditionsException(
                "Can't add record with forbidden fields")
        _rev = self.create_new_rev()
        if not '_id' in data:
            try:
                _id = self.id_ind.create_key()
            except:
                self.__not_opened()
                raise DatabaseException("No id?")
        else:
            _id = data['_id']
        assert _id is not None
        data['_rev'] = _rev  # for make_key_value compat with update / delete
        data['_id'] = _id
        self._insert_indexes(_rev, data)
        ret = {'_id': _id, '_rev': _rev}
        data.update(ret)
        return ret

    def update(self, data):
        """
        It's using **reference** on the given data dict object,
        to avoid it copy it before updating!

        ``data`` **must** contain ``_id`` and ``_rev`` fields.

        :param data: data to update
        """
        if not '_rev' in data or not '_id' in data:
            self.__not_opened()
            raise PreconditionsException("Can't update without _rev or _id")
        _rev = data['_rev']
        try:
            _rev = bytes(_rev)
        except:
            self.__not_opened()
            raise PreconditionsException(
                "`_rev` must be valid bytes object")
        _id, new_rev = self._update_indexes(_rev, data)
        ret = {'_id': _id, '_rev': new_rev}
        data.update(ret)
        return ret

    def get(self, index_name, key, with_doc=False, with_storage=True):
        """
        Get single data from Database by ``key``.

        :param index_name: index to get data from
        :param key: key to get
        :param with_doc: if ``True`` data from **id** index will be included in output
        :param with_storage: if ``True`` data from index storage will be included, otherwise just metadata.
        """
        # if not self.indexes_names.has_key(index_name):
        #     raise DatabaseException, "Invalid index name"
        try:
            ind = self.indexes_names[index_name]
        except KeyError:
            self.__not_opened()
            raise IndexNotFoundException(
                "Index `%s` doesn't exists" % index_name)
        try:
            l_key, _unk, start, size, status = ind.get(key)
        except ElemNotFound as ex:
            raise RecordNotFound(ex)
        if not start and not size:
            raise RecordNotFound("Not found")
        elif status == 'd':
            raise RecordDeleted("Deleted")
        if with_storage and size:
            storage = ind.storage
            data = storage.get(start, size, status)
        else:

            data = {}
        if with_doc and index_name != 'id':
            storage = ind.storage
            doc = self.get('id', l_key, False)
            if data:
                data['doc'] = doc
            else:
                data = {'doc': doc}
        data['_id'] = l_key
        if index_name == 'id':
            data['_rev'] = _unk
        else:
            data['key'] = _unk
        return data

    def get_many(self, index_name, key=None, limit=-1, offset=0, with_doc=False, with_storage=True, start=None, end=None, **kwargs):
        """
        Allows to get **multiple** data for given ``key`` for *Hash based indexes*.
        Also allows get **range** queries for *Tree based indexes* with ``start`` and ``end`` arguments.

        :param index_name: Index to perform the operation
        :param key: key to look for (has to be ``None`` to use range queries)
        :param limit: defines limit for query
        :param offset: defines offset (how many records from start it will ignore)
        :param with_doc: if ``True`` data from **id** index will be included in output
        :param with_storage: if ``True`` data from index storage will be included, otherwise just metadata.
        :param start: ``start`` parameter for range queries
        :param end: ``end`` parameter for range queries

        :returns: iterator over records
        """
        if index_name == 'id':
            self.__not_opened()
            raise PreconditionsException("Can't get many from `id`")
        try:
            ind = self.indexes_names[index_name]
        except KeyError:
            self.__not_opened()
            raise IndexNotFoundException(
                "Index `%s` doesn't exists" % index_name)
        storage = ind.storage
        if start is None and end is None:
            gen = ind.get_many(key, limit, offset)
        else:
            gen = ind.get_between(start, end, limit, offset, **kwargs)
        while True:
            try:
#                l_key, start, size, status = gen.next()
                ind_data = gen.next()
            except StopIteration:
                break
            else:
                if with_storage and ind_data[-2]:
                    data = storage.get(*ind_data[-3:])
                else:
                    data = {}
                doc_id = ind_data[0]
                if with_doc:
                    doc = self.get('id', doc_id, False)
                    if data:
                        data['doc'] = doc
                    else:
                        data = {'doc': doc}
                data['_id'] = doc_id
                if key is None:
                    data['key'] = ind_data[1]
                yield data

    def all(self, index_name, limit=-1, offset=0, with_doc=False, with_storage=True):
        """
        Alows to get all records for given index

        :param index_name: Index to perform the operation
        :param limit: defines limit for query
        :param offset: defines offset (how many records from start it will ignore)
        :param with_doc: if ``True`` data from **id** index will be included in output
        :param with_storage: if ``True`` data from index storage will be included, otherwise just metadata
        """
        try:
            ind = self.indexes_names[index_name]
        except KeyError:
            self.__not_opened()
            raise IndexNotFoundException(
                "Index `%s` doesn't exists" % index_name)
        storage = ind.storage
        gen = ind.all(limit, offset)
        while True:
            try:
                doc_id, unk, start, size, status = gen.next()
            except StopIteration:
                break
            else:
                if index_name == 'id':
                    if with_storage and size:
                        data = storage.get(start, size, status)
                    else:
                        data = {}
                    data['_id'] = doc_id
                    data['_rev'] = unk
                else:
                    data = {}
                    if with_storage and size:
                        data['value'] = storage.get(start, size, status)
                    data['key'] = unk
                    data['_id'] = doc_id
                    if with_doc:
                        doc = self.get('id', doc_id, False)
                        data['doc'] = doc
                yield data

    def run(self, index_name, target_funct, *args, **kwargs):
        """
        Allows to execute given function on Database side
        (important for server mode)

        If ``target_funct==sum`` then given index must have ``run_sum`` method.

        :param index_name: index name to perform action.
        :param target_funct: target function name (without *run* prefix)
        :param \*args: ``*args`` for function
        :param \*\*kwargs: ``**kwargs`` for function

        """
        try:
            ind = self.indexes_names[index_name]
        except KeyError:
            self.__not_opened()
            raise IndexNotFoundException(
                "Index `%s` doesn't exists" % index_name)
        try:
            funct = getattr(ind, "run_" + target_funct)
        except AttributeError:
            raise IndexException("Invalid function to run")
        return funct(self, *args, **kwargs)

    def count(self, target_funct, *args, **kwargs):
        """
        Counter. Allows to execute for example

        .. code-block:: python

            db.count(db.all, 'id')

        And it will return then how much records are in your ``id`` index.

        .. warning::
            It sets ``kwargs['with_storage'] = False`` and ``kwargs['with_doc'] = False``

        """
        kwargs['with_storage'] = False
        kwargs['with_doc'] = False
        iter_ = target_funct(*args, **kwargs)
        i = 0
        while True:
            try:
                iter_.next()
                i += 1
            except StopIteration:
                break
        return i

    def delete(self, data):
        """
        Delete data from database.

        ``data`` has to contain ``_id`` and ``_rev`` fields.

        :param data: data to delete
        """
        if not '_rev' in data or not '_id' in data:
            raise PreconditionsException("Can't delete without _rev or _id")
        _id = data['_id']
        _rev = data['_rev']
        try:
            _id = bytes(_id)
            _rev = bytes(_rev)
        except:
            raise PreconditionsException(
                "`_id` and `_rev` must be valid bytes object")
        data['_deleted'] = True
        self._delete_indexes(_id, _rev, data)
        return True

    def compact(self):
        """
        Compact all indexes. Runs :py:meth:`._compact_indexes` behind.
        """
        self.__not_opened()
        self._compact_indexes()

    def reindex(self):
        """
        Reindex all indexes. Runs :py:meth:`._reindex_indexes` behind.
        """
        self.__not_opened()
        self._reindex_indexes()

    def flush_indexes(self):
        """
        Flushes all indexes
        """
        self.__not_opened()
        for index in self.indexes:
            index.flush()

    def flush(self):
        """
        Flushes all indexes. Runs :py:meth:`.flush_indexes` behind.
        """
        return self.flush_indexes()

    def fsync(self):
        """
        It forces the kernel buffer to be written to disk. Use when you're sure that you need to.
        """
        self.__not_opened()
        for index in self.indexes:
            index.flush()
            index.fsync()

    def __get_size(self):
        """
        :returns: total size of database.
        """
        if not self.path:
            return 0
        return sum(
            os.path.getsize(os.path.join(dirpath, filename)) for dirpath, dirnames,
            filenames in os.walk(self.path) for filename in filenames)

    def get_index_details(self, name):
        """
        Will return index properties.

        :returns: index details
        """
        self.__not_opened()
        try:
            db_index = self.indexes_names[name]
        except KeyError:
            self.__not_opened()
            raise IndexNotFoundException("Index doesn't exist")

        props = {}
        for key, value in db_index.__dict__.iteritems():
            if not callable(value):  # not using inspect etc...
                props[key] = value

        return props

    def get_db_details(self):
        """
        Get's database details, size, indexes, environment etc.

        :returns: database details
        """
        props = {}
        props['path'] = self.path
        props['size'] = self.__get_size()
        props['indexes'] = self.indexes_names.keys()
        props['menv'] = menv
        return props


text:
package eu.tripledframework.eventstore.domain;

import java.lang.reflect.InvocationTargetException;

import eu.tripledframework.eventstore.domain.annotation.ConstructionHandler;
import eu.tripledframework.eventstore.domain.annotation.EP;
import eu.tripledframework.eventstore.event.AddressUpdatedEvent;
import eu.tripledframework.eventstore.event.AddressUpdatedEventWhichCannotBeInvoked;
import eu.tripledframework.eventstore.event.MyAggregateRootCreatedEvent;

public class MyAggregateRoot implements ConstructionAware {

  public String identifier;
  public String name;
  public String address;
  public boolean postReconstructCalled;
  public boolean constructorCalled;
  public boolean updateAddressCalled;
  public boolean updateAddressWhichCannotBeInvokedCalled;

  @ConstructionHandler(MyAggregateRootCreatedEvent.class)
  public MyAggregateRoot(@EP("aggregateRootIdentifier") String identifier, @EP("name") String name) {
    this.identifier = identifier;
    this.name = name;
    this.constructorCalled = true;
  }

  @ConstructionHandler(AddressUpdatedEvent.class)
  public void updateAddress(@EP("address") String address) {
    this.address = address;
    this.updateAddressCalled = true;
  }

  @ConstructionHandler(AddressUpdatedEventWhichCannotBeInvoked.class)
  public void updateAddressWhichCannotBeInvoked() throws InvocationTargetException {
    this.updateAddressWhichCannotBeInvokedCalled = true;
    throw new InvocationTargetException(null, "oeps");
  }

  @Override
  public void postConstruct() {
    this.postReconstructCalled = true;
  }

  public void reset() {
    constructorCalled = false;
    updateAddressCalled = false;
    updateAddressWhichCannotBeInvokedCalled = false;
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="EntryPointsManager">
    <list size="1">
      <item index="0" class="java.lang.String" itemvalue="org.bukkit.event.EventHandler" />
    </list>
  </component>
  <component name="JavadocGenerationManager">
    <option name="OUTPUT_DIRECTORY" value="$PROJECT_DIR$/docs" />
  </component>
  <component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" project-jdk-name="1.8" project-jdk-type="JavaSDK">
    <output url="file://$PROJECT_DIR$/out" />
  </component>
</project>


text:
//
// Created by Jiang Lu on 6/2/15.
//

#ifndef DUKV8_ISOLATE_H
#define DUKV8_ISOLATE_H

#include <duktape.h>
#include "base.h"
#include "auto_release_pool.h"
#include "platform.h"

namespace v8 {

/**
 * Isolate represents an isolated instance of the V8 engine.  V8
 * isolates have completely separate states.  Objects from one isolate
 * must not be used in other isolates.  When V8 is initialized a
 * default isolate is implicitly created and entered.  The embedder
 * can create additional isolates and use them in parallel in multiple
 * threads.  An isolate can be entered by at most one thread at any
 * given time.  The Locker/Unlocker API must be used to synchronize.
 */
class V8EXPORT Isolate {
public:
    /**
     * Stack-allocated class which sets the isolate for all operations
     * executed within a local scope.
     */
    class V8EXPORT Scope {
    public:
        explicit Scope(Isolate *isolate) : isolate_(isolate) {
            isolate->Enter();
        }

        ~Scope() { isolate_->Exit(); }

    private:
        Isolate *const isolate_;

        // Prevent copying of Scope objects.
        Scope(const Scope &);
        Scope &operator=(const Scope &);
    };

    /**
     * Creates a new isolate.  Does not change the currently entered
     * isolate.
     *
     * When an isolate is no longer used its resources should be freed
     * by calling Dispose().  Using the delete operator is not allowed.
     */
    static Isolate *New();

    /**
     * Returns the entered isolate for the current thread or NULL in
     * case there is no current isolate.
     */
    static Isolate *GetCurrent();

    /**
     * Custom callback used by embedders to help V8 determine if it should abort
     * when it throws and no internal handler can catch the exception.
     * If FLAG_abort_on_uncaught_exception is true, then V8 will abort if either:
     * - no custom callback is set.
     * - the custom callback set returns true.
     * Otherwise it won't abort.
     */
    typedef bool (*abort_on_uncaught_exception_t)();
    void SetAbortOnUncaughtException(abort_on_uncaught_exception_t callback);

    /**
     * Methods below this point require holding a lock (using Locker) in
     * a multi-threaded environment.
     */

    /**
     * Sets this isolate as the entered one for the current thread.
     * Saves the previously entered one (if any), so that it can be
     * restored when exiting.  Re-entering an isolate is allowed.
     */
    void Enter();

    /**
     * Exits this isolate by restoring the previously entered one in the
     * current thread.  The isolate may still stay the same, if it was
     * entered more than once.
     *
     * Requires: this == Isolate::GetCurrent().
     */
    void Exit();

    /**
     * Disposes the isolate.  The isolate must not be entered by any
     * thread to be disposable.
     */
    void Dispose();

    /**
     * Associate embedder-specific data with the isolate
     */
    inline void SetData(void *data);

    /**
     * Retrieve embedder-specific data from the isolate.
     * Returns NULL if SetData has never been called.
     */
    inline void *GetData();

    /**
     * 直接通过 TLS 获得当前线程的 Isolate 实例
     */
    static Isolate *Current();
    static Isolate *UncheckedCurrent();

    static void EnsureDefaultIsolate();
    static void EnterDefaultIsolate();

    inline DukContextRef GetDukContext();

    inline i::AutoReleasePool *GetAutoReleasePool();

    bool Init();
    void Deinit();

    bool IsInitialized() { return state_ == INITIALIZED; }

    // Destroys the non-default isolates.
    // Sets default isolate into "has_been_disposed" state rather then destroying,
    // for legacy API reasons.
    void TearDown();

    bool IsDefaultIsolate() const { return this == default_isolate_; }

    Isolate();
    ~Isolate();

private:
    Isolate(const Isolate &);
    Isolate &operator=(const Isolate &);

private:
    enum State {
        UNINITIALIZED,    // Some components may not have been allocated.
        INITIALIZED       // All components are fully initialized.
    };

    State state_;

    static Isolate *default_isolate_;
    Isolate *previous_isolate_;
    void *data_;
    i::AutoReleasePool *auto_release_pool_;
    duk_context *duk_ctx_;

    static i::Thread::LocalStorageKey isolate_key_;
};

void Isolate::SetData(void *data) {
    data_ = data;
}

void *Isolate::GetData() {
    return data_;
}

DukContextRef Isolate::GetDukContext() {
    return duk_ctx_;
}

i::AutoReleasePool *Isolate::GetAutoReleasePool() {
    return auto_release_pool_;
}

}

#endif //DUKV8_ISOLATE_H


text:
package com.example.nayon.nanjicamp.widget;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Typeface;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * Created by nayon on 2017-04-23.
 */
public class NanumTextView extends TextView{

    public NanumTextView(Context context) {
        super(context);
        setType(context);
    }

    public NanumTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setType(context);
    }

    public NanumTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setType(context);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public NanumTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        setType(context);
    }

    private void setType(Context context){
        this.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/NanumGothic.ttf.mp3"));
    }
}


text:
package org.semanticweb.yars.util.thread;

import java.util.Iterator;
import java.util.concurrent.BlockingQueue;

import org.semanticweb.yars.nx.Node;
import org.semanticweb.yars.nx.Nodes;
import org.semanticweb.yars.nx.cli.Main;

/**
 * Thread which takes a Node[] Iterator and successively adds
 * the contents to a blocking queue. Also adds Nodes.EOM when
 * the iterator is exhausted.
 *
 * @author aidhog
 *
 */
public class ProducerThread extends Thread{
	int _ticks = Main.TICKS;

	static int _thread_count = 0;

	Iterator<Node[]> _in;
	BlockingQueue<Node[]> _q;
	InterruptedException _e;

	public ProducerThread(Iterator<Node[]> in, BlockingQueue<Node[]> q){
		super(ProducerThread.class.getName()+_thread_count);
		_thread_count++;
		_q = q;
		_in = in;
	}

	public void run(){
		int i = 0;
		try {
			while(_in.hasNext()){
				i++;
				if(_ticks>0 && i%_ticks ==0){
					System.err.println(getName()+" done "+i);
				}
				_q.put(_in.next());
			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			_e = e;
		}
		_q.add(Nodes.EOM);
	}

	public void setTicks(int ticks){
		_ticks = ticks;
	}

	public boolean successful(){
		return _e == null;
	}

	public InterruptedException getException(){
		return _e;
	}
}


text:
#include "webrtc/modules/audio_processing/aecm/aecm_core.h"

#include <stddef.h>

// Define offset variables that will be compiled and abstracted to constant
// defines, which will then only be used in ARM assembly code.
int offset_aecm_dfaCleanQDomain = offsetof(AecmCore_t, dfaCleanQDomain);
int offset_aecm_outBuf = offsetof(AecmCore_t, outBuf);
int offset_aecm_xBuf = offsetof(AecmCore_t, xBuf);
int offset_aecm_dBufNoisy = offsetof(AecmCore_t, dBufNoisy);
int offset_aecm_dBufClean = offsetof(AecmCore_t, dBufClean);
int offset_aecm_channelStored = offsetof(AecmCore_t, channelStored);
int offset_aecm_channelAdapt16 = offsetof(AecmCore_t, channelAdapt16);
int offset_aecm_channelAdapt32 = offsetof(AecmCore_t, channelAdapt32);
int offset_aecm_real_fft = offsetof(AecmCore_t, real_fft);


text:
import logging
import os
import subprocess
import shutil
import threading
import time

# Added to support running module as script from arbitrary location.
from os.path import dirname, realpath, sep, pardir
fullpathlist = realpath(__file__).split(sep)
prepath = sep.join(fullpathlist[:-2])
import sys
sys.path.insert(0, prepath)

# module level threadlock
boscolock = threading.Lock()
boscoaddlock = threading.Lock()

class BoscoCluster(object):

    def __init__(self, entry, cluster_type='pbs', port=22, max_queued=-1,  ):
        self.log = logging.getLogger('autopyfactory')
        self.entry = entry
        (self.user, self.host) = entry.split('@')
        self.port = port
        self.max_queued = max_queued
        self.cluster_type = cluster_type
        self.log.debug("Init complete. ")

    def getentry(self):
        s += "entry=%s max_queueud=%d cluster_type=%s " % (self.entry, self.max_queued, self.cluster_type)
        return s

    def __str__(self):
        return self.getentry()

class _boscocli(object):
    """
    Encapsulates all bosco_cluster command functionality.

    """

    def __init__(self):
        self.log = logging.getLogger('autopyfactory')
        self.log.debug("Initializing bosco module...")
        self.boscopubkeyfile = os.path.expanduser("~/.ssh/bosco_key.rsa.pub")
        self.boscoprivkeyfile = os.path.expanduser("~/.ssh/bosco_key.rsa")
        self.boscopassfile = os.path.expanduser("~/.bosco/.pass")
        self.boscokeydir = os.path.expanduser("~/.ssh")
        self.boscodir = os.path.expanduser('~/.bosco')
        if os.path.exists(self.boscokeydir) and os.path.isdir(self.boscokeydir):
            self.log.debug("boscokeydir exists.")
        else:
            self.log.debug("Making boscokeydir.")
            os.makedirs(self.boscokeydir)
        if os.path.exists(self.boscodir) and os.path.isdir(self.boscodir):
            self.log.debug('bosco dir exists')
        else:
            self.log.debug("Making boscodir.")
            os.makedirs(self.boscodir)

    def _checkbosco(self):
        """
        Confirm BOSCO is installed.
        """
        self.log.debug("Checking to see if local bosco_cluster is on path...")
        isinstalled = False
        exetouse = None
        for path in os.environ['PATH'].split(os.pathsep):
            path = path.strip('"')
            exefile = os.path.join(path,'bosco_cluster')
            if os.path.isfile(exefile) and os.access(exefile, os.X_OK):
                isinstalled = True
                exetouse = exefile
        if not isinstalled:
            self.log.error('Missing dep. bosco_cluster not on PATH: %s' % os.environ['PATH'])
            #raise MissingDependencyFailure('Missing dep. bosco_cluster not on PATH: %s' % os.environ['PATH'] )
        else:
            self.log.debug("Using bosco_cluster: %s" % exetouse )
        return isinstalled

    def _getBoscoClusters(self):
        """
        [jhover@grid05 ~]$ bosco_cluster -l
        griddev03.racf.bnl.gov/slurm

        """
        cmd = 'bosco_cluster -l '
        self.log.debug("cmd is %s" % cmd)
        before = time.time()
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        out = None
        (out, err) = p.communicate()
        delta = time.time() - before
        self.log.debug('It took %s seconds to issue the command' %delta)
        self.log.debug('%s seconds to issue command' %delta)
        if p.returncode == 0 or p.returncode == 2:
            self.log.debug('Leaving with OK return code.')
        else:
            self.log.warning('Leaving with bad return code. rc=%s err=%s' %(p.returncode, err ))
        self.clusters = []
        lines = out.split("\n")
        self.log.debug("got %d lines" % len(lines))
        for line in lines:
            self.log.debug("line is %s" % line)
            if line.strip() == 'No clusters configured':
                self.log.debug("No clusters configured.")
            elif len(line) < 2:
                self.log.debug('empty line discarded')
            else:
                host, batch = line.split('/')
                #  entry, cluster_type='pbs', port=22, max_queued=-1,
                self.log.debug('got entry from bosco: %s %s Making object... ' % (host, batch))
                bentry = BoscoCluster(entry=host, cluster_type=batch)
                self.log.debug('made bentry object, appending.')
                self.clusters.append(bentry)

        return self.clusters

    def _clusteradd(self,
                    user,
                    host,
                    port,
                    batch,
                    pubkeyfile,
                    privkeyfile,
                    passfile=None):
        self.log.info("Setting up cluster %s@%s/%s " % (user, host, batch))

        self.log.debug("ensuring pubkeyfile")
        shutil.copy(pubkeyfile, self.boscopubkeyfile)
        shutil.copy(pubkeyfile, os.path.expanduser("~/.ssh/id_rsa.pub") )
        self.log.debug("ensuring privkeyfile")
        shutil.copy(privkeyfile, self.boscoprivkeyfile)
        shutil.copy(privkeyfile, os.path.expanduser("~/.ssh/id_rsa"))
        if passfile:
            self.log.debug("ensuring passfile")
            shutil.copy(passfile, self.boscopassfile )

        self._start_agent(pubkeyfile, privkeyfile, passfile)

        self.log.debug("getting add lock")
        boscoaddlock.acquire()
        try:
            cmd = 'bosco_cluster -a %s@%s %s ' % (user, host, batch)
            self.log.debug("cmd is %s" % cmd)
            before = time.time()
            p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
            out = None
            (out, err) = p.communicate()
            self.log.debug('bosco_cluster -a output was %s' % out)
            delta = time.time() - before
            self.log.debug('It took %s seconds to issue the command' %delta)
            self.log.debug('%s seconds to issue command' %delta)

            # remove bosco files to ensure account separation...
            for fn in [self.boscopubkeyfile, self.boscoprivkeyfile, self.boscopassfile ]:
                try:
                    self.log.debug("removing %s" % fn)
                    os.remove(fn)
                except OSError:
                    # file might not exist
                    pass
                except TypeError:
                    # passfile might be None
                    pass
        except Exception, e:
            self.log.exception("Exception during bosco_cluster -a installation. ")
        finally:
            self.log.debug("releasing add lock")
            boscoaddlock.release()

    def _start_agent(self, pubkeyfile, privkeyfile, passfile=None):
        self.log.debug('cmd is ssh-agent')
        cmd = 'ssh-agent '
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        out = None
        (out,err) = p.communicate()
        lines = out.split('\n')
        for line in lines:
            self.log.debug('line is %s' % line)
            exp = line.split(';')
            if '=' in line:
                (k,v) = exp[0].split('=')
                if k == 'SSH_AUTH_SOCK':
                    os.environ['SSH_AUTH_SOCK'] = v
                    self.log.debug('setting SSH_AUTH_SOCK= %s' % v )
                elif k == 'SSH_AGENT_PID':
                    os.environ['SSH_AGENT_PID'] = v
                    self.log.debug('setting SSH_AGENT_PID= %s' % v )
                else:
                    pass
        self.log.debug('SSH agent started, environment set....')

        #cmd = '/usr/bin/bosco_ssh_start --key %s --pass %s ' % (privkeyfile, passfile)
        cmd = 'bosco_ssh_start --key %s --nopass ' % privkeyfile
        self.log.debug('cmd is %s' % cmd)
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        out = None
        (out,err) = p.communicate()
        self.log.debug('ssh_start completed.')

        cmd = 'ssh-add -l '
        self.log.debug('cmd is %s' % cmd)
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        out = None
        (out,err) = p.communicate()
        self.log.debug('ssh-add -l : %s' % out)

    def _clusteraddnative(self,host,batch):
        self.log.info("Setting up cluster %s/%s " % (host,batch))

    def _checktarget(self, user, host, port, batch, pubkeyfile, privkeyfile, passfile=None ):
        """
        Ensure bosco_cluster has been run.
        """
        #Ensure paths
        pubkeyfile = os.path.expanduser(pubkeyfile)
        privkeyfile = os.path.expanduser(privkeyfile)
        try:
            passfile = os.path.expanduser(passfile)
        except AttributeError:
            pass

        self.log.debug("Checking to see if remote bosco is installed and up to date...")
        host = host.lower()
        batch = batch.lower()
        try:
            self.log.debug("getting lock")
            boscolock.acquire()
            clist = self._getBoscoClusters()
            self.log.debug("got list of %d clusters" % len(clist))
            found = False
            for c in clist:
                if c.user == user and c.host == host and c.cluster_type == batch:
                    found = True
            if not found:
                self.log.info("Setting up cluster %s/%s " % (host,batch))
                self._clusteradd(user, host, port, batch, pubkeyfile, privkeyfile, passfile)
            else:
                self.log.debug("Cluster %s@%s/%s already set up." % (user,host,batch))

        except Exception, e:
            self.log.exception("Exception during bosco remote installation. ")

        finally:
            self.log.debug("releasing lock")
            boscolock.release()

# Singleton implementation
class BoscoCLI(object):

    instance = None

    def __new__(cls, *k, **kw):
        if not BoscoCLI.instance:
            BoscoCLI.instance = _boscocli(*k, **kw)
        return BoscoCLI.instance

# =============================================================================

if __name__ == '__main__':
    # Set up logging.
    debug = 0
    info = 0

    # Check python version
    major, minor, release, st, num = sys.version_info

    # Set up logging, handle differences between Python versions...
    # In Python 2.3, logging.basicConfig takes no args
    #
    FORMAT23="[ %(levelname)s ] %(asctime)s %(filename)s (Line %(lineno)d): %(message)s"
    FORMAT24=FORMAT23
    FORMAT25="[%(levelname)s] %(asctime)s %(module)s.%(funcName)s(): %(message)s"
    FORMAT26=FORMAT25

    if major == 2:
        if minor ==3:
            formatstr = FORMAT23
        elif minor == 4:
            formatstr = FORMAT24
        elif minor == 5:
            formatstr = FORMAT25
        elif minor == 6:
            formatstr = FORMAT26
        elif minor == 7:
            formatstr = FORMAT26

    log = logging.getLogger('autopyfactory')
    hdlr = logging.StreamHandler(sys.stdout)
    formatter = logging.Formatter(FORMAT23)
    hdlr.setFormatter(formatter)
    log.addHandler(hdlr)

    if debug:
        log.setLevel(logging.DEBUG) # Override with command line switches
    if info:
        log.setLevel(logging.INFO) # Override with command line switches
    log.debug("Logging initialized.")

    bcli = BoscoCLI()
    bcli._checktarget('gridev03.racf.bnl.gov', 'slurm', '~/etc/apf/jhover/pass')


text:
package com.codefactoring.android.backlogtracker.sync.fetchers;

import com.codefactoring.android.backlogapi.BacklogToolConfig;

public class BacklogTestConfig extends BacklogToolConfig {
    @Override
    public String getBaseURL(String spaceUrl) {
        return spaceUrl;
    }
}


text:
using System;
using MiscUtil.Linq;
using NUnit.Framework;

namespace MiscUtil.UnitTests.Linq
{
    [TestFixture]
    public class FutureProxyTest
    {
        [Test]
        public void RequestingValueBeforeSourceHasDataPropagatesException()
        {
            Future<string> source = new Future<string>();
            FutureProxy<int> subject = FutureProxy<int>.FromFuture(source, x => x.Length);
            try
            {
                Console.WriteLine(subject.Value);
                Assert.Fail("Expected exception");
            }
            catch (InvalidOperationException)
            {
                // Expected
            }
        }

        [Test]
        public void RequestingValueAfterSourceHasDataPerformsTransformation()
        {
            Future<string> source = new Future<string>();
            FutureProxy<int> subject = FutureProxy<int>.FromFuture(source, x => x.Length);
            source.Value = "hello";
            Assert.AreEqual(5, subject.Value);
        }
    }
}


text:
'use strict';

require('configureForRelayOSS');

const RelayTestUtils = require('RelayTestUtils');

const callsFromGraphQL = require('callsFromGraphQL');
const callsToGraphQL = require('callsToGraphQL');

describe('callsToGraphQL', function() {
  it('converts array calls with null values', () => {
    const relayCalls = [
      {
        name: 'size',
        type: 'Int',
        value: null,
      },
    ];
    const graphqlCalls = [RelayTestUtils.createCall('size', null, 'Int')];
    expect(callsFromGraphQL(graphqlCalls)).toEqual(relayCalls);
    expect(callsToGraphQL(relayCalls)).toEqual(graphqlCalls);
  });

  it('converts array calls without values', () => {
    const relayCalls = [
      {
        name: 'size',
        type: '[Int]',
        value: [],
      },
    ];
    const graphqlCalls = [RelayTestUtils.createCall('size', [], '[Int]')];
    expect(callsFromGraphQL(graphqlCalls)).toEqual(relayCalls);
    expect(callsToGraphQL(relayCalls)).toEqual(graphqlCalls);
  });

  it('converts calls with array values', () => {
    const relayCalls = [
      {
        name: 'size',
        type: '[Int]',
        value: [32, 64],
      },
    ];
    const graphqlCalls = [RelayTestUtils.createCall('size', [32, 64], '[Int]')];
    expect(callsFromGraphQL(graphqlCalls)).toEqual(relayCalls);
    expect(callsToGraphQL(relayCalls)).toEqual(graphqlCalls);
  });

  it('converts singular calls with null values', () => {
    const relayCalls = [
      {
        name: 'size',
        type: 'Int',
        value: 32,
      },
    ];
    const graphqlCalls = [RelayTestUtils.createCall('size', 32, 'Int')];
    expect(callsFromGraphQL(graphqlCalls)).toEqual(relayCalls);
    expect(callsToGraphQL(relayCalls)).toEqual(graphqlCalls);
  });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" android:exitFadeDuration="@android:integer/config_mediumAnimTime">

    <item android:state_pressed="false" android:color="@android:color/white"/>
    <item android:state_pressed="true" android:color="@color/light_grey"/>

</selector>


text:
SHELL := /bin/bash

test:
	py.test

test-deps:
	pip install -r requirements.txt

six:
	python test_client.py

deps: requests


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

package build.bazel.tests.integration;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * A utility class to spawn a command and get its output.
 *
 * <p>This class can only be initialized using a builder created with the {@link #builder()} method.
 */
public final class Command {

  private final Path directory;
  private final List<String> args;
  private final List<String> stderr = Collections.synchronizedList(new LinkedList<>());
  private final List<String> stdout = Collections.synchronizedList(new LinkedList<>());
  private final Map<String, String> environment;
  private boolean executed = false;

  private Command(Path directory, List<String> args, Map<String, String> environment) {
    this.directory = directory;
    this.args = args;
    this.environment = environment;
  }

  /**
   * Executes the command represented by this instance, and return the exit code of the command.
   * This method should not be called twice on the same object.
   */
  public int run() throws IOException, InterruptedException {
    assert !executed;
    executed = true;
    ProcessBuilder builder = new ProcessBuilder(args);
    builder.directory(directory.toFile());
    builder.environment().putAll(environment);
    builder.redirectOutput(ProcessBuilder.Redirect.PIPE);
    builder.redirectError(ProcessBuilder.Redirect.PIPE);
    Process process = builder.start();
    Thread err = streamToLinesThread(process.getErrorStream(), stderr);
    // seriously? That's stdout, why is it called getInputStream???
    Thread out = streamToLinesThread(process.getInputStream(), stdout);
    int exitCode = process.waitFor();
    if (err != null) {
      err.join();
    }
    if (out != null) {
      out.join();
    }

    return exitCode;
  }

  private static Thread streamToLinesThread(
      final InputStream inputStream, final List<String> lines) {
    Thread thread =
        new Thread(
            () -> {
              new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))
                  .lines()
                  .forEach(lines::add);
            });
    thread.start();
    return thread;
  }

  /** Returns the list of lines of the standard error stream. */
  public List<String> getErrorLines() {
    synchronized (stderr) {
      return copyToUnmodifiableList(stderr);
    }
  }

  /** Returns the list of lines of the standard output stream. */
  public List<String> getOutputLines() {
    synchronized (stdout) {
      return copyToUnmodifiableList(stdout);
    }
  }

  private static <T> List<T> copyToUnmodifiableList(final List<T> source) {
    return Collections.unmodifiableList(new LinkedList<>(source));
  }

  /** A builder class to generate a Command object. */
  static class Builder {

    private Path directory;
    private List<String> args = new ArrayList<>();
    private Map<String, String> environment = new HashMap<>();

    private Builder() {
      // Default to the current working directory
      this.directory = Paths.get(System.getProperty("user.dir"));
    }

    /**
     * Set the working directory for the program, it is set to the current working directory of the
     * current java process by default.
     */
    public Builder setDirectory(Path directory) {
      this.directory = directory;
      return this;
    }

    /**
     * Add arguments to the command line. The first argument to be added to the builder is the
     * program name.
     */
    public Builder addArguments(String... args) {
      this.args.addAll(Arrays.asList(args));
      return this;
    }

    /**
     * Add a list of arguments to the command line. The first argument to be added to the builder is
     * the program name.
     */
    public Builder addArguments(Iterable<String> args) {
      for (String arg : args) {
        this.args.add(arg);
      }
      return this;
    }

    /** Sets environment variable in the runtime */
    public Builder withEnvironment(Map<String, String> environment) {
      this.environment = Collections.unmodifiableMap(environment);
      return this;
    }

    /** Build a Command object. */
    public Command build() {
      Objects.requireNonNull(directory);
      List<String> args = Collections.unmodifiableList(this.args);
      Map<String, String> env = Collections.unmodifiableMap(environment);
      return new Command(directory, args, env);
    }
  }

  /** Returns a {@link Builder} object to use to create a {@link Command} object. */
  static Builder builder() {
    return new Builder();
  }
}