text:
package com.amazonservices.mws.finances.model;

import com.amazonservices.mws.client.*;

/**
 * AdjustmentItem complex type.
 *
 * XML schema:
 *
 * <pre>
 * <complexType name="AdjustmentItem">
 *    <complexContent>
 *       <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *          <sequence>
 *             <element name="Quantity" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *             <element name="PerUnitAmount" type="{http://mws.amazonservices.com/Finances/2015-05-01}Currency" minOccurs="0"/>
 *             <element name="TotalAmount" type="{http://mws.amazonservices.com/Finances/2015-05-01}Currency" minOccurs="0"/>
 *             <element name="SellerSKU" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *             <element name="FnSKU" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *             <element name="ProductDescription" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *             <element name="ASIN" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *          </sequence>
 *       </restriction>
 *    </complexContent>
 * </complexType>
 * </pre>
 */
public class AdjustmentItem extends AbstractMwsObject {

    private String quantity;

    private Currency perUnitAmount;

    private Currency totalAmount;

    private String sellerSKU;

    private String fnSKU;

    private String productDescription;

    private String asin;

    /**
     * Get the value of Quantity.
     *
     * @return The value of Quantity.
     */
    public String getQuantity() {
        return quantity;
    }

    /**
     * Set the value of Quantity.
     *
     * @param quantity
     *            The new value to set.
     */
    public void setQuantity(String quantity) {
        this.quantity = quantity;
    }

    /**
     * Check to see if Quantity is set.
     *
     * @return true if Quantity is set.
     */
    public boolean isSetQuantity() {
        return quantity != null;
    }

    /**
     * Set the value of Quantity, return this.
     *
     * @param quantity
     *             The new value to set.
     *
     * @return This instance.
     */
    public AdjustmentItem withQuantity(String quantity) {
        this.quantity = quantity;
        return this;
    }

    /**
     * Get the value of PerUnitAmount.
     *
     * @return The value of PerUnitAmount.
     */
    public Currency getPerUnitAmount() {
        return perUnitAmount;
    }

    /**
     * Set the value of PerUnitAmount.
     *
     * @param perUnitAmount
     *            The new value to set.
     */
    public void setPerUnitAmount(Currency perUnitAmount) {
        this.perUnitAmount = perUnitAmount;
    }

    /**
     * Check to see if PerUnitAmount is set.
     *
     * @return true if PerUnitAmount is set.
     */
    public boolean isSetPerUnitAmount() {
        return perUnitAmount != null;
    }

    /**
     * Set the value of PerUnitAmount, return this.
     *
     * @param perUnitAmount
     *             The new value to set.
     *
     * @return This instance.
     */
    public AdjustmentItem withPerUnitAmount(Currency perUnitAmount) {
        this.perUnitAmount = perUnitAmount;
        return this;
    }

    /**
     * Get the value of TotalAmount.
     *
     * @return The value of TotalAmount.
     */
    public Currency getTotalAmount() {
        return totalAmount;
    }

    /**
     * Set the value of TotalAmount.
     *
     * @param totalAmount
     *            The new value to set.
     */
    public void setTotalAmount(Currency totalAmount) {
        this.totalAmount = totalAmount;
    }

    /**
     * Check to see if TotalAmount is set.
     *
     * @return true if TotalAmount is set.
     */
    public boolean isSetTotalAmount() {
        return totalAmount != null;
    }

    /**
     * Set the value of TotalAmount, return this.
     *
     * @param totalAmount
     *             The new value to set.
     *
     * @return This instance.
     */
    public AdjustmentItem withTotalAmount(Currency totalAmount) {
        this.totalAmount = totalAmount;
        return this;
    }

    /**
     * Get the value of SellerSKU.
     *
     * @return The value of SellerSKU.
     */
    public String getSellerSKU() {
        return sellerSKU;
    }

    /**
     * Set the value of SellerSKU.
     *
     * @param sellerSKU
     *            The new value to set.
     */
    public void setSellerSKU(String sellerSKU) {
        this.sellerSKU = sellerSKU;
    }

    /**
     * Check to see if SellerSKU is set.
     *
     * @return true if SellerSKU is set.
     */
    public boolean isSetSellerSKU() {
        return sellerSKU != null;
    }

    /**
     * Set the value of SellerSKU, return this.
     *
     * @param sellerSKU
     *             The new value to set.
     *
     * @return This instance.
     */
    public AdjustmentItem withSellerSKU(String sellerSKU) {
        this.sellerSKU = sellerSKU;
        return this;
    }

    /**
     * Get the value of FnSKU.
     *
     * @return The value of FnSKU.
     */
    public String getFnSKU() {
        return fnSKU;
    }

    /**
     * Set the value of FnSKU.
     *
     * @param fnSKU
     *            The new value to set.
     */
    public void setFnSKU(String fnSKU) {
        this.fnSKU = fnSKU;
    }

    /**
     * Check to see if FnSKU is set.
     *
     * @return true if FnSKU is set.
     */
    public boolean isSetFnSKU() {
        return fnSKU != null;
    }

    /**
     * Set the value of FnSKU, return this.
     *
     * @param fnSKU
     *             The new value to set.
     *
     * @return This instance.
     */
    public AdjustmentItem withFnSKU(String fnSKU) {
        this.fnSKU = fnSKU;
        return this;
    }

    /**
     * Get the value of ProductDescription.
     *
     * @return The value of ProductDescription.
     */
    public String getProductDescription() {
        return productDescription;
    }

    /**
     * Set the value of ProductDescription.
     *
     * @param productDescription
     *            The new value to set.
     */
    public void setProductDescription(String productDescription) {
        this.productDescription = productDescription;
    }

    /**
     * Check to see if ProductDescription is set.
     *
     * @return true if ProductDescription is set.
     */
    public boolean isSetProductDescription() {
        return productDescription != null;
    }

    /**
     * Set the value of ProductDescription, return this.
     *
     * @param productDescription
     *             The new value to set.
     *
     * @return This instance.
     */
    public AdjustmentItem withProductDescription(String productDescription) {
        this.productDescription = productDescription;
        return this;
    }

    /**
     * Get the value of ASIN.
     *
     * @return The value of ASIN.
     */
    public String getASIN() {
        return asin;
    }

    /**
     * Set the value of ASIN.
     *
     * @param asin
     *            The new value to set.
     */
    public void setASIN(String asin) {
        this.asin = asin;
    }

    /**
     * Check to see if ASIN is set.
     *
     * @return true if ASIN is set.
     */
    public boolean isSetASIN() {
        return asin != null;
    }

    /**
     * Set the value of ASIN, return this.
     *
     * @param asin
     *             The new value to set.
     *
     * @return This instance.
     */
    public AdjustmentItem withASIN(String asin) {
        this.asin = asin;
        return this;
    }

    /**
     * Read members from a MwsReader.
     *
     * @param r
     *      The reader to read from.
     */
    @Override
    public void readFragmentFrom(MwsReader r) {
        quantity = r.read("Quantity", String.class);
        perUnitAmount = r.read("PerUnitAmount", Currency.class);
        totalAmount = r.read("TotalAmount", Currency.class);
        sellerSKU = r.read("SellerSKU", String.class);
        fnSKU = r.read("FnSKU", String.class);
        productDescription = r.read("ProductDescription", String.class);
        asin = r.read("ASIN", String.class);
    }

    /**
     * Write members to a MwsWriter.
     *
     * @param w
     *      The writer to write to.
     */
    @Override
    public void writeFragmentTo(MwsWriter w) {
        w.write("Quantity", quantity);
        w.write("PerUnitAmount", perUnitAmount);
        w.write("TotalAmount", totalAmount);
        w.write("SellerSKU", sellerSKU);
        w.write("FnSKU", fnSKU);
        w.write("ProductDescription", productDescription);
        w.write("ASIN", asin);
    }

    /**
     * Write tag, xmlns and members to a MwsWriter.
     *
     * @param w
     *         The Writer to write to.
     */
    @Override
    public void writeTo(MwsWriter w) {
        w.write("http://mws.amazonservices.com/Finances/2015-05-01", "AdjustmentItem",this);
    }

    /** Default constructor. */
    public AdjustmentItem() {
        super();
    }

}


text:
'use strict';

/* jshint ignore:start */
/**
 * This code was generated by
 * \ / _    _  _|   _  _
 *  | (_)\/(_)(_|\/| |(/_  v1.0.0
 *       /       /
 */
/* jshint ignore:end */

var _ = require('lodash');  /* jshint ignore:line */
var Domain = require('../base/Domain');  /* jshint ignore:line */
var V2010 = require('./api/V2010');  /* jshint ignore:line */

/* jshint ignore:start */
/**
 * Initialize api domain
 *
 * @constructor
 *
 * @property {Twilio.Api.V2010} v2010 - v2010 version
 * @property {Twilio.Api.V2010.AccountContext} account - Main account resource
 * @property {Twilio.Api.V2010.AccountList} accounts - accounts resource
 * @property {Twilio.Api.V2010.AccountContext.AddressList} addresses -
 *          addresses resource
 * @property {Twilio.Api.V2010.AccountContext.ApplicationList} applications -
 *          applications resource
 * @property {Twilio.Api.V2010.AccountContext.AuthorizedConnectAppList} authorizedConnectApps -
 *          authorizedConnectApps resource
 * @property {Twilio.Api.V2010.AccountContext.AvailablePhoneNumberCountryList} availablePhoneNumbers -
 *          availablePhoneNumbers resource
 * @property {Twilio.Api.V2010.AccountContext.BalanceList} balance -
 *          balance resource
 * @property {Twilio.Api.V2010.AccountContext.CallList} calls - calls resource
 * @property {Twilio.Api.V2010.AccountContext.ConferenceList} conferences -
 *          conferences resource
 * @property {Twilio.Api.V2010.AccountContext.ConnectAppList} connectApps -
 *          connectApps resource
 * @property {Twilio.Api.V2010.AccountContext.IncomingPhoneNumberList} incomingPhoneNumbers -
 *          incomingPhoneNumbers resource
 * @property {Twilio.Api.V2010.AccountContext.KeyList} keys - keys resource
 * @property {Twilio.Api.V2010.AccountContext.MessageList} messages -
 *          messages resource
 * @property {Twilio.Api.V2010.AccountContext.NewKeyList} newKeys -
 *          newKeys resource
 * @property {Twilio.Api.V2010.AccountContext.NewSigningKeyList} newSigningKeys -
 *          newSigningKeys resource
 * @property {Twilio.Api.V2010.AccountContext.NotificationList} notifications -
 *          notifications resource
 * @property {Twilio.Api.V2010.AccountContext.OutgoingCallerIdList} outgoingCallerIds -
 *          outgoingCallerIds resource
 * @property {Twilio.Api.V2010.AccountContext.QueueList} queues - queues resource
 * @property {Twilio.Api.V2010.AccountContext.RecordingList} recordings -
 *          recordings resource
 * @property {Twilio.Api.V2010.AccountContext.SigningKeyList} signingKeys -
 *          signingKeys resource
 * @property {Twilio.Api.V2010.AccountContext.SipList} sip - sip resource
 * @property {Twilio.Api.V2010.AccountContext.ShortCodeList} shortCodes -
 *          shortCodes resource
 * @property {Twilio.Api.V2010.AccountContext.TokenList} tokens - tokens resource
 * @property {Twilio.Api.V2010.AccountContext.TranscriptionList} transcriptions -
 *          transcriptions resource
 * @property {Twilio.Api.V2010.AccountContext.UsageList} usage - usage resource
 * @property {Twilio.Api.V2010.AccountContext.ValidationRequestList} validationRequests -
 *          validationRequests resource
 *
 * @param {Twilio} twilio - The twilio client
 */
