text:
package ORG.oclc.oai.server.crosswalk;

import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import ORG.oclc.oai.server.verb.CannotDisseminateFormatException;

/**
 * Converts a native "item" to an OAI metadataFormat.
 */
public abstract class Crosswalk {
    /**
     * The schemaLocation supported by this crosswalk
     */
    private String schemaLocation;
    private String contentType;
    private String docType;
    private String encoding;

    /**
     * Constructor
     *
     * @param schemaLocation the schemaLocation supported by this crosswalk
     */
    public Crosswalk(String schemaLocation) {
        this(schemaLocation, (String)null);
    }

    /**
     * Constructor
     *
     * @param schemaLocation the schemaLocation supported by this crosswalk
     */
    public Crosswalk(String schemaLocation, String contentType) {
        this(schemaLocation, contentType, (String)null);
    }

    public Crosswalk(String schemaLocation, String contentType, String docType) {
        this(schemaLocation, contentType, docType, (String)null);
    }
    /**
     * Constructor
     *
     * @param schemaLocation the schemaLocation supported by this crosswalk
     */
    public Crosswalk(String schemaLocation, String contentType, String docType, String encoding) {
        this.schemaLocation = schemaLocation;
        if (contentType == null)
            contentType = "text/xml; charset=UTF-8";
        this.contentType = contentType;
        this.docType = docType;
        this.encoding = encoding;
    }

    /**
     * returns the schemaLocation
     *
     * @return the schemaLocation
     */
    public String getSchemaLocation() { return schemaLocation; }

    public String getContentType() { return contentType; }

    public String getDocType() { return docType; }

    public String getEncoding() { return encoding; }

    /**
     * parse the schemaURL from the schemaLocation
     *
     * @return the schemaURL portion of the schemaLocation
     */
    public String getSchemaURL() {
	StringTokenizer tokenizer = new StringTokenizer(schemaLocation, " ");
	String temp = tokenizer.nextToken();
	try {
	    return tokenizer.nextToken();
	} catch (NoSuchElementException e) {
	    // no namespace for the format
	    return temp;
	}
    }

    /**
     * parse the namespaceURL from the schemaLocation
     *
     * @return the namespaceURL portion of the schemaLocation
     */
    public String getNamespaceURL() {
	StringTokenizer tokenizer = new StringTokenizer(schemaLocation, " ");
	return tokenizer.nextToken();
    }

    /**
     * Can this nativeItem be represented in ETDMS format?
     * @param nativeItem a record in native format
     * @return true if ETDMS format is possible, false otherwise.
     */
    public abstract boolean isAvailableFor(Object nativeItem);

    /**
     * Perform the actual crosswalk.
     *
     * @param nativeItem the native "item". In this case, it is
     * already formatted as an OAI <record> element, with the
     * possible exception that multiple metadataFormats are
     * present in the <metadata> element.
     * @return a String containing the XML to be stored within the <metadata> element.
     * @exception CannotDisseminateFormatException nativeItem doesn't support this format.
     */
    public abstract String createMetadata(Object nativeItem)
	throws CannotDisseminateFormatException;

    /**
     * returns the schemaLocation for this crosswalk.
     * @return a String containing the schemaLocation.
     */
    public String toString() {
	return schemaLocation;
    }
}


text:
namespace remoting {

// Block size and format (BGRA 32 bit) are fixed.
static const int kBlockWidth = 32;
static const int kBlockHeight = 32;
static const int kBytesPerPixel = 4;

// Low level functions to compare 2 blocks of pixels.
//   zero means the blocks are identical.
//   one means  the blocks are different.
int BlockDifference(const uint8* image1, const uint8* image2, int stride);

}  // namespace remoting

#endif  // REMOTING_HOST_DIFFER_BLOCK_H_

redpajama_set_name: RedPajamaGithub


text:
require 'sidekiq/web'

Rails.application.routes.draw do

  Sidekiq::Web.use Rack::Auth::Basic do |username, password|
    username == ENV['SIDEKIQ_USERNAME'] && password == ENV['SIDEKIQ_PASSWORD']
  end

  mount Sidekiq::Web => '/sidekiq'

  root :to => 'users#index'

  resources :kitchens do
    member do
      get 'reservations_all'
      get 'reservations_pending'
      get 'reservations_approved'
      get 'reservations_denied'
    end
  end

  resources :reservations, :only => [:update, :edit]

  resources :kitchens, :except => [:index] do
    resources :reservations, :except => [:update, :edit]
    resources :photos do
      member do
        get 'set_as_front_page_photo', :action => 'set_as_front_page_photo'
      end
    end
  end

  resources :users, :except => :destroy do
    collection do
      get 'kitchens'
    end
    collection do
      get 'reservations_all'
      get 'reservations_pending'
      get 'reservations_approved'
      get 'reservations_denied'
    end
  end

  controller :sessions do
    get '/auth/facebook/callback', :action => 'create'
    get  '/session',               :action => 'show'
    get '/logout',                 :action => 'destroy',       :as => 'logout'
  end

  #omniauth-facebook routes

  get '/auth/facebook/callback',   :to => 'sessions#create'
  get '/auth/facebook',                                        :as => "facebook_login"

  controller :static_pages do
    get '/:page_name', :action => 'show', :as => 'page'
  end

end


text:
import { delay } from "redux-saga";
import { put, select, takeLatest } from "redux-saga/effects";
import storage from "../storage";
import { cdbPromise } from "../util";

import math from "mathjs";

/**
 * Validates and queries ConnectorDB for a dataset. Shows errors if necessary.
 */
function* query(action) {
  // First, validate all fields
  let analysis = yield select(state => state.pages.analysis);

  // Do the same for each element of the dataset
  let datasetKeys = Object.keys(analysis.dataset);
  for (let i = 0; i < datasetKeys.length; i++) {
    let currentdataset = analysis.dataset[datasetKeys[i]];
    if (
      currentdataset.stream.length === 0 ||
      currentdataset.stream.split("/").length != 3
    ) {
      yield put({
        type: "ANALYSIS_ERROR",
        value: "Invalid stream name (" + datasetKeys[i] + ")"
      });
      return;
    }
  }

  // This is the format in which the ConnectorDB server expects a query
  let query = {
    posttransform: analysis.posttransform,
    dataset: analysis.dataset,
    t1: analysis.t1.unix(),
    t2: analysis.t2.unix(),
    limit: 0,
    allownil: false
  };

  if (analysis.xdataset) {
    if (
      analysis.stream.length === 0 || analysis.stream.split("/").length != 3
    ) {
      yield put({
        type: "ANALYSIS_ERROR",
        value: "Invalid correlation stream name"
      });
      return;
    }
    query.stream = analysis.stream;
    query.transform = analysis.transform;
  } else {
    // Make sure that dt is a number
    try {
      let dt = math.eval(analysis.dt);
      if (isNaN(dt) || dt < 0.001) {
        yield put({
          type: "ANALYSIS_ERROR",
          value: "Invalid time delta (" + analysis.dt + ")"
        });
        return;
      }
      query.dt = dt;
    } catch (e) {
      yield put({
        type: "ANALYSIS_ERROR",
        value: "Invalid time delta (" + analysis.dt + ")"
      });
      return;
    }
  }

  // Alright, validation complete. Let's query for the dataset
  yield put({ type: "SHOW_DATASET", value: [] }); // First clear any data that might be there
  yield put({ type: "ANALYSIS_LOADING", value: true }); // Next turn loading on

  try {
    let dataset = yield cdbPromise(
      storage.cdb._doRequest("query/dataset", "POST", query),
      5 * 60 * 1000
    );
    yield put({ type: "SHOW_DATASET", value: dataset });
  } catch (err) {
    console.log(err);
    yield put({ type: "ANALYSIS_ERROR", value: err.toString() });
    yield put({ type: "ANALYSIS_LOADING", value: false });
  }
}

import React from "react";
import "codemirror/lib/codemirror.css";
import "codemirror/theme/monokai.css";
import CodeMirror from "react-codemirror";
import "codemirror/mode/python/python";

function* showPython(action) {
  let analysis = yield select(state => state.pages.analysis);
  let username = yield select(state => state.site.thisUser.name);

  let interpolations = "";
  let datasetKeys = Object.keys(analysis.dataset);
  for (let i = 0; i < datasetKeys.length; i++) {
    let currentdataset = analysis.dataset[datasetKeys[i]];
    interpolations =
      interpolations +
      `d.addStream("${currentdataset.stream}","${currentdataset.interpolator}",` +
      (currentdataset.transform != ""
        ? `transform=${JSON.stringify(currentdataset.transform)},`
        : "") +
      `colname="${datasetKeys[i]}")` +
      "\n";
  }

  let pythoncode =
    `import connectordb
from connectordb.query import Dataset

import getpass
p = getpass.getpass()

cdb = connectordb.ConnectorDB("${username}",p,url="${SiteURL}")

d = Dataset(cdb,${analysis.xdataset ? '"' + analysis.stream + '"' : "dt=" + analysis.dt},t1=${analysis.t1.unix()},t2=${analysis.t2.unix()}` +
    (analysis.transform == "" || !analysis.xdataset
      ? ""
      : `,
        transform=${JSON.stringify(analysis.transform)}`) +
    (analysis.posttransform == ""
      ? ""
      : `,
        posttransform=${JSON.stringify(analysis.posttransform)}`) +
    ")\n" +
    interpolations +
    `
data = d.run()
`;

  yield put({
    type: "SHOW_DIALOG",
    value: {
      title: "Python Code",
      open: true,
      contents: (

          <CodeMirror
            value={pythoncode}
            options={{
              mode: "text/x-python",
              lineWrapping: true,
              readOnly: true
            }}
          />

            Python API Docs

      )
    }
  });
}

// This should move to a different file at some point
function* showPythonQuery(action) {
  let stream = yield select(state => state.stream[action.value].view);
  let username = yield select(state => state.site.thisUser.name);
  let varname = action.value.split("/")[2];
  let pythoncode = `import connectordb

import getpass
p = getpass.getpass()

cdb = connectordb.ConnectorDB("${username}",p,url="${SiteURL}")

${varname} = cdb("${action.value}")

`;
  if (!stream.bytime && stream.transform == "") {
    pythoncode += `data = ${varname}[${stream.i1}:${stream.i2}]`;
  } else if (!stream.bytime && stream.transform != "") {
    pythoncode += `data = ${varname}(i1=${stream.i1},i2=${stream.i2},transform=${JSON.stringify(stream.transform)})`;
  } else {
    // by time
    pythoncode +=
      `data = ${varname}(t1=${stream.t1.unix()},t2=${stream.t2.unix()}` +
      (stream.transform != ""
        ? `,transform=${JSON.stringify(stream.transform)}`
        : "") +
      ")";
  }

  yield put({
    type: "SHOW_DIALOG",
    value: {
      title: "Python Code",
      open: true,
      contents: (

          <CodeMirror
            value={pythoncode}
            options={{
              mode: "text/x-python",
              lineWrapping: true,
              readOnly: true
            }}
          />

            Python API Docs

      )
    }
  });
}

// Our watcher Saga: spawn a new incrementAsync task on each INCREMENT_ASYNC
export default function* analysisSaga() {
  yield takeLatest("DATASET_QUERY", query);
  yield takeLatest("SHOW_ANALYSIS_CODE", showPython);
  yield takeLatest("SHOW_QUERY_CODE", showPythonQuery);
}


text:
This project demonstrates how to develop an offline enabled [OpenUI5](http://openui5.org/) stock application using the [AppCache API](https://developer.mozilla.org/en-US/docs/Web/HTML/Using_the_application_cache) and [LocalStorage](https://developer.mozilla.org/de/docs/Web/API/Window/localStorage).

You can try it out here:
https://pensoffsky.github.io/OpenUI5-AppCache/index.html

# Features
The app is able to run offline in all current browsers. It implements a very basic stock application. The last fetched data is persisted in the browser and even in airplane mode the app is reachable and will display the last fetched stock quotes.

# Concepts
## AppCache for UI5 & app resources
The [manifest.appcache](https://github.com/pensoffsky/OpenUI5-AppCache/blob/gh-pages/manifest.appcache) file defines which resources shall be stored in the browser for offline usage.

```
    CACHE MANIFEST
    resources/sap-ui-core.js
    resources/sap/m/library-preload.json
    resources/sap/ui/core/library-preload.json
    resources/sap/ui/thirdparty/jquery-mobile-custom.js
    resources/sap/ui/core/themes/sap_bluecrystal/library.css
    resources/sap/m/themes/sap_bluecrystal/library.css
    resources/sap/ui/core/messagebundle_en.properties
    resources/sap/m/messagebundle_en.properties
    resources/jquery.sap.storage.js
    resources/sap/ui/core/themes/base/fonts/SAP-icons.ttf
    resources/sap/ui/core/themes/sap_bluecrystal/library-parameters.json
    resources/sap/m/themes/sap_bluecrystal/library-parameters.json

    resources/sap/ui/thirdparty/unorm.js
    resources/sap/ui/thirdparty/unormdata.js
    resources/sap/ui/core/themes/base/fonts/SAP-icons.eot

    de.pensware.ui5StocksApp/Component.js
    de.pensware.ui5StocksApp/manifest.json
    de.pensware.ui5StocksApp/view/Main.view.xml
    de.pensware.ui5StocksApp/view/Main.controller.js

    de.pensware.financeAPI/Component.js
    de.pensware.financeAPI/js/stockQuotesAPI.js

    NETWORK:
    *
```

Everything below CACHE MANIFEST defines all the OpenUI5 and app resources needed to run the app. All these files are fetched on the first start of the app and are then available for offline usage. **NETWORK: *** means that every network request not specified in CACHE MANIFEST will be sent directly to the network.

## Component based design
The code related to fetching the stock quotes from yahoo is encapsulated into a [faceless component](http://help.sap.com/saphelp_nw74/helpdata/en/95/8ead51e2e94ab8bcdc90fb7e9d53d0/content.htm).
This [financeAPI component](https://github.com/pensoffsky/OpenUI5-AppCache/tree/gh-pages/de.pensware.financeAPI) is loaded with the following code:
```
var ofinanceAPI = sap.ui.component( {name: "de.pensware.financeAPI" } )
var oStockQuotesAPI = ofinanceAPI.getStockQuotesAPI();
```

## LocalStorage to persist data
Stock symbols and fetched data from yahoo finance api are stored in local storage for offline usage.

##Model View Controller + light weight ViewModel
The Main.view.xml is XML format. The Main.controller.js instantiates a JSONModel and sets it with the name "localUIModel" to the view.
```
_createAndSetLocalUIModel : function () {
	this._localUIModel = new sap.ui.model.json.JSONModel();
	this._localUIModel.setData({
		symbols: [{symbol: "test", price: "489"}, {symbol: "MSFT", price: ""}],
		newSymbol: "",
		aMessages: [],
		listMode: sap.m.ListMode.None
	});
	this.getView().setModel(this._localUIModel, "localUIModel");
}
```

Every input the user makes or data the app wants to display is written into this model. This way the Main.controller.js makes no assumptions on how the data is displayed and the Main.view.xml can be changed without having to change javascript code.

This also makes the controller testable. An event handler like onToggleListMode is only modifying the "localUIModel" and that can be tested very easily.
```
onToggleListMode : function () {
	var sCurrentMode = this._localUIModel.getProperty("/listMode");
	if (sCurrentMode === sap.m.ListMode.None) {
		this._localUIModel.setProperty("/listMode", sap.m.ListMode.Delete);
	} else {
		this._localUIModel.setProperty("/listMode", sap.m.ListMode.None);
	}
}
```

The test:
```
QUnit.test("onToggleListMode function", function (assert) {
	var oLocalUIModelData = this._oCntrllr._localUIModel.getData();
	//initial mode is sap.m.ListMode.None
	assert.equal(oLocalUIModelData.listMode, sap.m.ListMode.None);

	this._oCntrllr.onToggleListMode();
	assert.equal(oLocalUIModelData.listMode, sap.m.ListMode.Delete);

	this._oCntrllr.onToggleListMode();
	assert.equal(oLocalUIModelData.listMode, sap.m.ListMode.None);
});
```

## Injecting dependencies into controller for better testability
The stockquotes API object and the storage object are injected into the Main.controller.
This way the Main.controller can be instantiated with a mock version of the stockquotes API object for easy [unit testing](https://github.com/pensoffsky/OpenUI5-AppCache/blob/gh-pages/de.pensware.ui5StocksApp%2Ftest%2Funit%2Fview%2FMainController.js).
```
var oStockQuotesAPI = {
	fetchData: function () {
		return {
			fail: function () {}
		}
	}
};
var oStorage = jQuery.sap.storage(jQuery.sap.storage.Type.session);
this._oCntrllr = new de.pensware.ui5StocksApp.view.Main(oStockQuotesAPI, oStorage);
```


text:
package io.hekate.cluster.seed.etcd;

import io.hekate.HekateTestProps;
import io.hekate.cluster.seed.PersistentSeedNodeProviderTestBase;
import io.hekate.core.HekateException;
import io.hekate.core.report.DefaultConfigReporter;
import java.net.InetSocketAddress;
import java.util.function.Consumer;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Test;

import static io.hekate.core.internal.util.Utils.NL;
import static org.junit.Assert.assertEquals;

public class EtcdSeedNodeProviderTest extends PersistentSeedNodeProviderTestBase<EtcdSeedNodeProvider> {
    private static String url;

    @BeforeClass
    public static void prepareTestClass() {
        // May be disable the whole test class.
        Assume.assumeTrue(HekateTestProps.is("ETCD_ENABLED"));

        url = HekateTestProps.get("ETCD_URL");
    }

    @Override
    public void setUp() throws Exception {
        EtcdSeedNodeProvider provider = createProvider();

        provider.findSeedNodes(CLUSTER_1).forEach(address -> {
            try {
                provider.unregisterRemote(CLUSTER_1, address);
            } catch (HekateException e) {
                // No-op.
            }
        });

        provider.findSeedNodes(CLUSTER_2).forEach(address -> {
            try {
                provider.unregisterRemote(CLUSTER_2, address);
            } catch (HekateException e) {
                // No-op.
            }
        });

        super.setUp();
    }

    @Override
    public void tearDown() throws Exception {
        super.tearDown();

        // Need to await for gRPC-related threads termination
        // as there seems to be no way to hook into the Etcd client's shutdown logic.
        awaitForNoSuchThread("grpc-default");
    }

    @Test
    public void testConfigReport() throws Exception {
        EtcdSeedNodeProvider provider = createProvider();

        assertEquals(
            NL
                + "  etcd:" + NL
                + "    endpoints: " + provider.endpoints() + NL
                + "    base-path: " + provider.basePath() + NL
                + "    cleanup-interval: " + provider.cleanupInterval() + NL,
            DefaultConfigReporter.report(provider)
        );
    }

    @Test
    public void testErrors() throws Exception {
        EtcdSeedNodeProvider provider = createProvider(cfg -> {
            // Invalid user.
            cfg.setUsername("invalid");
            cfg.setPassword("invalid");
        });

        InetSocketAddress address = newSocketAddress();

        expect(HekateException.class, () ->
            provider.startDiscovery(CLUSTER_1, address)
        );

        expect(HekateException.class, () ->
            provider.findSeedNodes(CLUSTER_1)
        );

        expect(HekateException.class, () ->
            provider.registerRemote(CLUSTER_1, address)
        );

        expect(HekateException.class, () ->
            provider.unregisterRemote(CLUSTER_1, address)
        );

        expect(HekateException.class, () ->
            provider.stopDiscovery(CLUSTER_1, address)
        );
    }

    @Override
    protected EtcdSeedNodeProvider createProvider() throws Exception {
        return createProvider(null);
    }

    private EtcdSeedNodeProvider createProvider(Consumer<EtcdSeedNodeProviderConfig> configurer) throws Exception {
        EtcdSeedNodeProviderConfig cfg = new EtcdSeedNodeProviderConfig()
            .withBasePath("/hekate/test")
            .withCleanupInterval(100)
            .withEndpoint(url);

        if (configurer != null) {
            configurer.accept(cfg);
        }

        return new EtcdSeedNodeProvider(cfg);
    }
}


text:
/*********************************************************************************************************************
**
** Procedure Name	:	h3giCurrentCreditLimitsBusinessGet
** Author			:	Simon Markey
** Date Created		:
** Version			:	1.0.0
**
** Test				:	exec h3giCurrentCreditLimitsBusinessGet
**********************************************************************************************************************
**
** Description		:	Gets all the business credit limits and shadow limits
**
**********************************************************************************************************************/
CREATE PROCEDURE [dbo].[h3giCurrentCreditLimitsBusinessGet]
AS
BEGIN
	SELECT
	limitId AS LimitID,
	creditLimit AS Limit,
	shadowLimit AS Shadow
	FROM h3giCurrentCreditLimits
	WHERE isbusiness = 1
	ORDER BY creditLimit ASC
END

GRANT EXECUTE ON h3giCurrentCreditLimitsBusinessGet TO b4nuser
GO


text:
@interface MKMutableParallelArrayTest : XCTestCase

@end

@implementation MKMutableParallelArrayTest

- (void)setUp
{
    [super setUp];
    // Put setup code here. This method is called before the invocation of each test method in the class.
}

- (void)tearDown
{
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    [super tearDown];
}

- (void)testObjectAtIndex
{
    MKMutableParallelArray *mutableParallelArray = [[MKMutableParallelArray alloc] init];
    NSString               *object0              = @"Object1";
    NSString               *object1              = @"Object1";
    [mutableParallelArray addObject:object0];
    [mutableParallelArray addObject:object1];
    XCTAssertTrue([mutableParallelArray objectAtIndex:0] == object0, "Index 0 should be object0");
    XCTAssertTrue([mutableParallelArray objectAtIndex:1] == object1, "Index 1 should be object1");
}

- (void)testRemoveObject
{
    MKMutableParallelArray *mutableParallelArray = [[MKMutableParallelArray alloc] init];
    NSString               *object0              = @"Object1";
    NSString               *object1              = @"Object1";
    [mutableParallelArray addObject:object0];
    [mutableParallelArray addObject:object1];
    [mutableParallelArray removeObject:object0];
    XCTAssertTrue([mutableParallelArray objectAtIndex:0] == object1,
                  "object0 at index 0 should have been replaced by object1");
}

- (void)testAsArray
{
    MKMutableParallelArray *mutableParallelArray = [[MKMutableParallelArray alloc] init];
    NSString               *object0              = @"Object1";
    NSString               *object1              = @"Object1";
    [mutableParallelArray addObject:object0];
    [mutableParallelArray addObject:object1];
    NSArray *array = mutableParallelArray.asArray;
    [mutableParallelArray removeObject:array[0]];
    XCTAssertTrue([mutableParallelArray objectAtIndex:0] == object1,
                  "object0 at index 0 should have been replaced by object1");
}

@end


text:
package org.lemsml.jlems.core.type.structure;

import org.lemsml.jlems.core.expression.ParseError;
import org.lemsml.jlems.core.run.BuilderElement;
import org.lemsml.jlems.core.run.OtherwiseBuilder;
import org.lemsml.jlems.core.sim.ContentError;
import org.lemsml.jlems.core.type.Component;
import org.lemsml.jlems.core.type.ComponentType;
import org.lemsml.jlems.core.type.Lems;

public class Otherwise extends BuildElement {

	public BuilderElement makeBuilder(Component cpt) throws ContentError {
		return new OtherwiseBuilder();
	}

	@Override
	public void resolveLocal(Lems lems, ComponentType ct) throws ContentError, ParseError {
		// TODO Auto-generated method stub

	}

}


text:
AssemblerController::AssemblerController(QObject *parent)
   : QObject(parent),
     m_timer(NULL),
     m_speed(NORMAL),
     m_state(NO_SOURCE)
{
    m_timer = new QTimer(this);
    connect(m_timer, &QTimer::timeout, this, &AssemblerController::timerUpdate);
}

void AssemblerController::setSourceCode(const QString &asmSource)
{
    m_assembler.setSourceCode(asmSource);
    setState(asmSource.trimmed().isEmpty() ? NO_SOURCE : RESET);
    m_assembler.parse();
}

bool AssemblerController::lineHasError(int line) const
{
    if (m_assembler.errors().isEmpty())
        return false;
    for (const Assembler::Error& error : m_assembler.errors()) {
        if (error.line == line)
            return true;
    }
    return false;
}

void AssemblerController::timerUpdate()
{
    translateNextLine();
    if (m_timer->interval() != timerInterval())
        m_timer->setInterval(timerInterval());
}

int AssemblerController::timerInterval()
{
    static const int NORMAL_TIMER_INTERVAL = 1000;
    static const double INTERVAL_MULTIPLIER[] = { 2.0, 1.5, 1.0, 0.5, 0.25 };
    return qRound(NORMAL_TIMER_INTERVAL * INTERVAL_MULTIPLIER[m_speed]);
}

void AssemblerController::translateNextLine()
{
    m_assembler.translateNextLine();
    if (m_assembler.hasMoreLines())
        emit currentLineChanged(m_assembler.binaryCode().length() - 1);
    else
        setState(FINISHED);
}

void AssemblerController::setState(AssemblerController::State newState)
{
    if (m_state == newState) return;
    m_state = newState;

    if (m_state == RUNNING)
        m_timer->start(0);
    else if (m_timer->isActive())
        m_timer->stop();

    emit stateChanged(m_state);
}

void AssemblerController::run()
{
    if (m_state == FINISHED)
        reset();
    setState(RUNNING);
}

void AssemblerController::pause()
{
    setState(PAUSED);
}

void AssemblerController::step()
{
    if (m_state == RUNNING || m_state == RESET)
        pause();
    else if (m_state == FINISHED)
        reset();
    translateNextLine();
}

void AssemblerController::reset()
{
    m_assembler.clearTranslationData();
    setState(RESET);
}

void AssemblerController::translateAll()
{
    m_assembler.translateAll();
    setState(FINISHED);
}


text:
#include "../../generic/akin/LuvCH.hpp"
#include "../category.hpp"
#include "../../lms/category.hpp"

namespace color
 {
  namespace akin
   {

    template
     <
       typename tag_name
      ,::color::constant::lms::reference_enum reference_number

     >
     struct LuvCH< ::color::category::lms< tag_name, reference_number >  >
      {
       public:
         typedef ::color::category::LuvCH< tag_name > akin_type;
      };

   }
 }

#endif


text:
package org.elasticsearch.client.node;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionType;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.TransportAction;
import org.elasticsearch.client.AbstractClientHeadersTestCase;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.tasks.TaskManager;
import org.elasticsearch.transport.Transport;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import static org.mockito.Mockito.mock;

public class NodeClientHeadersTests extends AbstractClientHeadersTestCase {

    private static final ActionFilters EMPTY_FILTERS = new ActionFilters(Collections.emptySet());

    @Override
    protected Client buildClient(Settings headersSettings, ActionType[] testedActions) {
        Settings settings = HEADER_SETTINGS;
        TaskManager taskManager = new TaskManager(settings, threadPool, Collections.emptySet());
        Actions actions = new Actions(testedActions, taskManager);
        NodeClient client = new NodeClient(settings, threadPool);
        client.initialize(actions, taskManager, () -> "test",
            mock(Transport.Connection.class), null, new NamedWriteableRegistry(List.of()));
        return client;
    }

    private static class Actions extends HashMap<ActionType, TransportAction> {

        private Actions(ActionType[] actions, TaskManager taskManager) {
            for (ActionType action : actions) {
                put(action, new InternalTransportAction(action.name(), taskManager));
            }
        }
    }

    private static class InternalTransportAction extends TransportAction {

        private InternalTransportAction(String actionName, TaskManager taskManager) {
            super(actionName, EMPTY_FILTERS, taskManager);
        }

        @Override
        protected void doExecute(Task task, ActionRequest request, ActionListener listener) {
            listener.onFailure(new InternalException(actionName));
        }
    }

}


text:
**People that would directly benefit from my solution

 	1 - Company excutives and stakeholders
	2 - Wholesale Distribution outlets
	3 - Retailers
	4 - Consumers

** Secondary audience
	1 - Oversees Markets
	2 - Logistics Companies
	3 - Non for profit organizations
	4 - Family members Oversees

** Who are the proponates
	1 - Marketers
	2 - CEO's
	3 - Resllers
	4 - IT

** Who are the skeptics
	1 - Internal customers (Company Buyers)
	2 - Amazon
	3 - Google

** PERSONA MAPPING **
![Personas.pptx](i)

* FEATURES AND USEER STORIES*

- A predictive analysis recommedation engines
- A Realtime inventory control notifications
- Avdanced product search functions

** User Stories**

	As a internet distributer I would use the predictive analysis function to notify me of customer buying habits.

	I am a order processor and I would employ the realtime inventory control function to set purchase alerts.

	I am a consumer and I would use the advanced product seaarch function to compare prices of similar products sold online.


text:
layout: post
tags:
  - solaris
  - snmp
redirect_from:
  - /2006/09/08/
  - /solaris-zone-utilisation-via-snmp/
title:
---

It's been a bug-bear for a long time for me that the CPU metrics when querying a Solaris 10 host are global and not zone specific (which of course makes sense, just makes it harder to track zone utilisation).

So finally wrote a basic perl script that will provide that information via a SNMP mib, output looks like the following:

```bash
> snmpwalk -v 1 -c public localhost .1.3.6.1.4.1.2021.255.7
UCD-SNMP-MIB::ucdavis.255.7.0 = STRING: "Zone name"
UCD-SNMP-MIB::ucdavis.255.7.1 = STRING: "global"
UCD-SNMP-MIB::ucdavis.255.7.2 = STRING: "gallery"
UCD-SNMP-MIB::ucdavis.255.7.3 = STRING: "nakos"
UCD-SNMP-MIB::ucdavis.255.7.4 = STRING: "mcdougallfamily"
UCD-SNMP-MIB::ucdavis.255.7.5 = STRING: "shared"
UCD-SNMP-MIB::ucdavis.255.7.6 = STRING: "packer"
UCD-SNMP-MIB::ucdavis.255.7.7 = STRING: "si"
```
Script is available at [here](....)

Current bugs/issues
> snmpwalk will not step through all the sub-trees


text:
/* global chai */
/* global sinon */
/* global describe */
/* global it */
/* global expect */

import _ from 'lodash';

import mutationTracker from 'object-invariant-test-helper';

import { pendingReceivedClinicianInvites as reducer } from '../../../../app/redux/reducers/misc';

import * as actions from '../../../../app/redux/actions/index';

import { pendingReceivedClinicianInvites as initialState } from '../../../../app/redux/reducers/initialState';

var expect = chai.expect;

describe('pendingReceivedClinicianInvites', () => {
  describe('fetchClinicianInvitesSuccess', () => {
    it('should set state to an array of pending invites', () => {
      let initialStateForTest = [];
      let tracked = mutationTracker.trackObj(initialStateForTest);

      let pendingReceivedClinicianInvites = [
        { key: 'xyz123zyx' },
        { key: 'abc987cba' }
      ];

      let action = actions.sync.fetchClinicianInvitesSuccess(pendingReceivedClinicianInvites);

      let state = reducer(initialStateForTest, action);

      expect(state.length).to.equal(pendingReceivedClinicianInvites.length);
      expect(mutationTracker.hasMutated(tracked)).to.be.false;
    });
  });

  describe('acceptClinicianInviteSuccess', () => {
    it('should remove accepted membership from state array', () => {
      let initialStateForTest = [
        { key: 'xyz123zyx' },
        { key: 'abc987cba' }
      ];
      let tracked = mutationTracker.trackObj(initialStateForTest);

      let membership = { key: 'abc987cba' };

      let action = actions.sync.acceptClinicianInviteSuccess(membership.key);

      let state = reducer(initialStateForTest, action);

      expect(state.length).to.equal(initialStateForTest.length - 1);
      expect(_.find(state, membership)).to.be.undefined;
      expect(mutationTracker.hasMutated(tracked)).to.be.false;
    });
  });

  describe('dismissClinicianInviteSuccess', () => {
    it('should remove rejected invite from state array', () => {
      let initialStateForTest = [
        { key: 'xyz123zyx', email: 'g@g.com' },
        { key: 'abc987cba', email: 'a@a.com' }
      ];
      let tracked = mutationTracker.trackObj(initialStateForTest);

      let membership = { key: 'xyz123zyx' };

      let action = actions.sync.dismissClinicianInviteSuccess(membership.key);

      let state = reducer(initialStateForTest, action);

      expect(state.length).to.equal(initialStateForTest.length - 1);
      expect(_.find(state, membership)).to.be.undefined;
      expect(mutationTracker.hasMutated(tracked)).to.be.false;
    });
  });

  describe('logoutRequest', () => {
    it('should set to an empty array', () => {
      let initialStateForTest = [
        { key: 'xyz123zyx' },
        { key: 'abc987cba' }
      ];
      let tracked = mutationTracker.trackObj(initialStateForTest);

      let action = actions.sync.logoutRequest();

      let state = reducer(initialStateForTest, action);

      expect(state.length).to.equal(0);
      expect(mutationTracker.hasMutated(tracked)).to.be.false;
    });
  });
});


text:
layout: global
title: Multilayer perceptron classifier
displayTitle: Multilayer perceptron classifier
license: |
  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.
---

  > This section has been moved into the
   [classification and regression section](ml-classification-regression.html#multilayer-perceptron-classifier).


text:
package com.navercorp.pinpoint.exception;

/**
 * @author emeroad
 */
@SuppressWarnings("serial")
public class PinpointException extends RuntimeException {
    public PinpointException() {
    }

    public PinpointException(String message) {
        super(message);
    }

    public PinpointException(String message, Throwable cause) {
        super(message, cause);
    }

    public PinpointException(Throwable cause) {
        super(cause);
    }
}


text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

import itertools
import os
import shutil
import time
import traceback
from contextlib import contextmanager
from textwrap import dedent

from pex.pex_info import PexInfo
from six import StringIO
from six.moves import configparser

from pants.backend.python.subsystems.pytest import PyTest
from pants.backend.python.targets.python_tests import PythonTests
from pants.backend.python.tasks2.gather_sources import GatherSources
from pants.backend.python.tasks2.python_execution_task_base import PythonExecutionTaskBase
from pants.base.build_environment import get_buildroot
from pants.base.exceptions import ErrorWhileTesting, TaskError
from pants.base.hash_utils import Sharder
from pants.base.workunit import WorkUnitLabel
from pants.build_graph.target import Target
from pants.task.testrunner_task_mixin import TestRunnerTaskMixin
from pants.util.contextutil import temporary_dir, temporary_file
from pants.util.dirutil import safe_mkdir, safe_mkdir_for
from pants.util.process_handler import SubprocessProcessHandler
from pants.util.strutil import safe_shlex_split
from pants.util.xml_parser import XmlParser

class PythonTestResult(object):
  @staticmethod
  def exception():
    return PythonTestResult('EXCEPTION')

  @staticmethod
  def rc(value):
    return PythonTestResult('SUCCESS' if value == 0 else 'FAILURE', rc=value)

  def with_failed_targets(self, failed_targets):
    return PythonTestResult(self._msg, self._rc, failed_targets)

  def __init__(self, msg, rc=None, failed_targets=None):
    self._rc = rc
    self._msg = msg
    self._failed_targets = failed_targets or []

  def __str__(self):
    return self._msg

  @property
  def success(self):
    return self._rc == 0

  @property
  def failed_targets(self):
    return self._failed_targets

class PytestRun(TestRunnerTaskMixin, PythonExecutionTaskBase):

  @classmethod
  def subsystem_dependencies(cls):
    return super(PytestRun, cls).subsystem_dependencies() + (PyTest,)

  @classmethod
  def register_options(cls, register):
    super(PytestRun, cls).register_options(register)
    register('--fast', type=bool, default=True,
             help='Run all tests in a single pytest invocation. If turned off, each test target '
                  'will run in its own pytest invocation, which will be slower, but isolates '
                  'tests from process-wide state created by tests in other targets.')
    register('--junit-xml-dir', metavar='<DIR>',
             help='Specifying a directory causes junit xml results files to be emitted under '
                  'that dir for each test run.')
    register('--profile', metavar='<FILE>',
             help="Specifying a file path causes tests to be profiled with the profiling data "
                  "emitted to that file (prefix). Note that tests may run in a different cwd, so "
                  "it's best to use an absolute path to make it easy to find the subprocess "
                  "profiles later.")
    register('--options', type=list, help='Pass these options to pytest.')
    register('--coverage',
             help='Emit coverage information for specified packages or directories (absolute or'
                  'relative to the build root).  The special value "auto" indicates that Pants '
                  'should attempt to deduce which packages to emit coverage for.')
    register('--coverage-output-dir', metavar='<DIR>', default=None,
             help='Directory to emit coverage reports to.'
             'If not specified, a default within dist is used.')
    register('--test-shard',
             help='Subset of tests to run, in the form M/N, 0 <= M < N. For example, 1/3 means '
                  'run tests number 2, 5, 8, 11, ...')

  @classmethod
  def supports_passthru_args(cls):
    return True

  def __init__(self, *args, **kwargs):
    super(PytestRun, self).__init__(*args, **kwargs)

  def extra_requirements(self):
    return PyTest.global_instance().get_requirement_strings()

  def _test_target_filter(self):
    def target_filter(target):
      return isinstance(target, PythonTests)

    return target_filter

  def _validate_target(self, target):
    pass

  def _execute(self, all_targets):
    test_targets = self._get_test_targets()
    if test_targets:
      self.context.release_lock()
      self._run_tests(test_targets)

  class InvalidShardSpecification(TaskError):
    """Indicates an invalid `--test-shard` option."""

  def _get_junit_xml_path(self, targets):
    xml_path = os.path.join(self.workdir, 'junitxml',
                            'TEST-{}.xml'.format(Target.maybe_readable_identify(targets)))
    safe_mkdir_for(xml_path)
    return xml_path

  DEFAULT_COVERAGE_CONFIG = dedent(b"""
    [run]
    branch = True
    timid = True

    [report]
    exclude_lines =
        def __repr__
        raise NotImplementedError
    """)

  @staticmethod
  def _format_string_list(values):
    # The coverage rc ini files accept "Multi-valued strings" - ie: lists of strings - denoted by
    # indenting values on multiple lines like so:
    # [section]
    # name =
    #   value1
    #   value2
    #
    # See http://nedbatchelder.com/code/coverage/config.html for details.
    return '\n\t{values}'.format(values='\n\t'.join(values))

  @property
  def _debug(self):
    return self.get_options().level == 'debug'

  def _generate_coverage_config(self, source_mappings):
    # For the benefit of macos testing, add the 'real' path the the directory as an equivalent.
    def add_realpath(path):
      realpath = os.path.realpath(path)
      if realpath != canonical and realpath not in alternates:
        realpaths.add(realpath)

    cp = configparser.SafeConfigParser()
    cp.readfp(StringIO(self.DEFAULT_COVERAGE_CONFIG))

    # We use the source_mappings to setup the `combine` coverage command to transform paths in
    # coverage data files into canonical form.
    # See the "[paths]" entry here: http://nedbatchelder.com/code/coverage/config.html for details.
    cp.add_section('paths')
    for canonical, alternates in source_mappings.items():
      key = canonical.replace(os.sep, '.')
      realpaths = set()
      add_realpath(canonical)
      for path in alternates:
        add_realpath(path)
      cp.set('paths',
             key,
             self._format_string_list([canonical] + list(alternates) + list(realpaths)))

    # See the debug options here: http://nedbatchelder.com/code/coverage/cmd.html#cmd-run-debug
    if self._debug:
      debug_options = self._format_string_list([
        # Dumps the coverage config realized values.
        'config',
        # Logs which files are skipped or traced and why.
        'trace'])
      cp.set('run', 'debug', debug_options)

    return cp

  @contextmanager
  def _cov_setup(self, source_mappings, coverage_sources=None):
    cp = self._generate_coverage_config(source_mappings=source_mappings)
    # Note that it's important to put the tmpfile under the workdir, because pytest
    # uses all arguments that look like paths to compute its rootdir, and we want
    # it to pick the buildroot.
    with temporary_file(root_dir=self.workdir) as fp:
      cp.write(fp)
      fp.close()
      coverage_rc = fp.name
      # Note that --cov-report= with no value turns off terminal reporting, which
      # we handle separately.
      args = ['--cov-report=', '--cov-config', coverage_rc]
      for module in coverage_sources:
        args.extend(['--cov', module])
      yield args, coverage_rc

  @contextmanager
  def _maybe_emit_coverage_data(self, targets, pex):
    coverage = self.get_options().coverage
    if coverage is None:
      yield []
      return

    pex_src_root = os.path.relpath(
      self.context.products.get_data(GatherSources.PYTHON_SOURCES).path(), get_buildroot())

    source_mappings = {}
    for target in targets:
      libs = (tgt for tgt in target.closure()
              if tgt.has_sources('.py') and not isinstance(tgt, PythonTests))
      for lib in libs:
        source_mappings[lib.target_base] = [pex_src_root]

    def ensure_trailing_sep(path):
      return path if path.endswith(os.path.sep) else path + os.path.sep

    if coverage == 'auto':
      def compute_coverage_sources(tgt):
        if tgt.coverage:
          return tgt.coverage
        else:
          # This makes the assumption that tests/python/<tgt> will be testing src/python/<tgt>.
          # Note in particular that this doesn't work for pants' own tests, as those are under
          # the top level package 'pants_tests', rather than just 'pants'.
          # TODO(John Sirois): consider failing fast if there is no explicit coverage scheme;
          # but also  consider supporting configuration of a global scheme whether that be parallel
          # dirs/packages or some arbitrary function that can be registered that takes a test target
          # and hands back the source packages or paths under test.
          return set(os.path.dirname(s).replace(os.sep, '.')
                     for s in tgt.sources_relative_to_source_root())
      coverage_sources = set(itertools.chain(*[compute_coverage_sources(t) for t in targets]))
    else:
      coverage_sources = []
      for source in coverage.split(','):
        if os.path.isdir(source):
          # The source is a dir, so correct its prefix for the chroot.
          # E.g. if source is /path/to/src/python/foo/bar or src/python/foo/bar then
          # rel_source is src/python/foo/bar, and ...
          rel_source = os.path.relpath(source, get_buildroot())
          rel_source = ensure_trailing_sep(rel_source)
          found_target_base = False
          for target_base in source_mappings:
            prefix = ensure_trailing_sep(target_base)
            if rel_source.startswith(prefix):
              # ... rel_source will match on prefix=src/python/ ...
              suffix = rel_source[len(prefix):]
              # ... suffix will equal foo/bar ...
              coverage_sources.append(os.path.join(pex_src_root, suffix))
              found_target_base = True
              # ... and we end up appending <pex_src_root>/foo/bar to the coverage_sources.
              break
          if not found_target_base:
            self.context.log.warn('Coverage path {} is not in any target. Skipping.'.format(source))
        else:
          # The source is to be interpreted as a package name.
          coverage_sources.append(source)

    with self._cov_setup(source_mappings,
                         coverage_sources=coverage_sources) as (args, coverage_rc):
      try:
        yield args
      finally:
        env = {
          'PEX_MODULE': 'coverage.cmdline:main'
        }
        def pex_run(arguments):
          return self._pex_run(pex, workunit_name='coverage', args=arguments, env=env)

        # On failures or timeouts, the .coverage file won't be written.
        if not os.path.exists('.coverage'):
          self.context.log.warn('No .coverage file was found! Skipping coverage reporting.')
        else:
          # Normalize .coverage.raw paths using combine and `paths` config in the rc file.
          # This swaps the /tmp pex chroot source paths for the local original source paths
          # the pex was generated from and which the user understands.
          shutil.move('.coverage', '.coverage.raw')
          pex_run(['combine', '--rcfile', coverage_rc])
          pex_run(['report', '-i', '--rcfile', coverage_rc])
          if self.get_options().coverage_output_dir:
            target_dir = self.get_options().coverage_output_dir
          else:
            relpath = Target.maybe_readable_identify(targets)
            pants_distdir = self.context.options.for_global_scope().pants_distdir
            target_dir = os.path.join(pants_distdir, 'coverage', relpath)
          safe_mkdir(target_dir)
          pex_run(['html', '-i', '--rcfile', coverage_rc, '-d', target_dir])
          coverage_xml = os.path.join(target_dir, 'coverage.xml')
          pex_run(['xml', '-i', '--rcfile', coverage_rc, '-o', coverage_xml])

  def _get_shard_conftest_content(self):
    shard_spec = self.get_options().test_shard
    if shard_spec is None:
      return ''

    try:
      sharder = Sharder(shard_spec)
      if sharder.nshards < 2:
        return ''
      return dedent("""

        ### GENERATED BY PANTS ###

        def pytest_report_header(config):
          return 'shard: {shard} of {nshards} (0-based shard numbering)'

        def pytest_collection_modifyitems(session, config, items):
          total_count = len(items)
          removed = 0
          def is_conftest(itm):
            return itm.fspath and itm.fspath.basename == 'conftest.py'
          for i, item in enumerate(list(x for x in items if not is_conftest(x))):
            if i % {nshards} != {shard}:
              del items[i - removed]
              removed += 1
          reporter = config.pluginmanager.getplugin('terminalreporter')
          reporter.write_line('Only executing {{}} of {{}} total tests in shard {shard} of '
                              '{nshards}'.format(total_count - removed, total_count),
                              bold=True, invert=True, yellow=True)
        """.format(shard=sharder.shard, nshards=sharder.nshards))
    except Sharder.InvalidShardSpec as e:
      raise self.InvalidShardSpecification(e)

  def _get_conftest_content(self, sources_map):
    # A conftest hook to modify the console output, replacing the chroot-based
    # source paths with the source-tree based ones, which are more readable to the end user.
    # Note that python stringifies a dict to its source representation, so we can use sources_map
    # as a format argument directly.
    #
    # We'd prefer to hook into pytest_runtest_logstart(), which actually prints the line we
    # want to fix, but we can't because we won't have access to any of its state, so
    # we can't actually change what it prints.
    #
    # Alternatively, we could hook into pytest_collect_file() and just set a custom nodeid
    # for the entire pytest run.  However this interferes with pytest internals, including
    # fixture registration, leading to  fixtures not running when they should.
    # It also requires the generated conftest to be in the root of the source tree, which
    # complicates matters when there's already a user conftest.py there.
    console_output_conftest_content = dedent("""

      ### GENERATED BY PANTS ###

      import pytest

      # Map from source path relative to chroot -> source path relative to buildroot.
      _SOURCES_MAP = {}

      @pytest.hookimpl(hookwrapper=True)
      def pytest_runtest_protocol(item, nextitem):
        # Temporarily change the nodeid, which pytest uses for display here.
        real_nodeid = item.nodeid
        real_path = real_nodeid.split('::', 1)[0]
        fixed_path = _SOURCES_MAP.get(real_path, real_path)
        fixed_nodeid = fixed_path + real_nodeid[len(real_path):]
        try:
          item._nodeid = fixed_nodeid
          yield
        finally:
          item._nodeid = real_nodeid
    """.format(sources_map))
    # Add in the sharding conftest, if any.
    shard_conftest_content = self._get_shard_conftest_content()
    return (console_output_conftest_content + shard_conftest_content).encode('utf8')

  @contextmanager
  def _conftest(self, sources_map):
    """Creates a conftest.py to customize our pytest run."""
    conftest_content = self._get_conftest_content(sources_map)
    # Note that it's important to put the tmpdir under the workdir, because pytest
    # uses all arguments that look like paths to compute its rootdir, and we want
    # it to pick the buildroot.
    with temporary_dir(root_dir=self.workdir) as conftest_dir:
      conftest = os.path.join(conftest_dir, 'conftest.py')
      with open(conftest, 'w') as fp:
        fp.write(conftest_content)
      yield conftest

  @contextmanager
  def _test_runner(self, targets, sources_map):
    pex_info = PexInfo.default()
    pex_info.entry_point = 'pytest'
    pex = self.create_pex(pex_info)

    with self._conftest(sources_map) as conftest:
      with self._maybe_emit_coverage_data(targets, pex) as coverage_args:
        yield pex, [conftest] + coverage_args

  def _do_run_tests_with_args(self, pex, args):
    try:
      # The pytest runner we use accepts a --pdb argument that will launch an interactive pdb
      # session on any test failure.  In order to support use of this pass-through flag we must
      # turn off stdin buffering that otherwise occurs.  Setting the PYTHONUNBUFFERED env var to
      # any value achieves this in python2.7.  We'll need a different solution when we support
      # running pants under CPython 3 which does not unbuffer stdin using this trick.
      env = dict(os.environ)
      env['PYTHONUNBUFFERED'] = '1'

      # pytest uses py.io.terminalwriter for output. That class detects the terminal
      # width and attempts to use all of it. However we capture and indent the console
      # output, leading to weird-looking line wraps. So we trick the detection code
      # into thinking the terminal window is narrower than it is.
      env['COLUMNS'] = str(int(os.environ.get('COLUMNS', 80)) - 30)

      profile = self.get_options().profile
      if profile:
        env['PEX_PROFILE_FILENAME'] = '{0}.subprocess.{1:.6f}'.format(profile, time.time())

      with self.context.new_workunit(name='run',
                                     labels=[WorkUnitLabel.TOOL, WorkUnitLabel.TEST]) as workunit:
        rc = self._spawn_and_wait(pex, workunit=workunit, args=args, setsid=True, env=env)
        return PythonTestResult.rc(rc)
    except ErrorWhileTesting:
      # _spawn_and_wait wraps the test runner in a timeout, so it could
      # fail with a ErrorWhileTesting. We can't just set PythonTestResult
      # to a failure because the resultslog doesn't have all the failures
      # when tests are killed with a timeout. Therefore we need to re-raise
      # here.
      raise
    except Exception:
      self.context.log.error('Failed to run test!')
      self.context.log.info(traceback.format_exc())
      return PythonTestResult.exception()

  def _map_relsrc_to_targets(self, targets):
    pex_src_root = os.path.relpath(
      self.context.products.get_data(GatherSources.PYTHON_SOURCES).path(), get_buildroot())
    # First map chrooted sources back to their targets.
    relsrc_to_target = {os.path.join(pex_src_root, src): target for target in targets
      for src in target.sources_relative_to_source_root()}
    # Also map the source tree-rooted sources, because in some cases (e.g., a failure to even
    # eval the test file during test collection), that's the path pytest will use in the junit xml.
    relsrc_to_target.update({src: target for target in targets
      for src in target.sources_relative_to_buildroot()})

    return relsrc_to_target

  def _get_failed_targets_from_junitxml(self, junitxml, targets):
    relsrc_to_target = self._map_relsrc_to_targets(targets)

    # Now find the sources that contained failing tests.
    failed_targets = set()

    try:
      xml = XmlParser.from_file(junitxml)
      failures = int(xml.get_attribute('testsuite', 'failures'))
      errors = int(xml.get_attribute('testsuite', 'errors'))
      if failures or errors:
        for testcase in xml.parsed.getElementsByTagName('testcase'):
          test_failed = testcase.getElementsByTagName('failure')
          test_errored = testcase.getElementsByTagName('error')
          if test_failed or test_errored:
            # The 'file' attribute is a relsrc, because that's what we passed in to pytest.
            failed_targets.add(relsrc_to_target.get(testcase.getAttribute('file')))
    except (XmlParser.XmlError, ValueError) as e:
      raise TaskError('Error parsing xml file at {}: {}'.format(junitxml, e))

    return failed_targets

  def _get_target_from_test(self, test_info, targets):
    relsrc_to_target = self._map_relsrc_to_targets(targets)
    file_info = test_info['file']
    return relsrc_to_target.get(file_info)

  def _run_tests(self, targets):
    if self.get_options().fast:
      result = self._do_run_tests(targets)
      if not result.success:
        raise ErrorWhileTesting(failed_targets=result.failed_targets)
    else:
      results = {}
      for target in targets:
        rv = self._do_run_tests([target])
        results[target] = rv
        if not rv.success and self.get_options().fail_fast:
          break
      for target in sorted(results):
        self.context.log.info('{0:80}.....{1:>10}'.format(target.id, str(results[target])))
      failed_targets = [target for target, _rv in results.items() if not _rv.success]
      if failed_targets:
        raise ErrorWhileTesting(failed_targets=failed_targets)

  def _do_run_tests(self, targets):
    if not targets:
      return PythonTestResult.rc(0)

    buildroot = get_buildroot()
    source_chroot = os.path.relpath(
      self.context.products.get_data(GatherSources.PYTHON_SOURCES).path(), buildroot)
    sources_map = {}  # Path from chroot -> Path from buildroot.
    for t in targets:
      for p in t.sources_relative_to_source_root():
        sources_map[os.path.join(source_chroot, p)] = os.path.join(t.target_base, p)

    if not sources_map:
      return PythonTestResult.rc(0)

    with self._test_runner(targets, sources_map) as (pex, test_args):
      # Validate that the user didn't provide any passthru args that conflict
      # with those we must set ourselves.
      for arg in self.get_passthru_args():
        if arg.startswith('--junitxml') or arg.startswith('--confcutdir'):
          raise TaskError('Cannot pass this arg through to pytest: {}'.format(arg))

      junitxml_path = self._get_junit_xml_path(targets)
      # N.B. the `--confcutdir` here instructs pytest to stop scanning for conftest.py files at the
      # top of the buildroot. This prevents conftest.py files from outside (e.g. in users home dirs)
      # from leaking into pants test runs. See: https://github.com/pantsbuild/pants/issues/2726
      args = ['--junitxml', junitxml_path, '--confcutdir', get_buildroot(),
              '--continue-on-collection-errors']
      if self.get_options().fail_fast:
        args.extend(['-x'])
      if self._debug:
        args.extend(['-s'])
      if self.get_options().colors:
        args.extend(['--color', 'yes'])
      for options in self.get_options().options + self.get_passthru_args():
        args.extend(safe_shlex_split(options))
      args.extend(test_args)
      args.extend(sources_map.keys())

      result = self._do_run_tests_with_args(pex, args)
      external_junit_xml_dir = self.get_options().junit_xml_dir
      if external_junit_xml_dir:
        safe_mkdir(external_junit_xml_dir)
        shutil.copy(junitxml_path, external_junit_xml_dir)
      failed_targets = self._get_failed_targets_from_junitxml(junitxml_path, targets)

      def parse_error_handler(parse_error):
        # Simple error handler to pass to xml parsing function.
        raise TaskError('Error parsing xml file at {}: {}'
          .format(parse_error.xml_path, parse_error.cause))

      all_tests_info = self.parse_test_info(junitxml_path, parse_error_handler, ['file', 'name'])
      for test_name, test_info in all_tests_info.items():
        test_target = self._get_target_from_test(test_info, targets)
        self.report_test_info(self.options_scope, test_target, test_name, test_info)

      return result.with_failed_targets(failed_targets)

  def _pex_run(self, pex, workunit_name, args, env):
    with self.context.new_workunit(name=workunit_name,
                                   labels=[WorkUnitLabel.TOOL, WorkUnitLabel.TEST]) as workunit:
      process = self._spawn(pex, workunit, args, setsid=False, env=env)
      return process.wait()

  def _spawn(self, pex, workunit, args, setsid=False, env=None):
    env = env or {}
    process = pex.run(args, blocking=False, setsid=setsid, env=env,
                      stdout=workunit.output('stdout'), stderr=workunit.output('stderr'))
    return SubprocessProcessHandler(process)


text:
export enum Explicity {
    NotSpecified,
    Explicit,
    Implicit,
}

export { Explicity as Type };


text:
#ifndef PANDAS__LIBS_SRC_PARSE_HELPER_H_
#define PANDAS__LIBS_SRC_PARSE_HELPER_H_

#include <errno.h>
#include <float.h>
#include "inline_helper.h"
#include "headers/portable.h"

static double xstrtod(const char *p, char **q, char decimal, char sci,
                      int skip_trailing, int *maybe_int);

int to_double(char *item, double *p_value, char sci, char decimal,
              int *maybe_int) {
    char *p_end = NULL;

    *p_value = xstrtod(item, &p_end, decimal, sci, 1, maybe_int);

    return (errno == 0) && (!*p_end);
}

#if PY_VERSION_HEX < 0x02060000
#define PyBytes_Check PyString_Check
#define PyBytes_AS_STRING PyString_AS_STRING
#endif  // PY_VERSION_HEX

int floatify(PyObject *str, double *result, int *maybe_int) {
    int status;
    char *data;
    PyObject *tmp = NULL;
    const char sci = 'E';
    const char dec = '.';

    if (PyBytes_Check(str)) {
        data = PyBytes_AS_STRING(str);
    } else if (PyUnicode_Check(str)) {
        tmp = PyUnicode_AsUTF8String(str);
        data = PyBytes_AS_STRING(tmp);
    } else {
        PyErr_SetString(PyExc_TypeError, "Invalid object type");
        return -1;
    }

    status = to_double(data, result, sci, dec, maybe_int);

    if (!status) {
        /* handle inf/-inf */
        if (strlen(data) == 3) {
            if (0 == strcasecmp(data, "inf")) {
                *result = HUGE_VAL;
                *maybe_int = 0;
            } else {
                goto parsingerror;
            }
        } else if (strlen(data) == 4) {
            if (0 == strcasecmp(data, "-inf")) {
                *result = -HUGE_VAL;
                *maybe_int = 0;
            } else if (0 == strcasecmp(data, "+inf")) {
                *result = HUGE_VAL;
                *maybe_int = 0;
            } else {
                goto parsingerror;
            }
        } else {
            goto parsingerror;
        }
    }

    Py_XDECREF(tmp);
    return 0;

parsingerror:
    PyErr_Format(PyExc_ValueError, "Unable to parse string \"%s\"", data);
    Py_XDECREF(tmp);
    return -1;

    /*
    #if PY_VERSION_HEX >= 0x03000000
      return PyFloat_FromString(str);
    #else
      return PyFloat_FromString(str, NULL);
    #endif
    */
}

// ---------------------------------------------------------------------------
// Implementation of xstrtod

//
// strtod.c
//
// Convert string to double
//
// Copyright (C) 2002 Michael Ringgaard. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. 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.
// 3. Neither the name of the project 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 OWNER OR CONTRIBUTORS 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.
//
// -----------------------------------------------------------------------
// Modifications by Warren Weckesser, March 2011:
// * Rename strtod() to xstrtod().
// * Added decimal and sci arguments.
// * Skip trailing spaces.
// * Commented out the other functions.
//

PANDAS_INLINE void lowercase(char *p) {
    for (; *p; ++p) *p = tolower_ascii(*p);
}

PANDAS_INLINE void uppercase(char *p) {
    for (; *p; ++p) *p = toupper_ascii(*p);
}

static double xstrtod(const char *str, char **endptr, char decimal, char sci,
                      int skip_trailing, int *maybe_int) {
    double number;
    int exponent;
    int negative;
    char *p = (char *)str;
    double p10;
    int n;
    int num_digits;
    int num_decimals;

    errno = 0;
    *maybe_int = 1;

    // Skip leading whitespace
    while (isspace(*p)) p++;

    // Handle optional sign
    negative = 0;
    switch (*p) {
        case '-':
            negative = 1;  // Fall through to increment position
        case '+':
            p++;
    }

    number = 0.;
    exponent = 0;
    num_digits = 0;
    num_decimals = 0;

    // Process string of digits
    while (isdigit_ascii(*p)) {
        number = number * 10. + (*p - '0');
        p++;
        num_digits++;
    }

    // Process decimal part
    if (*p == decimal) {
        *maybe_int = 0;
        p++;

        while (isdigit_ascii(*p)) {
            number = number * 10. + (*p - '0');
            p++;
            num_digits++;
            num_decimals++;
        }

        exponent -= num_decimals;
    }

    if (num_digits == 0) {
        errno = ERANGE;
        return 0.0;
    }

    // Correct for sign
    if (negative) number = -number;

    // Process an exponent string
    if (toupper_ascii(*p) == toupper_ascii(sci)) {
        *maybe_int = 0;

        // Handle optional sign
        negative = 0;
        switch (*++p) {
            case '-':
                negative = 1;  // Fall through to increment pos
            case '+':
                p++;
        }

        // Process string of digits
        num_digits = 0;
        n = 0;
        while (isdigit_ascii(*p)) {
            n = n * 10 + (*p - '0');
            num_digits++;
            p++;
        }

        if (negative)
            exponent -= n;
        else
            exponent += n;

        // If no digits, after the 'e'/'E', un-consume it
        if (num_digits == 0) p--;
    }

    if (exponent < DBL_MIN_EXP || exponent > DBL_MAX_EXP) {
        errno = ERANGE;
        return HUGE_VAL;
    }

    // Scale the result
    p10 = 10.;
    n = exponent;
    if (n < 0) n = -n;
    while (n) {
        if (n & 1) {
            if (exponent < 0)
                number /= p10;
            else
                number *= p10;
        }
        n >>= 1;
        p10 *= p10;
    }

    if (number == HUGE_VAL) {
        errno = ERANGE;
    }

    if (skip_trailing) {
        // Skip trailing whitespace
        while (isspace_ascii(*p)) p++;
    }

    if (endptr) *endptr = p;

    return number;
}

#endif  // PANDAS__LIBS_SRC_PARSE_HELPER_H_


text:
// ZipStorer, by Jaime Olivares
// Website: zipstorer.codeplex.com
// Version: 2.35 (March 14, 2010)

using System.Collections.Generic;
using System.Text;

namespace System.IO.Compression
{
    ///
    /// Unique class for compression/decompression file. Represents a Zip file.
    ///
    public class ZipStorer : IDisposable
    {
        ///
        /// Compression method enumeration
        ///
        public enum Compression : ushort {
            /// Uncompressed storage
            Store = 0,
            /// Deflate compression method
            Deflate = 8 }

        ///
        /// Represents an entry in Zip file directory
        ///
        public struct ZipFileEntry
        {
            /// Compression method
            public Compression Method;
            /// Full path and filename as stored in Zip
            public string FilenameInZip;
            /// Original file size
            public uint FileSize;
            /// Compressed file size
            public uint CompressedSize;
            /// Offset of header information inside Zip storage
            public uint HeaderOffset;
            /// Offset of file inside Zip storage
            public uint FileOffset;
            /// Size of header information
            public uint HeaderSize;
            /// 32-bit checksum of entire file
            public uint Crc32;
            /// Last modification time of file
            public DateTime ModifyTime;
            /// User comment for file
            public string Comment;
            /// True if UTF8 encoding for filename and comments, false if default (CP 437)
            public bool EncodeUTF8;

            /// Overriden method
            /// <returns>Filename in Zip</returns>
            public override string ToString()
            {
                return this.FilenameInZip;
            }
        }

        #region Public fields
        /// True if UTF8 encoding for filename and comments, false if default (CP 437)
        public bool EncodeUTF8 = false;
        /// Force deflate algotithm even if it inflates the stored file. Off by default.
        public bool ForceDeflating = false;
        #endregion

        #region Private fields
        // List of files to store
        private List<ZipFileEntry> Files = new List<ZipFileEntry>();
        // Filename of storage file
        private string FileName;
        // Stream object of storage file
        private Stream ZipFileStream;
        // General comment
        private string Comment = "";
        // Central dir image
        private byte[] CentralDirImage = null;
        // Existing files in zip
        private ushort ExistingFiles = 0;
        // File access for Open method
        private FileAccess Access;
        // Static CRC32 Table
        private static UInt32[] CrcTable = null;
        // Default filename encoder
        private static Encoding DefaultEncoding = Encoding.GetEncoding(437);
        #endregion

        #region Public methods
        // Static constructor. Just invoked once in order to create the CRC32 lookup table.
        static ZipStorer()
        {
            // Generate CRC32 table
            CrcTable = new UInt32[256];
            for (int i = 0; i < CrcTable.Length; i++)
            {
                UInt32 c = (UInt32)i;
                for (int j = 0; j < 8; j++)
                {
                    if ((c & 1) != 0)
                        c = 3988292384 ^ (c >> 1);
                    else
                        c >>= 1;
                }
                CrcTable[i] = c;
            }
        }
        ///
        /// Method to create a new storage file
        ///
        /// <param name="_filename">Full path of Zip file to create</param>
        /// <param name="_comment">General comment for Zip file</param>
        /// <returns>A valid ZipStorer object</returns>
        public static ZipStorer Create(string _filename, string _comment)
        {
            Stream stream = new FileStream(_filename, FileMode.Create, FileAccess.ReadWrite);

            ZipStorer zip = Create(stream, _comment);
            zip.Comment = _comment;
            zip.FileName = _filename;

            return zip;
        }
        ///
        /// Method to create a new zip storage in a stream
        ///
        /// <param name="_stream"></param>
        /// <param name="_comment"></param>
        /// <returns>A valid ZipStorer object</returns>
        public static ZipStorer Create(Stream _stream, string _comment)
        {
            ZipStorer zip = new ZipStorer();
            zip.Comment = _comment;
            zip.ZipFileStream = _stream;
            zip.Access = FileAccess.Write;

            return zip;
        }
        ///
        /// Method to open an existing storage file
        ///
        /// <param name="_filename">Full path of Zip file to open</param>
        /// <param name="_access">File access mode as used in FileStream constructor</param>
        /// <returns>A valid ZipStorer object</returns>
        public static ZipStorer Open(string _filename, FileAccess _access)
        {
            Stream stream = (Stream)new FileStream(_filename, FileMode.Open, _access == FileAccess.Read ? FileAccess.Read : FileAccess.ReadWrite);

            ZipStorer zip = Open(stream, _access);
            zip.FileName = _filename;

            return zip;
        }
        ///
        /// Method to open an existing storage from stream
        ///
        /// <param name="_stream">Already opened stream with zip contents</param>
        /// <param name="_access">File access mode for stream operations</param>
        /// <returns>A valid ZipStorer object</returns>
        public static ZipStorer Open(Stream _stream, FileAccess _access)
        {
            if (!_stream.CanSeek && _access != FileAccess.Read)
                throw new InvalidOperationException("Stream cannot seek");

            ZipStorer zip = new ZipStorer();
            //zip.FileName = _filename;
            zip.ZipFileStream = _stream;
            zip.Access = _access;

            if (zip.ReadFileInfo())
                return zip;

            throw new System.IO.InvalidDataException();
        }
        ///
        /// Add full contents of a file into the Zip storage
        ///
        /// <param name="_method">Compression method</param>
        /// <param name="_pathname">Full path of file to add to Zip storage</param>
        /// <param name="_filenameInZip">Filename and path as desired in Zip directory</param>
        /// <param name="_comment">Comment for stored file</param>
        public void AddFile(Compression _method, string _pathname, string _filenameInZip, string _comment)
        {
            if (Access == FileAccess.Read)
                throw new InvalidOperationException("Writing is not alowed");

            FileStream stream = new FileStream(_pathname, FileMode.Open, FileAccess.Read);
            AddStream(_method, _filenameInZip, stream, File.GetLastWriteTime(_pathname), _comment);
            stream.Close();
        }
        ///
        /// Add full contents of a stream into the Zip storage
        ///
        /// <param name="_method">Compression method</param>
        /// <param name="_filenameInZip">Filename and path as desired in Zip directory</param>
        /// <param name="_source">Stream object containing the data to store in Zip</param>
        /// <param name="_modTime">Modification time of the data to store</param>
        /// <param name="_comment">Comment for stored file</param>
        public void AddStream(Compression _method, string _filenameInZip, Stream _source, DateTime _modTime, string _comment)
        {
            if (Access == FileAccess.Read)
                throw new InvalidOperationException("Writing is not alowed");

            long offset;
            if (this.Files.Count==0)
                offset = 0;
            else
            {
                ZipFileEntry last = this.Files[this.Files.Count-1];
                offset = last.HeaderOffset + last.HeaderSize;
            }

            // Prepare the fileinfo
            ZipFileEntry zfe = new ZipFileEntry();
            zfe.Method = _method;
            zfe.EncodeUTF8 = this.EncodeUTF8;
            zfe.FilenameInZip = NormalizedFilename(_filenameInZip);
            zfe.Comment = (_comment == null ? "" : _comment);

            // Even though we write the header now, it will have to be rewritten, since we don't know compressed size or crc.
            zfe.Crc32 = 0;  // to be updated later
            zfe.HeaderOffset = (uint)this.ZipFileStream.Position;  // offset within file of the start of this local record
            zfe.ModifyTime = _modTime;

            // Write local header
            WriteLocalHeader(ref zfe);
            zfe.FileOffset = (uint)this.ZipFileStream.Position;

            // Write file to zip (store)
            Store(ref zfe, _source);
            _source.Close();

            this.UpdateCrcAndSizes(ref zfe);

            Files.Add(zfe);
        }
        ///
        /// Updates central directory (if pertinent) and close the Zip storage
        ///
        /// <remarks>This is a required step, unless automatic dispose is used</remarks>
        public void Close()
        {
           if(this.ZipFileStream == null)
              return;

            if (this.Access != FileAccess.Read)
            {
                uint centralOffset = (uint)this.ZipFileStream.Position;
                uint centralSize = 0;

                if (this.CentralDirImage != null)
                    this.ZipFileStream.Write(CentralDirImage, 0, CentralDirImage.Length);

                for (int i = 0; i < Files.Count; i++)
                {
                    long pos = this.ZipFileStream.Position;
                    this.WriteCentralDirRecord(Files[i]);
                    centralSize += (uint)(this.ZipFileStream.Position - pos);
                }

                if (this.CentralDirImage != null)
                    this.WriteEndRecord(centralSize + (uint)CentralDirImage.Length, centralOffset);
                else
                    this.WriteEndRecord(centralSize, centralOffset);
            }

            if (this.ZipFileStream != null)
            {
                this.ZipFileStream.Flush();
                this.ZipFileStream.Dispose();
                this.ZipFileStream = null;
            }
        }
        ///
        /// Read all the file records in the central directory
        ///
        /// <returns>List of all entries in directory</returns>
        public List<ZipFileEntry> ReadCentralDir()
        {
            if (this.CentralDirImage == null)
                throw new InvalidOperationException("Central directory currently does not exist");

            List<ZipFileEntry> result = new List<ZipFileEntry>();

            for (int pointer = 0; pointer < this.CentralDirImage.Length; )
            {
                uint signature = BitConverter.ToUInt32(CentralDirImage, pointer);
                if (signature != 0x02014b50)
                    break;

                bool encodeUTF8 = (BitConverter.ToUInt16(CentralDirImage, pointer + 8) & 0x0800) != 0;
                ushort method = BitConverter.ToUInt16(CentralDirImage, pointer + 10);
                uint modifyTime = BitConverter.ToUInt32(CentralDirImage, pointer + 12);
                uint crc32 = BitConverter.ToUInt32(CentralDirImage, pointer + 16);
                uint comprSize = BitConverter.ToUInt32(CentralDirImage, pointer + 20);
                uint fileSize = BitConverter.ToUInt32(CentralDirImage, pointer + 24);
                ushort filenameSize = BitConverter.ToUInt16(CentralDirImage, pointer + 28);
                ushort extraSize = BitConverter.ToUInt16(CentralDirImage, pointer + 30);
                ushort commentSize = BitConverter.ToUInt16(CentralDirImage, pointer + 32);
                uint headerOffset = BitConverter.ToUInt32(CentralDirImage, pointer + 42);
                uint headerSize = (uint)( 46 + filenameSize + extraSize + commentSize);

                Encoding encoder = encodeUTF8 ? Encoding.UTF8 : DefaultEncoding;

                ZipFileEntry zfe = new ZipFileEntry();
                zfe.Method = (Compression)method;
                zfe.FilenameInZip = encoder.GetString(CentralDirImage, pointer + 46, filenameSize);
                zfe.FileOffset = GetFileOffset(headerOffset);
                zfe.FileSize = fileSize;
                zfe.CompressedSize = comprSize;
                zfe.HeaderOffset = headerOffset;
                zfe.HeaderSize = headerSize;
                zfe.Crc32 = crc32;
                zfe.ModifyTime = DosTimeToDateTime(modifyTime);
                if (commentSize > 0)
                    zfe.Comment = encoder.GetString(CentralDirImage, pointer + 46 + filenameSize + extraSize, commentSize);

                result.Add(zfe);
                pointer += (46 + filenameSize + extraSize + commentSize);
            }

            return result;
        }
        ///
        /// Copy the contents of a stored file into a physical file
        ///
        /// <param name="_zfe">Entry information of file to extract</param>
        /// <param name="_filename">Name of file to store uncompressed data</param>
        /// <returns>True if success, false if not.</returns>
        /// <remarks>Unique compression methods are Store and Deflate</remarks>
        public bool ExtractFile(ZipFileEntry _zfe, string _filename)
        {
            // Make sure the parent directory exist
            string path = System.IO.Path.GetDirectoryName(_filename);

            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            // Check it is directory. If so, do nothing
            if (Directory.Exists(_filename))
                return true;

            Stream output = new FileStream(_filename, FileMode.Create, FileAccess.Write);
            bool result = ExtractFile(_zfe, output);
            if (result)
                output.Close();

            File.SetCreationTime(_filename, _zfe.ModifyTime);
            File.SetLastWriteTime(_filename, _zfe.ModifyTime);

            return result;
        }
        ///
        /// Copy the contents of a stored file into an opened stream
        ///
        /// <param name="_zfe">Entry information of file to extract</param>
        /// <param name="_stream">Stream to store the uncompressed data</param>
        /// <returns>True if success, false if not.</returns>
        /// <remarks>Unique compression methods are Store and Deflate</remarks>
        public bool ExtractFile(ZipFileEntry _zfe, Stream _stream)
        {
            if (!_stream.CanWrite)
                throw new InvalidOperationException("Stream cannot be written");

            // check signature
            byte[] signature = new byte[4];
            this.ZipFileStream.Seek(_zfe.HeaderOffset, SeekOrigin.Begin);
            this.ZipFileStream.Read(signature, 0, 4);
            if (BitConverter.ToUInt32(signature, 0) != 0x04034b50)
                return false;

            // Select input stream for inflating or just reading
            Stream inStream;
            if (_zfe.Method == Compression.Store)
                inStream = this.ZipFileStream;
            else if (_zfe.Method == Compression.Deflate)
                inStream = new DeflateStream(this.ZipFileStream, CompressionMode.Decompress, true);
            else
                return false;

            // Buffered copy
            byte[] buffer = new byte[16384];
            this.ZipFileStream.Seek(_zfe.FileOffset, SeekOrigin.Begin);
            uint bytesPending = _zfe.FileSize;
            while (bytesPending > 0)
            {
                int bytesRead = inStream.Read(buffer, 0, (int)Math.Min(bytesPending, buffer.Length));
                _stream.Write(buffer, 0, bytesRead);
                bytesPending -= (uint)bytesRead;
            }
            _stream.Flush();

            if (_zfe.Method == Compression.Deflate)
                inStream.Dispose();
            return true;
        }
        ///
        /// Removes one of many files in storage. It creates a new Zip file.
        ///
        /// <param name="_zip">Reference to the current Zip object</param>
        /// <param name="_zfes">List of Entries to remove from storage</param>
        /// <returns>True if success, false if not</returns>
        /// <remarks>This method only works for storage of type FileStream</remarks>
        public static bool RemoveEntries(ref ZipStorer _zip, List<ZipFileEntry> _zfes)
        {
            if (!(_zip.ZipFileStream is FileStream))
                throw new InvalidOperationException("RemoveEntries is allowed just over streams of type FileStream");

            //Get full list of entries
            List<ZipFileEntry> fullList = _zip.ReadCentralDir();

            //In order to delete we need to create a copy of the zip file excluding the selected items
            string tempZipName = Path.GetTempFileName();
            string tempEntryName = Path.GetTempFileName();

            try
            {
                ZipStorer tempZip = ZipStorer.Create(tempZipName, string.Empty);

                foreach (ZipFileEntry zfe in fullList)
                {
                    if (!_zfes.Contains(zfe))
                    {
                        if (_zip.ExtractFile(zfe, tempEntryName))
                        {
                            tempZip.AddFile(zfe.Method, tempEntryName, zfe.FilenameInZip, zfe.Comment);
                        }
                    }
                }
                _zip.Close();
                tempZip.Close();

                File.Delete(_zip.FileName);
                File.Move(tempZipName, _zip.FileName);

                _zip = ZipStorer.Open(_zip.FileName, _zip.Access);
            }
            catch
            {
                return false;
            }
            finally
            {
                if (File.Exists(tempZipName))
                    File.Delete(tempZipName);
                if (File.Exists(tempEntryName))
                    File.Delete(tempEntryName);
            }
            return true;
        }
        #endregion

        #region Private methods
        // Calculate the file offset by reading the corresponding local header
        private uint GetFileOffset(uint _headerOffset)
        {
            byte[] buffer = new byte[2];

            this.ZipFileStream.Seek(_headerOffset + 26, SeekOrigin.Begin);
            this.ZipFileStream.Read(buffer, 0, 2);
            ushort filenameSize = BitConverter.ToUInt16(buffer, 0);
            this.ZipFileStream.Read(buffer, 0, 2);
            ushort extraSize = BitConverter.ToUInt16(buffer, 0);

            return (uint)(30 + filenameSize + extraSize + _headerOffset);
        }
        /* Local file header:
            local file header signature     4 bytes  (0x04034b50)
            version needed to extract       2 bytes
            general purpose bit flag        2 bytes
            compression method              2 bytes
            last mod file time              2 bytes
            last mod file date              2 bytes
            crc-32                          4 bytes
            compressed size                 4 bytes
            uncompressed size               4 bytes
            filename length                 2 bytes
            extra field length              2 bytes

            filename (variable size)
            extra field (variable size)
        */
        private void WriteLocalHeader(ref ZipFileEntry _zfe)
        {
            long pos = this.ZipFileStream.Position;
            Encoding encoder = _zfe.EncodeUTF8 ? Encoding.UTF8 : DefaultEncoding;
            byte[] encodedFilename = encoder.GetBytes(_zfe.FilenameInZip);

            this.ZipFileStream.Write(new byte[] { 80, 75, 3, 4, 20, 0}, 0, 6); // No extra header
            this.ZipFileStream.Write(BitConverter.GetBytes((ushort)(_zfe.EncodeUTF8 ? 0x0800 : 0)), 0, 2); // filename and comment encoding
            this.ZipFileStream.Write(BitConverter.GetBytes((ushort)_zfe.Method), 0, 2);  // zipping method
            this.ZipFileStream.Write(BitConverter.GetBytes(DateTimeToDosTime(_zfe.ModifyTime)), 0, 4); // zipping date and time
            this.ZipFileStream.Write(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0, 12); // unused CRC, un/compressed size, updated later
            this.ZipFileStream.Write(BitConverter.GetBytes((ushort)encodedFilename.Length), 0, 2); // filename length
            this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // extra length

            this.ZipFileStream.Write(encodedFilename, 0, encodedFilename.Length);
            _zfe.HeaderSize = (uint)(this.ZipFileStream.Position - pos);
        }
        /* Central directory's File header:
            central file header signature   4 bytes  (0x02014b50)
            version made by                 2 bytes
            version needed to extract       2 bytes
            general purpose bit flag        2 bytes
            compression method              2 bytes
            last mod file time              2 bytes
            last mod file date              2 bytes
            crc-32                          4 bytes
            compressed size                 4 bytes
            uncompressed size               4 bytes
            filename length                 2 bytes
            extra field length              2 bytes
            file comment length             2 bytes
            disk number start               2 bytes
            internal file attributes        2 bytes
            external file attributes        4 bytes
            relative offset of local header 4 bytes

            filename (variable size)
            extra field (variable size)
            file comment (variable size)
        */
        private void WriteCentralDirRecord(ZipFileEntry _zfe)
        {
            Encoding encoder = _zfe.EncodeUTF8 ? Encoding.UTF8 : DefaultEncoding;
            byte[] encodedFilename = encoder.GetBytes(_zfe.FilenameInZip);
            byte[] encodedComment = encoder.GetBytes(_zfe.Comment);

            this.ZipFileStream.Write(new byte[] { 80, 75, 1, 2, 23, 0xB, 20, 0 }, 0, 8);
            this.ZipFileStream.Write(BitConverter.GetBytes((ushort)(_zfe.EncodeUTF8 ? 0x0800 : 0)), 0, 2); // filename and comment encoding
            this.ZipFileStream.Write(BitConverter.GetBytes((ushort)_zfe.Method), 0, 2);  // zipping method
            this.ZipFileStream.Write(BitConverter.GetBytes(DateTimeToDosTime(_zfe.ModifyTime)), 0, 4);  // zipping date and time
            this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.Crc32), 0, 4); // file CRC
            this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.CompressedSize), 0, 4); // compressed file size
            this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.FileSize), 0, 4); // uncompressed file size
            this.ZipFileStream.Write(BitConverter.GetBytes((ushort)encodedFilename.Length), 0, 2); // Filename in zip
            this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // extra length
            this.ZipFileStream.Write(BitConverter.GetBytes((ushort)encodedComment.Length), 0, 2);

            this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // disk=0
            this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // file type: binary
            this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // Internal file attributes
            this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0x8100), 0, 2); // External file attributes (normal/readable)
            this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.HeaderOffset), 0, 4);  // Offset of header

            this.ZipFileStream.Write(encodedFilename, 0, encodedFilename.Length);
            this.ZipFileStream.Write(encodedComment, 0, encodedComment.Length);
        }
        /* End of central dir record:
            end of central dir signature    4 bytes  (0x06054b50)
            number of this disk             2 bytes
            number of the disk with the
            start of the central directory  2 bytes
            total number of entries in
            the central dir on this disk    2 bytes
            total number of entries in
            the central dir                 2 bytes
            size of the central directory   4 bytes
            offset of start of central
            directory with respect to
            the starting disk number        4 bytes
            zipfile comment length          2 bytes
            zipfile comment (variable size)
        */
        private void WriteEndRecord(uint _size, uint _offset)
        {
            Encoding encoder = this.EncodeUTF8 ? Encoding.UTF8 : DefaultEncoding;
            byte[] encodedComment = encoder.GetBytes(this.Comment);

            this.ZipFileStream.Write(new byte[] { 80, 75, 5, 6, 0, 0, 0, 0 }, 0, 8);
            this.ZipFileStream.Write(BitConverter.GetBytes((ushort)Files.Count+ExistingFiles), 0, 2);
            this.ZipFileStream.Write(BitConverter.GetBytes((ushort)Files.Count+ExistingFiles), 0, 2);
            this.ZipFileStream.Write(BitConverter.GetBytes(_size), 0, 4);
            this.ZipFileStream.Write(BitConverter.GetBytes(_offset), 0, 4);
            this.ZipFileStream.Write(BitConverter.GetBytes((ushort)encodedComment.Length), 0, 2);
            this.ZipFileStream.Write(encodedComment, 0, encodedComment.Length);
        }
        // Copies all source file into storage file
        private void Store(ref ZipFileEntry _zfe, Stream _source)
        {
            byte[] buffer = new byte[16384];
            int bytesRead;
            uint totalRead = 0;
            Stream outStream;

            long posStart = this.ZipFileStream.Position;
            long sourceStart = _source.Position;

            if (_zfe.Method == Compression.Store)
                outStream = this.ZipFileStream;
            else
                outStream = new DeflateStream(this.ZipFileStream, CompressionMode.Compress, true);

            _zfe.Crc32 = 0 ^ 0xffffffff;

            do
            {
                bytesRead = _source.Read(buffer, 0, buffer.Length);
                totalRead += (uint)bytesRead;
                if (bytesRead > 0)
                {
                    outStream.Write(buffer, 0, bytesRead);

                    for (uint i = 0; i < bytesRead; i++)
                    {
                        _zfe.Crc32 = ZipStorer.CrcTable[(_zfe.Crc32 ^ buffer[i]) & 0xFF] ^ (_zfe.Crc32 >> 8);
                    }
                }
            } while (bytesRead == buffer.Length);
            outStream.Flush();

            if (_zfe.Method == Compression.Deflate)
                outStream.Dispose();

            _zfe.Crc32 ^= 0xffffffff;
            _zfe.FileSize = totalRead;
            _zfe.CompressedSize = (uint)(this.ZipFileStream.Position - posStart);

            // Verify for real compression
            if (_zfe.Method == Compression.Deflate && !this.ForceDeflating && _source.CanSeek && _zfe.CompressedSize > _zfe.FileSize)
            {
                // Start operation again with Store algorithm
                _zfe.Method = Compression.Store;
                this.ZipFileStream.Position = posStart;
                this.ZipFileStream.SetLength(posStart);
                _source.Position = sourceStart;
                this.Store(ref _zfe, _source);
            }
        }
        /* DOS Date and time:
            MS-DOS date. The date is a packed value with the following format. Bits Description
                0-4 Day of the month (1–31)
                5-8 Month (1 = January, 2 = February, and so on)
                9-15 Year offset from 1980 (add 1980 to get actual year)
            MS-DOS time. The time is a packed value with the following format. Bits Description
                0-4 Second divided by 2
                5-10 Minute (0–59)
                11-15 Hour (0–23 on a 24-hour clock)
        */
        private uint DateTimeToDosTime(DateTime _dt)
        {
            return (uint)(
                (_dt.Second / 2) | (_dt.Minute << 5) | (_dt.Hour << 11) |
                (_dt.Day<<16) | (_dt.Month << 21) | ((_dt.Year - 1980) << 25));
        }
        private DateTime DosTimeToDateTime(uint _dt)
        {
            return new DateTime(
                (int)(_dt >> 25) + 1980,
                (int)(_dt >> 21) & 15,
                (int)(_dt >> 16) & 31,
                (int)(_dt >> 11) & 31,
                (int)(_dt >> 5) & 63,
                (int)(_dt & 31) * 2);
        }

        /* CRC32 algorithm
          The 'magic number' for the CRC is 0xdebb20e3.
          The proper CRC pre and post conditioning
          is used, meaning that the CRC register is
          pre-conditioned with all ones (a starting value
          of 0xffffffff) and the value is post-conditioned by
          taking the one's complement of the CRC residual.
          If bit 3 of the general purpose flag is set, this
          field is set to zero in the local header and the correct
          value is put in the data descriptor and in the central
          directory.
        */
        private void UpdateCrcAndSizes(ref ZipFileEntry _zfe)
        {
            long lastPos = this.ZipFileStream.Position;  // remember position

            this.ZipFileStream.Position = _zfe.HeaderOffset + 8;
            this.ZipFileStream.Write(BitConverter.GetBytes((ushort)_zfe.Method), 0, 2);  // zipping method

            this.ZipFileStream.Position = _zfe.HeaderOffset + 14;
            this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.Crc32), 0, 4);  // Update CRC
            this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.CompressedSize), 0, 4);  // Compressed size
            this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.FileSize), 0, 4);  // Uncompressed size

            this.ZipFileStream.Position = lastPos;  // restore position
        }
        // Replaces backslashes with slashes to store in zip header
        private string NormalizedFilename(string _filename)
        {
            string filename = _filename.Replace('\\', '/');

            int pos = filename.IndexOf(':');
            if (pos >= 0)
                filename = filename.Remove(0, pos + 1);

            return filename.Trim('/');
        }
        // Reads the end-of-central-directory record
        private bool ReadFileInfo()
        {
            if (this.ZipFileStream.Length < 22)
                return false;

            try
            {
                this.ZipFileStream.Seek(-17, SeekOrigin.End);
                BinaryReader br = new BinaryReader(this.ZipFileStream);
                do
                {
                    this.ZipFileStream.Seek(-5, SeekOrigin.Current);
                    UInt32 sig = br.ReadUInt32();
                    if (sig == 0x06054b50)
                    {
                        this.ZipFileStream.Seek(6, SeekOrigin.Current);

                        UInt16 entries = br.ReadUInt16();
                        Int32 centralSize = br.ReadInt32();
                        UInt32 centralDirOffset = br.ReadUInt32();
                        UInt16 commentSize = br.ReadUInt16();

                        // check if comment field is the very last data in file
                        if (this.ZipFileStream.Position + commentSize != this.ZipFileStream.Length)
                            return false;

                        // Copy entire central directory to a memory buffer
                        this.ExistingFiles = entries;
                        this.CentralDirImage = new byte[centralSize];
                        this.ZipFileStream.Seek(centralDirOffset, SeekOrigin.Begin);
                        this.ZipFileStream.Read(this.CentralDirImage, 0, centralSize);

                        // Leave the pointer at the begining of central dir, to append new files
                        this.ZipFileStream.Seek(centralDirOffset, SeekOrigin.Begin);
                        return true;
                    }
                } while (this.ZipFileStream.Position > 0);
            }
            catch { }

            return false;
        }
        #endregion

        #region IDisposable Members
        ///
        /// Closes the Zip file stream
        ///
        public void Dispose()
        {
            this.Close();
        }
        #endregion
    }
}


text:
namespace Microsoft.PythonTools.Analysis {
    public interface IAnalysisVariable {
        /// <summary>
        /// Returns the location of where the variable is defined.
        /// </summary>
        LocationInfo Location {
            get;
        }

        VariableType Type {
            get;
        }
    }
}