text:
HOST = 'http://www.dianping.com'

CITY_IDS = [
    (2, 'beijing'),
]

# only need '_hc.v'
COOKIES = 'showNav=#nav-tab|0|0; navCtgScroll=0; navCtgScroll=0; _hc.v=a38e4721-eee7-9167-2f73-d0ce0182365d.1486954839; PHOENIX_ID=0a010444-15a68e17bd2-25c5754a; __utma=205923334.1798401956.1487817449.1487817449.1487817449.1; __utmc=205923334; __utmz=205923334.1487817449.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); default_ab=shopreviewlist%3AA%3A1; __mta=171228447.1487818368557.1487925211991.1487925530915.6; s_ViewType=10; JSESSIONID=BB36B3E0304AE3DD14BCCDF129EB2521; aburl=1; cy=2; cye=beijing'
# convert cookies string to dict
COOKIES = dict([tuple(p.strip().split('=', 1)) for p in COOKIES.split(';')])

PROXIES = [
    # spec https://github.com/constverum/ProxyBroker
    'http://127.0.0.1:8888',
]

BOT_NAME = 'dianping_crawler'
MONGO_DATABASE = 'dianping'

SPIDER_MODULES = ['dianping_crawler.spiders']
NEWSPIDER_MODULE = 'dianping_crawler.spiders'

# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'dianping_crawler (+http://www.yourdomain.com)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

# Configure maximum concurrent requests performed by Scrapy (default: 16)
CONCURRENT_REQUESTS = 2

# Configure a delay for requests for the same website (default: 0)
# See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
DOWNLOAD_DELAY = 1
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
DEFAULT_REQUEST_HEADERS = {
#   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
#   'Accept-Language': 'en',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36',
}

# DELTAFETCH_ENABLED = True

# Enable or disable spider middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
SPIDER_MIDDLEWARES = {
    # 'dianping_crawler.middlewares.DianpingCrawlerSpiderMiddleware': 543,
    # 'dianping_crawler.middlewares.DeltaSpiderMiddleware': 543,
}

# Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
    # 'scrapy.downloadermiddlewares.retry.RetryMiddleware': 80,
    # 'dianping_crawler.middlewares.DeltaSpiderMiddleware': 543,
    # 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': 750,
}

# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   'dianping_crawler.pipelines.DianpingCrawlerPipeline': 300,
}