/* jshint ignore:end */
function Api(twilio) {
  Domain.prototype.constructor.call(this, twilio, 'https://api.twilio.com');

  // Versions
  this._v2010 = undefined;
}

_.extend(Api.prototype, Domain.prototype);
Api.prototype.constructor = Api;

Object.defineProperty(Api.prototype,
  'v2010', {
  get: function() {
    this._v2010 = this._v2010 || new V2010(this);
    return this._v2010;
  }
});

Object.defineProperty(Api.prototype,
  'account', {
  get: function() {
    return this.v2010.account;
  }
});

Object.defineProperty(Api.prototype,
  'accounts', {
  get: function() {
    return this.v2010.accounts;
  }
});

Object.defineProperty(Api.prototype,
  'addresses', {
  get: function() {
    return this.account.addresses;
  }
});

Object.defineProperty(Api.prototype,
  'applications', {
  get: function() {
    return this.account.applications;
  }
});

Object.defineProperty(Api.prototype,
  'authorizedConnectApps', {
  get: function() {
    return this.account.authorizedConnectApps;
  }
});

Object.defineProperty(Api.prototype,
  'availablePhoneNumbers', {
  get: function() {
    return this.account.availablePhoneNumbers;
  }
});

Object.defineProperty(Api.prototype,
  'balance', {
  get: function() {
    return this.account.balance;
  }
});

Object.defineProperty(Api.prototype,
  'calls', {
  get: function() {
    return this.account.calls;
  }
});

Object.defineProperty(Api.prototype,
  'conferences', {
  get: function() {
    return this.account.conferences;
  }
});

Object.defineProperty(Api.prototype,
  'connectApps', {
  get: function() {
    return this.account.connectApps;
  }
});

Object.defineProperty(Api.prototype,
  'incomingPhoneNumbers', {
  get: function() {
    return this.account.incomingPhoneNumbers;
  }
});

Object.defineProperty(Api.prototype,
  'keys', {
  get: function() {
    return this.account.keys;
  }
});

Object.defineProperty(Api.prototype,
  'messages', {
  get: function() {
    return this.account.messages;
  }
});

Object.defineProperty(Api.prototype,
  'newKeys', {
  get: function() {
    return this.account.newKeys;
  }
});

Object.defineProperty(Api.prototype,
  'newSigningKeys', {
  get: function() {
    return this.account.newSigningKeys;
  }
});

Object.defineProperty(Api.prototype,
  'notifications', {
  get: function() {
    return this.account.notifications;
  }
});

Object.defineProperty(Api.prototype,
  'outgoingCallerIds', {
  get: function() {
    return this.account.outgoingCallerIds;
  }
});

Object.defineProperty(Api.prototype,
  'queues', {
  get: function() {
    return this.account.queues;
  }
});

Object.defineProperty(Api.prototype,
  'recordings', {
  get: function() {
    return this.account.recordings;
  }
});

Object.defineProperty(Api.prototype,
  'signingKeys', {
  get: function() {
    return this.account.signingKeys;
  }
});

Object.defineProperty(Api.prototype,
  'sip', {
  get: function() {
    return this.account.sip;
  }
});

Object.defineProperty(Api.prototype,
  'shortCodes', {
  get: function() {
    return this.account.shortCodes;
  }
});

Object.defineProperty(Api.prototype,
  'tokens', {
  get: function() {
    return this.account.tokens;
  }
});

Object.defineProperty(Api.prototype,
  'transcriptions', {
  get: function() {
    return this.account.transcriptions;
  }
});

Object.defineProperty(Api.prototype,
  'usage', {
  get: function() {
    return this.account.usage;
  }
});

Object.defineProperty(Api.prototype,
  'validationRequests', {
  get: function() {
    return this.account.validationRequests;
  }
});

module.exports = Api;

redpajama_set_name: RedPajamaGithub


text:
package co.runrightfast.core.security.cert.impl;

import static co.runrightfast.core.security.BouncyCastle.BOUNCY_CASTLE;
import static co.runrightfast.core.security.SignatureAlgorithm.SHA512withRSA;
import co.runrightfast.core.security.cert.CertificateService;
import co.runrightfast.core.security.cert.CertificateServiceException;
import co.runrightfast.core.security.cert.X509V1CertRequest;
import co.runrightfast.core.security.cert.X509V3CertRequest;
import static co.runrightfast.core.security.util.SecurityUtils.strongSecureRandom;
import java.security.PrivateKey;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import lombok.NonNull;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.X509v1CertificateBuilder;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;

/**
 *
 * @author alfio
 */
public class CertificateServiceImpl implements CertificateService {

    @Override
    public X509Certificate generateX509CertificateV1(@NonNull final X509V1CertRequest request, @NonNull final PrivateKey privateKey) {
        final ContentSigner signer = contentSigner(privateKey);
        final X509v1CertificateBuilder certBuilder = request.x509v1CertificateBuilder();
        final X509CertificateHolder certHolder = certBuilder.build(signer);
        return toX509Certificate(certHolder);
    }

    private X509Certificate toX509Certificate(final X509CertificateHolder certHolder) {
        try {
            return new JcaX509CertificateConverter()
                    .setProvider(BOUNCY_CASTLE)
                    .getCertificate(certHolder);
        } catch (final CertificateException ex) {
            throw new CertificateServiceException(ex);
        }
    }

    private ContentSigner contentSigner(final PrivateKey privateKey) {
        try {
            return new JcaContentSignerBuilder(SHA512withRSA.name())
                    .setProvider(BOUNCY_CASTLE)
                    .setSecureRandom(strongSecureRandom())
                    .build(privateKey);
        } catch (final OperatorCreationException ex) {
            throw new CertificateServiceException(ex);
        }
    }

    @Override
    public X509Certificate generateX509CertificateV3(@NonNull final X509V3CertRequest request, @NonNull final PrivateKey privateKey) throws CertificateServiceException {
        final ContentSigner signer = contentSigner(privateKey);
        final X509v3CertificateBuilder certBuilder = request.x509v3CertificateBuilder();
        final X509CertificateHolder certHolder = certBuilder.build(signer);
        return toX509Certificate(certHolder);
    }

}


text:
package pbtypes

import proto "github.com/golang/protobuf/proto"

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal

// Void is an empty type used as the protobuf RPC method arg or result
// for methods that take no parameters or yield no results,
// respectively.
type Void struct {
}

func (m *Void) Reset()         { *m = Void{} }
func (m *Void) String() string { return proto.CompactTextString(m) }
func (*Void) ProtoMessage()    {}

func init() {
}


text:
"""Test CLR <-> Python type conversions."""

import operator
import pytest

import System
from Python.Test import ConversionTest, MethodResolutionInt, UnicodeString, CodecResetter
from Python.Runtime import PyObjectConversions
from Python.Runtime.Codecs import RawProxyEncoder

def test_bool_conversion():
    """Test bool conversion."""
    ob = ConversionTest()
    assert ob.BooleanField is False
    assert ob.BooleanField == 0

    ob.BooleanField = True
    assert ob.BooleanField is True
    assert ob.BooleanField == 1

    ob.BooleanField = False
    assert ob.BooleanField is False
    assert ob.BooleanField == 0

    with pytest.raises(TypeError):
        ob.BooleanField = 1

    with pytest.raises(TypeError):
        ob.BooleanField = 0

    with pytest.raises(TypeError):
        ob.BooleanField = None

    with pytest.raises(TypeError):
        ob.BooleanField = ''

    with pytest.raises(TypeError):
        ob.BooleanField = System.Boolean(0)

    with pytest.raises(TypeError):
        ob.BooleanField = System.Boolean(1)

    with pytest.raises(TypeError):
        ob.BooleanField = System.Boolean('a')

def test_sbyte_conversion():
    """Test sbyte conversion."""
    assert System.SByte.MaxValue == 127
    assert System.SByte.MinValue == -128

    ob = ConversionTest()
    assert ob.SByteField == 0

    ob.SByteField = 127
    assert ob.SByteField == 127

    ob.SByteField = -128
    assert ob.SByteField == -128

    ob.SByteField = System.SByte(127)
    assert ob.SByteField == 127

    ob.SByteField = System.SByte(-128)
    assert ob.SByteField == -128

    with pytest.raises(TypeError):
        ConversionTest().SByteField = "spam"

    with pytest.raises(TypeError):
        ConversionTest().SByteField = None

    with pytest.raises(OverflowError):
        ConversionTest().SByteField = 128

    with pytest.raises(OverflowError):
        ConversionTest().SByteField = -129

    with pytest.raises(OverflowError):
        _ = System.SByte(128)

    with pytest.raises(OverflowError):
        _ = System.SByte(-129)

