text:
package org.openqa.selenium;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.openqa.selenium.Ignore.Driver.CHROME;
import static org.openqa.selenium.Ignore.Driver.FIREFOX;
import static org.openqa.selenium.Ignore.Driver.HTMLUNIT;
import static org.openqa.selenium.Ignore.Driver.IE;
import static org.openqa.selenium.Ignore.Driver.IPHONE;
import static org.openqa.selenium.Ignore.Driver.REMOTE;
import static org.openqa.selenium.Ignore.Driver.SELENESE;

public class ExecutingJavascriptTest extends AbstractDriverTestCase {

  @JavascriptEnabled
  public void testShouldBeAbleToExecuteSimpleJavascriptAndReturnAString() {
    if (!(driver instanceof JavascriptExecutor)) {
      return;
    }

    driver.get(pages.xhtmlTestPage);

    Object result = executeScript("return document.title;");

    assertTrue(result instanceof String);
    assertEquals("XHTML Test Page", result);
  }

  @JavascriptEnabled
  public void testShouldBeAbleToExecuteSimpleJavascriptAndReturnALong() {
    if (!(driver instanceof JavascriptExecutor)) {
      return;
    }

    driver.get(pages.nestedPage);

    Object result = executeScript("return document.getElementsByName('checky').length;");

    assertTrue(result.getClass().getName(), result instanceof Long);
    assertTrue((Long) result > 1);
  }

  @JavascriptEnabled
  @Ignore(SELENESE)
  public void testShouldBeAbleToExecuteSimpleJavascriptAndReturnAWebElement() {
    if (!(driver instanceof JavascriptExecutor)) {
      return;
    }

    driver.get(pages.xhtmlTestPage);

    Object result = executeScript("return document.getElementById('id1');");

    assertNotNull(result);
    assertTrue("Expected WebElement, got: " + result.getClass(), result instanceof WebElement);
  }

  @JavascriptEnabled
  public void testShouldBeAbleToExecuteSimpleJavascriptAndReturnABoolean() {
    if (!(driver instanceof JavascriptExecutor)) {
      return;
    }

    driver.get(pages.xhtmlTestPage);

    Object result = executeScript("return true;");

    assertNotNull(result);
    assertTrue(result instanceof Boolean);
    assertTrue((Boolean) result);
  }

  @SuppressWarnings("unchecked")
  @JavascriptEnabled
  @Ignore(SELENESE)
  public void testShouldBeAbleToExecuteSimpleJavascriptAndAStringsArray() {
    if (!(driver instanceof JavascriptExecutor)) {
      return;
    }

    driver.get(pages.javascriptPage);
    List<Object> expectedResult = new ArrayList<Object>();
    expectedResult.add("zero");
    expectedResult.add("one");
    expectedResult.add("two");
    Object result = ((JavascriptExecutor) driver).executeScript(
    "return ['zero', 'one', 'two'];");

    ExecutingJavascriptTest.compareLists(expectedResult, (List<Object>) result);
  }

  @SuppressWarnings("unchecked")
  @JavascriptEnabled
  @Ignore({SELENESE, IPHONE})
  public void testShouldBeAbleToExecuteSimpleJavascriptAndReturnAnArray() {
    if (!(driver instanceof JavascriptExecutor)) {
      return;
    }

    driver.get(pages.javascriptPage);
    List<Object> expectedResult = new ArrayList<Object>();
    expectedResult.add("zero");
    List<Object> subList = new ArrayList<Object>();
    subList.add(true);
    subList.add(false);
    expectedResult.add(subList);
    Object result = executeScript("return ['zero', [true, false]];");
    assertNotNull(result);
    assertTrue("result was: " + result + " (" + result.getClass() + ")", result instanceof List);
    List<Object> list = (List<Object>) result;
    assertTrue(compareLists(expectedResult, list));
  }

  @SuppressWarnings("unchecked")
  @JavascriptEnabled
  @Ignore({IE, SELENESE, IPHONE, HTMLUNIT})
  public void testShouldBeAbleToExecuteJavascriptAndReturnABasicObjectLiteral() {
    if (!(driver instanceof JavascriptExecutor)) {
      return;
    }

    driver.get(pages.javascriptPage);

    Object result = executeScript("return {abc: '123', tired: false};");
    assertTrue("result was: " + result + " (" + result.getClass() + ")", result instanceof Map);
    Map<String, Object> map = (Map<String, Object>) result;

    Map<String, Object> expected = new HashMap<String, Object>();
    expected.put("abc", "123");
    expected.put("tired", false);

    assertEquals("Expected:<" + expected + ">, but was:<" + map + ">", expected.size(),
        map.size());
    for (Map.Entry<String, Object> entry : expected.entrySet()) {
      assertEquals("Difference at key:<" + entry.getKey() + ">", entry.getValue(), map.get(entry.getKey()));
    }
  }

  @SuppressWarnings("unchecked")
  @JavascriptEnabled
  @Ignore({IE, SELENESE, IPHONE, HTMLUNIT})
  public void testShouldBeAbleToExecuteSimpleJavascriptAndReturnAnObjectLiteral() {
    if (!(driver instanceof JavascriptExecutor)) {
      return;
    }

    driver.get(pages.javascriptPage);

    Map<String, Object> expectedResult = new HashMap<String, Object>(){{
      put("foo", "bar");
      put("baz", Arrays.asList("a", "b", "c"));
      put("person", new HashMap<String, String>(){{
        put("first", "John");
        put("last", "Doe");
      }});
    }};

    Object result = executeScript(
        "return {foo:'bar', baz: ['a', 'b', 'c'], " +
            "person: {first: 'John',last: 'Doe'}};");
    assertTrue("result was: " + result + " (" + result.getClass() + ")", result instanceof Map);

    Map<String, Object> map = (Map<String, Object>) result;
    assertEquals("Expected:<" + expectedResult + ">, but was:<" + map + ">", 3, map.size());
    assertEquals(expectedResult.keySet(), map.keySet());
    assertEquals("bar", map.get("foo"));
    assertTrue(compareLists((List<?>) expectedResult.get("baz"),
        (List<?>) map.get("baz")));

    Map<String, String> person = (Map<String, String>) map.get("person");
    assertEquals(2, person.size());
    assertEquals("John", person.get("first"));
    assertEquals("Doe", person.get("last"));
  }

  private static boolean compareLists(List<?> first, List<?> second) {
    if (first.size() != second.size()) {
      return false;
    }
    for (int i = 0; i < first.size(); ++i) {
      if (first.get(i) instanceof List<?>) {
        if (!(second instanceof List<?>)) {
          return false;
        } else {
          if (!compareLists((List<?>) first.get(i), (List<?>) second.get(i))) {
            return false;
          }
        }
      } else {
        if (!first.get(i).equals(second.get(i))) {
          return false;
        }
      }
    }
    return true;
  }

  @JavascriptEnabled
  public void testPassingAndReturningALongShouldReturnAWholeNumber() {
    if (!(driver instanceof JavascriptExecutor)) {
      return;
    }

    driver.get(pages.javascriptPage);
    Long expectedResult = 1L;
    Object result = executeScript("return arguments[0];", expectedResult);
    assertTrue("Expected result to be an Integer or Long but was a " +
               result.getClass(), result instanceof Integer || result instanceof Long);
    assertEquals(expectedResult.longValue(), result);
  }

  @JavascriptEnabled
  public void testPassingAndReturningADoubleShouldReturnADecimal() {
    if (!(driver instanceof JavascriptExecutor)) {
      return;
    }

    driver.get(pages.javascriptPage);
    Double expectedResult = 1.2;
    Object result = executeScript("return arguments[0];", expectedResult);
    assertTrue("Expected result to be a Double or Float but was a " +
               result.getClass(), result instanceof Float || result instanceof Double);
    assertEquals(expectedResult.doubleValue(), result);
  }

  @JavascriptEnabled
  public void testShouldThrowAnExceptionWhenTheJavascriptIsBad() {
    if (!(driver instanceof JavascriptExecutor)) {
      return;
    }

    driver.get(pages.xhtmlTestPage);

    try {
      executeScript("return squiggle();");
      fail("Expected an exception");
    } catch (Exception e) {
      // This is expected
    }
  }

  @JavascriptEnabled
  @Ignore(SELENESE)
  public void testShouldBeAbleToCallFunctionsDefinedOnThePage() {
    if (!(driver instanceof JavascriptExecutor)) {
      return;
    }

    driver.get(pages.javascriptPage);
    executeScript("displayMessage('I like cheese');");
    String text = driver.findElement(By.id("result")).getText();

    assertEquals("I like cheese", text.trim());
  }

  private Object executeScript(String script, Object... args) {
    return ((JavascriptExecutor) driver).executeScript(script, args);
  }

  @JavascriptEnabled
  public void testShouldBeAbleToPassAStringAnAsArgument() {
    if (!(driver instanceof JavascriptExecutor)) {
      return;
    }

    driver.get(pages.javascriptPage);
    String
        value =
        (String) executeScript("return arguments[0] == 'fish' ? 'fish' : 'not fish';", "fish");

    assertEquals("fish", value);
  }

  @JavascriptEnabled
  public void testShouldBeAbleToPassABooleanAnAsArgument() {
    if (!(driver instanceof JavascriptExecutor)) {
      return;
    }

    driver.get(pages.javascriptPage);
    boolean value = (Boolean) executeScript("return arguments[0] == true;", true);

    assertTrue(value);
  }

  @JavascriptEnabled
  public void testShouldBeAbleToPassANumberAnAsArgument() {
    if (!(driver instanceof JavascriptExecutor)) {
      return;
    }

    driver.get(pages.javascriptPage);
    boolean value = (Boolean) executeScript("return arguments[0] == 1 ? true : false;", 1);

    assertTrue(value);
  }

  @JavascriptEnabled
  @Ignore(SELENESE)
  public void testShouldBeAbleToPassAWebElementAsArgument() {
    if (!(driver instanceof JavascriptExecutor)) {
      return;
    }

    driver.get(pages.javascriptPage);
    WebElement button = driver.findElement(By.id("plainButton"));
    String value = (String) executeScript(
        "arguments[0]['flibble'] = arguments[0].getAttribute('id'); return arguments[0]['flibble'];",
        button);

    assertEquals("plainButton", value);
  }

  @JavascriptEnabled
  @Ignore({IE, SELENESE})
  public void testShouldBeAbleToPassAnArrayAsArgument() {
    if (!(driver instanceof JavascriptExecutor)) {
      return;
    }

    driver.get(pages.javascriptPage);
    Object[] array = new Object[]{"zero", 1, true, 3.14159};
    long length = (Long) executeScript("return arguments[0].length", array);
    assertEquals(array.length, length);
  }

  @JavascriptEnabled
  @Ignore({IE, SELENESE})
  public void testShouldBeAbleToPassACollectionAsArgument() {
    if (!(driver instanceof JavascriptExecutor)) {
      return;
    }

    driver.get(pages.javascriptPage);
    Collection<Object> collection = new ArrayList<Object>();
    collection.add("Cheddar");
    collection.add("Brie");
    collection.add(7);
    long length = (Long) executeScript("return arguments[0].length", collection);
    assertEquals(collection.size(), length);

    collection = new HashSet<Object>();
    collection.add("Gouda");
    collection.add("Stilton");
    collection.add("Stilton");
    collection.add(true);
    length = (Long) executeScript("return arguments[0].length", collection);
    assertEquals(collection.size(), length);
  }

