text:
'use strict';

function assertRejectsWithError(promise, name, message) {
  return promise.then(() => {
    assert_unreached('expected promise to reject with ' + name);
  }, error => {
    assert_equals(error.name, name);
    if (message !== undefined)
      assert_equals(error.message, message);
  });
}

// TODO(reillyg): Remove when jyasskin upstreams this to testharness.js:
// https://crbug.com/509058.
function callWithKeyDown(functionCalledOnKeyPress) {
  return new Promise(resolve => {
    function onKeyPress() {
      document.removeEventListener('keypress', onKeyPress, false);
      resolve(functionCalledOnKeyPress());
    }
    document.addEventListener('keypress', onKeyPress, false);

    eventSender.keyDown(' ', []);
  });
}

function usbMocks(mojo) {
  return define('USB Mocks', [
    'device/usb/public/interfaces/chooser_service.mojom',
    'device/usb/public/interfaces/device_manager.mojom',
    'device/usb/public/interfaces/device.mojom',
  ], (chooserService, deviceManager, device) => {
    function assertDeviceInfoEquals(device, info) {
      assert_equals(device.guid, info.guid);
      assert_equals(device.usbVersionMajor, info.usb_version_major);
      assert_equals(device.usbVersionMinor, info.usb_version_minor);
      assert_equals(device.usbVersionSubminor, info.usb_version_subminor);
      assert_equals(device.deviceClass, info.class_code);
      assert_equals(device.deviceSubclass, info.subclass_code);
      assert_equals(device.deviceProtocol, info.protocol_code);
      assert_equals(device.vendorId, info.vendor_id);
      assert_equals(device.productId, info.product_id);
      assert_equals(device.deviceVersionMajor, info.device_version_major);
      assert_equals(device.deviceVersionMinor, info.device_version_minor);
      assert_equals(device.deviceVersionSubminor,
                    info.device_version_subminor);
      assert_equals(device.manufacturerName, info.manufacturer_name);
      assert_equals(device.productName, info.product_name);
      assert_equals(device.serialNumber, info.serial_number);
      assert_equals(device.configurations.length,
                    info.configurations.length);
      for (var i = 0; i < device.configurations.length; ++i) {
        assertConfigurationInfoEquals(device.configurations[i],
                                      info.configurations[i]);
      }
    };

    function assertConfigurationInfoEquals(configuration, info) {
      assert_equals(configuration.configurationValue,
                    info.configuration_value);
      assert_equals(configuration.configurationName,
                    info.configuration_name);
      assert_equals(configuration.interfaces.length,
                    info.interfaces.length);
      for (var i = 0; i < configuration.interfaces.length; ++i) {
        assertInterfaceInfoEquals(configuration.interfaces[i],
                                  info.interfaces[i]);
      }
    };

    function assertInterfaceInfoEquals(iface, info) {
      assert_equals(iface.interfaceNumber, info.interface_number);
      assert_equals(iface.alternates.length, info.alternates.length);
      for (var i = 0; i < iface.alternates.length; ++i) {
        assertAlternateInfoEquals(iface.alternates[i], info.alternates[i]);
      }
    };

    function assertAlternateInfoEquals(alternate, info) {
      assert_equals(alternate.alternateSetting, info.alternate_setting);
      assert_equals(alternate.interfaceClass, info.class_code);
      assert_equals(alternate.interfaceSubclass, info.subclass_code);
      assert_equals(alternate.interfaceProtocol, info.protocol_code);
      assert_equals(alternate.interfaceName, info.interface_name);
      assert_equals(alternate.endpoints.length, info.endpoints.length);
      for (var i = 0; i < alternate.endpoints.length; ++i) {
        assertEndpointInfoEquals(alternate.endpoints[i], info.endpoints[i]);
      }
    }

    function assertEndpointInfoEquals(endpoint, info) {
      var direction;
      switch (info.direction) {
        case device.TransferDirection.INBOUND:
          direction = 'in';
          break;
        case device.TransferDirection.OUTBOUND:
          direction = 'out';
          break;
      }

      var type;
      switch (info.type) {
        case device.EndpointType.BULK:
          type = 'bulk';
          break;
        case device.EndpointType.INTERRUPT:
          type = 'interrupt';
          break;
        case device.EndpointType.ISOCHRONOUS:
          type = 'isochronous';
          break;
      }

      assert_equals(endpoint.endpointNumber, info.endpoint_number);
      assert_equals(endpoint.direction, direction);
      assert_equals(endpoint.type, type);
      assert_equals(endpoint.packetSize, info.packet_size);
    }

    class MockDevice extends device.Device.stubClass {
      constructor(info, pipe) {
        super();
        this.info_ = info;
        this.pipe_ = pipe;
        this.router_ = new mojo.router.Router(pipe);
        this.router_.setIncomingReceiver(this);
        this.opened_ = false;
        this.currentConfiguration_ = undefined;
        this.claimedInterfaces_ = new Map();
      }

      getDeviceInfo() {
        return Promise.resolve({ info: this.info_ });
      }

      getConfiguration() {
        if (this.currentConfiguration_ === undefined) {
          return Promise.resolve({ value: 0 });
        } else {
          return Promise.resolve({
              value: this.currentConfiguration_.configuration_value });
        }
      }

      open() {
        assert_false(this.opened_);
        this.opened_ = true;
        return Promise.resolve({ error: device.OpenDeviceError.OK });
      }

      close() {
        assert_true(this.opened_);
        this.opened_ = false;
        return Promise.resolve({ error: device.OpenDeviceError.OK });
      }

      setConfiguration(value) {
        assert_true(this.opened_);

        let selected_configuration = this.info_.configurations.find(
            configuration => configuration.configuration_value == value);
        if (selected_configuration !== undefined) {
          this.currentConfiguration_ = selected_configuration;
          return Promise.resolve({ success: true });
        } else {
          return Promise.resolve({ success: false });
        }
      }

      claimInterface(interfaceNumber) {
        assert_true(this.opened_);
        assert_true(this.currentConfiguration_ !== undefined,
                    'device configured');

        if (this.claimedInterfaces_.has(interfaceNumber))
          return Promise.resolve({ success: false });

        if (this.currentConfiguration_.interfaces.some(
                iface => iface.interface_number == interfaceNumber)) {
          this.claimedInterfaces_.set(interfaceNumber, 0);
          return Promise.resolve({ success: true });
        } else {
          return Promise.resolve({ success: false });
        }
      }

      releaseInterface(interfaceNumber) {
        assert_true(this.opened_);
        assert_true(this.currentConfiguration_ !== undefined,
                    'device configured');

        if (this.claimedInterfaces_.has(interfaceNumber)) {
          this.claimedInterfaces_.delete(interfaceNumber);
          return Promise.resolve({ success: true });
        } else {
          return Promise.resolve({ success: false });
        }
      }

      setInterfaceAlternateSetting(interfaceNumber, alternateSetting) {
        assert_true(this.opened_);
        assert_true(this.currentConfiguration_ !== undefined,
                    'device configured');

        if (!this.claimedInterfaces_.has(interfaceNumber))
          return Promise.resolve({ success: false });

        let iface = this.currentConfiguration_.interfaces.find(
            iface => iface.interface_number == interfaceNumber);
        if (iface === undefined)
          return Promise.resolve({ success: false });

        if (iface.alternates.some(
               x => x.alternate_setting == alternateSetting)) {
          this.claimedInterfaces_.set(interfaceNumber, alternateSetting);
          return Promise.resolve({ success: true });
        } else {
          return Promise.resolve({ success: false });
        }
      }

      reset() {
        assert_true(this.opened_);
        return Promise.resolve({ success: true });
      }

      clearHalt(endpoint) {
        assert_true(this.opened_);
        assert_true(this.currentConfiguration_ !== undefined,
                    'device configured');
        // TODO(reillyg): Check that endpoint is valid.
        return Promise.resolve({ success: true });
      }

      controlTransferIn(params, length, timeout) {
        assert_true(this.opened_);
        assert_true(this.currentConfiguration_ !== undefined,
                    'device configured');
        return Promise.resolve({
          status: device.TransferStatus.OK,
          data: [length >> 8, length & 0xff, params.request, params.value >> 8,
                 params.value & 0xff, params.index >> 8, params.index & 0xff]
        });
      }

      controlTransferOut(params, data, timeout) {
        assert_true(this.opened_);
        assert_true(this.currentConfiguration_ !== undefined,
                    'device configured');
        return Promise.resolve({
          status: device.TransferStatus.OK,
          bytesWritten: data.byteLength
        });
      }

      genericTransferIn(endpointNumber, length, timeout) {
        assert_true(this.opened_);
        assert_true(this.currentConfiguration_ !== undefined,
                    'device configured');
        // TODO(reillyg): Check that endpoint is valid.
        let data = new Array(length);
        for (let i = 0; i < length; ++i)
          data[i] = i & 0xff;
        return Promise.resolve({
          status: device.TransferStatus.OK,
          data: data
        });
      }

      genericTransferOut(endpointNumber, data, timeout) {
        assert_true(this.opened_);
        assert_true(this.currentConfiguration_ !== undefined,
                    'device configured');
        // TODO(reillyg): Check that endpoint is valid.
        return Promise.resolve({
          status: device.TransferStatus.OK,
          bytesWritten: data.byteLength
        });
      }

      isochronousTransferIn(endpointNumber, packetLengths, timeout) {
        assert_true(this.opened_);
        assert_true(this.currentConfiguration_ !== undefined,
                    'device configured');
        // TODO(reillyg): Check that endpoint is valid.
        let data = new Array(packetLengths.reduce((a, b) => a + b, 0));
        let dataOffset = 0;
        let packets = new Array(packetLengths.length);
        for (let i = 0; i < packetLengths.length; ++i) {
          for (let j = 0; j < packetLengths[i]; ++j)
            data[dataOffset++] = j & 0xff;
          packets[i] = {
            length: packetLengths[i],
            transferred_length: packetLengths[i],
            status: device.TransferStatus.OK
          };
        }
        return Promise.resolve({ data: data, packets: packets });
      }

      isochronousTransferOut(endpointNumber, data, packetLengths, timeout) {
        assert_true(this.opened_);
        assert_true(this.currentConfiguration_ !== undefined,
                    'device configured');
        // TODO(reillyg): Check that endpoint is valid.
        let packets = new Array(packetLengths.length);
        for (let i = 0; i < packetLengths.length; ++i) {
          packets[i] = {
            length: packetLengths[i],
            transferred_length: packetLengths[i],
            status: device.TransferStatus.OK
          };
        }
        return Promise.resolve({ packets: packets });
      }
    };

    class MockDeviceManager extends deviceManager.DeviceManager.stubClass {
      constructor() {
        super();
        this.router_ = null;
        this.mockDevices_ = new Map();
        this.addedDevices_ = [];
        this.removedDevices_ = [];
        this.deviceChangePromiseResolvers_ = [];
      }

      reset() {
        this.mockDevices_.forEach(device => {
          for (var handle of device.handles)
            mojo.core.close(handle.pipe_);
          this.removedDevices_.push(device.info);
        });
        this.mockDevices_.clear();
        this.maybeResolveDeviceChangePromise();
      }

      addMockDevice(info) {
        let device = {
          info: info,
          handles: []
        };
        this.mockDevices_.set(info.guid, device);
        this.addedDevices_.push(info);
        this.maybeResolveDeviceChangePromise();
      }

      removeMockDevice(info) {
        let device = this.mockDevices_.get(info.guid);
        for (var handle of device.handles)
          mojo.core.close(handle.pipe_);
        this.mockDevices_.delete(info.guid);
        this.removedDevices_.push(info);
        this.maybeResolveDeviceChangePromise();
      }

      bindToPipe(pipe) {
        assert_equals(this.router_, null);
        this.router_ = new mojo.router.Router(pipe);
        this.router_.setIncomingReceiver(this);
      }

      getDevices(options) {
        let devices = [];
        this.mockDevices_.forEach(device => {
          devices.push(device.info);
        });
        return Promise.resolve({ results: devices });
      }

      getDeviceChanges() {
        let promise = new Promise((resolve, reject) => {
          this.deviceChangePromiseResolvers_.push(resolve);
        });
        this.maybeResolveDeviceChangePromise();
        return promise;
      }

      maybeResolveDeviceChangePromise() {
        if (this.addedDevices_.length == 0 &&
            this.removedDevices_.length == 0) {
          return;
        }

        let resolve = this.deviceChangePromiseResolvers_.shift();
        if (resolve === undefined)
          return;

        resolve({
          changes: {
            devices_added: this.addedDevices_,
            devices_removed: this.removedDevices_
          }
        });
        this.addedDevices_ = [];
        this.removedDevices_ = [];
      }

      getDevice(guid, pipe) {
        let device = this.mockDevices_.get(guid);
        if (device === undefined) {
          mojo.core.close(pipe);
        } else {
          var mock = new MockDevice(device.info, pipe);
          device.handles.push(mock);
        }
      }
    }

    class MockChooserService
        extends chooserService.ChooserService.stubClass {
      constructor() {
        super();
        this.router_ = null;
        this.chosenDevice_ = null;
      }

      bindToPipe(pipe) {
        assert_equals(this.router_, null);
        this.router_ = new mojo.router.Router(pipe);
        this.router_.setIncomingReceiver(this);
      }

      setChosenDevice(deviceInfo) {
        this.chosenDeviceInfo_ = deviceInfo;
      }

      getPermission(deviceFilters) {
        return Promise.resolve({ result: this.chosenDeviceInfo_ });
      }
    }

    let mockDeviceManager = new MockDeviceManager;
    mojo.frameServiceRegistry.addServiceOverrideForTesting(
        deviceManager.DeviceManager.name,
        pipe => {
          mockDeviceManager.bindToPipe(pipe);
        });

    let mockChooserService = new MockChooserService;
    mojo.frameServiceRegistry.addServiceOverrideForTesting(
        chooserService.ChooserService.name,
        pipe => {
          mockChooserService.bindToPipe(pipe);
        });

    return fakeUsbDevices().then(fakeDevices => Promise.resolve({
      DeviceManager: deviceManager.DeviceManager,
      Device: device.Device,
      mockDeviceManager: mockDeviceManager,
      mockChooserService: mockChooserService,
      fakeDevices: fakeDevices,
      assertDeviceInfoEquals: assertDeviceInfoEquals,
      assertConfigurationInfoEquals: assertConfigurationInfoEquals,
    }));
  });
}