def test_byte_conversion():
    """Test byte conversion."""
    assert System.Byte.MaxValue == 255
    assert System.Byte.MinValue == 0

    ob = ConversionTest()
    assert ob.ByteField == 0

    ob.ByteField = 255
    assert ob.ByteField == 255

    ob.ByteField = 0
    assert ob.ByteField == 0

    ob.ByteField = System.Byte(255)
    assert ob.ByteField == 255

    ob.ByteField = System.Byte(0)
    assert ob.ByteField == 0

    with pytest.raises(TypeError):
        ConversionTest().ByteField = "spam"

    with pytest.raises(TypeError):
        ConversionTest().ByteField = None

    with pytest.raises(OverflowError):
        ConversionTest().ByteField = 256

    with pytest.raises(OverflowError):
        ConversionTest().ByteField = -1

    with pytest.raises(OverflowError):
        _ = System.Byte(256)

    with pytest.raises(OverflowError):
        _ = System.Byte(-1)

def test_char_conversion():
    """Test char conversion."""
    assert System.Char.MaxValue == chr(65535)
    assert System.Char.MinValue == chr(0)

    ob = ConversionTest()
    assert ob.CharField == u'A'

    ob.CharField = 'B'
    assert ob.CharField == u'B'

    ob.CharField = u'B'
    assert ob.CharField == u'B'

    ob.CharField = 67
    assert ob.CharField == u'C'

    with pytest.raises(OverflowError):
        ConversionTest().CharField = 65536

    with pytest.raises(OverflowError):
        ConversionTest().CharField = -1

    with pytest.raises(TypeError):
        ConversionTest().CharField = None

def test_int16_conversion():
    """Test int16 conversion."""
    assert System.Int16.MaxValue == 32767
    assert System.Int16.MinValue == -32768

    ob = ConversionTest()
    assert ob.Int16Field == 0

    ob.Int16Field = 32767
    assert ob.Int16Field == 32767

    ob.Int16Field = -32768
    assert ob.Int16Field == -32768

    ob.Int16Field = System.Int16(32767)
    assert ob.Int16Field == 32767

    ob.Int16Field = System.Int16(-32768)
    assert ob.Int16Field == -32768

    with pytest.raises(TypeError):
        ConversionTest().Int16Field = "spam"

    with pytest.raises(TypeError):
        ConversionTest().Int16Field = None

    with pytest.raises(OverflowError):
        ConversionTest().Int16Field = 32768

    with pytest.raises(OverflowError):
        ConversionTest().Int16Field = -32769

    with pytest.raises(OverflowError):
        _ = System.Int16(32768)

    with pytest.raises(OverflowError):
        _ = System.Int16(-32769)

def test_int32_conversion():
    """Test int32 conversion."""
    assert System.Int32.MaxValue == 2147483647
    assert System.Int32.MinValue == -2147483648

    ob = ConversionTest()
    assert ob.Int32Field == 0

    ob.Int32Field = 2147483647
    assert ob.Int32Field == 2147483647

    ob.Int32Field = -2147483648
    assert ob.Int32Field == -2147483648

    ob.Int32Field = System.Int32(2147483647)
    assert ob.Int32Field == 2147483647

    ob.Int32Field = System.Int32(-2147483648)
    assert ob.Int32Field == -2147483648

    with pytest.raises(TypeError):
        ConversionTest().Int32Field = "spam"

    with pytest.raises(TypeError):
        ConversionTest().Int32Field = None

    with pytest.raises(OverflowError):
        ConversionTest().Int32Field = 2147483648

    with pytest.raises(OverflowError):
        ConversionTest().Int32Field = -2147483649

    with pytest.raises(OverflowError):
        _ = System.Int32(2147483648)

    with pytest.raises(OverflowError):
        _ = System.Int32(-2147483649)

def test_int64_conversion():
    """Test int64 conversion."""
    assert System.Int64.MaxValue == 9223372036854775807
    assert System.Int64.MinValue == -9223372036854775808

    ob = ConversionTest()
    assert ob.Int64Field == 0

    ob.Int64Field = 9223372036854775807
    assert ob.Int64Field == 9223372036854775807

    ob.Int64Field = -9223372036854775808
    assert ob.Int64Field == -9223372036854775808

    ob.Int64Field = System.Int64(9223372036854775807)
    assert ob.Int64Field == 9223372036854775807

    ob.Int64Field = System.Int64(-9223372036854775808)
    assert ob.Int64Field == -9223372036854775808

    with pytest.raises(TypeError):
        ConversionTest().Int64Field = "spam"

    with pytest.raises(TypeError):
        ConversionTest().Int64Field = None

    with pytest.raises(OverflowError):
        ConversionTest().Int64Field = 9223372036854775808

    with pytest.raises(OverflowError):
        ConversionTest().Int64Field = -9223372036854775809

    with pytest.raises(OverflowError):
        _ = System.Int64(9223372036854775808)

    with pytest.raises(OverflowError):
        _ = System.Int64(-9223372036854775809)

def test_uint16_conversion():
    """Test uint16 conversion."""
    assert System.UInt16.MaxValue == 65535
    assert System.UInt16.MinValue == 0

    ob = ConversionTest()
    assert ob.UInt16Field == 0

    ob.UInt16Field = 65535
    assert ob.UInt16Field == 65535

    ob.UInt16Field = -0
    assert ob.UInt16Field == 0

    ob.UInt16Field = System.UInt16(65535)
    assert ob.UInt16Field == 65535

    ob.UInt16Field = System.UInt16(0)
    assert ob.UInt16Field == 0

    with pytest.raises(TypeError):
        ConversionTest().UInt16Field = "spam"

    with pytest.raises(TypeError):
        ConversionTest().UInt16Field = None

    with pytest.raises(OverflowError):
        ConversionTest().UInt16Field = 65536

    with pytest.raises(OverflowError):
        ConversionTest().UInt16Field = -1

    with pytest.raises(OverflowError):
        _ = System.UInt16(65536)

    with pytest.raises(OverflowError):
        _ = System.UInt16(-1)

def test_uint32_conversion():
    """Test uint32 conversion."""
    assert System.UInt32.MaxValue == 4294967295
    assert System.UInt32.MinValue == 0

    ob = ConversionTest()
    assert ob.UInt32Field == 0

    ob.UInt32Field = 4294967295
    assert ob.UInt32Field == 4294967295

    ob.UInt32Field = -0
    assert ob.UInt32Field == 0

    ob.UInt32Field = System.UInt32(4294967295)
    assert ob.UInt32Field == 4294967295

    ob.UInt32Field = System.UInt32(0)
    assert ob.UInt32Field == 0

    with pytest.raises(TypeError):
        ConversionTest().UInt32Field = "spam"

    with pytest.raises(TypeError):
        ConversionTest().UInt32Field = None

    with pytest.raises(OverflowError):
        ConversionTest().UInt32Field = 4294967296

    with pytest.raises(OverflowError):
        ConversionTest().UInt32Field = -1

    with pytest.raises(OverflowError):
        _ = System.UInt32(4294967296)

    with pytest.raises(OverflowError):
        _ = System.UInt32(-1)

def test_uint64_conversion():
    """Test uint64 conversion."""
    assert System.UInt64.MaxValue == 18446744073709551615
    assert System.UInt64.MinValue == 0

    ob = ConversionTest()
    assert ob.UInt64Field == 0

    ob.UInt64Field = 18446744073709551615
    assert ob.UInt64Field == 18446744073709551615

    ob.UInt64Field = -0
    assert ob.UInt64Field == 0

    ob.UInt64Field = System.UInt64(18446744073709551615)
    assert ob.UInt64Field == 18446744073709551615

    ob.UInt64Field = System.UInt64(0)
    assert ob.UInt64Field == 0

    with pytest.raises(TypeError):
        ConversionTest().UInt64Field = 0.5

    with pytest.raises(TypeError):
        ConversionTest().UInt64Field = "spam"

    with pytest.raises(TypeError):
        ConversionTest().UInt64Field = None

    with pytest.raises(OverflowError):
        ConversionTest().UInt64Field = 18446744073709551616

    with pytest.raises(OverflowError):
        ConversionTest().UInt64Field = -1

    with pytest.raises(OverflowError):
        _ = System.UInt64((18446744073709551616))

    with pytest.raises(OverflowError):
        _ = System.UInt64(-1)

def test_single_conversion():
    """Test single conversion."""
    assert System.Single.MaxValue == pytest.approx(3.402823e38)
    assert System.Single.MinValue == pytest.approx(-3.402823e38)

    ob = ConversionTest()
    assert ob.SingleField == 0.0

    ob.SingleField = 3.402823e38
    assert ob.SingleField == System.Single(3.402823e38)

    ob.SingleField = -3.402823e38
    assert ob.SingleField == System.Single(-3.402823e38)

    with pytest.raises(TypeError):
        ConversionTest().SingleField = "spam"

    with pytest.raises(TypeError):
        ConversionTest().SingleField = None

    with pytest.raises(OverflowError):
        ConversionTest().SingleField = 3.402824e38

    with pytest.raises(OverflowError):
        ConversionTest().SingleField = -3.402824e38

    with pytest.raises(OverflowError):
        _ = System.Single(3.402824e38)

    with pytest.raises(OverflowError):
        _ = System.Single(-3.402824e38)

def test_double_conversion():
    """Test double conversion."""
    assert System.Double.MaxValue == 1.7976931348623157e308
    assert System.Double.MinValue == -1.7976931348623157e308

    ob = ConversionTest()
    assert ob.DoubleField == 0.0

    ob.DoubleField = 1.7976931348623157e308
    assert ob.DoubleField == 1.7976931348623157e308

    ob.DoubleField = -1.7976931348623157e308
    assert ob.DoubleField == -1.7976931348623157e308

    ob.DoubleField = System.Double(1.7976931348623157e308)
    assert ob.DoubleField == 1.7976931348623157e308

    ob.DoubleField = System.Double(-1.7976931348623157e308)
    assert ob.DoubleField == -1.7976931348623157e308

    with pytest.raises(TypeError):
        ConversionTest().DoubleField = "spam"

    with pytest.raises(TypeError):
        ConversionTest().DoubleField = None