# Enable or disable extensions
# See http://scrapy.readthedocs.org/en/latest/topics/extensions.html
EXTENSIONS = {
   'scrapy.extensions.telnet.TelnetConsole': None,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See http://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'


text:
In order to develop new functionalities of Volumio, depending on which part you want to improve, you need to set up a development environment.
Volumio is designed to be an highly integrated system. This means that the WebUi is optimized to work along with the custom made Volumio system, and therefore it needs to run in a very tightly controlled environment. IT WON'T WORK on standard Raspbian or other non-volumio OSes. If you want to know what kind of customizations we're using, take a look at the [Volumio Builder](https://github.com/volumio/Build)

So, we suggest to have a running Volumio device connected to your local network, while developing on your machine

* [the Backend](Set_up_development_environment_for_backend)
* [the UI](Set_up_development_environment_for_UI)

If you are interested in creating your own images please read on here:

* [Creating Volumio Images](Set_up_development_environment_for_Volumio_images)

redpajama_set_name: RedPajamaGithub


text:
module Graphics.Rendering.OpenGL.Raw.NV.TexgenEmboss (
   -- * Tokens
   gl_EMBOSS_MAP,
   gl_EMBOSS_LIGHT,
   gl_EMBOSS_CONSTANT
) where

import Graphics.Rendering.OpenGL.Raw.Core32

gl_EMBOSS_MAP :: GLenum
gl_EMBOSS_MAP = 0x855F

gl_EMBOSS_LIGHT :: GLenum
gl_EMBOSS_LIGHT = 0x855D

gl_EMBOSS_CONSTANT :: GLenum
gl_EMBOSS_CONSTANT = 0x855E


text:
from abc import ABCMeta, abstractproperty

class Cls:
    @property
    def attribute(self, param, param1): # [property-with-parameters]
        return param + param1

class MyClassBase(metaclass=ABCMeta):
    """MyClassBase."""

    @abstractproperty
    def example(self):
        """Getter."""

    @abstractproperty
    @example.setter
    def example(self, value):
        """Setter."""


text:
using Esri.ArcGISRuntime;
using Esri.ArcGISRuntime.Controls;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Layers;
using System.Linq;
using Windows.UI.Xaml.Controls;

namespace ArcGISRuntimeSDKDotNet_PhoneSamples.Samples
{
	/// <summary>
	/// This sample demonstrates displaying an overview map to indicate the extent of the parent map.
	/// </summary>
	/// <title>Overview Map</title>
	/// <category>Mapping</category>
	public sealed partial class OverviewMap : Page
	{
		public OverviewMap()
		{
			this.InitializeComponent();

			MyMapView.Map.InitialViewpoint = new Viewpoint(new Envelope(-5, 20, 50, 65, SpatialReferences.Wgs84));

		}

		private async void MyMapView_ExtentChanged(object sender, System.EventArgs e)
		{
			var graphicslayer = overviewMap.Map.Layers.OfType<GraphicsLayer>().FirstOrDefault();
			Graphic g = graphicslayer.Graphics.FirstOrDefault();
			if (g == null) //first time
			{
				g = new Graphic();
				graphicslayer.Graphics.Add(g);
			}
			g.Geometry = MyMapView.Extent;

			// Adjust overview map scale
			await overviewMap.SetViewAsync(MyMapView.Extent.GetCenter(), MyMapView.Scale * 15);

		}
	}
}


text:
<component name="ProjectRunConfigurationManager">
  <configuration default="false" name="Stroom Create Admin Permissions" type="Application" factoryName="Application" singleton="false">
    <option name="MAIN_CLASS_NAME" value="stroom.app.App" />
    <module name="stroom.stroom-app.main" />
    <option name="PROGRAM_PARAMETERS" value="manage_users ../local.yml --createUser admin --createGroup Administrators --addToGroup admin Administrators --grantPermission Administrators "Administrator"" />
    <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/stroom-app" />
    <option name="VM_PARAMETERS" value="--add-opens java.base/java.nio=ALL-UNNAMED --add-opens java.base/sun.nio.ch=ALL-UNNAMED --add-opens java.base/java.lang=ALL-UNNAMED" />\
    <method v="2">
      <option name="Make" enabled="true" />
    </method>
  </configuration>
</component>


text:
import org.apache.camel.BeanInject;

public class TestClass3 {

}


text:
OBJS = select_echod epoll_echod udpd udp

CFLAGS = -g -O0

include ../include/example.mk


text:
namespace fd {

QuaxolChunk::QuaxolChunk(Vec4f position, Vec4f blockSize)
    : m_position(position)
    , m_blockSize(blockSize)
    , m_blockDims(c_mxSz, c_mxSz, c_mxSz, c_mxSz) {
}

QuaxolChunk::~QuaxolChunk() {}

bool QuaxolChunk::SetFromList(const TVecQuaxol* pPresent, const QuaxolSpec* offset) {
  if(!pPresent)
    return false;

  // This allows blocks to be loaded from anywhere and then made in local coords
  // for this specific chunk.
  QuaxolSpec origin(0,0,0,0);
  if(offset != NULL) {
    origin = *offset;
  }

  for(auto block : *pPresent) {
    QuaxolSpec local(block);
    local -= origin; // translate into chunk local coords.
    if(local.x < 0 || local.x >= c_mxSz
        || local.y < 0 || local.y >= c_mxSz
        || local.z < 0 || local.z >= c_mxSz
        || local.w < 0 || local.w >= c_mxSz) {
      printf("Block out of bounds: o:(%d %d %d %d) block:(%d %d %d %d)\n",
        origin.x, origin.y, origin.z, origin.w, local.x, local.y, local.z, local.w);
      continue;
    }

    int autoType = (local.w * 4 + (local.x % 3)) % 3;

    Block& fetchBlock = GetBlock(local.x, local.y, local.z, local.w);
    fetchBlock.present = true;
    fetchBlock.type = autoType;
  }

  UpdateRendering();

  return true;
}

bool QuaxolChunk::LoadFromList(const TVecQuaxol* pPresent, const QuaxolSpec* offset) {
  static unsigned char startFilled = 0; //0xff
  memset(&m_blocks, startFilled, sizeof(m_blocks));
  return SetFromList(pPresent, offset);
}

void QuaxolChunk::UpdateRendering() {
  UpdateConnects();
  UpdateTrisFromConnects();
}

void QuaxolChunk::Clear() {
  memset(m_blocks, 0, sizeof(m_blocks));
  UpdateRendering();
}

void QuaxolChunk::SetAt(const QuaxolSpec& pos, bool present) {
  if(!IsValid(pos)) return;
  Block& block = GetBlock(pos);
  block.present = present;
}

void QuaxolChunk::SetAt(const QuaxolSpec& pos, bool present, int type) {
  if(!IsValid(pos)) return;
  Block& block = GetBlock(pos);
  block.present = present;
  block.type = (unsigned char)type;
}

void QuaxolChunk::UpdateConnects() {
  // do this the slow but simple way as a first pass
  // index x,y,w,z currently, so do that loop
  m_cubeCount = 0;
  for (int x = 0; x < c_mxSz; ++x) {
    for (int y = 0; y < c_mxSz; ++y) {
      for (int w = 0; w < c_mxSz; ++w) {
        for (int z = 0; z < c_mxSz; ++z) {
          RenderBlock& rBlock = m_connects[x][y][z][w];
          rBlock.connectFlags = 0;
          if (!IsPresent(x, y, z, w)) {
            continue;
          }
          //else {
          //  rBlock.connectFlags = 0xff;
          //  continue;
          //}

          m_cubeCount += SetConnect(rBlock, RenderBlock::XPlus,  x+1, y, z, w);
          m_cubeCount += SetConnect(rBlock, RenderBlock::XMinus, x-1, y, z, w);
          m_cubeCount += SetConnect(rBlock, RenderBlock::YPlus,  x, y+1, z, w);
          m_cubeCount += SetConnect(rBlock, RenderBlock::YMinus, x, y-1, z, w);
          m_cubeCount += SetConnect(rBlock, RenderBlock::ZPlus,  x, y, z+1, w);
          m_cubeCount += SetConnect(rBlock, RenderBlock::ZMinus, x, y, z-1, w);
          m_cubeCount += SetConnect(rBlock, RenderBlock::WPlus,  x, y, z, w+1);
          m_cubeCount += SetConnect(rBlock, RenderBlock::WMinus, x, y, z, w-1);
        }
      }
    }
  }
}

void CanonicalCube::addFlaggedQuad(IndexList& indices, VertDirs& vertDirs, unsigned char flags, int a, int b, int c, int d) {
  unsigned char commonFlag = vertDirs[a] & vertDirs[b] & vertDirs[c] & vertDirs[d];
  if (commonFlag & flags) {
    indices.push_back(a);
    indices.push_back(b);
    indices.push_back(c);

    indices.push_back(c);
    indices.push_back(b);
    indices.push_back(d);
  }
}

void CanonicalCube::addFlaggedCube(IndexList& indices, VertDirs& vertDirs, unsigned char flags, int a, int b, int c, int d, int e, int f, int g, int h) {
  addFlaggedQuad(indices, vertDirs, flags, a, b, c, d);
  addFlaggedQuad(indices, vertDirs, flags, a, b, e, f);
  addFlaggedQuad(indices, vertDirs, flags, a, c, e, g);
  addFlaggedQuad(indices, vertDirs, flags, b, d, f, h);
  addFlaggedQuad(indices, vertDirs, flags, c, d, g, h);
  addFlaggedQuad(indices, vertDirs, flags, e, f, g, h);
}

//          |   \\       \?
//          |     \\      \?
// --> x    v y     v z    \?
//                          v w
// 00  01
// 02  03
//   04  05
//   06  07
//  08  09
//  10  11
//    12  13
//    14  15
// the premise is that not only are whole cubes clipped
// but also faces on adjacent cubes
// probably going to realize this is hopelessly wrong about 10 seconds
// after I see the results for the first time
void CanonicalCube::addFlaggedTesseract(IndexList& indices, VertDirs& vertDirs, unsigned char flags) {
  static bool bOverride = false;
  if(flags & RenderBlock::XPlus || bOverride) {
    addFlaggedCube(indices, vertDirs, flags, 1, 3, 5, 7, 9, 11, 13, 15); // x plus
  }
  if(flags & RenderBlock::XMinus || bOverride) {
    addFlaggedCube(indices, vertDirs, flags, 0, 2, 4, 6, 8, 10, 12, 14); // x minus
  }
  if (flags & RenderBlock::YPlus || bOverride) {
    addFlaggedCube(indices, vertDirs, flags, 2, 3, 6, 7, 10, 11, 14, 15); // y plus
  }
  if (flags & RenderBlock::YMinus || bOverride) {
    addFlaggedCube(indices, vertDirs, flags, 0, 1, 4, 5, 8, 9, 12, 13); // y minus
  }
  if (flags & RenderBlock::ZPlus || bOverride) {
    addFlaggedCube(indices, vertDirs, flags, 4, 5, 6, 7, 12, 13, 14, 15); // z plus
  }
  if (flags & RenderBlock::ZMinus || bOverride) {
    addFlaggedCube(indices, vertDirs, flags, 0, 1, 2, 3, 8, 9, 10, 11); // z minus
  }
  if (flags & RenderBlock::WPlus || bOverride) {
    addFlaggedCube(indices, vertDirs, flags, 8, 9, 10, 11, 12, 13, 14, 15); // w plus
  }
  if (flags & RenderBlock::WMinus || bOverride) {
    addFlaggedCube(indices, vertDirs, flags, 0, 1, 2, 3, 4, 5, 6, 7); // w minus
  }
}

void CanonicalCube::populateVerts(float size, QVertList& packVerts, VecList& verts, VertDirs& vertDirs) {
  const int dim = 4;
  int numVerts = 1 << dim;
  packVerts.resize(0);
  packVerts.reserve(numVerts);
  verts.resize(0);
  verts.reserve(numVerts);
  vertDirs.resize(0);
  vertDirs.reserve(numVerts);
  for (int i = 0; i < numVerts; i++) {
    int possibleDim = dim - 1;
    const int& mask = i;

    QuaxolVert packVert;
    packVert._position = 0;
    packVert._uv_ao = 0;
    Vec4f vert;

    unsigned char dirs = 0;
    while (possibleDim >= 0) {
      if (mask & (1 << possibleDim)) {
        packVert._position |= (1 << (possibleDim * c_quaxolPositionBits));
        vert.set(possibleDim, size);
        dirs |= (1 << ((possibleDim * 2) + 0));
      } else {
        dirs |= (1 << ((possibleDim * 2) + 1));
      }
      possibleDim--;
    }

    verts.push_back(vert);
    vertDirs.push_back(dirs);
    packVerts.push_back(packVert);
  }
}

CanonicalCube QuaxolChunk::s_canonicalCubesByFlag[RenderBlock::NumDirCombinations];
void QuaxolChunk::BuildCanonicalCubesByFlag(float blockSize) {
  VecList tessVerts;
  QVertList packVerts;
  CanonicalCube::VertDirs vertDirs;
  assert(sizeof(QuaxolVert) == 4);
  CanonicalCube::populateVerts(blockSize, packVerts, tessVerts, vertDirs);

  IndexList indices;
  indices.reserve(8 * 6 * 3 * 2);

  typedef std::map<int, int> OldToNewHash;
  OldToNewHash oldToNew;

  for(int flag = 0; flag < RenderBlock::NumDirCombinations; ++flag) {
    indices.resize(0);
    CanonicalCube::addFlaggedTesseract(indices, vertDirs, flag);

    CanonicalCube& cube = s_canonicalCubesByFlag[flag];
    cube.m_connectFlags = flag;

    // not all the verts will be used possibly
    oldToNew.clear();
    // note: this is the index into the array of indices
    int endIndex = (int)indices.size();
    for(int index = 0; index < endIndex; ++index) {
      int oldIndex = indices[index];
      int newIndex;
      auto oldToNewIt = oldToNew.find(oldIndex);
      if(oldToNewIt == oldToNew.end()) {
        newIndex = (int)cube.m_verts.size();
        cube.m_verts.emplace_back(tessVerts[oldIndex]);
        cube.m_packVerts.emplace_back(packVerts[oldIndex]);
        oldToNew.insert(std::make_pair(oldIndex, newIndex));
      } else {
        newIndex = oldToNewIt->second;
      }

      cube.m_indices.emplace_back(newIndex);
    }
  }
}

CanonicalCube QuaxolChunk::s_canonicalCubesByDir[RenderBlock::NumDirs];
void QuaxolChunk::BuildCanonicalCubesByDir(float blockSize) {
  Mesh tesseract;
  // essentially relying on implicit ordering assumption here
  tesseract.buildQuaxolTesseract(blockSize);

  //for(int d = 0; d < RenderBlock::NumDirCombinations; ++d) {
  for(int d = 0; d < RenderBlock::NumDirs; ++d) {
    CanonicalCube& cube = s_canonicalCubesByDir[d];
    cube.m_dirIndex = (RenderBlock::DirIndex)d;
    cube.m_dir = (RenderBlock::Dir)(1 << d);
    cube.m_indices.resize(0);
    cube.m_verts.resize(0);
    const int indicesPerCube = 6 * 2 * 3;
    const int vertsPerCube = 8;
    cube.m_indices.reserve(indicesPerCube); // tri list, bleh
    cube.m_verts.reserve(vertsPerCube);

    int startIndex = d * indicesPerCube;
    int endIndex = (d+1) * indicesPerCube;
    assert(endIndex <= (int)tesseract._indices.size());

    typedef std::map<int, int> OldToNewHash;
    OldToNewHash oldToNew;
    // note: this is the index into the array of indices
    for(int index = startIndex; index < endIndex; ++index) {
      int oldIndex = tesseract._indices[index];
      int newIndex;
      auto oldToNewIt = oldToNew.find(oldIndex);
      if(oldToNewIt == oldToNew.end()) {
        newIndex = (int)cube.m_verts.size();
        cube.m_verts.emplace_back(tesseract._verts[oldIndex]);
        oldToNew.insert(std::make_pair(oldIndex, newIndex));
      } else {
        newIndex = oldToNewIt->second;
      }

      cube.m_indices.emplace_back(newIndex);
    }

    assert((int)cube.m_verts.size() == vertsPerCube);
    assert((int)cube.m_indices.size() == indicesPerCube);
  }
}

void QuaxolChunk::AddRenderCubeByFlag(
    const Vec4f& vertOffset, const QuaxolVert& packOffset, unsigned char connectFlags) {
  CanonicalCube& cube = s_canonicalCubesByFlag[connectFlags];
  assert(cube.m_connectFlags == connectFlags); // call BuildCanonicalCubesByFlag

  int indexOffset = (int)m_verts.size();
  for(auto vert : cube.m_verts) {
    m_verts.emplace_back(vert + vertOffset);
  }
  for(auto vert : cube.m_packVerts) {
    QuaxolVert movedVert = packOffset;
    //as long there isn't overflow this should be fine
    movedVert._position += vert._position;
    m_packVerts.emplace_back(movedVert);
  }
  for(auto index : cube.m_indices) {
    m_indices.emplace_back(index + indexOffset);
  }
}

void QuaxolChunk::AddRenderCubeByDir(
    const Vec4f& vertOffset, RenderBlock::DirIndex dirIndex) {
  CanonicalCube& cube = s_canonicalCubesByDir[dirIndex];
  assert(cube.m_dirIndex == dirIndex); // call BuildCanonicalCubesByDir

  int indexOffset = (int)m_verts.size();
  for(auto vert : cube.m_verts) {
    m_verts.emplace_back(vert + vertOffset);
  }
  for(auto index : cube.m_indices) {
    m_indices.emplace_back(index + indexOffset);
  }
}

void QuaxolChunk::UpdateTrisFromConnects() {

  int expectedVerts = m_cubeCount * 8;
  int expectedTris = m_cubeCount * 12; // probably should do quads?
  m_verts.resize(0);
  m_verts.reserve(expectedVerts);
  m_packVerts.resize(0);
  m_packVerts.reserve(expectedVerts);
  m_indices.resize(0);
  m_indices.reserve(expectedTris * 3);

  Vec4f zeroOffset(0,0,0,0);

  QuaxolVert offsetPackVert;

  for (int x = 0; x < c_mxSz; ++x) {
    offsetPackVert._pos_x = x;
    for (int y = 0; y < c_mxSz; ++y) {
      offsetPackVert._pos_y = y;
      for (int z = 0; z < c_mxSz; ++z) {
        offsetPackVert._pos_z = z;
        for (int w = 0; w < c_mxSz; ++w) {
          offsetPackVert._pos_w = w;

          const Block& block = m_blocks[x][y][z][w];
          const RenderBlock& rBlock = m_connects[x][y][z][w];
          QuaxolSpec blockSpec(x, y, z, w);

          offsetPackVert._uvInd = block.type;
          Vec4f blockCoords = blockSpec.ToFloatCoords(zeroOffset, m_blockSize);
          AddRenderCubeByFlag(blockCoords, offsetPackVert, rBlock.connectFlags);

          //for(int c = 0; c < RenderBlock::NumDirs; ++c) {
          //  if(rBlock.connectFlags & (1 << c)) {
          //    AddRenderCubeByDir(blockCoords, (RenderBlock::DirIndex)c);
          //  }
          //} // dir

        } // w
      } // z
    } // y
  } // x
}

void QuaxolChunk::DebugSwapAxis(int sourceInd, int destInd) {
  Block copyBlocks[c_mxSz][c_mxSz][c_mxSz][c_mxSz];
  memcpy(&copyBlocks, m_blocks, sizeof(m_blocks));

  for (int x = 0; x < c_mxSz; ++x) {
    for (int y = 0; y < c_mxSz; ++y) {
      for (int z = 0; z < c_mxSz; ++z) {
        for (int w = 0; w < c_mxSz; ++w) {
          QuaxolSpec orig(x, y, z, w);
          QuaxolSpec swapped(orig);
          swapped[sourceInd] = orig[destInd];
          swapped[destInd] = orig[sourceInd];

          m_blocks[swapped.x][swapped.y][swapped.z][swapped.w] =
              copyBlocks[orig.x][orig.y][orig.z][orig.w];
        } // w
      } // z
    } // y
  } // x

  UpdateRendering();
}

}; // namespace fd


text:
@charset "UTF-8";
/* display css: ht-height wt-width*/
.wtl{float:left;border-radius:10px;}
.wtc{margin:0 auto;border-radius:10px;}
.wtr{float:right;border-radius:10px;}
.wt{width:100%;border-radius:10px;text-align:center;}
.ht{height:100%;border-radius:10px;text-align:center;}
.wt2{width:2%;}.wt4{width:4%;}.wt8{width:8%;}.wt12{width:12%;}
.ht2{height:2%;}.ht4{height:4%;}.ht8{height:8%;}.ht12{height:12%;}
.wt5{width:5%;}.wt10{width:10%;}.wt20{width:20%;}.wt30{width:30%;}.wt40{width:40%;}
.wt50{width:50%;}.wt60{width:60%;}.wt70{width:70%;}.wt80{width:80%;}.wt90{width:90%;}
.wt16{width:16%;}.wt25{width:25%;}.wt32{width:32%;}.wt48{width:48%;}.wt96{width:96%;}
.ht5{height:5%;}.ht10{height:10%;}.ht20{height:20%;}.ht30{height:30%;}.ht40{height:40%;}
.ht50{height:50%;}.ht60{height:60%;}.ht70{height:70%;}.ht80{height:80%;}.ht90{height:90%;}
.ht16{height:16%;}.ht25{height:25%;}.ht32{height:32%;}.ht48{height:48%;}.ht96{height:96%;}
.bg1{background:url(bg1.png);}.bg2{background:url(bg2.png);}.bg3{background:url(bg3.png);}
.bg4{background:url(bg4.png);}.bg5{background:url(bg5.png);}.bg6{background:url(bg6.png);}
.mgl5{margin-left:5%;}.mgl8{margin-left:8%;}.mgl12{margin-left:12%;}
.mgr5{margin-right:5%;}.mgr8{margin-right:8%;}.mgr12{margin-right:12%;}
.flexc{ display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-pack:center;
		display:-moz-box;-moz-box-orient:vertical;-webkit-box-pack:center;
		display:-ms-flexbox;-ms-flex-direction:column;-ms-flex-pack:center;
		display:-webkit-flex;-webkit-flex-direction:column;display:flex;flex-direction:column;
		-webkit-justify-content:center;justify-content:center;}
.flexr{ display:-webkit-box;-webkit-box-orient:horizontal;-webkit-box-pack:center;
		display:-moz-box;-moz-box-orient:horizontal;-webkit-box-pack:center;
		display:-ms-flexbox;-ms-flex-direction:row;-ms-flex-pack:center;
		display:-webkit-flex;-webkit-flex-direction:row;display:flex;flex-direction:row;
		-webkit-justify-content:center;justify-content:center;}
/*show content*/
.page h3{font-size:1.5em;height:1.5em;line-height:1.5em;font-weight:bolder;color:rgb(34, 88, 1);text-align:center;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;}
.page p{font-size:14px;line-height:24px;height:24px;overflow:hidden;color:white;text-align:center;}
.page ul{text-align:center;color:red;}
.page ul li{font-size:14px;line-height:28px;height:28px;text-align:left;color:rgb(34, 88, 1);list-style:disc inside;overflow:hidden;}
.man{background-position:center;background-size:contain;background-repeat:no-repeat;}
.m1{background-image:url(../pic/m1.png);}.m2{background-image:url(../pic/m2.png);}
.w1{background-image:url(../pic/w1.png);}.w2{background-image:url(../pic/w2.png);}
/* last page */
#lastpage h3{height:40px;line-height:40px;width:80%;margin:0 auto;border-bottom:2px solid rgb(34, 88, 1);}
#lastpage p{font-size:14px;line-height:22px;color:rgb(34, 88, 1);}
#lastpage .pic{width:200px;height:200px;margin:1.2em auto;background:url(NetXXBJ.jpg) no-repeat center;background-size:contain;border-radius:20px;border-color:rgb(34, 88, 1);}
/* 自定义动画START .active #tag/.active .class,必须加.active确保每次播放 */
.active .page .flexc,.active .page .flexr{-webkit-animation:zoomIn 1s ease 0s 1 both;animation:zoomIn 1s ease 0s 1 both;}
.active #page5 .man{-webkit-animation:bounce 1s 1s,flash 1s 3s,pulse 1s 5s,rubberBand 1s 7s,shake 1s 9s,swing 1s 11s,tada 1s 13s,wobble 1s 15s;
							animation:bounce 1s 1s,flash 1s 3s,pulse 1s 5s,rubberBand 1s 7s,shake 1s 9s,swing 1s 11s,tada 1s 13s,wobble 1s 15s;}
.active #page6 .man{-webkit-animation:flip 1s 1s,flipInX 1s 3s,flipInY 1s 5s,hinge 1s 7s,rollIn 1s 9s,rollOut 1s 11s,lightSpeedIn 1s 13s,lightSpeedOut 1s 15s;
							animation:flip 1s 1s,flipInX 1s 3s,flipInY 1s 5s,hinge 1s 7s,rollIn 1s 9s,rollOut 1s 11s,lightSpeedIn 1s 13s,lightSpeedOut 1s 15s;}