  @JavascriptEnabled
  public void testShouldThrowAnExceptionIfAnArgumentIsNotValid() {
    if (!(driver instanceof JavascriptExecutor)) {
      return;
    }

    driver.get(pages.javascriptPage);
    try {
      executeScript("return arguments[0];", driver);
      fail("Exception should have been thrown");
    } catch (IllegalArgumentException e) {
      // this is expected
    }
  }

  @JavascriptEnabled
  public void testShouldBeAbleToPassInMoreThanOneArgument() {
    if (!(driver instanceof JavascriptExecutor)) {
      return;
    }

    driver.get(pages.javascriptPage);
    String result = (String) executeScript("return arguments[0] + arguments[1];", "one", "two");

    assertEquals("onetwo", result);
  }

  @Ignore(value = {CHROME, SELENESE, IPHONE},
      reason = "Can't execute script in iframe, track crbug 20773\n"
               + "iPhone: Frame switching not yet implemented.")
  @JavascriptEnabled
  public void testShouldBeAbleToGrabTheBodyOfFrameOnceSwitchedTo() {
    driver.get(pages.richTextPage);

    driver.switchTo().frame("editFrame");
    WebElement body =
        (WebElement) ((JavascriptExecutor) driver).executeScript("return document.body");

    assertEquals("", body.getText());
  }

  @Ignore
  public void testShouldBeAbleToReturnAnArrayOfWebElements() {
    driver.get(pages.formPage);

    List<WebElement> items = (List<WebElement>) ((JavascriptExecutor) driver)
        .executeScript("return document.getElementsByName('snack');");

    assertTrue(items.size() > 0);
  }

  @JavascriptEnabled
  @Ignore(SELENESE)
  public void testJavascriptStringHandlingShouldWorkAsExpected() {
    driver.get(pages.javascriptPage);

    String value = (String) executeScript("return '';");
    assertEquals("", value);

    value = (String) executeScript("return undefined;");
    assertNull(value);

    value = (String) executeScript("return ' '");
    assertEquals(" ", value);
  }

  @JavascriptEnabled
  @Ignore({CHROME, FIREFOX})
  public void testShouldBeAbleToExecuteABigChunkOfJavascriptCode() throws IOException {
    driver.get(pages.javascriptPage);

    File jqueryFile = new File("common/src/web/jquery-1.3.2.js");
    if(!jqueryFile.isFile()) {
      jqueryFile = new File("../common/src/web/jquery-1.3.2.js");
      if(!jqueryFile.isFile()) {
        jqueryFile = new File("../../common/src/web/jquery-1.3.2.js");
      }
    }
    String jquery = FileUtils.readFileToString(jqueryFile, "US-ASCII");
    assertTrue("The javascript code should be at least 50 KB.", jquery.length() > 50000);
    // This should not throw an exception ...
    executeScript(jquery);
  }

  @SuppressWarnings("unchecked")
  @JavascriptEnabled
  @Ignore({SELENESE, CHROME, REMOTE, IPHONE})
  public void testShouldBeAbleToExecuteScriptAndReturnElementsList() {
    driver.get(pages.formPage);
    String scriptToExec = "return document.getElementsByName('snack');";

    List<WebElement> resultsList = (List<WebElement>) ((JavascriptExecutor) driver)
      .executeScript(scriptToExec);

    assertTrue(resultsList.size() > 0);
  }

  @NeedsFreshDriver
  @NoDriverAfterTest
  @Ignore //Reason for ignore: Failure indicates hang condition,
          //which would break the test suite.  Really needs a timeout set.
  public void testShouldThrowExceptionIfExecutingOnNoPage() {
    try {
      ((JavascriptExecutor)driver).executeScript("return 1;");
    } catch (WebDriverException e) {
      //Expected
      return;
    }
    fail("Expected exception to be thrown");
  }
}


text:
const VoiceResponse = require('twilio').twiml.VoiceResponse;

const response = new VoiceResponse();
const connect = response.connect();
connect.autopilot('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');

console.log(response.toString());

redpajama_set_name: RedPajamaGithub


text:
require_relative "../is_visual_element"

module Blinkie
  module Drawing
    module Layout

      class Horizontal

        extend Forwardable
        include IsVisualElement

        def initialize(elements = [])
          @elements = elements
        end

        def_delegator :@elements, :<<

        def update
          @elements.each(&:update)
        end

        def draw(left, top)
          @elements.each do |element|
            element.draw(left, top)
            left += element.width
          end
        end

        def width
          @elements.map(&:width).inject(0, &:+)
        end

        def height
          @elements.map(&:height).max
        end

        def mouse_event(x, y, event)
          @elements.each do |element|
            return true if element.try_mouse_event(x, y, event)
            x -= element.width
          end
          false
        end

      end

    end
  end
end


text:
package RUM::Action::Version;

use strict;
use warnings;

use base 'RUM::Base';

use RUM::Pipeline;

sub run {
    my ($class) = @_;
    print("RUM version $RUM::Pipeline::VERSION, released $RUM::Pipeline::RELEASE_DATE\n");
}

1;

__END__

=head1 NAME

RUM::Action::Version - Print RUM version number and release date

=head1 METHODS

=over 4

=item run

Print the version number.

=item accepted_options

Returns the map of options accepted by this action.

=cut

=back


text:
package commands

import (
	"errors"
	"fmt"

	"github.com/docker/machine/cli"
	"github.com/docker/machine/libmachine/log"
)

func cmdRm(c *cli.Context) error {
	if len(c.Args()) == 0 {
		cli.ShowCommandHelp(c, "rm")
		return errors.New("You must specify a machine name")
	}

	force := c.Bool("force")
	store := getStore(c)

	for _, hostName := range c.Args() {
		h, err := loadHost(store, hostName)
		if err != nil {
			return fmt.Errorf("Error removing host %q: %s", hostName, err)
		}

		if err := h.Driver.Remove(); err != nil {
			if !force {
				log.Errorf("Provider error removing machine %q: %s", hostName, err)
				continue
			}
		}

		if err := store.Remove(hostName); err != nil {
			log.Errorf("Error removing machine %q from store: %s", hostName, err)
		} else {
			log.Infof("Successfully removed %s", hostName)
		}
	}

	return nil
}


text:
``` purescript
class (Monad m) <= MonadEff eff m where
  liftEff :: forall a. Eff eff a -> m a
```

The `MonadEff` class captures those monads which support native effects.

Instances are provided for `Eff` itself, and the standard monad transformers.

`liftEff` can be used in any appropriate monad transformer stack to lift an action
of type `Eff eff a` into the monad.

Note that `MonadEff` is parameterized by the row of effects, so type inference can be
tricky. It is generally recommended to either work with a polymorphic row of effects,
or a concrete, closed row of effects such as `(trace :: Trace)`.

#### `monadEffEff`

``` purescript
instance monadEffEff :: MonadEff eff (Eff eff)
```

#### `monadEffMaybe`

``` purescript
instance monadEffMaybe :: (Monad m, MonadEff eff m) => MonadEff eff (MaybeT m)
```

#### `monadEffError`

``` purescript
instance monadEffError :: (Monad m, MonadEff eff m) => MonadEff eff (ErrorT e m)
```

#### `monadEffState`

``` purescript
instance monadEffState :: (Monad m, MonadEff eff m) => MonadEff eff (StateT s m)
```

#### `monadEffWriter`

``` purescript
instance monadEffWriter :: (Monad m, Monoid w, MonadEff eff m) => MonadEff eff (WriterT w m)
```

#### `monadEffReader`

``` purescript
instance monadEffReader :: (Monad m, MonadEff eff m) => MonadEff eff (ReaderT r m)
```

#### `monadEffRWS`

``` purescript
instance monadEffRWS :: (Monad m, Monoid w, MonadEff eff m) => MonadEff eff (RWST r w s m)
```


text:
import * as ts from "typescript";
import * as Util from "util";

export enum ParameterHint {
    File,
    Directory
}

export enum ParameterType {
    String,
    Number,
    Boolean,
    Map,
    Mixed
}

export enum ParameterScope {
    TypeDoc, TypeScript
}

export interface IOptionDeclaration
{
    name:string;
    component?:string;
    short?:string;
    help:string;
    type?:ParameterType;
    hint?:ParameterHint;
    scope?:ParameterScope;
    map?:{};
    mapError?:string;
    isArray?:boolean;
    defaultValue?:any;
    convert?:(param:OptionDeclaration, value?:any) => any;
}

export class OptionDeclaration
{
    name:string;

    short:string;

    component:string;

    help:string;

    type:ParameterType;

    hint:ParameterHint;

    scope:ParameterScope;

    map:Object;

    mapError:string;

    isArray:boolean;

    defaultValue:any;

    constructor(data:IOptionDeclaration) {
        for (var key in data) {
            this[key] = data[key];
        }

        this.type  = this.type  || ParameterType.String;
        this.scope = this.scope || ParameterScope.TypeDoc;
    }

    getNames():string[] {
        var result = [this.name.toLowerCase()];

        if (this.short) {
            result.push(this.short.toLowerCase());
        }

        return result;
    }

    convert(value:any, errorCallback?:Function):any {
        switch (this.type) {
            case ParameterType.Number:
                value = parseInt(value);
                break;
            case ParameterType.Boolean:
                value = (typeof value === void 0 ? true : !!value);
                break;
            case ParameterType.String:
                value = value || "";
                break;
            case ParameterType.Map:
                var key = value ? (value + "").toLowerCase() : '';
                if (key in this.map) {
                    value = this.map[key];
                } else if (errorCallback) {
                    if (this.mapError) {
                        errorCallback(this.mapError);
                    } else {
                        errorCallback('Invalid value for option "%s".', this.name);
                    }
                }
                break;
        }

        return value;
    }
}


text:
#ifndef _PRESENCEPUSHTASK_H_
#define _PRESENCEPUSHTASK_H_

#include <vector>

#include "talk/examples/call/callclient.h"
#include "talk/xmpp/presencestatus.h"
#include "talk/xmpp/xmppengine.h"
#include "talk/xmpp/xmpptask.h"
#include "webrtc/base/sigslot.h"

namespace buzz {

class PresencePushTask : public XmppTask {
 public:
  PresencePushTask(XmppTaskParentInterface* parent, CallClient* client)
    : XmppTask(parent, XmppEngine::HL_TYPE),
      client_(client) {}
  virtual int ProcessStart();

  sigslot::signal1<const PresenceStatus&> SignalStatusUpdate;
  sigslot::signal1<const Jid&> SignalMucJoined;
  sigslot::signal2<const Jid&, int> SignalMucLeft;
  sigslot::signal2<const Jid&, const MucPresenceStatus&> SignalMucStatusUpdate;

 protected:
  virtual bool HandleStanza(const XmlElement * stanza);
  void HandlePresence(const Jid& from, const XmlElement * stanza);
  void HandleMucPresence(buzz::Muc* muc,
                         const Jid& from, const XmlElement * stanza);
  static void FillStatus(const Jid& from, const XmlElement * stanza,
                         PresenceStatus* status);
  static void FillMucStatus(const Jid& from, const XmlElement * stanza,
                            MucPresenceStatus* status);

 private:
  CallClient* client_;
};

}

#endif


text:
#pragma once

// ensure the MCU series is correct
#ifndef STM32PLUS_F1_MD_VL
#error This class can only be used with the STM32F1 MD VL series
#endif

/*
 * Forward declare the IRQ handler names
 */