function usb_test(func, name, properties) {
  mojo_test(mojo => usbMocks(mojo).then(usb => {
    let result = Promise.resolve(func(usb));
    let cleanUp = () => usb.mockDeviceManager.reset();
    result.then(cleanUp, cleanUp);
    return result;
  }), name, properties);
}


text:
layout: page
title: about
permalink: /about/
published: true
---

## me

{% include wommy/medallion.html %}

Hi, I'm Tommy

I love everything about [Media](https://en.wikipedia.org/wiki/Media_(communication)): its consumption, production, and distribution; and the [Internet](https://en.wikipedia.org/wiki/Internet): for all the affordances it provides Digital Media.

I work hard to help people be heard on [the Web](https://en.wikipedia.org/wiki/World_Wide_Web).

*This is my voice*: **Welcome!**

<!--more-->

## the website

so i've been working on this design for awhile. there are two layers: technomad and wommy. technomad is the greater application/template/workflow that allows/guides/facilitates the artist to compose/produce/distribute digital media. wommy is my manifestation of that.

its funny that i say that wommy is a manifestation of technomad, because actually, technomad is the distillation of wommy. i have been explicitly working on my own digital presence since 2010. it has taken many twists and turns, been shelfed and picked up again, but, has always stuck with me. and for that reason, i know that i probably will never stop contributing to it, at least in some way, shape, or form.

everything i have done since i left my home in metro Detroit for college in Chicago, has been towards this.

my original project in the summer of 2011 was a ToDo app, called River. At the time, i had no/none/zip/zero/zilch coding experience. I just finished up my first year of [DePaul](depaul.edu), which i transferred to after two years at [Columbia College Chicago](colum.edu). My transition was far rougher than i had ever imagined, the majority of it being needlessly so, artifically created by DePaul.

river was first incepted in the spring of 2011

that  created technomad by manifesting wommy. i created  creating principles.

redpajama_set_name: RedPajamaGithub


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>

  <groupId>com.bso.framework</groupId>
  <artifactId>camel-throttle</artifactId>
  <packaging>jar</packaging>
  <version>1.0.0</version>

  <name>Camel CircleQueue Component</name>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-core</artifactId>
      <version>2.15.0</version>
    </dependency>

    <!-- logging -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.5</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.5</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
      <scope>test</scope>
    </dependency>

    <!-- testing -->
    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-test</artifactId>
      <version>2.15.0</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.5.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-resources-plugin</artifactId>
        <version>2.6</version>
        <configuration>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>

      <!-- to generate the MANIFEST-FILE of the bundle -->
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <version>2.3.7</version>
        <extensions>true</extensions>
        <configuration>
          <instructions>
            <Bundle-SymbolicName>com.bso.framework.camel.throttle</Bundle-SymbolicName>
            <Export-Service>org.apache.camel.spi.ComponentResolver;component=CircleQueue</Export-Service>
          </instructions>
        </configuration>
      </plugin>

    </plugins>
  </build>

</project>


text:
<metadata>
  <title>envelopeTransform3</title>
  <description>
    <div>
      Use HTML content to provide a description of this template.
    </div>
  </description>
</metadata>


text:
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::{fmt, io};

use fail::fail_point;

use crate::core::{InvertedIndexReader, Segment, SegmentComponent, SegmentId};
use crate::directory::{CompositeFile, FileSlice};
use crate::error::DataCorruption;
use crate::fastfield::{intersect_alive_bitsets, AliveBitSet, FacetReader, FastFieldReaders};
use crate::fieldnorm::{FieldNormReader, FieldNormReaders};
use crate::schema::{Field, FieldType, IndexRecordOption, Schema};
use crate::space_usage::SegmentSpaceUsage;
use crate::store::StoreReader;
use crate::termdict::TermDictionary;
use crate::{DocId, Opstamp};

/// Entry point to access all of the datastructures of the `Segment`
///
/// - term dictionary
/// - postings
/// - store
/// - fast field readers
/// - field norm reader
///
/// The segment reader has a very low memory footprint,
/// as close to all of the memory data is mmapped.
#[derive(Clone)]
pub struct SegmentReader {
    inv_idx_reader_cache: Arc<RwLock<HashMap<Field, Arc<InvertedIndexReader>>>>,

    segment_id: SegmentId,
    delete_opstamp: Option<Opstamp>,

    max_doc: DocId,
    num_docs: DocId,

    termdict_composite: CompositeFile,
    postings_composite: CompositeFile,
    positions_composite: CompositeFile,
    fast_fields_readers: Arc<FastFieldReaders>,
    fieldnorm_readers: FieldNormReaders,

    store_file: FileSlice,
    alive_bitset_opt: Option<AliveBitSet>,
    schema: Schema,
}

impl SegmentReader {
    /// Returns the highest document id ever attributed in
    /// this segment + 1.
    pub fn max_doc(&self) -> DocId {
        self.max_doc
    }

    /// Returns the number of alive documents.
    /// Deleted documents are not counted.
    pub fn num_docs(&self) -> DocId {
        self.num_docs
    }

    /// Returns the schema of the index this segment belongs to.
    pub fn schema(&self) -> &Schema {
        &self.schema
    }

    /// Return the number of documents that have been
    /// deleted in the segment.
    pub fn num_deleted_docs(&self) -> DocId {
        self.max_doc - self.num_docs
    }

    /// Returns true if some of the documents of the segment have been deleted.
    pub fn has_deletes(&self) -> bool {
        self.num_deleted_docs() > 0
    }

    /// Accessor to a segment's fast field reader given a field.
    ///
    /// Returns the u64 fast value reader if the field
    /// is a u64 field indexed as "fast".
    ///
    /// Return a FastFieldNotAvailableError if the field is not
    /// declared as a fast field in the schema.
    ///
    /// # Panics
    /// May panic if the index is corrupted.
    pub fn fast_fields(&self) -> &FastFieldReaders {
        &self.fast_fields_readers
    }

    /// Accessor to the `FacetReader` associated to a given `Field`.
    pub fn facet_reader(&self, field: Field) -> crate::Result<FacetReader> {
        let field_entry = self.schema.get_field_entry(field);

        match field_entry.field_type() {
            FieldType::Facet(_) => {
                let term_ords_reader = self.fast_fields().u64s(field)?;
                let termdict = self
                    .termdict_composite
                    .open_read(field)
                    .map(TermDictionary::open)
                    .unwrap_or_else(|| Ok(TermDictionary::empty()))?;
                Ok(FacetReader::new(term_ords_reader, termdict))
            }
            _ => Err(crate::TantivyError::InvalidArgument(format!(
                "Field {:?} is not a facet field.",
                field_entry.name()
            ))),
        }
    }

    /// Accessor to the segment's `Field norms`'s reader.
    ///
    /// Field norms are the length (in tokens) of the fields.
    /// It is used in the computation of the [TfIdf](https://fulmicoton.gitbooks.io/tantivy-doc/content/tfidf.html).
    ///
    /// They are simply stored as a fast field, serialized in
    /// the `.fieldnorm` file of the segment.
    pub fn get_fieldnorms_reader(&self, field: Field) -> crate::Result<FieldNormReader> {
        self.fieldnorm_readers.get_field(field)?.ok_or_else(|| {
            let field_name = self.schema.get_field_name(field);
            let err_msg = format!(
                "Field norm not found for field {field_name:?}. Was the field set to record norm \
                 during indexing?"
            );
            crate::TantivyError::SchemaError(err_msg)
        })
    }

    pub(crate) fn fieldnorms_readers(&self) -> &FieldNormReaders {
        &self.fieldnorm_readers
    }

    /// Accessor to the segment's `StoreReader`.
    pub fn get_store_reader(&self) -> io::Result<StoreReader> {
        StoreReader::open(self.store_file.clone())
    }

    /// Open a new segment for reading.
    pub fn open(segment: &Segment) -> crate::Result<SegmentReader> {
        Self::open_with_custom_alive_set(segment, None)
    }

    /// Open a new segment for reading.
    pub fn open_with_custom_alive_set(
        segment: &Segment,
        custom_bitset: Option<AliveBitSet>,
    ) -> crate::Result<SegmentReader> {
        let termdict_file = segment.open_read(SegmentComponent::Terms)?;
        let termdict_composite = CompositeFile::open(&termdict_file)?;

        let store_file = segment.open_read(SegmentComponent::Store)?;

        fail_point!("SegmentReader::open#middle");

        let postings_file = segment.open_read(SegmentComponent::Postings)?;
        let postings_composite = CompositeFile::open(&postings_file)?;

        let positions_composite = {
            if let Ok(positions_file) = segment.open_read(SegmentComponent::Positions) {
                CompositeFile::open(&positions_file)?
            } else {
                CompositeFile::empty()
            }
        };

        let schema = segment.schema();

        let fast_fields_data = segment.open_read(SegmentComponent::FastFields)?;
        let fast_fields_composite = CompositeFile::open(&fast_fields_data)?;
        let fast_field_readers =
            Arc::new(FastFieldReaders::new(schema.clone(), fast_fields_composite));
        let fieldnorm_data = segment.open_read(SegmentComponent::FieldNorms)?;
        let fieldnorm_readers = FieldNormReaders::open(fieldnorm_data)?;

        let original_bitset = if segment.meta().has_deletes() {
            let delete_file_slice = segment.open_read(SegmentComponent::Delete)?;
            let delete_data = delete_file_slice.read_bytes()?;
            Some(AliveBitSet::open(delete_data))
        } else {
            None
        };

        let alive_bitset_opt = intersect_alive_bitset(original_bitset, custom_bitset);

        let max_doc = segment.meta().max_doc();
        let num_docs = alive_bitset_opt
            .as_ref()
            .map(|alive_bitset| alive_bitset.num_alive_docs() as u32)
            .unwrap_or(max_doc);

        Ok(SegmentReader {
            inv_idx_reader_cache: Default::default(),
            num_docs,
            max_doc,
            termdict_composite,
            postings_composite,
            fast_fields_readers: fast_field_readers,
            fieldnorm_readers,
            segment_id: segment.id(),
            delete_opstamp: segment.meta().delete_opstamp(),
            store_file,
            alive_bitset_opt,
            positions_composite,
            schema,
        })
    }

    /// Returns a field reader associated to the field given in argument.
    /// If the field was not present in the index during indexing time,
    /// the InvertedIndexReader is empty.
    ///
    /// The field reader is in charge of iterating through the
    /// term dictionary associated to a specific field,
    /// and opening the posting list associated to any term.
    ///
    /// If the field is marked as index, a warn is logged and an empty `InvertedIndexReader`
    /// is returned.
    /// Similarly if the field is marked as indexed but no term has been indexed for the given
    /// index. an empty `InvertedIndexReader` is returned (but no warning is logged).
    pub fn inverted_index(&self, field: Field) -> crate::Result<Arc<InvertedIndexReader>> {
        if let Some(inv_idx_reader) = self
            .inv_idx_reader_cache
            .read()
            .expect("Lock poisoned. This should never happen")
            .get(&field)
        {
            return Ok(Arc::clone(inv_idx_reader));
        }
        let field_entry = self.schema.get_field_entry(field);
        let field_type = field_entry.field_type();
        let record_option_opt = field_type.get_index_record_option();

        if record_option_opt.is_none() {
            warn!("Field {:?} does not seem indexed.", field_entry.name());
        }

        let postings_file_opt = self.postings_composite.open_read(field);

        if postings_file_opt.is_none() || record_option_opt.is_none() {
            // no documents in the segment contained this field.
            // As a result, no data is associated to the inverted index.
            //
            // Returns an empty inverted index.
            let record_option = record_option_opt.unwrap_or(IndexRecordOption::Basic);
            return Ok(Arc::new(InvertedIndexReader::empty(record_option)));
        }

        let record_option = record_option_opt.unwrap();
        let postings_file = postings_file_opt.unwrap();

        let termdict_file: FileSlice =
            self.termdict_composite.open_read(field).ok_or_else(|| {
                DataCorruption::comment_only(format!(
                    "Failed to open field {:?}'s term dictionary in the composite file. Has the \
                     schema been modified?",
                    field_entry.name()
                ))
            })?;

        let positions_file = self.positions_composite.open_read(field).ok_or_else(|| {
            let error_msg = format!(
                "Failed to open field {:?}'s positions in the composite file. Has the schema been \
                 modified?",
                field_entry.name()
            );
            DataCorruption::comment_only(error_msg)
        })?;

        let inv_idx_reader = Arc::new(InvertedIndexReader::new(
            TermDictionary::open(termdict_file)?,
            postings_file,
            positions_file,
            record_option,
        )?);

        // by releasing the lock in between, we may end up opening the inverting index
        // twice, but this is fine.
        self.inv_idx_reader_cache
            .write()
            .expect("Field reader cache lock poisoned. This should never happen.")
            .insert(field, Arc::clone(&inv_idx_reader));

        Ok(inv_idx_reader)
    }

    /// Returns the segment id
    pub fn segment_id(&self) -> SegmentId {
        self.segment_id
    }

    /// Returns the delete opstamp
    pub fn delete_opstamp(&self) -> Option<Opstamp> {
        self.delete_opstamp
    }

    /// Returns the bitset representing
    /// the documents that have been deleted.
    pub fn alive_bitset(&self) -> Option<&AliveBitSet> {
        self.alive_bitset_opt.as_ref()
    }

    /// Returns true if the `doc` is marked
    /// as deleted.
    pub fn is_deleted(&self, doc: DocId) -> bool {
        self.alive_bitset()
            .map(|delete_set| delete_set.is_deleted(doc))
            .unwrap_or(false)
    }

    /// Returns an iterator that will iterate over the alive document ids
    pub fn doc_ids_alive(&self) -> Box<dyn Iterator<Item = DocId> + '_> {
        if let Some(alive_bitset) = &self.alive_bitset_opt {
            Box::new(alive_bitset.iter_alive())
        } else {
            Box::new(0u32..self.max_doc)
        }
    }

    /// Summarize total space usage of this segment.
    pub fn space_usage(&self) -> io::Result<SegmentSpaceUsage> {
        Ok(SegmentSpaceUsage::new(
            self.num_docs(),
            self.termdict_composite.space_usage(),
            self.postings_composite.space_usage(),
            self.positions_composite.space_usage(),
            self.fast_fields_readers.space_usage(),
            self.fieldnorm_readers.space_usage(),
            self.get_store_reader()?.space_usage(),
            self.alive_bitset_opt
                .as_ref()
                .map(AliveBitSet::space_usage)
                .unwrap_or(0),
        ))
    }
}

fn intersect_alive_bitset(
    left_opt: Option<AliveBitSet>,
    right_opt: Option<AliveBitSet>,
) -> Option<AliveBitSet> {
    match (left_opt, right_opt) {
        (Some(left), Some(right)) => {
            assert_eq!(left.bitset().max_value(), right.bitset().max_value());
            Some(intersect_alive_bitsets(left, right))
        }
        (Some(left), None) => Some(left),
        (None, Some(right)) => Some(right),
        (None, None) => None,
    }
}

impl fmt::Debug for SegmentReader {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "SegmentReader({:?})", self.segment_id)
    }
}

