text:
namespace NPOI.SS.Formula
{

    using System;
    using System.Text;
    using System.Collections;
    using System.Collections.Generic;
    using NPOI.SS.UserModel;

    [Serializable]
    public class WorkbookNotFoundException : Exception
    {
        public WorkbookNotFoundException(String msg):base(msg)
        {

        }
    }
    /**
     * Manages a collection of {@link WorkbookEvaluator}s, in order To support evaluation of formulas
     * across spreadsheets.<p/>
     *
     * For POI internal use only
     *
     * @author Josh Micich
     */
    public class CollaboratingWorkbooksEnvironment
    {
        public static readonly CollaboratingWorkbooksEnvironment EMPTY = new CollaboratingWorkbooksEnvironment();

        private Dictionary<String, WorkbookEvaluator> _evaluatorsByName;
        private WorkbookEvaluator[] _evaluators;

        private bool _unhooked;
        private CollaboratingWorkbooksEnvironment()
        {
            _evaluatorsByName = new Dictionary<String, WorkbookEvaluator>();
            _evaluators = new WorkbookEvaluator[0];
        }
        public static void Setup(String[] workbookNames, WorkbookEvaluator[] evaluators)
        {
            int nItems = workbookNames.Length;
            if (evaluators.Length != nItems)
            {
                throw new ArgumentException("Number of workbook names is " + nItems
                        + " but number of evaluators is " + evaluators.Length);
            }
            if (nItems < 1)
            {
                throw new ArgumentException("Must provide at least one collaborating worbook");
            }
            CollaboratingWorkbooksEnvironment env = new CollaboratingWorkbooksEnvironment(workbookNames, evaluators, nItems);
            HookNewEnvironment(evaluators, env);
        }
        public static void Setup(Dictionary<String, WorkbookEvaluator> evaluatorsByName)
        {
            if (evaluatorsByName.Count < 1)
            {
                throw new  ArgumentException("Must provide at least one collaborating worbook");
            }
            List<WorkbookEvaluator> temp = new List<WorkbookEvaluator>(evaluatorsByName.Count);
            temp.AddRange(evaluatorsByName.Values);
            WorkbookEvaluator[] evaluators = temp.ToArray();
            new CollaboratingWorkbooksEnvironment(evaluatorsByName, evaluators);
        }
        public static void SetupFormulaEvaluator(Dictionary<String, IFormulaEvaluator> evaluators)
        {
            Dictionary<String, WorkbookEvaluator> evaluatorsByName = new Dictionary<String, WorkbookEvaluator>(evaluators.Count);
            foreach (KeyValuePair<string, IFormulaEvaluator> swb in evaluators)
            {
                string wbName = swb.Key;
                IFormulaEvaluator eval = swb.Value;
                if (eval is IWorkbookEvaluatorProvider)
                {
                    evaluatorsByName.Add(wbName, ((IWorkbookEvaluatorProvider)eval).GetWorkbookEvaluator());
                }
                else
                {
                    throw new ArgumentException("Formula Evaluator " + eval +
                                                       " provides no WorkbookEvaluator access");
                }
            }
            Setup(evaluatorsByName);
        }
        private CollaboratingWorkbooksEnvironment(String[] workbookNames, WorkbookEvaluator[] evaluators, int nItems)
            : this(ToUniqueMap(workbookNames, evaluators, nItems), evaluators)
        {

        }
        private static Dictionary<String, WorkbookEvaluator> ToUniqueMap(String[] workbookNames, WorkbookEvaluator[] evaluators, int nItems)
        {
            Dictionary<String, WorkbookEvaluator> evaluatorsByName = new Dictionary<String, WorkbookEvaluator>(nItems * 3 / 2);
            for (int i = 0; i < nItems; i++)
            {
                String wbName = workbookNames[i];
                WorkbookEvaluator wbEval = evaluators[i];
                if (evaluatorsByName.ContainsKey(wbName))
                {
                    throw new ArgumentException("Duplicate workbook name '" + wbName + "'");
                }
                evaluatorsByName.Add(wbName, wbEval);
            }
            return evaluatorsByName;
        }
        private CollaboratingWorkbooksEnvironment(Dictionary<String, WorkbookEvaluator> evaluatorsByName, WorkbookEvaluator[] evaluators)
        {
            Dictionary<WorkbookEvaluator, String> uniqueEvals = new Dictionary<WorkbookEvaluator, String>(evaluators.Length);
            foreach (KeyValuePair<string, WorkbookEvaluator> me in evaluatorsByName)
            {
                if (uniqueEvals.ContainsKey(me.Value))
                {
                    String msg = "Attempted to register same workbook under names '" +
                        uniqueEvals[me.Value] + "' and '" + me.Key + "'";
                    throw new ArgumentException(msg);
                }
                uniqueEvals.Add(me.Value, me.Key);
            }
            UnhookOldEnvironments(evaluators);
            HookNewEnvironment(evaluators, this);
            _unhooked = false;
            _evaluators = (WorkbookEvaluator[])evaluators.Clone();
            _evaluatorsByName = evaluatorsByName;
        }

        private static void HookNewEnvironment(WorkbookEvaluator[] evaluators, CollaboratingWorkbooksEnvironment env)
        {

            // All evaluators will need To share the same cache.
            // but the cache takes an optional evaluation listener.
            int nItems = evaluators.Length;
            IEvaluationListener evalListener = evaluators[0].GetEvaluationListener();
            // make sure that all evaluators have the same listener
            for (int i = 0; i < nItems; i++)
            {
                if (evalListener != evaluators[i].GetEvaluationListener())
                {
                    // This would be very complex To support
                    throw new Exception("Workbook evaluators must all have the same evaluation listener");
                }
            }
            EvaluationCache cache = new EvaluationCache(evalListener);

            for (int i = 0; i < nItems; i++)
            {
                evaluators[i].AttachToEnvironment(env, cache, i);
            }

        }
        private void UnhookOldEnvironments(WorkbookEvaluator[] evaluators)
        {
            ArrayList oldEnvs = new ArrayList();
            for (int i = 0; i < evaluators.Length; i++)
            {
                oldEnvs.Add(evaluators[i].GetEnvironment());
            }
            CollaboratingWorkbooksEnvironment[] oldCWEs = new CollaboratingWorkbooksEnvironment[oldEnvs.Count];
            oldCWEs = (CollaboratingWorkbooksEnvironment[])oldEnvs.ToArray(typeof(CollaboratingWorkbooksEnvironment));
            for (int i = 0; i < oldCWEs.Length; i++)
            {
                oldCWEs[i].Unhook();
            }
        }

        /**
         *
         */
        private void Unhook()
        {
            if (_evaluators.Length < 1)
            {
                return;
            }
            for (int i = 0; i < _evaluators.Length; i++)
            {
                _evaluators[i].DetachFromEnvironment();
            }
            _unhooked = true;
        }

        public WorkbookEvaluator GetWorkbookEvaluator(String workbookName)
        {
            if (_unhooked)
            {
                throw new InvalidOperationException("This environment Has been unhooked");
            }
            WorkbookEvaluator result;
            if (_evaluatorsByName.ContainsKey(workbookName))
            {
                result = (WorkbookEvaluator)_evaluatorsByName[workbookName];
            }
            else
            {
                StringBuilder sb = new StringBuilder(256);
                sb.Append("Could not resolve external workbook name '").Append(workbookName).Append("'.");
                if (_evaluators.Length < 1)
                {
                    sb.Append(" Workbook environment has not been set up.");
                }
                else
                {
                    sb.Append(" The following workbook names are valid: (");
                    IEnumerator i = _evaluatorsByName.Keys.GetEnumerator();
                    int count = 0;
                    while (i.MoveNext())
                    {
                        if (count++ > 0)
                        {
                            sb.Append(", ");
                        }
                        sb.Append("'").Append(i.Current).Append("'");
                    }
                    sb.Append(")");
                }
                throw new WorkbookNotFoundException(sb.ToString());
            }
            return result;
        }
    }
}


text:
function display(S)
% xini::display  - overloaded method
%
% displays the content of an xini object
%
% FORMAT:       display(IniFileObject)
%
% Input fields:
%
%       IniFileObject   object of which content should be displayed