extern "C" void USART1_IRQHandler();
extern "C" void USART2_IRQHandler();
extern "C" void USART3_IRQHandler();

namespace stm32plus {

  /**
   * Helper class to enable only the desired interrupts in the NVIC. This will
   * be fully specialised for each USART peripheral
   * @tparam TUsartNumber The number of the USART peripheral (1..3)
   */

  template<uint8_t TUsartNumber>
  class UsartInterruptFeatureEnabler {

    private:
      typedef void (*FPTR)();         // this trick will force the linker to include the ISR
      static FPTR _forceLinkage;

    public:
      static void enable();
  };

  /**
   * DMA feature to handle interrupts
   * @tparam TUsartNumber The number of the USART peripheral (1..3)
   */

  template<uint8_t TUsartNumber>
  class UsartInterruptFeature : public UsartEventSource,
                                public UsartFeatureBase {

    protected:
      uint16_t _interruptMask;

    public:

      enum {
        RECEIVE = USART_IT_RXNE,
        TRANSMIT = USART_IT_TXE
      };

      static UsartEventSource *_usartInstance;

    public:
      UsartInterruptFeature(Usart& usart);
      ~UsartInterruptFeature();

      void enableInterrupts(uint16_t interruptMask);
      void disableInterrupts(uint16_t interruptMask);
  };

  /**
   * Typedefs for each USART
   */

  typedef UsartInterruptFeature<1> Usart1InterruptFeature;
  typedef UsartInterruptFeature<2> Usart2InterruptFeature;
  typedef UsartInterruptFeature<3> Usart3InterruptFeature;

  /**
   * Constructor, initialises the interrupt mask for this class to zero.
   */

  template<uint8_t TUsartNumber>
  inline UsartInterruptFeature<TUsartNumber>::UsartInterruptFeature(Usart& usart)
    : UsartFeatureBase(usart) {

    _interruptMask=0;
    _usartInstance=this;
  }

  /**
   * Destructor, if any interrupts are configured for this class then
   * disable them so that ISR calls don't disappear off into nothing
   */

  template<uint8_t TUsartNumber>
  inline UsartInterruptFeature<TUsartNumber>::~UsartInterruptFeature() {
    if(_interruptMask!=0)
      disableInterrupts(_interruptMask);
  }

  /**
   * Enable the interrupts specified in the mask
   * @param interruptMask The bitmask of interrupts, e.g. USART_IT_TXE / USART_IT_RXNE
   */

  template<uint8_t TUsartNumber>
  inline void UsartInterruptFeature<TUsartNumber>::enableInterrupts(uint16_t interruptMask) {

    _interruptMask|=interruptMask;
    UsartInterruptFeatureEnabler<TUsartNumber>::enable();
    USART_ITConfig(_usart,interruptMask,ENABLE);
  }

  /**
   * Disable the interrupts specified in the mask
   * @param interruptMask The bitmask of interrupts, e.g. USART_IT_TXE / USART_IT_RXNE
   */

  template<uint8_t TUsartNumber>
  inline void UsartInterruptFeature<TUsartNumber>::disableInterrupts(uint16_t interruptMask) {
    _interruptMask&=~interruptMask;
    USART_ITConfig(_usart,interruptMask,DISABLE);
  }

  /**
   * Enabler specialisation, Usart 1
   */

  template<>
  inline void UsartInterruptFeatureEnabler<1>::enable() {
    _forceLinkage=&USART1_IRQHandler;
    Nvic::configureIrq(USART1_IRQn);
  }

  /**
   * Enabler specialisation, Usart 2
   */

  template<>
  inline void UsartInterruptFeatureEnabler<2>::enable() {
    _forceLinkage=&USART2_IRQHandler;
    Nvic::configureIrq(USART2_IRQn);
  }

  /**
   * Enabler specialisation, Usart 3
   */

  template<>
  inline void UsartInterruptFeatureEnabler<3>::enable() {
    _forceLinkage=&USART3_IRQHandler;
    Nvic::configureIrq(USART3_IRQn);
  }
}


text:
package info.globalbus.blueprint.plugin.handlers.blueprint.config;

import java.lang.reflect.AnnotatedElement;
import org.apache.aries.blueprint.annotation.config.Config;
import org.apache.aries.blueprint.plugin.spi.BeanAnnotationHandler;
import org.apache.aries.blueprint.plugin.spi.BeanEnricher;
import org.apache.aries.blueprint.plugin.spi.ContextEnricher;

public class ConfigAnnotationHandler implements BeanAnnotationHandler<Config> {

    @Override
    public Class<Config> getAnnotation() {
        return Config.class;
    }

    @Override
    public void handleBeanAnnotation(AnnotatedElement annotatedElement, String id,
                                     ContextEnricher contextEnricher, BeanEnricher beanEnricher) {
        Config config = annotatedElement.getAnnotation(Config.class);
        contextEnricher.addBlueprintContentWriter("cm/property-placeholder", new ConfigWriter(config));
    }

}


text:
class AddBuiltInKeyToNationalParks < ActiveRecord::Migration
  def change
    add_column :national_parks, :built_in_key, :string
  end
end


text:
require "spec_helper"

describe AppointmentsController do
  describe "routing" do

    it "routes to #index" do
      get("/appointments").should route_to("appointments#index")
    end

    it "routes to #new" do
      get("/appointments/new").should route_to("appointments#new")
    end

    it "routes to #show" do
      get("/appointments/1").should route_to("appointments#show", :id => "1")
    end

    it "routes to #edit" do
      get("/appointments/1/edit").should route_to("appointments#edit", :id => "1")
    end

    it "routes to #create" do
      post("/appointments").should route_to("appointments#create")
    end

    it "routes to #update" do
      put("/appointments/1").should route_to("appointments#update", :id => "1")
    end

    it "routes to #destroy" do
      delete("/appointments/1").should route_to("appointments#destroy", :id => "1")
    end

  end
end


text:
jest.mock('../../../internal/esi-agent');

import { API, makeAPI } from '../../../index';
import { ESIAgent } from '../../../internal/esi-agent';

let api: API = makeAPI();
// Cast to any to get the private agent property
let agent: ESIAgent = (api as any).agent;

function createOrderEntry(typeId, isBuyOrder) {
  return {
    'duration': 90,
    'is_buy_order': isBuyOrder,
    'issued': '2016-09-03T05:12:25Z',
    'location_id': 60005599,
    'min_volume': 1,
    'order_id': 4623824223,
    'price': 9.9,
    'range': 'region',
    'type_id': typeId,
    'volume_remain': 1296000,
    'volume_total': 2000000
  };
}

// Returns 3 buy orders for type 2, 2 sell orders for type 2, plus
// some buy and sell orders for other types
function createOrderResponse() {
  return [
    createOrderEntry(2, true),
    createOrderEntry(2, true),
    createOrderEntry(3, false),
    createOrderEntry(2, true),
    createOrderEntry(2, false),
    createOrderEntry(4, true),
    createOrderEntry(2, false),
  ];
}

afterEach(() => {
  agent.__reset();
});

test('Structure.info', () => {
  agent.__expectRoute('get_universe_structures_structure_id', {
    'structure_id': 2
  }, { token: 'my token' });
  return api.characters(1, 'my token').structures(2).info().then(result => {
    expect(result).toBeDefined();
  });
});

test('Structure.vulnerability', () => {
  let schedule = [{ hour: 0, day: 0 }];
  agent.__expectRoute('get_characters_character_id', { 'character_id': 1 });
  agent.__expectRoute('put_corporations_corporation_id_structures_structure_id',
      {
        'corporation_id': 109299958, 'structure_id': 2, 'new_schedule': schedule
      }, { token: 'my token' });
  return api.characters(1, 'my token').structures(2).vulnerability(schedule)
  .then(result => {
    expect(result).not.toBeDefined();
  });
});

test('Structure.orders', () => {
  agent.__expectRoute('get_markets_structures_structure_id', {
    'structure_id': 2, 'page': 1
  }, { token: 'my token' });
  return api.characters(1, 'my token').structures(2).orders(1).then(result => {
    expect(result).toBeDefined();
  });
});

test('Structure.orders all', () => {
  agent.__expectRoute('get_markets_structures_structure_id', {
    'structure_id': 2, 'page': 1
  }, {
    token: 'my token', returns: createOrderResponse()
  });
  agent.__expectRoute('get_markets_structures_structure_id', {
    'structure_id': 2, 'page': 2
  }, {
    token: 'my token', returns: []
  });
  return api.characters(1, 'my token').structures(2).orders().then(result => {
    expect(result.length).toEqual(7);
  });
});

test('Structure.ordersFor', () => {
  agent.__expectRoute('get_markets_structures_structure_id', {
    'structure_id': 2, 'page': 1
  }, {
    token: 'my token', returns: createOrderResponse()
  });
  agent.__expectRoute('get_markets_structures_structure_id', {
    'structure_id': 2, 'page': 2
  }, {
    token: 'my token', returns: []
  });
  return api.characters(1, 'my token').structures(2).ordersFor(2)
  .then(result => {
    expect(result.length).toEqual(5);
  });
});

test('Structure.buyOrdersFor', () => {
  agent.__expectRoute('get_markets_structures_structure_id', {
    'structure_id': 2, 'page': 1
  }, {
    token: 'my token', returns: createOrderResponse()
  });
  agent.__expectRoute('get_markets_structures_structure_id', {
    'structure_id': 2, 'page': 2
  }, {
    token: 'my token', returns: []
  });
  return api.characters(1, 'my token').structures(2).buyOrdersFor(2)
  .then(result => {
    expect(result.length).toEqual(3);
  });
});

test('Structure.sellOrdersFor', () => {
  agent.__expectRoute('get_markets_structures_structure_id', {
    'structure_id': 2, 'page': 1
  }, {
    token: 'my token', returns: createOrderResponse()
  });
  agent.__expectRoute('get_markets_structures_structure_id', {
    'structure_id': 2, 'page': 2
  }, {
    token: 'my token', returns: []
  });
  return api.characters(1, 'my token').structures(2).sellOrdersFor(2)
  .then(result => {
    expect(result.length).toEqual(2);
  });
});

test('Structures.search', () => {
  agent.__expectRoute('get_characters_character_id_search', {
    'character_id': 1,
    'search': 'search text',
    'categories': ['structure'],
    'strict': false
  }, { token: 'my token' });
  return api.characters(1, 'my token').structures.search('search text')
  .then(result => {
    // Expect the results to be an array
    expect(Array.isArray(result)).toBeTruthy();
  });
});

test('Structures.search.strict', () => {
  agent.__expectRoute('get_characters_character_id_search', {
    'character_id': 1,
    'search': 'search text',
    'categories': ['structure'],
    'strict': true
  }, { token: 'my token' });
  return api.characters(1, 'my token').structures.search.strict('search text')
  .then(result => {
    // Expect the results to be an array
    expect(Array.isArray(result)).toBeTruthy();
  });
});


text:
using System;
using System.Xml.Linq;
using WordBank.Utility.Exceptions;
using WordBank.Utility.Interfaces;

namespace WordBank.Utility
{
    public class XDocumentParser : IXDocumentParser
    {
        public XDocument ParseXDocument(string xml)
        {
            XDocument xDoc;

            try
            {
                xDoc = XDocument.Parse(xml);
            }
            catch (Exception e)
            {
                throw new XmlParseException("failed to parse xml", e);
            }

            return xDoc;
        }
    }
}