#[cfg(test)]
mod test {
    use crate::core::Index;
    use crate::schema::{Schema, Term, STORED, TEXT};
    use crate::DocId;

    #[test]
    fn test_num_alive() -> crate::Result<()> {
        let mut schema_builder = Schema::builder();
        schema_builder.add_text_field("name", TEXT | STORED);
        let schema = schema_builder.build();
        let index = Index::create_in_ram(schema.clone());
        let name = schema.get_field("name").unwrap();

        {
            let mut index_writer = index.writer_for_tests()?;
            index_writer.add_document(doc!(name => "tantivy"))?;
            index_writer.add_document(doc!(name => "horse"))?;
            index_writer.add_document(doc!(name => "jockey"))?;
            index_writer.add_document(doc!(name => "cap"))?;
            // we should now have one segment with two docs
            index_writer.delete_term(Term::from_field_text(name, "horse"));
            index_writer.delete_term(Term::from_field_text(name, "cap"));

            // ok, now we should have a deleted doc
            index_writer.commit()?;
        }
        let searcher = index.reader()?.searcher();
        assert_eq!(2, searcher.segment_reader(0).num_docs());
        assert_eq!(4, searcher.segment_reader(0).max_doc());
        Ok(())
    }
    #[test]
    fn test_alive_docs_iterator() -> crate::Result<()> {
        let mut schema_builder = Schema::builder();
        schema_builder.add_text_field("name", TEXT | STORED);
        let schema = schema_builder.build();
        let index = Index::create_in_ram(schema.clone());
        let name = schema.get_field("name").unwrap();

        {
            let mut index_writer = index.writer_for_tests()?;
            index_writer.add_document(doc!(name => "tantivy"))?;
            index_writer.add_document(doc!(name => "horse"))?;
            index_writer.add_document(doc!(name => "jockey"))?;
            index_writer.add_document(doc!(name => "cap"))?;
            // we should now have one segment with two docs
            index_writer.commit()?;
        }

        {
            let mut index_writer2 = index.writer(50_000_000)?;
            index_writer2.delete_term(Term::from_field_text(name, "horse"));
            index_writer2.delete_term(Term::from_field_text(name, "cap"));

            // ok, now we should have a deleted doc
            index_writer2.commit()?;
        }
        let searcher = index.reader()?.searcher();
        let docs: Vec<DocId> = searcher.segment_reader(0).doc_ids_alive().collect();
        assert_eq!(vec![0u32, 2u32], docs);
        Ok(())
    }
}


text:
<?php

namespace spec\Spyl\Bundle\BakaBundle\Reader;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

use Spyl\Bundle\BakaBundle\Model\Content;

class PageReaderSpec extends ObjectBehavior
{

    /**
     * @param \Symfony\Component\Routing\RouterInterface $router
     */
	function let($router)
	{
	    $this->beConstructedWith('', '', $router);
	}

    function it_is_initializable()
    {
        $this->shouldHaveType('Spyl\Bundle\BakaBundle\Reader\PageReader');
    }

    function it_lists_a_manga_content_pages()
    {
    	$this->listPages();
    }
}


text:
module Estore
  module Commands
    module ReadStreamForward
      def read(stream, from, limit)
        msg = ReadStreamEvents.new(
          event_stream_id: stream,
          from_event_number: from,
          max_count: limit,
          resolve_link_tos: true,
          require_master: false
        )

        write('ReadStreamEventsForward', msg)
      end

      def error(response)
        case response.result
        when ReadStreamEventsCompleted::ReadStreamResult::AccessDenied
          :access_denied
        when ReadStreamEventsCompleted::ReadStreamResult::Error
          response.error ? response.error : 'No message given'
        else
          false
        end
      end
    end
  end
end