.active #page7 .man{-webkit-animation:zoomIn 1s 1s,zoomInDown 1s 3s,zoomInLeft 1s 5s,zoomInRight 1s 7s,zoomInUp 1s 9s;
							animation:zoomIn 1s 1s,zoomInDown 1s 3s,zoomInLeft 1s 5s,zoomInRight 1s 7s,zoomInUp 1s 9s;}
.active #page8 .man{-webkit-animation:fadeIn 1s 1s,fadeInDown 1s 3s,fadeInLeft 1s 5s,fadeInRight 1s 7s,fadeInUp 1s 9s;
							animation:fadeIn 1s 1s,fadeInDown 1s 3s,fadeInLeft 1s 5s,fadeInRight 1s 7s,fadeInUp 1s 9s;}
.active #page9 .man{-webkit-animation:bounceIn 1s 1s,bounceInDown 1s 3s,bounceInLeft 1s 5s,bounceInRight 1s 7s,bounceInUp 1s 9s;
							animation:bounceIn 1s 1s,bounceInDown 1s 3s,bounceInLeft 1s 5s,bounceInRight 1s 7s,bounceInUp 1s 9s;}
.active #page10 .man{-webkit-animation:rotateIn 1s 1s,rotateInDownLeft 1s 3s,rotateInDownRight 1s 5s,rotateInUpLeft 1s 7s,rotateInUpRight 1s 9s;
							animation:rotateIn 1s 1s,rotateInDownLeft 1s 3s,rotateInDownRight 1s 5s,rotateInUpLeft 1s 7s,rotateInUpRight 1s 9s;}
/* 自定义动画END .active #tag/.active .class,必须加.active确保每次播放 */


text:
//@import "base.css";
//@import "jquery.ui.theme.css";


text:
function loadContext() {
	var context = {
		tabId: self.options.tabId,
		isSharePoint: typeof(unsafeWindow._spPageContextInfo) != 'undefined'
	};

	if (context.isSharePoint) {
		context.spPageContextInfo = unsafeWindow._spPageContextInfo;

		if (typeof(unsafeWindow.ctx) != 'undefined') {
			context.ctx = unsafeWindow.ctx;
		}
	}

	self.port.emit('context-ready', context);
}

self.port.on('load-context', loadContext);


text:
> The repository for *high quality* TypeScript type definitions.