text:
class CallScreen < PM::Screen
  include YinsiHelpers
  include BW::KVO

  stylesheet :call

  def on_init # only called once, ever
    set_tab_icon(:phone, "Call")
  end

  def on_load
    layout(self.view, :root) do
      @username = subview(UITextField, :username, delegate: self)
      @call_time = subview(UILabel, :call_time)
      @challenge_text = subview(ChallengeTextView, :challenge_text)
      @call_button = subview(FUIButton, :call_button)
    end

    @call_button.on(:touch) { push_call_button }

    dismiss_keyboard_on_tap
  end

  # Delegate for keyboard go/return button
  def textFieldShouldReturn
    push_call_button
  end

  def call(username)
    User.lookup_sip_address(username) do |sip_address|
      if sip_address.nil?
        # TODO: Remove this puts and maybe think about more error handling
        puts "User not found" # Trust the user already got feedback
      else
        do_call(sip_address)
      end

    end
  end

  def setup_sip_agent
    if @sip_agent
      @sip_agent.reset
    else
      @sip_agent = GSUserAgent.sharedAgent
    end

    account_config = GSAccountConfiguration.defaultConfiguration
    account_config.address = "#{User.current.sip_username}@yinsiapp.com"
    account_config.username = User.current.sip_username
    account_config.password = User.current.sip_password
    account_config.domain = "yinsiapp.com"
    account_config.proxyServer = User.current.sip_proxy
    account_config.enableRingback = true
    account_config.ringbackFilename = "ringtone.wav"

    config = GSConfiguration.defaultConfiguration
    config.account = account_config
    config.logLevel = 3
    config.consoleLogLevel = 3
    config.transportType = GSUDPTransportType

    @sip_agent.configure(config)
    @sip_agent.start

    account = @sip_agent.account
    account.delegate = self
    observe(account, :status) do |old, new|
      case(new)
        when GSAccountStatusOffline
          puts "Account: offline"
        when GSAccountStatusConnecting
          puts "Account: connecting"
        when GSAccountStatusConnected
          puts "Account: Connected!"
        when GSAccountStatusDisconnecting
          puts "Account: Disconnecting..."
        when GSAccountStatusInvalid
          puts "Account: Invalid account info :("
      end
    end
    account.connect
  end

  # Delegate method on incoming calls
  def account(account, didReceiveIncomingCall: call)
    #TODO: Implement something here
    puts "You have an inbound call!"
  end

  ##############################################
  # Private Methods
  ##############################################
  private

  def do_call(address)
    puts "Calling: #{address}"
    @call = GSCall.outgoingCallToUri(address, fromAccount: @sip_agent.account)
    #observe(@call, :status) do |old, new|
    #  puts "Call status changed from #{old} to #{new}."
    #end
    @call.begin
  end

  def push_call_button
    call(@username.text) unless @username.text.empty?
  end
end


text:
"use strict";
var SubscribeOnObservable_1 = require('../observable/SubscribeOnObservable');
/**
 * Asynchronously subscribes Observers to this Observable on the specified Scheduler.
 *
 * <img src="./img/subscribeOn.png" width="100%">
 *
 * @param {Scheduler} the Scheduler to perform subscription actions on.
 * @return {Observable<T>} the source Observable modified so that its subscriptions happen on the specified Scheduler
 .
 * @method subscribeOn
 * @owner Observable
 */
function subscribeOn(scheduler, delay) {
    if (delay === void 0) { delay = 0; }
    return this.lift(new SubscribeOnOperator(scheduler, delay));
}
exports.subscribeOn = subscribeOn;
var SubscribeOnOperator = (function () {
    function SubscribeOnOperator(scheduler, delay) {
        this.scheduler = scheduler;
        this.delay = delay;
    }
    SubscribeOnOperator.prototype.call = function (subscriber, source) {
        return new SubscribeOnObservable_1.SubscribeOnObservable(source, this.delay, this.scheduler).subscribe(subscriber);
    };
    return SubscribeOnOperator;
}());
//# sourceMappingURL=subscribeOn.js.map


text:
<?php

/**
 * User Subscriptions
 *
 * @package bbPress
 * @subpackage Theme
 */

?>

	<?php do_action( 'bbp_template_before_user_subscriptions' ); ?>

	<?php if ( bbp_is_subscriptions_active() ) : ?>

		<?php if ( bbp_is_user_home() || current_user_can( 'edit_users' ) ) : ?>

<?php _e( 'Subscribed Forums', 'bbpress' ); ?>

					<?php if ( bbp_get_user_forum_subscriptions() ) : ?>

						<?php bbp_get_template_part( 'loop', 'forums' ); ?>

					<?php else : ?>

<?php bbp_is_user_home() ? _e( 'You are not currently subscribed to any forums.', 'bbpress' ) : _e( 'This user is not currently subscribed to any forums.', 'bbpress' ); ?>

					<?php endif; ?>

<?php _e( 'Subscribed Topics', 'bbpress' ); ?>

					<?php if ( bbp_get_user_topic_subscriptions() ) : ?>

						<?php bbp_get_template_part( 'pagination', 'topics' ); ?>

						<?php bbp_get_template_part( 'loop',       'topics' ); ?>

						<?php bbp_get_template_part( 'pagination', 'topics' ); ?>

					<?php else : ?>

<?php bbp_is_user_home() ? _e( 'You are not currently subscribed to any topics.', 'bbpress' ) : _e( 'This user is not currently subscribed to any topics.', 'bbpress' ); ?>

					<?php endif; ?>

		<?php endif; ?>

	<?php endif; ?>

	<?php do_action( 'bbp_template_after_user_subscriptions' ); ?>


text:
import dotenv from 'dotenv';
import mongoose from 'mongoose';
dotenv.config({ path: '.env' });
import {app, ioServer} from './app';
import {catSystem} from './logging';
mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true } );
const db = mongoose.connection;
(<any>mongoose).Promise = global.Promise;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
  catSystem.info('Connected to MongoDB');
  ioServer.listen(process.env.WSPORT || 4300, () => {
    console.log('WebSockets are available at port ' + (process.env.WSPORT || 4300));
  });
  app.listen(app.get('port'), () => {
    catSystem.info('Angular Full Stack listening on port ' + app.get('port'));
  });
});


text:
var should = require('should');
var actionheroPrototype = require(__dirname + '/../../actionhero.js').actionheroPrototype;
var actionhero = new actionheroPrototype();
var api;

describe('Core: Exceptions', function(){

  before(function(done){
    actionhero.start(function(err, a){
      api = a;
      done();
    })
  });

  after(function(done){
    actionhero.stop(function(){
      done();
    });
  });

  var uncaughtExceptionHandlers = process.listeners('uncaughtException');
  beforeEach(function(done){
    uncaughtExceptionHandlers.forEach(function(e){
      process.removeListener('uncaughtException', e);
    });
    done();
  })

  afterEach(function(done){
    uncaughtExceptionHandlers.forEach(function(e){
      process.on('uncaughtException', e);
    });
    done();
  });

  it('I can inject a bad task that breaks', function(done){
    api.actions.actions.badAction = {
      '1': {
        name: 'badAction',
        description: 'I will break',
        inputs: { required: [], optional: [] },
        outputExample: {},
        version: 1,
        run: function(api, connection, next){
          thing // undefined
          next(connection, true);
        }
      }
    }
    api.actions.versions.badAction = [1];
    api.actions.actions.badAction.should.be.an.instanceOf(Object);
    done();
  });

  it('the bad action should fail gracefully', function(done){
    /**
     * @nullivex
     * This test in particular is interesting because of the way it expects
     * mocha to handle and rethrow the exception.
     *
     * Implementing grunt and grunt-mocha-test will run this code inside a domain
     * and the action runner also creates a domain so they are nested. In node ~0.8.9
     * this seems to cause the exception to land in mocha's lap rather than being
     * rethrown to the child domain.
     *
     * I believe this works fine in node ~0.9.0 because they ironed out some of the
     * issues especially with nested domains and how exceptions are bubbled in those
     * environments there is an issue about this here: https://github.com/joyent/node/issues/4375
     *
     * So, it is best just to ignore this test in node ~0.8.9 and below and it should
     * still pass in normal environments.
     */
    if(9 < parseInt(process.version.split('.')[1],10)){
      api.specHelper.runAction('badAction', {}, function(response){
        response.error.should.equal('Error: The server experienced an internal error');
        done();
      });
    } else {
      done()
    }
  });

  it('other actions still work', function(done){
    api.specHelper.runAction('randomNumber', {}, function(response){
      should.not.exist(response.error);
      done();
    });
  });

  it('I can remove the bad action', function(done){
    delete api.actions.actions.badAction;
    delete api.actions.versions.badAction;
    should.not.exist(api.actions.actions.badAction);
    done();
  });
});


text:
/* -*- mode:C++; indent-tabs-mode:nil; -*- */
/* MIT License -- MyThOS: The Many-Threads Operating System
 *
 * 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.
 *
 * Copyright 2016 Randolf Rotta, Robert Kuban, and contributors, BTU Cottbus-Senftenberg
 */
#pragma once

#include <cstdint>
#include <cstddef>

namespace mythos {

  struct StackFrame {
    StackFrame* bp;
    void* ret;
  };

  class stack_iterator {
  public:

    typedef StackFrame* reg_t;
    typedef StackFrame value_type;
    typedef value_type& reference_type;

    stack_iterator(reg_t bp) : _bp(bp) {}

    stack_iterator& operator++()
    {
      if (_bp->ret) {
        // no return address: end of stack
        _bp = _bp->bp;
      } else {
        _bp = nullptr;
      }
      return *this;
    }

    stack_iterator operator++(int)
    {
      stack_iterator tmp(*this);
      ++tmp;
      return tmp;
    }

    reference_type operator*()
    {
      return *(_bp);
    }

    bool operator==(const stack_iterator& other) const
    {
      return other._bp == _bp;
    }
    bool operator!=(const stack_iterator& other) const { return !(*this == other); }

  private:
    reg_t _bp;
  };

  class StackTrace {
  public:

    typedef stack_iterator::reg_t reg_t;

    StackTrace() { asm volatile ("mov %%rbp, %0\n\t" : "=r" (_rbp)); }
    StackTrace(reg_t bp) : _rbp(bp) {}
    StackTrace(void* bp) : _rbp(reinterpret_cast<reg_t>(bp)) {}
    StackTrace(uintptr_t bp) : _rbp(reinterpret_cast<reg_t>(bp)) {}

    StackTrace(const StackTrace&) = delete;

    stack_iterator begin() const
    {
      return stack_iterator(_rbp);
    }

    stack_iterator end() const
    {
      return stack_iterator(nullptr);
    }

  private:

    reg_t _rbp;
  };

} // namespace mythos


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<title>Tree dubautia factsheet on ARKive - Dubautia arborea</title>
        <link rel="canonical" href="http://www.arkive.org/tree-dubautia/dubautia-arborea/" />
		<link rel="stylesheet" type="text/css" media="screen,print" href="/rcss/factsheet.css" />
		<link rel="icon" href="/favicon.ico" type="image/x-icon" />
		<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />

Tree dubautia (Dubautia arborea)

Kingdom	Plantae

Phylum	Tracheophyta

Class	Magnoliopsida

Order	Asterales

Family	Compositae

Genus	Dubautia (1)

Classified as Endangered (EN) on the IUCN Red List (1).

Information on the tree dubautia is currently being researched and written and will appear here shortly.

