text:
"""Module to compute Trotter errors in the plane-wave dual basis."""
from __future__ import absolute_import

import numpy

from openfermion.config import *
from openfermion.ops import FermionOperator
from openfermion.utils import count_qubits, normal_ordered
from openfermion.utils._low_depth_trotter_error import stagger_with_info

def simulation_ordered_grouped_hubbard_terms_with_info(
        hubbard_hamiltonian):
    """Give terms from the Fermi-Hubbard Hamiltonian in simulated order.

    Uses the simulation ordering, grouping terms into hopping
    (i^ j + j^ i) and on-site potential (i^j^ i j) operators.
    Pre-computes term information (indices each operator acts on, as
    well as whether each operator is a hopping operator).

    Args:
        hubbard_hamiltonian (FermionOperator): The Hamiltonian.
        original_ordering (list): The initial Jordan-Wigner canonical order.

    Returns:
        A 3-tuple of terms from the Hubbard Hamiltonian in order of
        simulation, the indices they act on, and whether they are hopping
        operators (both also in the same order).

    Notes:
        Assumes that the Hubbard model has spin and is on a 2D square
        aperiodic lattice. Uses the "stagger"-based Trotter step for the
        Hubbard model detailed in Kivlichan et al., "Quantum Simulation
        of Electronic Structure with Linear Depth and Connectivity",
        arxiv:1711.04789.
    """
    hamiltonian = normal_ordered(hubbard_hamiltonian)
    n_qubits = count_qubits(hamiltonian)
    side_length = int(numpy.sqrt(n_qubits / 2.0))

    ordered_terms = []
    ordered_indices = []
    ordered_is_hopping_operator = []

    original_ordering = list(range(n_qubits))
    for i in range(0, n_qubits - side_length, 2 * side_length):
        for j in range(2 * bool(i % (4 * side_length)), 2 * side_length, 4):
            original_ordering[i+j], original_ordering[i+j+1] = (
                original_ordering[i+j+1], original_ordering[i+j])

    input_ordering = list(original_ordering)

    # Follow odd-even transposition sort. In alternating steps, swap each even
    # qubits with the odd qubit to its right, and in the next step swap each
    # the odd qubits with the even qubit to its right. Do this until the input
    # ordering has been reversed.
    parities = [False, True] * int(side_length / 2 + 1)  # int floors here
    for parity in parities:
        results = stagger_with_info(
            hubbard_hamiltonian, input_ordering, parity)
        terms_in_step, indices_in_step, is_hopping_operator_in_step = results

        ordered_terms.extend(terms_in_step)
        ordered_indices.extend(indices_in_step)
        ordered_is_hopping_operator.extend(is_hopping_operator_in_step)

    input_ordering = list(original_ordering)

    parities = [True] + [False, True] * int(side_length / 2)  # int floors here
    for parity in parities:
        results = stagger_with_info(
            hubbard_hamiltonian, input_ordering, parity)
        terms_in_step, indices_in_step, is_hopping_operator_in_step = results

        ordered_terms.extend(terms_in_step)
        ordered_indices.extend(indices_in_step)
        ordered_is_hopping_operator.extend(is_hopping_operator_in_step)

    return (ordered_terms, ordered_indices, ordered_is_hopping_operator)


text:
require 'spec_helper'

describe Runner::Concurrency do
  context "when I spawn a task" do
    before do
      @customer = Customer.new
    end

    it "should run a thread when a ConcurrencyThread is used" do
      threader = Runner::Concurrency::ConcurrencyThread.new
      test_variable = nil
      thread = threader.run do
        test_variable = 1
      end
      thread.join
      test_variable.should eq 1
    end

    it "should run a fork when a ConcurrencyFork is used" do
      forker = Runner::Concurrency::ConcurrencyFork.new
      forker.run do
        # This part isn't really testable to my knowledge because Process.detach is called on the child right after
        # Which means the process is out of reach.
      end
    end

    context "and I yield a method" do
      it "should use ConcurrencyYield" do
        @yielder = Runner::Concurrency::ConcurrencyYield.new
        Runner::Concurrency::ConcurrencyYield.stub!(:new).and_return @yielder

        @yielder.should_receive :run
        task = @customer.spawn(:with => :yield).empty_method
      end
    end

    context "and I fork a method" do
      it "should use ConcurrencyFork" do
        @forker = Runner::Concurrency::ConcurrencyFork.new
        Runner::Concurrency::ConcurrencyFork.stub!(:new).and_return @forker

        @forker.should_receive :run
        task = @customer.spawn(:with => :fork).empty_method
      end
    end

    context "and I thread a method" do
      it "should use ConcurrencyThread" do
        @threader = Runner::Concurrency::ConcurrencyThread.new
        Runner::Concurrency::ConcurrencyThread.stub!(:new).and_return @threader

        @threader.should_receive :run
        task = @customer.spawn(:with => :thread).empty_method
      end
    end

    context "with I specify an invalid concurrency method" do
      it "should use ConcurrencyFork by default" do
        @forker = Runner::Concurrency::ConcurrencyFork.new
        Runner::Concurrency::ConcurrencyFork.stub!(:new).and_return @forker

        @forker.should_receive :run
        task = @customer.spawn(:with => :invalid_concurrency_method).empty_method
      end

      context "and I config to raise on concurrency handler" do
        it "should raise an exception" do
          Runner.raise_on_concurrency_handler_error = true

          Class.send(:include, Runner::Concurrency::Helper)
          handler = Class.new
          handler.instance_eval do
            def test_raise
              proc do
                concurrency(:invalid_concurrency_method) do
                  # Nothing
                end
              end
            end
          end
          handler.test_raise.should raise_exception(Runner::ConcurrencyHandlerError)
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package scodec.bits

private[bits] trait BitVectorPlatform


text:
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;

using Internal.Runtime.Augments;
using Internal.Runtime.CompilerServices;
using Internal.Reflection.Augments;

namespace System
{
    [StructLayout(LayoutKind.Sequential)]
    public struct RuntimeMethodHandle : ISerializable
    {
        private IntPtr _value;

        public unsafe IntPtr Value => _value;

        public override bool Equals(Object obj)
        {
            if (!(obj is RuntimeMethodHandle))
                return false;

            return Equals((RuntimeMethodHandle)obj);
        }

        public bool Equals(RuntimeMethodHandle handle)
        {
            if (_value == handle._value)
                return true;

            RuntimeTypeHandle declaringType1, declaringType2;
            MethodNameAndSignature nameAndSignature1, nameAndSignature2;
            RuntimeTypeHandle[] genericArgs1, genericArgs2;

            RuntimeAugments.TypeLoaderCallbacks.GetRuntimeMethodHandleComponents(this, out declaringType1, out nameAndSignature1, out genericArgs1);
            RuntimeAugments.TypeLoaderCallbacks.GetRuntimeMethodHandleComponents(handle, out declaringType2, out nameAndSignature2, out genericArgs2);

            if (!declaringType1.Equals(declaringType2))
                return false;
            if (!nameAndSignature1.Equals(nameAndSignature2))
                return false;
            if ((genericArgs1 == null && genericArgs2 != null) || (genericArgs1 != null && genericArgs2 == null))
                return false;
            if (genericArgs1 != null)
            {
                if (genericArgs1.Length != genericArgs2.Length)
                    return false;
                for (int i = 0; i < genericArgs1.Length; i++)
                {
                    if (!genericArgs1[i].Equals(genericArgs2[i]))
                        return false;
                }
            }

            return true;
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private int _rotl(int value, int shift)
        {
            return (int)(((uint)value << shift) | ((uint)value >> (32 - shift)));
        }

        public override int GetHashCode()
        {
            RuntimeTypeHandle declaringType;
            MethodNameAndSignature nameAndSignature;
            RuntimeTypeHandle[] genericArgs;
            RuntimeAugments.TypeLoaderCallbacks.GetRuntimeMethodHandleComponents(this, out declaringType, out nameAndSignature, out genericArgs);

            int hashcode = declaringType.GetHashCode();
            hashcode = (hashcode + _rotl(hashcode, 13)) ^ nameAndSignature.Name.GetHashCode();
            if (genericArgs != null)
            {
                for (int i = 0; i < genericArgs.Length; i++)
                {
                    int argumentHashCode = genericArgs[i].GetHashCode();
                    hashcode = (hashcode + _rotl(hashcode, 13)) ^ argumentHashCode;
                }
            }

            return hashcode;
        }

        public static bool operator ==(RuntimeMethodHandle left, RuntimeMethodHandle right)
        {
            return left.Equals(right);
        }

        public static bool operator !=(RuntimeMethodHandle left, RuntimeMethodHandle right)
        {
            return !left.Equals(right);
        }

        public IntPtr GetFunctionPointer()
        {
            RuntimeTypeHandle declaringType;
            MethodNameAndSignature nameAndSignature;
            RuntimeTypeHandle[] genericArgs;
            RuntimeAugments.TypeLoaderCallbacks.GetRuntimeMethodHandleComponents(this, out declaringType, out nameAndSignature, out genericArgs);

            return ReflectionAugments.ReflectionCoreCallbacks.GetFunctionPointer(this, declaringType);
        }

        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            throw new PlatformNotSupportedException();
        }
    }
}


text:
#include "RandomRGB.h"
#include <Utilities/Utilities.h>
#include <main.h> //So we can flush the displayManager to the actual display

RandomRGB::RandomRGB(DisplayManager* globalDisplayManager){
	g_displayManager = globalDisplayManager;
}

RandomRGB::~RandomRGB(){

}

void RandomRGB::initDemo(){
	uint8_t randomRow[8];
	//Create 8 random rows and populate the initial display
	for(uint8_t rowIndex=0; rowIndex<8; rowIndex++){
		DisplayMatrix::randomFillRowRGB(randomRow, sizeof(randomRow));
		display.setTopBuffer(randomRow,sizeof(randomRow));
		display.transformMatrix(DOWN);
	}
	g_displayManager->setDisplayMatrix(display.getCurrentMatrix(),64);
	//ShiftPWM.populateDisplayData();
}

void RandomRGB::runDemoLoop(){
	//Create random row of rgb
	uint8_t randomRow[8];
	DisplayMatrix::randomFillRowRGB(randomRow, sizeof(randomRow));

	//Capture the current display
	display.setCurrentMatrix(g_displayManager->getCurrentDisplayMatrix()->getCurrentMatrix(),64);

	//Calculate a random direction
	uint8_t direction = Utilities::randomNumber(3);
	direction++; //1-4
	//Populate the correct buffer
	switch (direction){
		case UP:
			display.setBottomBuffer(randomRow,sizeof(randomRow));
			break;
		case RIGHT:
			display.setLeftBuffer(randomRow,sizeof(randomRow));
			break;
		case DOWN:
			display.setTopBuffer(randomRow,sizeof(randomRow));
			break;
		case LEFT:
			display.setRightBuffer(randomRow,sizeof(randomRow));
			break;
		default:
			//Error, Invalid Transform Direction
		break;
	}

	//Now transform in the random direction
	display.transformMatrix(e_direction(direction));

	//Set back to the display
	g_displayManager->setDisplayMatrix(display.getCurrentMatrix(),64);

	//Present display
	flushDisplayMatrix(2,15);
}


text:
require 'action_view'

module SplitTester
  module TranslationHelper
    def self.included(base)
      # Using class_eval here because base.send(:include, InstanceMethods)
      # wasn't overwriting the translate method properly. Not sure why.
      base.class_eval {
         def translate(key, options = {})
           key = scope_key_by_partial(key)
           if is_split_test?
             # normalize the parameters so that we can add in
             # the current_split_test_key properly
             scope = options.delete(:scope)
             keys = I18n.normalize_keys(I18n.locale, key, scope)
             keys.shift
             key = keys.join('.')

             # Set the standard key as a default to fall back on automatically
             if options[:default]
               options[:default] = [options[:default]] unless options[:default].is_a?(Array)
               options[:default].unshift(key.to_sym)
             else
               options[:default] = [key.to_sym]
             end

             key = "#{current_split_test_key}.#{key}"
           end
           translation = I18n.translate(key, options.merge!(:raise => true))
           if html_safe_translation_key?(key) && translation.respond_to?(:html_safe)
             translation.html_safe
           else
             translation
           end
         rescue I18n::MissingTranslationData => e
           keys = I18n.normalize_keys(e.locale, e.key, e.options[:scope])
           content_tag('span', keys.join(', '), :class => 'translation_missing')
         end
        alias t translate
      }
    end
  end
end


text:
"""
A bag contains one red disc and one blue disc. In a game of chance a player
takes a disc at random and its colour is noted. After each turn the disc is
returned to the bag, an extra red disc is added, and another disc is taken at
random.

The player pays £1 to play and wins if they have taken more blue discs than red
discs at the end of the game.

If the game is played for four turns, the probability of a player winning is
exactly 11/120, and so the maximum prize fund the banker should allocate for
winning in this game would be £10 before they would expect to incur a loss.
Note that any payout will be a whole number of pounds and also includes the
original £1 paid to play the game, so in the example given the player actually
wins £9.

Find the maximum prize fund that should be allocated to a single game in which
fifteen turns are played.

Solution comment: Very quick, ~0.5 ms (would be much less for C++ impl.).
Derived explicitly the N = 4 case above, from which the pattern emerges.  The
memoization helps a whole bunch. Would have been slightly better to use DP and
build the table directly, but memoizing a recursive solution is so much nicer.
"""

import time
import numpy as np
from functools import lru_cache

def P(n):
    """Probability of drawing a blue in the n-th round."""
    return 1 / (n + 1)

@lru_cache(maxsize=None)
def Prob(blues, n, N):
    """
    Return probability of getting some number of blues, starting on round n,
    with N rounds total.
    """
    if blues <= 0:
        return 1    # Can always get 0 blues.
    elif blues > N - n + 1:
        return 0    # Can never get more blues than draws.
    elif blues == N - n + 1:
        return np.prod(P(np.arange(n, N+1)))  # Prob of getting blue of every draw.
    else:
        # Prob is prob of getting a blue now and then blues-1 on the remaining throws,
        # or prob of getting red now and blues blues on the remaining throws.
        return P(n) * Prob(blues - 1, n + 1, N) + (1-P(n)) * Prob(blues, n + 1, N)

if __name__ == "__main__":
    t0 = time.time()
    rounds = 15
    bet = 1
    winning_prob = Prob(rounds // 2 + 1, 1, rounds)
    print('Execution time: {:.3f} ms'.format((time.time() - t0) * 1e3))
    print('Max payout with {} rounds: {}£'.format(rounds, int(bet / winning_prob)))


text:
'use strict';

angular.module('myApp.layout', ['ngMaterial'])
    .factory('layoutService', function () {
        var layoutService = {};

        var addButtonAction = null;
        var addButtonScopesWatcher = [];

        layoutService.addButton = {
            setAction: function (callback) {
                addButtonAction = callback;
                this.emit();
            },
            clear: function () {
                addButtonAction = null;
                this.emit();
            },
            subscribe: function (scope, localVar) {
                addButtonScopesWatcher.push([scope, localVar || 'addButtonAction']);
            },
            emit: function () {
                angular.forEach(addButtonScopesWatcher, function (scope) {
                    scope[0][scope[1]] = addButtonAction;
                });
            }
        };

        return layoutService;
    })
    .controller('ToolbarCtrl', ['$scope', '$mdSidenav', function ($scope, $mdSidenav) {
        $scope.toggleLeft = function () {
            $mdSidenav('left').toggle();
        };
    }])
    .controller('SidebarMenuCtrl', ['$scope', '$location', '$mdSidenav', function ($scope, $location, $mdSidenav) {

        $scope.currentPath = $location.path();

        $scope.$on('$routeChangeSuccess', function () {
            $scope.currentPath = $location.path();
        });

        $scope.close = function () {
            $mdSidenav('left').close();
        };
    }])
    .controller('AddButton', ['$scope', 'layoutService', function ($scope, layoutService) {
        $scope.addButtonAction = null;
        layoutService.addButton.subscribe($scope);
    }])
;


text:
Strip whitespace (or other characters) from the beginning and/or end of a string.

```php
$etl->transform('trim', $options);
```

## Options

### Columns
Columns that will be transformed. If `empty`, the transformation is applied to all columns.

| Type | Default value |
|----- | ------------- |
| array | `[]` |

```php
$options = ['columns' => ['name', 'email']];
```

### Type
The options `trim` | `all` | `both` will trim both sides, `ltrim` | `start` | `left` will trim the left side and `rtrim` | `end` | `right` will trim the right side of the string.

| Type | Default value |
|----- | ------------- |
| string | both |

```php
$options = ['type' => 'right'];
```

### Mask
The stripped characters. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

| Type | Default value |
|----- | ------------- |
| string | " \t\n\r\0\x0B" |

```php
$options = ['mask' => '|'];
```


text:
/* { dg-options "-Woverloaded-virtual" } */

class Base {
public:
  virtual ~Base() {
  }
};

class Derived: public Base {
public:
  int Base() { // There should be no error here.
    return 5;
  }
};

int main() {
}


text:
namespace Kvasir {
//Serial Peripheral Interface
    namespace Spi0C1{    ///<SPI control register 1
        using Addr = Register::Address<0x40076000,0xffffff00,0x00000000,unsigned char>;
        ///LSB first (shifter direction)
        enum class LsbfeVal {
            v0=0x00000000,     ///<SPI serial data transfers start with most significant bit
            v1=0x00000001,     ///<SPI serial data transfers start with least significant bit
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,LsbfeVal> lsbfe{};
        namespace LsbfeValC{
            constexpr Register::FieldValue<decltype(lsbfe)::Type,LsbfeVal::v0> v0{};
            constexpr Register::FieldValue<decltype(lsbfe)::Type,LsbfeVal::v1> v1{};
        }
        ///Slave select output enable
        enum class SsoeVal {
            v0=0x00000000,     ///<When MODFEN is 0: In master mode, SS pin function is general-purpose I/O (not SPI). In slave mode, SS pin function is slave select input. When MODFEN is 1: In master mode, SS pin function is SS input for mode fault. In slave mode, SS pin function is slave select input.
            v1=0x00000001,     ///<When MODFEN is 0: In master mode, SS pin function is general-purpose I/O (not SPI). In slave mode, SS pin function is slave select input. When MODFEN is 1: In master mode, SS pin function is automatic SS output. In slave mode: SS pin function is slave select input.
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,SsoeVal> ssoe{};
        namespace SsoeValC{
            constexpr Register::FieldValue<decltype(ssoe)::Type,SsoeVal::v0> v0{};
            constexpr Register::FieldValue<decltype(ssoe)::Type,SsoeVal::v1> v1{};
        }
        ///Clock phase
        enum class CphaVal {
            v0=0x00000000,     ///<First edge on SPSCK occurs at the middle of the first cycle of a data transfer
            v1=0x00000001,     ///<First edge on SPSCK occurs at the start of the first cycle of a data transfer
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,CphaVal> cpha{};
        namespace CphaValC{
            constexpr Register::FieldValue<decltype(cpha)::Type,CphaVal::v0> v0{};
            constexpr Register::FieldValue<decltype(cpha)::Type,CphaVal::v1> v1{};
        }
        ///Clock polarity
        enum class CpolVal {
            v0=0x00000000,     ///<Active-high SPI clock (idles low)
            v1=0x00000001,     ///<Active-low SPI clock (idles high)
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,CpolVal> cpol{};
        namespace CpolValC{
            constexpr Register::FieldValue<decltype(cpol)::Type,CpolVal::v0> v0{};
            constexpr Register::FieldValue<decltype(cpol)::Type,CpolVal::v1> v1{};
        }
        ///Master/slave mode select
        enum class MstrVal {
            v0=0x00000000,     ///<SPI module configured as a slave SPI device
            v1=0x00000001,     ///<SPI module configured as a master SPI device
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,MstrVal> mstr{};
        namespace MstrValC{
            constexpr Register::FieldValue<decltype(mstr)::Type,MstrVal::v0> v0{};
            constexpr Register::FieldValue<decltype(mstr)::Type,MstrVal::v1> v1{};
        }
        ///SPI transmit interrupt enable
        enum class SptieVal {
            v0=0x00000000,     ///<Interrupts from SPTEF inhibited (use polling)
            v1=0x00000001,     ///<When SPTEF is 1, hardware interrupt requested
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,SptieVal> sptie{};
        namespace SptieValC{
            constexpr Register::FieldValue<decltype(sptie)::Type,SptieVal::v0> v0{};
            constexpr Register::FieldValue<decltype(sptie)::Type,SptieVal::v1> v1{};
        }
        ///SPI system enable
        enum class SpeVal {
            v0=0x00000000,     ///<SPI system inactive
            v1=0x00000001,     ///<SPI system enabled
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,SpeVal> spe{};
        namespace SpeValC{
            constexpr Register::FieldValue<decltype(spe)::Type,SpeVal::v0> v0{};
            constexpr Register::FieldValue<decltype(spe)::Type,SpeVal::v1> v1{};
        }
        ///SPI interrupt enable: for SPRF and MODF
        enum class SpieVal {
            v0=0x00000000,     ///<Interrupts from SPRF and MODF are inhibited-use polling
            v1=0x00000001,     ///<Request a hardware interrupt when SPRF or MODF is 1
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,SpieVal> spie{};
        namespace SpieValC{
            constexpr Register::FieldValue<decltype(spie)::Type,SpieVal::v0> v0{};
            constexpr Register::FieldValue<decltype(spie)::Type,SpieVal::v1> v1{};
        }
    }
    namespace Spi0C2{    ///<SPI control register 2
        using Addr = Register::Address<0x40076001,0xffffff64,0x00000000,unsigned char>;
        ///SPI pin control 0
        enum class Spc0Val {
            v0=0x00000000,     ///<SPI uses separate pins for data input and data output (pin mode is normal). In master mode of operation: MISO is master in and MOSI is master out. In slave mode of operation: MISO is slave out and MOSI is slave in.
            v1=0x00000001,     ///<SPI configured for single-wire bidirectional operation (pin mode is bidirectional). In master mode of operation: MISO is not used by SPI; MOSI is master in when BIDIROE is 0 or master I/O when BIDIROE is 1. In slave mode of operation: MISO is slave in when BIDIROE is 0 or slave I/O when BIDIROE is 1; MOSI is not used by SPI.
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,Spc0Val> spc0{};
        namespace Spc0ValC{
            constexpr Register::FieldValue<decltype(spc0)::Type,Spc0Val::v0> v0{};
            constexpr Register::FieldValue<decltype(spc0)::Type,Spc0Val::v1> v1{};
        }
        ///SPI stop in wait mode
        enum class SpiswaiVal {
            v0=0x00000000,     ///<SPI clocks continue to operate in wait mode
            v1=0x00000001,     ///<SPI clocks stop when the MCU enters wait mode
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,SpiswaiVal> spiswai{};
        namespace SpiswaiValC{
            constexpr Register::FieldValue<decltype(spiswai)::Type,SpiswaiVal::v0> v0{};
            constexpr Register::FieldValue<decltype(spiswai)::Type,SpiswaiVal::v1> v1{};
        }
        ///Bidirectional mode output enable
        enum class BidiroeVal {
            v0=0x00000000,     ///<Output driver disabled so SPI data I/O pin acts as an input
            v1=0x00000001,     ///<SPI I/O pin enabled as an output
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,BidiroeVal> bidiroe{};
        namespace BidiroeValC{
            constexpr Register::FieldValue<decltype(bidiroe)::Type,BidiroeVal::v0> v0{};
            constexpr Register::FieldValue<decltype(bidiroe)::Type,BidiroeVal::v1> v1{};
        }
        ///Master mode-fault function enable
        enum class ModfenVal {
            v0=0x00000000,     ///<Mode fault function disabled, master SS pin reverts to general-purpose I/O not controlled by SPI
            v1=0x00000001,     ///<Mode fault function enabled, master SS pin acts as the mode fault input or the slave select output
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,ModfenVal> modfen{};
        namespace ModfenValC{
            constexpr Register::FieldValue<decltype(modfen)::Type,ModfenVal::v0> v0{};
            constexpr Register::FieldValue<decltype(modfen)::Type,ModfenVal::v1> v1{};
        }
        ///SPI match interrupt enable
        enum class SpmieVal {
            v0=0x00000000,     ///<Interrupts from SPMF inhibited (use polling)
            v1=0x00000001,     ///<When SPMF is 1, requests a hardware interrupt
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,SpmieVal> spmie{};
        namespace SpmieValC{
            constexpr Register::FieldValue<decltype(spmie)::Type,SpmieVal::v0> v0{};
            constexpr Register::FieldValue<decltype(spmie)::Type,SpmieVal::v1> v1{};
        }
    }
    namespace Spi0Br{    ///<SPI baud rate register
        using Addr = Register::Address<0x40076002,0xffffff80,0x00000000,unsigned char>;
        ///SPI baud rate divisor
        enum class SprVal {
            v0000=0x00000000,     ///<Baud rate divisor is 2
            v0001=0x00000001,     ///<Baud rate divisor is 4
            v0010=0x00000002,     ///<Baud rate divisor is 8
            v0011=0x00000003,     ///<Baud rate divisor is 16
            v0100=0x00000004,     ///<Baud rate divisor is 32
            v0101=0x00000005,     ///<Baud rate divisor is 64
            v0110=0x00000006,     ///<Baud rate divisor is 128
            v0111=0x00000007,     ///<Baud rate divisor is 256
            v1000=0x00000008,     ///<Baud rate divisor is 512
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,SprVal> spr{};
        namespace SprValC{
            constexpr Register::FieldValue<decltype(spr)::Type,SprVal::v0000> v0000{};
            constexpr Register::FieldValue<decltype(spr)::Type,SprVal::v0001> v0001{};
            constexpr Register::FieldValue<decltype(spr)::Type,SprVal::v0010> v0010{};
            constexpr Register::FieldValue<decltype(spr)::Type,SprVal::v0011> v0011{};
            constexpr Register::FieldValue<decltype(spr)::Type,SprVal::v0100> v0100{};
            constexpr Register::FieldValue<decltype(spr)::Type,SprVal::v0101> v0101{};
            constexpr Register::FieldValue<decltype(spr)::Type,SprVal::v0110> v0110{};
            constexpr Register::FieldValue<decltype(spr)::Type,SprVal::v0111> v0111{};
            constexpr Register::FieldValue<decltype(spr)::Type,SprVal::v1000> v1000{};
        }
        ///SPI baud rate prescale divisor
        enum class SpprVal {
            v000=0x00000000,     ///<Baud rate prescaler divisor is 1
            v001=0x00000001,     ///<Baud rate prescaler divisor is 2
            v010=0x00000002,     ///<Baud rate prescaler divisor is 3
            v011=0x00000003,     ///<Baud rate prescaler divisor is 4
            v100=0x00000004,     ///<Baud rate prescaler divisor is 5
            v101=0x00000005,     ///<Baud rate prescaler divisor is 6
            v110=0x00000006,     ///<Baud rate prescaler divisor is 7
            v111=0x00000007,     ///<Baud rate prescaler divisor is 8
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,4),Register::ReadWriteAccess,SpprVal> sppr{};
        namespace SpprValC{
            constexpr Register::FieldValue<decltype(sppr)::Type,SpprVal::v000> v000{};
            constexpr Register::FieldValue<decltype(sppr)::Type,SpprVal::v001> v001{};
            constexpr Register::FieldValue<decltype(sppr)::Type,SpprVal::v010> v010{};
            constexpr Register::FieldValue<decltype(sppr)::Type,SpprVal::v011> v011{};
            constexpr Register::FieldValue<decltype(sppr)::Type,SpprVal::v100> v100{};
            constexpr Register::FieldValue<decltype(sppr)::Type,SpprVal::v101> v101{};
            constexpr Register::FieldValue<decltype(sppr)::Type,SpprVal::v110> v110{};
            constexpr Register::FieldValue<decltype(sppr)::Type,SpprVal::v111> v111{};
        }
    }
    namespace Spi0S{    ///<SPI status register
        using Addr = Register::Address<0x40076003,0xffffff0f,0x00000000,unsigned char>;
        ///Master mode fault flag
        enum class ModfVal {
            v0=0x00000000,     ///<No mode fault error
            v1=0x00000001,     ///<Mode fault error detected
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,ModfVal> modf{};
        namespace ModfValC{
            constexpr Register::FieldValue<decltype(modf)::Type,ModfVal::v0> v0{};
            constexpr Register::FieldValue<decltype(modf)::Type,ModfVal::v1> v1{};
        }
        ///SPI transmit buffer empty flag
        enum class SptefVal {
            v0=0x00000000,     ///<SPI transmit buffer not empty
            v1=0x00000001,     ///<SPI transmit buffer empty
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,SptefVal> sptef{};
        namespace SptefValC{
            constexpr Register::FieldValue<decltype(sptef)::Type,SptefVal::v0> v0{};
            constexpr Register::FieldValue<decltype(sptef)::Type,SptefVal::v1> v1{};
        }
        ///SPI match flag
        enum class SpmfVal {
            v0=0x00000000,     ///<Value in the receive data buffer does not match the value in the M register
            v1=0x00000001,     ///<Value in the receive data buffer matches the value in the M register
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,SpmfVal> spmf{};
        namespace SpmfValC{
            constexpr Register::FieldValue<decltype(spmf)::Type,SpmfVal::v0> v0{};
            constexpr Register::FieldValue<decltype(spmf)::Type,SpmfVal::v1> v1{};
        }
        ///SPI read buffer full flag
        enum class SprfVal {
            v0=0x00000000,     ///<No data available in the receive data buffer
            v1=0x00000001,     ///<Data available in the receive data buffer
        };
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,SprfVal> sprf{};
        namespace SprfValC{
            constexpr Register::FieldValue<decltype(sprf)::Type,SprfVal::v0> v0{};
            constexpr Register::FieldValue<decltype(sprf)::Type,SprfVal::v1> v1{};
        }
    }
    namespace Spi0D{    ///<SPI data register
        using Addr = Register::Address<0x40076005,0xffffff00,0x00000000,unsigned char>;
        ///Data (low byte)
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> bits{};
    }
    namespace Spi0M{    ///<SPI match register
        using Addr = Register::Address<0x40076007,0xffffff00,0x00000000,unsigned char>;
        ///Hardware compare value (low byte)
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> bits{};
    }
}


text:
title:  Til ettertanke
date:  07/08/2020
---

Les «Talentene» i _Ord som lever_ (2006), side 231–265 [COL 325–365].

Når Bibelens lære om åndelige gaver forstås riktig, skaper det enhet i menigheten. Det virker samlende når vi innser at alle er verdifulle medlemmer av Kristi legeme. Alle menighetens medlemmer er nødvendige for å fullføre Kristi misjon. Hvert medlem har en oppgave.

«Alle har fått et arbeid å gjøre for Mesteren. Han har gitt hver av sine tjenere spesielle gaver eller talenter. 'En ga han fem talenter, en annen to og en tredje én talent – etter det hver enkelt hadde evne til.' Hver tjener er vist en tillit som han er ansvarlig for, og de ulike oppgavene står i forhold til våre evner. Ved å dele ut gavene har ikke Gud vært urettferdig. Han har fordelt talentene etter tjenernes evner, og han forventer tilsvarende avkastning.» – _Testimonies for the Church_, bind 2, side 282.

Husk også at Åndens gaver gis til Guds ære og ikke vår egen. Gud ga dem for at hans navn kunne opphøyes og hans sak fremmes.

**Spørsmål til drøftelse**

`Hva vil det si at hver av oss har fått gaver fra Gud? Hvilke praktiske følger har dette for din lokale menighet? Hvilken forskjell kan denne tanken gjøre når det gjelder å engasjere alle i tjeneste?`

`Fortell hvordan et annet medlems gaver har velsignet deg. Fortell hvordan du oppdaget dine egne åndelige gaver. Hva tror du gavene dine er, og hvordan bruker du dem til å velsigne andre?`

`Denne studien påpekte at gavene våre vokser når vi bruker dem. Se tilbake på livet. Kan du tenke på gaver som Gud har gitt deg som har vokst når du har brukt dem til hans navns ære? Og still deg spørsmålet fra slutten av torsdagens avsnitt, om hvor trofast du er med det Gud har gitt deg.`


text:
from oslo_config import cfg

quota_group = cfg.OptGroup(
    name='quota',
    title='Quota Options',
    help="""
Quota options allow to manage quotas in openstack deployment.
""")

quota_opts = [
    cfg.IntOpt('instances',
        min=-1,
        default=10,
        deprecated_group='DEFAULT',
        deprecated_name='quota_instances',
        help="""
The number of instances allowed per project.

Possible Values

* A positive integer or 0.
* -1 to disable the quota.
"""),
    cfg.IntOpt('cores',
        min=-1,
        default=20,
        deprecated_group='DEFAULT',
        deprecated_name='quota_cores',
        help="""
The number of instance cores or vCPUs allowed per project.

Possible values:

* A positive integer or 0.
* -1 to disable the quota.
"""),
    cfg.IntOpt('ram',
        min=-1,
        default=50 * 1024,
        deprecated_group='DEFAULT',
        deprecated_name='quota_ram',
        help="""
The number of megabytes of instance RAM allowed per project.

Possible values:

* A positive integer or 0.
* -1 to disable the quota.
"""),
    cfg.IntOpt('metadata_items',
        min=-1,
        default=128,
        deprecated_group='DEFAULT',
        deprecated_name='quota_metadata_items',
        help="""
The number of metadata items allowed per instance.

Users can associate metadata with an instance during instance creation. This
metadata takes the form of key-value pairs.

Possible values:

* A positive integer or 0.
* -1 to disable the quota.
"""),
    cfg.IntOpt('injected_files',
        min=-1,
        default=5,
        deprecated_group='DEFAULT',
        deprecated_name='quota_injected_files',
        help="""
The number of injected files allowed.

File injection allows users to customize the personality of an instance by
injecting data into it upon boot. Only text file injection is permitted: binary
or ZIP files are not accepted. During file injection, any existing files that
match specified files are renamed to include ``.bak`` extension appended with a
timestamp.

Possible values:

* A positive integer or 0.
* -1 to disable the quota.
"""),
    cfg.IntOpt('injected_file_content_bytes',
        min=-1,
        default=10 * 1024,
        deprecated_group='DEFAULT',
        deprecated_name='quota_injected_file_content_bytes',
        help="""
The number of bytes allowed per injected file.

Possible values:

* A positive integer or 0.
* -1 to disable the quota.
"""),
    cfg.IntOpt('injected_file_path_length',
        min=-1,
        default=255,
        deprecated_group='DEFAULT',
        deprecated_name='quota_injected_file_path_length',
        help="""
The maximum allowed injected file path length.

Possible values:

* A positive integer or 0.
* -1 to disable the quota.
"""),
    cfg.IntOpt('key_pairs',
        min=-1,
        default=100,
        deprecated_group='DEFAULT',
        deprecated_name='quota_key_pairs',
        help="""
The maximum number of key pairs allowed per user.

Users can create at least one key pair for each project and use the key pair
for multiple instances that belong to that project.

Possible values:

* A positive integer or 0.
* -1 to disable the quota.
"""),
    cfg.IntOpt('server_groups',
        min=-1,
        default=10,
        deprecated_group='DEFAULT',
        deprecated_name='quota_server_groups',
        help="""
The maxiumum number of server groups per project.

Server groups are used to control the affinity and anti-affinity scheduling
policy for a group of servers or instances. Reducing the quota will not affect
any existing group, but new servers will not be allowed into groups that have
become over quota.

Possible values:

* A positive integer or 0.
* -1 to disable the quota.
"""),
    cfg.IntOpt('server_group_members',
        min=-1,
        default=10,
        deprecated_group='DEFAULT',
        deprecated_name='quota_server_group_members',
        help="""
The maximum number of servers per server group.

Possible values:

* A positive integer or 0.
* -1 to disable the quota.
"""),
    cfg.StrOpt('driver',
        default='nova.quota.DbQuotaDriver',
        choices=[
            ('nova.quota.DbQuotaDriver', 'Stores quota limit information '
             'in the database and relies on the ``quota_*`` configuration '
             'options for default quota limit values. Counts quota usage '
             'on-demand.'),
            ('nova.quota.NoopQuotaDriver', 'Ignores quota and treats all '
             'resources as unlimited.'),
        ],
        help="""
Provides abstraction for quota checks. Users can configure a specific
driver to use for quota checks.
"""),
    cfg.BoolOpt('recheck_quota',
        default=True,
        help="""
Recheck quota after resource creation to prevent allowing quota to be exceeded.

This defaults to True (recheck quota after resource creation) but can be set to
False to avoid additional load if allowing quota to be exceeded because of
racing requests is considered acceptable. For example, when set to False, if a
user makes highly parallel REST API requests to create servers, it will be
possible for them to create more servers than their allowed quota during the
race. If their quota is 10 servers, they might be able to create 50 during the
burst. After the burst, they will not be able to create any more servers but
they will be able to keep their 50 servers until they delete them.

The initial quota check is done before resources are created, so if multiple
parallel requests arrive at the same time, all could pass the quota check and
create resources, potentially exceeding quota. When recheck_quota is True,
quota will be checked a second time after resources have been created and if
the resource is over quota, it will be deleted and OverQuota will be raised,
usually resulting in a 403 response to the REST API user. This makes it
impossible for a user to exceed their quota with the caveat that it will,
however, be possible for a REST API user to be rejected with a 403 response in
the event of a collision close to reaching their quota limit, even if the user
has enough quota available when they made the request.
"""),
    cfg.BoolOpt(
        'count_usage_from_placement',
        default=False,
        help="""
Enable the counting of quota usage from the placement service.

Starting in Train, it is possible to count quota usage for cores and ram from
the placement service and instances from the API database instead of counting
from cell databases.

This works well if there is only one Nova deployment running per placement
deployment. However, if an operator is running more than one Nova deployment
sharing a placement deployment, they should not set this option to True because
currently the placement service has no way to partition resource providers per
Nova deployment. When this option is left as the default or set to False, Nova
will use the legacy counting method to count quota usage for instances, cores,
and ram from its cell databases.

Note that quota usage behavior related to resizes will be affected if this
option is set to True. Placement resource allocations are claimed on the
destination while holding allocations on the source during a resize, until the
resize is confirmed or reverted. During this time, when the server is in
VERIFY_RESIZE state, quota usage will reflect resource consumption on both the
source and the destination. This can be beneficial as it reserves space for a
revert of a downsize, but it also means quota usage will be inflated until a
resize is confirmed or reverted.

Behavior will also be different for unscheduled servers in ERROR state. A
server in ERROR state that has never been scheduled to a compute host will
not have placement allocations, so it will not consume quota usage for cores
and ram.

Behavior will be different for servers in SHELVED_OFFLOADED state. A server in
SHELVED_OFFLOADED state will not have placement allocations, so it will not
consume quota usage for cores and ram. Note that because of this, it will be
possible for a request to unshelve a server to be rejected if the user does not
have enough quota available to support the cores and ram needed by the server
to be unshelved.

The ``populate_queued_for_delete`` and ``populate_user_id`` online data
migrations must be completed before usage can be counted from placement. Until
the data migration is complete, the system will fall back to legacy quota usage
counting from cell databases depending on the result of an EXISTS database
query during each quota check, if this configuration option is set to True.
Operators who want to avoid the performance hit from the EXISTS queries should
wait to set this configuration option to True until after they have completed
their online data migrations via ``nova-manage db online_data_migrations``.
"""),
]

def register_opts(conf):
    conf.register_group(quota_group)
    conf.register_opts(quota_opts, group=quota_group)

def list_opts():
    return {quota_group: quota_opts}


text:
@implementation DockSquadImporterMac

- (void)announceError:(NSError *)error window:(id)window
{
    NSAlert* alert = [NSAlert alertWithError: error];
    [alert beginSheetModalForWindow: window completionHandler: nil];
}

- (void)showAirbag:(NSString *)importWarning window:(id)window
{
    NSAlert* airbag = [[NSAlert alloc] init];
    airbag.messageText = importWarning;
    [airbag addButtonWithTitle: @"Import"];
    [airbag addButtonWithTitle: @"Cancel"];
    id handler = ^(NSModalResponse returnCode) {
        [[airbag window] orderOut: self];
        if (returnCode == NSAlertFirstButtonReturn) {
            [self performImport];
        }
    };
    [airbag beginSheetModalForWindow: window completionHandler: handler];
}

- (void)explainNothingToDo:(NSString *)explanation details:(NSString*)details window:(id)window
{
    NSAlert* warning = [[NSAlert alloc] init];
    warning.messageText = explanation;
    warning.informativeText = details;
    [warning beginSheetModalForWindow: window completionHandler: nil];
}

@end


text:
import React, { Component, PropTypes } from 'react';

import Image from '../common/Image.react';

class Sticker extends Component {
  static propTypes = {
    sticker: PropTypes.object.isRequired,
    onClick: PropTypes.func.isRequired
  };

  constructor(props) {
    super(props);

    this.onClick = this.onClick.bind(this);
  }

  shouldComponentUpdate(nextProps) {
    return nextProps.sticker === this.props.sticker;
  }

  onClick() {
    this.props.onClick(this.props.sticker);
  }

  render() {
    const { url } = this.props.sticker;

    return (
      <div className="sticker" onClick={this.onClick}>
        <Image src={url} />
      </div>
    );
  }
}

export default Sticker;


text:
import subprocess as sp
import pytest
from snakemake import shell

def test_samtools_sort_and_index(sample1_se_sort_bam, sample1_se_sort_bam_bai):
    with pytest.raises(sp.CalledProcessError):
        shell('samtools view {sample1_se_sort_bam} 2L:1-100')
    shell('samtools view {sample1_se_sort_bam_bai[bam]} 2L:1-100')


text:
import configparser
import os
import unittest

from TM1py.Services import TM1Service
from TM1py.Utils.Utils import CaseAndSpaceInsensitiveSet, CaseAndSpaceInsensitiveDict, CaseAndSpaceInsensitiveTuplesDict

config = configparser.ConfigParser()
config.read(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'config.ini'))

class TestCaseAndSpaceInsensitiveDict(unittest.TestCase):
    @classmethod
    def setUp(cls):
        cls.map = CaseAndSpaceInsensitiveDict()
        cls.map["key1"] = "value1"
        cls.map["key2"] = "value2"
        cls.map["key3"] = "value3"

    @classmethod
    def tearDown(cls):
        del cls.map

    def test_set(self):
        self.map["key4"] = "value4"
        self.assertEqual(self.map["KEY4"], "value4")
        self.assertEqual(self.map["key4"], "value4")
        self.assertEqual(self.map["K e Y 4"], "value4")

    def test_get(self):
        self.assertEqual(self.map["KEY1"], "value1")
        self.assertEqual(self.map["key2"], "value2")
        self.assertEqual(self.map["K e Y 3"], "value3")

    def test_del(self):
        del self.map["KEY1"]
        del self.map["key2"]
        del self.map["K e Y 3"]

    def test_iter(self):
        for key1, key2 in zip(self.map, ("key1", "key2", "key3")):
            self.assertEqual(key1, key2)

    def test_len(self):
        self.assertEqual(3, len(self.map))

    def test_copy(self):
        c = self.map.copy()
        self.assertIsNot(c, self.map)
        self.assertEqual(c, self.map)

    def test_eq(self):
        map = CaseAndSpaceInsensitiveDict()
        map["key1"] = "value1"
        map["key2"] = "value2"
        map["key3"] = "value3"
        self.assertEqual(self.map, map)

    def test_eq_case_and_space_insensitive(self):
        map = CaseAndSpaceInsensitiveDict()
        map["key1"] = "value1"
        map["KEY2"] = "value2"
        map["K e Y 3"] = "value3"
        self.assertEqual(self.map, map)

    def test_ne(self):
        map = CaseAndSpaceInsensitiveDict()
        map["key 1"] = "wrong"
        map["key 2"] = "value2"
        map["key3"] = "value3"
        self.assertNotEqual(self.map, map)

        map = CaseAndSpaceInsensitiveDict()
        map["key1"] = "value1"
        map["key 2"] = "wrong"
        map["key3"] = "value3"
        self.assertNotEqual(self.map, map)

        map = CaseAndSpaceInsensitiveDict()
        map["key1"] = "value1"
        map["key2"] = "value2"
        map["key4"] = "value4"
        self.assertNotEqual(self.map, map)

class TestCaseAndSpaceInsensitiveSet(unittest.TestCase):

    @classmethod
    def setUp(cls):
        cls.original_values = ("Value1", "Value 2", "V A L U E 3")
        cls.set = CaseAndSpaceInsensitiveSet()
        cls.set.add(cls.original_values[0])
        cls.set.add(cls.original_values[1])
        cls.set.add(cls.original_values[2])

    @classmethod
    def tearDown(cls):
        del cls.set

    def test_get(self):
        self.assertIn("Value1", self.set)
        self.assertIn("VALUE1", self.set)
        self.assertIn("V ALUE 1", self.set)
        self.assertIn("Value2", self.set)
        self.assertIn("Value2", self.set)
        self.assertIn("V A L UE2", self.set)
        self.assertIn("Value3", self.set)
        self.assertIn("VALUE3", self.set)
        self.assertIn("V A LUE3", self.set)

        self.assertNotIn("Value", self.set)
        self.assertNotIn("VALUE4", self.set)
        self.assertNotIn("VA LUE 4", self.set)

    def test_del(self):
        del self.set["VALUE1"]
        del self.set["value2"]
        del self.set["V a L u E 3"]

    def test_discard(self):
        self.set.discard("Value1")
        self.set.discard("Value2")
        self.set.discard("Value3")
        # test for empty-ness
        self.assertFalse(self.set)

    def test_discard_case_and_space_insensitivity(self):
        self.set.discard("VAL UE 1")
        self.set.discard("Value2")
        self.set.discard("VA   LUE3")
        # test for empty-ness
        self.assertFalse(self.set)

    def test_len(self):
        self.set.add("Value4")
        self.assertEqual(4, len(self.set))
        self.set.discard("VALUE 4")
        self.assertEqual(3, len(self.set))

    def test_iter(self):
        self.assertEqual(len(self.set), len(self.original_values))
        for value in self.set:
            self.assertIn(value, self.original_values)

    def test_add(self):
        self.set.add("Value4")
        self.assertIn("Value4", self.set)
        self.assertIn("VALUE4", self.set)
        self.assertIn(" VALUE4", self.set)
        self.assertIn("VALUE4 ", self.set)
        self.assertIn("V ALUE 4", self.set)
        self.assertIn("Va L UE4", self.set)
        self.assertIn(" VAlue4", self.set)

    def test_copy(self):
        c = self.set.copy()
        self.assertIsNot(c, self.set)
        self.assertEqual(c, self.set)

    def test_eq(self):
        new_set = CaseAndSpaceInsensitiveSet()
        new_set.add(self.original_values[0])
        new_set.add(self.original_values[1])
        new_set.add(self.original_values[2])
        self.assertEqual(self.set, new_set)

    def test_eq_case_and_space_sensitivity(self):
        new_set = CaseAndSpaceInsensitiveSet()
        new_set.add(self.original_values[0].upper())
        new_set.add(self.original_values[1].lower())
        new_set.add(self.original_values[2].lower())
        self.assertEqual(self.set, new_set)

    def test_eq_against_set(self):
        new_set = set()
        new_set.add(self.original_values[0])
        new_set.add(self.original_values[1])
        new_set.add(self.original_values[2])
        self.assertEqual(self.set, new_set)

    def test_eq_against_set_case_and_space_sensitivity(self):
        new_set = set()
        new_set.add(self.original_values[0].upper())
        new_set.add(self.original_values[1].lower())
        new_set.add(self.original_values[2].upper())
        self.assertEqual(self.set, new_set)

    def test_ne(self):
        new_set = CaseAndSpaceInsensitiveSet()
        new_set.add("wrong1")
        new_set.add("wrong2")
        new_set.add("wrong3")
        self.assertNotEqual(self.set, new_set)

    def test_ne_against_set(self):
        new_set = set()
        new_set.add("wrong1")
        new_set.add("wrong2")
        new_set.add("wrong3")
        self.assertNotEqual(self.set, new_set)

class TestCaseAndSpaceInsensitiveTuplesDict(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.tm1 = TM1Service(**config['tm1srv01'])

    def setUp(self):
        self.map = CaseAndSpaceInsensitiveTuplesDict()
        self.map[("Elem1", "Elem1")] = "Value1"
        self.map[("Elem1", "Elem2")] = 2
        self.map[("Elem1", "Elem3")] = 3

    def tearDown(self):
        del self.map

    def test_del(self):
        self.assertIn(("Elem1", "Elem1"), self.map)
        self.assertIn(("Elem1", "Elem2"), self.map)
        self.assertIn(("Elem1", "Elem3"), self.map)
        del self.map[("El em1", "ELEM1")]
        del self.map[("El em1", "E L E M 2")]
        del self.map[("El em1", " eLEM3")]
        self.assertNotIn(("Elem1", "Elem1"), self.map)
        self.assertNotIn(("Elem1", "Elem2"), self.map)
        self.assertNotIn(("Elem1", "Elem3"), self.map)

    def test_eq(self):
        map = CaseAndSpaceInsensitiveTuplesDict()
        map[("Elem1", "Elem1")] = "Value1"
        map[("Elem1", "Elem2")] = 2
        map[("Elem1", "Elem3")] = 3
        self.assertEqual(map, self.map)

        map = CaseAndSpaceInsensitiveTuplesDict()
        map[("Elem 1", "Elem1")] = "Value1"
        map[("ELEM 1", "E L E M 2")] = 2
        map[(" Elem1 ", "Elem 3")] = 3
        self.assertEqual(map, self.map)

    def test_ne(self):
        map = CaseAndSpaceInsensitiveTuplesDict()
        map[("Elem1", "Elem1")] = "Value1"
        map[("Elem1", "Elem2")] = 0
        map[("Elem1", "Elem3")] = 3
        self.assertNotEqual(map, self.map)

        map = CaseAndSpaceInsensitiveTuplesDict()
        map[("Elem 1", "Elem1")] = "Value1"
        map[("ELEM 1", "E L E M 2")] = "wrong"
        map[(" Elem1 ", "Elem 3")] = 3
        self.assertNotEqual(map, self.map)

        map = CaseAndSpaceInsensitiveTuplesDict()
        map[("wrong", "Elem1")] = "Value1"
        map[("Elem1", "Elem2")] = 2
        map[("Elem1", "Elem3")] = 3
        self.assertNotEqual(map, self.map)

    def test_get(self):
        self.assertEqual(self.map[("ELEM1", "ELEM1")], "Value1")
        self.assertEqual(self.map[("elem1", "e l e m 2")], 2)
        self.assertEqual(self.map[("e l e M 1", "elem3")], 3)
        self.assertNotEqual(self.map[("e l e M 1", "elem3")], 2)

    def test_iter(self):
        for tuple1, tuple2 in zip(self.map, [("Elem1", "Elem1"), ("Elem1", "Elem2"), ("Elem1", "Elem3")]):
            self.assertEqual(tuple1, tuple2)

    def test_len(self):
        self.assertEqual(len(self.map), 3)

    def test_set(self):
        self.map[("E L E M 1", "E L E M 2")] = 3
        self.assertEqual(self.map[("Elem1", "Elem2")], 3)

    def test_copy(self):
        c = self.map.copy()
        self.assertIsNot(c, self.map)
        self.assertEqual(c, self.map)

    def test_full(self):
        mdx_rows = '[}Clients].Members'
        mdx_columns = '[}Groups].Members'
        cube_name = '[}ClientGroups]'
        mdx = 'SELECT {} ON ROWS, {} ON COLUMNS FROM {}'.format(mdx_rows, mdx_columns, cube_name)
        data = self.tm1.cubes.cells.execute_mdx(mdx)

        # Get
        if self.tm1.version[0:2] == '10':
            coordinates = ('[}Clients].[ad min]', '[}Groups].[ADM IN]')
        else:
            coordinates = ('[}Clients].[}Clients].[ad min]', '[}Groups].[}Groups].[ADM IN]')
        self.assertIsNotNone(data[coordinates])

        # Delete
        if self.tm1.version[0:2] == '10':
            coordinates = ('[}clients].[}clients].[admin]', '[}groups].[}groups].[admin]')
        else:
            coordinates = ('[}clients].[}clients].[admin]', '[}groups].[}groups].[admin]')
        self.assertTrue(coordinates in data)
        del data[coordinates]
        self.assertFalse(coordinates in data)

        # Copy
        data_cloned = data.copy()
        self.assertTrue(data_cloned == data)
        self.assertFalse(data_cloned is data)

    @classmethod
    def tearDownClass(cls):
        cls.tm1.logout()

if __name__ == '__main__':
    unittest.main()


text:
using System;
using System.Runtime.Serialization;
using CacheProvider.Interface;

namespace CacheProvider.Model
{
	[Serializable, DataContract]
	public class CacheObject: ICacheObject
    {
		[DataMember]
		public string Validator { get; set; }
		[DataMember]
		public byte[] Item { get; set; }
    }
}


text:
namespace GraphExec.Tests.Math
{
    public sealed class AddOperationInfo : OperationInfo
    {
        public AddOperationInfo()
        {
            this.Operation = Operations.Add;
        }
    }
}


text:
"""
Setup script for Heretic.
"""

import setuptools

from heretic import __project__, __version__

import os
if os.path.exists('README.rst'):
    README = open('README.rst').read()
else:
    README = ""  # a placeholder, readme is generated on release
CHANGES = open('CHANGES.md').read()

setuptools.setup(
    name=__project__,
    version=__version__,

    description="Heretic is a validation engine for written in python.",
    url='http://pypi.python.org/pypi/Heretic',
    author='Jeff Kloosterman',
    author_email='kloosterman.jeff@gmail.com',

    packages=setuptools.find_packages(),

    entry_points={'console_scripts': []},

    long_description=(README + '\n' + CHANGES),
    license='MIT',
    classifiers=[
        'Development Status :: 1 - Planning',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3.3',
    ],

    install_requires=[],
)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Syll. fung. (Abellini) 16: 739 (1902)

#### Original name
Phaeopezia lignicola Rostr.

### Remarks
null


text:
package uk.nhs.careconnect.ri.stu3.dao.transforms;

import org.apache.commons.collections4.Transformer;
import org.hl7.fhir.dstu3.model.*;
import org.springframework.stereotype.Component;
import uk.nhs.careconnect.ri.stu3.dao.daoutils;
import uk.nhs.careconnect.ri.database.entity.referral.*;

@Component
public class ReferralRequestEntityToFHIRReferralRequestTransformer implements Transformer<ReferralRequestEntity, ReferralRequest> {

    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ReferralRequestEntityToFHIRReferralRequestTransformer.class);

    @Override
    public ReferralRequest transform(final ReferralRequestEntity referralRequestEntity) {
        final ReferralRequest referral = new ReferralRequest();

        Meta meta = new Meta(); //.addProfile(CareConnectProfile.Location_1);

        if (referralRequestEntity.getUpdated() != null) {
            meta.setLastUpdated(referralRequestEntity.getUpdated());
        }
        else {
            if (referralRequestEntity.getCreated() != null) {
                meta.setLastUpdated(referralRequestEntity.getCreated());
            }
        }
        referral.setMeta(meta);

        referral.setId(referralRequestEntity.getId().toString());

        for(ReferralRequestIdentifier identifier : referralRequestEntity.getIdentifiers())
        {
            Identifier ident = referral.addIdentifier();
            ident = daoutils.getIdentifier(identifier, ident);
        }

        if (referralRequestEntity.getIntent() != null) {
            referral.setIntent(referralRequestEntity.getIntent());
        }
        if (referralRequestEntity.getPriority() !=null) {
            referral.setPriority(referralRequestEntity.getPriority());
        }
        if (referralRequestEntity.getStatus() != null) {
            referral.setStatus(referralRequestEntity.getStatus());
        }
        for (ReferralRequestServiceRequested service : referralRequestEntity.getServices()) {
            referral.addServiceRequested()
                    .addCoding()
                    .setSystem(service.getService().getSystem())
                    .setCode(service.getService().getCode())
                    .setDisplay(service.getService().getDisplay());
        }
        if (referralRequestEntity.getPatient() != null) {
            referral.setSubject(new Reference("Patient/" + referralRequestEntity.getPatient().getId())
                    .setDisplay(referralRequestEntity.getPatient().getNames().get(0).getDisplayName()));
        }
        if (referralRequestEntity.getType() != null) {
            referral.getType()
                    .addCoding()
                    .setDisplay(referralRequestEntity.getType().getDisplay())
                    .setSystem(referralRequestEntity.getType().getSystem())
                    .setCode(referralRequestEntity.getType().getCode());
        }
        if (referralRequestEntity.getSpecialty() != null) {
            referral.getSpecialty()
                    .addCoding()
                    .setDisplay(referralRequestEntity.getSpecialty().getDisplay())
                    .setSystem(referralRequestEntity.getSpecialty().getSystem())
                    .setCode(referralRequestEntity.getSpecialty().getCode());
        }
        if (referralRequestEntity.getContextEncounter() != null) {
            referral.setContext(new Reference("Encounter/" + referralRequestEntity.getContextEncounter().getId()));
        }
        if (referralRequestEntity.getAuthoredOn() != null) {
            referral.setAuthoredOn(referralRequestEntity.getAuthoredOn());
        }
        if (referralRequestEntity.getRequesterOrganisation() != null) {
            referral.getRequester().setAgent(new Reference("Organization/" + referralRequestEntity.getRequesterOrganisation().getId()).setDisplay(referralRequestEntity.getRequesterOrganisation().getName()));
        }
        if (referralRequestEntity.getRequesterPractitioner() != null) {
            referral.getRequester().setAgent(new Reference("Practitioner/" + referralRequestEntity.getRequesterPractitioner().getId()).setDisplay(referralRequestEntity.getRequesterPractitioner().getNames().get(0).getDisplayName()));
        }
        if (referralRequestEntity.getRequesterPatient() != null) {
            referral.getRequester().setAgent(new Reference("Patient/" + referralRequestEntity.getRequesterPatient().getId()));
        }
        if (referralRequestEntity.getOnBehalfOrganisation() != null) {
            referral.getRequester().setOnBehalfOf(new Reference("Organization/" + referralRequestEntity.getOnBehalfOrganisation().getId()).setDisplay(referralRequestEntity.getOnBehalfOrganisation().getName()));
        }
        for (ReferralRequestReason reason : referralRequestEntity.getReasons()) {
            referral.addReasonCode()
                    .addCoding()
                    .setSystem(reason.getReason().getSystem())
                    .setCode(reason.getReason().getCode())
                    .setDisplay(reason.getReason().getDisplay());
        }
        for (ReferralRequestReasonReference reason : referralRequestEntity.getReasonReferences()) {
            if (reason.getCondition() != null) {
                referral.addReasonReference(new Reference("Condition/"+reason.getCondition().getId()).setDisplay(reason.getCondition().getCode().getDisplay()));
            }
            if (reason.getObservation() != null) {
                referral.addReasonReference(new Reference("Observation/"+reason.getObservation().getId()).setDisplay(reason.getObservation().getCode().getDisplay()));
            }
        }
        for (ReferralRequestRecipient recipient : referralRequestEntity.getRecipients()) {
            if (recipient.getOrganisation() != null) {
                referral.addRecipient(new Reference("Organization/" + recipient.getOrganisation().getId()).setDisplay(recipient.getOrganisation().getName()));
            }
            if (recipient.getPractitioner() != null) {
                referral.addRecipient(new Reference("Practitioner/" + recipient.getPractitioner().getId()).setDisplay(recipient.getPractitioner().getNames().get(0).getDisplayName()));
            }
            if (recipient.getService() != null) {
                referral.addRecipient(new Reference("HealthcareService/" + recipient.getService().getId()).setDisplay(recipient.getService().getName()));
            }
        }

        return referral;

    }
}


text:
package org.jasig.cas.ticket;

import org.jasig.cas.authentication.RootCasException;

/**
 * Generic ticket exception. Top of the TicketException hierarchy.
 *
 * @author Scott Battaglia
 * @since 3.0
 */
public abstract class TicketException extends RootCasException {
    private static final long serialVersionUID = -5128676415951733624L;

    public TicketException(final String code, final Throwable throwable) {
      super(code, throwable);
    }

    public TicketException(final String code) {
      super(code);
    }

    public TicketException(final String code, final String msg) {
      super(code, msg);
    }
}


text:
class CreateImages < ActiveRecord::Migration[5.0]
  def change
    create_table :images do |t|
      t.string :token

      t.timestamps
    end
  end
end


text:
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import *  # NOQA
from future import standard_library
standard_library.install_aliases()  # NOQA

from chainerrl.agents.dqn import DQN
from chainerrl.functions import scale_grad

class ResidualDQN(DQN):
    """DQN that allows maxQ also backpropagate gradients."""

    def __init__(self, *args, **kwargs):
        self.grad_scale = kwargs.pop('grad_scale', 1.0)
        super().__init__(*args, **kwargs)

    def sync_target_network(self):
        pass

    def _compute_target_values(self, exp_batch):

        batch_next_state = exp_batch['next_state']
        if self.recurrent:
            target_next_qout, _ = self.model.n_step_forward(
                batch_next_state, exp_batch['next_recurrent_state'],
                output_mode='concat')
        else:
            target_next_qout = self.model(batch_next_state)

        next_q_max = target_next_qout.max

        batch_rewards = exp_batch['reward']
        batch_terminal = exp_batch['is_state_terminal']
        batch_discount = exp_batch['discount']

        return (batch_rewards
                + batch_discount * (1.0 - batch_terminal) * next_q_max)

    def _compute_y_and_t(self, exp_batch):

        batch_state = exp_batch['state']

        # Compute Q-values for current states
        if self.recurrent:
            qout, _ = self.model.n_step_forward(
                batch_state, exp_batch['recurrent_state'],
                output_mode='concat')
        else:
            qout = self.model(batch_state)

        batch_actions = exp_batch['action']
        batch_q = qout.evaluate_actions(batch_actions)[..., None]

        # Target values must also backprop gradients
        batch_q_target = self._compute_target_values(exp_batch)[..., None]

        return batch_q, scale_grad.scale_grad(batch_q_target, self.grad_scale)

    @property
    def saved_attributes(self):
        # ResidualDQN doesn't use target models
        return ('model', 'optimizer')


text:
<Alloy>
    <Window class="container" id="win2">
        <Button id="btnClose" title="Close"/>
    </Window>
</Alloy>


text:
title: 'Book: High performance browser networking'
status: published
tags:
- book
- performance
- network
---

I recently finished [this excellent book](http://chimera.labs.oreilly.com/books/1230000000545) written by Ilya Grigorik, an engineer at Google. This book is really really good and if you are even remotely interested in web performances you should definitely read it.

It's very dense, packed with information and practical tips. I'm considering doing one or two quick presentation at my [local meetup](http://www.meetup.com/javascript-enthusiasts/). It's focused on network performances, which are the most important (css and rendering performances are the icing on the cake, do it only when you have a fast loading website).

A few examples:

* Why latency matters more than bandwidth.
* Why you should bundle and minify all your scripts and css to minimize the number of requests (inner working of TCP).
* How you can tune your kernel, TLS configuration and server settings to [save one RTT](http://www.igvita.com/2013/12/16/optimizing-nginx-tls-time-to-first-byte/)
* Why you should use browser caching, and understand the tradeof of sharding resources.
* Inner working of http2 and why it'll be awesome
* How the "futures" API work (websocket, server sent events and webRTC)
* And so more...

I highly recommend this book one more time for any web engineer (front end, back end or both). Even though we tend to treat the browser as a black box, there is a point where we need to understand its inner working to deliver better quality products.


text:
package com.google.cloud.compute.deprecated;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

import com.google.api.services.compute.model.Disk;
import com.google.common.collect.ImmutableList;
import java.util.List;
import org.junit.Test;

public class DiskInfoTest {

  private static final String GENERATED_ID = "42";
  private static final DiskId DISK_ID = DiskId.of("project", "zone", "disk");
  private static final Long CREATION_TIMESTAMP = 1453293540000L;
  private static final DiskInfo.CreationStatus CREATION_STATUS = DiskInfo.CreationStatus.READY;
  private static final String DESCRIPTION = "description";
  private static final Long SIZE_GB = 500L;
  private static final DiskTypeId TYPE = DiskTypeId.of("project", "zone", "disk");
  private static final List<LicenseId> LICENSES =
      ImmutableList.of(LicenseId.of("project", "license1"), LicenseId.of("project", "license2"));
  private static final List<InstanceId> ATTACHED_INSTANCES =
      ImmutableList.of(
          InstanceId.of("project", "zone", "instance1"),
          InstanceId.of("project", "zone", "instance2"));
  private static final SnapshotId SNAPSHOT = SnapshotId.of("project", "snapshot");
  private static final ImageId IMAGE = ImageId.of("project", "image");
  private static final String SNAPSHOT_ID = "snapshotId";
  private static final String IMAGE_ID = "snapshotId";
  private static final Long LAST_ATTACH_TIMESTAMP = 1453293600000L;
  private static final Long LAST_DETACH_TIMESTAMP = 1453293660000L;
  private static final StandardDiskConfiguration DISK_CONFIGURATION =
      StandardDiskConfiguration.newBuilder().setSizeGb(SIZE_GB).setDiskType(TYPE).build();
  private static final SnapshotDiskConfiguration SNAPSHOT_DISK_CONFIGURATION =
      SnapshotDiskConfiguration.newBuilder(SNAPSHOT)
          .setSizeGb(SIZE_GB)
          .setDiskType(TYPE)
          .setSourceSnapshotId(SNAPSHOT_ID)
          .build();
  private static final ImageDiskConfiguration IMAGE_DISK_CONFIGURATION =
      ImageDiskConfiguration.newBuilder(IMAGE)
          .setSizeGb(SIZE_GB)
          .setDiskType(TYPE)
          .setSourceImageId(IMAGE_ID)
          .build();
  private static final DiskInfo DISK_INFO =
      DiskInfo.newBuilder(DISK_ID, DISK_CONFIGURATION)
          .setGeneratedId(GENERATED_ID)
          .setCreationTimestamp(CREATION_TIMESTAMP)
          .setCreationStatus(CREATION_STATUS)
          .setDescription(DESCRIPTION)
          .setLicenses(LICENSES)
          .setAttachedInstances(ATTACHED_INSTANCES)
          .setLastAttachTimestamp(LAST_ATTACH_TIMESTAMP)
          .setLastDetachTimestamp(LAST_DETACH_TIMESTAMP)
          .build();
  private static final DiskInfo SNAPSHOT_DISK_INFO =
      DiskInfo.newBuilder(DISK_ID, SNAPSHOT_DISK_CONFIGURATION)
          .setGeneratedId(GENERATED_ID)
          .setCreationTimestamp(CREATION_TIMESTAMP)
          .setCreationStatus(CREATION_STATUS)
          .setDescription(DESCRIPTION)
          .setLicenses(LICENSES)
          .setAttachedInstances(ATTACHED_INSTANCES)
          .setLastAttachTimestamp(LAST_ATTACH_TIMESTAMP)
          .setLastDetachTimestamp(LAST_DETACH_TIMESTAMP)
          .build();
  private static final DiskInfo IMAGE_DISK_INFO =
      DiskInfo.newBuilder(DISK_ID, IMAGE_DISK_CONFIGURATION)
          .setGeneratedId(GENERATED_ID)
          .setCreationTimestamp(CREATION_TIMESTAMP)
          .setCreationStatus(CREATION_STATUS)
          .setDescription(DESCRIPTION)
          .setLicenses(LICENSES)
          .setAttachedInstances(ATTACHED_INSTANCES)
          .setLastAttachTimestamp(LAST_ATTACH_TIMESTAMP)
          .setLastDetachTimestamp(LAST_DETACH_TIMESTAMP)
          .build();

  @Test
  public void testToBuilder() {
    compareDiskInfo(DISK_INFO, DISK_INFO.toBuilder().build());
    compareDiskInfo(IMAGE_DISK_INFO, IMAGE_DISK_INFO.toBuilder().build());
    compareDiskInfo(SNAPSHOT_DISK_INFO, SNAPSHOT_DISK_INFO.toBuilder().build());
    DiskInfo diskInfo = DISK_INFO.toBuilder().setDescription("newDescription").build();
    assertEquals("newDescription", diskInfo.getDescription());
    diskInfo = diskInfo.toBuilder().setDescription("description").build();
    compareDiskInfo(DISK_INFO, diskInfo);
  }

  @Test
  public void testToBuilderIncomplete() {
    DiskInfo diskInfo = DiskInfo.of(DISK_ID, DISK_CONFIGURATION);
    assertEquals(diskInfo, diskInfo.toBuilder().build());
    diskInfo = DiskInfo.of(DISK_ID, SNAPSHOT_DISK_CONFIGURATION);
    assertEquals(diskInfo, diskInfo.toBuilder().build());
    diskInfo = DiskInfo.of(DISK_ID, IMAGE_DISK_CONFIGURATION);
    assertEquals(diskInfo, diskInfo.toBuilder().build());
  }

  @Test
  public void testBuilder() {
    assertEquals(GENERATED_ID, DISK_INFO.getGeneratedId());
    assertEquals(DISK_ID, DISK_INFO.getDiskId());
    assertEquals(DISK_CONFIGURATION, DISK_INFO.getConfiguration());
    assertEquals(CREATION_TIMESTAMP, DISK_INFO.getCreationTimestamp());
    assertEquals(CREATION_STATUS, DISK_INFO.getCreationStatus());
    assertEquals(DESCRIPTION, DISK_INFO.getDescription());
    assertEquals(LICENSES, DISK_INFO.getLicenses());
    assertEquals(ATTACHED_INSTANCES, DISK_INFO.getAttachedInstances());
    assertEquals(LAST_ATTACH_TIMESTAMP, DISK_INFO.getLastAttachTimestamp());
    assertEquals(LAST_DETACH_TIMESTAMP, DISK_INFO.getLastDetachTimestamp());
    assertEquals(GENERATED_ID, IMAGE_DISK_INFO.getGeneratedId());
    assertEquals(DISK_ID, IMAGE_DISK_INFO.getDiskId());
    assertEquals(IMAGE_DISK_CONFIGURATION, IMAGE_DISK_INFO.getConfiguration());
    assertEquals(CREATION_TIMESTAMP, IMAGE_DISK_INFO.getCreationTimestamp());
    assertEquals(CREATION_STATUS, IMAGE_DISK_INFO.getCreationStatus());
    assertEquals(DESCRIPTION, IMAGE_DISK_INFO.getDescription());
    assertEquals(LICENSES, IMAGE_DISK_INFO.getLicenses());
    assertEquals(ATTACHED_INSTANCES, IMAGE_DISK_INFO.getAttachedInstances());
    assertEquals(LAST_ATTACH_TIMESTAMP, IMAGE_DISK_INFO.getLastAttachTimestamp());
    assertEquals(LAST_DETACH_TIMESTAMP, IMAGE_DISK_INFO.getLastDetachTimestamp());
    assertEquals(GENERATED_ID, SNAPSHOT_DISK_INFO.getGeneratedId());
    assertEquals(DISK_ID, SNAPSHOT_DISK_INFO.getDiskId());
    assertEquals(SNAPSHOT_DISK_CONFIGURATION, SNAPSHOT_DISK_INFO.getConfiguration());
    assertEquals(CREATION_TIMESTAMP, SNAPSHOT_DISK_INFO.getCreationTimestamp());
    assertEquals(CREATION_STATUS, SNAPSHOT_DISK_INFO.getCreationStatus());
    assertEquals(DESCRIPTION, SNAPSHOT_DISK_INFO.getDescription());
    assertEquals(LICENSES, SNAPSHOT_DISK_INFO.getLicenses());
    assertEquals(ATTACHED_INSTANCES, SNAPSHOT_DISK_INFO.getAttachedInstances());
    assertEquals(LAST_ATTACH_TIMESTAMP, SNAPSHOT_DISK_INFO.getLastAttachTimestamp());
    assertEquals(LAST_DETACH_TIMESTAMP, SNAPSHOT_DISK_INFO.getLastDetachTimestamp());
  }

  @Test
  public void testOf() {
    DiskInfo diskInfo = DiskInfo.of(DISK_ID, DISK_CONFIGURATION);
    assertNull(diskInfo.getGeneratedId());
    assertEquals(DISK_ID, diskInfo.getDiskId());
    assertEquals(DISK_CONFIGURATION, diskInfo.getConfiguration());
    assertNull(diskInfo.getCreationTimestamp());
    assertNull(diskInfo.getCreationStatus());
    assertNull(diskInfo.getDescription());
    assertNull(diskInfo.getLicenses());
    assertNull(diskInfo.getAttachedInstances());
    assertNull(diskInfo.getLastAttachTimestamp());
    assertNull(diskInfo.getLastDetachTimestamp());
    diskInfo = DiskInfo.of(DISK_ID, IMAGE_DISK_CONFIGURATION);
    assertNull(diskInfo.getGeneratedId());
    assertEquals(DISK_ID, diskInfo.getDiskId());
    assertEquals(IMAGE_DISK_CONFIGURATION, diskInfo.getConfiguration());
    assertNull(diskInfo.getCreationTimestamp());
    assertNull(diskInfo.getCreationStatus());
    assertNull(diskInfo.getDescription());
    assertNull(diskInfo.getLicenses());
    assertNull(diskInfo.getAttachedInstances());
    assertNull(diskInfo.getLastAttachTimestamp());
    assertNull(diskInfo.getLastDetachTimestamp());
    diskInfo = DiskInfo.of(DISK_ID, SNAPSHOT_DISK_CONFIGURATION);
    assertNull(diskInfo.getGeneratedId());
    assertEquals(DISK_ID, diskInfo.getDiskId());
    assertEquals(SNAPSHOT_DISK_CONFIGURATION, diskInfo.getConfiguration());
    assertNull(diskInfo.getCreationTimestamp());
    assertNull(diskInfo.getCreationStatus());
    assertNull(diskInfo.getDescription());
    assertNull(diskInfo.getLicenses());
    assertNull(diskInfo.getAttachedInstances());
    assertNull(diskInfo.getLastAttachTimestamp());
    assertNull(diskInfo.getLastDetachTimestamp());
  }

  @Test
  public void testToAndFromPb() {
    DiskInfo diskInfo = DiskInfo.fromPb(DISK_INFO.toPb());
    compareDiskInfo(DISK_INFO, diskInfo);
    diskInfo = DiskInfo.fromPb(SNAPSHOT_DISK_INFO.toPb());
    compareDiskInfo(SNAPSHOT_DISK_INFO, diskInfo);
    diskInfo = DiskInfo.fromPb(IMAGE_DISK_INFO.toPb());
    compareDiskInfo(IMAGE_DISK_INFO, diskInfo);
    Disk disk =
        new Disk()
            .setSelfLink(DISK_ID.getSelfLink())
            .setType(TYPE.getSelfLink())
            .setSizeGb(SIZE_GB);
    diskInfo = DiskInfo.of(DISK_ID, DISK_CONFIGURATION);
    compareDiskInfo(diskInfo, DiskInfo.fromPb(disk));
    disk =
        new Disk()
            .setType(TYPE.getSelfLink())
            .setSizeGb(SIZE_GB)
            .setSelfLink(DISK_ID.getSelfLink())
            .setSourceSnapshotId(SNAPSHOT_ID)
            .setSourceSnapshot(SNAPSHOT.getSelfLink());
    diskInfo = DiskInfo.of(DISK_ID, SNAPSHOT_DISK_CONFIGURATION);
    compareDiskInfo(diskInfo, DiskInfo.fromPb(disk));
    disk =
        new Disk()
            .setType(TYPE.getSelfLink())
            .setSizeGb(SIZE_GB)
            .setSelfLink(DISK_ID.getSelfLink())
            .setSourceImageId(IMAGE_ID)
            .setSourceImage(IMAGE.getSelfLink());
    diskInfo = DiskInfo.of(DISK_ID, IMAGE_DISK_CONFIGURATION);
    compareDiskInfo(diskInfo, DiskInfo.fromPb(disk));
  }

  @Test
  public void testSetProjectId() {
    StandardDiskConfiguration standardDiskConfiguration =
        DISK_CONFIGURATION
            .toBuilder()
            .setDiskType(DiskTypeId.of(TYPE.getZone(), TYPE.getType()))
            .build();
    DiskInfo diskInfo =
        DISK_INFO
            .toBuilder()
            .setDiskId(DiskId.of(DISK_ID.getZone(), DISK_ID.getDisk()))
            .setConfiguration(standardDiskConfiguration)
            .build();
    compareDiskInfo(DISK_INFO, diskInfo.setProjectId("project"));
    SnapshotDiskConfiguration snapshotDiskConfiguration =
        SNAPSHOT_DISK_CONFIGURATION
            .toBuilder()
            .setDiskType(DiskTypeId.of(TYPE.getZone(), TYPE.getType()))
            .setSourceSnapshot(SnapshotId.of(SNAPSHOT.getSnapshot()))
            .build();
    diskInfo =
        SNAPSHOT_DISK_INFO
            .toBuilder()
            .setDiskId(DiskId.of(DISK_ID.getZone(), DISK_ID.getDisk()))
            .setConfiguration(snapshotDiskConfiguration)
            .build();
    compareDiskInfo(SNAPSHOT_DISK_INFO, diskInfo.setProjectId("project"));
    ImageDiskConfiguration imageDiskConfiguration =
        IMAGE_DISK_CONFIGURATION
            .toBuilder()
            .setDiskType(DiskTypeId.of(TYPE.getZone(), TYPE.getType()))
            .setSourceImage(ImageId.of(IMAGE.getImage()))
            .build();
    diskInfo =
        IMAGE_DISK_INFO
            .toBuilder()
            .setDiskId(DiskId.of(DISK_ID.getZone(), DISK_ID.getDisk()))
            .setConfiguration(imageDiskConfiguration)
            .build();
    compareDiskInfo(IMAGE_DISK_INFO, diskInfo.setProjectId("project"));
  }

  public void compareDiskInfo(DiskInfo expected, DiskInfo value) {
    assertEquals(expected, value);
    assertEquals(expected.getConfiguration(), value.getConfiguration());
    assertEquals(expected.getGeneratedId(), value.getGeneratedId());
    assertEquals(expected.getDiskId(), value.getDiskId());
    assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp());
    assertEquals(expected.getCreationStatus(), value.getCreationStatus());
    assertEquals(expected.getDescription(), value.getDescription());
    assertEquals(expected.getLicenses(), value.getLicenses());
    assertEquals(expected.getAttachedInstances(), value.getAttachedInstances());
    assertEquals(expected.getLastAttachTimestamp(), value.getLastAttachTimestamp());
    assertEquals(expected.getLastDetachTimestamp(), value.getLastDetachTimestamp());
    assertEquals(expected.hashCode(), value.hashCode());
  }
}


text:
using System.Collections.Generic;

namespace Reposify.Tests
{
    /// <summary> return the PolyType's with Int value contained in IntValues </summary>
    public class QueryIn : IDbQuery<IList<PolyType>>
    {
        public int[] IntValues;
    }
}


text:
package org.apache.logging.log4j.core.jackson;

import com.fasterxml.jackson.databind.ObjectMapper;

public class LevelMixInYamlTest extends LevelMixInTest {

    @Override
    protected ObjectMapper newObjectMapper() {
        return new Log4jYamlObjectMapper();
    }

}


text:
package Epam_test.Bll;

import Epam_test.Model.Tank;

import java.util.Comparator;

/**
 * Created by User on 16.09.2015.
 */
public class Comparators<R>
{

    public static class SortToTop implements Comparator<Tank>
    {

        @Override
        public int compare(Tank tank1, Tank tank2)
        { int result;
            if (tank1.getMass()>tank2.getMass())
            {
                result=1;
            }
            else{result=-1;}

            return result;

        }
    }public static class SortToDown implements Comparator<Tank>
    {

        @Override
        public int compare(Tank tank1, Tank tank2)
        { int result;
            if (tank1.getMass()>tank2.getMass())
            {
                result=-1;
            }
            else{result=1;}

            return result;

        }
    }

}


text:
<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new AppBundle\AppBundle(),
            new Geptool\Bundle\JiraApiBundle\JiraApiBundle(),
            new Geptool\Bundle\TestBundle\GeptoolTestBundle(),
            new Geptool\Bundle\MainBundle\GeptoolMainBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
    }
}


text:
package org.optaplanner.core.impl.heuristic.selector.move.generic.list;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.optaplanner.core.impl.testdata.util.PlannerTestUtils.mockRebasingScoreDirector;

import org.junit.jupiter.api.Test;
import org.optaplanner.core.api.score.buildin.simple.SimpleScore;
import org.optaplanner.core.api.score.director.ScoreDirector;
import org.optaplanner.core.impl.domain.variable.descriptor.ListVariableDescriptor;
import org.optaplanner.core.impl.heuristic.move.AbstractMove;
import org.optaplanner.core.impl.score.director.InnerScoreDirector;
import org.optaplanner.core.impl.testdata.domain.list.TestdataListEntity;
import org.optaplanner.core.impl.testdata.domain.list.TestdataListSolution;
import org.optaplanner.core.impl.testdata.domain.list.TestdataListValue;

class ListAssignMoveTest {

    @Test
    void doMove() {
        TestdataListValue v1 = new TestdataListValue("1");
        TestdataListValue v2 = new TestdataListValue("2");
        TestdataListValue v3 = new TestdataListValue("3");
        TestdataListEntity e1 = new TestdataListEntity("e1");

        InnerScoreDirector<TestdataListSolution, SimpleScore> scoreDirector = mock(InnerScoreDirector.class);
        ListVariableDescriptor<TestdataListSolution> variableDescriptor =
                TestdataListEntity.buildVariableDescriptorForValueList();

        // v1 -> e1[0]
        ListAssignMove<TestdataListSolution> move = new ListAssignMove<>(variableDescriptor, v1, e1, 0);
        AbstractMove<TestdataListSolution> undoMove = move.doMove(scoreDirector);
        assertThat(e1.getValueList()).containsExactly(v1);

        // undo
        undoMove.doMoveOnly(scoreDirector);
        assertThat(e1.getValueList()).isEmpty();
        assertThatThrownBy(() -> undoMove.doMove(scoreDirector)).isInstanceOf(UnsupportedOperationException.class);

        // v2 -> e1[0]
        new ListAssignMove<>(variableDescriptor, v2, e1, 0).doMove(scoreDirector);
        // v3 -> e1[1]
        new ListAssignMove<>(variableDescriptor, v3, e1, 1).doMove(scoreDirector);
        // v1 -> e1[0]
        new ListAssignMove<>(variableDescriptor, v1, e1, 0).doMove(scoreDirector);
        assertThat(e1.getValueList()).containsExactly(v1, v2, v3);
    }

    @Test
    void rebase() {
        TestdataListValue v1 = new TestdataListValue("1");
        TestdataListEntity e1 = new TestdataListEntity("e1");

        TestdataListValue destinationV1 = new TestdataListValue("1");
        TestdataListEntity destinationE1 = new TestdataListEntity("e1");

        ListVariableDescriptor<TestdataListSolution> variableDescriptor =
                TestdataListEntity.buildVariableDescriptorForValueList();

        ScoreDirector<TestdataListSolution> destinationScoreDirector = mockRebasingScoreDirector(
                variableDescriptor.getEntityDescriptor().getSolutionDescriptor(), new Object[][] {
                        { v1, destinationV1 },
                        { e1, destinationE1 },
                });

        assertSameProperties(
                destinationV1, destinationE1, 0,
                new ListAssignMove<>(variableDescriptor, v1, e1, 0).rebase(destinationScoreDirector));
    }

    static void assertSameProperties(
            Object movedValue, Object destinationEntity, int destinationIndex,
            ListAssignMove<?> move) {
        assertThat(move.getMovedValue()).isSameAs(movedValue);
        assertThat(move.getDestinationEntity()).isSameAs(destinationEntity);
        assertThat(move.getDestinationIndex()).isEqualTo(destinationIndex);
    }

    @Test
    void toStringTest() {
        TestdataListValue v1 = new TestdataListValue("1");
        TestdataListEntity e1 = new TestdataListEntity("E1");

        ListVariableDescriptor<TestdataListSolution> variableDescriptor =
                TestdataListEntity.buildVariableDescriptorForValueList();

        assertThat(new ListAssignMove<>(variableDescriptor, v1, e1, 15)).hasToString("1 {null -> E1[15]}");
    }
}


text:
class VPathEditor : public EditTSCtrl
{
    typedef EditTSCtrl Parent;

public:

    enum RenderType
    {
        k_RenderSegments,
        k_RenderNodes,
    };

    enum EditMode
    {
        k_Gizmo,
        k_AddNode,
        k_DeleteNode
    };

    struct Selection
    {
        Selection( void ) :
                Path( NULL ),
                Node( -1 )
        {
            TangentHandle[0].zero();
            TangentHandle[1].zero();
        };

        VPath     *Path;
        S32        Node;
        Point3F    TangentHandle[2];
    };

    struct PathEditAction
    {
        PathEditAction( void ) :
                Dirty( false ),
                Transform( true )
        {
            // Void.
        };

        bool        Dirty;
        MatrixF     Transform;
    };

    struct NodeEditAction
    {
        NodeEditAction( void ) :
                Dirty( false ),
                Position( 0.f, 0.f, 0.f ),
                Rotation( 0.f, 0.f, 0.f, 0.f ),
                Weight( 0.f )
        {
            // Void.
        };

        bool        Dirty;
        Point3F     Position;
        QuatF       Rotation;
        F32         Weight;
    };

    bool                mIsDirty;
    EditMode            mEditMode;

    Selection           mSelection;
    PathEditAction      mPathEdit;
    NodeEditAction      mNodeEdit;

    bool                mEditWeight;
    S32                 mEditWeightHandle;

    GFXStateBlockRef    mStateBlock;

public:

    VPathEditor( void );

    virtual bool    onAdd( void );
    virtual bool    onWake( void );

    static  void    initPersistFields( void );

    // Gui Events.

    virtual void    on3DMouseDown( const Gui3DMouseEvent &pEvent );
    virtual void    on3DMouseUp( const Gui3DMouseEvent &pEvent );
    virtual void    on3DMouseMove( const Gui3DMouseEvent &pEvent );
    virtual void    on3DMouseDragged( const Gui3DMouseEvent &pEvent );

    // Render Methods.

    virtual void    setStateBlock( void );
    virtual void    renderScene( const RectI &pUpdateRect );
    void            renderPaths( const RenderType &pRenderType );

    void            renderPath( const RenderType &pRenderType, VPath *pPath, const ColorI &pColor );
    void            renderLinearPath( VPath *pPath, const ColorI &pColor );
    void            renderBezierPath( VPath *pPath, const ColorI &pColor );

    DECLARE_CONOBJECT( VPathEditor );

public:

    // Reference Methods.

    VPath          *getClientPath( VPath *pPath );

    // Selection Methods.

    inline bool     isValidSelection( void ) { return ( mSelection.Path != NULL && mSelection.Node != -1 ); };

    bool            updateSelection( const Gui3DMouseEvent &pEvent );
    void            updateSelection( VPath *pPathObject, const S32 &pNodeIndex );
    void            updateSelection( void );

    // Weight Editing.

    bool            isEditingWeight( const Gui3DMouseEvent &pEvent );
    inline bool     isEditingWeight( void ) { return mEditWeight; };

    void            updateWeight( const Gui3DMouseEvent &pEvent );

    // Path Editor.

    bool            getPointOnPath( VPath *pPath, const Gui3DMouseEvent &pEvent, S32 &pNode, MatrixF &pTransform );
    bool            getPointOnLinearPath( VPath *pPath, const Gui3DMouseEvent &pEvent, S32 &pNode, MatrixF &pTransform );
    bool            getPointOnBezierPath( VPath *pPath, const Gui3DMouseEvent &pEvent, S32 &pNode, MatrixF &pTransform );

    void            setPathPosition( const Point3F &pPosition );
    void            setPathRotation( const QuatF &pRotation );
    void            setPathTransform( const MatrixF &pTransform );
    void            setPathScale( const VectorF &pScale );

    // Node Editing.

    void            addNode( const Gui3DMouseEvent &pEvent );
    void            deleteNode( const S32 &pNodeIndex );

    void            setNodePosition( const S32 &pNodeIndex, const Point3F &pPosition );
    void            setNodeRotation( const S32 &pNodeIndex, const QuatF &pRotation );
    void            setNodeWeight( const S32 &pNodeIndex, const F32 &pWeight );
    void            setNodeOrientationMode( const S32 &pNodeIndex, const VPathNode::eOrientationType &pType );
    void            setNodeOrientationMode( const S32 &pNodeIndex, const VPathNode::eOrientationType &pType, const Point3F &pPoint );

    void            pushPathEdit( void );
    void            popPathEdit( void );

    void            pushNodeEdit( void );
    void            popNodeEdit( void );

    void            setWorldEditorDirty( void );

private:

    class VPathEditorEditPathAction : public UndoAction
    {
    public:

        VPathEditorEditPathAction( const UTF8 *pName = "" ) :
                UndoAction( pName )
        {
            // Void.
        };

        VPathEditor               *mEditor;

        VPath                     *mPath;
        MatrixF                    mTransform;

        virtual void    undo( void );
        virtual void    redo( void );
    };

    class VPathEditorEditNodeAction : public UndoAction
    {
    public:

        VPathEditorEditNodeAction( const UTF8 *pName = "" ) :
                UndoAction( pName )
        {
            // Void.
        };

        VPathEditor               *mEditor;

        VPath                     *mPath;
        S32                        mNodeIndex;

        Point3F                    mNodePosition;
        QuatF                      mNodeRotation;
        F32                        mNodeWeight;

        VPathNode::sOrientation    mNodeOrientation;

        virtual void    undo( void );
        virtual void    redo( void );
    };

    class VPathEditorAddNodeAction : public VPathEditorEditNodeAction
    {
    public:

        VPathEditorAddNodeAction( const UTF8 *pName = "" ) :
                VPathEditorEditNodeAction( "Add Node" )
        {
            // Void.
        };

        virtual void    undo( void );
        virtual void    redo( void );
    };

    class VPathEditorDeleteNodeAction : public VPathEditorEditNodeAction
    {
    public:

        VPathEditorDeleteNodeAction( const UTF8 *pName = "" ) :
                VPathEditorEditNodeAction( "Delete Node" )
        {
            // Void.
        };

        virtual void    undo( void );
        virtual void    redo( void );
    };
};

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

// Define Types.
typedef VPathEditor::EditMode VPathEditorMode;

// Declare Enum Types.
DefineEnumType( VPathEditorMode );

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

namespace Utility
{
    bool            FindNearestDistanceBetweenLines( const Point3F &pA0, const Point3F &pA1, const Point3F &pB0, const Point3F &pB1, Point3F *pOutA, Point3F *pOutB, F32 *pDist );

    bool            IntersectLineSegment( const Point3F &pA0, const Point3F &pA1, const Point3F &pB0, const Point3F &pB1, const bool pSnap, Point3F *pX );
    bool            FindNearestPointOnLine( const Point3F &pSrcPosition, const Point3F &pA0, const Point3F &pA1, Point3F *pDstPosition );

    F32             GetPitch( const VectorF &pVec );
    F32             GetYaw( const VectorF &pVec );
};

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

#endif // _VT_VPATHEDITOR_H_


text:
Copy in the font files:

    sudo pip install Pillow
    sudo pip install tinycss
    python font-awesome-to-png.py --font ../fonts/fontawesome-webfont.ttf --css ../css/font-awesome.css --size 32 --color blue ALL


text:
package com.orange.datavenue.operation;

import android.os.AsyncTask;
import android.util.Log;

import com.orange.datavenue.OperationCallback;
import com.orange.datavenue.client.Config;
import com.orange.datavenue.client.api.AccountsApi;

import com.orange.datavenue.client.common.HTTPException;
import com.orange.datavenue.client.common.SDKException;
import com.orange.datavenue.client.model.Account;
import com.orange.datavenue.client.model.AccountsUpdate;

/**
 * @author Stéphane SANDON
 */
public class UpdateAccountOperation extends AsyncTask<String, Void, String> {

    private static final String TAG_NAME = UpdateAccountOperation.class.getSimpleName();

    String  mOpeClient = null;
    String  mKey       = null;
    String  mAccountId = null;
    Account mAccount   = null;
    AccountsUpdate mAccountUpdate = null;

    OperationCallback mCallback  = null;
    Exception         mException = null;

    /**
     *
     * @param opeClient
     * @param key
     * @param accountId
     * @param accountUpdate
     * @param op
     */
    public UpdateAccountOperation(String opeClient, String key, String accountId, AccountsUpdate accountUpdate, OperationCallback op) {
        mOpeClient     = opeClient;
        mKey           = key;
        mAccountId     = accountId;
        mAccountUpdate = accountUpdate;
        mCallback      = op;
    }

    @Override
    protected String doInBackground(String... strings) {
        Config config = new Config(mOpeClient, mKey);
        AccountsApi accountsApi = new AccountsApi(config);

        try {
            accountsApi.updateAccount(mAccountId, mAccountUpdate);
            mAccount = accountsApi.getAccount(mAccountId);
        } catch(HTTPException e) {
            Log.e(TAG_NAME, e.toString());
            mException = e;
        } catch (SDKException s) {
            Log.e(TAG_NAME, s.toString());
            mException = s;
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        if (mCallback != null) {
            mCallback.process(mAccount, mException);
        }
    }
}


text:
from struct import unpack, unpack_from

from vertica_python.vertica.messages.message import BackendMessage

class RowDescription(BackendMessage):

    def __init__(self, data):

        self.fields = []
        field_count = unpack('!H', data[0:2])[0]
        pos = 2

        for i in range(field_count):
            field_info = unpack_from("!{0}sxIHIHIH".format(data.find(b'\x00', pos) - pos), data, pos)
            self.fields.append({
                'name': field_info[0],
                'table_oid': field_info[1],
                'attribute_number': field_info[2],
                'data_type_oid': field_info[3],
                'data_type_size': field_info[4],
                'type_modifier': field_info[5],
                'format_code': field_info[6],
            })

            pos += 19 + len(field_info[0])

RowDescription._message_id(b'T')