text:
package com.github.lburgazzoli.hazelcast.serialization.json;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class JsonEnvelope {
    private final byte[] data;

    public JsonEnvelope(final byte[] data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return new String(this.data);
    }

    byte[] data() {
        return this.data;
    }

    // *************************************************************************
    //
    // *************************************************************************

    public static <T> T asObject(
        JsonEnvelope envelope, ObjectMapper mapper, Class<T> type) throws IOException {
        return mapper.readValue(envelope.data, type);
    }

    public static <T> JsonEnvelope fromObject(ObjectMapper mapper, T object) throws IOException {
        return new JsonEnvelope(mapper.writeValueAsBytes(object));
    }
}


text:
extern "C" {
#endif

DLLEXPORT void libsupport_init(void);

#ifdef __cplusplus
}
#endif

#endif


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/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.7"/>
<title>ODFPY: odf.odf2moinmoin Namespace Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

ODFPY
    1.2.0

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

 All Classes Namespaces Files Functions Variables

Classes |
Variables

odf.odf2moinmoin Namespace Reference

Classes

class  	ListProperties

 	Holds properties for a list style.  More...

class  	ODF2MoinMoin

class  	ParagraphProps

 	Holds properties of a paragraph style.  More...

class  	TextProps

 	Holds properties for a text style.  More...

Variables

list 	IGNORED_TAGS

list 	INLINE_TAGS = [ nsdict[item[0]]+":"+item[1] for item in inline_elements]

Variable Documentation

          list odf.odf2moinmoin.IGNORED_TAGS

Initial value:

    1 = [

    2     'draw:a'

    3     'draw:g',

    4     'draw:line',

    5     'draw:object-ole',

    6     'office:annotation',

    7     'presentation:notes',

    8     'svg:desc',

    9 ]

Definition at line 27 of file odf2moinmoin.py.

          list odf.odf2moinmoin.INLINE_TAGS = [ nsdict[item[0]]+":"+item[1] for item in inline_elements]

Definition at line 37 of file odf2moinmoin.py.

odf

odf2moinmoin

Generated on Tue Oct 28 2014 13:47:25 for ODFPY by

     1.8.7


text:
;

angular.module('myApp', ["ngRoute", "googlechart"])
.config(['$routeProvider',
	function ($routeProvider) {
		$routeProvider.
		when('/base', {
			templateUrl: 'partial/base.html',
			controller: 'BaseCtrl'
		}).
		when('/settings', {
			templateUrl: 'partial/settings.html',
			controller: 'SettingsCtrl'
		}).
		otherwise({
			redirectTo: '/base'
		})
	}])
.value('googleChartApiConfig', {
		version: '1',
		optionalSettings: {
			packages: ['corechart'],
			language: 'ja'
		}
	})
.controller('MainCtrl', function ($scope, $timeout) {
	console.log("MainCtrl.start");

	// Build the date object
	$scope.date = {};

	// Update function
	var updateTime = function() {
		$scope.date.raw = new Date();
		$timeout(updateTime, 1000);
	}

	// Kick off the update function
	updateTime();
})
;


text:
//
//  OAuthConnectionHandler.h
//  Strava OAuth Example
//
//  Created by Jeff Remer on 12/7/12.
//  Copyright (c) 2012 Strava. All rights reserved.
//

#import "HTTPConnection.h"

/** NSNotification constant posted when the connection opened */
extern NSString *const OAuthConnectionHandlerDidStartNotification;
/** NSError domain for OAuthConnectionHandler errors */
extern NSString *const OAuthConnectionHandlerErrorDomain;

/** Possible error codes returned in connectionHandler:didFail: */
NS_ENUM(NSUInteger, OAuthConnectionHandlerError) {
    OAuthConnectionHandlerErrorUnknown = 0,
    OAuthConnectionHandlerInvalidScope,
    OAuthConnectionHandlerAccessDenied
};

@protocol OAuthConnectionHandlerDelegate;

/** OAuthConnectionHandler is a HTTPConnection that listens for information from an OAuth provider */
@interface OAuthConnectionHandler : HTTPConnection

/** The OAuthConnectionHandlerDelegate recieves messages when the OAuth provider
 * provides a request token or throws an error.
 */
@property (nonatomic, assign) id<OAuthConnectionHandlerDelegate> delegate;

@end

@protocol OAuthConnectionHandlerDelegate <NSObject>

/* Called when the OAuthConnectionHandler receives a request token from the OAuth provider.
 *
 * @param handler The receiving OAuthConnectionHandler
 * @param requestToken The request token provided by the OAuth provider
 */
- (void)connectionHandler:(OAuthConnectionHandler *)handler didRecieveOAuthRequestToken:(NSString *)requestToken;

/* Called when the OAuthConnectionHandler receives an error from the OAuth provider.
 *
 * @param handler The receiving OAuthConnectionHandler
 * @param error A error with an OAuthConnectionHandlerError error code
 */
- (void)connectionHandler:(OAuthConnectionHandler *)handler didFail:(NSError*)error;

@end


text:
Contributing to Sumerian Named Entity Recongnition
==================================================

To start contributing, you can install the project by

.. code-block:: bash

   git clone https://github.com/wwunlp/sner.git
   cd sner/
   pip3 install .

Please follow the
`Google Python Style Guide <https://google.github.io/styleguide/pyguide>`_.

The project is organized into
``classes``, ``docs``, ``models``, ``scripts``, and ``tests``.

- Class files should probably go into ``classes``.
- The main file fora model should go into ``models``.
- General scripts should go into ``scripts``, and scripts for models should
  into a sub-directory of the model in ``scripts``.
- Test files should go into ``tests``.
- Compile docs with ``sphinx``, and post the html files to ``docs/``.

If you're parsing ``.atf`` files, please look at the
`ATF reference <https://sner.readthedocs.io/en/latest/atf_reference.html>`_.


text:
//
//  FFDayScrollView.m
//  FFCalendar
//
//  Created by Fernanda G. Geraissate on 2/23/14.
//  Copyright (c) 2014 Fernanda G. Geraissate. All rights reserved.
//
//  http://fernandasportfolio.tumblr.com
//

#import "FFDayScrollView.h"

#import "FFViewWithHourLines.h"
#import "FFImportantFilesForCalendar.h"

@interface FFDayScrollView ()
@end

@implementation FFDayScrollView

#pragma mark - Synthesize

@synthesize dictEvents;
@synthesize collectionViewDay;
@synthesize labelWithActualHour;

#pragma mark - Lifecycle

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code

        [self setAutoresizingMask:AR_WIDTH_HEIGHT | UIViewAutoresizingFlexibleRightMargin];
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

