text:
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):
    def forwards(self, orm):
        # Adding field 'Operation.params'
        db.add_column(
            u"edge_operation",
            "params",
            self.gf("django.db.models.fields.TextField")(null=True, blank=True),
            keep_default=False,
        )

        # Changing field 'Operation.type'
        db.alter_column(
            u"edge_operation", "type", self.gf("django.db.models.fields.IntegerField")()
        )

    def backwards(self, orm):
        # Deleting field 'Operation.params'
        db.delete_column(u"edge_operation", "params")

        # Changing field 'Operation.type'
        db.alter_column(
            u"edge_operation",
            "type",
            self.gf("django.db.models.fields.CharField")(max_length=64),
        )

    models = {
        "edge.chunk": {
            "Meta": {"object_name": "Chunk"},
            "id": (
                "django.db.models.fields.BigIntegerField",
                [],
                {"primary_key": "True"},
            ),
            "initial_fragment": (
                "django.db.models.fields.related.ForeignKey",
                [],
                {"to": "orm['edge.Fragment']", "on_delete": "models.PROTECT"},
            ),
            "sequence": ("django.db.models.fields.TextField", [], {"null": "True"}),
        },
        "edge.chunk_feature": {
            "Meta": {"object_name": "Chunk_Feature"},
            "chunk": (
                "django.db.models.fields.related.ForeignKey",
                [],
                {"to": "orm['edge.Chunk']", "on_delete": "models.PROTECT"},
            ),
            "feature": (
                "django.db.models.fields.related.ForeignKey",
                [],
                {"to": "orm['edge.Feature']", "on_delete": "models.PROTECT"},
            ),
            "feature_base_first": ("django.db.models.fields.IntegerField", [], {}),
            "feature_base_last": ("django.db.models.fields.IntegerField", [], {}),
            "id": (
                "django.db.models.fields.BigIntegerField",
                [],
                {"primary_key": "True"},
            ),
        },
        "edge.edge": {
            "Meta": {"object_name": "Edge"},
            "fragment": (
                "django.db.models.fields.related.ForeignKey",
                [],
                {"to": "orm['edge.Fragment']", "on_delete": "models.PROTECT"},
            ),
            "from_chunk": (
                "django.db.models.fields.related.ForeignKey",
                [],
                {
                    "related_name": "'out_edges'",
                    "on_delete": "models.PROTECT",
                    "to": "orm['edge.Chunk']",
                },
            ),
            "id": (
                "django.db.models.fields.BigIntegerField",
                [],
                {"primary_key": "True"},
            ),
            "to_chunk": (
                "django.db.models.fields.related.ForeignKey",
                [],
                {
                    "related_name": "'in_edges'",
                    "null": "True",
                    "on_delete": "models.PROTECT",
                    "to": "orm['edge.Chunk']",
                },
            ),
        },
        "edge.feature": {
            "Meta": {"object_name": "Feature"},
            "_qualifiers": (
                "django.db.models.fields.TextField",
                [],
                {"null": "True", "db_column": "'qualifiers'"},
            ),
            u"id": ("django.db.models.fields.AutoField", [], {"primary_key": "True"}),
            "length": ("django.db.models.fields.IntegerField", [], {}),
            "name": ("django.db.models.fields.CharField", [], {"max_length": "100"}),
            "strand": ("django.db.models.fields.IntegerField", [], {"null": "True"}),
            "type": ("django.db.models.fields.CharField", [], {"max_length": "100"}),
        },
        "edge.fragment": {
            "Meta": {"object_name": "Fragment"},
            "active": ("django.db.models.fields.BooleanField", [], {"default": "True"}),
            "circular": ("django.db.models.fields.BooleanField", [], {}),
            "created_on": (
                "django.db.models.fields.DateTimeField",
                [],
                {"auto_now_add": "True", "null": "True", "blank": "True"},
            ),
            "est_length": (
                "django.db.models.fields.IntegerField",
                [],
                {"null": "True", "blank": "True"},
            ),
            u"id": ("django.db.models.fields.AutoField", [], {"primary_key": "True"}),
            "name": ("django.db.models.fields.CharField", [], {"max_length": "256"}),
            "parent": (
                "django.db.models.fields.related.ForeignKey",
                [],
                {
                    "to": "orm['edge.Fragment']",
                    "null": "True",
                    "on_delete": "models.PROTECT",
                },
            ),
            "start_chunk": (
                "django.db.models.fields.related.ForeignKey",
                [],
                {
                    "to": "orm['edge.Chunk']",
                    "null": "True",
                    "on_delete": "models.PROTECT",
                },
            ),
        },
        "edge.fragment_chunk_location": {
            "Meta": {
                "unique_together": "(('fragment', 'chunk'),)",
                "object_name": "Fragment_Chunk_Location",
                "index_together": "(('fragment', 'base_last'), ('fragment', 'base_first'))",
            },
            "base_first": ("django.db.models.fields.IntegerField", [], {}),
            "base_last": ("django.db.models.fields.IntegerField", [], {}),
            "chunk": (
                "django.db.models.fields.related.ForeignKey",
                [],
                {"to": "orm['edge.Chunk']", "on_delete": "models.PROTECT"},
            ),
            "fragment": (
                "django.db.models.fields.related.ForeignKey",
                [],
                {"to": "orm['edge.Fragment']", "on_delete": "models.PROTECT"},
            ),
            "id": (
                "django.db.models.fields.BigIntegerField",
                [],
                {"primary_key": "True"},
            ),
        },
        "edge.fragment_index": {
            "Meta": {"object_name": "Fragment_Index"},
            "fragment": (
                "django.db.models.fields.related.OneToOneField",
                [],
                {"to": "orm['edge.Fragment']", "unique": "True"},
            ),
            "fresh": ("django.db.models.fields.BooleanField", [], {}),
            u"id": ("django.db.models.fields.AutoField", [], {"primary_key": "True"}),
            "updated_on": (
                "django.db.models.fields.DateTimeField",
                [],
                {"null": "True"},
            ),
        },
        "edge.genome": {
            "Meta": {"object_name": "Genome"},
            "active": ("django.db.models.fields.BooleanField", [], {"default": "True"}),
            "created_on": (
                "django.db.models.fields.DateTimeField",
                [],
                {"auto_now_add": "True", "null": "True", "blank": "True"},
            ),
            "fragments": (
                "django.db.models.fields.related.ManyToManyField",
                [],
                {
                    "to": "orm['edge.Fragment']",
                    "through": "orm['edge.Genome_Fragment']",
                    "symmetrical": "False",
                },
            ),
            u"id": ("django.db.models.fields.AutoField", [], {"primary_key": "True"}),
            "name": ("django.db.models.fields.CharField", [], {"max_length": "256"}),
            "notes": (
                "django.db.models.fields.TextField",
                [],
                {"null": "True", "blank": "True"},
            ),
            "operations": (
                "django.db.models.fields.related.ManyToManyField",
                [],
                {"to": "orm['edge.Operation']", "symmetrical": "False"},
            ),
            "parent": (
                "django.db.models.fields.related.ForeignKey",
                [],
                {
                    "to": "orm['edge.Genome']",
                    "null": "True",
                    "on_delete": "models.PROTECT",
                },
            ),
        },
        "edge.genome_fragment": {
            "Meta": {"object_name": "Genome_Fragment"},
            "fragment": (
                "django.db.models.fields.related.ForeignKey",
                [],
                {"to": "orm['edge.Fragment']"},
            ),
            "genome": (
                "django.db.models.fields.related.ForeignKey",
                [],
                {"to": "orm['edge.Genome']"},
            ),
            u"id": ("django.db.models.fields.AutoField", [], {"primary_key": "True"}),
            "inherited": ("django.db.models.fields.BooleanField", [], {}),
        },
        "edge.operation": {
            "Meta": {"object_name": "Operation"},
            "fragment": (
                "django.db.models.fields.related.ForeignKey",
                [],
                {"to": "orm['edge.Fragment']"},
            ),
            u"id": ("django.db.models.fields.AutoField", [], {"primary_key": "True"}),
            "notes": (
                "django.db.models.fields.TextField",
                [],
                {"null": "True", "blank": "True"},
            ),
            "params": (
                "django.db.models.fields.TextField",
                [],
                {"null": "True", "blank": "True"},
            ),
            "type": ("django.db.models.fields.IntegerField", [], {}),
        },
    }

    complete_apps = ["edge"]