% Version:  v0.9c
% Build:    11050218
% Date:     May-02 2011, 6:17 PM EST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://neuroelf.net/
%
% Copyright (c) 2010, 2011, Jochen Weber
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%     * Redistributions of source code must retain the above copyright
%       notice, this list of conditions and the following disclaimer.
%     * Redistributions in binary form must reproduce the above copyright
%       notice, this list of conditions and the following disclaimer in the
%       documentation and/or other materials provided with the distribution.
%     * Neither the name of Columbia University nor the
%       names of its contributors may be used to endorse or promote products
%       derived from this software without specific prior written permission.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
% ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
% DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
% DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
% (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
% ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

% for sizes check
num_h = numel(S);
isf = isxini(S);

% if we have output arguments
if num_h == 1
    if ~isf
        error( ...
            'xini:InvalidObject', ...
            'Cannot display information on invalid object.' ...
        );
    end
    disp(xini(S, 'display'));
else
    for hc = 1:num_h
        if ~isf(hc)
            continue;
        end
        disp('----------------------------------');
        try
            disp(xini(S(hc), 'getfilename'));
            dips(xini(S(hc), 'display'));
        catch ne_eo;
            rethrow(ne_eo);
        end
    end
end

redpajama_set_name: RedPajamaGithub


text:
__scVEGs__ is a novel algorithm for single-cell RNA-seq (scRNA-seq) data to determine significant variably expressed genes (VEGs) using a gene expression variation model (GEVM). It utilizes the relation between coefficient of variation (CV) and average expression level to address the over-dispersion of single-cell data, and its corresponding statistical significance to quantify the variably expressed genes. For more details about the algorithm , read the scVEGs paper that will be published in BMC genomics.

# Installation

scVEGs is a function in R that can be used by

```{r,eval=FALSE}
source("scVEGs.r")
```

In the future, scVEGs will be integrated with other tools for scRNA-seq to create an R package.

# Use scVEGs to determine significant variably expressed genes

In the R script __scVEGs_script.r__, it is an thorough example to detect VEGs using the function scVEGs.

First, import a data matrix that contains the UMI read count result of a single-cell RNA-seq data set. We have provided a data set __data_GSE65525__, which is obtained from Gene Expression Omnibus [(GSE65525)](http://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE65525 ). We also assign some cutoff criterions for detecting VEGs. For the species option, scVEGs calculates the transcripts per million (TPM) of the data and removes genes that have less than 1% of cells that TPM > 1. For now, we have provided the gene length information for __hg19__ (hg19_genes_length.tsv) and __mm9__ (mm9_genes_length.tsv). The filtering step will be skipped if species is assigned other than hsa or mmu.

```{r}
data <- read.delim('data_GSE65525.txt', header = TRUE, stringsAsFactors = TRUE)
rownames(data) <- data[, 1]
data <- data[, -1]
pVal <- 0.01		# p-value cutoff
pFlag <- 1			# pFlag: 1, use Benjamini adjusted p-value.  0: use raw p-value.
species <- 'mmu'	# Species of input data, hsa or mmu.
```

The following step is to do a scaling normalization across the data set. You can revise or skip this step as your preference.

```{r}
cellSum <- apply(data, 2, sum)
scaleNum <- mean(cellSum)/cellSum
scaleFactor <- t(kronecker( matrix(1, 1, dim(data)[1]), scaleNum))
normData <- scaleFactor * data
```

At last, we can execute the function scVEGs and export the detected significant VEGs.

```{r}
outputName <- 'result_GSE65525'
sig <- scVEGs(normData, pVal, pFlag, species, outputName)
write.table(sig, file = 'result_GSE65525_sig.txt', append = FALSE, quote = FALSE, sep = "\t", eol = "\n", na = "NA", dec = ".", row.names = TRUE, col.names = TRUE, qmethod = c("escape", "double"))
```

# Bug reports

Report bugs as issues on our [GitHub repository](https://github.com/hillas/scVEGs/issues) or you can report directly to my email: chenhh@uthscsa.edu.


text:
<?xml version='1.0' encoding='utf-8' ?>
<!DOCTYPE section PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
<!ENTITY % BOOK_ENTITIES SYSTEM "cloudstack.ent">
%BOOK_ENTITIES;
]>

<!-- Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
-->
<section id="prepare-system-vm-template">
  <title>Prepare the System VM Template</title>
  <para>Secondary storage must be seeded with a template that is used for &PRODUCT; system VMs.
    Citrix provides you with the necessary binary package of the system VM.</para>
  <note>
    <para>When copying and pasting a command, ensure that the command has pasted as a single line
      before executing. Some document viewers may introduce unwanted line breaks in copied
      text.</para>
  </note>
   <orderedlist>
    <listitem>
      <para>If you are using a separate NFS server, mount the secondary storage on your Management
        Server. Replace the example NFS server name and NFS share paths below with your own.</para>
      <programlisting># mount -t nfs nfsservername:/nfs/share/secondary /mnt/secondary</programlisting>
      <para>If your secondary storage mount point is not named /mnt/secondary, substitute your own
      mount point name.</para>
      </listitem>
    <listitem>
      <para>On the Management Server, run one or more of the following cloud-install-sys-tmplt
        commands to retrieve and decompress the system VM template. Run the command for each
        hypervisor type that you expect end users to run in this Zone.</para>
       <para>If you set the &PRODUCT; database encryption type to "web" when you set up the database,
        you must now add the parameter -s <management-server-secret-key>. See <xref
          linkend="about-password-encryption"/>.</para>
      <para>This process will require approximately 5 GB of free space on the local file system and
      up to 30 minutes each time it runs.</para>
       <itemizedlist>
        <listitem>
          <para>For XenServer:</para>
          <programlisting># /usr/lib64/cloud/common/scripts/storage/secondary/cloud-install-sys-tmplt -m /mnt/secondary -u http://download.cloud.com/templates/4.2/systemvmtemplate-2013-07-12-master-xen.vhd.bz2 -h xenserver -s <optional-management-server-secret-key> -F</programlisting>
        </listitem>
        <listitem>
          <para>For vSphere:</para>
          <programlisting># /usr/lib64/cloud/common/scripts/storage/secondary/cloud-install-sys-tmplt -m /mnt/secondary -u http://download.cloud.com/templates/4.2/systemvmtemplate-4.2-vh7.ova -h vmware -s <optional-management-server-secret-key>  -F</programlisting>
        </listitem>
        <listitem>
          <para>For KVM:</para>
          <programlisting># /usr/lib64/cloud/common/scripts/storage/secondary/cloud-install-sys-tmplt -m /mnt/secondary -u http://download.cloud.com/templates/4.2/systemvmtemplate-2013-06-12-master-kvm.qcow2.bz2 -h kvm -s <optional-management-server-secret-key> -F</programlisting>
        </listitem>
        <listitem>
          <para>For LXC:</para>
          <programlisting># /usr/lib64/cloud/common/scripts/storage/secondary/cloud-install-sys-tmplt -m /mnt/secondary -u http://download.cloud.com/templates/acton/acton-systemvm-02062012.qcow2.bz2 -h lxc -s <optional-management-server-secret-key> -F</programlisting>
        </listitem>
      </itemizedlist>
    </listitem>
    <listitem>
       <para>When the script has finished, unmount secondary storage and remove the created
        directory.</para>
      <programlisting># umount /mnt/secondary
# rmdir /mnt/secondary</programlisting>
    </listitem>
    <listitem>
      <para>Repeat these steps for each secondary storage server.</para>
    </listitem>
  </orderedlist>
</section>


text:
<?php

interface f_c_action_interface
{
}


text:
'use strict';

var ready = require('domready');

require('./lib/hbs'); // To register our helpers and partials

var ListView = require('./views/list');
var NavbarView = require('./views/navbar');
var PaginationView = require('./views/pagination');

var Events = require('./collections/events');

var router = require('./router');

var events = new Events(window.data.eventList);

ready(function(){
  var navbar = new NavbarView({
    el: document.querySelector('nav')
  });

  navbar.render();

  var pagination = new PaginationView({
    el: document.querySelector('#pagination'),
    collection: events
  });

  pagination.render();

  var list = new ListView({
    el: document.querySelector('#event-list'),
    collection: events
  });

  list.render();

  router.history.start({
    pushState: true
  });
});


text:
        <list-view data-id="listview" data-widget="vm.$components.listview.widget" data-model="vm.$viewModels.CustomerDsModel" data-events="vm.$components.listview.events" data-options="vm.$components.listview.options" data-dom-ready="vm.$domReady">
        </list-view>

        <kb-custom-html data-id="customhtml1" data-options="vm.$components.customhtml1.options">
        </kb-custom-html>

        <kb-button data-id="newButton" data-widget="vm.$components.newButton.widget" data-options="vm.$components.newButton.options" data-events="vm.$components.newButton.events">
        </kb-button>

        <kb-button data-id="save" data-widget="vm.$components.save.widget" data-options="vm.$components.save.options" data-events="vm.$components.save.events">
        </kb-button>

        <kb-button data-id="delete" data-widget="vm.$components.delete.widget" data-options="vm.$components.delete.options" data-events="vm.$components.delete.events">
        </kb-button>

        <kb-button data-id="cancel" data-widget="vm.$components.cancel.widget" data-options="vm.$components.cancel.options" data-events="vm.$components.cancel.events">
        </kb-button>

        <kb-custom-html data-id="customhtml0" data-options="vm.$components.customhtml0.options">
        </kb-custom-html>

                <kb-label data-text="Cust Num" data-for-attribute=""></kb-label>

                <integer-text-box data-id="custNum" data-widget="vm.$components.custNum.widget" data-title="Cust Num" data-options="vm.$components.custNum.options" data-model="vm.$viewModels.CustomerDsModel.CustNum" data-events="vm.$components.custNum.events" data-validation="vm.$components.custNum.validation">
                </integer-text-box>

                <kb-label data-text="Name" data-for-attribute=""></kb-label>

                <text-box data-id="name" data-title="Name" data-model="vm.$viewModels.CustomerDsModel.Name" data-placeholder="Enter Name" data-debounce="0" data-default-value="" data-events="vm.$components.name.events" data-validation="vm.$components.name.validation">
                </text-box>

                <kb-label data-text="Address" data-for-attribute=""></kb-label>

                <text-box data-id="address" data-title="Address" data-model="vm.$viewModels.CustomerDsModel.Address" data-placeholder="Enter Address" data-debounce="0" data-default-value="" data-events="vm.$components.address.events" data-validation="vm.$components.address.validation">
                </text-box>

                <kb-label data-text="Phone" data-for-attribute=""></kb-label>

                <phone-text-box data-id="phone" data-widget="vm.$components.phone.widget" data-title="Phone" data-model="vm.$viewModels.CustomerDsModel.Phone" data-options="vm.$components.phone.options" data-events="vm.$components.phone.events" data-validation="vm.$components.phone.validation">
                </phone-text-box>

                <kb-label data-text="Sales Rep" data-for-attribute=""></kb-label>

                <text-box data-id="salesRep" data-title="Sales Rep" data-model="vm.$viewModels.CustomerDsModel.SalesRep" data-placeholder="Enter Sales Rep" data-debounce="0" data-default-value="" data-events="vm.$components.salesRep.events" data-validation="vm.$components.salesRep.validation">
                </text-box>

                <kb-label data-text="Balance" data-for-attribute=""></kb-label>

                <numeric-text-box data-id="balance" data-widget="vm.$components.balance.widget" data-title="Balance" data-options="vm.$components.balance.options" data-model="vm.$viewModels.CustomerDsModel.Balance" data-events="vm.$components.balance.events" data-validation="vm.$components.balance.validation">
                </numeric-text-box>

                <kb-label data-text="State" data-for-attribute=""></kb-label>

                <text-box data-id="state" data-title="State" data-model="vm.$viewModels.CustomerDsModel.State" data-placeholder="Enter State" data-debounce="0" data-default-value="" data-events="vm.$components.state.events" data-validation="vm.$components.state.validation">
                </text-box>

                <kb-label data-text="Country" data-for-attribute=""></kb-label>

                <text-box data-id="country" data-title="Country" data-model="vm.$viewModels.CustomerDsModel.Country" data-placeholder="Enter Country" data-debounce="0" data-default-value="" data-events="vm.$components.country.events" data-validation="vm.$components.country.validation">
                </text-box>


text:
Instacab Dispatcher is a Node.js app which coordinates drivers and clients, dispatches ride requests to nearest drivers, keeps GPS logs, provides API via WebSockets for client and driver apps, provides ETA using [Google Distance Matrix](https://developers.google.com/maps/documentation/distancematrix/), provides REST API for `God View` interface to display all clients, drivers and trips in real-time on the map.

## How Does It Work

* Listens port 9000 for API WebSocket connections
* Waits for AMQP (RabbitMQ) messages from [Instacab Backend](https://github.com/tisunov/Instacab/) to update city vehicle options availability
* All client and driver state is kept in memory with Redis as storage between restarts.

## Requirements
* Node.js 0.10.x
* Redis 2.8
* MongoDB
* RabbitMQ

## Client API Interface

* TODO

## Driver API Interface

* TODO

## Getting Started

1. Checkout Dispatcher source at the command prompt if you haven't yet:

        git checkout https://github.com/tisunov/InstacabDispatcher

2. At the command prompt, install required npm packages:

        npm install

3. Install and start [RabbitMQ](http://www.rabbitmq.com/download.html)

4. Start Instacab Dispatcher

        node app.js

5. Start Instacab Backend

## Setting Up Instacab Backend

Please refer to [Instacab Backend](https://github.com/tisunov/Instacab/)

## Instacab iPhone Client App

Please refer to [Instacab Client](https://github.com/tisunov/InstacabClient/)

## Known Bugs
* Memory footprint keeps growing while running in production, node.js memory leak detection tools yielded no results so far.

## TODO

- [ ] Write unit tests
- [ ] Translate Russian strings
- [ ] Consider ditching WebSockets in favor REST API, we are updating whole app state anyways.
- [ ] Use AMQP to communicate with backend instead HTTP
- [ ] Use [winston](https://github.com/flatiron/winston) for logging


text:
import { decodeCharacterReferences } from 'utils/html';

export default function Triple$toString () {
	return ( this.value != undefined ? decodeCharacterReferences( '' + this.value ) : '' );
}


text:
package com.box.sdk;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonValue;

/**
 * The abstract base class for items in a user's file tree (files, folders, etc.).
 */
public abstract class BoxItem extends BoxResource {
    /**
     * Constructs a BoxItem for an item with a given ID.
     * @param  api the API connection to be used by the item.
     * @param  id  the ID of the item.
     */
    public BoxItem(BoxAPIConnection api, String id) {
        super(api, id);
    }

    /**
     * Copies this item to another folder.
     * @param  destination the destination folder.
     * @return             info about the copied item.
     */
    public abstract BoxItem.Info copy(BoxFolder destination);

    /**
     * Copies this item to another folder and gives it a new name. If the destination is the same folder as the item's
     * current parent, then newName must be a new, unique name.
     * @param  destination the destination folder.
     * @param  newName     a new name for the copied item.
     * @return             info about the copied item.
     */
    public abstract BoxItem.Info copy(BoxFolder destination, String newName);

    /**
     * Creates a new shared link for this item.
     *
     *
This method is a convenience method for manually creating a new shared link and applying it to this item with
     * {@link Info#setSharedLink}. You may want to create the shared link manually so that it can be updated along with
     * other changes to the item's info in a single network request, giving a boost to performance.

     *
     * @param  access      the access level of the shared link.
     * @param  unshareDate the date and time at which the link will expire. Can be null to create a non-expiring link.
     * @param  permissions the permissions of the shared link. Can be null to use the default permissions.
     * @return             the created shared link.
     */
    public abstract BoxSharedLink createSharedLink(BoxSharedLink.Access access, Date unshareDate,
        BoxSharedLink.Permissions permissions);

    /**
     * Gets information about this item.
     * @return info about this item.
     */
    public abstract BoxItem.Info getInfo();

    /**
     * Gets information about this item that's limited to a list of specified fields.
     * @param  fields the fields to retrieve.
     * @return        info about this item containing only the specified fields.
     */
    public abstract BoxItem.Info getInfo(String... fields);

    /**
     * Contains information about a BoxItem.
     */
    public abstract class Info extends BoxResource.Info {
        private String sequenceID;
        private String etag;
        private String name;
        private Date createdAt;
        private Date modifiedAt;
        private String description;
        private long size;
        private List<BoxFolder> pathCollection;
        private BoxUser.Info createdBy;
        private BoxUser.Info modifiedBy;
        private Date trashedAt;
        private Date purgedAt;
        private Date contentCreatedAt;
        private Date contentModifiedAt;
        private BoxUser.Info ownedBy;
        private BoxSharedLink sharedLink;
        private List<String> tags;
        private BoxFolder.Info parent;
        private String itemStatus;

        /**
         * Constructs an empty Info object.
         */
        public Info() {
            super();
        }

        /**
         * Constructs an Info object by parsing information from a JSON string.
         * @param  json the JSON string to parse.
         */
        public Info(String json) {
            super(json);
        }

        /**
         * Constructs an Info object using an already parsed JSON object.
         * @param  jsonObject the parsed JSON object.
         */
        Info(JsonObject jsonObject) {
            super(jsonObject);
        }

        /**
         * Gets a unique string identifying the version of the item.
         * @return a unique string identifying the version of the item.
         */
        public String getEtag() {
            return this.etag;
        }

        /**
         * Gets the name of the item.
         * @return the name of the item.
         */
        public String getName() {
            return this.name;
        }

        /**
         * Sets the name of the item.
         * @param name the new name of the item.
         */
        public void setName(String name) {
            this.name = name;
            this.addPendingChange("name", name);
        }

        /**
         * Gets the time the item was created.
         * @return the time the item was created.
         */
        public Date getCreatedAt() {
            return this.createdAt;
        }

        /**
         * Gets the time the item was last modified.
         * @return the time the item was last modified.
         */
        public Date getModifiedAt() {
            return this.modifiedAt;
        }

        /**
         * Gets the description of the item.
         * @return the description of the item.
         */
        public String getDescription() {
            return this.description;
        }

        /**
         * Sets the description of the item.
         * @param description the new description of the item.
         */
        public void setDescription(String description) {
            this.description = description;
            this.addPendingChange("description", description);
        }

        /**
         * Gets the size of the item in bytes.
         * @return the size of the item in bytes.
         */
        public long getSize() {
            return this.size;
        }

        /**
         * Gets the path of folders to the item, starting at the root.
         * @return the path of folders to the item.
         */
        public List<BoxFolder> getPathCollection() {
            return this.pathCollection;
        }

        /**
         * Gets info about the user who created the item.
         * @return info about the user who created the item.
         */
        public BoxUser.Info getCreatedBy() {
            return this.createdBy;
        }

        /**
         * Gets info about the user who last modified the item.
         * @return info about the user who last modified the item.
         */
        public BoxUser.Info getModifiedBy() {
            return this.modifiedBy;
        }

        /**
         * Gets the time that the item was trashed.
         * @return the time that the item was trashed.
         */
        public Date getTrashedAt() {
            return this.trashedAt;
        }

        /**
         * Gets the time that the item was purged from the trash.
         * @return the time that the item was purged from the trash.
         */
        public Date getPurgedAt() {
            return this.purgedAt;
        }

        /**
         * Gets the time that the item was created according to the uploader.
         * @return the time that the item was created according to the uploader.
         */
        public Date getContentCreatedAt() {
            return this.contentCreatedAt;
        }

        /**
         * Gets the time that the item was last modified according to the uploader.
         * @return the time that the item was last modified according to the uploader.
         */
        public Date getContentModifiedAt() {
            return this.contentModifiedAt;
        }

        /**
         * Gets info about the user who owns the item.
         * @return info about the user who owns the item.
         */
        public BoxUser.Info getOwnedBy() {
            return this.ownedBy;
        }

        /**
         * Gets the shared link for the item.
         * @return the shared link for the item.
         */
        public BoxSharedLink getSharedLink() {
            return this.sharedLink;
        }

        /**
         * Sets a shared link for the item.
         * @param sharedLink the shared link for the item.
         */
        public void setSharedLink(BoxSharedLink sharedLink) {
            if (this.sharedLink == sharedLink) {
                return;
            }

            this.removeChildObject("shared_link");
            this.sharedLink = sharedLink;
            this.addChildObject("shared_link", sharedLink);
        }

        /**
         * Gets a unique ID for use with the {@link EventStream}.
         * @return a unique ID for use with the EventStream.
         */
        public String getSequenceID() {
            return this.sequenceID;
        }

        /**
         * Gets a list of all the tags applied to the item.
         *
         *
Note that this field isn't populated by default and must be specified as a field parameter when getting
         * Info about the item.

         *
         * @return a list of all the tags applied to the item.
         */
        public List<String> getTags() {
            return this.tags;
        }

        /**
         * Gets info about the parent folder of the item.
         * @return info abou thte parent folder of the item.
         */
        public BoxFolder.Info getParent() {
            return this.parent;
        }

        /**
         * Gets the status of the item.
         * @return the status of the item.
         */
        public String getItemStatus() {
            return this.itemStatus;
        }

        @Override
        protected void parseJSONMember(JsonObject.Member member) {
            super.parseJSONMember(member);

            try {
                JsonValue value = member.getValue();
                switch (member.getName()) {
                    case "sequence_id":
                        this.sequenceID = value.asString();
                        break;
                    case "etag":
                        this.etag = value.asString();
                        break;
                    case "name":
                        this.name = value.asString();
                        break;
                    case "created_at":
                        this.createdAt = BoxDateFormat.parse(value.asString());
                        break;
                    case "modified_at":
                        this.modifiedAt = BoxDateFormat.parse(value.asString());
                        break;
                    case "description":
                        this.description = value.asString();
                        break;
                    case "size":
                        this.size = Double.valueOf(value.toString()).longValue();
                        break;
                    case "trashed_at":
                        this.trashedAt = BoxDateFormat.parse(value.asString());
                        break;
                    case "purged_at":
                        this.purgedAt = BoxDateFormat.parse(value.asString());
                        break;
                    case "content_created_at":
                        this.contentCreatedAt = BoxDateFormat.parse(value.asString());
                        break;
                    case "content_modified_at":
                        this.contentModifiedAt = BoxDateFormat.parse(value.asString());
                        break;
                    case "path_collection":
                        this.pathCollection = this.parsePathCollection(value.asObject());
                        break;
                    case "created_by":
                        this.createdBy = this.parseUserInfo(value.asObject());
                        break;
                    case "modified_by":
                        this.modifiedBy = this.parseUserInfo(value.asObject());
                        break;
                    case "owned_by":
                        this.ownedBy = this.parseUserInfo(value.asObject());
                        break;
                    case "shared_link":
                        if (this.sharedLink == null) {
                            this.setSharedLink(new BoxSharedLink(value.asObject()));
                        } else {
                            this.sharedLink.update(value.asObject());
                        }
                        break;
                    case "tags":
                        this.tags = this.parseTags(value.asArray());
                        break;
                    case "parent":
                        JsonObject jsonObject = value.asObject();
                        if (this.parent == null) {
                            String id = jsonObject.get("id").asString();
                            BoxFolder parentFolder = new BoxFolder(getAPI(), id);
                            this.parent = parentFolder.new Info(jsonObject);
                        } else {
                            this.parent.update(jsonObject);
                        }
                        break;
                    case "item_status":
                        this.itemStatus = value.asString();
                        break;
                    default:
                        break;
                }
            } catch (ParseException e) {
                assert false : "A ParseException indicates a bug in the SDK.";
            }
        }

        private List<BoxFolder> parsePathCollection(JsonObject jsonObject) {
            int count = jsonObject.get("total_count").asInt();
            List<BoxFolder> pathCollection = new ArrayList<BoxFolder>(count);
            JsonArray entries = jsonObject.get("entries").asArray();
            for (JsonValue value : entries) {
                JsonObject entry = value.asObject();
                String id = entry.get("id").asString();
                pathCollection.add(new BoxFolder(getAPI(), id));
            }

            return pathCollection;
        }

        private BoxUser.Info parseUserInfo(JsonObject jsonObject) {
            String userID = jsonObject.get("id").asString();
            BoxUser user = new BoxUser(getAPI(), userID);
            return user.new Info(jsonObject);
        }

        private List<String> parseTags(JsonArray jsonArray) {
            List<String> tags = new ArrayList<String>(jsonArray.size());
            for (JsonValue value : jsonArray) {
                tags.add(value.asString());
            }

            return tags;
        }
    }
}


text:
module Krikri::Enrichments
  ##
  # Splits a Resource into multiple resources of its own class by a given
  # delimiter in its `#providedLabel`. The full original resource is retained
  # with the first value from the split label.
  #
  # @example
  #   splitter = SplitProvidedLabelAtDelimiter.new
  #   concept = DPLA::MAP::Concept.new
  #   concept.providedLabel = 'abc; 123'
  #   concept.exactMatch = RDF::URI('http://example.org/alphabet')
  #
  #   results = splitter.enrich_value(concept)
  #
  #   results.map(&:providedLabel)
  #   # => [['abc'], ['123']]
  #
  #   results.map(&:exactMatch)
  #   # => [[#<ActiveTriple::Resource:...>], []]
  #
  # @see Audumbla::FieldEnrichment
  class SplitProvidedLabelAtDelimiter
    include Audumbla::FieldEnrichment

    ##
    # @param delimiter [String] a substring on which to split `#providedLabel`
    def initialize(delimiter = ';')
      @delimiter = delimiter
    end

    ##
    # @param value [Object] the value to split
    # @see Audumbla::FieldEnrichment
    def enrich_value(value)
      return value unless value.is_a?(ActiveTriples::Resource) &&
                          value.respond_to?(:providedLabel)

      construct_results(value)
    end

    private

    ##
    # @param value [ActiveTriples::Resource]
    #
    # @return [Array<ActiveTriples::Resource>] an array of resources derived
    #   from the split `#providedLabel` of `value`
    def construct_results(value)
      values = split_value(value)

      value.providedLabel = values.shift
      results = [value]

      values.each { |v| results << build_resource(value.class, v) }

      results
    end

    ##
    # @param klass [Class]
    # @param providedLabel [String]
    #
    # @return [klass] a new resource of `klass` with the providedLabel given
    def build_resource(klass, providedLabel)
      resource = klass.new
      resource.providedLabel = providedLabel
      resource
    end

    ##
    # @param value [#providedLabel]
    # @return [Array<String>] a flat array of provided labels split from
    #   the original
    def split_value(value)
      value.providedLabel.map { |l| l.split(';').map(&:strip) }.flatten
    end
  end
end


text:
Check Out Cancelled

your check out process cancelled continue shopping

            <button class="btn btn-success">Continue Shopping</button>

<foot></foot>


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

namespace NDbfReaderEx
{
  public partial class DbfTable : IDisposable
  {
    #region variables/constants ---------------------------------------------------------------------------

    public static bool defaultOnlyDBase3Enabled = false;
    public        bool onlyDBase3Enabled        = defaultOnlyDBase3Enabled;

    private const int  codepageBytePosition     = 29;                     // http://www.dbf2002.com/dbf-file-format.html   "Code page mark"
    private const int  firstFieldSubrecordVer3  = 32;                     // http://www.dbf2002.com/dbf-file-format.html   "32 – n	: Field subrecords"
    private const int  firstFieldSubrecordVer4  = 68;                     // http://www.dbase.com/Knowledgebase/INT/db7_file_fmt.htm   "Field Descriptor Array (see 1.2)."
    private const byte headerRecordTerminator   = 0x0D;                   // http://www.dbf2002.com/dbf-file-format.html   "n+1: Header record terminator (0x0D)"
    private const int  maxColumnCount           = 1024;                   // I extend it for myself: original 255  http://msdn.microsoft.com/en-us/library/3kfd3hw9(v=vs.80).aspx
    private const byte endOfFileTerminator      = 0x1A;

    private const int  minDbfFileLengthVer3     = 32 + 32 + 1;            // http://www.dbf2002.com/dbf-file-format.html   (header info + 1 filed + headerRecordTerminator)
    private const int  minDbfFileLengthVer4     = 68 + 48 + 1;            // http://www.dbase.com/Knowledgebase/INT/db7_file_fmt.htm    (header info + 1 filed + headerRecordTerminator)
    #endregion

    #region enums/constans ----------------------------------------------------------------------------------

    /// <summary>
    /// Valid codepage bytes by standard codepage names for DBF file.
    /// information have got from http://forums.esri.com/Thread.asp?c=93&f=1170&t=197185#587982
    /// also added from           https://msdn.microsoft.com/en-us/library/8t45x02s(v=vs.80).aspx
    /// also added from           http://shapelib.maptools.org/codepage.html
    /// </summary>
    public enum CodepageCodes : byte
    {
      OEM               = 0x00,                                           // OEM = 0
      CP_437            = 0x01,                                           // Codepage_437_US_MSDOS = &H1
      CP_850            = 0x02,                                           // Codepage_850_International_MSDOS = &H2
      CP_1252           = 0x03,                                           // Codepage_1252_Windows_ANSI = &H3

      CP_10000          = 0x04,                                           // Standard Macintosh

      CP_865_Danish     = 0x08,		                                        // Danish OEM
      CP_437_Dutch      = 0x09,		                                        // Dutch OEM
      CP_850_Dutch      = 0x0A,		                                        // Dutch OEM*
      CP_437_Finnish    = 0x0B,		                                        // Finnish OEM
      CP_437_French     = 0x0D,		                                        // French OEM
      CP_850_French     = 0x0E,		                                        // French OEM*
      CP_437_German     = 0x0F,		                                        // German OEM
      CP_850_German     = 0x10,		                                        // German OEM*
      CP_437_Italian    = 0x11,		                                        // Italian OEM
      CP_850_Italian    = 0x12,		                                        // Italian OEM*
      CP_932_Japanese   = 0x13,		                                        // Japanese Shift-JIS
      CP_850_Spanish    = 0x14,		                                        // Spanish OEM*
      CP_437_Swedish    = 0x15,		                                        // Swedish OEM
      CP_850_Swedish    = 0x16,		                                        // Swedish OEM*
      CP_865_Norwegian  = 0x17,		                                        // Norwegian OEM
      CP_437_Spanish    = 0x18,		                                        // Spanish OEM
      CP_437_GB         = 0x19,		                                        // English OEM (Great Britain)
      CP_850_GB         = 0x1A,		                                        // English OEM (Great Britain)*
      CP_437_US         = 0x1B,		                                        // English OEM (US)
      CP_863            = 0x1C,		                                        // French OEM (Canada)
      CP_850_French2    = 0x1D,		                                        // French OEM*
      CP_852_Czech      = 0x1F,		                                        // Czech OEM
      CP_852_Hungarian  = 0x22,		                                        // Hungarian OEM
      CP_852_Polish     = 0x23,		                                        // Polish OEM
      CP_860            = 0x24,		                                        // Portuguese OEM
      CP_850_Portuguese = 0x25,		                                        // Portuguese OEM*
      CP_866_Russian    = 0x26,		                                        // Russian OEM
      CP_850_US         = 0x37,		                                        // English OEM (US)*
      CP_852_Romanian   = 0x40,		                                        // Romanian OEM
      CP_936_Chinese    = 0x4D,		                                        // Chinese GBK (PRC)
      CP_949_Korean     = 0x4E,		                                        // Korean (ANSI/OEM)
      CP_950_Chinese    = 0x4F,		                                        // Chinese Big5 (Taiwan)
      CP_874_Thai       = 0x50,	                                          // Thai (ANSI/OEM)

      ANSI              = 0x57,                                           // ANSI = &H57

      CP_1252_WestEu    =	0x58,		                                        // Western European ANSI
	    CP_1252_Spanish   = 0x59,		                                        // Spanish ANSI

      CP_852            = 0x64,                                           // Codepage_852_EasernEuropean_MSDOS = &H64
      CP_866            = 0x65,                                           // Codepage_866_Russian_MSDOS = &H65
      CP_865            = 0x66,                                           // Codepage_865_Nordic_MSDOS = &H66
      CP_861            = 0x67,                                           // Codepage_861_Icelandic_MSDOS = &H67
      CP_895            = 0x68,                                           // Kamenicky (Czech) MS-DOS
      CP_620            = 0x69,                                           // Mazovia (Polish) MS-DOS
      CP_737            = 0x6A,                                           // Codepage_737_Greek_MSDOS = &H6A
      CP_857            = 0x6B,                                           // Codepage_857_Turkish_MSDOS = &H6B

      CP_863_Canadian   = 0x6C,        	                                  // French-Canadian MS-DOS

      CP_950            = 0x78,                                           // Codepage_950_Chinese_Windows = &H78
      CP_949            = 0x79,                                           // Korean Windows
      CP_936            = 0x7A,                                           // Codepage_936_Chinese_Windows = &H7A
      CP_932            = 0x7B,                                           // Codepage_932_Japanese_Windows = &H7B

      CP_874            = 0x7C,                                           // Thai Windows

      CP_1255           = 0x7D,                                           // Codepage_1255_Hebrew_Windows = &H7D
      CP_1256           = 0x7E,                                           // Codepage_1256_Arabic_Windows = &H7E

      CP_737_Greek      = 0x86,	                                          // Greek OEM
  	  CP_852_Slovenian  = 0x87,	                                          // Slovenian OEM
  	  CP_857_Turkish    = 0x88,	                                          // Turkish OEM

      CP_10007          = 0x96,                                           // Russian Macintosh
      CP_10029          = 0x97,                                           // Macintosh EE
      CP_10006          = 0x98,                                           // Greek Macintosh

      CP_1250           = 0xC8,                                           // Codepage_1250_Eastern_European_Windows = &HC8
      CP_1251           = 0xC9,                                           // Codepage_1251_Russian_Windows = &HC9
      CP_1254           = 0xCA,                                           // Codepage_1254_Turkish_Windows = &HCA
      CP_1253           = 0xCB,                                           // Codepage_1253_Greek_Windows = &HCB

      CP_1257           = 0xCC	                                          // Baltic Windows
    };

    public static int GetEncodingCodePageFromCodepageCodes(CodepageCodes codepageCode)
    {
      string codepageName = codepageCode.ToString();

      if (codepageName.StartsWith("CP_"))
      {
        string[] nameParts = codepageName.Split('_');

        return int.Parse(nameParts[1]);;
      }

      switch (codepageCode)
      { // Name isn't started "CP_"
        case CodepageCodes.OEM:
          return CultureInfo.CurrentCulture.TextInfo.OEMCodePage;
        case CodepageCodes.ANSI:
          return CultureInfo.CurrentCulture.TextInfo.ANSICodePage;
      }

      return int.MinValue;
    }

    /// <summary>
    /// http://www.dbf2002.com/dbf-file-format.html
    /// </summary>
    public enum DbfFileTypes : byte
    {
      FoxBASE       = 0x02,                                     // FoxBASE
      DBase3        = 0x03,                                     // FoxBASE+/Dbase III plus, no memo
      DBase7        = 0x04,                                     // NEW *** added by eMeL
      VisualFoxPro  = 0x30,                                     // Visual FoxPro
      VisualFoxPro2 = 0x31,                                     // Visual FoxPro, autoincrement enabled
      VisualFoxPro3 = 0x32,                                     // Visual FoxPro with field type Varchar or Varbinary
      DBase4Sql     = 0x43,                                     // dBASE IV SQL table files, no memo
      DBase4SqlSys  = 0x63,                                     // dBASE IV SQL system files, no memo
      DBase3M       = 0x83,                                     // FoxBASE+/dBASE III PLUS, with memo
      DBase7M       = 0x84,                                     // NEW *** added by eMeL / with memo
      DBase4M       = 0x8B,                                     // dBASE IV with memo
      DBase4SqlM    = 0xCB,                                     // dBASE IV SQL table files, with memo
      FoxPro2M      = 0xF5,                                     // FoxPro 2.x (or earlier) with memo
      HiperSix      = 0xE5,                                     // HiPer-Six format with SMT memo file
      FoxBASE2      = 0xFB                                      // FoxBASE
    };
    #endregion

    #region ReadDbfHeader_* ---------------------------------------------------------------------------------

    public static DbfHeader ReadDbfHeader(Stream stream, bool? onlyDBase3Enabled = null)
    {
      DbfHeader header;

      stream.Position = 0;                                                      // start from first byte

      if (stream.Length < minDbfFileLengthVer3)
      {
        throw new IOException("Not a DBF file! ('DBF File length' is too short!) [< " + minDbfFileLengthVer3 + "]");
      }

      BinaryReader reader = new BinaryReader(stream);                           // don't use using '(BinaryReader reader...' because 'using' dispose 'stream' too!
      {
        header.type = (DbfFileTypes)(reader.ReadByte());                        // pos: 0          -- DBF File type:

        if (! DbfHeader.HasNewHeaderStructure(header.type))
        {
          if (Array.IndexOf(Enum.GetValues(typeof(DbfFileTypes)), header.type) < 0)
          {
            if (onlyDBase3Enabled ?? defaultOnlyDBase3Enabled)
            {
              throw new IOException("Not a DBF file! ('DBF File type' is not valid!) [dBase3]");
            }
          }
        }

        int minDbfFileLength = DbfHeader.HasNewHeaderStructure(header.type) ? minDbfFileLengthVer4 : minDbfFileLengthVer3;

        if (stream.Length < minDbfFileLength)
        {
          throw new IOException("Not a DBF file! ('DBF File length' is too short!) [< " + minDbfFileLength + "]");
        }

        //

        int lastUpdateYear  = reader.ReadByte();                                // pos: 1,2,3      -- Last update (YYMMDD)
        int lastUpdateMonth = reader.ReadByte();
        int lastUpdateDay   = reader.ReadByte();

        int maxYear = (DateTime.Today.Year - 2000) + 1;                         // DBase III / Clipper date

        bool correctedYear = false;

        if (lastUpdateYear >= 100)
        { // If not a dBaseIII or Clipper file, correct it
          // because dBaseIII+ (and earlier) has a Year 2000 bug. It stores the year as simply the last two digits of the actual year.
          maxYear += 100;
          correctedYear = true;
        }

        if ((lastUpdateYear  < 0) || (lastUpdateYear  > maxYear) ||             // !WARNING: only next year is valid
            (lastUpdateMonth < 1) || (lastUpdateMonth > 12)      ||
            (lastUpdateDay   < 1) || (lastUpdateDay   > 31))
        {
          throw new IOException("Not a DBF file! ('Last update' (YYMMDD) error!)");
        }

        header.lastUpdate = new DateTime((correctedYear ? 1900 : 2000) + lastUpdateYear, lastUpdateMonth, lastUpdateDay);

        //

        header.recCount            = reader.ReadInt32();
        header.firstRecordPosition = reader.ReadInt16();
        header.rowLength           = reader.ReadInt16();

        if (header.recCount < 0)
        {
          throw new IOException("Not a DBF file! (Number of records in file error!)");
        }

        //

        if (DbfHeader.HasNewHeaderStructure(header.type))
        {
          int maxLengthOfFieldPropertiesStructure;  // it's too complex, we use only a fabricated number. http://www.dbase.com/Knowledgebase/INT/db7_file_fmt.htm

          maxLengthOfFieldPropertiesStructure = 64 * 1024;

          if ((header.firstRecordPosition < minDbfFileLengthVer4) ||
              (header.firstRecordPosition > (68 + (48 * maxColumnCount) + 1 + maxLengthOfFieldPropertiesStructure)) ||
              (header.firstRecordPosition > stream.Length))                     // !WARNING: I don't know valid limit
          {
            throw new IOException("Not a DBF file! (firstRecordPosition) [dBase4-7]");
          }
        }
        else
        {
          if ((header.firstRecordPosition < minDbfFileLengthVer3) ||
              (header.firstRecordPosition > (32 + (32 * maxColumnCount) + 1 + 2 + 264)) ||
              (header.firstRecordPosition > stream.Length))                     // !WARNING: I don't know valid limit
          {
            throw new IOException("Not a DBF file! (firstRecordPosition) [dBase3]");
          }
        }

        //

        stream.Position = codepageBytePosition;                                // pos: http://www.dbf2002.com/dbf-file-format.html

        header.codepageCode = (CodepageCodes)(reader.ReadByte());

        if (Array.IndexOf(Enum.GetValues(typeof(CodepageCodes)), header.codepageCode) < 0)
        {
          throw new IOException("Not a DBF file! ('Code page mark' is not valid!)");
        }
      }

      return header;
    }

    public static Encoding ReadDbfHeader_Encoding(CodepageCodes code, bool throwException = false)
    {
      int codepage = GetEncodingCodePageFromCodepageCodes(code);

      if (codepage < 0)
      { // not found
        if (throwException)
        {
          throw new Exception(String.Format("ReadDbfHeader_Encoding(): '{0}' codepage code invalid!", code));
        }
        else
        {
          return null;
        }
      }

      return Encoding.GetEncoding(codepage);
    }

    public static IColumn[] ReadDbfColumns(Stream stream, Encoding encoding, bool newHeaderStructure, bool openMemo)
    {
      List<IColumn> columns = new List<IColumn>();

      stream.Position = newHeaderStructure ? firstFieldSubrecordVer4 : firstFieldSubrecordVer3;

      int calcOffset = 0;

      for (int i = 0; (i < maxColumnCount); i++)
      {
        IColumn column = GetNextColumnDefinition(stream, encoding, calcOffset, newHeaderStructure);

        if (column == null)
        { // No more column definition
          break;
        }
        else
        { // Store column definition
          if (column.dbfType == NativeColumnType.Memo)
          {
            if (openMemo)
            {
              columns.Add(column);
            }
          }
          else
          {
            columns.Add(column);
          }

          calcOffset += column.size;
        }
      }

      if (columns.Count < 1)
      {
        throw new Exception("DBF file format error! (At least one column definition required!)");
      }

      return columns.ToArray();
    }

    private static Column GetNextColumnDefinition(Stream stream, Encoding encoding, int calcOffset, bool newHeaderStructure)
    { // If there isn't more column definition return null.
      string            columnName;
      NativeColumnType  columnType;
      int               columnOffset;                                           // isn't stored by dBase3/Clipper, must calculate by 'calcOffset'
      short             columnSize;
      short             columnDec;

      //

      int    bufferLen = newHeaderStructure ? 32 : 11;                          // http://www.dbf2002.com/dbf-file-format.html "Field name with a maximum of 10 characters. If less than 10, it is padded with null characters (0x00)."
                                                                                // http://www.dbase.com/Knowledgebase/INT/db7_file_fmt.htm
      byte[] buffer = new byte[bufferLen];

      int readed = stream.Read(buffer, 0, buffer.Length);

      if ((readed > 0) && (buffer[0] == headerRecordTerminator))
      { // found Header record terminator (0x0D)
        return null;                                                            // there isn't more column definition record
      }

      if (readed != buffer.Length)
      {
        throw new Exception("DBF file format error! (don't found 'Header record terminator' (0x0D)!)");
      }

      { // http://www.dbf2002.com/dbf-file-format.html "If less than 10, it is padded with null characters (0x00)." - NO! It can contains garbage bytes after 0x00!
        int nameLen = newHeaderStructure ? 32 : 10;

        for (int i = 0; (i < nameLen); i++)
        {
          if ((buffer[i] == 0x00) || (buffer[i] == 0x20))                                     // name is closed and/or trimmed blanks (can closed with blank in real world)
          {
            nameLen = i;
            break;
          }
        }

        if (nameLen == 0)
        {
          throw new Exception("DBF file format error! (don't found column name!)");
        }

        columnName = Encoding.ASCII.GetString(buffer, 0, nameLen);
      }

      //

      BinaryReader reader = new BinaryReader(stream);                                 // don't use 'using (BinaryReader reader...' because 'using' dispose 'stream' too.

      if (newHeaderStructure)
      {
        columnType = (NativeColumnType)reader.ReadByte();
        columnSize = reader.ReadByte();
        columnDec  = reader.ReadByte();

        reader.ReadBytes(13);
      }
      else
      {
        columnType = (NativeColumnType)reader.ReadByte();
        columnOffset = reader.ReadInt32();                                              // fake in dBase3 header
        columnSize = reader.ReadByte();
        columnDec = reader.ReadByte();

        reader.ReadBytes(14);                                                           // skip don't used and reserved caharacters
      }

      reader = null;

      //

      columnOffset = calcOffset;                                                      // isn't stored in header by dBase/Clipper, must calculate by 'calcOffset'

      if ((char)columnType == '+')                                                    // TODO: set column to ReadOnly
      { // Because store as same format and only read field data
        columnType = NativeColumnType.Long;
      }

      switch (columnType)
      {
        case NativeColumnType.Char:
          return new StringColumn(columnName, columnType, columnOffset, columnSize, columnDec, encoding);

        case NativeColumnType.Memo:
          return new MemoColumn(columnName, columnType, columnOffset, columnSize, columnDec, encoding);

        case NativeColumnType.Date:
          return new DateTimeColumn(columnName, columnType, columnOffset);

        case NativeColumnType.Long:
          Debug.Assert(columnSize == 4);
          return new Int32Column(columnName, columnType, columnOffset);

        case NativeColumnType.Logical:
          Debug.Assert(columnSize == 1);
          return new BooleanColumn(columnName, columnType, columnOffset);

        case NativeColumnType.Numeric:
        case NativeColumnType.Float:
          return new DecimalColumn(columnName, columnType, columnOffset, columnSize, columnDec);

        case NativeColumnType.Double:
          Debug.Assert(columnSize == 8);
          return new DoubleColumn(columnName, columnType, columnOffset);

        default:
          throw ExceptionFactory.CreateNotSupportedException("The {0} column's type '{1}' is not supported.", columnName, columnType);
      }
    }

    #endregion

    #region row read/write ----------------------------------------------------------------------------------

    public DbfRow GetRow(int recNo, bool throwException = false)
    {
      ThrowIfDisposed();

      if ((recNo < 0) || (recNo >= recCount))
      {
        if (throwException)
        {
          throw new Exception(String.Format("DbfTable.GetRow({0}): invalid record number! [count of records: {1}]", recNo, recCount));
        }
        else
        {
          return null;
        }
      }

      int    offset = _header.firstRecordPosition + (recNo * _header.rowLength);
      byte[] buffer = new byte[_header.rowLength];

      _stream.Position = offset;
      int readed = _stream.Read(buffer, 0, _header.rowLength);

      if (readed != _header.rowLength)
      {
        throw new IOException(String.Format("DBF file is corrupted! [Haven't enought bytes for {0}. row!]", recNo));
      }

      return new DbfRow(recNo, buffer, _columns, dbfTableClassID);
    }

    /// <summary>
    /// Update a dbf record by a DbfRow.
    ///
    ///
    /// </summary>
    /// <param name="row">Recno in DbfRow points record to update.</param>
    /// <param name="throwException"></param>
    /// <param name="updateRecNo">If DbfRow is a foreign/orphan row you must signal it explicit with updateRecNo value.</param>
    /// <returns>A boolean value or exception for success & DbfRow atached to this table if it was a foreign/orphan row.</returns>
    public bool UpdateRow(DbfRow row, bool throwException = true, int updateRecNo = int.MaxValue)
    {
      ThrowIfDisposed();

      if (row == null)
      {
        throw ExceptionFactory.CreateArgumentException("UpdateRow(row)", "Null parameter invalid!");
      }

      if (row.dbfTableClassID != this.dbfTableClassID)
      {
        if (updateRecNo != int.MaxValue)
        { // explicit signal for update a foreign/orphan row into this dbf file
          if ((updateRecNo < 0) || (updateRecNo >= recCount))
          {
            if (throwException)
            {
              throw new Exception(String.Format("DbfTable.UpdateRow(updateRecNo:{0}): invalid record number! [count of records: {1}]", updateRecNo, recCount));
            }
            else
            {
              return false;
            }
          }

          row.AtachedToAnotherTable(this, updateRecNo);
        }
        else if (throwException)
        {
          throw new Exception(String.Format("DbfTable.UpdateRow(): DbfRow parameter is a foreign/orphan value!"));
        }
        else
        {
          return false;
        }
      }

      if ((row.recNo < 0) || (row.recNo >= recCount))
      {
        if (throwException)
        {
          throw new Exception(String.Format("DbfTable.UpdateRow({0}): invalid record number! [count of records: {1}]", row.recNo, recCount));
        }
        else
        {
          return false;
        }
      }

      if (row._buffer.Length != _header.rowLength)
      {
        throw ExceptionFactory.CreateArgumentException("UpdateRow(row)", "Length of buffer in row different then file rowlength!");
      }

      int offset = _header.firstRecordPosition + (row.recNo * _header.rowLength);

      try
      {
        _stream.Write(row._buffer, offset, row._buffer.Length);
      }
      catch (Exception e)
      {
        throw new IOException(String.Format("DBF file is corrupted! [Write error at {0}. row!]", row.recNo), e);
      }

      row._modified = false;

      return true;
    }

    /// <summary>
    /// Insert a row and return success.
    /// If error happends return false (or throw an exception)
    /// Set row._recNo to record position of new record.
    /// </summary>
    /// <param name="row"></param>
    /// <param name="throwException"></param>
    /// <returns></returns>
    public bool InsertRow(DbfRow row, bool throwException = true, bool foreignRowEnabled = false)
    {
      ThrowIfDisposed();

      if (row == null)
      {
        throw ExceptionFactory.CreateArgumentException("InsertRow(row)", "Null parameter invalid!");
      }

      if (row.dbfTableClassID != this.dbfTableClassID)
      {
        if (foreignRowEnabled)
        { // explicit signal for insert a foreign/orphan row into this dbf file
          row.AtachedToAnotherTable(this, DbfRow.forInsert_recNoValue);
        }
        else if (throwException)
        {
          throw new Exception(String.Format("DbfTable.UpdateRow(): DbfRow parameter is a foreign/orphan value!"));
        }
        else
        {
          return false;
        }
      }

      row._recNo    = 99999999;         // TODO: !!!!!!!!!!!!!!!!!!!!!!
      row._modified = false;

      throw new NotImplementedException("InsertRow");
    }

    public bool WriteRow(DbfRow row, bool throwException = true)
    {
      if (row == null)
      {
        throw ExceptionFactory.CreateArgumentException("WriteRow(row)", "Null parameter invalid!");
      }

      if (row.dbfTableClassID != this.dbfTableClassID)
      {
        if (throwException)
        {
          throw new Exception(String.Format("DbfTable.WriteRow(): DbfRow parameter is a foreign/orphan value!"));
        }
        else
        {
          return false;
        }
      }

      if (row.recNo == DbfRow.forInsert_recNoValue)
      {
        return InsertRow(row, throwException);
      }
      else
      {
        return UpdateRow(row, throwException);
      }
    }

    public void DetachRow(DbfRow row, bool throwException = true)
    {
      row.AtachedToAnotherTable(null, DbfRow.forInsert_recNoValue);
    }

    #endregion

    #region row data read -----------------------------------------------------------------------------------
    #endregion

    #region CreateFile --------------------------------------------------------------------------------------

    private static DbfTable CreateHeader_DBF(Stream stream,
                                         IEnumerable<IColumnBase> columns,                                  // ColumnDefinitionForCreateTable --> IColumnBase
                                         DbfTableType tableType     = DbfTableType.Undefined,
                                         CodepageCodes codepageCode = CodepageCodes.OEM,
                                         Encoding encoding = null)
    {
      if (tableType == DbfTableType.Undefined)
      { // Crawling columns definition and choose one
        // TODO:!!!
        // tableType = *****;
      }

      var par = new DbfTableParameters(encoding, true, StrictHeader.full, tableType, null, null);

      //

      switch (par.tableTypeMainGroup)
      {
        case DbfTableType.DBF_Ver3:
        case DbfTableType.DBF_Ver4:
        case DbfTableType.DBF_Ver7:
          CreateHeader_dBase(stream, columns, par.tableType, codepageCode);
          break;

        case DbfTableType.Undefined:
          throw ExceptionFactory.CreateArgumentException("tableType", "Undefined table type for CreateHeader_DBF() !");
        default:
          throw ExceptionFactory.CreateArgumentException("tableType", "Invalid table type for CreateHeader_DBF() !");
      }

      if (encoding == null)
      {
        Debug.Assert(codepageCode != CodepageCodes.OEM);
      }
      else
      {
        Debug.Assert(codepageCode == CodepageCodes.OEM);
      }

      DbfTable ret = new DbfTable(stream, par);

      return ret;
    }

    private static void CreateHeader_dBase(Stream stream, IEnumerable<IColumnBase> columns,
                                            DbfTableType tableType     = DbfTableType.Undefined,
                                            CodepageCodes codepageCode = CodepageCodes.OEM)
    {
      if (stream == null)
      {
        throw new ArgumentNullException("stream");
      }

      if (!stream.CanRead)
      {
        throw ExceptionFactory.CreateArgumentException("stream", "The stream does not allow creating (CanRead property returns false).");
      }

      if (!stream.CanWrite)
      {
        throw ExceptionFactory.CreateArgumentException("stream", "The stream does not allow creating (CanWrite property returns false).");
      }

      if (!stream.CanSeek)
      {
        throw ExceptionFactory.CreateArgumentException("stream", "The stream does not allow creating (CanSeek property returns false).");
      }

      //

      var columnDefs = new List<IColumnBase>(columns);

      if (columnDefs.Count < 1)
      {
        throw ExceptionFactory.CreateArgumentException("columns", "Header definition is empty!");
      }

      //

      bool headerVer7;

      switch (DbfTableParameters.GetTableTypeMainGroup(tableType))
      {
        case DbfTableType.DBF_Ver3:
        case DbfTableType.DBF_Ver4:
          headerVer7 = false;
          break;

        case DbfTableType.DBF_Ver7:
          headerVer7 = true;
          break;

        default:
          throw ExceptionFactory.CreateArgumentException("tableType", "Invalid dbf type! [" + tableType + "]");
      }

      //

      DbfFileTypes dbfFileType = headerVer7 ? DbfFileTypes.DBase7 : DbfFileTypes.DBase3;

      short        lengthOfDataRecords = 1;                                         // 1 for 'delete flag'

      foreach (IColumnBase col in columnDefs)
      {
        if (col.dbfType == NativeColumnType.Memo)
        {
          dbfFileType = headerVer7 ? DbfFileTypes.DBase7M : DbfFileTypes.DBase3M;
        }

        lengthOfDataRecords += col.size;
      }

      //

      short positionOfFirstDataRecord;

      if (headerVer7)
      {
        throw new NotImplementedException();    // TODO: !!!
      }
      else
      {
        positionOfFirstDataRecord = (short)(32 + (columnDefs.Count * 32) + 1);
      }

      //

      byte[] lastUpdate = new byte[3];

      {
        int year = DateTime.Now.Year - 2000;
        int month = DateTime.Now.Month;
        int day = DateTime.Now.Day;

        lastUpdate[0] = (byte)year;
        lastUpdate[1] = (byte)month;
        lastUpdate[2] = (byte)day;
      }

      //

      stream.SetLength(0);
      BinaryWriter writer = new BinaryWriter(stream);                           // don't use using '(BinaryWriter reader...' because 'using' dispose 'stream' too!

      writer.Write((byte)dbfFileType);                                          // http://www.dbf2002.com/dbf-file-format.html
      writer.Write(lastUpdate);
      writer.Write((Int32)0);                                                   // "Number of records in file"
      writer.Write(positionOfFirstDataRecord);
      writer.Write(lengthOfDataRecords);
      writer.Write(new byte[16]);
      writer.Write((byte)0);                                                    // "Table flags"
      writer.Write((byte)codepageCode);                                         // 29. byte
      writer.Write(new byte[2]);                                                // reserved

      foreach (IColumnBase col in columnDefs)
      {
        byte[] name = Encoding.ASCII.GetBytes(col.name);
        Array.Resize<byte>(ref name, 11);
        writer.Write(name);

        writer.Write((byte)col.dbfType);

        writer.Write((Int32)0);                                                 // "Displacement of field in record"

        writer.Write((byte)col.size);
        writer.Write((byte)col.dec);

        writer.Write(new byte[14]);                                             // reserved
      }

      writer.Write(headerRecordTerminator);                                     // "Header record terminator"

      //

      if (tableType == DbfTableType.DBF_Ver3_Clipper)
      {
        writer.Write((byte)0x00);                                               // Optional: Extra byte for Clipper (only after header) befor EOF
      }

      writer.Write(endOfFileTerminator);
    }

    private static Stream CreateHeader_Memo(string dbfFileName, MemoFileType memoType)
    {
      switch (memoType)
      {
        case MemoFileType.DBT_Ver3:
        case MemoFileType.DBT_Ver4:
          return CreateHeader_MemoDBT(dbfFileName, memoType);

        case MemoFileType.Undefined:
          throw ExceptionFactory.CreateArgumentException("memoType", "Undefined memo type for CreateHeader_Memo() !");

        default:
          throw ExceptionFactory.CreateArgumentException("memoType", "Invalid memo type for CreateHeader_Memo() !");
      }
    }

    private static Stream CreateHeader_MemoDBT(string dbfFileName, MemoFileType memoFileType, int memoBlockSize = 0)
    {
      string dbtFileName = Path.Combine(Path.GetDirectoryName(dbfFileName), Path.GetFileNameWithoutExtension(dbfFileName) + ".dbt");

      if (memoBlockSize < 1)
      { // Set default
        memoBlockSize = 512;
      }

      switch (memoFileType)
      {
        case MemoFileType.Undefined:
          throw new Exception("CreateHeader_MemoDBT: Don't know MemoFileType parameter value !");
        case MemoFileType.DBT_Ver3:
          if (memoBlockSize != 512)
          {
            throw new Exception("CreateHeader_MemoDBT: DBT version 3 and (memoBlockSize != 512) !");
          }
          break;
        case MemoFileType.DBT_Ver4:
          if ((memoBlockSize < 64) || (memoBlockSize < 32 * 1024))
          {
            throw new Exception("CreateHeader_MemoDBT(" + memoBlockSize + "): DBT version 4 - valid memoBlockSize values are 64..32768 !");
          }

          if ((memoBlockSize % 64) != 0)
          {
            throw new Exception("CreateHeader_MemoDBT(" + memoBlockSize + "): DBT version 4 - valid memoBlockSize is a multiple of 64 !");
          }
          break;
        default:
          throw new Exception("CreateHeader_MemoDBT: Don't handle MemoFileType parameter value !");
      }

      Stream stream = new FileStream(dbtFileName, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None);

      {
        //stream.SetLength(512);                                                // Header block / If the stream is expanded, the contents of the stream between the old and the new length are not defined.
        byte[] headerBlock = new byte[memoBlockSize];                           // Header block is filled with zero

        stream.Write(headerBlock, 0, headerBlock.Length);
      }

      stream.Position = 0;

      BinaryWriter writer = new BinaryWriter(stream);                           // don't use 'using (BinaryWriter writer...' because 'using' dispose 'stream' too!

      writer.Write((Int32)1);                                                   // "Number of next available block for appending data"  http://www.clicketyclick.dk/databases/xbase/format/dbt.html#DBT_STRUCT

      switch (memoFileType)
      {
        case MemoFileType.DBT_Ver3:
          writer.BaseStream.Position = 16;                                      // position of "Version no."                            --''--
          writer.Write((byte)0x03);
          break;

        case MemoFileType.DBT_Ver4:
          writer.BaseStream.Position = 8;                                       // position of "filename"                            --''--
          {
            string fileName  = Path.GetFileNameWithoutExtension(dbtFileName);
            byte[] fileBytes = Encoding.Default.GetBytes(fileName);

            writer.Write(fileBytes, 0, Math.Min(8, fileBytes.Length));
          }
          writer.BaseStream.Position = 16;                                      // position of "Version no."                            --''--
          writer.Write((byte)0x00);
          break;
      }

      writer.BaseStream.Position = 20;
      writer.Write((Int16)memoBlockSize);

      return stream;
    }

    #endregion

    #region MemoFile ----------------------------------------------------------------------------------------

    public void JoinMemoStream(Stream fileStream, MemoFileType memoType = MemoFileType.Undefined)
    {
      if (memoType == MemoFileType.Undefined)
      {
        memoType = parameters.memoType;

        if (memoType == MemoFileType.Undefined)
        { // Scan memo stream for detect type...
          // There aren't any signature in DBT or FPT file, so we can't detect type of it correctly.

          memoType = DefaultMemoFileFormatForDbf();
        }
      }

      if (parameters.encoding == null)
      {
        parameters.encoding = ReadDbfHeader_Encoding(dbfHeader.codepageCode, true);
      }

      switch (memoType)
      {
        case MemoFileType.DBT_Ver3:
        case MemoFileType.DBT_Ver4:
          this._memoFile = new MemoFileDBT(fileStream, parameters.encoding, memoType, parameters.strictHeader);
          break;
        case MemoFileType.Undefined:
          throw ExceptionFactory.CreateArgumentException("memoType", "There isn't information of format of the memory stream!");
        default:
          throw new NotImplementedException();
      }

      //

      var memoFields = from col in _columns
                       where col.dbfType == NativeColumnType.Memo
                       select col;

      foreach (var colDef in memoFields)
      {
        MemoColumn memoColumn = colDef as MemoColumn;

        Debug.Assert(memoColumn != null);

        memoColumn.memoFile = this._memoFile;
      }
    }

    private void JoinMemoFile()
    {
      if (! this.isExistsMemoField)
      {
        Trace.TraceWarning("DbfTable/JoinMemoFile/! isExistsMemoField");
        return;
      }

      if (! parameters.openMemo)
      {
        Trace.TraceWarning("DbfTable/JoinMemoFile/! openMemo");
        return;
      }

      if (parameters.memoType == MemoFileType.Undefined)
      {
        parameters.memoType = DefaultMemoFileFormatForDbf();                          // calculate this from DBF header data
      }

      switch (parameters.memoType)
      {
        case MemoFileType.Undefined:
          {
            string testFilename = Path.ChangeExtension(dataFileName, ".DBT");

            if (File.Exists(testFilename))
            {
              memoFileName = testFilename;
            }
          }
          break;

        case MemoFileType.DBT_Ver3:
        case MemoFileType.DBT_Ver4:
          memoFileName = Path.ChangeExtension(dataFileName, ".DBT");
          break;

        default:
          throw new Exception(String.Format("JoinMemoFile(): untreated MemoFileType! [{0}]", parameters.memoType));
      }

      if (String.IsNullOrWhiteSpace(memoFileName))
      {
        throw new Exception(String.Format("Don't be known the format or name of the memo/blob file for '{0}' DBF file!", this.dataFileName));
      }
      else if (File.Exists(memoFileName))
      {
        var stream = new FileStream(memoFileName, FileMode.Open, parameters.fileAccess, parameters.fileShare);

        JoinMemoStream(stream, parameters.memoType);
      }
      else
      {
        throw new Exception(String.Format("Don't found the '{0}' memo/blob file for '{1}' DBF file!", memoFileName, this.dataFileName));
      }
    }

    #endregion

    #region IndexFile ----------------------------------------------------------------------------------------

    [CLSCompliant(false)]
    public IIndexFile JoinIndexStream(Stream fileStream, bool? skipDeleted = null, IndexFileType indexType = IndexFileType.Undefined)
    {
      IndexFileBase indexFile = null;

      if (indexType == IndexFileType.Undefined)
      {
        indexType = parameters.indexType;
      }

      switch (indexType)
      {
        case IndexFileType.NTX:
          indexFile = new IndexFileNTX(fileStream, this, skipDeleted ?? this.skipDeleted);
          break;
        case IndexFileType.NDX:
          indexFile = new IndexFileNDX(fileStream, this, skipDeleted ?? this.skipDeleted);
          break;
        case IndexFileType.Undefined:
          throw new Exception("JoinIndexStream(): Don't known the format of the index stream!");
        default:
          throw new Exception("JoinIndexStream(): Don't handle the format of the index stream!");
      }

      if (this._indexFiles == null)
      {
        this._indexFiles = new List<IndexFileBase>();
      }

      this._indexFiles.Add(indexFile);

      return indexFile;
    }

    [CLSCompliant(false)]
    public IIndexFile JoinIndexFile(IndexFileType indexType, string indexFileID = null, bool? skipDeleted = null)
    {
      return JoinIndexFile(indexType, null, indexFileID, skipDeleted);
    }

    [CLSCompliant(false)]
    public IIndexFile JoinIndexFile(IndexFileType indexType = IndexFileType.Undefined, char? separatorChar = null, string indexFileID = null, bool? skipDeleted = null)
    {
      string fileName = Path.Combine(Path.GetDirectoryName(this.dataFileName), Path.GetFileNameWithoutExtension(this.dataFileName));

      if (separatorChar != null)
      {
        fileName += separatorChar;
      }

      if (! String.IsNullOrWhiteSpace(indexFileID))
      {
        fileName += indexFileID;
      }

      if (indexType == IndexFileType.Undefined)
      {
        indexType = parameters.indexType;
      }

      switch (indexType)
      {
        case IndexFileType.Undefined:
          throw new Exception("JoinIndexFile(): IndexFileType.Undefined parameter!");
        case IndexFileType.NDX:
          fileName += ".ndx";
          break;
        case IndexFileType.NTX:
          fileName += ".ntx";
          break;
        default:
          throw new Exception("JoinIndexFile(" + indexType + "): Don't handled parameter value !");
      }

      return JoinIndexFile(fileName, skipDeleted);
    }

    [CLSCompliant(false)]
    public IIndexFile JoinIndexFile(string indexFileName, bool? skipDeleted = null)
    {
      string fileName = Path.Combine(Path.GetDirectoryName(indexFileName), Path.GetFileNameWithoutExtension(indexFileName) + ".");
      string fileExt  = Path.GetExtension(indexFileName);

      IndexFileType indexType = parameters.indexType;

      if (fileExt.ToUpper() == ".NDX")
      {
        indexType = IndexFileType.NDX;
      }
      else if (fileExt.ToUpper() == ".NTX")
      {
        indexType = IndexFileType.NTX;
      }
      // .... others too
      else if (indexType == IndexFileType.Undefined)
      { // Scan extension of files for detect type...
        if (File.Exists(fileName + "NDX"))
        {
          indexType = IndexFileType.NDX;
        }
        else if (File.Exists(fileName + "NTX"))
        {
          indexType = IndexFileType.NTX;
        }
        // .... others too
      }

      switch (indexType)
      {
        case IndexFileType.NTX:
          fileName += "NTX";
          break;
        case IndexFileType.NDX:
          fileName += "NDX";
          break;
        case IndexFileType.Undefined:
          throw new Exception("JoinIndexFile(): Don't know the format of index file!");
        default:
          throw new Exception("JoinIndexFile(): Don't handle the format of index file!");
      }

      if (File.Exists(fileName))
      {
        var stream = new FileStream(fileName, FileMode.Open, parameters.fileAccess, parameters.fileShare);

        return JoinIndexStream(stream, skipDeleted, indexType);
      }
      else
      {
        throw ExceptionFactory.CreateArgumentException("indexFileName", "Index file does not found! [{0}/{1}]", indexFileName, fileName);
      }
    }

    #endregion

    #region technical ---------------------------------------------------------------------------------------

    private static string GetIndexExtension(DbfTableType tableType)
    {
      string ret = null;

      switch (tableType)
      {
        case DbfTableType.DBF_Ver3_Clipper:
          ret = ".ntx";
          break;

        case DbfTableType.DBF_Ver3_dBase:
          ret = ".ndx";
          break;

        case DbfTableType.Undefined:
          ret = null;
          break;

        default:
          Debug.Fail("GetIndexExtension(): invalid 'DbfTableType' parameter value!");
          break;
      }

      return ret;
    }

    private void StoreTableType(DbfTableType tableType)
    {
      if (parameters.tableType == DbfTableType.Undefined)
      {
        parameters.tableType = tableType;
      }
      else if (tableType == DbfTableType.Undefined)
      { // Do nothing: Don't forget a better this.tableType value
      }
      else if (parameters.tableType != tableType)
      {
        throw ExceptionFactory.CreateArgumentException("tableType", "Different dbf table type parameter value!");
      }
    }

    public MemoFileType DefaultMemoFileFormatForDbf()
    {
      MemoFileType ret = MemoFileType.Undefined;

      if (_header.newHeaderStructure)
      {
        if (isExistsMemoField)
        {
          ret = MemoFileType.DBT_Ver4;
        }
      }
      else
      {
        switch (_header.type)
        {
          case DbfFileTypes.FoxBASE:
            break;
          case DbfFileTypes.DBase3:
            if (isExistsMemoField)
            {
              ret = MemoFileType.DBT_Ver3;
            }
            break;
          case DbfFileTypes.VisualFoxPro:
            break;
          case DbfFileTypes.VisualFoxPro2:
            break;
          case DbfFileTypes.VisualFoxPro3:
            break;
          case DbfFileTypes.DBase4Sql:
            if (isExistsMemoField)
            {
              ret = MemoFileType.DBT_Ver4;
            }
            break;
          case DbfFileTypes.DBase4SqlSys:
            if (isExistsMemoField)
            {
              ret = MemoFileType.DBT_Ver4;
            }
            break;
          case DbfFileTypes.DBase3M:
             ret = MemoFileType.DBT_Ver3;
            break;
          case DbfFileTypes.DBase4M:
             ret = MemoFileType.DBT_Ver4;
            break;
          case DbfFileTypes.DBase4SqlM:
             ret = MemoFileType.DBT_Ver4;
            break;
          case DbfFileTypes.FoxPro2M:
            break;
          case DbfFileTypes.HiperSix:
            break;
          case DbfFileTypes.FoxBASE2:
            break;
          default:
            ret = MemoFileType.Undefined;
            break;
        }
      }

      return ret;
    }
    #endregion
  }
}


text:
/********************************************************************
 * 2014 -
 * open source under Apache License Version 2.0
 ********************************************************************/
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#ifndef _HDFS_LIBHDFS3_COMMON_FILEWRAPPER_H_
#define _HDFS_LIBHDFS3_COMMON_FILEWRAPPER_H_

#include <string>
#include <cassert>
#include <cstdio>
#include <string>
#include <vector>

namespace Hdfs {
namespace Internal {

class FileWrapper {
public:
    virtual ~FileWrapper() {
    }

    virtual bool open(int fd, bool delegate) = 0;
    virtual bool open(const std::string & path) = 0;
    virtual void close() = 0;
    virtual const char * read(std::vector<char> & buffer, int32_t size) = 0;
    virtual void copy(char * buffer, int32_t size) = 0;
    virtual void seek(int64_t position) = 0;
};

class CFileWrapper: public FileWrapper {
public:
    CFileWrapper();
    ~CFileWrapper();
    bool open(int fd, bool delegate);
    bool open(const std::string & path);
    void close();
    const char * read(std::vector<char> & buffer, int32_t size);
    void copy(char * buffer, int32_t size);
    void seek(int64_t offset);

private:
    FILE * file;
    std::string path;
};

class MappedFileWrapper: public FileWrapper {
public:
    MappedFileWrapper();
    ~MappedFileWrapper();
    bool open(int fd, bool delegate);
    bool open(const std::string & path);
    void close();
    const char * read(std::vector<char> & buffer, int32_t size);
    void copy(char * buffer, int32_t size);
    void seek(int64_t offset);

private:
    bool openInternal(int fd, bool delegate, size_t size);

private:
    bool delegate;
    const char * begin;
    const char * position;
    int fd;
    int64_t size;
    std::string path;
};

}
}

#endif /* _HDFS_LIBHDFS3_COMMON_FILEWRAPPER_H_ */


text:
Generic monkey patching tool to keep patches better organised and uniform.

## Using patchy

**patchy(target, source=None)**
Takes a target (class or module to be patched) and source (class or module to pull patches from) and returns an instance that allows you to apply patches.
Source or target can be a class or module instance, or a dotted path to one.
If source is not provided, then _auto()_ and _apply(attrs)_ will not be able to source items to patch and will require them provided directly.

```python
from patchy import patchy

with patchy('django', 'my_djago_patch') as p:
    p.add('something_new', named=my_func)
    p.cls('db', 'my_db_patch').auto()
```

**super_patchy(\*args, do_call=True, \*\*kwargs)**
When called from within a function that has been monkey patched into somewhere else by patchy, will call or return the function that it replaced. If called from a function that appears to be bound (first argument is _self_ or _cls_) will also bind that value to the replaced function, so these never need to be provided.
When called with _do_call=False_ will return the function itself.
When called without _do_call_ then will call the replaced function passing _\*args_ and _\*\*kwargs_ and return the return value from it.

```python
from patchy import super_patchy

def new_func(arg):
    super_patchy(arg)
    old_func = super_patchy(do_call=False)
```

## Patchy instances

**add(\*attrs, \*\*kattrs)**
_apply()_ without merge.

**merge(\*attrs, \*\*kattrs)**
_apply()_ with merge.

**auto(merge=True, types=object)**
Apply non-private (startswith('\_')) locally declared objects (hasattr('\_\_module__')) such as functions and classes) of the source to the target. Also applies any attribute (regardless of type) in the _instance.allow_ set.
_(class patching)_ Also apply all primative attributes. Default _allow_ includes {'\_\_init__', '\_\_new__'}
_(module patching)_ Default _allow_ includes {'\_\_all__'}

**apply(attrs, kattrs, merge=False)**
Any attrs with a *\_\_name__* attribute will be applied to the target with that as their attribute name.
Any values provided as attrs will be fetched from the provided source and applied to the target.
Any values provided as kattrs will be applied directly to the target with the name specified.
Merge will attempt to combine collections and _auto()_ patch classes instead of replacing them.

**cls(target, source=None)** (modules only)
Get a patchy instance for the specified class, relative to the module being patched.
If source is not specified it will attempt to be derived from the source of this instance.
For example, from patchy('django', 'django_patch').cls('db.models.Model'):
 * Look for class within a containing module via full name relative to this instance substituting module_sep (default '\_')
 ie, 'Model' within 'django_db_models' relative to 'django_patch'
 * Look for class within the source module for this instance.
 ie, 'Model' within 'django_patch'

**mod(target, source=None)** (module only)
Get a patchy instance for the specified module, relative to the module being patched.
If source is not specified it will attempt to be derived from the source of this instance.
For example, from patchy('django', 'django_patch').mod('db.models'):
 * Look for module via short name relative to this instance.
 ie, 'db.models' relative to 'django_patch'
 * Look for module via full name relative to this instance substituting module_sep (default '\_')
 ie, 'django_db_models' relative to 'django_patch'