- (void)setDictEvents:(NSMutableDictionary *)_dictEvents {

    dictEvents = _dictEvents;

    if (!collectionViewDay) {

        FFViewWithHourLines *viewWithHourLines = [[FFViewWithHourLines alloc] initWithFrame:CGRectZero];

        collectionViewDay = [FFDayCollectionView alloc];
        collectionViewDay.currentDeviceType = self.currentDeviceType;
        collectionViewDay = [collectionViewDay
                             initWithFrame:CGRectMake(10.,0.,self.frame.size.width-10,viewWithHourLines.totalHeight+HEIGHT_CELL_HOUR)collectionViewLayout:[UICollectionViewFlowLayout new]];
        [collectionViewDay scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:[NSDate componentsOfDate:[[FFDateManager sharedManager] currentDate]].day-1+7 inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
        [self addSubview:collectionViewDay];

        labelWithActualHour = [viewWithHourLines labelWithCurrentHourWithWidth:self.frame.size.width];
        [labelWithActualHour setFrame:CGRectMake(labelWithActualHour.frame.origin.x, labelWithActualHour.frame.origin.y+viewWithHourLines.frame.origin.y, labelWithActualHour.frame.size.width, labelWithActualHour.frame.size.height)];

        [self setContentSize:CGSizeMake(self.frame.size.width, collectionViewDay.frame.origin.y+collectionViewDay.frame.size.height-HEIGHT_CELL_HOUR)];
        [self scrollRectToVisible:CGRectMake(0, labelWithActualHour.frame.origin.y, self.frame.size.width, self.frame.size.height) animated:NO];
    }

    [collectionViewDay setDictEvents:dictEvents];
    [collectionViewDay reloadData];
}

@end


text:
import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {Button} from 'react-bootstrap';
import uuid from 'node-uuid';

import * as userActions from '../../actions/userActions';
import {capitalizeFirstLetter} from '../../utils';

class PokemonsPage extends React.Component {
  _getPokemonsContent() {
    return this.props.caughtPokemons.map(item => {
      return (

{capitalizeFirstLetter(item.name)}

            <img src={`https://img.pokemondb.net/artwork/${item.name}.jpg`}/>

            <Button
              bsStyle="danger"
              onClick={this.props.userActions.releasePokemon.bind(this, {id: item.id, name: item.name})}>
              Release
            </Button>

      );
    });
  }

  render() {
    let content = null;

    if(this.props.caughtPokemons.length === 0) {
      content = "Try to catch some pokemons...";
    } else {
      content = this._getPokemonsContent();
    }

    return (

          {content}

    );
  }
}

PokemonsPage.propTypes = {
  userActions: PropTypes.object.isRequired,
  caughtPokemons: PropTypes.array
};

function mapStateToProps(state) {
  return {
    caughtPokemons: state.userReducer.caughtPokemons,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    userActions: bindActionCreators(userActions, dispatch)
  };
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(PokemonsPage);


text:
/// <reference path="../poker.commanding.api.ts" />

import * as ko from "knockout";
import { App } from "../app";
import { _ } from "../languagemanager";
import { SimplePopup } from "../popups/simplepopup";
import { AccountManager } from "../services/accountManager";
import { PopupBase } from "../ui/popupbase";

declare var app: App;

export class ChangePasswordPopup extends PopupBase {
    public oldPassword = ko.observable<string>().extend({ required: true });
    public password: KnockoutObservable<string>;
    public confirmPassword: KnockoutObservable<string>;
    public errorMessage: KnockoutObservable<string>;
    public errors: KnockoutValidationErrors;
    public loading: KnockoutObservable<boolean>;
    private validationModel: KnockoutObservable<ChangePasswordPopup>;

    constructor() {
        super();
        this.password = ko.observable<string>().extend({ required: true });
        this.confirmPassword = ko.observable<string>().extend({ required: true });
        this.errors = ko.validation.group(this);
        this.validationModel = ko.validatedObservable(this);
        this.errorMessage = ko.observable<string>();
        this.loading = ko.observable(false);
    }
    public shown(args: any[]= []): void {
        this.oldPassword(null);
        this.password(null);
        this.confirmPassword(null);
        this.errors.showAllMessages(false);
        super.shown(args);
    }
    public async confirm() {
        const self = this;
        const isValid = this.validationModel.isValid();
        if (!isValid) {
            this.errors.showAllMessages(true);
            return;
        }

        if (!this.loading()) {
            self.loading(true);
            self.errorMessage(null);
            const accountApi = new AccountManager();
            const data = await accountApi.changePasword(this.oldPassword(), this.password());
            if (data.Status === "Ok") {
                self.loading(false);
                self.oldPassword(null);
                self.password(null);
                self.confirmPassword(null);
                app.closePopup();
                SimplePopup.display(_("auth.changePassword"), _("auth.passwordChangedSuccess"));
            } else {
                // Report authentication or authorization errors
                self.errorMessage(_("errors." + data.Status));
            }
        }
    }
}


text:
"""
riko.modules.regex
~~~~~~~~~~~~~~~~~~
Provides functions for modifying the content of a field of an item using
regular expressions, a powerful type of pattern matching.

Think of it as search-and-replace on steriods. You can define multiple Regex
rules. Each has the general format: "In [field] replace [regex pattern] with
[text]".

Examples:
    basic usage::

        >>> from riko.modules.regex import pipe
        >>>
        >>> match = r'(\\w+)\\s(\\w+)'
        >>> rule = {'field': 'content', 'match': match, 'replace': '$2wide'}
        >>> conf = {'rule': rule}
        >>> item = {'content': 'hello world'}
        >>> next(pipe(item, conf=conf))['content'] == 'worldwide'
        True

Attributes:
    OPTS (dict): The default pipe options
    DEFAULTS (dict): The default parser options
"""
import pygogo as gogo

from functools import reduce

from . import processor
from riko.utils import get_new_rule, substitute, multi_substitute, group_by
from riko.bado import coroutine, return_value, itertools as ait
from riko.dotdict import DotDict
from meza.process import merge

OPTS = {'listize': True, 'extract': 'rule', 'emit': True}
DEFAULTS = {'convert': True, 'multi': False}
logger = gogo.Gogo(__name__, monolog=True).logger

@coroutine
def async_parser(item, rules, skip=False, **kwargs):
    """ Asynchronously parsers the pipe content

    Args:
        item (obj): The entry to process (a DotDict instance)
        rules (List[obj]): the parsed rules (Objectify instances).
        skip (bool): Don't parse the content
        kwargs (dict): Keyword arguments

    Kwargs:
        stream (dict): The original item

    Returns:
        Deferred: twisted.internet.defer.Deferred dict

    Examples:
        >>> from riko.bado import react
        >>> from riko.bado.mock import FakeReactor
        >>> from meza.fntools import Objectify
        >>>
        >>> item = DotDict({'content': 'hello world', 'title': 'greeting'})
        >>> match = r'(\\w+)\\s(\\w+)'
        >>> replace = '$2wide'
        >>>
        >>> def run(reactor):
        ...     callback = lambda x: print(x['content'])
        ...     rule = {'field': 'content', 'match': match, 'replace': replace}
        ...     conf = {'rule': rule, 'multi': False, 'convert': True}
        ...     rules = [Objectify(rule)]
        ...     kwargs = {'stream': item, 'conf': conf}
        ...     d = async_parser(item, rules, **kwargs)
        ...     return d.addCallbacks(callback, logger.error)
        >>>
        >>> try:
        ...     react(run, _reactor=FakeReactor())
        ... except SystemExit:
        ...     pass
        ...
        worldwide
    """
    multi = kwargs['conf']['multi']
    recompile = not multi

    @coroutine
    def async_reducer(item, rules):
        field = rules[0]['field']
        word = item.get(field, **kwargs)
        grouped = group_by(rules, 'flags')
        group_rules = [g[1] for g in grouped] if multi else rules
        reducer = multi_substitute if multi else substitute
        replacement = yield ait.coop_reduce(reducer, group_rules, word)
        combined = merge([item, {field: replacement}])
        return_value(DotDict(combined))

    if skip:
        item = kwargs['stream']
    else:
        new_rules = [get_new_rule(r, recompile=recompile) for r in rules]
        grouped = group_by(new_rules, 'field')
        field_rules = [g[1] for g in grouped]
        item = yield ait.async_reduce(async_reducer, field_rules, item)

    return_value(item)

def parser(item, rules, skip=False, **kwargs):
    """ Parsers the pipe content

    Args:
        item (obj): The entry to process (a DotDict instance)
        rules (List[obj]): the parsed rules (Objectify instances).
        skip (bool): Don't parse the content
        kwargs (dict): Keyword arguments

    Kwargs:
        stream (dict): The original item

    Returns:
        dict: The item

    Examples:
        >>> from meza.fntools import Objectify
        >>>
        >>> item = DotDict({'content': 'hello world', 'title': 'greeting'})
        >>> match = r'(\\w+)\\s(\\w+)'
        >>> rule = {'field': 'content', 'match': match, 'replace': '$2wide'}
        >>> conf = {'rule': rule, 'multi': False, 'convert': True}
        >>> rules = [Objectify(rule)]
        >>> kwargs = {'stream': item, 'conf': conf}
        >>> regexed = parser(item, rules, **kwargs)
        >>> regexed == {'content': 'worldwide', 'title': 'greeting'}
        True
        >>> conf['multi'] = True
        >>> parser(item, rules, **kwargs) == regexed
        True
    """
    multi = kwargs['conf']['multi']
    recompile = not multi

    def meta_reducer(item, rules):
        field = rules[0]['field']
        word = item.get(field, **kwargs)
        grouped = group_by(rules, 'flags')
        group_rules = [g[1] for g in grouped] if multi else rules
        reducer = multi_substitute if multi else substitute
        replacement = reduce(reducer, group_rules, word)
        return DotDict(merge([item, {field: replacement}]))

    if skip:
        item = kwargs['stream']
    else:
        new_rules = [get_new_rule(r, recompile=recompile) for r in rules]
        grouped = group_by(new_rules, 'field')
        field_rules = [g[1] for g in grouped]
        item = reduce(meta_reducer, field_rules, item)

    return item

@processor(DEFAULTS, isasync=True, **OPTS)
def async_pipe(*args, **kwargs):
    """A processor that asynchronously replaces text in fields of an item
    using regexes.

    Args:
        item (dict): The entry to process
        kwargs (dict): The keyword arguments passed to the wrapper

    Kwargs:
        conf (dict): The pipe configuration. Must contain the key 'rule'. May
            contain the keys 'multi' or 'convert'.

            rule (dict): can be either a dict or list of dicts. Must contain
                the keys 'field', 'match', and 'replace'.

                field (str): The item attribute to search
                match (str): The regex to apply
                replace (str): The string replacement
                default (str): Default if search pattern isn't found (
                    default: None, i.e, return the original string)

                singlematch (bool): Stop after first match (default: False)
                singlelinematch (bool): Don't search across newlines with '^',
                    '$', or '.' (default: False)

                casematch (bool): Perform case sensitive match (default: False)

            multi (bool): Efficiently combine multiple regexes (default: False)
            convert (bool): Convert regex into a Python compatible format
                (default: True)

    Yields:
        Deferred: twisted.internet.defer.Deferred item with replaced content

    Examples:
        >>> from riko.bado import react
        >>> from riko.bado.mock import FakeReactor
        >>>
        >>> item = {'content': 'hello world', 'title': 'greeting'}
        >>> match = r'(\\w+)\\s(\\w+)'
        >>> replace = '$2wide'
        >>>
        >>> def run(reactor):
        ...     callback = lambda x: print(next(x)['content'])
        ...     rule = {'field': 'content', 'match': match, 'replace': replace}
        ...     conf = {'rule': rule, 'multi': False, 'convert': True}
        ...     d = async_pipe(item, conf=conf)
        ...     return d.addCallbacks(callback, logger.error)
        >>>
        >>> try:
        ...     react(run, _reactor=FakeReactor())
        ... except SystemExit:
        ...     pass
        ...
        worldwide
    """
    return async_parser(*args, **kwargs)

@processor(DEFAULTS, **OPTS)
def pipe(*args, **kwargs):
    """A processor that replaces text in fields of an item using regexes.

    Args:
        item (dict): The entry to process
        kwargs (dict): The keyword arguments passed to the wrapper

    Kwargs:
        conf (dict): The pipe configuration. Must contain the key 'rule'. May
            contain the keys 'multi' or 'convert'.

            rule (dict): can be either a dict or list of dicts. Must contain
                the keys 'field', 'match', and 'replace'.

                field (str): The item attribute to search
                match (str): The regex to apply
                replace (str): The string replacement
                default (str): Default if search pattern isn't found (
                    default: None, i.e, return the original string)

                singlematch (bool): Stop after first match (default: False)
                singlelinematch (bool): Don't search across newlines with '^',
                    '$', or '.' (default: False)

                casematch (bool): Perform case sensitive match (default: False)

            multi (bool): Efficiently combine multiple regexes (default: False)
            convert (bool): Convert regex into a Python compatible format
                (default: True)

    Yields:
        dict: an item with replaced content

    Examples:
        >>> # default matching
        >>> item = {'content': 'hello world', 'title': 'greeting'}
        >>> match = r'(\\w+)\\s(\\w+)'
        >>> rule = {'field': 'content', 'match': match, 'replace': '$2wide'}
        >>> conf = {'rule': rule, 'multi': False, 'convert': True}
        >>> result = next(pipe(item, conf=conf))
        >>> result == {'content': 'worldwide', 'title': 'greeting'}
        True
        >>> # multiple regex mode
        >>> conf['multi'] = True
        >>> next(pipe(item, conf=conf)) == result
        True
        >>> # case insensitive matching
        >>> item = {'content': 'Hello hello'}
        >>> rule.update({'match': r'hello.*', 'replace': 'bye'})
        >>> next(pipe(item, conf=conf))['content'] == 'bye'
        True
        >>> # case sensitive matching
        >>> rule['casematch'] = True
        >>> next(pipe(item, conf=conf))['content'] == 'Hello bye'
        True
    """
    return parser(*args, **kwargs)


text:
(function(window,document,undefined) {
var AFTER, BEFORE, EventEmitter, INVALID_PARAMS_ERROR, READY_STATE, convertHeaders, createXHRFacade, patchClass, pluginEvents, xhook, _base,
  __slice = [].slice;

BEFORE = 'before';

AFTER = 'after';

READY_STATE = 'readyState';

INVALID_PARAMS_ERROR = "Invalid number or parameters. Please see API documentation.";

(_base = Array.prototype).indexOf || (_base.indexOf = function(item) {
  var i, x, _i, _len;
  for (i = _i = 0, _len = this.length; _i < _len; i = ++_i) {
    x = this[i];
    if (x === item) {
      return i;
    }
  }
  return -1;
});

EventEmitter = function(ctx) {
  var emitter, events, listeners;
  events = {};
  listeners = function(event) {
    return events[event] || [];
  };
  emitter = {
    listeners: function(event) {
      return Array.prototype.slice.call(listeners(event));
    },
    on: function(event, callback, i) {
      events[event] = listeners(event);
      if (events[event].indexOf(callback) >= 0) {
        return;
      }
      i = i === undefined ? events[event].length : i;
      events[event].splice(i, 0, callback);
    },
    off: function(event, callback) {
      var i;
      i = listeners(event).indexOf(callback);
      if (i === -1) {
        return;
      }
      listeners(event).splice(i, 1);
    },
    fire: function() {
      var args, event, listener, _i, _len, _ref;
      event = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
      _ref = listeners(event);
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        listener = _ref[_i];
        listener.apply(ctx, args);
      }
    }
  };
  return emitter;
};

pluginEvents = EventEmitter();

xhook = {};

xhook[BEFORE] = function(handler, i) {
  return pluginEvents.on(BEFORE, handler, i);
};

xhook[AFTER] = function(handler, i) {
  return pluginEvents.on(AFTER, handler, i);
};

convertHeaders = function(h, dest) {
  var header, headers, k, v, _i, _len;
  if (dest == null) {
    dest = {};
  }
  switch (typeof h) {
    case "object":
      headers = [];
      for (k in h) {
        v = h[k];
        headers.push("" + k + ":\t" + v);
      }
      return headers.join('\n');
    case "string":
      headers = h.split('\n');
      for (_i = 0, _len = headers.length; _i < _len; _i++) {
        header = headers[_i];
        if (/([^:]+):\s*(.+)/.test(header)) {
          if (!dest[RegExp.$1]) {
            dest[RegExp.$1] = RegExp.$2;
          }
        }
      }
      return dest;
  }
};

xhook.headers = convertHeaders;

patchClass = function(name) {
  var Class;
  Class = window[name];
  if (!Class) {
    return;
  }
  window[name] = function(arg) {
    if (typeof arg === "string" && !/\.XMLHTTP/.test(arg)) {
      return;
    }
    return createXHRFacade(new Class(arg));
  };
};

patchClass("ActiveXObject");

patchClass("XMLHttpRequest");

createXHRFacade = function(xhr) {
  var checkEvent, copyBody, copyHead, currentState, event, extractProps, face, faceEvents, readyBody, readyHead, request, response, setReadyState, transiting, _i, _len, _ref;
  if (pluginEvents.listeners(BEFORE).length === 0 && pluginEvents.listeners(AFTER).length === 0) {
    return xhr;
  }
  transiting = false;
  request = {
    headers: {}
  };
  response = null;
  faceEvents = EventEmitter();
  readyHead = function() {
    face.status = response.status;
    face.statusText = response.statusText;
    response.headers || (response.headers = {});
  };
  readyBody = function() {
    face.responseType = response.type || '';
    face.response = response.data || null;
    face.responseText = response.text || response.data || '';
    face.responseXML = response.xml || null;
  };
  copyHead = function() {
    var key, val, _ref, _results;
    response.status = xhr.status;
    response.statusText = xhr.statusText;
    _ref = convertHeaders(xhr.getAllResponseHeaders());
    _results = [];
    for (key in _ref) {
      val = _ref[key];
      if (!response.headers[key]) {
        _results.push(response.headers[key] = val);
      } else {
        _results.push(void 0);
      }
    }
    return _results;
  };
  copyBody = function() {
    response.type = xhr.responseType;
    response.text = xhr.responseText;
    response.data = xhr.response || response.text;
    return response.xml = xhr.responseXML;
  };
  currentState = 0;
  setReadyState = function(n) {
    var fire, hooks, process;
    extractProps();
    fire = function() {
      while (n > currentState && currentState < 4) {
        face[READY_STATE] = ++currentState;
        if (currentState === 2) {
          readyHead();
        }
        if (currentState === 4) {
          readyBody();
        }
        faceEvents.fire("readystatechange");
        if (currentState === 4) {
          faceEvents.fire("load");
        }
      }
    };
    if (n < 4) {
      return fire();
    }
    hooks = pluginEvents.listeners(AFTER);
    process = function() {
      var hook;
      if (!hooks.length) {
        return fire();
      }
      hook = hooks.shift();
      if (hook.length === 2) {
        hook(request, response);
        return process();
      } else if (hook.length === 3) {
        return hook(request, response, process);
      } else {
        throw INVALID_PARAMS_ERROR;
      }
    };
    process();
  };
  checkEvent = function(e) {
    var clone, key, val;
    clone = {};
    for (key in e) {
      val = e[key];
      clone[key] = val === xhr ? face : val;
    }
    return clone;
  };
  extractProps = function() {
    var fn, key, _i, _len, _ref;
    _ref = ['timeout'];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      key = _ref[_i];
      if (xhr[key] && request[key] === undefined) {
        request[key] = xhr[key];
      }
    }
    for (key in face) {
      fn = face[key];
      if (typeof fn === 'function' && /^on(\w+)/.test(key)) {
        faceEvents.on(RegExp.$1, fn);
      }
    }
  };
  xhr.onreadystatechange = function(event) {
    try {
      if (xhr[READY_STATE] === 2) {
        copyHead();
        setReadyState(2);
      }
    } catch (_error) {}
    if (xhr[READY_STATE] === 4) {
      transiting = false;
      copyHead();
      copyBody();
      setReadyState(4);
    }
  };
  _ref = ['abort', 'progress'];
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
    event = _ref[_i];
    xhr["on" + event] = function(obj) {
      return faceEvents.fire(event, checkEvent(obj));
    };
  }
  face = {
    withCredentials: false,
    response: null,
    status: 0
  };
  face.addEventListener = function(event, fn) {
    return faceEvents.on(event, fn);
  };
  face.removeEventListener = faceEvents.off;
  face.dispatchEvent = function() {};
  face.open = function(method, url, async) {
    request.method = method;
    request.url = url;
    request.async = async;
    setReadyState(1);
  };
  face.send = function(body) {
    var hooks, process, send;
    request.body = body;
    send = function() {
      var header, value, _ref1;
      response = {
        headers: {}
      };
      transiting = true;
      xhr.open(request.method, request.url, request.async);
      if (request.timeout) {
        xhr.timeout = request.timeout;
      }
      _ref1 = request.headers;
      for (header in _ref1) {
        value = _ref1[header];
        xhr.setRequestHeader(header, value);
      }
      xhr.send(request.body);
    };
    hooks = pluginEvents.listeners(BEFORE);
    process = function() {
      var done, hook;
      if (!hooks.length) {
        return send();
      }
      done = function(resp) {
        if (typeof resp === 'object' && typeof resp.status === 'number') {
          response = resp;
          setReadyState(4);
        } else {
          return process();
        }
      };
      hook = hooks.shift();
      if (hook.length === 1) {
        return done(hook(request));
      } else if (hook.length === 2) {
        return hook(request, done);
      } else {
        throw INVALID_PARAMS_ERROR;
      }
    };
    process();
  };
  face.abort = function() {
    if (transiting) {
      xhr.abort();
    }
    faceEvents.fire('abort', arguments);
  };
  face.setRequestHeader = function(header, value) {
    request.headers[header] = value;
  };
  face.getResponseHeader = function(header) {
    return response.headers[header];
  };
  face.getAllResponseHeaders = function() {
    return convertHeaders(response.headers);
  };
  face.upload = EventEmitter();
  return face;
};

window.xhook = xhook;
}(window,document));