def test_decimal_conversion():
    """Test decimal conversion."""
    from System import Decimal

    max_d = Decimal.Parse("79228162514264337593543950335")
    min_d = Decimal.Parse("-79228162514264337593543950335")

    assert Decimal.ToInt64(Decimal(10)) == 10

    ob = ConversionTest()
    assert ob.DecimalField == Decimal(0)

    ob.DecimalField = Decimal(10)
    assert ob.DecimalField == Decimal(10)

    ob.DecimalField = Decimal.One
    assert ob.DecimalField == Decimal.One

    ob.DecimalField = Decimal.Zero
    assert ob.DecimalField == Decimal.Zero

    ob.DecimalField = max_d
    assert ob.DecimalField == max_d

    ob.DecimalField = min_d
    assert ob.DecimalField == min_d

    with pytest.raises(TypeError):
        ConversionTest().DecimalField = None

    with pytest.raises(TypeError):
        ConversionTest().DecimalField = "spam"

    with pytest.raises(TypeError):
        ConversionTest().DecimalField = 1

def test_string_conversion():
    """Test string / unicode conversion."""
    ob = ConversionTest()

    assert ob.StringField == "spam"
    assert ob.StringField == u"spam"

    ob.StringField = "eggs"
    assert ob.StringField == "eggs"
    assert ob.StringField == u"eggs"

    ob.StringField = u"spam"
    assert ob.StringField == "spam"
    assert ob.StringField == u"spam"

    ob.StringField = u'\uffff\uffff'
    assert ob.StringField == u'\uffff\uffff'

    ob.StringField = System.String("spam")
    assert ob.StringField == "spam"
    assert ob.StringField == u"spam"

    ob.StringField = System.String(u'\uffff\uffff')
    assert ob.StringField == u'\uffff\uffff'

    ob.StringField = None
    assert ob.StringField is None

    with pytest.raises(TypeError):
        ConversionTest().StringField = 1

    world = UnicodeString()
    test_unicode_str = u"안녕"
    assert test_unicode_str == str(world.value)
    assert test_unicode_str == str(world.GetString())
    assert test_unicode_str == str(world)

def test_interface_conversion():
    """Test interface conversion."""
    from Python.Test import Spam, ISpam

    ob = ConversionTest()

    assert ISpam(ob.SpamField).GetValue() == "spam"
    assert ob.SpamField.GetValue() == "spam"

    ob.SpamField = Spam("eggs")
    assert ISpam(ob.SpamField).GetValue() == "eggs"
    assert ob.SpamField.GetValue() == "eggs"

    # need to test spam subclass here.

    ob.SpamField = None
    assert ob.SpamField is None

    with pytest.raises(TypeError):
        ob = ConversionTest()
        ob.SpamField = System.String("bad")

    with pytest.raises(TypeError):
        ob = ConversionTest()
        ob.SpamField = System.Int32(1)

def test_object_conversion():
    """Test ob conversion."""
    from Python.Test import Spam

    ob = ConversionTest()
    assert ob.ObjectField is None

    ob.ObjectField = Spam("eggs")
    assert ob.ObjectField.__class__.__name__ == "Spam"
    assert ob.ObjectField.GetValue() == "eggs"

    ob.ObjectField = None
    assert ob.ObjectField is None

    ob.ObjectField = System.String("spam")
    assert ob.ObjectField == "spam"

    ob.ObjectField = System.Int32(1)
    assert ob.ObjectField == 1

    # need to test subclass here

    class Foo(object):
        pass
    ob.ObjectField = Foo
    assert ob.ObjectField == Foo

    class PseudoSeq:
        def __getitem__(self, idx):
           return 0

    ob.ObjectField = PseudoSeq()
    assert ob.ObjectField.__class__.__name__ == "PseudoSeq"

def test_null_conversion():
    """Test null conversion."""
    import System

    ob = ConversionTest()

    ob.StringField = None
    assert ob.StringField is None

    ob.ObjectField = None
    assert ob.ObjectField is None

    ob.SpamField = None
    assert ob.SpamField is None

    pi = 22/7
    assert ob.Echo[System.Double](pi) == pi
    assert ob.Echo[System.DateTime](None) is None

    # Primitive types and enums should not be set to null.

    with pytest.raises(TypeError):
        ConversionTest().Int32Field = None

    with pytest.raises(TypeError):
        ConversionTest().EnumField = None

def test_byte_array_conversion():
    """Test byte array conversion."""
    ob = ConversionTest()

    assert ob.ByteArrayField is None

    ob.ByteArrayField = [0, 1, 2, 3, 4]
    array = ob.ByteArrayField
    assert len(array) == 5
    assert array[0] == 0
    assert array[4] == 4

    value = b"testing"
    ob.ByteArrayField = value
    array = ob.ByteArrayField
    for i, _ in enumerate(value):
        assert array[i] == operator.getitem(value, i)

def test_sbyte_array_conversion():
    """Test sbyte array conversion."""
    ob = ConversionTest()

    assert ob.SByteArrayField is None

    ob.SByteArrayField = [0, 1, 2, 3, 4]
    array = ob.SByteArrayField
    assert len(array) == 5
    assert array[0] == 0
    assert array[4] == 4

    value = b"testing"
    ob.SByteArrayField = value
    array = ob.SByteArrayField
    for i, _ in enumerate(value):
        assert array[i] == operator.getitem(value, i)

def test_codecs():
    """Test codec registration from Python"""
    class ListAsRawEncoder(RawProxyEncoder):
        __namespace__ = "Python.Test"
        def CanEncode(self, clr_type):
            return clr_type.Name == "List`1" and clr_type.Namespace == "System.Collections.Generic"

    list_raw_encoder = ListAsRawEncoder()
    PyObjectConversions.RegisterEncoder(list_raw_encoder)

    ob = ConversionTest()

    l = ob.ListField
    l.Add(42)
    assert ob.ListField.Count == 1

    CodecResetter.Reset()

def test_int_param_resolution_required():
    """Test resolution of `int` parameters when resolution is needed"""

    mri = MethodResolutionInt()
    data = list(mri.MethodA(0x1000, 10))
    assert len(data) == 10
    assert data[0] == 0

    data = list(mri.MethodA(0x100000000, 10))
    assert len(data) == 10
    assert data[0] == 0

def test_iconvertible_conversion():
    change_type = System.Convert.ChangeType

    assert 1024 == change_type(1024, System.Int32)
    assert 1024 == change_type(1024, System.Int64)
    assert 1024 == change_type(1024, System.Int16)

def test_intptr_construction():
    from System import IntPtr, UIntPtr, Int64, UInt64
    from ctypes import sizeof, c_void_p

    ptr_size = sizeof(c_void_p)
    max_intptr = 2 ** (ptr_size * 8 - 1) - 1
    min_intptr = -max_intptr - 1
    max_uintptr = 2 ** (ptr_size * 8) - 1
    min_uintptr = 0

    ob = ConversionTest()

    assert ob.IntPtrField == IntPtr.Zero
    assert ob.UIntPtrField == UIntPtr.Zero

    for v in [0, -1, 1024, max_intptr, min_intptr]:
        ob.IntPtrField = IntPtr(Int64(v))
        assert ob.IntPtrField == IntPtr(v)
        assert ob.IntPtrField.ToInt64() == v

    for v in [min_intptr - 1, max_intptr + 1]:
        with pytest.raises(OverflowError):
            IntPtr(v)

    for v in [0, 1024, min_uintptr, max_uintptr, max_intptr]:
        ob.UIntPtrField = UIntPtr(UInt64(v))
        assert ob.UIntPtrField == UIntPtr(v)
        assert ob.UIntPtrField.ToUInt64() == v

    for v in [min_uintptr - 1, max_uintptr + 1, min_intptr]:
        with pytest.raises(OverflowError):
            UIntPtr(v)

def test_explicit_conversion():
    from operator import index
    from System import (
        Int64, UInt64, Int32, UInt32, Int16, UInt16, Byte, SByte, Boolean
    )
    from System import Double, Single

    assert int(Boolean(False)) == 0
    assert int(Boolean(True)) == 1

    for t in [UInt64, UInt32, UInt16, Byte]:
        assert index(t(127)) == 127
        assert int(t(127)) == 127
        assert float(t(127)) == 127.0

    for t in [Int64, Int32, Int16, SByte]:
        assert index(t(127)) == 127
        assert index(t(-127)) == -127
        assert int(t(127)) == 127
        assert int(t(-127)) == -127
        assert float(t(127)) == 127.0
        assert float(t(-127)) == -127.0

    assert int(Int64(Int64.MaxValue)) == 2**63 - 1
    assert int(Int64(Int64.MinValue)) == -2**63
    assert int(UInt64(UInt64.MaxValue)) == 2**64 - 1

    for t in [Single, Double]:
        assert float(t(0.125)) == 0.125
        assert int(t(123.4)) == 123
        with pytest.raises(TypeError):
            index(t(123.4))


text:
from mimetypes import types_map
import tornado.ioloop
import tornado.web
import numpy as np
import json
import time
import cv2
import sys
import os