This information is awaiting authentication by a species expert, and will be updated as soon as possible. If you are able to help please contact: arkive@wildscreen.org.uk

IUCN Red List  (May, 2009)
http://www.iucnredlist.org


text:
'use strict';

import { Range } from './Positioning';
import { X12FunctionalGroup } from './X12FunctionalGroup';
import { X12Segment } from './X12Segment';
import { defaultSerializationOptions, X12SerializationOptions } from './X12SerializationOptions';

export class X12Transaction {
    constructor() {
        this.segments = new Array<X12Segment>();
    }

    header: X12Segment;
    trailer: X12Segment;

    segments: X12Segment[];

    toString(options?: X12SerializationOptions): string {
        options = defaultSerializationOptions(options);

        let edi = this.header.toString(options);

        if (options.format) {
            edi += options.endOfLine;
        }

        for (let i = 0; i < this.segments.length; i++) {
            edi += this.segments[i].toString(options);

            if (options.format) {
                edi += options.endOfLine;
            }
        }

        edi += this.trailer.toString(options);

        return edi;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

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

  <parent>
    <groupId>com.jakewharton.timber</groupId>
    <artifactId>timber-parent</artifactId>
    <version>3.0.3-SNAPSHOT</version>
  </parent>

  <artifactId>timber</artifactId>
  <name>Timber</name>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.robolectric</groupId>
      <artifactId>robolectric</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.easytesting</groupId>
      <artifactId>fest-assert-core</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>com.google.android</groupId>
      <artifactId>android</artifactId>
      <scope>provided</scope>
    </dependency>
  </dependencies>
</project>


text:
@yield('bannertitle')

@yield('leader')

@yield('bannerbutton')


text:
using System.IO;
using System.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace Lucene.Net.Codecs
{

    using AtomicReader = Lucene.Net.Index.AtomicReader;
    using BinaryDocValues = Lucene.Net.Index.BinaryDocValues;
    using Bits = Lucene.Net.Util.Bits;
    using BytesRef = Lucene.Net.Util.BytesRef;
    using FieldInfo = Lucene.Net.Index.FieldInfo;
    using FilteredTermsEnum = Lucene.Net.Index.FilteredTermsEnum;
    using LongBitSet = Lucene.Net.Util.LongBitSet;
    using MergeState = Lucene.Net.Index.MergeState;
    using NumericDocValues = Lucene.Net.Index.NumericDocValues;
    using OrdinalMap = Lucene.Net.Index.MultiDocValues.OrdinalMap;
    using SortedDocValues = Lucene.Net.Index.SortedDocValues;
    using SortedSetDocValues = Lucene.Net.Index.SortedSetDocValues;
    using TermsEnum = Lucene.Net.Index.TermsEnum;
    using ArrayUtil = Lucene.Net.Util.ArrayUtil;

    ///
    /// Abstract API that consumes numeric, binary and
    /// sorted docvalues.  Concrete implementations of this
    /// actually do "something" with the docvalues (write it into
    /// the index in a specific format).
    ///

    /// The lifecycle is:
    ///

    ///
DocValuesConsumer is created by
    ///       <seealso cref="DocValuesFormat#fieldsConsumer(SegmentWriteState)"/> or
    ///       <seealso cref="NormsFormat#normsConsumer(SegmentWriteState)"/>.
    ///
<seealso cref="#addNumericField"/>, <seealso cref="#addBinaryField"/>,
    ///       or <seealso cref="#addSortedField"/> are called for each Numeric,
    ///       Binary, or Sorted docvalues field. The API is a "pull" rather
    ///       than "push", and the implementation is free to iterate over the
    ///       values multiple times (<seealso cref="Iterable#iterator()"/>).
    ///
After all fields are added, the consumer is <seealso cref="#close"/>d.
    ///

    ///
    /// @lucene.experimental
    ///
    public abstract class DocValuesConsumer : IDisposable
    {
        ///
        /// Sole constructor. (For invocation by subclass
        ///  constructors, typically implicit.)
        ///
        protected internal DocValuesConsumer()
        {
        }

        ///
        /// Writes numeric docvalues for a field.
        /// <param name="field"> field information </param>
        /// <param name="values"> Iterable of numeric values (one for each document). {@code null} indicates
        ///               a missing value. </param>
        /// <exception cref="IOException"> if an I/O error occurred. </exception>
        public abstract void AddNumericField(FieldInfo field, IEnumerable<long?> values);

        ///
        /// Writes binary docvalues for a field.
        /// <param name="field"> field information </param>
        /// <param name="values"> Iterable of binary values (one for each document). {@code null} indicates
        ///               a missing value. </param>
        /// <exception cref="IOException"> if an I/O error occurred. </exception>
        public abstract void AddBinaryField(FieldInfo field, IEnumerable<BytesRef> values);

        ///
        /// Writes pre-sorted binary docvalues for a field.
        /// <param name="field"> field information </param>
        /// <param name="values"> Iterable of binary values in sorted order (deduplicated). </param>
        /// <param name="docToOrd"> Iterable of ordinals (one for each document). {@code -1} indicates
        ///                 a missing value. </param>
        /// <exception cref="IOException"> if an I/O error occurred. </exception>
        public abstract void AddSortedField(FieldInfo field, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrd);

        ///
        /// Writes pre-sorted set docvalues for a field
        /// <param name="field"> field information </param>
        /// <param name="values"> Iterable of binary values in sorted order (deduplicated). </param>
        /// <param name="docToOrdCount"> Iterable of the number of values for each document. A zero ordinal
        ///                      count indicates a missing value. </param>
        /// <param name="ords"> Iterable of ordinal occurrences (docToOrdCount*maxDoc total). </param>
        /// <exception cref="IOException"> if an I/O error occurred. </exception>
        public abstract void AddSortedSetField(FieldInfo field, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrdCount, IEnumerable<long?> ords);

        ///
        /// Merges the numeric docvalues from toMerge.
        ///

        /// The default implementation calls <seealso cref="#addNumericField"/>, passing
        /// an Iterable that merges and filters deleted documents on the fly.

        ///
        public virtual void MergeNumericField(FieldInfo fieldInfo, MergeState mergeState, IList<NumericDocValues> toMerge, IList<Bits> docsWithField)
        {
            AddNumericField(fieldInfo, GetMergeNumericFieldEnumerable(fieldInfo, mergeState, toMerge, docsWithField));
        }

        private IEnumerable<long?> GetMergeNumericFieldEnumerable(FieldInfo fieldinfo, MergeState mergeState, IList<NumericDocValues> toMerge, IList<Bits> docsWithField)
        {
            int readerUpto = -1;
            int docIDUpto = 0;
            AtomicReader currentReader = null;
            NumericDocValues currentValues = null;
            Bits currentLiveDocs = null;
            Bits currentDocsWithField = null;

            while (true)
            {
                if (readerUpto == toMerge.Count)
                {
                    yield break;
                }

                if (currentReader == null || docIDUpto == currentReader.MaxDoc)
                {
                    readerUpto++;
                    if (readerUpto < toMerge.Count)
                    {
                        currentReader = mergeState.Readers[readerUpto];
                        currentValues = toMerge[readerUpto];
                        currentDocsWithField = docsWithField[readerUpto];
                        currentLiveDocs = currentReader.LiveDocs;
                    }
                    docIDUpto = 0;
                    continue;
                }

                if (currentLiveDocs == null || currentLiveDocs.Get(docIDUpto))
                {
                    long? nextValue;
                    if (currentDocsWithField.Get(docIDUpto))
                    {
                        nextValue = currentValues.Get(docIDUpto);
                    }
                    else
                    {
                        nextValue = null;
                    }

                    docIDUpto++;
                    yield return nextValue;
                    continue;
                }

                docIDUpto++;
            }
        }

        ///
        /// Merges the binary docvalues from toMerge.
        ///

        /// The default implementation calls <seealso cref="#addBinaryField"/>, passing
        /// an Iterable that merges and filters deleted documents on the fly.
        ///
        public void MergeBinaryField(FieldInfo fieldInfo, MergeState mergeState, IList<BinaryDocValues> toMerge, IList<Bits> docsWithField)
        {
            AddBinaryField(fieldInfo, GetMergeBinaryFieldEnumerable(fieldInfo, mergeState, toMerge, docsWithField));
        }

        private IEnumerable<BytesRef> GetMergeBinaryFieldEnumerable(FieldInfo fieldInfo, MergeState mergeState, IList<BinaryDocValues> toMerge, IList<Bits> docsWithField)
        {
            int readerUpto = -1;
            int docIDUpto = 0;
            AtomicReader currentReader = null;
            BinaryDocValues currentValues = null;
            Bits currentLiveDocs = null;
            Bits currentDocsWithField = null;

            while (true)
            {
                if (readerUpto == toMerge.Count)
                {
                    yield break;
                }

                if (currentReader == null || docIDUpto == currentReader.MaxDoc)
                {
                    readerUpto++;
                    if (readerUpto < toMerge.Count)
                    {
                        currentReader = mergeState.Readers[readerUpto];
                        currentValues = toMerge[readerUpto];
                        currentDocsWithField = docsWithField[readerUpto];
                        currentLiveDocs = currentReader.LiveDocs;
                    }
                    docIDUpto = 0;
                    continue;
                }

                if (currentLiveDocs == null || currentLiveDocs.Get(docIDUpto))
                {
                    var nextValue = new BytesRef();

                    if (currentDocsWithField.Get(docIDUpto))
                    {
                        currentValues.Get(docIDUpto, nextValue);
                    }
                    else
                    {
                        nextValue = null;
                    }

                    docIDUpto++;
                    yield return nextValue;
                    continue;
                }

                docIDUpto++;
            }
        }

        ///
        /// Merges the sorted docvalues from toMerge.
        ///

        /// The default implementation calls <seealso cref="#addSortedField"/>, passing
        /// an Iterable that merges ordinals and values and filters deleted documents.

        ///
        public virtual void MergeSortedField(FieldInfo fieldInfo, MergeState mergeState, IList<SortedDocValues> toMerge)
        {
            AtomicReader[] readers = mergeState.Readers.ToArray();
            SortedDocValues[] dvs = toMerge.ToArray();

            // step 1: iterate thru each sub and mark terms still in use
            var liveTerms = new TermsEnum[dvs.Length];
            for (int sub = 0; sub < liveTerms.Length; sub++)
            {
                AtomicReader reader = readers[sub];
                SortedDocValues dv = dvs[sub];
                Bits liveDocs = reader.LiveDocs;
                if (liveDocs == null)
                {
                    liveTerms[sub] = dv.TermsEnum();
                }
                else
                {
                    var bitset = new LongBitSet(dv.ValueCount);
                    for (int i = 0; i < reader.MaxDoc; i++)
                    {
                        if (liveDocs.Get(i))
                        {
                            int ord = dv.GetOrd(i);
                            if (ord >= 0)
                            {
                                bitset.Set(ord);
                            }
                        }
                    }
                    liveTerms[sub] = new BitsFilteredTermsEnum(dv.TermsEnum(), bitset);
                }
            }

            // step 2: create ordinal map (this conceptually does the "merging")
            var map = new OrdinalMap(this, liveTerms);

            // step 3: add field
            AddSortedField(fieldInfo, GetMergeSortValuesEnumerable(map, dvs),
                // doc -> ord
                GetMergeSortedFieldDocToOrdEnumerable(readers, dvs, map)
           );
        }

        private IEnumerable<BytesRef> GetMergeSortValuesEnumerable(OrdinalMap map, SortedDocValues[] dvs)
        {
            int currentOrd = 0;

            while (currentOrd < map.ValueCount)
            {
                var scratch = new BytesRef();
                int segmentNumber = map.GetFirstSegmentNumber(currentOrd);
                var segmentOrd = (int)map.GetFirstSegmentOrd(currentOrd);
                dvs[segmentNumber].LookupOrd(segmentOrd, scratch);
                currentOrd++;
                yield return scratch;
            }
        }

        private IEnumerable<long?> GetMergeSortedFieldDocToOrdEnumerable(AtomicReader[] readers, SortedDocValues[] dvs, OrdinalMap map)
        {
            int readerUpTo = -1;
            int docIDUpTo = 0;
            AtomicReader currentReader = null;
            Bits currentLiveDocs = null;

            while (true)
            {
                if (readerUpTo == readers.Length)
                {
                    yield break;
                }

                if (currentReader == null || docIDUpTo == currentReader.MaxDoc)
                {
                    readerUpTo++;
                    if (readerUpTo < readers.Length)
                    {
                        currentReader = readers[readerUpTo];
                        currentLiveDocs = currentReader.LiveDocs;
                    }
                    docIDUpTo = 0;
                    continue;
                }

                if (currentLiveDocs == null || currentLiveDocs.Get(docIDUpTo))
                {
                    int segOrd = dvs[readerUpTo].GetOrd(docIDUpTo);
                    docIDUpTo++;
                    yield return segOrd == -1 ? -1 : map.GetGlobalOrd(readerUpTo, segOrd);
                    continue;
                }

                docIDUpTo++;
            }
        }

        /*
        private class IterableAnonymousInnerClassHelper3 : IEnumerable<BytesRef>
        {
            private readonly DocValuesConsumer OuterInstance;

            private SortedDocValues[] Dvs;
            private OrdinalMap Map;

            public IterableAnonymousInnerClassHelper3(DocValuesConsumer outerInstance, SortedDocValues[] dvs, OrdinalMap map)
            {
                this.OuterInstance = outerInstance;
                this.Dvs = dvs;
                this.Map = map;
            }

                // ord -> value
            public virtual IEnumerator<BytesRef> GetEnumerator()
            {
              return new IteratorAnonymousInnerClassHelper3(this);
            }

            private class IteratorAnonymousInnerClassHelper3 : IEnumerator<BytesRef>
            {
                private readonly IterableAnonymousInnerClassHelper3 OuterInstance;

                public IteratorAnonymousInnerClassHelper3(IterableAnonymousInnerClassHelper3 outerInstance)
                {
                    this.OuterInstance = outerInstance;
                    scratch = new BytesRef();
                }

                internal readonly BytesRef scratch;
                internal int currentOrd;

                public virtual bool HasNext()
                {
                  return currentOrd < OuterInstance.Map.ValueCount;
                }

                public virtual BytesRef Next()
                {
                  if (!HasNext())
                  {
                    throw new Exception();
                  }
                  int segmentNumber = OuterInstance.Map.GetFirstSegmentNumber(currentOrd);
                  int segmentOrd = (int)OuterInstance.Map.GetFirstSegmentOrd(currentOrd);
                  OuterInstance.Dvs[segmentNumber].LookupOrd(segmentOrd, scratch);
                  currentOrd++;
                  return scratch;
                }

                public virtual void Remove()
                {
                  throw new System.NotSupportedException();
                }
            }
        }

        private class IterableAnonymousInnerClassHelper4 : IEnumerable<Number>
        {
            private readonly DocValuesConsumer OuterInstance;

            private AtomicReader[] Readers;
            private SortedDocValues[] Dvs;
            private OrdinalMap Map;

            public IterableAnonymousInnerClassHelper4(DocValuesConsumer outerInstance, AtomicReader[] readers, SortedDocValues[] dvs, OrdinalMap map)
            {
                this.OuterInstance = outerInstance;
                this.Readers = readers;
                this.Dvs = dvs;
                this.Map = map;
            }

            public virtual IEnumerator<Number> GetEnumerator()
            {
              return new IteratorAnonymousInnerClassHelper4(this);
            }

            private class IteratorAnonymousInnerClassHelper4 : IEnumerator<Number>
            {
                private readonly IterableAnonymousInnerClassHelper4 OuterInstance;

                public IteratorAnonymousInnerClassHelper4(IterableAnonymousInnerClassHelper4 outerInstance)
                {
                    this.OuterInstance = outerInstance;
                    readerUpto = -1;
                }

                internal int readerUpto;
                internal int docIDUpto;
                internal int nextValue;
                internal AtomicReader currentReader;
                internal Bits currentLiveDocs;
                internal bool nextIsSet;

                public virtual bool HasNext()
                {
                  return nextIsSet || SetNext();
                }

                public virtual void Remove()
                {
                  throw new System.NotSupportedException();
                }

                public virtual Number Next()
                {
                  if (!HasNext())
                  {
                    throw new NoSuchElementException();
                  }
                  Debug.Assert(nextIsSet);
                  nextIsSet = false;
                  // TODO make a mutable number
                  return nextValue;
                }

                private bool SetNext()
                {
                  while (true)
                  {
                    if (readerUpto == OuterInstance.Readers.Length)
                    {
                      return false;
                    }

                    if (currentReader == null || docIDUpto == currentReader.MaxDoc)
                    {
                      readerUpto++;
                      if (readerUpto < OuterInstance.Readers.Length)
                      {
                        currentReader = OuterInstance.Readers[readerUpto];
                        currentLiveDocs = currentReader.LiveDocs;
                      }
                      docIDUpto = 0;
                      continue;
                    }

                    if (currentLiveDocs == null || currentLiveDocs.get(docIDUpto))
                    {
                      nextIsSet = true;
                      int segOrd = OuterInstance.Dvs[readerUpto].GetOrd(docIDUpto);
                      nextValue = segOrd == -1 ? - 1 : (int) OuterInstance.Map.GetGlobalOrd(readerUpto, segOrd);
                      docIDUpto++;
                      return true;
                    }

                    docIDUpto++;
                  }
                }
            }
        }*/

        ///
        /// Merges the sortedset docvalues from toMerge.
        ///

        /// The default implementation calls <seealso cref="#addSortedSetField"/>, passing
        /// an Iterable that merges ordinals and values and filters deleted documents .
        ///
        public virtual void MergeSortedSetField(FieldInfo fieldInfo, MergeState mergeState, IList<SortedSetDocValues> toMerge)
        {
            var readers = mergeState.Readers.ToArray();
            var dvs = toMerge.ToArray();

            // step 1: iterate thru each sub and mark terms still in use
            var liveTerms = new TermsEnum[dvs.Length];
            for (int sub = 0; sub < liveTerms.Length; sub++)
            {
                var reader = readers[sub];
                var dv = dvs[sub];
                var liveDocs = reader.LiveDocs;
                if (liveDocs == null)
                {
                    liveTerms[sub] = dv.TermsEnum();
                }
                else
                {
                    var bitset = new LongBitSet(dv.ValueCount);
                    for (int i = 0; i < reader.MaxDoc; i++)
                    {
                        if (liveDocs.Get(i))
                        {
                            dv.Document = i;
                            long ord;
                            while ((ord = dv.NextOrd()) != SortedSetDocValues.NO_MORE_ORDS)
                            {
                                bitset.Set(ord);
                            }
                        }
                    }
                    liveTerms[sub] = new BitsFilteredTermsEnum(dv.TermsEnum(), bitset);
                }
            }

            // step 2: create ordinal map (this conceptually does the "merging")
            var map = new OrdinalMap(this, liveTerms);

            // step 3: add field
            AddSortedSetField(fieldInfo, GetMergeSortedSetValuesEnumerable(map, dvs),
                // doc -> ord count
                GetMergeSortedSetDocToOrdCountEnumerable(readers, dvs),
                // ords
                GetMergeSortedSetOrdsEnumerable(readers, dvs, map)
            );
        }

        private IEnumerable<BytesRef> GetMergeSortedSetValuesEnumerable(OrdinalMap map, SortedSetDocValues[] dvs)
        {
            long currentOrd = 0;

            while (currentOrd < map.ValueCount)
            {
                int segmentNumber = map.GetFirstSegmentNumber(currentOrd);
                long segmentOrd = map.GetFirstSegmentOrd(currentOrd);
                var scratch = new BytesRef();
                dvs[segmentNumber].LookupOrd(segmentOrd, scratch);
                currentOrd++;
                yield return scratch;
            }
        }

        private IEnumerable<long?> GetMergeSortedSetDocToOrdCountEnumerable(AtomicReader[] readers, SortedSetDocValues[] dvs)
        {
            int readerUpto = -1;
            int docIDUpto = 0;
            AtomicReader currentReader = null;
            Bits currentLiveDocs = null;

            while (true)
            {
                if (readerUpto == readers.Length)
                {
                    yield break;
                }

                if (currentReader == null || docIDUpto == currentReader.MaxDoc)
                {
                    readerUpto++;
                    if (readerUpto < readers.Length)
                    {
                        currentReader = readers[readerUpto];
                        currentLiveDocs = currentReader.LiveDocs;
                    }
                    docIDUpto = 0;
                    continue;
                }

                if (currentLiveDocs == null || currentLiveDocs.Get(docIDUpto))
                {
                    SortedSetDocValues dv = dvs[readerUpto];
                    dv.Document = docIDUpto;
                    long value = 0;
                    while (dv.NextOrd() != SortedSetDocValues.NO_MORE_ORDS)
                    {
                        value++;
                    }
                    docIDUpto++;
                    yield return value;
                    continue;
                }

                docIDUpto++;
            }
        }

        private IEnumerable<long?> GetMergeSortedSetOrdsEnumerable(AtomicReader[] readers, SortedSetDocValues[] dvs, OrdinalMap map)
        {
            int readerUpto = -1;
            int docIDUpto = 0;
            AtomicReader currentReader = null;
            Bits currentLiveDocs = null;
            var ords = new long[8];
            int ordUpto = 0;
            int ordLength = 0;

            while (true)
            {
                if (readerUpto == readers.Length)
                {
                    yield break;
                }

                if (ordUpto < ordLength)
                {
                    var value = ords[ordUpto];
                    ordUpto++;
                    yield return value;
                    continue;
                }

                if (currentReader == null || docIDUpto == currentReader.MaxDoc)
                {
                    readerUpto++;
                    if (readerUpto < readers.Length)
                    {
                        currentReader = readers[readerUpto];
                        currentLiveDocs = currentReader.LiveDocs;
                    }
                    docIDUpto = 0;
                    continue;
                }

                if (currentLiveDocs == null || currentLiveDocs.Get(docIDUpto))
                {
                    Debug.Assert(docIDUpto < currentReader.MaxDoc);
                    SortedSetDocValues dv = dvs[readerUpto];
                    dv.Document = docIDUpto;
                    ordUpto = ordLength = 0;
                    long ord;
                    while ((ord = dv.NextOrd()) != SortedSetDocValues.NO_MORE_ORDS)
                    {
                        if (ordLength == ords.Length)
                        {
                            ords = ArrayUtil.Grow(ords, ordLength + 1);
                        }
                        ords[ordLength] = map.GetGlobalOrd(readerUpto, ord);
                        ordLength++;
                    }
                    docIDUpto++;
                    continue;
                }

                docIDUpto++;
            }
        }

        /*
        private class IterableAnonymousInnerClassHelper5 : IEnumerable<BytesRef>
        {
            private readonly DocValuesConsumer OuterInstance;

            private SortedSetDocValues[] Dvs;
            private OrdinalMap Map;

            public IterableAnonymousInnerClassHelper5(DocValuesConsumer outerInstance, SortedSetDocValues[] dvs, OrdinalMap map)
            {
                this.OuterInstance = outerInstance;
                this.Dvs = dvs;
                this.Map = map;
            }

                // ord -> value
            public virtual IEnumerator<BytesRef> GetEnumerator()
            {
              return new IteratorAnonymousInnerClassHelper5(this);
            }

            private class IteratorAnonymousInnerClassHelper5 : IEnumerator<BytesRef>
            {
                private readonly IterableAnonymousInnerClassHelper5 OuterInstance;

                public IteratorAnonymousInnerClassHelper5(IterableAnonymousInnerClassHelper5 outerInstance)
                {
                    this.OuterInstance = outerInstance;
                    scratch = new BytesRef();
                }

                internal readonly BytesRef scratch;
                internal long currentOrd;

                public virtual bool HasNext()
                {
                  return currentOrd < OuterInstance.Map.ValueCount;
                }

                public virtual BytesRef Next()
                {
                  if (!HasNext())
                  {
                    throw new Exception();
                  }
                  int segmentNumber = OuterInstance.Map.GetFirstSegmentNumber(currentOrd);
                  long segmentOrd = OuterInstance.Map.GetFirstSegmentOrd(currentOrd);
                  OuterInstance.Dvs[segmentNumber].LookupOrd(segmentOrd, scratch);
                  currentOrd++;
                  return scratch;
                }

                public virtual void Remove()
                {
                  throw new System.NotSupportedException();
                }
            }
        }

        private class IterableAnonymousInnerClassHelper6 : IEnumerable<Number>
        {
            private readonly DocValuesConsumer OuterInstance;

            private AtomicReader[] Readers;
            private SortedSetDocValues[] Dvs;

            public IterableAnonymousInnerClassHelper6(DocValuesConsumer outerInstance, AtomicReader[] readers, SortedSetDocValues[] dvs)
            {
                this.OuterInstance = outerInstance;
                this.Readers = readers;
                this.Dvs = dvs;
            }

            public virtual IEnumerator<Number> GetEnumerator()
            {
              return new IteratorAnonymousInnerClassHelper6(this);
            }

            private class IteratorAnonymousInnerClassHelper6 : IEnumerator<Number>
            {
                private readonly IterableAnonymousInnerClassHelper6 OuterInstance;

                public IteratorAnonymousInnerClassHelper6(IterableAnonymousInnerClassHelper6 outerInstance)
                {
                    this.OuterInstance = outerInstance;
                    readerUpto = -1;
                }

                internal int readerUpto;
                internal int docIDUpto;
                internal int nextValue;
                internal AtomicReader currentReader;
                internal Bits currentLiveDocs;
                internal bool nextIsSet;

                public virtual bool HasNext()
                {
                  return nextIsSet || SetNext();
                }

                public virtual void Remove()
                {
                  throw new System.NotSupportedException();
                }

                public virtual Number Next()
                {
                  if (!HasNext())
                  {
                    throw new Exception();
                  }
                  Debug.Assert(nextIsSet);
                  nextIsSet = false;
                  // TODO make a mutable number
                  return nextValue;
                }

                private bool SetNext()
                {
                  while (true)
                  {
                    if (readerUpto == OuterInstance.Readers.Length)
                    {
                      return false;
                    }

                    if (currentReader == null || docIDUpto == currentReader.MaxDoc)
                    {
                      readerUpto++;
                      if (readerUpto < OuterInstance.Readers.Length)
                      {
                        currentReader = OuterInstance.Readers[readerUpto];
                        currentLiveDocs = currentReader.LiveDocs;
                      }
                      docIDUpto = 0;
                      continue;
                    }

                    if (currentLiveDocs == null || currentLiveDocs.Get(docIDUpto))
                    {
                      nextIsSet = true;
                      SortedSetDocValues dv = OuterInstance.Dvs[readerUpto];
                      dv.Document = docIDUpto;
                      nextValue = 0;
                      while (dv.NextOrd() != SortedSetDocValues.NO_MORE_ORDS)
                      {
                        nextValue++;
                      }
                      docIDUpto++;
                      return true;
                    }

                    docIDUpto++;
                  }
                }
            }
        }

        private class IterableAnonymousInnerClassHelper7 : IEnumerable<Number>
        {
            private readonly DocValuesConsumer OuterInstance;

            private AtomicReader[] Readers;
            private SortedSetDocValues[] Dvs;
            private OrdinalMap Map;

            public IterableAnonymousInnerClassHelper7(DocValuesConsumer outerInstance, AtomicReader[] readers, SortedSetDocValues[] dvs, OrdinalMap map)
            {
                this.OuterInstance = outerInstance;
                this.Readers = readers;
                this.Dvs = dvs;
                this.Map = map;
            }

            public virtual IEnumerator<Number> GetEnumerator()
            {
              return new IteratorAnonymousInnerClassHelper7(this);
            }

            private class IteratorAnonymousInnerClassHelper7 : IEnumerator<Number>
            {
                private readonly IterableAnonymousInnerClassHelper7 OuterInstance;

                public IteratorAnonymousInnerClassHelper7(IterableAnonymousInnerClassHelper7 outerInstance)
                {
                    this.OuterInstance = outerInstance;
                    readerUpto = -1;
                    ords = new long[8];
                }

                internal int readerUpto;
                internal int docIDUpto;
                internal long nextValue;
                internal AtomicReader currentReader;
                internal Bits currentLiveDocs;
                internal bool nextIsSet;
                internal long[] ords;
                internal int ordUpto;
                internal int ordLength;

                public virtual bool HasNext()
                {
                  return nextIsSet || SetNext();
                }

                public virtual void Remove()
                {
                  throw new System.NotSupportedException();
                }

                public virtual Number Next()
                {
                  if (!HasNext())
                  {
                    throw new Exception();
                  }
                  Debug.Assert(nextIsSet);
                  nextIsSet = false;
                  // TODO make a mutable number
                  return nextValue;
                }

                private bool SetNext()
                {
                  while (true)
                  {
                    if (readerUpto == OuterInstance.Readers.Length)
                    {
                      return false;
                    }

                    if (ordUpto < ordLength)
                    {
                      nextValue = ords[ordUpto];
                      ordUpto++;
                      nextIsSet = true;
                      return true;
                    }

                    if (currentReader == null || docIDUpto == currentReader.MaxDoc)
                    {
                      readerUpto++;
                      if (readerUpto < OuterInstance.Readers.Length)
                      {
                        currentReader = OuterInstance.Readers[readerUpto];
                        currentLiveDocs = currentReader.LiveDocs;
                      }
                      docIDUpto = 0;
                      continue;
                    }

                    if (currentLiveDocs == null || currentLiveDocs.Get(docIDUpto))
                    {
                      Debug.Assert(docIDUpto < currentReader.MaxDoc);
                      SortedSetDocValues dv = OuterInstance.Dvs[readerUpto];
                      dv.Document = docIDUpto;
                      ordUpto = ordLength = 0;
                      long ord;
                      while ((ord = dv.NextOrd()) != SortedSetDocValues.NO_MORE_ORDS)
                      {
                        if (ordLength == ords.Length)
                        {
                          ords = ArrayUtil.Grow(ords, ordLength + 1);
                        }
                        ords[ordLength] = OuterInstance.Map.GetGlobalOrd(readerUpto, ord);
                        ordLength++;
                      }
                      docIDUpto++;
                      continue;
                    }

                    docIDUpto++;
                  }
                }
            }
        }*/

        // TODO: seek-by-ord to nextSetBit
        internal class BitsFilteredTermsEnum : FilteredTermsEnum
        {
            internal readonly LongBitSet LiveTerms;

            internal BitsFilteredTermsEnum(TermsEnum @in, LongBitSet liveTerms)
                : base(@in, false)
            {
                Debug.Assert(liveTerms != null);
                LiveTerms = liveTerms;
            }

            protected internal override AcceptStatus Accept(BytesRef term)
            {
                return LiveTerms.Get(Ord()) ? AcceptStatus.YES : AcceptStatus.NO;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected abstract void Dispose(bool disposing);
    }
}


text:
package org.ojai.tests.types;

import static org.junit.Assert.assertEquals;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.junit.Test;
import org.ojai.tests.BaseTest;
import org.ojai.types.ODate;

public class TestDate extends BaseTest {

  private final DateFormat ISO_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

  @Test
  public void testDateParsed() throws ParseException {
    ODate date = ODate.parse("1970-1-2");
    assertEquals(1970, date.getYear());
    assertEquals(1, date.getMonth());
    assertEquals(2, date.getDayOfMonth());
    assertEquals(1, date.toDaysSinceEpoch());
    assertEquals(ISO_DATE_FORMAT.parse("1970-1-2"), date.toDate());

    date = ODate.parse("1970-1-1");
    assertEquals(1970, date.getYear());
    assertEquals(1, date.getMonth());
    assertEquals(1, date.getDayOfMonth());
    assertEquals(0, date.toDaysSinceEpoch());
    assertEquals(ISO_DATE_FORMAT.parse("1970-1-1"), date.toDate());

    date = ODate.parse("1969-12-31");
    assertEquals(1969, date.getYear());
    assertEquals(12, date.getMonth());
    assertEquals(31, date.getDayOfMonth());
    assertEquals(-1, date.toDaysSinceEpoch());
    assertEquals(ISO_DATE_FORMAT.parse("1969-12-31"), date.toDate());

    date = ODate.parse("2015-12-31");
    assertEquals(2015, date.getYear());
    assertEquals(12, date.getMonth());
    assertEquals(31, date.getDayOfMonth());
    assertEquals(16800, date.toDaysSinceEpoch());
    assertEquals(ISO_DATE_FORMAT.parse("2015-12-31"), date.toDate());
  }

  @Test
  // must set "-Duser.timezone=GMT-07" to pass
  public void testDateFromEpochMillis() throws ParseException {
    long epoch = 1451538715641L; // "2015-12-31" in GMT, "2015-12-30" in GMT-07
    ODate date = new ODate(epoch);
    assertEquals(2015, date.getYear());
    assertEquals(12, date.getMonth());
    assertEquals(30, date.getDayOfMonth());
    assertEquals(16799, date.toDaysSinceEpoch());
    assertEquals(ISO_DATE_FORMAT.parse("2015-12-30"), date.toDate());

    Date jdate = new Date(epoch);
    date = new ODate(jdate);
    assertEquals(2015, date.getYear());
    assertEquals(12, date.getMonth());
    assertEquals(30, date.getDayOfMonth());
    assertEquals(16799, date.toDaysSinceEpoch());
    assertEquals(ISO_DATE_FORMAT.parse("2015-12-30"), date.toDate());

    epoch = 0L; // 1970-01-01 hrs in GMT is 1969-12-31 hrs in GMT-07
    date = new ODate(epoch);
    assertEquals(1969, date.getYear());
    assertEquals(12, date.getMonth());
    assertEquals(31, date.getDayOfMonth());
    assertEquals(-1, date.toDaysSinceEpoch());
    assertEquals(ISO_DATE_FORMAT.parse("1969-12-31"), date.toDate());
  }

  @Test
  @SuppressWarnings("deprecation")
  public void testDateFromJavaUtilDate() throws ParseException {
    Date utilDate = ISO_DATE_FORMAT.parse("2015-12-31");
    ODate date = new ODate(utilDate);
    assertEquals(2015, date.getYear());
    assertEquals(12, date.getMonth());
    assertEquals(31, date.getDayOfMonth());
    assertEquals(16800, date.toDaysSinceEpoch());
    assertEquals(utilDate, date.toDate());

    utilDate = new Date(2015-1900, 12-1, 31);
    date = new ODate(utilDate);
    assertEquals(2015, date.getYear());
    assertEquals(12, date.getMonth());
    assertEquals(31, date.getDayOfMonth());
    assertEquals(16800, date.toDaysSinceEpoch());
    assertEquals(utilDate, date.toDate());
  }

  @Test
  public void testDateFromFields() throws ParseException {
    ODate date = new ODate(2015, 12, 31);
    assertEquals(2015, date.getYear());
    assertEquals(12, date.getMonth());
    assertEquals(31, date.getDayOfMonth());
    assertEquals(16800, date.toDaysSinceEpoch());
    assertEquals(ISO_DATE_FORMAT.parse("2015-12-31"), date.toDate());
  }

}


text:
<?php
namespace Concrete\Core\Workflow;

use Concrete\Core\Permission\AssignableObjectInterface;
use Concrete\Core\Permission\AssignableObjectTrait;
use Concrete\Core\Permission\Key\Key;
use Concrete\Core\Workflow\HistoryEntry\BasicHistoryEntry as BasicWorkflowHistoryEntry;
use Concrete\Core\Workflow\Progress\Action\ApprovalAction as WorkflowProgressApprovalAction;
use Concrete\Core\Workflow\Progress\Action\CancelAction as WorkflowProgressCancelAction;
use Concrete\Core\Workflow\Progress\BasicData as BasicWorkflowProgressData;
use Concrete\Core\Workflow\Progress\Progress as WorkflowProgress;
use Core;
use Concrete\Core\Permission\Access\Access as PermissionAccess;
use PermissionKey;
use User;
use UserInfo;

class BasicWorkflow extends \Concrete\Core\Workflow\Workflow implements AssignableObjectInterface
{
    use AssignableObjectTrait;

    public function executeBeforePermissionAssignment($cascadeToChildren = true)
    {
        return;
    }

    public function setChildPermissionsToOverride()
    {
        return false;
    }

    public function setPermissionsToOverride()
    {
        return false;
    }

    public function getPermissionAssignmentClassName()
    {
        return '\\Concrete\\Core\\Permission\\Assignment\\BasicWorkflowAssignment';
    }

    public function updateDetails($post)
    {
        $permissions = PermissionKey::getList('basic_workflow');
        foreach ($permissions as $pk) {
            $pk->setPermissionObject($this);
            $pt = $pk->getPermissionAssignmentObject();
            $paID = $post['pkID'][$pk->getPermissionKeyID()];
            $pt->clearPermissionAssignment();
            if ($paID > 0) {
                $pa = PermissionAccess::getByID($paID, $pk);
                if (is_object($pa)) {
                    $pt->assignPermissionAccess($pa);
                }
            }
        }
    }

    public function getWorkflowProgressApprovalUsers(WorkflowProgress $wp)
    {
        $pk = Key::getByHandle('approve_basic_workflow_action');
        $pk->setPermissionObject($this);
        $access = $pk->getPermissionAssignmentObject()->getPermissionAccessObject();
        $users = [\UserInfo::getByID(USER_SUPER_ID)];
        $usersToRemove = [];

        if (is_object($access)) {
            // Loop through all items and get the relevant users.
            $items = $access->getAccessListItems(Key::ACCESS_TYPE_INCLUDE);
            foreach ($items as $item) {
                $entity = $item->getAccessEntityObject();
                $users = array_merge($entity->getAccessEntityUsers($access), $users);
            }

            // Now we loop through the array and remove
            $items = $access->getAccessListItems(Key::ACCESS_TYPE_EXCLUDE);
            foreach ($items as $item) {
                $entity = $item->getAccessEntityObject();
                foreach ($entity->getAccessEntityUsers($access) as $user) {
                    $usersToRemove[] = $user->getUserID();
                }
            }

            $users = array_unique($users);
            $usersToRemove = array_unique($usersToRemove);

            $users = array_filter($users, function ($element) use ($usersToRemove) {
                if (in_array($element->getUserID(), $usersToRemove)) {
                    return false;
                }

                return true;
            });
        }

        return $users;
    }

    /**
     * Returns true if the logged-in user can approve the current workflow.
     */
    public function canApproveWorkflow()
    {
        $pk = Key::getByHandle('approve_basic_workflow_action');
        $pk->setPermissionObject($this);

        return $pk->validate();
    }

    public function loadDetails()
    {
    }

    public function delete()
    {
        $db = Core::make('database')->connection();
        $db->executeQuery('DELETE FROM BasicWorkflowPermissionAssignments WHERE wfID = ?', [$this->wfID]);
        parent::delete();
    }

    public function start(WorkflowProgress $wp)
    {
        // lets save the basic data associated with this workflow.
        $req = $wp->getWorkflowRequestObject();

        // Check if the workflow is not already approved
        if (is_object($req)) {
            if ($this->canApproveWorkflow()) {
                // Then that means we have the ability to approve the workflow we just started.
                // In that case, we transparently approve it, and skip the entry notification step.
                $wpr = $req->approve($wp);
                $wp->delete();

                return $wpr;
            } else {
                $db = Core::make('database')->connection();
                $db->executeQuery(
                    'INSERT INTO BasicWorkflowProgressData (wpID, uIDStarted) VALUES (?, ?)',
                    [$wp->getWorkflowProgressID(), $req->getRequesterUserID()]);

                $ui = UserInfo::getByID($req->getRequesterUserID());

                // let's get all the people who are set to be notified on entry
                $message = t(
                    'On %s, user %s submitted the following request: %s',
                    Core::make('helper/date')->formatDateTime($wp->getWorkflowProgressDateAdded(), true),
                    $ui->getUserName(),
                    $req->getWorkflowRequestDescriptionObject()->getEmailDescription());
                $this->notify($wp, $message, 'notify_on_basic_workflow_entry');
            }
        }
    }

    protected function notify(
        WorkflowProgress $wp,
        $message,
        $permission = 'notify_on_basic_workflow_entry',
        $parameters = []
    ) {
        $nk = PermissionKey::getByHandle($permission);
        $nk->setPermissionObject($this);
        $users = $nk->getCurrentlyActiveUsers($wp);

        foreach ($users as $ui) {
            $mh = Core::make('helper/mail');
            $mh->addParameter('uName', $ui->getUserName());
            $mh->to($ui->getUserEmail());
            $adminUser = UserInfo::getByID(USER_SUPER_ID);
            $mh->from($adminUser->getUserEmail(), t('Basic Workflow'));
            $mh->addParameter('message', $message);
            foreach ($parameters as $key => $value) {
                $mh->addParameter($key, $value);
            }
            $mh->addParameter('siteName', \Core::make('site')->getSite()->getSiteName());
            $mh->load('basic_workflow_notification');
            $mh->sendMail();
            unset($mh);
        }
    }

    public function getWorkflowProgressCurrentDescription(WorkflowProgress $wp)
    {
        $bdw = new BasicWorkflowProgressData($wp);
        $ux = UserInfo::getByID($bdw->getUserStartedID());
        if (is_object($ux)) {
            $userName = $ux->getUserName();
        } else {
            $userName = t('(Deleted User)');
        }
        $req = $wp->getWorkflowRequestObject();
        $description = $req->getWorkflowRequestDescriptionObject()->getInContextDescription();

        return t(
            '%s Submitted by <strong>%s</strong> on %s.',
            $description,
            $userName,
            Core::make('helper/date')->formatDateTime($wp->getWorkflowProgressDateAdded(), true)
        );
    }

    public function getWorkflowProgressStatusDescription(WorkflowProgress $wp)
    {
        $req = $wp->getWorkflowRequestObject();

        return $req->getWorkflowRequestDescriptionObject()->getShortStatus();
    }

    public function cancel(WorkflowProgress $wp)
    {
        if ($this->canApproveWorkflowProgressObject($wp)) {
            $req = $wp->getWorkflowRequestObject();
            $bdw = new BasicWorkflowProgressData($wp);
            $u = new User();
            $bdw->markCompleted($u);

            $ux = UserInfo::getByID($bdw->getUserCompletedID());

            $message = t(
                "On %s, user %s cancelled the following request: \n\n---\n%s\n---\n\n",
                Core::make('helper/date')->formatDateTime($bdw->getDateCompleted(), true),
                $ux->getUserName(),
                $req->getWorkflowRequestDescriptionObject()->getEmailDescription()
            );
            $this->notify($wp, $message, 'notify_on_basic_workflow_deny');

            $hist = new BasicWorkflowHistoryEntry();
            $hist->setAction('cancel');
            $hist->setRequesterUserID($u->getUserID());
            $wp->addWorkflowProgressHistoryObject($hist);

            $wpr = $req->runTask('cancel', $wp);
            $wp->markCompleted();

            $bdw = new BasicWorkflowProgressData($wp);
            $bdw->delete();

            return $wpr;
        }

        return null;
    }

    public function canApproveWorkflowProgressObject(WorkflowProgress $wp)
    {
        return $this->canApproveWorkflow();
    }

    public function approve(WorkflowProgress $wp)
    {
        if ($this->canApproveWorkflowProgressObject($wp)) {
            $req = $wp->getWorkflowRequestObject();
            $bdw = new BasicWorkflowProgressData($wp);
            $u = new User();
            $bdw->markCompleted($u);

            $ux = UserInfo::getByID($bdw->getUserCompletedID());

            $message = t(
                "On %s, user %s approved the following request: \n\n---\n%s\n---\n\n",
                Core::make('helper/date')->formatDateTime($bdw->getDateCompleted(), true),
                $ux->getUserName(),
                $req->getWorkflowRequestDescriptionObject()->getEmailDescription()
            );
            $this->notify($wp, $message, 'notify_on_basic_workflow_approve');

            $wpr = $req->runTask('approve', $wp);
            $wp->markCompleted();

            $hist = new BasicWorkflowHistoryEntry();
            $hist->setAction('approve');
            $hist->setRequesterUserID($u->getUserID());
            $wp->addWorkflowProgressHistoryObject($hist);

            $bdw = new BasicWorkflowProgressData($wp);
            $bdw->delete();

            return $wpr;
        }

        return null;
    }

    public function getWorkflowProgressActions(WorkflowProgress $wp)
    {
        $pk = PermissionKey::getByHandle('approve_basic_workflow_action');
        $pk->setPermissionObject($this);
        $buttons = [];
        if ($this->canApproveWorkflowProgressObject($wp)) {
            $req = $wp->getWorkflowRequestObject();
            $button1 = new WorkflowProgressCancelAction();

            $button2 = new WorkflowProgressApprovalAction();
            $button2->setWorkflowProgressActionStyleClass($req->getWorkflowRequestApproveButtonClass());
            $button2->setWorkflowProgressActionStyleInnerButtonRightHTML(
                $req->getWorkflowRequestApproveButtonInnerButtonRightHTML()
            );
            $button2->setWorkflowProgressActionLabel($req->getWorkflowRequestApproveButtonText());

            $buttons[] = $button1;
            $buttons[] = $button2;
        }

        return $buttons;
    }
}