Also see the [definitelytyped.org](http://definitelytyped.org) website, although information in this README is more up-to-date.

*You can also read this README in [Spanish](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md), [Korean](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md), and [Russian](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ru.md)!*

## Current status

This section tracks the health of the repository and publishing process.
It may be helpful for contributors experiencing any issues with their PRs and packages.

* All packages are [type-checking/linting](https://github.com/Microsoft/dtslint) cleanly: [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
* All packages are being [published to npm](https://github.com/Microsoft/types-publisher) in under an hour: [![Publish Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13)
* [typescript-bot](https://github.com/typescript-bot) has been active on DefinitelyTyped [![Activity Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.typescript-bot-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14)

If anything here seems wrong, or any of the above are failing, please raise an issue in [the DefinitelyTyped Gitter channel](https://gitter.im/DefinitelyTyped/DefinitelyTyped).

[![Join the chat at https://gitter.im/DefinitelyTyped/DefinitelyTyped](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/DefinitelyTyped/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

## What are declaration files?

See the [TypeScript handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html).

## How do I get them?

### npm

This is the preferred method. This is only available for TypeScript 2.0+ users. For example:

```sh
npm install --save-dev @types/node
```

The types should then be automatically included by the compiler.
See more in the [handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html).

For an NPM package "foo", typings for it will be at "@types/foo".
If you can't find your package, look for it on [TypeSearch](https://microsoft.github.io/TypeSearch/).

If you still can't find it, check if it [bundles](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) its own typings.
This is usually provided in a `"types"` or `"typings"` field in the `package.json`,
or just look for any ".d.ts" files in the package and manually include them with a `/// <reference path="" />`.

### Other methods

These can be used by TypeScript 1.0.

* [Typings](https://github.com/typings/typings)
* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (use preferred alternatives, nuget DT type publishing has been turned off)
* Manually download from the `master` branch of this repository

You may need to add manual [references](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html).

## How can I contribute?

Definitely Typed only works because of contributions by users like you!

### Test

Before you share your improvement with the world, use it yourself.

#### Test editing an existing package

To add new features you can use [module augmentation](http://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation).
You can also directly edit the types in `node_modules/@types/foo/index.d.ts`, or copy them from there and follow the steps below.

#### Test a new package

Add to your `tsconfig.json`:

```json
"baseUrl": "types",
"typeRoots": ["types"],
```

(You can also use `src/types`.)
Create `types/foo/index.d.ts` containing declarations for the module "foo".
You should now be able import from `"foo"` in your code and it will route to the new type definition.
Then build *and* run the code to make sure your type definition actually corresponds to what happens at runtime.
Once you've tested your definitions with real code, make a [PR](#make-a-pull-request)
then follow the instructions to [edit an existing package](#edit-an-existing-package) or
[create a new package](#create-a-new-package).

### Make a pull request

Once you've tested your package, you can share it on Definitely Typed.

First, [fork](https://guides.github.com/activities/forking/) this repository, install [node](https://nodejs.org/), and run `npm install`.

#### Edit an existing package

* `cd types/my-package-to-edit`
* Make changes. Remember to edit tests.
  If you make breaking changes, do not forget to [update a major version](#if-a-library-is-updated-to-a-new-major-version-with-breaking-changes-how-should-i-update-its-type-declaration-package).
* You may also want to add yourself to "Definitions by" section of the package header.
  - This will cause you to be notified (via your GitHub username) whenever someone makes a pull request or issue about the package.
  - Do this by adding your name to the end of the line, as in `// Definitions by: Alice <https://github.com/alice>, Bob <https://github.com/bob>`.
  - Or if there are more people, it can be multiline
  ```typescript
  // Definitions by: Alice <https://github.com/alice>
  //                 Bob <https://github.com/bob>
  //                 Steve <https://github.com/steve>
  //                 John <https://github.com/john>
  ```
* If there is a `tslint.json`, run `npm run lint package-name`. Otherwise, run `tsc` in the package directory.

When you make a PR to edit an existing package, `dt-bot` should @-mention previous authors.
If it doesn't, you can do so yourself in the comment associated with the PR.

#### Create a new package

If you are the library author and your package is written in TypeScript, [bundle the autogenerated declaration files](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) in your package instead of publishing to Definitely Typed.

If you are adding typings for an NPM package, create a directory with the same name.
If the package you are adding typings for is not on NPM, make sure the name you choose for it does not conflict with the name of a package on NPM.
(You can use `npm info foo` to check for the existence of the `foo` package.)

Your package should have this structure:

| File | Purpose |
| --- | --- |
| index.d.ts | This contains the typings for the package. |
| foo-tests.ts | This contains sample code which tests the typings. This code does *not* run, but it is type-checked. |
| tsconfig.json | This allows you to run `tsc` within the package. |
| tslint.json | Enables linting. |

Generate these by running `npx dts-gen --dt --name my-package-name --template module` if you have npm ≥ 5.2.0, `npm install -g dts-gen` and `dts-gen --dt --name my-package-name --template module` otherwise.
See all options at [dts-gen](https://github.com/Microsoft/dts-gen).

You may edit the `tsconfig.json` to add new files, to add `"target": "es6"` (needed for async functions), to add to `"lib"`, or to add the `"jsx"` compiler option.

Definitely Typed members routinely monitor for new PRs, though keep in mind that the number of other PRs may slow things down.

For a good example package, see [base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js).

#### Common mistakes

* First, follow advice from the [handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html).
* Formatting: Either use all tabs, or always use 4 spaces.
* `function sum(nums: number[]): number`: Use `ReadonlyArray` if a function does not write to its parameters.
* `interface Foo { new(): Foo; }`:
    This defines a type of objects that are new-able. You probably want `declare class Foo { constructor(); }`.
* `const Class: { new(): IClass; }`:
    Prefer to use a class declaration `class Class { constructor(); }` instead of a new-able constant.
* `getMeAT<T>(): T`:
    If a type parameter does not appear in the types of any parameters, you don't really have a generic function, you just have a disguised type assertion.
    Prefer to use a real type assertion, e.g. `getMeAT() as number`.
    Example where a type parameter is acceptable: `function id<T>(value: T): T;`.
    Example where it is not acceptable: `function parseJson<T>(json: string): T;`.
    Exception: `new Map<string, number>()` is OK.
* Using the types `Function` and `Object` is almost never a good idea. In 99% of cases it's possible to specify a more specific type. Examples are `(x: number) => number` for [functions](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) and `{ x: number, y: number }` for objects. If there is no certainty at all about the type, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) is the right choice, not `Object`. If the only known fact about the type is that it's some object, use the type [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), not `Object` or `{ [key: string]: any }`.
* `var foo: string | any`:
    When `any` is used in a union type, the resulting type is still `any`. So while the `string` portion of this type annotation may _look_ useful, it in fact offers no additional typechecking over simply using `any`.
    Depending on the intention, acceptable alternatives could be `any`, `string`, or `string | object`.

#### Removing a package

When a package [bundles](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) its own types, types should be removed from Definitely Typed to avoid confusion.

You can remove it by running `npm run not-needed -- typingsPackageName asOfVersion sourceRepoURL [libraryName]`.
- `typingsPackageName`: This is the name of the directory to delete.
- `asOfVersion`: A stub will be published to `@types/foo` with this version. Should be higher than any currently published version, and should be a version of `foo` on npm.
- `sourceRepoURL`: This should point to the repository that contains the typings.
- `libraryName`: Name of npm package that replaces the Definitely Typed types. Usually this is identical to "typingsPackageName", in which case you can omit it.

Any other packages in Definitely Typed that referenced the deleted package should be updated to reference the bundled types.
You can get this list by looking at the errors from `npm run test`.
To fix the errors, add a `package.json` with `"dependencies": { "foo": "x.y.z" }`.
For example:

```json
{
  "private": true,
  "dependencies": {
    "foo": "^2.6.0"
  }
}
```

When you add a `package.json` to dependents of `foo`, you will also need to open a PR to add `foo` [to dependenciesWhitelist.txt in types-publisher](https://github.com/Microsoft/types-publisher/blob/master/dependenciesWhitelist.txt).

If a package was never on Definitely Typed, it does not need to be added to `notNeededPackages.json`.

#### Lint

All new packages must be linted. To lint a package, add a `tslint.json` to that package containing
```js
{
    "extends": "dtslint/dt.json"
}
```

This should be the only content in a finished project's `tslint.json` file. If a `tslint.json` turns rules off, this is because that hasn't been fixed yet. For example:

```js
{
    "extends": "dtslint/dt.json",
    "rules": {
        // This package uses the Function type, and it will take effort to fix.
        "ban-types": false
    }
}
```

(To indicate that a lint rule truly does not apply, use `// tslint:disable rule-name` or better, `//tslint:disable-next-line rule-name`.)

To assert that an expression is of a given type, use `$ExpectType`. To assert that an expression causes a compile error, use `$ExpectError`.

```js
// $ExpectType void
f(1);

// $ExpectError
f("one");
```

For more details, see [dtslint](https://github.com/Microsoft/dtslint#write-tests) readme.

Test by running `npm run lint package-name` where `package-name` is the name of your package.
This script uses [dtslint](https://github.com/Microsoft/dtslint).

## FAQ

#### What exactly is the relationship between this repository and the `@types` packages on NPM?

The `master` branch is automatically published to the `@types` scope on NPM thanks to [types-publisher](https://github.com/Microsoft/types-publisher).

#### I've submitted a pull request. How long until it is merged?

It depends, but most pull requests will be merged within a week. PRs that have been approved by an author listed in the definition's header are usually merged more quickly; PRs for new definitions will take more time as they require more review from maintainers. Each PR is reviewed by a TypeScript or Definitely Typed team member before being merged, so please be patient as human factors may cause delays. Check the [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) to see progress as maintainers work through the open PRs.

#### My PR is merged; when will the `@types` NPM package be updated?

NPM packages should update within a few minutes. If it's been more than an hour, mention the PR number on [the Definitely Typed Gitter channel](https://gitter.im/DefinitelyTyped/DefinitelyTyped) and the current maintainer will get the correct team member to investigate.

#### I'm writing a definition that depends on another definition. Should I use `<reference types="" />` or an import?

If the module you're referencing is an external module (uses `export`), use an import.
If the module you're referencing is an ambient module (uses `declare module`, or just declares globals), use `<reference types="" />`.

#### I notice some packages having a `package.json` here.

Usually you won't need this. When publishing a package we will normally automatically create a `package.json` for it.
A `package.json` may be included for the sake of specifying dependencies. Here's an [example](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pikaday/package.json).
We do not allow other fields, such as `"description"`, to be defined manually.
Also, if you need to reference an older version of typings, you must do that by adding `"dependencies": { "@types/foo": "x.y.z" }` to the package.json.

#### Some packages have no `tslint.json`, and some `tsconfig.json` are missing `"noImplicitAny": true`, `"noImplicitThis": true`, or `"strictNullChecks": true`.

Then they are wrong. You can help by submitting a pull request to fix them.

#### Can I request a definition?

Here are the [currently requested definitions](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest).

#### What about type definitions for the DOM?

If types are part of a web standard, they should be contributed to [TSJS-lib-generator](https://github.com/Microsoft/TSJS-lib-generator) so that they can become part of the default `lib.dom.d.ts`.

#### Should I add an empty namespace to a package that doesn't export a module to use ES6 style imports?

Some packages, like [chai-http](https://github.com/chaijs/chai-http), export a function.

Importing this module with an ES6 style import in the form `import * as foo from "foo";` leads to the error:

> error TS2497: Module 'foo' resolves to a non-module entity and cannot be imported using this construct

This error can be suppressed by merging the function declaration with an empty namespace of the same name, but this practice is discouraged.
This is a commonly cited [Stack Overflow answer](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this) regarding this matter.

It is more appropriate to import the module using the `import foo = require("foo");` syntax.
Nevertheless, if you want to use a default import like `import foo from "foo";` you have two options:
- you can use the [`--allowSyntheticDefaultImports` compiler option](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-8.html#support-for-default-import-interop-with-systemjs) if your module runtime supports an interop scheme for non-ECMAScript modules, i.e. if default imports work in your environment (e.g. Webpack, SystemJS, esm).
- you can use the [`--esModuleInterop` compiler option](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#support-for-import-d-from-cjs-form-commonjs-modules-with---esmoduleinterop) if you want TypeScript to take care of non-ECMAScript interop (since Typescript 2.7).

#### A package uses `export =`, but I prefer to use default imports. Can I change `export =` to `export default`?

Like in the previous question, refer to using either the [`--allowSyntheticDefaultImports`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-8.html#support-for-default-import-interop-with-systemjs)
or [`--esModuleInterop`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#support-for-import-d-from-cjs-form-commonjs-modules-with---esmoduleinterop)
compiler options.

Do not change the type definition if it is accurate.
For an NPM package, `export =` is accurate if `node -p 'require("foo")'` works to import a module, and `export default` is accurate if `node -p 'require("foo").default'` works to import a module.

#### I want to use features from TypeScript 2.1 or above.

Then you will have to add a comment to the last line of your definition header (after `// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped`): `// TypeScript Version: 2.1`.

#### I want to use features from TypeScript 3.1 or above.

You can use the same `// TypeScript Version: 3.1` comment as above.
However, if your project needs to maintain types that are compatible with 3.1 and above *at the same time as* types that are compatible with 3.0 or below, you will need to use the `typesVersions` feature, which is available in TypeScript 3.1 and above.
You can find a detailed explanation of this feature in the [official TypeScript documentation](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-1.html#version-selection-with-typesversions).

Here's a short explanation to get you started:

1. You'll have to add a `package.json` file to your package definition, with the following contents:

```json
{
    "private": true,
    "types": "index",
    "typesVersions": {
        ">=3.1.0-0": { "*": ["ts3.1/*"] }
    }
}
```

2. Create the sub-directory mentioned in the `typesVersions` field inside your types directory (`ts3.1/` in this example)
and add the types and tests specific for the new TypeScript version. You don't need the typical definition header
in any of the files from the `ts3.1/` directory.

3. Set the `baseUrl` and `typeRoots` options in `ts3.1/tsconfig.json` to the correct paths, they should look something like this:
```json
{
    "compilerOptions": {
        "baseUrl": "../../",
        "typeRoots": ["../../"]
    }
}
```

You can look [here](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/debounce-promise) and [here](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/create-html-element) for examples.

#### I want to add a DOM API not present in TypeScript by default.

This may belong in [TSJS-Lib-Generator](https://github.com/Microsoft/TSJS-lib-generator#readme). See the guidelines there.
If the standard is still a draft, it belongs here.
Use a name beginning with `dom-` and include a link to the standard as the "Project" link in the header.
When it graduates draft mode, we may remove it from Definitely Typed and deprecate the associated `@types` package.

#### How do Definitely Typed package versions relate to versions of the corresponding library?

_NOTE: The discussion in this section assumes familiarity with [Semantic versioning](https://semver.org/)_

Each Definitely Typed package is versioned when published to NPM.
The [types-publisher](https://github.com/Microsoft/types-publisher) (the tool that publishes `@types` packages to npm) will set the declaration package's version by using the `major.minor` version number listed in the first line of its `index.d.ts` file.
For example, here are the first few lines of [Node's type declarations](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/1253faabf5e0d2c5470db6ea87795d7f96fef7e2/types/node/index.d.ts) for version `10.12.x` at the time of writing:

```js
// Type definitions for Node.js 10.12
// Project: http://nodejs.org/
// Definitions by: Microsoft TypeScript <https://github.com/Microsoft>
//                 Definitely Typed <https://github.com/DefinitelyTyped>
//                 Alberto Schiabel <https://github.com/jkomyno>
```

Because `10.12` is at the end the first line, the npm version of the `@types/node` package will also be `10.12.x`.
Note that the first-line comment in the `index.d.ts` file should only contain the `major.minor` version (e.g. `10.12`) and should not contain a patch version (e.g. `10.12.4`).
This is because only the major and minor release numbers are aligned between library packages and type declaration packages.
The patch release number of the type declaration package (e.g. `.0` in `10.12.0`) is initialized to zero by Definitely Typed and is incremented each time a new `@types/node` package is published to NPM for the same major/minor version of the corresponding library.

Sometimes type declaration package versions and library package versions can get out of sync.
Below are a few common reasons why, in order of how much they inconvenience users of a library.
Only the last case is typically problematic.

* As noted above, the patch version of the type declaration package is unrelated to the library patch version.
  This allows Definitely Typed to safely update type declarations for the same major/minor version of a library.
* If updating a package for new functionality, don't forget to update the version number to line up with that version of the library.
  If users make sure versions correspond between JavaScript packages and their respective `@types` packages, then `npm update` should typically just work.
* It's common for type declaration package updates to lag behind library updates because it's often library users, not maintainers, who update Definitely Typed when new library features are released.
  So there may be a lag of days, weeks, or even months before a helpful community member sends a PR to update the type declaration package for a new library release.
  If you're impacted by this, you can be the change you want to see in the world and you can be that helpful community member!

:exclamation: If you're updating type declarations for a library, always set the `major.minor` version in the first line of `index.d.ts` to match the library version that you're documenting! :exclamation:

#### If a library is updated to a new major version with breaking changes, how should I update its type declaration package?

[Semantic versioning](https://semver.org/) requires that versions with breaking changes must increment the major version number.
For example, a library that removes a publicly exported function after its `3.5.8` release must bump its version to `4.0.0` in its next release.
Furthermore, when the library's `4.0.0` release is out, its Definitely Typed type declaration package should also be updated to `4.0.0`, including any breaking changes to the library's API.

Many libraries have a large installed base of developers (including maintainers of other packages using that library as a dependency) who won't move right away to a new version that has breaking changes, because it might be months until a maintainer has time to rewrite code to adapt to the new version.
In the meantime, users of old library versions still may want to update type declarations for older versions.

If you intend to continue updating the older version of a library's type declarations, you may create a new subfolder (e.g. `/v2/`) named for the current (soon to be "old") version, and copy existing files from the current version to it.

Because the root folder should always contain the type declarations for the latest ("new") version, you'll need to make a few changes to the files in your old-version subdirectory to ensure that relative path references point to the subdirectory, not the root.

1. Update the relative paths in `tsconfig.json` as well as `tslint.json`.
2. Add path mapping rules to ensure that tests are running against the intended version.

For example, the [`history`](https://github.com/ReactTraining/history/) library introduced breaking changes between version `2.x` and `3.x`.
Because many users still consumed the older `2.x` version, a maintainer who wanted to update the type declarations for this library to `3.x` added a `v2` folder inside the history repository that contains type declarations for the older version.
At the time of writing, the [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/1253faabf5e0d2c5470db6ea87795d7f96fef7e2/types/history/v2/tsconfig.json) looks roughly like:

```json
{
    "compilerOptions": {
        "baseUrl": "../../",
        "typeRoots": ["../../"],
        "paths": {
            "history": [ "history/v2" ]
        },
    },
    "files": [
        "index.d.ts",
        "history-tests.ts"
    ]
}
```

If there are other packages in Definitely Typed that are incompatible with the new version, you will need to add path mappings to the old version.
You will also need to do this recursively for packages depending on packages depending on the old version.

For example, `react-router` depends on `history@2`, so [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/v2/tsconfig.json) has a path mapping to `"history": [ "history/v2" ]`.
Transitively, `react-router-bootstrap` (which depends on `react-router`) also needed to add the same path mapping (`"history": [ "history/v2" ]`) in its `tsconfig.json` until its `react-router` dependency was updated to the latest version.

Also, `/// <reference types=".." />` will not work with path mapping, so dependencies must use `import`.

#### How do I write definitions for packages that can be used globally and as a module?

The TypeScript handbook contains excellent [general information about writing definitions](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), and also [this example definition file](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) which shows how to create a definition using ES6-style module syntax, while also specifying objects made available to the global scope.  This technique is demonstrated practically in the [definition for big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), which is a library that can be loaded globally via script tag on a web page, or imported via require or ES6-style imports.

To test how your definition can be used both when referenced globally or as an imported module, create a `test` folder, and place two test files in there.  Name one `YourLibraryName-global.test.ts` and the other `YourLibraryName-module.test.ts`.  The *global* test file should exercise the definition according to how it would be used in a script loaded on a web page where the library is available on the global scope - in this scenario you should not specify an import statement.  The *module* test file should exercise the definition according to how it would be used when imported (including the `import` statement(s)).  If you specify a `files` property in your `tsconfig.json` file, be sure to include both test files.  A [practical example of this](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) is also available on the big.js definition.

Please note that it is not required to fully exercise the definition in each test file - it is sufficient to test only the globally-accessible elements on the global test file and fully exercise the definition in the module test file, or vice versa.

#### What about scoped packages?

Types for a scoped package `@foo/bar` should go in `types/foo__bar`. Note the double underscore.

When `dts-gen` is used to scaffold a scoped package, the `paths` property has to be manually adapted in the generated
`tsconfig.json` to correctly reference the scoped package:

```json
{
    "paths":{
      "@foo/bar": ["foo__bar"]
    }
}
```

#### The file history in GitHub looks incomplete.

GitHub doesn't [support](http://stackoverflow.com/questions/5646174/how-to-make-github-follow-directory-history-after-renames) file history for renamed files. Use [`git log --follow`](https://www.git-scm.com/docs/git-log) instead.

## License

This project is licensed under the MIT license.

Copyrights on the definition files are respective of each contributor listed at the beginning of each definition file.


text:
package com.thoughtworks.go.util;

import ch.qos.logback.classic.Level;
import com.googlecode.junit.ext.JunitExtRunner;
import com.googlecode.junit.ext.RunIf;
import com.rits.cloning.Cloner;
import com.thoughtworks.go.junitext.DatabaseChecker;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.io.File;
import java.util.Properties;

import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;

@RunWith(JunitExtRunner.class)
public class SystemEnvironmentTest {
    static final Cloner CLONER = new Cloner();
    private Properties original;
    private SystemEnvironment systemEnvironment;

    @Before
    public void before() {
        original = CLONER.deepClone(System.getProperties());
        systemEnvironment = new SystemEnvironment();
    }

    @After
    public void after() {
        System.setProperties(original);
        new SystemEnvironment().reset(SystemEnvironment.ENABLE_CONFIG_MERGE_FEATURE);
    }

    @Test
    public void shouldDisableNewFeaturesByDefault() {
        assertThat(systemEnvironment.isFeatureEnabled("cruise.experimental.feature.some-feature"), is(false));
    }

    @Test
    public void shouldBeAbletoEnableAllNewFeatures() {
        Properties properties = new Properties();
        properties.setProperty(SystemEnvironment.CRUISE_EXPERIMENTAL_ENABLE_ALL, "true");
        SystemEnvironment systemEnvironment = new SystemEnvironment(properties);
        assertThat(systemEnvironment.isFeatureEnabled("cruise.experimental.feature.some-feature"), is(true));
    }

    @Test
    public void shouldFindJettyConfigInTheConfigDir() {
        assertThat(systemEnvironment.getJettyConfigFile(), is(new File(systemEnvironment.getConfigDir(), "jetty.xml")));
        systemEnvironment.set(SystemEnvironment.JETTY_XML_FILE_NAME, "jetty-old.xml");
        assertThat(systemEnvironment.getJettyConfigFile(), is(new File(systemEnvironment.getConfigDir(), "jetty-old.xml")));
    }

    @Test
    public void shouldUnderstandOperatingSystem() {
        assertThat(systemEnvironment.getOperatingSystemName(), is(System.getProperty("os.name")));
    }

    @Test
    public void shouldUnderstandWetherToUseCompressedJs() throws Exception {
        assertThat(systemEnvironment.useCompressedJs(), is(true));
        systemEnvironment.setProperty(GoConstants.USE_COMPRESSED_JAVASCRIPT, Boolean.FALSE.toString());
        assertThat(systemEnvironment.useCompressedJs(), is(false));
        systemEnvironment.setProperty(GoConstants.USE_COMPRESSED_JAVASCRIPT, Boolean.TRUE.toString());
        assertThat(systemEnvironment.useCompressedJs(), is(true));
    }

    @Test
    public void shouldSetTrueAsDefaultForUseIframeSandbox() {
        assertThat(systemEnvironment.useIframeSandbox(), is(true));
    }

    @Test
    public void shouldCacheAgentConnectionSystemPropertyOnFirstAccess() {
        System.setProperty(SystemEnvironment.AGENT_CONNECTION_TIMEOUT_IN_SECONDS, "1");
        assertThat(systemEnvironment.getAgentConnectionTimeout(), is(1));
        System.setProperty(SystemEnvironment.AGENT_CONNECTION_TIMEOUT_IN_SECONDS, "2");
        assertThat(systemEnvironment.getAgentConnectionTimeout(), is(1));
    }

    @Test
    public void shouldCacheSslPortSystemPropertyOnFirstAccess() {
        System.setProperty(SystemEnvironment.CRUISE_SERVER_SSL_PORT, "8154");
        assertThat(systemEnvironment.getSslServerPort(), is(8154));
        System.setProperty(SystemEnvironment.CRUISE_SERVER_SSL_PORT, "20000");
        assertThat(systemEnvironment.getSslServerPort(), is(8154));
    }

    @Test
    public void shouldCacheConfigDirOnFirstAccess() {
        assertThat(systemEnvironment.getConfigDir(), is("config"));
        System.setProperty(SystemEnvironment.CONFIG_DIR_PROPERTY, "raghu");
        assertThat(systemEnvironment.getConfigDir(), is("config"));
    }

    @Test
    public void shouldCacheConfigFilePathOnFirstAccess() {
        assertThat(systemEnvironment.configDir(), is(new File("config")));
        System.setProperty(SystemEnvironment.CONFIG_FILE_PROPERTY, "foo");
        assertThat(systemEnvironment.getConfigDir(), is("config"));
    }

    @Test
    public void shouldCacheDatabaseDiskFullOnFirstAccess() {
        System.setProperty(SystemEnvironment.DATABASE_FULL_SIZE_LIMIT, "100");
        assertThat(systemEnvironment.getDatabaseDiskSpaceFullLimit(), is(100L));
        System.setProperty(SystemEnvironment.DATABASE_FULL_SIZE_LIMIT, "50M");
        assertThat(systemEnvironment.getDatabaseDiskSpaceFullLimit(), is(100L));
    }

    @Test
    public void shouldCacheArtifactDiskFullOnFirstAccess() {
        System.setProperty(SystemEnvironment.ARTIFACT_FULL_SIZE_LIMIT, "100");
        assertThat(systemEnvironment.getArtifactReposiotryFullLimit(), is(100L));
        System.setProperty(SystemEnvironment.ARTIFACT_FULL_SIZE_LIMIT, "50M");
        assertThat(systemEnvironment.getArtifactReposiotryFullLimit(), is(100L));
    }

    @Test
    public void shouldClearCachedValuesOnSettingNewProperty() {
        System.setProperty(SystemEnvironment.ARTIFACT_FULL_SIZE_LIMIT, "100");
        assertThat(systemEnvironment.getArtifactReposiotryFullLimit(), is(100L));
        systemEnvironment.setProperty(SystemEnvironment.ARTIFACT_FULL_SIZE_LIMIT, "50");
        assertThat(systemEnvironment.getArtifactReposiotryFullLimit(), is(50L));
    }

    @Test
    public void shouldPrefixApplicationPathWithContext() {
        assertThat(systemEnvironment.pathFor("foo/bar"), is("/go/foo/bar"));
        assertThat(systemEnvironment.pathFor("/baz/quux"), is("/go/baz/quux"));
    }

    @Test
    public void shouldUnderstandConfigRepoDir() {
        Properties properties = new Properties();
        SystemEnvironment systemEnvironment = new SystemEnvironment(properties);
        assertThat(systemEnvironment.getConfigRepoDir(), is(new File("db/config.git")));
        properties.setProperty(SystemEnvironment.CRUISE_CONFIG_REPO_DIR, "foo/bar.git");
        assertThat(systemEnvironment.getConfigRepoDir(), is(new File("foo/bar.git")));
    }

    @Test
    public void shouldUnderstandMaterialUpdateInterval() {
        assertThat(systemEnvironment.getMaterialUpdateIdleInterval(), is(60000L));
        systemEnvironment.setProperty(SystemEnvironment.MATERIAL_UPDATE_IDLE_INTERVAL_PROPERTY, "20");
        assertThat(systemEnvironment.getMaterialUpdateIdleInterval(), is(20L));
    }

    @Test
    public void shouldUnderstandH2CacheSize() {
        assertThat(systemEnvironment.getCruiseDbCacheSize(), is(String.valueOf(128 * 1024)));
        System.setProperty(SystemEnvironment.CRUISE_DB_CACHE_SIZE, String.valueOf(512 * 1024));
        assertThat(systemEnvironment.getCruiseDbCacheSize(), is(String.valueOf(512 * 1024)));
    }

    @Test
    public void shouldReturnTheJobWarningLimit() {
        assertThat(systemEnvironment.getUnresponsiveJobWarningThreshold(), is(5 * 60 * 1000L));
        System.setProperty(SystemEnvironment.UNRESPONSIVE_JOB_WARNING_THRESHOLD, "30");
        assertThat(systemEnvironment.getUnresponsiveJobWarningThreshold(), is(30 * 60 * 1000L));
    }

    @Test
    public void shouldReturnTheDefaultValueForActiveMqUseJMX() {
        assertThat(systemEnvironment.getActivemqUseJmx(), is(false));
        System.setProperty(SystemEnvironment.ACTIVEMQ_USE_JMX, "true");
        assertThat(systemEnvironment.getActivemqUseJmx(), is(true));
    }

    @Test
    public void shouldResolveRevisionsForDependencyGraph_byDefault() {
        assertThat(System.getProperty(SystemEnvironment.RESOLVE_FANIN_REVISIONS), nullValue());
        assertThat(new SystemEnvironment().enforceRevisionCompatibilityWithUpstream(), is(true));
    }

    @Test
    public void should_NOT_resolveRevisionsForDependencyGraph_whenExplicitlyDisabled() {
        System.setProperty(SystemEnvironment.RESOLVE_FANIN_REVISIONS, SystemEnvironment.CONFIGURATION_NO);
        assertThat(new SystemEnvironment().enforceRevisionCompatibilityWithUpstream(), is(false));
    }

    @Test
    public void shouldResolveRevisionsForDependencyGraph_whenEnabledExplicitly() {
        System.setProperty(SystemEnvironment.RESOLVE_FANIN_REVISIONS, SystemEnvironment.CONFIGURATION_YES);
        assertThat(new SystemEnvironment().enforceRevisionCompatibilityWithUpstream(), is(true));
    }

    @Test
    public void should_cache_whetherToResolveRevisionsForDependencyGraph() {//because access to properties is synchronized
        assertThat(System.getProperty(SystemEnvironment.RESOLVE_FANIN_REVISIONS), nullValue());
        SystemEnvironment systemEnvironment = new SystemEnvironment();
        assertThat(systemEnvironment.enforceRevisionCompatibilityWithUpstream(), is(true));
        System.setProperty(SystemEnvironment.RESOLVE_FANIN_REVISIONS, SystemEnvironment.CONFIGURATION_NO);
        assertThat(systemEnvironment.enforceRevisionCompatibilityWithUpstream(), is(true));
    }

    @Test
    public void shouldTurnOnConfigMergeFeature_byDefault() {
        assertThat(System.getProperty(SystemEnvironment.ENABLE_CONFIG_MERGE_PROPERTY), nullValue());
        assertThat(new SystemEnvironment().get(SystemEnvironment.ENABLE_CONFIG_MERGE_FEATURE), is(true));
    }

    @Test
    public void should_NOT_TurnOnConfigMergeFeature_whenExplicitlyDisabled() {
        System.setProperty(SystemEnvironment.ENABLE_CONFIG_MERGE_PROPERTY, SystemEnvironment.CONFIGURATION_NO);
        assertThat(new SystemEnvironment().get(SystemEnvironment.ENABLE_CONFIG_MERGE_FEATURE), is(false));
    }

    @Test
    public void shouldTurnOnConfigMergeFeature_whenEnabledExplicitly() {
        System.setProperty(SystemEnvironment.ENABLE_CONFIG_MERGE_PROPERTY, SystemEnvironment.CONFIGURATION_YES);
        assertThat(new SystemEnvironment().get(SystemEnvironment.ENABLE_CONFIG_MERGE_FEATURE), is(true));
    }

    @Test
    public void should_cache_whetherToTurnOnConfigMergeFeature() {//because access to properties is synchronized
        assertThat(System.getProperty(SystemEnvironment.ENABLE_CONFIG_MERGE_PROPERTY), nullValue());
        assertThat(new SystemEnvironment().get(SystemEnvironment.ENABLE_CONFIG_MERGE_FEATURE), is(true));
        System.setProperty(SystemEnvironment.ENABLE_CONFIG_MERGE_PROPERTY, SystemEnvironment.CONFIGURATION_NO);
        assertThat(new SystemEnvironment().get(SystemEnvironment.ENABLE_CONFIG_MERGE_FEATURE), is(true));
    }

    @Test
    public void shouldGetTfsSocketTimeOut() {
        assertThat(systemEnvironment.getTfsSocketTimeout(), is(SystemEnvironment.TFS_SOCKET_TIMEOUT_IN_MILLISECONDS));
        System.setProperty(SystemEnvironment.TFS_SOCKET_TIMEOUT_PROPERTY, "100000000");
        assertThat(systemEnvironment.getTfsSocketTimeout(), is(100000000));
    }

    @Test
    public void shouldGiveINFOAsTheDefaultLevelOfAPluginWithoutALoggingLevelSet() throws Exception {
        assertThat(systemEnvironment.pluginLoggingLevel("some-plugin-1"), is(Level.INFO));
    }

    @Test
    public void shouldGiveINFOAsTheDefaultLevelOfAPluginWithAnInvalidLoggingLevelSet() throws Exception {
        System.setProperty("plugin.some-plugin-2.log.level", "SOME-INVALID-LOG-LEVEL");

        assertThat(systemEnvironment.pluginLoggingLevel("some-plugin-2"), is(Level.INFO));
    }

    @Test
    public void shouldGiveTheLevelOfAPluginWithALoggingLevelSet() throws Exception {
        System.setProperty("plugin.some-plugin-3.log.level", "DEBUG");
        System.setProperty("plugin.some-plugin-4.log.level", "INFO");
        System.setProperty("plugin.some-plugin-5.log.level", "WARN");
        System.setProperty("plugin.some-plugin-6.log.level", "ERROR");

        assertThat(systemEnvironment.pluginLoggingLevel("some-plugin-3"), is(Level.DEBUG));
        assertThat(systemEnvironment.pluginLoggingLevel("some-plugin-4"), is(Level.INFO));
        assertThat(systemEnvironment.pluginLoggingLevel("some-plugin-5"), is(Level.WARN));
        assertThat(systemEnvironment.pluginLoggingLevel("some-plugin-6"), is(Level.ERROR));
    }

    @Test
    @RunIf(value = DatabaseChecker.class, arguments = {DatabaseChecker.H2})
    public void shouldGetGoDatabaseProvider() {
        assertThat("default provider should be h2db", systemEnvironment.getDatabaseProvider(), is("com.thoughtworks.go.server.database.H2Database"));
        System.setProperty("go.database.provider", "foo");
        assertThat(systemEnvironment.getDatabaseProvider(), is("foo"));
    }

    @Test
    public void shouldFindGoServerStatusToBeActiveByDefault() throws Exception {
        assertThat(systemEnvironment.isServerActive(), is(true));
    }

    @Test
    public void shouldPutServerInActiveMode() throws Exception {
        String key = "go.server.state";
        try {
            System.setProperty(key, "passive");
            systemEnvironment.switchToActiveState();
            assertThat(systemEnvironment.isServerActive(), is(true));
        } finally {
            System.clearProperty(key);
        }
    }

    @Test
    public void shouldPutServerInPassiveMode() throws Exception {
        String key = "go.server.state";
        try {
            System.setProperty(key, "active");
            systemEnvironment.switchToPassiveState();
            assertThat(systemEnvironment.isServerActive(), is(false));
        } finally {
            System.clearProperty(key);
        }
    }

    @Test
    public void shouldFindGoServerStatusToBePassive() throws Exception {
        try {
            SystemEnvironment systemEnvironment = new SystemEnvironment();
            System.setProperty("go.server.state", "passive");
            assertThat(systemEnvironment.isServerActive(), is(false));
        } finally {
            System.clearProperty("go.server.state");
        }
    }

    @Test
    public void shouldUseJetty9ByDefault() {
        assertThat(systemEnvironment.get(SystemEnvironment.APP_SERVER), is(SystemEnvironment.JETTY9));
        assertThat(systemEnvironment.usingJetty9(), is(true));

        systemEnvironment.set(SystemEnvironment.APP_SERVER, "JETTY6");
        assertThat(systemEnvironment.usingJetty9(), is(false));
    }

    @Test
    public void shouldGetDefaultLandingPageAsPipelines() throws Exception {
        String landingPage = systemEnvironment.landingPage();
        assertThat(landingPage, is("/pipelines"));
    }

    @Test
    public void shouldAbleToOverrideDefaultLandingPageAsPipelines() throws Exception {
        try {
            System.setProperty("go.landing.page", "/admin/pipelines");
            String landingPage = systemEnvironment.landingPage();
            assertThat(landingPage, is("/admin/pipelines"));
        } finally {
            System.clearProperty("go.landing.page");
        }
    }

    @Test
    public void shouldSetTLS1Dot2AsDefaultTransportProtocolForAgent() {
        assertThat(SystemEnvironment.GO_SSL_TRANSPORT_PROTOCOL_TO_BE_USED_BY_AGENT.propertyName(), is("go.ssl.agent.protocol"));
        assertThat(systemEnvironment.get(SystemEnvironment.GO_SSL_TRANSPORT_PROTOCOL_TO_BE_USED_BY_AGENT), is("TLSv1.2"));
        System.setProperty(SystemEnvironment.GO_SSL_TRANSPORT_PROTOCOL_TO_BE_USED_BY_AGENT.propertyName(), "SSL");
        assertThat(systemEnvironment.get(SystemEnvironment.GO_SSL_TRANSPORT_PROTOCOL_TO_BE_USED_BY_AGENT), is("SSL"));
    }

    @Test
    public void shouldGetIncludedCiphersForSSLConfig() {
        assertThat(SystemEnvironment.GO_SSL_INCLUDE_CIPHERS.propertyName(), is("go.ssl.ciphers.include"));
        assertThat(SystemEnvironment.GO_SSL_INCLUDE_CIPHERS instanceof SystemEnvironment.GoStringArraySystemProperty, is(true));
        assertThat(systemEnvironment.get(SystemEnvironment.GO_SSL_INCLUDE_CIPHERS), is(nullValue()));
    }

    @Test
    public void shouldGetExcludedCiphersForSSLConfig() {
        assertThat(SystemEnvironment.GO_SSL_EXCLUDE_CIPHERS.propertyName(), is("go.ssl.ciphers.exclude"));
        assertThat(SystemEnvironment.GO_SSL_EXCLUDE_CIPHERS instanceof SystemEnvironment.GoStringArraySystemProperty, is(true));
        assertThat(systemEnvironment.get(SystemEnvironment.GO_SSL_EXCLUDE_CIPHERS), is(nullValue()));
    }

    @Test
    public void shouldGetExcludedProtocolsForSSLConfig() {
        assertThat(SystemEnvironment.GO_SSL_EXCLUDE_PROTOCOLS.propertyName(), is("go.ssl.protocols.exclude"));
        assertThat(SystemEnvironment.GO_SSL_EXCLUDE_PROTOCOLS instanceof SystemEnvironment.GoStringArraySystemProperty, is(true));
        assertThat(systemEnvironment.get(SystemEnvironment.GO_SSL_EXCLUDE_PROTOCOLS), is(nullValue()));
    }

    @Test
    public void shouldGetIncludedProtocolsForSSLConfig() {
        assertThat(SystemEnvironment.GO_SSL_INCLUDE_PROTOCOLS.propertyName(), is("go.ssl.protocols.include"));
        assertThat(SystemEnvironment.GO_SSL_INCLUDE_PROTOCOLS instanceof SystemEnvironment.GoStringArraySystemProperty, is(true));
        assertThat(systemEnvironment.get(SystemEnvironment.GO_SSL_INCLUDE_PROTOCOLS), is(nullValue()));
    }

    @Test
    public void shouldGetRenegotiationAllowedFlagForSSLConfig() {
        assertThat(SystemEnvironment.GO_SSL_RENEGOTIATION_ALLOWED.propertyName(), is("go.ssl.renegotiation.allowed"));
        boolean defaultValue = true;
        assertThat(systemEnvironment.get(SystemEnvironment.GO_SSL_RENEGOTIATION_ALLOWED), is(defaultValue));
        System.clearProperty("go.ssl.renegotiation.allowed");
        assertThat(systemEnvironment.get(SystemEnvironment.GO_SSL_RENEGOTIATION_ALLOWED), is(defaultValue));
        System.setProperty("go.ssl.renegotiation.allowed", "false");
        assertThat(systemEnvironment.get(SystemEnvironment.GO_SSL_RENEGOTIATION_ALLOWED), is(false));
    }

    @Test
    public void ShouldRemoveWhiteSpacesForStringArraySystemProperties() {
        String[] defaultValue = {"junk", "funk"};
        String propertyName = "property.name";
        SystemEnvironment.GoStringArraySystemProperty property = new SystemEnvironment.GoStringArraySystemProperty(propertyName, defaultValue);
        System.setProperty(propertyName, " foo    ,  bar  ");
        assertThat(systemEnvironment.get(property).length, is(2));
        assertThat(systemEnvironment.get(property)[0], is("foo"));
        assertThat(systemEnvironment.get(property)[1], is("bar"));
    }

    @Test
    public void ShouldUseDefaultValueForStringArraySystemPropertiesWhenTheValueIsSetToEmptyString() {
        String[] defaultValue = {"junk", "funk"};
        String propertyName = "property.name";
        SystemEnvironment.GoStringArraySystemProperty property = new SystemEnvironment.GoStringArraySystemProperty(propertyName, defaultValue);
        System.clearProperty(propertyName);
        assertThat(systemEnvironment.get(property), is(defaultValue));
        System.setProperty(propertyName, " ");
        assertThat(systemEnvironment.get(property), is(defaultValue));
    }

    @Test
    public void shouldSetConfigRepoGCToBeAggressiveByDefault() {
        assertThat(new SystemEnvironment().get(SystemEnvironment.GO_CONFIG_REPO_GC_AGGRESSIVE), is(true));
    }

    @Test
    public void shouldTurnOffPeriodicGCByDefault() {
        assertThat(new SystemEnvironment().get(SystemEnvironment.GO_CONFIG_REPO_PERIODIC_GC), is(false));
    }

    @Test
    public void shouldGetUpdateServerPublicKeyFilePath() {
        assertThat(SystemEnvironment.GO_UPDATE_SERVER_PUBLIC_KEY_FILE_NAME.propertyName(), is("go.update.server.public.key.file.name"));

        System.setProperty("go.update.server.public.key.file.name", "public_key");
        assertThat(systemEnvironment.getUpdateServerPublicKeyPath(), is(systemEnvironment.getConfigDir() + "/public_key"));
    }

    @Test
    public void shouldGetUpdateServerUrl() {
        assertThat(SystemEnvironment.GO_UPDATE_SERVER_URL.propertyName(), is("go.update.server.url"));

        System.setProperty("go.update.server.url", "http://update_server_url");
        assertThat(systemEnvironment.getUpdateServerUrl(), is("http://update_server_url"));
    }

    @Test
    public void shouldGetMaxNumberOfRequestsForEncryptionApi() {
        assertThat(SystemEnvironment.GO_ENCRYPTION_API_MAX_REQUESTS.propertyName(), is("go.encryption.api.max.requests"));
        assertThat(systemEnvironment.getMaxEncryptionAPIRequestsPerMinute(), is(30));

        System.setProperty("go.encryption.api.max.requests", "50");

        assertThat(systemEnvironment.getMaxEncryptionAPIRequestsPerMinute(), is(50));
    }

    @Test
    public void shouldCheckIfGOUpdatesIsEnabled() {
        assertThat(SystemEnvironment.GO_CHECK_UPDATES.propertyName(), is("go.check.updates"));
        assertTrue(systemEnvironment.isGOUpdateCheckEnabled());

        System.setProperty("go.check.updates", "false");
        assertFalse(systemEnvironment.isGOUpdateCheckEnabled());
    }

    @Test
    public void shouldEnableTemplateAutoSuggestByDefault() {
        assertThat(SystemEnvironment.GO_FETCH_ARTIFACT_TEMPLATE_AUTO_SUGGEST.propertyName(), is("go.fetch-artifact.template.auto-suggest"));
        assertTrue(systemEnvironment.isFetchArtifactTemplateAutoSuggestEnabled());
    }

    @Test
    public void shouldDisableTemplateAutoSuggest() {
        System.setProperty("go.fetch-artifact.template.auto-suggest", "false");
        assertFalse(systemEnvironment.isFetchArtifactTemplateAutoSuggestEnabled());
    }

    @Test
    public void shouldReturnTheDefaultGCExpireTimeInMilliSeconds() {
        assertThat(SystemEnvironment.GO_CONFIG_REPO_GC_EXPIRE.propertyName(), is("go.config.repo.gc.expire"));
        assertThat(systemEnvironment.getConfigGitGCExpireTime(), is(24*60*60*1000L));
    }

    @Test
    public void shouldReturnTHeGCExpireTimeInMilliSeconds() {
        assertThat(systemEnvironment.getConfigGitGCExpireTime(), is(24*60*60*1000L));
        System.setProperty("go.config.repo.gc.expire", "1");
        assertThat(systemEnvironment.getConfigGitGCExpireTime(), is(60*60*1000L));
    }

    @Test
    public void shouldReturnTrueIfBooleanSystemPropertyIsEnabledByY() {
        assertThat(new SystemEnvironment().get(SystemEnvironment.GO_CONFIG_REPO_PERIODIC_GC), is(false));
        System.setProperty("go.config.repo.gc.periodic", "Y");
        assertThat(new SystemEnvironment().get(SystemEnvironment.GO_CONFIG_REPO_PERIODIC_GC), is(true));
    }

    @Test
    public void shouldReturnTrueIfBooleanSystemPropertyIsEnabledByTrue() {
        assertThat(new SystemEnvironment().get(SystemEnvironment.GO_CONFIG_REPO_PERIODIC_GC), is(false));
        System.setProperty("go.config.repo.gc.periodic", "true");
        assertThat(new SystemEnvironment().get(SystemEnvironment.GO_CONFIG_REPO_PERIODIC_GC), is(true));
    }

    @Test
    public void shouldReturnFalseIfBooleanSystemPropertyIsAnythingButYOrTrue() {
        assertThat(new SystemEnvironment().get(SystemEnvironment.GO_CONFIG_REPO_PERIODIC_GC), is(false));
        System.setProperty("go.config.repo.gc.periodic", "some-value");
        assertThat(new SystemEnvironment().get(SystemEnvironment.GO_CONFIG_REPO_PERIODIC_GC), is(false));
    }

    @Test
    public void shouldBeInStandByModeIfGoServerModeIsSetToStandby() {
        assertFalse(new SystemEnvironment().isServerInStandbyMode());

        System.setProperty("go.server.mode", "StandBy");

        assertTrue(new SystemEnvironment().isServerInStandbyMode());
    }
}


text:
package sandwich

import (
	"compress/gzip"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestGzip(t *testing.T) {
	greet := func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hi there!")
	}
	handler := Gzip(New()).With(greet)

	resp := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/", nil)
	req.Header.Add(headerAcceptEncoding, "gzip")
	handler.ServeHTTP(resp, req)

	if resp.Header().Get(headerContentEncoding) != "gzip" {
		t.Errorf("Not gzip'd? Content-encoding: %q", resp.Header())
	}

	if resp.Header().Get(headerContentLength) != "" {
		t.Errorf("Not supposed to include content-length: %q", resp.Header())
	}

	r, err := gzip.NewReader(resp.Body)
	if err != nil {
		t.Fatal(err)
	}
	defer r.Close()
	if body, err := ioutil.ReadAll(r); err != nil {
		t.Fatal(err)
	} else if string(body) != "Hi there!" {
		t.Errorf("Wrong response: %q", string(body))
	}

	// Also, test without the accept header and make sure it's NOT gzip'd.
	resp = httptest.NewRecorder()
	req, _ = http.NewRequest("GET", "/", nil)
	handler.ServeHTTP(resp, req)
	if resp.Header().Get(headerContentEncoding) == "gzip" {
		t.Errorf("Unexpectedly gzip'd: Content-encoding: %q", resp.Header())
	}
	if resp.Body.String() != "Hi there!" {
		t.Errorf("Wrong response: %q", resp.Body.String())
	}
}


text:
from sounding_dir.readsoundings import readsound
import numpy as np
import string
from scipy.io import savemat
import glob
import matplotlib.pyplot as plt
from ubcplot.stdplot import simplots
import pickle

def findz(press,temp,z0):
    Rd=287.
    rho=press*100./((temp+273.15)*Rd)
    delz=-np.diff(press*100.)/(rho[:-1]*9.8)
    the_z=z0 + delz
    return np.concatenate(([z0],the_z))

picfile='s_alburqurque.pic'
picfile=open(picfile,'r')
the_data=pickle.load(picfile)
picfile.close()
newDict=the_data['data']
theKeys=newDict.keys()
theKeys.sort()
outArray=np.empty([len(theKeys),],dtype='object')
for count,the_key in enumerate(theKeys):
    outArray[count]=newDict[the_key]

figcount=0
allkeys=newDict.keys()
firstsound=newDict[allkeys[0]]
figfac=simplots()
figcount+=1
figfac.fignum=figcount
ax1=figfac.singleplot()
ax1.plot(firstsound.temp,firstsound.height*1.e-3)
for key in allkeys[1:]:
    thesound=newDict[key]
    ax1.plot(thesound.temp,thesound.height*1.e-3)
ax1.set_title('Albuquerque NM, July 2010 -- 62 soundings')
ax1.set_xlabel('temperature (deg C)')
ax1.set_ylabel('height (km)')
ax1.figure.savefig('alb_height.png',dpi=200)

figfac=simplots()
figcount+=1
figfac.fignum=figcount
ax1=figfac.singleplot()
ax1.plot(firstsound.temp,firstsound.press)
ax1.invert_yaxis()
for key in allkeys[1:]:
    thesound=newDict[key]
    ax1.plot(thesound.temp,thesound.press)
ax1.set_title('Albuquerque NM, July 2010 - 62 soundings')
ax1.set_xlabel('temperature (deg C)')
ax1.set_ylabel('pressure (hPa)')
ax1.figure.savefig('alb_press.png',dpi=200)

figfac=simplots()
figcount+=1
figfac.fignum=figcount
ax1=figfac.singleplot()
ax1.semilogy(firstsound.temp,firstsound.press)
ax1.invert_yaxis()
for key in allkeys[1:]:
    thesound=newDict[key]
    ax1.semilogy(thesound.temp,thesound.press)
ax1.set_title('Albuquerque NM, July 2010 - 62 soundings')
ax1.set_xlabel('temperature (deg C)')
ax1.set_ylabel('pressure (hPa)')
ax1.set_ylim([900.,2.])
ax1.figure.canvas.draw()
ax1.figure.savefig('alb_press_logy.png',dpi=200)

figfac=simplots()
figcount+=1
figfac.fignum=figcount
ax1=figfac.singleplot()
for key in allkeys:
    if '12Z' in key:
        thesound=newDict[key]
        ax1.plot(thesound.temp,thesound.height*1.e-3)

the_z=np.linspace(1600,7000,10)
the_temp= 37. - 9.8/1004.*(the_z - 1600)
ax1.plot(the_temp,the_z*1.e-3,'r',lw=3)
ax1.set_ylim([1.5,7])
ax1.set_xlim([-20,40])
ax1.set_title('July 2010 - 5am soundings')
ax1.set_xlabel('temperature (deg C)')
ax1.set_ylabel('height (km)')
ax1.figure.savefig('alb_height_5am.png',dpi=200)

figfac=simplots()
figcount+=1
figfac.fignum=figcount
ax1=figfac.singleplot()
for key in allkeys:
    if '0Z' in key:
        thesound=newDict[key]
        ax1.plot(thesound.temp,thesound.height*1.e-3)

the_z=np.linspace(1600,7000,10)
the_temp= 37. - 9.8/1004.*(the_z - 1600)
ax1.plot(the_temp,the_z*1.e-3,'r',lw=3)
ax1.set_ylim([1.5,7])
ax1.set_xlim([-20,40])
ax1.set_title('July 2010 - 5pm soundings')
ax1.set_xlabel('temperature (deg C)')
ax1.set_ylabel('height (km)')
ax1.figure.savefig('alb_height_5pm.png',dpi=200)

p0=[]
for key in allkeys:
    p0.append(thesound.press[0])

minpress=np.min(p0)
presslevs=np.linspace(305,minpress-1,150)
import scipy.interpolate
night_tempsounds=[]
night_heightsounds=[]
day_tempsounds=[]
day_heightsounds=[]
origpress=[]
origtemp=[]
origheight=[]
for key in allkeys:
    thesound=newDict[key]
    press=thesound.press[::-1]
    temp=thesound.temp[::-1]
    height=thesound.height[::-1]
    closepress=(press - 300.)**2.
    minarg=np.atleast_1d(np.argmin(closepress))[0]
    press=press[minarg:]
    temp=temp[minarg:]
    height=height[minarg:]
    origheight.append(height)
    origtemp.append(temp)
    origpress.append(press)
    try:
        interptemp=scipy.interpolate.UnivariateSpline(press,temp)
        interpheight=scipy.interpolate.UnivariateSpline(press,height)
    except:
        pass
    newtemps=interptemp(presslevs)
    newheights=interpheight(presslevs)
    if '12Z' in key:
        night_tempsounds.append(newtemps)
        night_heightsounds.append(newheights)
    else:
        day_tempsounds.append(newtemps)
        day_heightsounds.append(newheights)

figfac=simplots()
figcount+=1
figfac.fignum=figcount
ax1=figfac.singleplot()
mean_heights=np.array(day_heightsounds)
mean_heights=mean_heights.mean(axis=0)
mean_temps=np.array(day_tempsounds)
mean_temps=mean_temps.mean(axis=0)
ax1.plot(mean_temps,mean_heights*1.e-3,'g-',lw=3)
ax1.set_ylim([1.5,7])
ax1.set_xlim([-20,40])
mean_heights=np.array(night_heightsounds)
mean_heights=mean_heights.mean(axis=0)
mean_temps=np.array(night_tempsounds)
mean_temps=mean_temps.mean(axis=0)
ax1.plot(mean_temps,mean_heights*1.e-3,'k-',lw=3)
the_z=np.linspace(1600,7000,10)
the_temp= 32. - 9.8/1004.*(the_z - 1600)
ax1.plot(the_temp,the_z*1.e-3,'r',lw=1.5)
ax1.grid(True)
ax1.set_xlabel('temperature (deg C)')
ax1.set_ylabel('height (km)')
ax1.set_title('Albuquerque NM, July 2010 -- July average')

## figfac=simplots()
## figcount+=1
## figfac.fignum=figcount
## ax1=figfac.singleplot()
## for sound in tempsounds:
##     ax1.plot(sound,presslevs,'g-')
## #ax1.plot(thesound.temp,thesound.press,'b-',lw=2)
## ax1.invert_yaxis()
## ax1.set_xlim([-25,40])
## ax1.set_ylim([900,500])

## figfac=simplots()
## figcount+=1
## figfac.fignum=figcount
## ax1=figfac.singleplot()
## for count,height in enumerate(heightsounds):
##     ax1.plot(height,presslevs,'g-',lw=10)
##     ax1.plot(origheight[count],origpress[count],'b-')
## ax1.invert_yaxis()
## ax1.set_ylim([900,500])

plt.show()