redpajama_set_name: RedPajamaGithub


text:
package com.lee.cn.cd;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: wylipengming
 * Date: 14-3-11
 * Time: 下午3:58
 * 读取配置文件
 */
public class ConfigReader {
    private final static String attributeKey = "attribute";
    private final static String headerKey = "header";
    private final static String titleKey = "title";
    private final static String staticHeaderKey = "staticHeader";
    private final static String staticAttributeKey = "staticAttribute";

    private final static String itemSeparator = ",";
    private final static String listSeparator = "#";

    private static ThreadLocal<ConfigReader> threadLocal = new ThreadLocal<ConfigReader>();
    private ConfigReader(){}

    public static ConfigReader getInstall(){
        ConfigReader reader = threadLocal.get();
        if(reader == null){
            reader = new ConfigReader();
            threadLocal.set(reader);
        }
        return reader;
    }

    ////////////////////////////
    ////服务于业务逻辑-start/////
    ////////////////////////////

    public String[] getTitles(String configPath) throws Exception{
        return readProperty(configPath,titleKey,itemSeparator);
    }

    public List<String[]> getAttributes(String configPath) throws Exception{
        return readProperty(configPath,attributeKey);
    }

    public List<String[]> getHeaders(String configPath) throws Exception{
        return readProperty(configPath,headerKey);
    }