text:
#ifndef _asn_oid_h_
#define _asn_oid_h_

#include "asn_octs.h"

typedef AsnOcts AsnOid;  /* standard oid type  */

#define ASNOID_PRESENT(aoid) ASNOCTS_PRESENT(aoid)

AsnLen BEncAsnOid PROTO((BUF_TYPE b, AsnOid* data));

void BDecAsnOid PROTO((BUF_TYPE b, AsnOid* result, AsnLen* bytesDecoded,
                       ENV_TYPE env));

#define BEncAsnOidContent(b, oid)   BEncAsnOctsContent(b, oid)

void BDecAsnOidContent PROTO((BUF_TYPE b,
                            AsnTag tag,
                            AsnLen len,
                            AsnOid*  result,
                            AsnLen* bytesDecoded,
                            ENV_TYPE env));

#define FreeAsnOid FreeAsnOcts

void PrintAsnOid PROTO((FILE* f, AsnOid* b, unsigned short int indent));

#define AsnOidsEquiv(o1, o2) AsnOctsEquiv(o1, o2)

/* linked oid type that may be easier to use in some circumstances */
#define NULL_OID_ARCNUM -1
typedef struct OID
{
    struct OID* next;
    long int arcNum;
} OID;

AsnLen EncodedOidLen PROTO((OID* oid));

void BuildEncodedOid PROTO( (OID* oid, AsnOid* result));

void UnbuildEncodedOid PROTO( (AsnOid* eoid, OID** result));

#endif /* conditional include */


text:
Ripley.TabBar = function ( callback ) {

    this.constructor = Ripley.TabBar;

    Ripley.Panel.call( this, callback );

}

Ripley.TabBar.name = 'TabBar';

Ripley.TabBar.class = 'TabBar';

Ripley.TabBar.ulStyle = {
    listStyle: 'none',
    padding: 0,
    margin: 0
};

Ripley.TabBar.prototype = Object.create( Ripley.Panel.prototype );

Ripley.TabBar.prototype.__init = function () {

    this.ul = new Ripley.Ul();
    this.element.appendChild( this.ul );

    this.ul.setStyles( this.constructor.ulStyle );

}

Ripley.TabBar.prototype.addTab = function ( tab, callback ) {

    if ( typeof( tab ) == 'string' ) tab = new Ripley.Tab( tab );

    tab.onClick( function () { } );
    this.addChild( tab );
    this.ul.appendChild( tab.element );

    var scope = this;
    tab.onClick( function () {

        var active = scope.activeTab();
        if ( active !== undefined ) active.setInactive();
        tab.setActive();

    } );

    this.element.appendChild( tab.buttonView.element );

    if ( callback !== undefined ) callback( tab );

}

Ripley.TabBar.prototype.tab = function ( name ) {

    return this._findTab( 'name', name );

}

Ripley.TabBar.prototype.activeTab = function () {

    return this._findTab( 'active', true );

}

Ripley.TabBar.prototype.setActive = function ( arg ) {

    if ( typeof arg == "number" ) {

        this.children[ arg ].setActive();

    } else if ( typeof arg == "string" ) {

        this.tab( arg ).setActive();

    } else if ( arg instanceof Ripley.Tab ) {

        arg.setActive();

    } else {

        throw "Unsupported argument type: " + typeof arg;

    }

}