class Experiment():

    TRIALS = 500
    NAME = 'R0_500_jpg'
    OUT_FMT = time.strftime('%Y_%m_%d')+'_{}_x{}_{}x{}.json'

    MEGABYTE = 1024**2

    # Whether to use real data or noise
    FILE_NAME = "/n/coxfs01/thejohnhoffer/R0/images/256_2_2_raw/00007.jpg"
    NOISE = False

    def __init__(self, _shape, _dtype, _levels, _tiles, _output):
        self._shape = _shape
        self._dtype = _dtype
        self._levels = _levels
        self._tiles = _tiles
        # Record number of steps
        n_tiles = len(_tiles)
        self._steps = self.TRIALS * n_tiles
        self._step = 0
        # Make the output filename
        out_file = self.OUT_FMT.format(self.NAME, _tiles[0], *_shape)
        self._output = os.path.join(_output, out_file)
        # Make an array to store the results
        self._results = [[] for i in range(n_tiles)]
        # Create new images
        self.new_images()

    @property
    def tile_id(self):
        # Get the tile id for this step
        n_tiles = len(self._tiles)
        return self._step % n_tiles

    def get_tile(self):
        # Get the tile id for this step
        return self._tiles[self.tile_id]

    def save_data(self, _results):
        # Get the bytes per each voxel
        voxel_bytes = np.iinfo(self._dtype).bits // 8
        # Get the total mebibytes of the slice
        full_bytes = voxel_bytes * np.prod(self._shape)
        full_mb = int(full_bytes / self.MEGABYTE)

        # Get the mean of the trials
        mean_times = np.mean(_results, 1)
        # Get the mean and all of the rates
        mean_rates = full_mb / mean_times
        all_rates = full_mb / np.array(_results)
        # Combine all the constants together
        output = {
            'mean_times': mean_times.tolist(),
            'mean_rates': mean_rates.tolist(),
            'all_rates': all_rates.tolist(),
            'all_times': _results,
            'tiles': self._tiles,
            'shape': self._shape,
            'levels': self._levels,
            'dtype': np.dtype(self._dtype).name,
        }
        # Write the model to json
        with open(self._output, 'w') as fd:
            json.dump(output, fd, indent=4)
        # Notify
        msg = """Done!
    Wrote {}
        """.format(self._output)
        print(msg)

    def add_step(self, _time):
        # Add time to results
        self.add_time(_time)
        # Move to the next steep
        if self._step + 1 < self._steps:
            self._step += 1
            command = "continue"
        else:
            # Save the data
            self.save_data(self._results)
            # Reset the step count
            self._step = 0
            # Kill the program
            command = "stop"
        # Create new images
        self.new_images()
        return command

    def add_time(self, time):
        # Milliseconds to seconds
        seconds = float(time) / 1000.0
        # Add the time to the results
        self._results[self.tile_id].append(seconds)

    def add_server(self, _server):
        self._server = _server

    # Create all the images
    def new_images(self):
        """ Make a volume for each resolution
        """
        vols = []
        # Get all variables
        _shape = self._shape
        _dtype = self._dtype
        _levels = self._levels
        _tile = self.get_tile()
        # Noise max value
        dmax = np.iinfo(_dtype).max
        # Define grid by even multiple of tiles
        _grid = np.floor_divide(_shape, _tile)
        # Square the tile dimensions
        tile_shape = (_tile,) * 2
        # Add a volume for each resolution
        for level in range(_levels):
            # Get the scale
            scale = 2**level
            # Double the number of tiles per scale
            scale_grid = np.floor_divide(_grid, scale)
            # Make a volume stack of all tiles
            full_shape = np.r_[scale_grid, tile_shape]
            #
            # Make random noise
            #
            if self.NOISE:
                # Get name of data type used to make noise
                dname = np.dtype(_dtype).name
                msg = """Making {} of {} noise... for scale {}"""
                print msg.format(full_shape, dname, level)

                # Create all tiles for the random noise
                scaled_vol = np.random.randint(0, dmax, full_shape, _dtype)
            #
            # Load from a file
            #
            else:
                # Get name of data type used to load image
                dname = np.dtype(_dtype).name
                msg = """Loading {} of {} image... for scale {}"""
                print msg.format(full_shape, dname, level)

                # Load from the file
                raw_image = cv2.imread(self.FILE_NAME, 0)
                # Convert to correct size and crop
                base_image  = _dtype(raw_image[:_shape[0], :_shape[1]])
                # Halve the image resolution per scale
                scaled_image = base_image[::scale, ::scale]

                # Reshape the image into tiles
                scaled_vol = np.zeros(full_shape, dtype=_dtype)
                # Format all the tiles
                for ty in range(scale_grid[0]):
                    for tx in range(scale_grid[1]):
                        # Get coordinates from image
                        y0, y1 = tile_shape[0] * np.uint64([ty, ty+1])
                        x0, x1 = tile_shape[1] * np.uint64([tx, tx+1])
                        # Add subvolume to tile list
                        scaled_vol[ty,tx] = scaled_image[y0:y1,x0:x1]

            # Add the volume to the list of all resolutions
            vols.append(scaled_vol)

        # Return all volumes
        self._images = vols

class ExperimentHandler(tornado.web.RequestHandler):

    @property
    def _tile(self):
        return self._exp.get_tile()

    @property
    def _shape(self):
        return self._exp._shape

    @property
    def _dtype(self):
        return self._exp._dtype

    @property
    def _levels(self):
        return self._exp._levels

    @property
    def _images(self):
        return self._exp._images

    @property
    def _tile_shape(self):
        return self._images[0].shape[2:]

    def set_extra_headers(self, path):
        # Disable cache
        self.set_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')

class ImageHandler(ExperimentHandler):

    # Tile constants
    SCALE = ("scale", 0)
    X = ("x", 0)
    Y = ("y", 0)

    IMAGE_TYPE = ".jpg"

    # Boot constants
    REBOOT_TYPE = ".txt"
    TIME = ("time", 0)

    def initialize(self, _exp):
        # Store the expriment
        self._exp = _exp

    def get(self, request):
        # Reboot server
        if request == 'reboot':
            # Set the mime type
            mime = types_map.get(self.REBOOT_TYPE)
            # Save the given time
            time = self.get_int_query(*self.TIME)
            # Load images for the next step
            result = self._exp.add_step(time)
        # Get a tile
        else:
            # Set the mime type
            mime = types_map.get(self.IMAGE_TYPE)
            # Give the requested tile
            result = self.parse_tile()
        # Set mime type
        self.set_header("Content-Type", mime)
        # Write result
        self.write(result)

    def parse_tile(self):
        """ Get a tile at a scaled X,Y offset
        """
        # Get the tile size and scale
        tile_scale = self.get_int_query(*self.SCALE)
        # Get the x and y offsets
        x_offset = self.get_int_query(*self.X)
        y_offset = self.get_int_query(*self.Y)

        # Log the currently loading tile
        msg = """Loading a {}px tile at {},{}
        at resolution {}
        """.format(self._tile_shape, y_offset, x_offset, tile_scale)
        #print(msg)

        # Get the tile from the matrix
        tile = self._images[tile_scale][y_offset, x_offset, :, :]
        # Return the tile as an image
        image = cv2.imencode(self.IMAGE_TYPE, tile)
        return image[1].tostring()

    def get_int_query(self, name, default):
        """ Get integer argument from query string
        """
        result = self.get_query_argument(name, default)
        try:
            return int(result)
        except (TypeError, ValueError):
            msg = """
            The {} {} is not an integer.
            """.format(name, result)
            raise tornado.web.HTTPError(400, msg)

class HTMLHandler(ExperimentHandler):

    def initialize(self, _exp, _path, _hide):
        """ Prepare to render HTML paths
        """
        # Store experiment and path
        self._exp = _exp
        self._path = _path
        # Should hide drawing?
        self._hide = _hide

    def get(self, request):
        if not request:
            request = 'index.html'
        # Join request to parent path
        path = os.path.join(self._path, request)
        # Render the html page
        keywords = {
            'HIDE': self._hide,
            'TILE_WIDTH': self._tile,
            'FULL_WIDTH': self._shape[1],
            'FULL_HEIGHT': self._shape[0],
            'MAX_LEVEL': self._levels - 1,
            'TIME': int(time.time() * 1000),
        }
        self.render(path, **keywords)

def start_server(_port, _shape, _tile, _dtype, _levels, _output, _hide):

    # Test all possible tile sizes
    min_max = np.log2([_tile, min(*_shape)])+[0, 2-_levels]
    # Create a range of tiles
    tiles = np.uint64(2**np.arange(*min_max)).tolist()

    # Create the experiment
    experiment = Experiment(_shape, _dtype, _levels, tiles, _output)

    # Serve images
    image_info = {
        "_exp": experiment,
    }
    # Serve HTML templates
    html_info = {
        "_path": os.path.join(os.getcwd(),"view"),
        "_hide": str(int(_hide)),
        "_exp": experiment,
    }
    # Serve static files
    static_info = {
        "path": os.path.join(os.getcwd(),"view"),
    }
    # Define the Web App
    web_app = tornado.web.Application([
        (r"/?()", HTMLHandler, html_info),
        (r"/(.*\.html)", HTMLHandler, html_info),
        (r"/(tile)/?.*", ImageHandler, image_info),
        (r"/(reboot)/?.*", ImageHandler, image_info),
        (r"/(.*)", tornado.web.StaticFileHandler, static_info),
    ], autoreload=True)

    # Start the Web App
    web_app.listen(_port)
    print "serving on port {}".format(_port)
    tornado.ioloop.IOLoop.current().start()

if __name__ == "__main__":

    PORT = 8487
    SHAPE = [2**12, 2**12]
    TILE = 2**9
    DTYPE = np.uint8
    LEVELS = 1

    # Should hide drawing?
    HIDE = True

    # Results directory
    OUTPUT = '/n/coxfs01/thejohnhoffer/web_test/'

    # End if shape less than tile
    if min(*SHAPE) < TILE:
        msg = """
        Cannot divide {} into tiles of {}
        """.format(SHAPE, TILE)
        print msg
        sys.exit()
    # Make sure there aren't too many levels
    max_level = int(np.log2(min(*SHAPE) / TILE) + 1)
    # Negative of zero less than max level
    if LEVELS <= 0:
        LEVELS += max_level
    # Level may never be greater than max
    LEVELS = np.clip(LEVELS, 1, max_level)

    # Start the server
    start_server(PORT, SHAPE, TILE, DTYPE, LEVELS, OUTPUT, HIDE)


text:
import {
  beforeEach,
  describe,
  it,
} from '@bigtest/mocha';
import { expect } from 'chai';

import setupApplication from '../helpers/setup-application';
import UserFormPage from '../interactors/user-form-page';