    public List<String[]> getStaticHeaders(String configPath) throws Exception{
        return readProperty(configPath,staticHeaderKey);
    }

    public List<String[]> getStaticAttributes(String configPath) throws Exception{
        return readProperty(configPath,staticAttributeKey);
    }

    ////////////////////////////
    ////服务于业务逻辑-end///////
    ////////////////////////////

    /**
     * 按照父单元读取规则读取
     *
     * @param configPath
     * @param key
     * @return
     * @throws Exception
     */
    public List<String[]> readProperty(String configPath,String key) throws Exception{
        List<String[]> list = new ArrayList<String[]>();
        //按照组合方式,切分成只有itemSeparator的项
        String[] items = readProperty(configPath, key,listSeparator);
        if(items == null || items.length < 1){
            return null;
        }
        for(String item : items){
            String[] dim = resolveStr(item,itemSeparator);
            if(dim != null && dim.length > 0){
                list.add(dim);
            }
        }
        if(list == null || items.length < 1){
            return null;
        }
        return list;
    }

    /**
     * 子单元读取
     * @param configPath
     * @param key
     * @param separator
     * @return
     * @throws Exception
     */
    private String[] readProperty(String configPath,String key,String separator) throws Exception{
        String attrStr = PropertyUtil.getInstall().readPropertyWithByte(configPath,key);
        return resolveStr(attrStr,separator);
    }

    /**
     * 字串解析
     * @param target
     * @param separator
     * @return
     */
    private String[] resolveStr(String target,String separator){
        if(target == null || "".equals(target)){
            return null;
        }

        String[] attributes = target.split(separator);
        List<String> list = Arrays.asList(attributes);

        if(list != null && !list.isEmpty()){
            Iterator<String> iter = list.iterator();

            while(iter.hasNext()){
                String str = iter.next();
                if(str == null || "".equals(str) || "".equals(str.trim()) ){
                    iter.remove();
                }
            }
            if(list.isEmpty()){
                return null;
            }else{
                return (String[]) list.toArray();
            }
        }
        return null;
    }

}


text:
General cross products for numpy. (Simple Cython project for experimenting with wrapping C libraries.)

### Usage

```python
import numpy as np
import cross_product as cp

v = np.eye(3, dtype=np.float32)
np.testing.assert_array_almost_equal(cp.cross(v[0], v[1]), v[2])

v = np.eye(4, dtype=np.float32)
np.testing.assert_array_almost_equal(cp.cross(v[0], v[1], v[2]), v[3])
```


text:
package runtime

import (
	"unsafe"
)

func disableWER() {
	// do not display Windows Error Reporting dialogue
	const (
		SEM_FAILCRITICALERRORS     = 0x0001
		SEM_NOGPFAULTERRORBOX      = 0x0002
		SEM_NOALIGNMENTFAULTEXCEPT = 0x0004
		SEM_NOOPENFILEERRORBOX     = 0x8000
	)
	errormode := uint32(stdcall1(_SetErrorMode, SEM_NOGPFAULTERRORBOX))
	stdcall1(_SetErrorMode, uintptr(errormode)|SEM_FAILCRITICALERRORS|SEM_NOGPFAULTERRORBOX|SEM_NOOPENFILEERRORBOX)
}

// in sys_windows_386.s and sys_windows_amd64.s
func exceptiontramp()
func firstcontinuetramp()
func lastcontinuetramp()

func initExceptionHandler() {
	stdcall2(_AddVectoredExceptionHandler, 1, funcPC(exceptiontramp))
	if _AddVectoredContinueHandler == nil || unsafe.Sizeof(&_AddVectoredContinueHandler) == 4 {
		// use SetUnhandledExceptionFilter for windows-386 or
		// if VectoredContinueHandler is unavailable.
		// note: SetUnhandledExceptionFilter handler won't be called, if debugging.
		stdcall1(_SetUnhandledExceptionFilter, funcPC(lastcontinuetramp))
	} else {
		stdcall2(_AddVectoredContinueHandler, 1, funcPC(firstcontinuetramp))
		stdcall2(_AddVectoredContinueHandler, 0, funcPC(lastcontinuetramp))
	}
}