Ripley.TabBar.prototype._findTab = function ( key, value ) {

    for ( i = 0; i < this.children.length; i ++ ) {

        var child = this.children[ i ];

        if ( ! ( child instanceof Ripley.Tab ) ) continue;

        var match = false;

        if ( typeof child[ key ] == 'function' ) {

            match = child[ key ]() == value;

        } else {

            match = child[ key ] == value;

        }

        if ( match ) return child;

    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>no.nordicsemi.android.error</title>
<meta name="date" content="2015-07-22">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

no.nordicsemi.android.error

Classes

GattError


text:
.class Lcom/android/systemui/statusbar/policy/KeyguardMonitorImpl$1;
.super Lcom/android/systemui/settings/CurrentUserTracker;
.source "KeyguardMonitorImpl.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/systemui/statusbar/policy/KeyguardMonitorImpl;-><init>(Landroid/content/Context;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/systemui/statusbar/policy/KeyguardMonitorImpl;

# direct methods
.method constructor <init>(Lcom/android/systemui/statusbar/policy/KeyguardMonitorImpl;Landroid/content/Context;)V
    .locals 0

    iput-object p1, p0, Lcom/android/systemui/statusbar/policy/KeyguardMonitorImpl$1;->this$0:Lcom/android/systemui/statusbar/policy/KeyguardMonitorImpl;

    invoke-direct {p0, p2}, Lcom/android/systemui/settings/CurrentUserTracker;-><init>(Landroid/content/Context;)V

    return-void
.end method

# virtual methods
.method public onUserSwitched(I)V
    .locals 1

    iget-object v0, p0, Lcom/android/systemui/statusbar/policy/KeyguardMonitorImpl$1;->this$0:Lcom/android/systemui/statusbar/policy/KeyguardMonitorImpl;

    invoke-static {v0, p1}, Lcom/android/systemui/statusbar/policy/KeyguardMonitorImpl;->-set0(Lcom/android/systemui/statusbar/policy/KeyguardMonitorImpl;I)I

    iget-object v0, p0, Lcom/android/systemui/statusbar/policy/KeyguardMonitorImpl$1;->this$0:Lcom/android/systemui/statusbar/policy/KeyguardMonitorImpl;

    invoke-static {v0}, Lcom/android/systemui/statusbar/policy/KeyguardMonitorImpl;->-wrap0(Lcom/android/systemui/statusbar/policy/KeyguardMonitorImpl;)V

    return-void
.end method


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class main.java.utilities.ListMerger</title>
<meta name="date" content="2015-02-21">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
main.java.utilities.ListMerger

Packages that use ListMerger

Package
Description

main.java.utilities

Uses of ListMerger in main.java.utilities

Subclasses of ListMerger in main.java.utilities

Modifier and Type
Class and Description

class
ListMergerWithLogicalNot

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
package com.amazonaws.services.outposts.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.outposts.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * GetOutpostInstanceTypesResult JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetOutpostInstanceTypesResultJsonUnmarshaller implements Unmarshaller<GetOutpostInstanceTypesResult, JsonUnmarshallerContext> {

    public GetOutpostInstanceTypesResult unmarshall(JsonUnmarshallerContext context) throws Exception {
        GetOutpostInstanceTypesResult getOutpostInstanceTypesResult = new GetOutpostInstanceTypesResult();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return getOutpostInstanceTypesResult;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("InstanceTypes", targetDepth)) {
                    context.nextToken();
                    getOutpostInstanceTypesResult.setInstanceTypes(new ListUnmarshaller<InstanceTypeItem>(InstanceTypeItemJsonUnmarshaller.getInstance())

                    .unmarshall(context));
                }
                if (context.testExpression("NextToken", targetDepth)) {
                    context.nextToken();
                    getOutpostInstanceTypesResult.setNextToken(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("OutpostId", targetDepth)) {
                    context.nextToken();
                    getOutpostInstanceTypesResult.setOutpostId(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("OutpostArn", targetDepth)) {
                    context.nextToken();
                    getOutpostInstanceTypesResult.setOutpostArn(context.getUnmarshaller(String.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return getOutpostInstanceTypesResult;
    }

    private static GetOutpostInstanceTypesResultJsonUnmarshaller instance;

    public static GetOutpostInstanceTypesResultJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new GetOutpostInstanceTypesResultJsonUnmarshaller();
        return instance;
    }
}


text:
package stray.blocks;

import java.util.HashMap;

import stray.LevelEditor.EditorGroup;
import stray.Main;
import stray.Settings;
import stray.entity.Entity;
import stray.util.AssetMap;
import stray.util.MathHelper;
import stray.util.Utils;
import stray.world.World;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;

public class Block {

	/**
	 *
	 * @param path
	 *            actual path; omit .png!
	 */
	public Block(String path) {
		this.path = path;
	}

	public static final int globalMagicNumber = Main.getRandom().nextInt();

	protected boolean connectedTextures = false;
	protected boolean variants = false;
	protected String animationlink = null;
	protected int varianttypes = 4;
	protected int solidFaces = BlockFaces.NONE;
	protected boolean usingMissingTex = false;

	public EditorGroup levelEditorGroup = EditorGroup.NORMAL;

	public void tickUpdate(World world, int x, int y) {

	}

	public float getDragCoefficient(World world, int x, int y) {
		return 1;
	}

	public boolean isRenderedFront() {
		return false;
	}

	public Block solidify(int faces) {
		solidFaces = faces;
		return this;
	}

	public void onCollideLeftFace(World world, int x, int y, Entity e) {

	}

	public void onCollideRightFace(World world, int x, int y, Entity e) {

	}

	public void onCollideUpFace(World world, int x, int y, Entity e) {

	}

	public void onCollideDownFace(World world, int x, int y, Entity e) {

	}

	public int isSolid(World world, int x, int y) {
		return solidFaces;
	}

	public String getAnimation() {
		return animationlink;
	}

	public Block setAnimation(String animationlink) {
		this.animationlink = animationlink;
		return this;
	}

	public void dispose() {

	}

	public int getTickRate() {
		return 1;
	}

	/**
	 * turns off connected textures too
	 *
	 * @return itself for chaining
	 */
	public Block hasVariants(int types) {
		variants = true;
		varianttypes = types;
		connectedTextures = false;
		return this;
	}

	public Block useConTextures() {
		connectedTextures = true;

		return this;
	}

	public Block setEditorGroup(EditorGroup i) {
		levelEditorGroup = i;
		return this;
	}

	public void addTextures(Main main) {
		if (path == null) return;

		if (animationlink != null) {
			// assumes animation is loaded already
			return;
		}

		if (!connectedTextures) {
			if (!Gdx.files.internal(path + ".png").exists() && !variants) {
				Main.logger.warn("WARNING: a block has no texture (" + path
						+ ".png); using missing texture");
				connectedTextures = false;
				variants = false;
				usingMissingTex = true;

				return;
			}
		} else {
			if (!Gdx.files.internal(path + "-full.png").exists() && !variants) {
				Main.logger.warn("WARNING: a block has no \"full\" texture (" + path
						+ ".png); using missing texture");
				connectedTextures = false;
				variants = false;
				usingMissingTex = true;

				return;
			}
		}
		if (!connectedTextures) {
			if (!variants) {
				main.manager.load(path + ".png", Texture.class);
			} else {
				for (int i = 0; i < varianttypes; i++) {
					main.manager.load(path + i + ".png", Texture.class);
				}
			}
		} else {

			main.manager.load(path + "-full.png", Texture.class);
			main.manager.load(path + "-corner.png", Texture.class);
			main.manager.load(path + "-edgehor.png", Texture.class);
			main.manager.load(path + "-edgever.png", Texture.class);
		}

	}

	public void postLoad(Main main) {
		sprites = new HashMap<String, String>();
		if (animationlink != null) return;
		if (path == null) return;
		if (usingMissingTex) return;
		if (connectedTextures) {

			sprites.put("full", path + "-full.png");
			sprites.put("corner", path + "-corner.png");
			sprites.put("edgehor", path + "-edgehor.png");
			sprites.put("edgever", path + "-edgever.png");
		} else {
			if (!variants) {
				sprites.put("defaulttex", path + ".png");
			} else {
				for (int i = 0; i < varianttypes; i++) {
					sprites.put("defaulttex" + i, path + i + ".png");
				}
			}
		}
	}

	// protected void drawAt(Batch batch, Texture sprite, float f, float g) {
	// batch.draw(sprite, f, Main.convertY(g + World.tilesizey),
	// World.tilesizex, World.tilesizey);
	// }

	/**
	 * only used for connected textures connected: full, corner, edgehor,
	 * edgever
	 */
	protected HashMap<String, String> sprites;

	protected String path = "";

	private int getVarFromTime() {

		int time = (MathHelper.getNthDigit(System.currentTimeMillis(), 1))
				+ (MathHelper.getNthDigit(System.currentTimeMillis(), 2) * 10)
				+ (MathHelper.getNthDigit(System.currentTimeMillis(), 3) * 100)
				+ (MathHelper.getNthDigit(System.currentTimeMillis(), 4) * 1000);
		// 10k
		return ((int) time / (10000 / varianttypes));
	}

	// /**
	// * topleft origin!
	// *
	// * @param batch
	// * @param x
	// * @param y
	// */
	// public void renderModel(World world, int x, int y) {
	// Batch batch = world.batch;
	// if (path == null) return;
	// if (usingMissingTex) {
	// batch.draw(world.main.manager.get(AssetMap.get("blockmissingtexture"),
	// Texture.class),
	// x, Main.convertY(y + World.tilesizey), World.tilesizex, World.tilesizey);
	// return;
	// }
	//
	// if (animationlink != null) {
	// batch.draw(world.main.animations.get(animationlink).getCurrentFrame(), x,
	// Main.convertY(y + World.tilesizey), World.tilesizex, World.tilesizey);
	// return;
	// }
	//
	// if (!connectedTextures) {
	// if (!variants) {
	// drawAt(batch, world.main.manager.get(sprites.get("defaulttex"),
	// Texture.class), x,
	// y);
	// } else {
	// drawAt(batch, world.main.manager.get(sprites.get("defaulttex" +
	// getVarFromTime()),
	// Texture.class), x, y);
	// }
	// } else {
	// drawAt(batch, world.main.manager.get(sprites.get("full"), Texture.class),
	// x, y);
	// }
	// }

	public static int variantNum(World world, int x, int y) {
		return variantNum(world.msTime, x, y);
	}

	public static int variantNum(long magic, int x, int y) {
		return ((int) ((magic + (x + 17) * (y + 53) * 214013L + 2531011L) >> 16) & 0x7fff);
	}

	public static int variantNum(int x, int y) {
		return variantNum(Block.globalMagicNumber, x, y);
	}

	// public void renderPlain(Main main, float camerax, float cameray, int x,
	// int y, int magic) {
	// if (animationlink != null) {
	// main.batch.draw(main.animations.get(animationlink).getCurrentFrame(), x
	// * World.tilesizex - camerax, y * World.tilesizey - cameray,
	// World.tilesizex,
	// World.tilesizey);
	// return;
	// }
	//
	// if (usingMissingTex) {
	// main.batch.draw(main.manager.get(AssetMap.get("blockmissingtexture"),
	// Texture.class), x
	// * World.tilesizex - camerax, y * World.tilesizey - cameray,
	// World.tilesizex,
	// World.tilesizey);
	// return;
	// }
	//
	// if (path == null) return;
	//
	// if (!connectedTextures) {
	// if (!variants) {
	// drawAt(main.batch, main.manager.get(sprites.get("defaulttex"),
	// Texture.class), x
	// * World.tilesizex - camerax, y * World.tilesizey - cameray);
	// } else {
	// drawAt(main.batch, main.manager.get(sprites.get("defaulttex"
	// + ((variantNum(magic, x, y)) & (varianttypes - 1))), Texture.class), x
	// * World.tilesizex - camerax, y * World.tilesizey - cameray);
	// }
	// } else {
	// drawAt(main.batch, main.manager.get(sprites.get("full"), Texture.class),
	// x
	// * World.tilesizex - camerax, y * World.tilesizey - cameray);
	//
	// }
	// }

	public void render(World world, int x, int y) {
		renderWithOffset(world, x, y, 0, 0);
	}

	public void renderWithOffset(World world, int x, int y, float offx, float offy) {
		if (usingMissingTex) {
			world.batch.draw(
					world.main.manager.get(AssetMap.get("blockmissingtexture"), Texture.class),
					x * world.tilesizex - world.camera.camerax + offx,
					Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey
							+ offy));
			return;
		}
		if (animationlink != null) {
			world.batch.draw(
					world.main.animations.get(animationlink).getCurrentFrame(),
					x * world.tilesizex - world.camera.camerax + offx,
					Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey
							+ offy));
			return;
		}
		if (path == null) return;

		if (!connectedTextures) {
			if (!variants) {
				world.batch.draw(
						world.main.manager.get(sprites.get("defaulttex"), Texture.class),
						x * world.tilesizex - world.camera.camerax + offx,
						Main.convertY((y * world.tilesizey - world.camera.cameray)
								+ World.tilesizey + offy));
			} else {
				world.batch.draw(world.main.manager.get(sprites.get("defaulttex"
						+ ((variantNum(world, x, y)) & (varianttypes - 1))), Texture.class), x
						* world.tilesizex - world.camera.camerax + offx, Main.convertY((y
						* world.tilesizey - world.camera.cameray)
						+ World.tilesizey + offy));
			}
		} else {
			drawConnectedTexture(world, x, y, offx, offy,
					world.main.manager.get(sprites.get("corner"), Texture.class),
					world.main.manager.get(sprites.get("full"), Texture.class),
					world.main.manager.get(sprites.get("edgever"), Texture.class),
					world.main.manager.get(sprites.get("edgehor"), Texture.class));
		}
	}

	public void drawConnectedTexture(World world, int x, int y, float offx, float offy,
			Texture corner, Texture full, Texture ver, Texture hor) {
		boolean up, down, left, right;
		up = world.getBlock(x, y - 1) == this;
		down = world.getBlock(x, y + 1) == this;
		left = world.getBlock(x - 1, y) == this;
		right = world.getBlock(x + 1, y) == this;

		if (up && down && left && right) {
			if (world.getBlock(x + 1, y + 1) != this || world.getBlock(x + 1, y - 1) != this
					|| world.getBlock(x - 1, y + 1) != this || world.getBlock(x - 1, y - 1) != this) {
				world.batch.draw(
						corner,
						x * world.tilesizex - world.camera.camerax + offx,
						Main.convertY((y * world.tilesizey - world.camera.cameray)
								+ World.tilesizey + offy));
			} else world.batch.draw(
					full,
					x * world.tilesizex - world.camera.camerax + offx,
					Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey
							+ offy));
		} else if (up && down && (left == false || right == false)) {
			world.batch.draw(
					ver,
					x * world.tilesizex - world.camera.camerax + offx,
					Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey
							+ offy));
		} else if (left && right && (up == false || down == false)) {
			world.batch.draw(
					hor,
					x * world.tilesizex - world.camera.camerax + offx,
					Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey
							+ offy));
		} else {
			world.batch.draw(
					corner,
					x * world.tilesizex - world.camera.camerax + offx,
					Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey
							+ offy));
		}
	}

	public void drawConnectedTexture(World world, int x, int y, float offx, float offy,
			TextureRegion corner, TextureRegion full, TextureRegion ver, TextureRegion hor) {
		boolean up, down, left, right;
		up = world.getBlock(x, y - 1) == this;
		down = world.getBlock(x, y + 1) == this;
		left = world.getBlock(x - 1, y) == this;
		right = world.getBlock(x + 1, y) == this;

		if (up && down && left && right) {
			if (world.getBlock(x + 1, y + 1) != this || world.getBlock(x + 1, y - 1) != this
					|| world.getBlock(x - 1, y + 1) != this || world.getBlock(x - 1, y - 1) != this) {
				world.batch.draw(
						corner,
						x * world.tilesizex - world.camera.camerax + offx,
						Main.convertY((y * world.tilesizey - world.camera.cameray)
								+ World.tilesizey));
			} else world.batch.draw(
					full,
					x * world.tilesizex - world.camera.camerax + offx,
					Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey
							+ offy));
		} else if (up && down && (left == false || right == false)) {
			world.batch.draw(
					ver,
					x * world.tilesizex - world.camera.camerax + offx,
					Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey
							+ offy));
		} else if (left && right && (up == false || down == false)) {
			world.batch.draw(
					hor,
					x * world.tilesizex - world.camera.camerax + offx,
					Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey
							+ offy));
		} else {
			world.batch.draw(
					corner,
					x * world.tilesizex - world.camera.camerax + offx,
					Main.convertY((y * world.tilesizey - world.camera.cameray) + World.tilesizey
							+ offy));
		}
	}

	// protected void drawAt(SpriteBatch batch, TextureRegion corner, float f,
	// float g) {
	// batch.draw(corner, f, Main.convertY(g + World.tilesizey),
	// World.tilesizex, World.tilesizey);
	// }

	public static boolean isEntityNear(World world, int x, int y, int rad, Class<?> cls) {
		for (int i = 0; i < world.entities.size; i++) {
			Entity e = world.entities.get(i);
			if (!(cls.isInstance(e))) continue;
			if (MathHelper.intersects(e.x, e.y, e.sizex, e.sizey, x - rad + 1, y - rad + 1,
					rad * 2 - 1, rad * 2 - 1)) return true;
		}

		return false;
	}

	public static Entity getNearestEntity(World world, int x, int y, int rad, Class<?> cls) {
		if (isEntityNear(world, x, y, rad, cls)) {
			for (int i = 0; i < world.entities.size; i++) {
				Entity e = world.entities.get(i);
				if (!(cls.isInstance(e))) continue;
				if (MathHelper.intersects(e.x, e.y, e.sizex, e.sizey, x - rad + 1, y - rad + 1,
						rad * 2 - 1, rad * 2 - 1)) return e;
			}
		}

		return null;
	}

	public static boolean entityIntersects(World world, double x, double y, Entity e) {
		return entityIntersects(world, x, y, e, 1, 1);
	}

	public static boolean entityIntersects(World world, double x, double y, Entity e, double sizex,
			double sizey) {
		if (e == null) return false;
		return MathHelper.intersects(x, y, sizex, sizey, e.x, e.y, e.sizex, e.sizey);
	}

	public static boolean isBlockVisible(float camx, float camy, int x, int y) {
		return MathHelper.intersects(x * World.tilesizex, y * World.tilesizey, World.tilesizex,
				World.tilesizey, camx, camy, Settings.DEFAULT_WIDTH, Gdx.graphics.getHeight());
	}

	public static boolean playSound(int x, int y, float camx, float camy, Sound sound, float vol,
			float pitch, boolean mustbevisible) {
		if (!Block.isBlockVisible(camx, camy, x, y) && mustbevisible) return false;
		sound.play(vol * Settings.soundVolume, pitch, Utils.getSoundPan(x, camx));
		return true;
	}

	public static boolean playSound(int x, int y, float camx, float camy, Sound sound, float vol,
			float pitch) {
		return playSound(x, y, camx, camy, sound, vol, pitch, true);
	}

	public static class BlockFaces {

		public static final int NONE = 0x0;
		public static final int ALL = 0xF;
		public static final int UP = 0x1;
		public static final int DOWN = 0x2;
		public static final int LEFT = 0x4;
		public static final int RIGHT = 0x8;

	}

}