describe('Service points modal', () => {
  setupApplication({
    interfaces: {
      'service-points-users': '1.0',
    }
  });

  describe('visit user edit page', () => {
    beforeEach(async function () {
      const user = this.server.create('user');
      const sp = this.server.create('service-point');
      this.server.create('service-point');
      this.server.create('service-points-user', {
        userId: user.id,
        servicePointsIds: [sp.id],
      });
      this.visit(`/users/${user.id}/edit`);
      await UserFormPage.whenLoaded();
    });

    describe('when expanding the service points accordion', () => {
      beforeEach(async () => {
        await UserFormPage.toggleSPAccordionButton.click();
      });

      it('1 service point should be displayed', () => {
        expect(UserFormPage.servicePoints().length).to.equal(1);
      });

      it('add service points button should be present', () => {
        expect(UserFormPage.addServicePointButton.isPresent).to.be.true;
      });

      describe('clicking the add service points button', () => {
        beforeEach(async function () {
          await UserFormPage.addServicePointButton.click();
        });

        it('service point modal should be present', () => {
          expect(UserFormPage.servicePointsModal.isPresent).to.be.true;
        });

        it('1 service point should be checked', () => {
          expect(UserFormPage.servicePointsModal.checkBoxes(0).isChecked).to.be.false;
          expect(UserFormPage.servicePointsModal.checkBoxes(1).isChecked).to.be.true;
          expect(UserFormPage.servicePointsModal.checkBoxes(2).isChecked).to.be.false;
        });

        describe('when adding all service points', () => {
          beforeEach(async function () {
            await UserFormPage.servicePointsModal.checkBoxes(0).clickInput();
            await UserFormPage.servicePointsModal.saveButton.click();
          });

          it('2 service points should be displayed', () => {
            expect(UserFormPage.servicePoints().length).to.equal(2);
          });

          describe('when unchecking all service points', () => {
            beforeEach(async function () {
              await UserFormPage.addServicePointButton.click();
              await UserFormPage.servicePointsModal.checkBoxes(1).clickInput();
              await UserFormPage.servicePointsModal.checkBoxes(2).clickInput();
              await UserFormPage.servicePointsModal.saveButton.click();
            });

            it('service points should not be displayed', () => {
              expect(UserFormPage.servicePoints().length).to.equal(0);
            });
          });

          describe('when deleting all service points', () => {
            beforeEach(async function () {
              await UserFormPage.servicePoints(1).deleteServicePoint();
              await UserFormPage.servicePoints(0).deleteServicePoint();
            });

            it('service points should not be displayed', () => {
              expect(UserFormPage.servicePoints().length).to.equal(0);
            });

            describe('when opening service points modal', () => {
              beforeEach(async function () {
                await UserFormPage.addServicePointButton.click();
              });

              it('service points should not be checked', () => {
                expect(UserFormPage.servicePointsModal.checkBoxes(0).isChecked).to.be.false;
                expect(UserFormPage.servicePointsModal.checkBoxes(1).isChecked).to.be.false;
                expect(UserFormPage.servicePointsModal.checkBoxes(2).isChecked).to.be.false;
              });
            });
          });
        });
      });
    });
  });
});


text:
This gem wraps the [Andular.js](http://angularjs.org/) library for use in Padrino and above.

## Installation

Add this line to your application's Gemfile:

    gem 'padrino-angularjs'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install padrino-angularjs

## Usage

Install Angular.js library for your app:

    $ padrino g angularjs_install

Options|Default|Aliases|Description
-------|-------|-------|-----------
root   |.      |-r     |specify the root destination path
app    |/app   |-a     |specify the application
destroy|false  |-d     |removes all generated files

You'll be ready to go!

If you require optional angular files, you may include them as well in your Javascript manifest file (*app*/assets/javascripts/application.js)
For example:

    //= require angular-resource

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
if [ $# -lt 1 ]; then
  echo "usage: $0 [ronpaulcoin srcroot] build-test arguments..."
fi

cd $1
shift

./autogen.sh
./configure
./qa/pull-tester/build-tests.sh "$@"


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Projinfocuspage extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function __construct()
    {
            parent::__construct();
            $this->load->helper(array('form', 'url'));
            $this->load->library('upload');
            $this->load->model('projinfocus_model');
    }

	public function index()
	{
		$this->data['type']='list';
		$this->data['menu_status']='proj_in_focus';
		$this->data['content']='projinfocuspage/index.php';

		$data2=$this->projinfocus_model->selectProjFocusAll();
		// echo "<pre>"; print_r($data2);

		$allregions=$this->projinfocus_model->selectProjFocusRegion();
		//echo "<pre>"; print_r($allregions);

		$this->data['allregions']=$allregions;

		$this->data['data']=$data2;
		$this->load->view('index', $this->data);
	}

	public function add()
	{
			$data2=$this->projinfocus_model->selectActiveProjFocusRegion();

			$this->data['data']=$data2;
			$this->data['type']='form';
			$this->data['menu_status']='proj_in_focus';
			$this->data['content']='projinfocuspage/add.php';
			$this->load->view('index', $this->data);
	}

	public function edit($id)
	{
		if(!empty($this->input->post('link')))
		{
            $data2['link']=trim($this->input->post('link'));
            $data2['venue']=trim($this->input->post('venue'));
            $data2['description']=trim($this->input->post('description'));
            $data2['region']=trim($this->input->post('region'));
            $data2['sequence']=trim($this->input->post('sequence'));
            $data2['status']=trim($this->input->post('status'));

            $this->projinfocus_model->updateAllProjinFocus($id,$data2);
            redirect('projinfocuspage');
		}
		else{

			$data2=$this->projinfocus_model->selectAllProjinFocusbyId($id);
			$dataRegions=$this->projinfocus_model->selectActiveProjFocusRegion();

			$this->data['dataregions']=$dataRegions;
			//echo "<pre>";print_r($this->data['dataregions']);
			//die;
			$this->data['data']=array(
						'link'   	 => trim($data2[0]['link']),
						'venue'   	 => trim($data2[0]['venue']),
						'description'=> trim($data2[0]['description']),
						'region'     => trim($data2[0]['region']),
						'sequence'   => trim($data2[0]['sequence']),
						'status'  	 => trim($data2[0]['status'])
						);
			$this->data['type']='form';
			$this->data['menu_status']='proj_in_focus';
			$this->data['content']='projinfocuspage/edit.php';
			$this->load->view('index', $this->data);
		}

	}

	public function delete($id)
	{
		$data2['status']=0;
		$this->projinfocus_model->removeProjinFocusall($id, $data2);
		redirect('projinfocuspage');
	}
}


text:
'use strict';

var util = require('util');

var models = require('./index');

/**
 * @class
 * Initializes a new instance of the Usage class.
 * @constructor
 */
function Usage() { }

/**
 * Validate the payload against the Usage schema
 *
 * @param {JSON} payload
 *
 */
Usage.prototype.validate = function (payload) {
  if (!payload) {
    throw new Error('Usage cannot be null.');
  }
  if (payload['unit']) {
    var allowedValues = [ 'Count', 'Bytes', 'Seconds', 'Percent', 'CountsPerSecond', 'BytesPerSecond' ];
    if (!allowedValues.some( function(item) { return item === payload['unit']; })) {
      throw new Error(payload['unit'] + ' is not a valid value. The valid values are: ' + allowedValues);
    }
  }

  if (payload['currentValue'] !== null && payload['currentValue'] !== undefined && typeof payload['currentValue'] !== 'number') {
    throw new Error('payload[\'currentValue\'] must be of type number.');
  }

  if (payload['limit'] !== null && payload['limit'] !== undefined && typeof payload['limit'] !== 'number') {
    throw new Error('payload[\'limit\'] must be of type number.');
  }

  if (payload['name']) {
    models['UsageName'].validate(payload['name']);
  }
};

/**
 * Deserialize the instance to Usage schema
 *
 * @param {JSON} instance
 *
 */
Usage.prototype.deserialize = function (instance) {
  if (instance) {
    if (instance.name !== null && instance.name !== undefined) {
      instance.name = models['UsageName'].deserialize(instance.name);
    }
  }
  return instance;
};

module.exports = new Usage();


text:
'use strict';

/* Filters */

angular.module('jobOffersFilters', [])
    .filter('TEST', function() {
        return function(input) {
            return input;
        };
    })
    .filter('orderObjectByIntegerKey', function(){
        return function(input) {
            if (!angular.isObject(input)) return input;
            var array = [], ret = [];
            for(var objectKey in input) {
                array.push(parseInt(objectKey));
            }
            array.sort(function(a,b){return a-b;});
            for(var k=0; k<array.length; k++){
                ret.push(input[array[k]]);
            }
            return ret;
        }
    })
;


text:
<?php

$tempFiles = glob('./tmp/*');
array_map('unlink',$tempFiles);

require_once __DIR__ . '/../vendor/autoload.php'; // Autoload files using Composer autoload

$modes = Manticorp\Image::getAvailableBlendingModes();

$filename1 = __DIR__ . '/resources/trettofrappucino.png';
$filename2 = __DIR__ . '/resources/poplin_small.png';

$top = new Manticorp\Image($filename1);
$base  = new Manticorp\Image($filename2);

$top->setDimensions(300,300);
$base->setDimensions(100,100);

$output = clone $top;
$output->setOutputFn('./tmp/output-offset-multiply.png');
$output->blendWith($base, 'multiply', 1, 1, array('offsetx'=>10, 'offsety'=>10));
$output->blendWith($base, 'multiply', 1, 1, array('offsetx'=>10, 'offsety'=>110));
$output->blendWith($base, 'multiply', 1, 1, array('offsetx'=>110, 'offsety'=>10));
$output->blendWith($base, 'multiply', 1, 1, array('offsetx'=>110, 'offsety'=>110));

echo $output->getImgTag(); //

$output = clone $top;
$output->setOutputFn('./tmp/output-offset-overlay.png');
$output->blendWith($base, 'overlay', 1, 1, array('offsetx'=>10, 'offsety'=>10));
$output->blendWith($base, 'overlay', 1, 1, array('offsetx'=>10, 'offsety'=>110));
$output->blendWith($base, 'overlay', 1, 1, array('offsetx'=>110, 'offsety'=>10));
$output->blendWith($base, 'overlay', 1, 1, array('offsetx'=>110, 'offsety'=>110));

echo $output->getImgTag(); //

$output = clone $top;
$output->setOutputFn('./tmp/output-offset-hardlight.png');
$output->blendWith($base, 'hardlight', 1, 1, array('offsetx'=>10, 'offsety'=>10));
$output->blendWith($base, 'hardlight', 1, 1, array('offsetx'=>10, 'offsety'=>110));
$output->blendWith($base, 'hardlight', 1, 1, array('offsetx'=>110, 'offsety'=>10));
$output->blendWith($base, 'hardlight', 1, 1, array('offsetx'=>110, 'offsety'=>110));

echo $output->getImgTag(); //


text:
package org.eclipse.gemini.blueprint.context.support;

import org.easymock.IMocksControl;
import org.eclipse.gemini.blueprint.util.OsgiStringUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.springframework.beans.BeansException;

import java.util.Dictionary;
import java.util.Hashtable;

import static org.easymock.EasyMock.createNiceControl;
import static org.easymock.EasyMock.expect;
import static org.junit.Assert.assertEquals;

/**
 * @author Costin Leau
 */
public class AbstractBundleXmlApplicationContextTest {

    OsgiBundleXmlApplicationContext xmlContext;

    IMocksControl bundleCtxCtrl, bundleCtrl;

    BundleContext context;

    Bundle bundle;

    Dictionary dictionary;

    @Before
    public void setUp() throws Exception {
        bundleCtxCtrl = createNiceControl();
        context = bundleCtxCtrl.createMock(BundleContext.class);
        bundleCtrl = createNiceControl();
        bundle = bundleCtrl.createMock(Bundle.class);

        expect(context.getBundle()).andReturn(bundle).atLeastOnce();

        dictionary = new Hashtable();

        // allow headers to be taken multiple times
        expect(bundle.getHeaders()).andReturn(dictionary).atLeastOnce();
    }

    private void createContext() {
        xmlContext = new OsgiBundleXmlApplicationContext(new String[]{}) {
            public void refresh() throws BeansException {
                // no-op
            }
        };
        xmlContext.setBundleContext(context);
    }

    @After
    public void tearDown() throws Exception {
        context = null;
        bundleCtxCtrl = null;
        xmlContext = null;
        bundle = null;
        bundleCtrl = null;
    }

    @Test
    public void testGetBundleName() {
        String symbolicName = "symbolic";
        expect(bundle.getSymbolicName()).andReturn(symbolicName).atLeastOnce();
        bundleCtxCtrl.replay();
        bundleCtrl.replay();

        // check default
        createContext();

        assertEquals(symbolicName, OsgiStringUtils.nullSafeSymbolicName(bundle));
    }

    @Test
    public void testGetBundleNameFallbackMechanism() {
        bundleCtxCtrl.replay();
        bundleCtrl.replay();

        String title = "Phat City";
        dictionary.put(Constants.BUNDLE_NAME, title);

        // check default
        createContext();

        // use the 2 symbolic name calls
        assertEquals(title, OsgiStringUtils.nullSafeName(bundle));
    }

    @Test
    public void testGetServiceName() {
        String symbolicName = "symbolic";
        expect(bundle.getSymbolicName()).andReturn(symbolicName).atLeastOnce();
        bundleCtxCtrl.replay();
        bundleCtrl.replay();

        createContext();
        assertEquals(symbolicName, OsgiStringUtils.nullSafeSymbolicName(bundle));

    }

}


text:
CKEDITOR.lang['sv'] = {
    "dir": "ltr",
    "editor": "Rich Text Editor",
    "common": {
        "editorHelp": "Tryck ALT 0 för hjälp",
        "browseServer": "Bläddra på server",
        "url": "URL",
        "protocol": "Protokoll",
        "upload": "Ladda upp",
        "uploadSubmit": "Skicka till server",
        "image": "Bild",
        "flash": "Flash",
        "form": "Formulär",
        "checkbox": "Kryssruta",
        "radio": "Alternativknapp",
        "textField": "Textfält",
        "textarea": "Textruta",
        "hiddenField": "Dolt fält",
        "button": "Knapp",
        "select": "Flervalslista",
        "imageButton": "Bildknapp",
        "notSet": "<ej angivet>",
        "id": "Id",
        "name": "Namn",
        "langDir": "Språkriktning",
        "langDirLtr": "Vänster till Höger (VTH)",
        "langDirRtl": "Höger till Vänster (HTV)",
        "langCode": "Språkkod",
        "longDescr": "URL-beskrivning",
        "cssClass": "Stilmall",
        "advisoryTitle": "Titel",
        "cssStyle": "Stilmall",
        "ok": "OK",
        "cancel": "Avbryt",
        "close": "Stäng",
        "preview": "Förhandsgranska",
        "resize": "Dra för att ändra storlek",
        "generalTab": "Allmänt",
        "advancedTab": "Avancerad",
        "validateNumberFailed": "Värdet är inte ett nummer.",
        "confirmNewPage": "Alla ändringar i innehållet kommer att förloras. Är du säker på att du vill ladda en ny sida?",
        "confirmCancel": "Några av de alternativ har ändrats. Är du säker på att stänga dialogrutan?",
        "options": "Alternativ",
        "target": "Mål",
        "targetNew": "Nytt fönster (_blank)",
        "targetTop": "Översta fönstret (_top)",
        "targetSelf": "Samma fönster (_self)",
        "targetParent": "Föregående fönster (_parent)",
        "langDirLTR": "Vänster till höger (LTR)",
        "langDirRTL": "Höger till vänster (RTL)",
        "styles": "Stil",
        "cssClasses": "Stilmallar",
        "width": "Bredd",
        "height": "Höjd",
        "align": "Justering",
        "alignLeft": "Vänster",
        "alignRight": "Höger",
        "alignCenter": "Centrerad",
        "alignTop": "Överkant",
        "alignMiddle": "Mitten",
        "alignBottom": "Nederkant",
        "invalidValue": "Felaktigt värde.",
        "invalidHeight": "Höjd måste vara ett nummer.",
        "invalidWidth": "Bredd måste vara ett nummer.",
        "invalidCssLength": "Värdet för fältet \"%1\" måste vara ett positivt nummer med eller utan CSS-mätenheter (px, %, in, cm, mm, em, ex, pt, eller pc).",
        "invalidHtmlLength": "rdet för fältet \"%1\" måste vara ett positivt nummer med eller utan godkända HTML-mätenheter (px eller %).",
        "invalidInlineStyle": "Det angivna värdet för style måste innehålla en eller flera tupler separerade med semikolon i följande format: \"name : value\"",
        "cssLengthTooltip": "Ange ett nummer i pixlar eller ett nummer men godkänd CSS-mätenhet (px, %, in, cm, mm, em, ex, pt, eller pc).",
        "unavailable": "%1, Ej tillgänglig"
    },
    "about": {
        "copy": "Copyright © $1. Alla rättigheter reserverade.",
        "dlgTitle": "Om CKEditor",
        "help": "Se $1 för hjälp.",
        "moreInfo": "För information av licenciering besök vår hemsida:",
        "title": "Om CKEditor",
        "userGuide": "CKEditor User's Guide"
    },
    "basicstyles": {
        "bold": "Fet",
        "italic": "Kursiv",
        "strike": "Genomstruken",
        "subscript": "Nedsänkta tecken",
        "superscript": "Upphöjda tecken",
        "underline": "Understruken"
    },
    "blockquote": {"toolbar": "Blockcitat"},
    "clipboard": {
        "copy": "Kopiera",
        "copyError": "Säkerhetsinställningar i Er webläsare tillåter inte åtgården Kopiera. Använd (Ctrl/Cmd+C) istället",
        "cut": "Klipp ut",
        "cutError": "Säkerhetsinställningar i Er webläsare tillåter inte åtgården Klipp ut. Använd (Ctrl/Cmd+X) istället.",
        "paste": "Klistra in",
        "pasteArea": "Paste Area",
        "pasteMsg": "Var god och klistra in Er text i rutan nedan genom att använda (Ctrl/Cmd+V) klicka sen på OK.",
        "securityMsg": "På grund av din webbläsares säkerhetsinställningar kan verktyget inte få åtkomst till urklippsdatan. Var god och använd detta fönster istället.",
        "title": "Klistra in"
    },
    "contextmenu": {"options": "Context Menu Options"},
    "toolbar": {
        "toolbarCollapse": "Dölj verktygsfält",
        "toolbarExpand": "Visa verktygsfält",
        "toolbarGroups": {
            "document": "Document",
            "clipboard": "Clipboard/Undo",
            "editing": "Editing",
            "forms": "Forms",
            "basicstyles": "Basic Styles",
            "paragraph": "Paragraph",
            "links": "Links",
            "insert": "Insert",
            "styles": "Styles",
            "colors": "Colors",
            "tools": "Tools"
        },
        "toolbars": "Redigera verktygsfält"
    },
    "elementspath": {"eleLabel": "Elementets sökväg", "eleTitle": "%1 element"},
    "format": {
        "label": "Teckenformat",
        "panelTitle": "Teckenformat",
        "tag_address": "Adress",
        "tag_div": "Normal (DIV)",
        "tag_h1": "Rubrik 1",
        "tag_h2": "Rubrik 2",
        "tag_h3": "Rubrik 3",
        "tag_h4": "Rubrik 4",
        "tag_h5": "Rubrik 5",
        "tag_h6": "Rubrik 6",
        "tag_p": "Normal",
        "tag_pre": "Formaterad"
    },
    "horizontalrule": {"toolbar": "Infoga horisontal linje"},
    "image": {
        "alertUrl": "Var god och ange bildens URL",
        "alt": "Alternativ text",
        "border": "Kant",
        "btnUpload": "Skicka till server",
        "button2Img": "Vill du omvandla den valda bildknappen på en enkel bild?",
        "hSpace": "Horis. marginal",
        "img2Button": "Vill du omvandla den valda bildknappen på en enkel bild?",
        "infoTab": "Bildinformation",
        "linkTab": "Länk",
        "lockRatio": "Lås höjd/bredd förhållanden",
        "menu": "Bildegenskaper",
        "resetSize": "Återställ storlek",
        "title": "Bildegenskaper",
        "titleButton": "Egenskaper för bildknapp",
        "upload": "Ladda upp",
        "urlMissing": "Bildkällans URL saknas.",
        "vSpace": "Vert. marginal",
        "validateBorder": "Kantlinje måste vara ett heltal.",
        "validateHSpace": "HSpace måste vara ett heltal.",
        "validateVSpace": "VSpace måste vara ett heltal."
    },
    "indent": {"indent": "Öka indrag", "outdent": "Minska indrag"},
    "fakeobjects": {
        "anchor": "Ankare",
        "flash": "Flashanimation",
        "hiddenfield": "Gömt fält",
        "iframe": "iFrame",
        "unknown": "Okänt objekt"
    },
    "link": {
        "acccessKey": "Behörighetsnyckel",
        "advanced": "Avancerad",
        "advisoryContentType": "Innehållstyp",
        "advisoryTitle": "Titel",
        "anchor": {
            "toolbar": "Infoga/Redigera ankarlänk",
            "menu": "Egenskaper för ankarlänk",
            "title": "Egenskaper för ankarlänk",
            "name": "Ankarnamn",
            "errorName": "Var god ange ett ankarnamn",
            "remove": "Radera ankare"
        },
        "anchorId": "efter objektid",
        "anchorName": "efter ankarnamn",
        "charset": "Teckenuppställning",
        "cssClasses": "Stylesheet class",
        "emailAddress": "E-postadress",
        "emailBody": "Innehåll",
        "emailSubject": "Ämne",
        "id": "Id",
        "info": "Länkinformation",
        "langCode": "Språkriktning",
        "langDir": "Språkriktning",
        "langDirLTR": "Vänster till höger (VTH)",
        "langDirRTL": "Höger till vänster (HTV)",
        "menu": "Redigera länk",
        "name": "Namn",
        "noAnchors": "(Inga ankare kunde hittas)",
        "noEmail": "Var god ange E-postadress",
        "noUrl": "Var god ange länkens URL",
        "other": "<annan>",
        "popupDependent": "Beroende (endast Netscape)",
        "popupFeatures": "Popup-fönstrets egenskaper",
        "popupFullScreen": "Helskärm (endast IE)",
        "popupLeft": "Position från vänster",
        "popupLocationBar": "Adressfält",
        "popupMenuBar": "Menyfält",
        "popupResizable": "Resizable",
        "popupScrollBars": "Scrolllista",
        "popupStatusBar": "Statusfält",
        "popupToolbar": "Verktygsfält",
        "popupTop": "Position från sidans topp",
        "rel": "Förhållande",
        "selectAnchor": "Välj ett ankare",
        "styles": "Stilmall",
        "tabIndex": "Tabindex",
        "target": "Mål",
        "targetFrame": "<ram>",
        "targetFrameName": "Målets ramnamn",
        "targetPopup": "<popup-fönster>",
        "targetPopupName": "Popup-fönstrets namn",
        "title": "Länk",
        "toAnchor": "Ankare i sidan",
        "toEmail": "E-post",
        "toUrl": "URL",
        "toolbar": "Infoga/Redigera länk",
        "type": "Länktyp",
        "unlink": "Radera länk",
        "upload": "Ladda upp"
    },
    "list": {"bulletedlist": "Punktlista", "numberedlist": "Numrerad lista"},
    "magicline": {"title": "Infoga paragraf här"},
    "maximize": {"maximize": "Maximera", "minimize": "Minimera"},
    "pastetext": {"button": "Klistra in som vanlig text", "title": "Klistra in som vanlig text"},
    "pastefromword": {
        "confirmCleanup": "Texten du vill klistra in verkar vara kopierad från Word. Vill du rensa innan du klistrar?",
        "error": "Det var inte möjligt att städa upp den inklistrade data på grund av ett internt fel",
        "title": "Klistra in från Word",
        "toolbar": "Klistra in från Word"
    },
    "removeformat": {"toolbar": "Radera formatering"},
    "sourcearea": {"toolbar": "Källa"},
    "specialchar": {
        "options": "Special Character Options",
        "title": "Välj utökat tecken",
        "toolbar": "Klistra in utökat tecken"
    },
    "scayt": {
        "about": "Om SCAYT",
        "aboutTab": "Om",
        "addWord": "Lägg till ord",
        "allCaps": "Ignorera alla ord med enbart versaler",
        "dic_create": "Skapa",
        "dic_delete": "Ta bort",
        "dic_field_name": "Ordlistans namn",
        "dic_info": "Inledningsvis lagras ordlistan i en cookie. När ordlista växer till en punkt där det inte kan lagras i en cookie, lagras den på vår server. För att lagra din personliga ordlista på vår server du ska ange ett namn för din ordbok. Om du redan har en lagrad ordbok, skriv namnet och klicka på knappen Återställ.",
        "dic_rename": "Byt namn",
        "dic_restore": "Återställ",
        "dictionariesTab": "Ordlistor",
        "disable": "Inaktivera SCAYT",
        "emptyDic": "Ordlistans namn får ej vara tomt.",
        "enable": "Aktivera SCAYT",
        "ignore": "Ignorera",
        "ignoreAll": "Ignorera alla",
        "ignoreDomainNames": "Ignorera domännamn",
        "langs": "Språk",
        "languagesTab": "Språk",
        "mixedCase": "Ignorera ord med blandat shiftläge",
        "mixedWithDigits": "Ignorera ord med nummer",
        "moreSuggestions": "Fler förslag",
        "opera_title": "Stöds ej av Opera",
        "options": "Inställningar",
        "optionsTab": "Inställningar",
        "title": "Stavningskontroll medan du skriver",
        "toggle": "Växla SCAYT",
        "noSuggestions": "No suggestion"
    },
    "stylescombo": {
        "label": "Anpassad stil",
        "panelTitle": "Formatmallar",
        "panelTitle1": "Blockstil",
        "panelTitle2": "Inbäddad stil",
        "panelTitle3": "Objektets stil"
    },
    "table": {
        "border": "Kantstorlek",
        "caption": "Rubrik",
        "cell": {
            "menu": "Cell",
            "insertBefore": "Lägg till cell före",
            "insertAfter": "Lägg till cell efter",
            "deleteCell": "Radera celler",
            "merge": "Sammanfoga celler",
            "mergeRight": "Sammanfoga höger",
            "mergeDown": "Sammanfoga ner",
            "splitHorizontal": "Dela cell horisontellt",
            "splitVertical": "Dela cell vertikalt",
            "title": "Egenskaper för cell",
            "cellType": "Celltyp",
            "rowSpan": "Rad spann",
            "colSpan": "Kolumnen spann",
            "wordWrap": "Radbrytning",
            "hAlign": "Horisontell justering",
            "vAlign": "Vertikal justering",
            "alignBaseline": "Baslinje",
            "bgColor": "Bakgrundsfärg",
            "borderColor": "Ramfärg",
            "data": "Data",
            "header": "Rubrik",
            "yes": "Ja",
            "no": "Nej",
            "invalidWidth": "Cellens bredd måste vara ett nummer.",
            "invalidHeight": "Cellens höjd måste vara ett nummer.",
            "invalidRowSpan": "Radutvidgning måste vara ett heltal.",
            "invalidColSpan": "Kolumn måste vara ett heltal.",
            "chooseColor": "Välj"
        },
        "cellPad": "Cellutfyllnad",
        "cellSpace": "Cellavstånd",
        "column": {
            "menu": "Kolumn",
            "insertBefore": "Lägg till kolumn före",
            "insertAfter": "Lägg till kolumn efter",
            "deleteColumn": "Radera kolumn"
        },
        "columns": "Kolumner",
        "deleteTable": "Radera tabell",
        "headers": "Rubriker",
        "headersBoth": "Båda",
        "headersColumn": "Första kolumnen",
        "headersNone": "Ingen",
        "headersRow": "Första raden",
        "invalidBorder": "Ram måste vara ett nummer.",
        "invalidCellPadding": "Luft i cell måste vara ett nummer.",
        "invalidCellSpacing": "Luft i cell måste vara ett nummer.",
        "invalidCols": "Antal kolumner måste vara ett nummer större än 0.",
        "invalidHeight": "Tabellens höjd måste vara ett nummer.",
        "invalidRows": "Antal rader måste vara större än 0.",
        "invalidWidth": "Tabell måste vara ett nummer.",
        "menu": "Tabellegenskaper",
        "row": {
            "menu": "Rad",
            "insertBefore": "Lägg till rad före",
            "insertAfter": "Lägg till rad efter",
            "deleteRow": "Radera rad"
        },
        "rows": "Rader",
        "summary": "Sammanfattning",
        "title": "Tabellegenskaper",
        "toolbar": "Tabell",
        "widthPc": "procent",
        "widthPx": "pixlar",
        "widthUnit": "enhet bredd"
    },
    "undo": {"redo": "Gör om", "undo": "Ångra"},
    "wsc": {
        "btnIgnore": "Ignorera",
        "btnIgnoreAll": "Ignorera alla",
        "btnReplace": "Ersätt",
        "btnReplaceAll": "Ersätt alla",
        "btnUndo": "Ångra",
        "changeTo": "Ändra till",
        "errorLoading": "Tjänsten är ej tillgänglig: %s.",
        "ieSpellDownload": "Stavningskontrollen är ej installerad. Vill du göra det nu?",
        "manyChanges": "Stavningskontroll slutförd: %1 ord rättades.",
        "noChanges": "Stavningskontroll slutförd: Inga ord rättades.",
        "noMispell": "Stavningskontroll slutförd: Inga stavfel påträffades.",
        "noSuggestions": "- Förslag saknas -",
        "notAvailable": "Tyvärr är tjänsten ej tillgänglig nu",
        "notInDic": "Saknas i ordlistan",
        "oneChange": "Stavningskontroll slutförd: Ett ord rättades.",
        "progress": "Stavningskontroll pågår...",
        "title": "Kontrollera stavning",
        "toolbar": "Stavningskontroll"
    }
};


text:
opendata.py
from StringIO import StringIO
from zipfile import ZipFile
from urllib import urlopen
import json
import re
import string
import time

while True:

 print "open url"
 url = urlopen("http://data.geo.admin.ch.s3.amazonaws.com/ch.meteoschweiz.swissmetnet/data.zip")

 print "open zip file"
 zipfile = ZipFile(StringIO(url.read()))

#iterator
 i = 0
 index = 0

#json "file"
 output = []

#Open File
 f = open('wetterstation/wetterdaten_schweiz.json','w')

#Loop file
 for line in zipfile.open('VQHA69.txt').readlines():

     if i == 0:
        #header MeteoSchweiz / MeteoSuisse / MeteoSvizzera / MeteoSwiss
         header = line
         print header
     if i == 2:
#stn|time|tre200s0|sre000z0|rre150z0|dkl010z0|fu3010z0|pp0qnhs0|fu3010z1|ure200s0|prestas0|pp0qf
        ueberschrift = line.split('|')
        print ueberschrift
     if i > 3: #DATA
         data = line.split('|')
         d = {}

         for index, item in enumerate(data):
             key = ueberschrift[index]
             value = item

             key.rstrip()
             key.replace('\\', "")

             value.rstrip()
             value.replace('\\', "")

             print key + "/" + value
             d[key]=value

         output.append(d)

            #print json.dumps(line.split('|'))
#            print line.split('|')

     i += 1
#save to mongo db...
# f = open('wetterstation/wetterdaten_schweiz.json','w')

#print json.dumps(output, separators=(',',':'))

 f.write(json.dumps(output, ensure_ascii=False, encoding="utf-8"))
# f.write(json.dumps(output, separators=(',',':')))

 f.close()
 time.sleep(600)