func isgoexception(info *exceptionrecord, r *context) bool {
	// Only handle exception if executing instructions in Go binary
	// (not Windows library code).
	// TODO(mwhudson): needs to loop to support shared libs
	if r.ip() < firstmoduledata.text || firstmoduledata.etext < r.ip() {
		return false
	}

	// Go will only handle some exceptions.
	switch info.exceptioncode {
	default:
		return false
	case _EXCEPTION_ACCESS_VIOLATION:
	case _EXCEPTION_INT_DIVIDE_BY_ZERO:
	case _EXCEPTION_INT_OVERFLOW:
	case _EXCEPTION_FLT_DENORMAL_OPERAND:
	case _EXCEPTION_FLT_DIVIDE_BY_ZERO:
	case _EXCEPTION_FLT_INEXACT_RESULT:
	case _EXCEPTION_FLT_OVERFLOW:
	case _EXCEPTION_FLT_UNDERFLOW:
	case _EXCEPTION_BREAKPOINT:
	}
	return true
}

// Called by sigtramp from Windows VEH handler.
// Return value signals whether the exception has been handled (EXCEPTION_CONTINUE_EXECUTION)
// or should be made available to other handlers in the chain (EXCEPTION_CONTINUE_SEARCH).
func exceptionhandler(info *exceptionrecord, r *context, gp *g) int32 {
	if !isgoexception(info, r) {
		return _EXCEPTION_CONTINUE_SEARCH
	}

	// Make it look like a call to the signal func.
	// Have to pass arguments out of band since
	// augmenting the stack frame would break
	// the unwinding code.
	gp.sig = info.exceptioncode
	gp.sigcode0 = uintptr(info.exceptioninformation[0])
	gp.sigcode1 = uintptr(info.exceptioninformation[1])
	gp.sigpc = r.ip()

	// Only push runtime·sigpanic if r.ip() != 0.
	// If r.ip() == 0, probably panicked because of a
	// call to a nil func.  Not pushing that onto sp will
	// make the trace look like a call to runtime·sigpanic instead.
	// (Otherwise the trace will end at runtime·sigpanic and we
	// won't get to see who faulted.)
	if r.ip() != 0 {
		sp := unsafe.Pointer(r.sp())
		sp = add(sp, ^uintptr(unsafe.Sizeof(uintptr(0))-1)) // sp--
		*((*uintptr)(sp)) = r.ip()
		r.setsp(uintptr(sp))
	}
	r.setip(funcPC(sigpanic))
	return _EXCEPTION_CONTINUE_EXECUTION
}

// It seems Windows searches ContinueHandler's list even
// if ExceptionHandler returns EXCEPTION_CONTINUE_EXECUTION.
// firstcontinuehandler will stop that search,
// if exceptionhandler did the same earlier.
func firstcontinuehandler(info *exceptionrecord, r *context, gp *g) int32 {
	if !isgoexception(info, r) {
		return _EXCEPTION_CONTINUE_SEARCH
	}
	return _EXCEPTION_CONTINUE_EXECUTION
}

var testingWER bool

// lastcontinuehandler is reached, because runtime cannot handle
// current exception. lastcontinuehandler will print crash info and exit.
func lastcontinuehandler(info *exceptionrecord, r *context, gp *g) int32 {
	if testingWER {
		return _EXCEPTION_CONTINUE_SEARCH
	}

	_g_ := getg()

	if panicking != 0 { // traceback already printed
		exit(2)
	}
	panicking = 1

	print("Exception ", hex(info.exceptioncode), " ", hex(info.exceptioninformation[0]), " ", hex(info.exceptioninformation[1]), " ", hex(r.ip()), "\n")

	print("PC=", hex(r.ip()), "\n")
	if _g_.m.lockedg != nil && _g_.m.ncgo > 0 && gp == _g_.m.g0 {
		if iscgo {
			print("signal arrived during external code execution\n")
		}
		gp = _g_.m.lockedg
	}
	print("\n")

	var docrash bool
	if gotraceback(&docrash) > 0 {
		tracebacktrap(r.ip(), r.sp(), 0, gp)
		tracebackothers(gp)
		dumpregs(r)
	}

	if docrash {
		crash()
	}

	exit(2)
	return 0 // not reached
}

func sigpanic() {
	g := getg()
	if !canpanic(g) {
		throw("unexpected signal during runtime execution")
	}

	switch uint32(g.sig) {
	case _EXCEPTION_ACCESS_VIOLATION:
		if g.sigcode1 < 0x1000 || g.paniconfault {
			panicmem()
		}
		print("unexpected fault address ", hex(g.sigcode1), "\n")
		throw("fault")
	case _EXCEPTION_INT_DIVIDE_BY_ZERO:
		panicdivide()
	case _EXCEPTION_INT_OVERFLOW:
		panicoverflow()
	case _EXCEPTION_FLT_DENORMAL_OPERAND,
		_EXCEPTION_FLT_DIVIDE_BY_ZERO,
		_EXCEPTION_FLT_INEXACT_RESULT,
		_EXCEPTION_FLT_OVERFLOW,
		_EXCEPTION_FLT_UNDERFLOW:
		panicfloat()
	}
	throw("fault")
}

var (
	badsignalmsg [100]byte
	badsignallen int32
)

func setBadSignalMsg() {
	const msg = "runtime: signal received on thread not created by Go.\n"
	for i, c := range msg {
		badsignalmsg[i] = byte(c)
		badsignallen++
	}
}

// Following are not implemented.

func initsig() {
}

func sigenable(sig uint32) {
}

func sigdisable(sig uint32) {
}

func sigignore(sig uint32) {
}

func badsignal2()

func raisebadsignal(sig int32) {
	badsignal2()
}

func crash() {
	// TODO: This routine should do whatever is needed
	// to make the Windows program abort/crash as it
	// would if Go was not intercepting signals.
	// On Unix the routine would remove the custom signal
	// handler and then raise a signal (like SIGABRT).
	// Something like that should happen here.
	// It's okay to leave this empty for now: if crash returns
	// the ordinary exit-after-panic happens.
}


text:
/* -*-c++-*- */
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
 * Copyright 2008-2013 Pelican Mapping
 * http://osgearth.org
 *
 * osgEarth is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 */
#include <osgEarth/Capabilities>
#include <osg/FragmentProgram>
#include <osg/GraphicsContext>
#include <osg/GL>
#include <osg/GLExtensions>
#include <osg/GL2Extensions>
#include <osg/Texture>
#include <osgViewer/Version>
#include <OpenThreads/Thread>

using namespace osgEarth;

#define LC "[Capabilities] "

// ---------------------------------------------------------------------------
// A custom P-Buffer graphics context that we will use to query for OpenGL
// extension and hardware support. (Adapted from osgconv in OpenSceneGraph)

struct MyGraphicsContext
{
    MyGraphicsContext()
    {

    	osg::GraphicsContext::ScreenIdentifier si;
	    si.readDISPLAY();
	    si.setUndefinedScreenDetailsToDefaultScreen();

        osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
    	traits->hostName = si.hostName;
	    traits->displayNum = si.displayNum;
	    traits->screenNum = si.screenNum;
        traits->x = 0;
        traits->y = 0;
        traits->width = 1;
        traits->height = 1;
        traits->windowDecoration = false;
        traits->doubleBuffer = false;
        traits->sharedContext = 0;
        traits->pbuffer = false;

        // Intel graphics adapters dont' support pbuffers, and some of their drivers crash when
        // you try to create them. So by default we will only use the unmapped/pbuffer method
        // upon special request.
        if ( getenv( "OSGEARTH_USE_PBUFFER_TEST" ) )
        {
            traits->pbuffer = true;
            OE_INFO << LC << "Activating pbuffer test for graphics capabilities" << std::endl;
            _gc = osg::GraphicsContext::createGraphicsContext(traits.get());
            if ( !_gc.valid() )
                OE_WARN << LC << "Failed to create pbuffer" << std::endl;
        }

        if (!_gc.valid())
        {
            // fall back on a mapped window
            traits->pbuffer = false;
            _gc = osg::GraphicsContext::createGraphicsContext(traits.get());
        }

        if (_gc.valid())
        {
            _gc->realize();
            _gc->makeCurrent();

            if ( traits->pbuffer == false )
            {
                OE_DEBUG << LC << "Realized graphics window for OpenGL operations." << std::endl;
            }
            else
            {
                OE_DEBUG << LC << "Realized pbuffer for OpenGL operations." << std::endl;
            }
        }
        else
        {
            OE_WARN << LC << "Failed to create graphic window too." << std::endl;
        }
    }

    bool valid() const { return _gc.valid() && _gc->isRealized(); }

    osg::ref_ptr<osg::GraphicsContext> _gc;
};

// ---------------------------------------------------------------------------

#define SAYBOOL(X) (X?"yes":"no")

Capabilities::Capabilities() :
_maxFFPTextureUnits     ( 1 ),
_maxGPUTextureUnits     ( 1 ),
_maxGPUTextureCoordSets ( 1 ),
_maxGPUAttribs          ( 1 ),
_maxTextureSize         ( 256 ),
_maxFastTextureSize     ( 256 ),
_maxLights              ( 1 ),
_depthBits              ( 0 ),
_supportsGLSL           ( false ),
_GLSLversion            ( 1.0f ),
_supportsTextureArrays  ( false ),
_supportsMultiTexture   ( false ),
_supportsStencilWrap    ( true ),
_supportsTwoSidedStencil( false ),
_supportsTexture3D      ( false ),
_supportsTexture2DLod   ( false ),
_supportsMipmappedTextureUpdates( false ),
_supportsDepthPackedStencilBuffer( false ),
_supportsOcclusionQuery ( false ),
_supportsDrawInstanced  ( false ),
_supportsUniformBufferObjects( false ),
_supportsNonPowerOfTwoTextures( false ),
_maxUniformBlockSize    ( 0 ),
_preferDLforStaticGeom  ( true ),
_numProcessors          ( 1 ),
_supportsFragDepthWrite ( false ),
_supportsS3TC           ( false ),
_supportsPVRTC          ( false ),
_supportsARBTC          ( false ),
_supportsETC            ( false ),
_supportsRGTC           ( false )
{
    // little hack to force the osgViewer library to link so we can create a graphics context
    osgViewerGetVersion();

    // check the environment in order to disable ATI workarounds
    bool enableATIworkarounds = true;
    if ( ::getenv( "OSGEARTH_DISABLE_ATI_WORKAROUNDS" ) != 0L )
        enableATIworkarounds = false;

    // logical CPUs (cores)
    _numProcessors = OpenThreads::GetNumberOfProcessors();

    // create a graphics context so we can query OpenGL support:
    MyGraphicsContext mgc;

    if ( mgc.valid() )
    {
        osg::GraphicsContext* gc = mgc._gc.get();
        unsigned int id = gc->getState()->getContextID();
        const osg::GL2Extensions* GL2 = osg::GL2Extensions::Get( id, true );

        if ( ::getenv("OSGEARTH_NO_GLSL") )
        {
            _supportsGLSL = false;
            OE_INFO << LC << "Note: GLSL expressly disabled (OSGEARTH_NO_GLSL)" << std::endl;
        }
        else
        {
            _supportsGLSL = GL2->isGlslSupported();
        }

        OE_INFO << LC << "Detected hardware capabilities:" << std::endl;

        _vendor = std::string( reinterpret_cast<const char*>(glGetString(GL_VENDOR)) );
        OE_INFO << LC << "  Vendor = " << _vendor << std::endl;

        _renderer = std::string( reinterpret_cast<const char*>(glGetString(GL_RENDERER)) );
        OE_INFO << LC << "  Renderer = " << _renderer << std::endl;

        _version = std::string( reinterpret_cast<const char*>(glGetString(GL_VERSION)) );
        OE_INFO << LC << "  Version = " << _version << std::endl;

        glGetIntegerv( GL_MAX_TEXTURE_UNITS, &_maxFFPTextureUnits );
        OE_INFO << LC << "  Max FFP texture units = " << _maxFFPTextureUnits << std::endl;

        glGetIntegerv( GL_MAX_TEXTURE_IMAGE_UNITS_ARB, &_maxGPUTextureUnits );
        OE_INFO << LC << "  Max GPU texture units = " << _maxGPUTextureUnits << std::endl;

        glGetIntegerv( GL_MAX_TEXTURE_COORDS_ARB, &_maxGPUTextureCoordSets );
        OE_INFO << LC << "  Max GPU texture coord indices = " << _maxGPUTextureCoordSets << std::endl;

        glGetIntegerv( GL_MAX_VERTEX_ATTRIBS, &_maxGPUAttribs );
        OE_INFO << LC << "  Max GPU attributes = " << _maxGPUAttribs << std::endl;

        glGetIntegerv( GL_DEPTH_BITS, &_depthBits );
        OE_INFO << LC << "  Depth buffer bits = " << _depthBits << std::endl;

        glGetIntegerv( GL_MAX_TEXTURE_SIZE, &_maxTextureSize );
#if !(defined(OSG_GLES1_AVAILABLE) || defined(OSG_GLES2_AVAILABLE))
        // Use the texture-proxy method to determine the maximum texture size
        for( int s = _maxTextureSize; s > 2; s >>= 1 )
        {
            glTexImage2D( GL_PROXY_TEXTURE_2D, 0, GL_RGBA8, s, s, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0L );
            GLint width = 0;
            glGetTexLevelParameteriv( GL_PROXY_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &width );
            if ( width == s )
            {
                _maxTextureSize = s;
                break;
            }
        }
#endif
        OE_INFO << LC << "  Max texture size = " << _maxTextureSize << std::endl;

        //PORT@tom, what effect will this have?
#ifdef OSG_GL_FIXED_FUNCTION_AVAILABLE
        glGetIntegerv( GL_MAX_LIGHTS, &_maxLights );
#else
        _maxLights = 1;
#endif
        OE_INFO << LC << "  Max lights = " << _maxLights << std::endl;

        OE_INFO << LC << "  GLSL = " << SAYBOOL(_supportsGLSL) << std::endl;

        if ( _supportsGLSL )
        {
            _GLSLversion = GL2->getLanguageVersion();
            OE_INFO << LC << "  GLSL Version = " << getGLSLVersionInt() << std::endl;
        }

        _supportsTextureArrays =
            _supportsGLSL &&
            osg::getGLVersionNumber() >= 2.0f && // hopefully this will detect Intel cards
            osg::isGLExtensionSupported( id, "GL_EXT_texture_array" );
        OE_INFO << LC << "  Texture arrays = " << SAYBOOL(_supportsTextureArrays) << std::endl;

        _supportsTexture3D = osg::isGLExtensionSupported( id, "GL_EXT_texture3D" );
        OE_INFO << LC << "  3D textures = " << SAYBOOL(_supportsTexture3D) << std::endl;

        _supportsMultiTexture =
            osg::getGLVersionNumber() >= 1.3f ||
            osg::isGLExtensionSupported( id, "GL_ARB_multitexture") ||
            osg::isGLExtensionSupported( id, "GL_EXT_multitexture" );
        OE_INFO << LC << "  Multitexturing = " << SAYBOOL(_supportsMultiTexture) << std::endl;

        _supportsStencilWrap = osg::isGLExtensionSupported( id, "GL_EXT_stencil_wrap" );
        OE_INFO << LC << "  Stencil wrapping = " << SAYBOOL(_supportsStencilWrap) << std::endl;

        _supportsTwoSidedStencil = osg::isGLExtensionSupported( id, "GL_EXT_stencil_two_side" );
        OE_INFO << LC << "  2-sided stencils = " << SAYBOOL(_supportsTwoSidedStencil) << std::endl;

        _supportsDepthPackedStencilBuffer = osg::isGLExtensionSupported( id, "GL_EXT_packed_depth_stencil" ) ||
                                            osg::isGLExtensionSupported( id, "GL_OES_packed_depth_stencil" );
        OE_INFO << LC << "  depth-packed stencil = " << SAYBOOL(_supportsDepthPackedStencilBuffer) << std::endl;

        _supportsOcclusionQuery = osg::isGLExtensionSupported( id, "GL_ARB_occlusion_query" );
        OE_INFO << LC << "  occlusion query = " << SAYBOOL(_supportsOcclusionQuery) << std::endl;

        _supportsDrawInstanced =
            _supportsGLSL &&
            osg::isGLExtensionOrVersionSupported( id, "GL_EXT_draw_instanced", 3.1f );
        OE_INFO << LC << "  draw instanced = " << SAYBOOL(_supportsDrawInstanced) << std::endl;

        glGetIntegerv( GL_MAX_UNIFORM_BLOCK_SIZE, &_maxUniformBlockSize );
        OE_INFO << LC << "  max uniform block size = " << _maxUniformBlockSize << std::endl;

        _supportsUniformBufferObjects =
            _supportsGLSL &&
            osg::isGLExtensionOrVersionSupported( id, "GL_ARB_uniform_buffer_object", 2.0f );
        OE_INFO << LC << "  uniform buffer objects = " << SAYBOOL(_supportsUniformBufferObjects) << std::endl;

        if ( _supportsUniformBufferObjects && _maxUniformBlockSize == 0 )
        {
            OE_INFO << LC << "  ...but disabled, since UBO block size reports zero" << std::endl;
            _supportsUniformBufferObjects = false;
        }

        _supportsNonPowerOfTwoTextures =
            osg::isGLExtensionSupported( id, "GL_ARB_texture_non_power_of_two" );
        OE_INFO << LC << "  NPOT textures = " << SAYBOOL(_supportsNonPowerOfTwoTextures) << std::endl;

        // Writing to gl_FragDepth is not supported under GLES:
#if (defined(OSG_GLES1_AVAILABLE) || defined(OSG_GLES2_AVAILABLE))
        _supportsFragDepthWrite = false;
#else
        _supportsFragDepthWrite = true;
#endif

        //_supportsTexture2DLod = osg::isGLExtensionSupported( id, "GL_ARB_shader_texture_lod" );
        //OE_INFO << LC << "  texture2DLod = " << SAYBOOL(_supportsTexture2DLod) << std::endl;

        // NVIDIA:
        bool isNVIDIA = _vendor.find("NVIDIA") == 0;

        // NVIDIA has h/w acceleration of some kind for display lists, supposedly.
        // In any case they do benchmark much faster in osgEarth for static geom.
        // BUT unfortunately, they dont' seem to work too well with shaders. Colors
        // change randomly, etc. Might work OK for textured geometry but not for
        // untextured. TODO: investigate.
#if 1
        _preferDLforStaticGeom = false;
        if ( ::getenv("OSGEARTH_TRY_DISPLAY_LISTS") )
        {
            _preferDLforStaticGeom = true;
        }
#else
        if ( ::getenv("OSGEARTH_ALWAYS_USE_VBOS") )
        {
            _preferDLforStaticGeom = false;
        }
        else
        {
            _preferDLforStaticGeom = isNVIDIA;
        }
#endif

        OE_INFO << LC << "  prefer DL for static geom = " << SAYBOOL(_preferDLforStaticGeom) << std::endl;

        // ATI workarounds:
        bool isATI = _vendor.find("ATI ") == 0;

        _supportsMipmappedTextureUpdates = isATI && enableATIworkarounds ? false : true;
        OE_INFO << LC << "  Mipmapped texture updates = " << SAYBOOL(_supportsMipmappedTextureUpdates) << std::endl;

#if 0
        // Intel workarounds:
        bool isIntel =
            _vendor.find("Intel ")   != std::string::npos ||
            _vendor.find("Intel(R)") != std::string::npos ||
            _vendor.compare("Intel") == 0;
#endif

        _maxFastTextureSize = _maxTextureSize;

        OE_INFO << LC << "  Max Fast Texture Size = " << _maxFastTextureSize << std::endl;

        // tetxure compression
        OE_INFO << LC << "  Compression = ";
        _supportsARBTC = osg::isGLExtensionSupported( id, "GL_ARB_texture_compression" );
        if (_supportsARBTC) OE_INFO_CONTINUE << "ARB ";

        _supportsS3TC = osg::isGLExtensionSupported( id, "GL_EXT_texture_compression_s3tc" );
        if ( _supportsS3TC ) OE_INFO_CONTINUE << "S3 ";

        _supportsPVRTC = osg::isGLExtensionSupported( id, "GL_IMG_texture_compression_pvrtc" );
        if ( _supportsPVRTC ) OE_INFO_CONTINUE << "PVR ";

        _supportsETC = osg::isGLExtensionSupported( id, "GL_OES_compressed_ETC1_RGB8_texture" );
        if ( _supportsETC ) OE_INFO_CONTINUE << "ETC1 ";

        _supportsRGTC = osg::isGLExtensionSupported( id, "GL_EXT_texture_compression_rgtc" );
        if ( _supportsRGTC ) OE_INFO_CONTINUE << "RG";

        OE_INFO_CONTINUE << std::endl;
    }
}

bool
Capabilities::supportsTextureCompression(const osg::Texture::InternalFormatMode& mode) const
{
    switch( mode )
    {
    case osg::Texture::USE_ARB_COMPRESSION:
        return _supportsARBTC;
        break;

    case osg::Texture::USE_S3TC_DXT1a_COMPRESSION:
    case osg::Texture::USE_S3TC_DXT1c_COMPRESSION:
    case osg::Texture::USE_S3TC_DXT1_COMPRESSION:
    case osg::Texture::USE_S3TC_DXT3_COMPRESSION:
    case osg::Texture::USE_S3TC_DXT5_COMPRESSION:
        return _supportsS3TC;
        break;

    case osg::Texture::USE_PVRTC_2BPP_COMPRESSION:
    case osg::Texture::USE_PVRTC_4BPP_COMPRESSION:
        return _supportsPVRTC;
        break;

    case osg::Texture::USE_ETC_COMPRESSION:
        return _supportsETC;
        break;

    case osg::Texture::USE_RGTC1_COMPRESSION:
    case osg::Texture::USE_RGTC2_COMPRESSION:
        return _supportsRGTC;
        break;

    default:
        return false;
    }

    return false;
}