text:
package functry;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 *
 *
 * @author Malte Nottmeyer
 */
public class TryRunRecoveringTest extends FuncTryTest {

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {}

	@Before
	public void setUp() throws Exception {}

	@After
	public void tearDown() throws Exception {}

	@Test
	public void testRecoverTryRun() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testRecoverRunRunnable() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testRecoverRunConsumerOfQsuperThrowable() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testRecoverTryTryRunnable() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testRecoverTryTryRunnableFinallyOfVoid() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testRecoverTryTryConsumerOfQsuperThrowable() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testRecoverTryTryConsumerOfQsuperThrowableFinallyOfVoid() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testRecoverGetTrySupplierOfTryRun() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testRecoverGetTryFunctionOfQsuperThrowableTryRun() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testRecoverClassOfETryRun() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testRecoverRunClassOfERunnable() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testRecoverRunClassOfEConsumerOfQsuperThrowable() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testRecoverTryClassOfETryRunnable() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testRecoverTryClassOfETryRunnableFinallyOfVoid() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testRecoverTryClassOfETryConsumerOfQsuperThrowable() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testRecoverTryClassOfETryConsumerOfQsuperThrowableFinallyOfVoid() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testRecoverGetTryClassOfESupplierOfTryRun() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testRecoverGetTryClassOfEFunctionOfQsuperThrowableTryRun() {
		fail("Not yet implemented"); // TODO
	}

}


text:
default['bosun']['init_style']      = 'runit'
default['bosun']['install_style']   = 'binary' # binary or source

default['bosun']['tsdb_host']       = '127.0.0.1'
default['bosun']['tsdb_port']       = '4242'

default['bosun']['conf_dir']        = '/etc/bosun'
default['bosun']['log_dir']         = '/var/log/bosun'
default['bosun']['open_files']      = 65_535
default['bosun']['install_path']    = '/usr/local/bin/bosun'

default['bosun']['config_cookbook'] = 'bosun'

# Installation source

default['bosun']['release_url'] = 'https://github.com/bosun-monitor/bosun/releases/download'
default['bosun']['version'] = '0.4.0'


text:
import "reflect-metadata";

import { createHashHistory, History } from "history";
import { Container } from "inversify";
import getDecorators from "inversify-inject-decorators";
import { Translator } from "readium-desktop/common/services/translator";
import {
    diRendererSymbolTable as diSymbolTable,
} from "readium-desktop/renderer/library/diSymbolTable";
import { ILibraryRootState } from "readium-desktop/renderer/library/redux/states";
import { initStore } from "readium-desktop/renderer/library/redux/store/memory";
import { Store } from "redux";

import App from "./components/App";
import { IRouterLocationState } from "./routing";

// Create container used for dependency injection
const container = new Container();

// Create store
const history: History<IRouterLocationState> = createHashHistory();
container.bind<History>(diSymbolTable.history).toConstantValue(history);

const store = initStore(history);
container.bind<Store<ILibraryRootState>>(diSymbolTable.store).toConstantValue(store);

// Create translator
const translator = new Translator();
container.bind<Translator>(diSymbolTable.translator).toConstantValue(translator);

container.bind<typeof App>(diSymbolTable["react-library-app"]).toConstantValue(App);

// local interface to force type return
interface IGet {
    (s: "history"): History;
    (s: "store"): Store<ILibraryRootState>;
    (s: "translator"): Translator;
    (s: "react-library-app"): typeof App;
}

// export function to get back depedency from container
// the type any for container.get is overloaded by IGet
const diGet: IGet = (symbol: keyof typeof diSymbolTable) => container.get<any>(diSymbolTable[symbol]);

const {
    lazyInject,
    lazyInjectNamed,
    lazyInjectTagged,
    lazyMultiInject,
} = getDecorators(container);

export {
    diGet as diLibraryGet,
    lazyInject,
    lazyInjectNamed,
    lazyInjectTagged,
    lazyMultiInject,
};


text:
Listeners
=========

.. automodule:: pymco.listener
   :members: