text:
require 'active_support/core_ext/string/access'

module ActiveMerchant
  module Billing
    class DataCashGateway < Gateway
      self.default_currency = 'GBP'
      self.supported_countries = ['GB']

      self.supported_cardtypes = [ :visa, :master, :american_express, :discover, :diners_club, :jcb, :maestro ]

      self.homepage_url = 'http://www.datacash.com/'
      self.display_name = 'DataCash'

      self.test_url = 'https://testserver.datacash.com/Transaction'
      self.live_url = 'https://mars.transaction.datacash.com/Transaction'

      AUTH_TYPE = 'auth'
      CANCEL_TYPE = 'cancel'
      FULFILL_TYPE = 'fulfill'
      PRE_TYPE = 'pre'
      REFUND_TYPE = 'refund'
      TRANSACTION_REFUND_TYPE = 'txn_refund'

      POLICY_ACCEPT = 'accept'
      POLICY_REJECT = 'reject'

      # Datacash success code
      DATACASH_SUCCESS = '1'

      def initialize(options = {})
        requires!(options, :login, :password)
        super
      end

      def purchase(money, authorization_or_credit_card, options = {})
        requires!(options, :order_id)

        if authorization_or_credit_card.is_a?(String)
          request = build_purchase_or_authorization_request_with_continuous_authority_reference_request(AUTH_TYPE, money, authorization_or_credit_card, options)
        else
          request = build_purchase_or_authorization_request_with_credit_card_request(AUTH_TYPE, money, authorization_or_credit_card, options)
        end

        commit(request)
      end

      def authorize(money, authorization_or_credit_card, options = {})
        requires!(options, :order_id)

        if authorization_or_credit_card.is_a?(String)
          request = build_purchase_or_authorization_request_with_continuous_authority_reference_request(AUTH_TYPE, money, authorization_or_credit_card, options)
        else
          request = build_purchase_or_authorization_request_with_credit_card_request(PRE_TYPE, money, authorization_or_credit_card, options)
        end

        commit(request)
      end

      def capture(money, authorization, options = {})
        commit(build_void_or_capture_request(FULFILL_TYPE, money, authorization, options))
      end

      def void(authorization, options = {})
        request = build_void_or_capture_request(CANCEL_TYPE, nil, authorization, options)

        commit(request)
      end

      def credit(money, reference_or_credit_card, options = {})
        if reference_or_credit_card.is_a?(String)
          ActiveMerchant.deprecated CREDIT_DEPRECATION_MESSAGE
          refund(money, reference_or_credit_card)
        else
          request = build_credit_request(money, reference_or_credit_card, options)
          commit(request)
        end
      end

      def refund(money, reference, options = {})
        commit(build_transaction_refund_request(money, reference))
      end

      def supports_scrubbing?
        true
      end

      def scrub(transcript)
        transcript.
          gsub(/(<pan>)\d(<\/pan>)/i, '\1[FILTERED]\2').
          gsub(/(<cv2>)\d+(<\/cv2>)/i, '\1[FILTERED]\2').
          gsub(/(<password>).+(<\/password>)/i, '\1[FILTERED]\2')
      end

      def query(reference)
        request = query_request(reference)
        commit(request)
      end

      def threedsecure_authorize(authorization)
        request = threedsecure_authorization_request(authorization)
        commit(request)
      end

      def threedsecure_verify(authorization, pares_message)
        request = threedsecure_authorization_request(authorization, pares_message)
        commit(request)
      end

      private

      def threedsecure_authorization_request(reference, pares_message = nil)
        xml = Builder::XmlMarkup.new :indent => 2
        xml.instruct!
        xml.tag! :Request do
          add_authentication(xml)
          xml.tag! :Transaction do
            xml.tag! :HistoricTxn do
              xml.tag! :reference, reference
              xml.tag! :method, 'threedsecure_authorization_request'
              if pares_message
                xml.tag! :pares_message, pares_message
              end
            end

          end
        end
        xml.target!

      end

      def query_request(reference)
        xml = Builder::XmlMarkup.new :indent => 2
        xml.instruct!
        xml.tag! :Request do
          add_authentication(xml)
          xml.tag! :Transaction do
            xml.tag! :HistoricTxn do
              xml.tag! :reference, reference
              xml.tag! :method, 'query'
            end
          end
        end
        xml.target!
      end

      def build_void_or_capture_request(type, money, authorization, options)
        parsed_authorization = parse_authorization_string(authorization)
        xml = Builder::XmlMarkup.new :indent => 2
        xml.instruct!
        xml.tag! :Request, :version => '2' do
          add_authentication(xml)

          xml.tag! :Transaction do
            xml.tag! :HistoricTxn do
              xml.tag! :reference, parsed_authorization[:reference]
              xml.tag! :authcode, parsed_authorization[:auth_code]
              xml.tag! :method, type
            end

            if money
              xml.tag! :TxnDetails do
                xml.tag! :merchantreference, format_reference_number(options[:order_id])
                xml.tag! :amount, amount(money), :currency => options[:currency] || currency(money)
                xml.tag! :capturemethod, 'ecomm'
              end
            end
          end
        end
        xml.target!
      end

      def build_purchase_or_authorization_request_with_credit_card_request(type, money, credit_card, options)
        xml = Builder::XmlMarkup.new :indent => 2
        xml.instruct!
        xml.tag! :Request, :version => '2' do
          add_authentication(xml)

          xml.tag! :Transaction do
            if options[:set_up_continuous_authority]
              xml.tag! :ContAuthTxn, :type => 'setup'
            end
            xml.tag! :CardTxn do
              xml.tag! :method, type
              add_credit_card(xml, credit_card, options[:billing_address])
            end
            xml.tag! :TxnDetails do
              xml.tag! :merchantreference, format_reference_number(options[:order_id])
              xml.tag! :amount, amount(money), :currency => options[:currency] || currency(money)
              xml.tag! :capturemethod, (options[:threedsecure] ? "ecomm" : "cnp")

              if options[:threedsecure]
                xml.tag! :ThreeDSecure do
                  xml.tag! :purchase_datetime, Time.now.strftime("%Y%m%d %H:%M:%S")
                  xml.tag! :purchase_desc, options[:threedsecure][:purchase_desc]
                  xml.tag! :verify, 'yes'
                  xml.tag! :merchant_url, options[:threedsecure][:merchant_url]
                  xml.tag! :Browser do
                    xml.tag! :device_category, options[:threedsecure][:device_category]
                    xml.tag! :user_agent, options[:threedsecure][:user_agent]
                    xml.tag! :accept_headers, options[:threedsecure][:accept_headers]
                  end
                end
              end
            end
          end
        end
        xml.target!
      end

      def build_purchase_or_authorization_request_with_continuous_authority_reference_request(type, money, authorization, options)
        parsed_authorization = parse_authorization_string(authorization)
        raise ArgumentError, 'The continuous authority reference is required for continuous authority transactions' if parsed_authorization[:ca_reference].blank?

        xml = Builder::XmlMarkup.new :indent => 2
        xml.instruct!
        xml.tag! :Request, :version => '2' do
          add_authentication(xml)
          xml.tag! :Transaction do
            xml.tag! :ContAuthTxn, :type => 'historic'
            xml.tag! :HistoricTxn do
              xml.tag! :reference, parsed_authorization[:ca_reference]
              xml.tag! :method, type
            end
            xml.tag! :TxnDetails do
              xml.tag! :merchantreference, format_reference_number(options[:order_id])
              xml.tag! :amount, amount(money), :currency => options[:currency] || currency(money)
              xml.tag! :capturemethod, 'cont_auth'
            end
          end
        end
        xml.target!
      end

      def build_transaction_refund_request(money, authorization)
        parsed_authorization = parse_authorization_string(authorization)
        xml = Builder::XmlMarkup.new :indent => 2
        xml.instruct!
        xml.tag! :Request, :version => '2' do
          add_authentication(xml)
          xml.tag! :Transaction do
            xml.tag! :HistoricTxn do
              xml.tag! :reference, parsed_authorization[:reference]
              xml.tag! :method, TRANSACTION_REFUND_TYPE
            end
            unless money.nil?
              xml.tag! :TxnDetails do
                xml.tag! :amount, amount(money)
                xml.tag! :capturemethod, 'ecomm'
              end
            end
          end
        end
        xml.target!
      end

      def build_credit_request(money, credit_card, options)
        xml = Builder::XmlMarkup.new :indent => 2
        xml.instruct!
        xml.tag! :Request, :version => '2' do
          add_authentication(xml)
          xml.tag! :Transaction do
            xml.tag! :CardTxn do
              xml.tag! :method, REFUND_TYPE
              add_credit_card(xml, credit_card, options[:billing_address])
            end
            xml.tag! :TxnDetails do
              xml.tag! :merchantreference, format_reference_number(options[:order_id])
              xml.tag! :amount, amount(money)
              xml.tag! :capturemethod, 'ecomm'
            end
          end
        end
        xml.target!
      end

      def add_authentication(xml)
        xml.tag! :Authentication do
          xml.tag! :client, @options[:login]
          xml.tag! :password, @options[:password]
        end
      end

      def add_credit_card(xml, credit_card, address)
        xml.tag! :Card do
          # DataCash calls the CC number 'pan'
          xml.tag! :pan, credit_card.number
          xml.tag! :expirydate, format_date(credit_card.month, credit_card.year)

          xml.tag! :Cv2Avs do
            xml.tag! :cv2, credit_card.verification_value if credit_card.verification_value?
            if address
              xml.tag! :street_address1, address[:address1] unless address[:address1].blank?
              xml.tag! :street_address2, address[:address2] unless address[:address2].blank?
              xml.tag! :street_address3, address[:address3] unless address[:address3].blank?
              xml.tag! :street_address4, address[:address4] unless address[:address4].blank?
              xml.tag! :postcode, address[:zip] unless address[:zip].blank?
            end

            # The ExtendedPolicy defines what to do when the passed data
            # matches, or not...
            #
            # All of the following elements MUST be present for the
            # xml to be valid (or can drop the ExtendedPolicy and use
            # a predefined one
            xml.tag! :ExtendedPolicy do
              xml.tag! :cv2_policy,
                :notprovided =>   POLICY_REJECT,
                :notchecked =>    POLICY_ACCEPT,
                :matched =>       POLICY_ACCEPT,
                :notmatched =>    POLICY_REJECT,
                :partialmatch =>  POLICY_REJECT
              xml.tag! :postcode_policy,
                :notprovided =>   POLICY_ACCEPT,
                :notchecked =>    POLICY_ACCEPT,
                :matched =>       POLICY_ACCEPT,
                :notmatched =>    POLICY_REJECT,
                :partialmatch =>  POLICY_ACCEPT
              xml.tag! :address_policy,
                :notprovided =>   POLICY_ACCEPT,
                :notchecked =>    POLICY_ACCEPT,
                :matched =>       POLICY_ACCEPT,
                :notmatched =>    POLICY_REJECT,
                :partialmatch =>  POLICY_ACCEPT
            end
          end
        end
      end

      def commit(request)
        response = parse(ssl_post(test? ? self.test_url : self.live_url, request))

        Response.new(response[:status] == '1', response[:reason], response,
          :test => test?,
          :authorization => "#{response[:datacash_reference]};#{response[:authcode]};#{response[:ca_reference]}"
        )
      end

      def format_date(month, year)
        "#{format(month, :two_digits)}/#{format(year, :two_digits)}"
      end

      def parse(body)
        response = {}
        xml = REXML::Document.new(body)
        root = REXML::XPath.first(xml, '//Response')

        root.elements.to_a.each do |node|
          parse_element(response, node)
        end

        response
      end

      def parse_element(response, node)
        if node.has_elements?
          node.elements.each { |e| parse_element(response, e) }
        else
          response[node.name.underscore.to_sym] = node.text
        end
      end

      def format_reference_number(number)
        number.to_s.gsub(/[^A-Za-z0-9]/, '').rjust(6, '0').first(30)
      end

      def parse_authorization_string(authorization)
        reference, auth_code, ca_reference = authorization.to_s.split(';')
        {:reference => reference, :auth_code => auth_code, :ca_reference => ca_reference}
      end
    end
  end
end


text:
module ProposalsHelper
  def category_icon(category)
    case category
    when 'lodging'  then 'home'
    when 'services' then 'suitcase'
    when 'goods'    then 'gift'
    end
  end

  def category_tag(category)
    fa_tag(category_icon(category))
  end

  def fa_tag(icon, text: nil, tooltip: nil, placement: nil)
    text &&= " " + text
    placement ||= "bottom"
    tooltip &&= %(data-toggle="tooltip" title="#{tooltip}" data-placement="#{placement}" )
    %(<i #{tooltip}class="fa fa-#{icon}"></i>#{text}).html_safe
  end

  def wanted_icon
    "rotate-right"
  end

  def offer_icon
    "gift"
  end

  def community_icon
    "group"
  end

  def filtered_proposal_path(category = nil)
    type = params[:type].underscore.pluralize
    path = "#{type}_path"
    public_send(path, category: category)
  end
end

redpajama_set_name: RedPajamaGithub


text:
package uk.org.nbn.nbnv.importer.validation

import uk.org.nbn.nbnv.importer.testing.BaseFunSuite
import uk.org.nbn.nbnv.importer.records.NbnRecord
import org.mockito.Mockito._
import uk.org.nbn.nbnv.importer.fidelity.ResultLevel

class Nbnv85ValidatorSuite extends BaseFunSuite {

  test("should validate an integer easting and norhting"){
    val rec = mock[NbnRecord]
    when(rec.eastRaw).thenReturn(Some("123"))
    when(rec.northRaw).thenReturn(Some("123"))

    val v = new Nbnv85Validator
    val r = v.validate(rec)

    r.level should be (ResultLevel.DEBUG)
  }

  test("should validate a decimal easting and northing"){
    val rec = mock[NbnRecord]
    when(rec.eastRaw).thenReturn(Some("123.23"))
    when(rec.northRaw).thenReturn(Some("123.23"))

    val v = new Nbnv85Validator
    val r = v.validate(rec)

    r.level should be (ResultLevel.DEBUG)
  }

  test("should not validate negative values"){
    val rec = mock[NbnRecord]
    when(rec.eastRaw).thenReturn(Some("-1.123"))
    when(rec.northRaw).thenReturn(Some("-47.23"))

    val v = new Nbnv85Validator
    val r = v.validate(rec)

    r.level should be (ResultLevel.ERROR)
  }

  test("should not validate a non numeric easting"){
    val rec = mock[NbnRecord]
    when(rec.eastRaw).thenReturn(Some("123E"))
    when(rec.northRaw).thenReturn(Some("123"))

    val v = new Nbnv85Validator
    val r = v.validate(rec)

    r.level should be (ResultLevel.ERROR)
  }

  test("should not validate a non numeric norhing") {
    val rec = mock[NbnRecord]
    when(rec.eastRaw).thenReturn(Some("123"))
    when(rec.northRaw).thenReturn(Some("123E"))

    val v = new Nbnv85Validator
    val r = v.validate(rec)

    r.level should be (ResultLevel.ERROR)
  }

}


text:
{% extends "base.html" %}
{% block extra_css %}
<link rel="stylesheet" href="/static/css/ayi.css">
{% endblock extra_css %}
{% block content %}

{% endblock content %}
{% block extra_js %}

{% endblock extra_js %}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using JoinRpg.Experimental.Plugin.Interfaces;
using JoinRpg.Helpers;
using JoinRpg.Helpers.Web;
using QRCoder;

namespace JoinRpg.Experimental.Plugin.SteampunkDetective
{
  public class CluePrinterOperation : IPrintCardPluginOperation
  {
    private static readonly CompareCluesByFieldId ClueCompareByFieldId = new CompareCluesByFieldId();

    private class CompareCluesByFieldId : IEqualityComparer<SignDefinition>
    {
      public bool Equals(SignDefinition x, SignDefinition y) => x.FieldId == y.FieldId && x.FieldId !=0;

      public int GetHashCode(SignDefinition obj) => obj.FieldId;
    }

    private ClueConfiguration Config { get; set; }

    private int MaxCode { get; set; }
    private HashSet<int> UsedCodes { get; } = new HashSet<int>();

    public IEnumerable<HtmlCardPrintResult> PrintForCharacter(CharacterInfo character)
    {
      var possibleSigns =
        Config.SignDefinitions.Where(sign => sign.IsValidForCharacter(character))
          .SelectMany(s => Enumerable.Repeat(s, s.Weight))
          .ToArray();
      var fieldsToShowInQrCode = character.Fields.Where(f => possibleSigns.Any(s => s.FieldId == f.FieldId));
      var characterMasterDesc =
        $"{character.CharacterName} ({character.Groups.Select(g => g.ToString()).JoinStrings(",")}) {fieldsToShowInQrCode.Select(f => f.ToString()).JoinStrings(", ")}";

      if (Config.ShowHeaderClue)
      {
        yield return new HtmlCardPrintResult($"
{characterMasterDesc}
", CardSize.A7);
      }

      var random = Config.ConsistentGeneration ? new Random(character.CharacterId) : new Random();

      for (var i = 0; i < Config.CluePerCharacter; i++)
      {
        var characterQrCodeContents =
        $"{i}.{character.CharacterId} {character.Groups.Where(g => Config.GroupsToShowInQr.Contains(g.CharacterGroupId)).Select(g => g.ToString()).JoinStrings(",")} {character.CharacterName}";
        var qrCodeForCharacter = GenerateQrCodeForCharacter(character, characterQrCodeContents);
        yield return GenerateClue(possibleSigns, random, qrCodeForCharacter);
      }
    }

    private HtmlCardPrintResult GenerateClue(IReadOnlyCollection<SignDefinition> possibleSigns, Random random, string embeddedImageTag)
    {
      var randomCodes = random.GetRandomSource().Select(c => c % MaxCode).Where(c => !UsedCodes.Contains(c));

      var signs = possibleSigns
        .Shuffle(random)
        .Distinct(ClueCompareByFieldId)
        .Take(Config.MaxMeaningfulSignsCount)
        .Select(c => c.Code)
        .ToArray()
        .UnionUntilTotalCount(randomCodes, Config.MinNumberOfSignInClue)
        .Shuffle(random);
      var signString = signs
        .Select(c => c.ToString("D3"))
        .JoinStrings(" ");

      return
        new HtmlCardPrintResult(
          $@"

Карточка улики.

Оставьте ее на месте, если вы не детектив

{signString}

  {embeddedImageTag}

",
          CardSize.A7);
    }

    private string GenerateQrCodeForCharacter(CharacterInfo character, string qrCodeContents)
    {
      var qrGenerator = new QRCodeGenerator();
      var utf8Bytes = qrCodeContents.AsUtf8BytesWithLimit(90).ToArray();

      var key = Config.QrEncryptionKey;
      var encryptedBytes = key != null ? BouncyFacade.Encrypt(key, utf8Bytes) : Convert.ToBase64String(utf8Bytes);

      var qrCodeData = qrGenerator.CreateQrCode(encryptedBytes, QRCodeGenerator.ECCLevel.H);
      var qrCode = new QRCode(qrCodeData);
      var qrCodeImage = qrCode.GetGraphic(pixelsPerModule: 2);
      return qrCodeImage.ToEmbeddedImageTag();
    }

    public void SetConfiguration(IPluginConfiguration config)
    {
      if (config == null) throw new ArgumentNullException(nameof(config));

      Config = config.GetConfiguration<ClueConfiguration>();

      var maxCode = 1;
      var digits = Config.Digits;
      while (digits > 0)
      {
        maxCode *= 10;
        digits--;
      }
      MaxCode = maxCode - 1;

      foreach (var signDefinition in Config.SignDefinitions)
      {
        if (signDefinition.Code > MaxCode)
        {
          throw new PluginConfigurationIncorrectException($"Code {signDefinition.Code} is too large. Should be less than {MaxCode}");
        }
        if (UsedCodes.Contains(signDefinition.Code))
        {
          throw new PluginConfigurationIncorrectException($"Code {signDefinition.Code} is duplicated");
        }
        UsedCodes.Add(signDefinition.Code);
      }
    }
  }
}


text:
#define LOG_NDEBUG 0
#define LOG_TAG "CameraMetadataTestFunctional"
#include "cutils/log.h"
#include "cutils/properties.h"
#include "utils/Errors.h"

#include "gtest/gtest.h"
#include "system/camera_metadata.h"
#include "hardware/hardware.h"
#include "hardware/camera2.h"

#include "Camera2Device.h"
#include "utils/StrongPointer.h"

#include <gui/CpuConsumer.h>
#include <gui/Surface.h>

#include <string>

#include "CameraStreamFixture.h"
#include "TestExtensions.h"

namespace android {
namespace camera2 {
namespace tests {

//FIXME: dont hardcode
static CameraStreamParams METADATA_STREAM_PARAMETERS = {
    /*mFormat*/     HAL_PIXEL_FORMAT_YCrCb_420_SP,
    /*mHeapCount*/  2
};

class CameraMetadataTest
    : public ::testing::Test,
      public CameraStreamFixture {

public:
    CameraMetadataTest()
    : CameraStreamFixture(METADATA_STREAM_PARAMETERS) {
        TEST_EXTENSION_FORKING_CONSTRUCTOR;
    }

    ~CameraMetadataTest() {
        TEST_EXTENSION_FORKING_DESTRUCTOR;
    }

    int GetTypeFromTag(uint32_t tag) const {
        return get_camera_metadata_tag_type(tag);
    }

    int GetTypeFromStaticTag(uint32_t tag) const {
        const CameraMetadata& staticInfo = mDevice->info();
        camera_metadata_ro_entry entry = staticInfo.find(tag);
        return entry.type;
    }

    int GetEntryCountFromStaticTag(uint32_t tag) const {
        const CameraMetadata& staticInfo = mDevice->info();
        camera_metadata_ro_entry entry = staticInfo.find(tag);
        return entry.count;
    }

    bool HasElementInArrayFromStaticTag(uint32_t tag, int32_t element) const {
        const CameraMetadata& staticInfo = mDevice->info();
        camera_metadata_ro_entry entry = staticInfo.find(tag);
        for (size_t i = 0; i < entry.count; ++i) {
            if (entry.data.i32[i] == element)
                return true;
        }
        return false;
    }

protected:

};

TEST_F(CameraMetadataTest, types) {

    TEST_EXTENSION_FORKING_INIT;

    //FIXME: set this up in an external file of some sort (xml?)
    {
        char value[PROPERTY_VALUE_MAX];
        property_get("ro.build.id", value, "");
        std::string str_value(value);

        if (str_value == "manta")
        {
            EXPECT_EQ(TYPE_BYTE,
                GetTypeFromStaticTag(ANDROID_QUIRKS_TRIGGER_AF_WITH_AUTO));
            EXPECT_EQ(TYPE_BYTE,
                GetTypeFromStaticTag(ANDROID_QUIRKS_USE_ZSL_FORMAT));
            EXPECT_EQ(TYPE_BYTE,
                GetTypeFromStaticTag(ANDROID_QUIRKS_METERING_CROP_REGION));
        }
    }

    /*
    TODO:
    go through all static metadata and make sure all fields we expect
    that are there, ARE there.

    dont worry about the type as its enforced by the metadata api
    we can probably check the range validity though
    */

    if (0) {
        camera_metadata_ro_entry entry;
        EXPECT_EQ(TYPE_BYTE,     entry.type);
        EXPECT_EQ(TYPE_INT32,    entry.type);
        EXPECT_EQ(TYPE_FLOAT,    entry.type);
        EXPECT_EQ(TYPE_INT64,    entry.type);
        EXPECT_EQ(TYPE_DOUBLE,   entry.type);
        EXPECT_EQ(TYPE_RATIONAL, entry.type);
    }
}

TEST_F(CameraMetadataTest, RequiredFormats) {
    TEST_EXTENSION_FORKING_INIT;

    EXPECT_TRUE(
        HasElementInArrayFromStaticTag(ANDROID_SCALER_AVAILABLE_FORMATS,
                                      HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED));

    EXPECT_TRUE(
        HasElementInArrayFromStaticTag(ANDROID_SCALER_AVAILABLE_FORMATS,
                                       HAL_PIXEL_FORMAT_BLOB)); // JPEG

    EXPECT_TRUE(
        HasElementInArrayFromStaticTag(ANDROID_SCALER_AVAILABLE_FORMATS,
                                       HAL_PIXEL_FORMAT_YCrCb_420_SP)); // NV21

    EXPECT_TRUE(
        HasElementInArrayFromStaticTag(ANDROID_SCALER_AVAILABLE_FORMATS,
                                       HAL_PIXEL_FORMAT_YV12));
}

TEST_F(CameraMetadataTest, SaneResolutions) {
    TEST_EXTENSION_FORKING_INIT;

    // Iff there are listed raw resolutions, the format should be available
    int rawResolutionsCount =
            GetEntryCountFromStaticTag(HAL_PIXEL_FORMAT_RAW_SENSOR);
    EXPECT_EQ(rawResolutionsCount > 0,
        HasElementInArrayFromStaticTag(ANDROID_SCALER_AVAILABLE_FORMATS,
                                        HAL_PIXEL_FORMAT_RAW_SENSOR));

    // Required processed sizes.
    int processedSizeCount =
           GetEntryCountFromStaticTag(ANDROID_SCALER_AVAILABLE_PROCESSED_SIZES);
    EXPECT_NE(0, processedSizeCount);
    EXPECT_EQ(0, processedSizeCount % 2); // multiple of 2 (w,h)

    // Required JPEG sizes
    int jpegSizeCount =
            GetEntryCountFromStaticTag(ANDROID_SCALER_AVAILABLE_JPEG_SIZES);
    EXPECT_NE(0, jpegSizeCount);
    EXPECT_EQ(0, jpegSizeCount % 2); // multiple of 2 (w,h)

}

}
}
}


text:
<resources>
    <string name="current_language">Español</string>
</resources>


text:
var profiler = require('../decorators/profiler'),
    wrap     = require('../helpers/wrapper'),
    fs       = require('fs'),
    dr       = require('doctor'),
    config   = require('../../config.json'),
    hashes   = require('../collections/hashes'),
    profiles = require('../collections/profiles'),
    time     = require('microtime'),
    mkdirp   = require('mkdirp'),
    path     = require('path'),
    fns      = { }

function _set(prop, value) {
  if (typeof prop === 'string')
    this[prop] = value
  else
    for (var i in prop)
      if (prop.hasOwnProperty(i))
        _set.call(this, i, prop[i])
}

function globalProfiler(items) {
  require.extensions['.js'] = function (module, file) {
    var skip = false,
        prof = { }

    var reg = function register(info) {

      if (info.type.indexOf('function') > -1) {

        var prof = profiles.register(info.source, file),
            name = info.source.substring(9, info.source.indexOf('('))

        name = name === '' ? hashes.add('', file + info.line + info.column) : name

        this[file + '::' + name] = prof
      }
    }.bind(fns)

    var enter = function enter(info) {

      if (info.type.indexOf('function') > -1) {

        var name    = info.name === 'function' ? hashes.add('', file + info.line + info.column) : info.name
            profile = this[file + '::' + name],
            latest  = profile.get('invokations').length - 1

        if (latest === -1) {

          var prof = { initialized: time.now(), observers: [ ] }
              p    = {
                set: function()     { _set.apply(prof, arguments); return this; },
                get: function(prop) { return prof[prop]  }
              }

          profile.get('invokations').push(p)

          latest = 0
        }

        profile.
          set({line: info.line, column: info.column}).
          get('invokations')[latest].
          set('start', time.now())
      }
    }.bind(fns)

    var exit = function exit(info) {
      if (info.type.indexOf('function') > -1) {
        var name    = info.name === 'function' ? hashes.add('', file + info.line + info.column) : info.name
            profile = this[file + '::' + name],
            latest  = profile.get('invokations').length - 1

        if (latest === -1) {
          var prof = { initialized: time.now(), observers: [ ] }
              p    = {
                set: function()     { _set.apply(prof, arguments); return this; },
                get: function(prop) { return prof[prop]  }
              }

          profile.get('invokations').push(p)

          latest = 0
        }

        profile.
          get('invokations')[latest].
          set('end', time.now())
      }
    }.bind(fns)

    for (var i = 0; i < config.no.length; i++)
      if (file.indexOf(config.no[i]) > -1) {
        skip = true
        break
      }

    if (skip === false) {
      var doctored = dr.insertEnterExitHooksSync(file, enter, exit, reg),
          pth      = file.split('/'),
          name     = pth.pop(),
          base     = __dirname.split('/')

      base.pop()
      base.pop()

      var location = base.join('/') + '/doctored' + pth.join('/') + '/'

      console.error("\nDr'd", location)

      mkdirp.sync(location)

      fs.writeFileSync(location + name, doctored)

      module._compile(doctored, location + name)

      if (typeof Proxy === 'undefined')
        module.exports = wrap(profiler.wrap, module.exports)
      else
        module.exports = profiler.proxy(module.exports)

    } else
      module._compile(fs.readFileSync(file, 'utf8'), file)
  };
}

exports.profile = globalProfiler


text:
if(NOT EXISTS "${RunCMake_TEST_BINARY_DIR}/CMakeCache.txt")
  message(FATAL_ERROR "missing test prerequisite CMakeCache.txt")
endif()

set(CMAKE_INSTALL_CMAKE "${RunCMake_TEST_BINARY_DIR}/cmake_install.cmake")

if(EXISTS ${CMAKE_INSTALL_CMAKE})
  message(FATAL_ERROR "${CMAKE_INSTALL_CMAKE} should not exist")
endif()


text:
<?php

/**
 * Featured Content.
 *
 * This module will allow users to define a subset of posts
 * to be displayed in a theme-designated featured content area.
 *
 * This feature will only be activated for themes that declare
 * that they support it. This can be done by adding code similar
 * to the following during the "after_setup_theme" action:
 *
 * add_theme_support( 'featured-content', array(
 *     'featured_content_filter' => 'mytheme_get_featured_content',
 *     'description' => 'Describe the featured content area.',
 *     'max_posts' => 20,
 * ) );
 *
 * For maximum compatibility with different methods of posting
 * users will designate a featured post tag to associate posts
 * to. Since this tag now has special meaning beyond that of a
 * normal tags, users will have the ability to hide it from the
 * front-end of their site.
 */
class Featured_Content {

	/**
	 * The maximum number of posts that a featured content
	 * area can contain. We define a default value here but
	 * themes can override this by defining a "max_posts"
	 * entry in the second parameter passed in the call to
	 * add_theme_support( 'featured-content' ).
	 *
	 * @see Featured_Content::init()
	 */
	public static $max_posts = 15;

	/**
	 * Instantiate.
	 *
	 * All custom functionality will be hooked into the "init" action.
	 */
	public static function setup() {
		add_action( 'init', array( __class__, 'init' ) );
	}

	/**
	 * Conditionally Hook into WordPress.
	 *
	 * Themes must declare that they support this module by adding
	 * add_theme_support( 'featured-content' ); during after_setup_theme.
	 *
	 * If no theme support is found there is no need to hook into
	 * WordPress. We'll just return early instead.
	 *
	 * @uses Featured_Content::$max_posts
	 */
	public static function init() {
		$theme_support = get_theme_support( 'featured-content' );

		// Return early if theme does not support featured content.
		if ( ! $theme_support )
			return;

		// An array of named arguments must be passed as
		// the second parameter of add_theme_support().
		if ( ! isset( $theme_support[0] ) )
			return;

		// Return early if "featured_content_filter" has not been defined.
		if ( ! isset( $theme_support[0]['featured_content_filter'] ) )
			return;

		$filter = $theme_support[0]['featured_content_filter'];

		// Themes can override the number of max posts.
		if ( isset( $theme_support[0]['max_posts'] ) )
			self::$max_posts = absint( $theme_support[0]['max_posts'] );

		add_filter( $filter,                 array( __CLASS__, 'get_featured_posts' ) );
		add_action( 'admin_init',            array( __CLASS__, 'register_setting' ) );
		add_action( 'save_post',             array( __CLASS__, 'delete_transient' ) );
		add_action( 'delete_post_tag',       array( __CLASS__, 'delete_post_tag' ) );
		add_action( 'pre_get_posts',         array( __CLASS__, 'pre_get_posts' ) );

		// Hide "featured" tag from the front-end.
		if ( self::get_setting( 'hide-tag' ) ) {
			add_filter( 'get_terms',     array( __CLASS__, 'hide_featured_term' ), 10, 2 );
			add_filter( 'get_the_terms', array( __CLASS__, 'hide_the_featured_term' ), 10, 3 );
		}
	}

	/**
	 * Get Featured Posts.
	 *
	 * This method is not intended to be called directly.
	 * Theme developers should place a filter directly in
	 * their theme and then pass its name as a value of the
	 * "featured_content_filter" key in the array passed as
	 * the $args parameter during the call to:
	 * add_theme_support( 'featured-content', $args ).
	 *
	 * @uses Featured_Content::get_featured_post_ids()
	 *
	 * @return array|bool
	 */
	public static function get_featured_posts() {
		$post_ids = self::get_featured_post_ids();

		// User has disabled Featured Content.
		if ( false === $post_ids )
			return false;

		// No need to query if there is are no featured posts.
		if ( empty( $post_ids ) )
			return array();

		$featured_posts = get_posts( array(
			'include'        => $post_ids,
			'posts_per_page' => count( $post_ids )
		) );

		return $featured_posts;
	}

	/**
	 * Get Featured Post IDs.
	 *
	 * This function will return the an array containing the
	 * post IDs of all featured posts.
	 *
	 * Sets the "featured_content_ids" transient.
	 *
	 * @return array|false Array of post IDs. false if user has disabled this feature.
	 */
	public static function get_featured_post_ids() {
		$settings = self::get_setting();

		// Return false if the user has disabled this feature.
		$tag = $settings['tag-id'];
		if ( empty( $tag ) )
			return false;

		// Return array of cached results if they exist.
		$featured_ids = get_transient( 'featured_content_ids' );
		if ( ! empty( $featured_ids ) )
			return array_map( 'absint', (array) $featured_ids );

		// Query for featured posts.
		$featured = get_posts( array(
			'numberposts' => $settings['quantity'],
			'tax_query'   => array(
				array(
					'field'    => 'term_id',
					'taxonomy' => 'post_tag',
					'terms'    => $tag,
				),
			),
		) );

		// Return empty array if no featured content exists.
		if ( ! $featured )
			return array();

		// Ensure correct format before save/return.
		$featured_ids = wp_list_pluck( (array) $featured, 'ID' );
		$featured_ids = array_map( 'absint', $featured_ids );

		set_transient( 'featured_content_ids', $featured_ids );

		return $featured_ids;
	}

	/**
	 * Delete Transient.
	 *
	 * Hooks in the "save_post" action.
	 * @see Featured_Content::validate_settings().
	 */
	public static function delete_transient() {
		delete_transient( 'featured_content_ids' );
	}

	/**
	 * Exclude featured posts from the blog query when the blog is the front-page.
	 *
	 * Filter the home page posts, and remove any featured post ID's from it. Hooked
	 * onto the 'pre_get_posts' action, this changes the parameters of the query
	 * before it gets any posts.
	 *
	 * @uses Featured_Content::get_featured_post_ids();
	 * @param WP_Query $query
	 * @return WP_Query Possibly modified WP_query
	 */
	public static function pre_get_posts( $query = false ) {

		// Bail if not home, not a query, not main query.
		if ( ! is_home() || ! is_a( $query, 'WP_Query' ) || ! $query->is_main_query() )
			return;

		$page_on_front = get_option( 'page_on_front' );

		// Bail if the blog page is not the front page.
		if ( ! empty( $page_on_front ) )
			return;

		$featured = self::get_featured_post_ids();

		// Bail if no featured posts.
		if ( ! $featured )
			return;

		// We need to respect post ids already in the blacklist.
		$post__not_in = $query->get( 'post__not_in' );

		if ( ! empty( $post__not_in ) ) {
			$featured = array_merge( (array) $post__not_in, $featured );
			$featured = array_unique( $featured );
		}

		$query->set( 'post__not_in', $featured );
	}

	/**
	 * Reset tag option when the saved tag is deleted.
	 *
	 * It's important to mention that the transient needs
	 * to be deleted too. While it may not be obvious by
	 * looking at the function alone, the transient is
	 * deleted by Featured_Content::validate_settings().
	 *
	 * @param int $tag_id the term_id of the tag that has been deleted.
	 *
	 * Hooks in the "delete_post_tag" action.
	 * @see Featured_Content::validate_settings().
	 */
	public static function delete_post_tag( $tag_id ) {
		$settings = self::get_setting();

		if ( empty( $settings['tag-id'] ) )
			return;

		if ( $tag_id != $settings['tag-id'] )
			return;

		$settings['tag-id'] = 0;
		$settings = self::validate_settings( $settings );
		update_option( 'featured-content', $settings );
	}

	/**
	 * Hide featured tag from displaying when global terms are queried from the front-end.
	 *
	 * Hooks into the "get_terms" filter.
	 *
	 * @param array $terms A list of term objects. This is the return value of get_terms().
	 * @param array $taxonomies An array of taxonomy slugs.
	 *
	 * @uses Featured_Content::get_setting()
	 */
	public static function hide_featured_term( $terms, $taxonomies ) {

		// This filter is only appropriate on the front-end.
		if ( is_admin() )
			return $terms;

		// We only want to hide the featured tag.
		if ( ! in_array( 'post_tag', $taxonomies ) )
			return $terms;

		// Bail if no terms were returned.
		if ( empty( $terms ) )
			return $terms;

		foreach( $terms as $order => $term ) {
			if ( self::get_setting( 'tag-id' ) == $term->term_id && 'post_tag' == $term->taxonomy )
				unset( $terms[$order] );
		}

		return $terms;
	}

	/**
	 * Hide featured tag from displaying when terms associated with
	 * a post object are queried from the front-end.
	 *
	 * Hooks into the "get_the_terms" filter.
	 *
	 * @param array $terms A list of term objects. This is the return value of get_the_terms().
	 * @param int $id The ID field for the post object that terms are associated with.
	 * @param array $taxonomy An array of taxonomy slugs.
	 *
	 * @uses Featured_Content::get_setting()
	 */
	public static function hide_the_featured_term( $terms, $id, $taxonomy ) {

		// This filter is only appropriate on the front-end.
		if ( is_admin() )
			return $terms;

		// Make sure we are in the correct taxonomy.
		if ( ! 'post_tag' == $taxonomy )
			return $terms;

		// No terms? Return early!
		if ( empty( $terms ) )
			return $terms;

		foreach( $terms as $order => $term ) {
			if ( self::get_setting( 'tag-id' ) == $term->term_id )
				unset( $terms[$term->term_id] );
		}

		return $terms;
	}

	/**
	 * Register custom setting on the Settings -> Reading screen.
	 *
	 * @uses Featured_Content::render_form()
	 * @uses Featured_Content::validate_settings()
	 */
	public static function register_setting() {
		add_settings_field( 'featured-content', __( 'Featured content', 'jetpack' ), array( __class__, 'render_form' ), 'reading' );
		register_setting( 'reading', 'featured-content', array( __class__, 'validate_settings' ) );
	}

	/**
	 * Renders all form fields on the Settings -> Reading screen.
	 */
	public static function render_form() {
		$settings = self::get_setting();

		$tag_name = '';
		if ( ! empty( $settings['tag-id'] ) ) {
			$tag = get_term( $settings['tag-id'], 'post_tag' );
			if ( ! is_wp_error( $tag ) && isset( $tag->name ) )
				$tag_name = $tag->name;
		}
		?>

				<?php echo _e( 'Tag name:', 'jetpack' ); ?>
				<input type="text" id="featured-content-tag-name" name="featured-content[tag-name]" value="<?php echo esc_attr( $tag_name ); ?>">
				<input type="hidden" id="featured-content-tag-id" name="featured-content[tag-id]" value="<?php echo esc_attr( $settings['tag-id'] ); ?>">

				<?php _e( 'Number of posts:', 'jetpack' ); ?>
				<input class="small-text" type="number" step="1" min="1" max="<?php echo esc_attr( self::$max_posts ); ?>" id="featured-content-quantity" name="featured-content[quantity]" value="<?php echo esc_attr( $settings['quantity'] ); ?>">

				<input type="checkbox" id="featured-content-hide-tag" name="featured-content[hide-tag]" <?php checked( $settings['hide-tag'], 1 ); ?>">
				<?php _e( 'Hide tag from displaying in post meta and tag clouds.', 'jetpack' ); ?>

		<?php
	}

	/**
	 * Get Settings.
	 *
	 * Get all settings recognized by this module. This
	 * function will return all settings whether or not
	 * they have been stored in the database yet. This
	 * ensures that all keys are available at all times.
	 *
	 * In the event that you only require one setting, you
	 * may pass its name as the first parameter to the function
	 * and only that value will be returned.
	 *
	 * @uses Featured_Content::self::sanitize_quantity()
	 *
	 * @param string $key The key of a recognized setting.
	 * @return mixed Array of all settings by default. A single value if passed as first parameter.
	 */
	public static function get_setting( $key = 'all' ) {
		$saved = (array) get_option( 'featured-content' );

		$defaults = array(
			'hide-tag' => 1,
			'quantity' => 5,
			'tag-id'   => 0,
		);

		$options = wp_parse_args( $saved, $defaults );
		$options = array_intersect_key( $options, $defaults );
		$options['quantity'] = self::sanitize_quantity( $options['quantity'] );

		if ( 'all' != $key ) {
			if ( isset( $options[$key] ) )
				return $options[$key];
			else
				return false;
		}

		return $options;
	}

	/**
	 * Validate Settings.
	 *
	 * Make sure that all user supplied content is in an
	 * expected format before saving to the database. This
	 * function will also delete the transient set in
	 * Featured_Content::get_featured_content().
	 *
	 * @uses Featured_Content::self::sanitize_quantity()
	 * @uses Featured_Content::self::delete_transient()
	 */
	function validate_settings( $input ) {
		$output = array();

		if ( isset( $input['tag-id'] ) )
			$output['tag-id'] = absint( $input['tag-id'] );

		if ( isset( $input['tag-name'] ) && ! empty( $input['tag-name'] ) ) {
			$new_tag = wp_create_tag( $input['tag-name'] );
			if ( ! is_wp_error( $new_tag ) && isset( $new_tag['term_id'] ) )
				$tag = get_term( $new_tag['term_id'], 'post_tag' );
			if ( isset( $tag->term_id ) )
				$output['tag-id'] = $tag->term_id;
		} else {
			unset( $output['tag-id'] );
		}

		if ( isset( $input['quantity'] ) )
			$output['quantity'] = self::sanitize_quantity( $input['quantity'] );

		$output['hide-tag'] = ( isset( $input['hide-tag'] ) ) ? 1 : 0;

		self::delete_transient();

		return $output;
	}

	/**
	 * Sanitize Quantity
	 *
	 * @param int $input The value to sanitize.
	 * @output int A number between 1 and FeaturedContent::$max_posts.
	 *
	 * @uses Featured_Content::$max_posts
	 */
	public static function sanitize_quantity( $input ) {
		$quantity = absint( $input );

		if ( $quantity > self::$max_posts )
			$quantity = self::$max_posts;
		else if ( 1 > $quantity )
			$quantity = 1;

		return $quantity;
	}
}

Featured_Content::setup();


text:
<?php

namespace MyCompany\Factory;

use MyCompany\Service\UserService;
use Zend\Mail\Transport\Smtp;
use Zend\Mail\Transport\SmtpOptions;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\View\Renderer\PhpRenderer;
use Zend\View\Resolver\TemplateMapResolver;

class UserServiceFactory implements FactoryInterface
{

    /**
     * Create service
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return mixed
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        if($serviceLocator instanceof ServiceLocatorAwareInterface){
            $serviceLocator = $serviceLocator->getServiceLocator();
        }

        $mailTransport = new Smtp();
        $smtpOtions = new SmtpOptions(array(
            'name'              => 'smtp.yandex.ru',
            'host'              => 'smtp.yandex.ru',
            'port'              => 465, // Notice port change for TLS is 587
            'connection_class'  => 'plain',
            'connection_config' => array(
                'username' => 'ruslan@prophp.eu',
                'password' => 'mn867535144',
                'ssl'      => 'ssl',
            ),
        ));
        $mailTransport->setOptions($smtpOtions);

        $mailRenderer = new PhpRenderer();
        $resolver = new TemplateMapResolver();
        $resolver->setMap($serviceLocator->get('Config')['view_manager']['template_map']);
        $mailRenderer->setResolver($resolver);

        $em = $serviceLocator->get('doctrine.entitymanager.orm_default');
        $service = new UserService($em,$mailRenderer,$mailTransport);

        return $service;
    }
}


text:
<#
.Synopsis
 Compare the list of root certification authorities (CAs) trusted by a user
 on a computer against a reference list of CAs.  The reference list is just a
 simple text file of the SHA1 hash thumbprints of root CA certificates.

.Description
 Compare the list of root certification authorities (CAs) trusted by a user
 on a computer against a reference list CAs.  The reference list is just a
 simple text file of the SHA1 hash thumbprints of the CA certificates.  The
 output is a CSV text file of the currently-trusted certificates which are
 NOT in the reference list.  Script also writes an event to the Application
 event log (Event ID = 9017, Source = RootCertificateAudit) on the computer
 where the script is run.  The script is quite simple, actually, and is
 mainly intended as a starter script or skeleton script to be modified for
 the needs of the organization; feel free to add more error handling, etc.

.Parameter FilePath
 The local or UNC path to the text file containing the list of certificate
 SHA1 hash thumbprints against which to compare as a reference.

.Parameter OutputPath
 The local or UNC path to the folder for the output CSV file which will contain
 a list of the currently-trusted root CAs which are NOT on the reference
 list of hashes, hence, possibly bad or in violation of policy.

 .Notes
 Refactoring Author: Bryan Lockwood, http://itcookbook.net
 Original Author: Jason Fossen, Enclave Consulting (http://www.sans.org/windows-security/)
 Version: 2.0
 Updated: 20150224

 Original script and some explaining text are available at http://goo.gl/E3B4tv

 LEGAL: PUBLIC DOMAIN.  SCRIPT PROVIDED "AS IS" WITH NO WARRANTIES OR GUARANTEES OF
  ANY KIND, INCLUDING BUT NOT LIMITED TO MERCHANTABILITY AND/OR FITNESS FOR
  A PARTICULAR PURPOSE.  ALL RISKS OF DAMAGE REMAINS WITH THE USER, EVEN IF
  THE AUTHOR, SUPPLIER OR DISTRIBUTOR HAS BEEN ADVISED OF THE POSSIBILITY OF
  ANY SUCH DAMAGE.  IF YOUR STATE DOES NOT PERMIT THE COMPLETE LIMITATION OF
  LIABILITY, THEN DELETE THIS FILE SINCE YOU ARE NOT PROHIBITED TO HAVE IT.

#>
function Audit-Roots
{
    [CmdletBinding()]
    #[OutputType([int])]
    Param
    (
        [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,Position=0)]
        $FilePath,

        [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,Position=1)]
        $OutputPath
    )

    Process
    {
        # Extract hashes of "Trusted Root Certification Authorities" for the current user.
        $usertrusted  = dir cert:\currentuser\root | foreach { $_ | select-object Thumbprint,Subject}
        # Extract hashes of "Third-Party Trusted Root Certification Authorities" for the current user.
        $usertrusted += dir cert:\currentuser\authroot | foreach { $_ | select-object Thumbprint,Subject}
        # Extract hashes of "Trusted Root Certification Authorities" for the computer.
        $computertrusted = dir cert:\localmachine\root | foreach { $_ | select-object Thumbprint,Subject}
        # Extract hashes of "Third-Party Trusted Root Certification Authorities" for the computer.
        $computertrusted += dir cert:\localmachine\authroot | foreach { $_ | select-object Thumbprint,Subject}

        # Combine all the user and computer CA hashes and exclude the duplicates.
        $combined = ($usertrusted + $computertrusted) | sort Thumbprint -unique
        # Read in the hashes from the reference list of thumbprints.
        $reference = get-content -path $FilePath
        # Get list of locally-trusted hashes which are NOT in the reference file.
        $additions = $combined | foreach { if ($reference -notcontains $_.Thumbprint) { $_ } }

        # Save the list to a CSV file to the output path
        [string]$savepath = "$OutputPath" + "\" + $env:computername
        $savepath = $savepath + "+" + $env:username + "+" + $(get-date -format yyyyMMdd-HHmm) + ".csv"
        $additions | export-csv -notypeinfo -literalpath $savepath

        # Write the list to the local Application event log for archival:
        New-EventLog -LogName Application -Source RootCertificateAudit -ErrorAction SilentlyContinue

        $GoodMessage = "All of the root CA certificates trusted by $env:userdomain\$env:username "
        $GoodMessage = $GoodMessage + "are on the reference list of certificate hashes obtained from "
        $GoodMessage = $GoodMessage + $FilePath

        $BadMessage = "The following root CA certificates are trusted by $env:userdomain\$env:username, "
        $BadMessage = $BadMessage + "`n" + "but they NOT on the supplied hash list ($FilePath): "
        $BadMessage = $BadMessage + "`n" + $($additions | format-list | out-string)

        if ($additions.count -eq 0) {
            Write-EventLog -logname Application -source RootCertificateAudit -eventID 9017 -message $GoodMessage -EntryType Information
            Write-Host $GoodMessage
        } else {
            Write-EventLog -logname Application -source RootCertificateAudit -eventID 9017 -message $BadMessage -EntryType Warning
            Write-Warning $BadMessage
        }

    }
}

Audit-Roots -FilePath .\Sept2014-WindowsRootCAList.txt -OutputPath .\


text:
package com.intellij.psi.formatter;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertSame;

/**
 * @author Denis Zhdanov
 * @since 09/21/2010
 */
public class StaticTextWhiteSpaceDefinitionStrategyTest {

  private StaticTextWhiteSpaceDefinitionStrategy myStrategy;

  @Before
  public void setUp() {
    myStrategy = new StaticTextWhiteSpaceDefinitionStrategy("abc");
  }

  @Test
  public void notAtFirstPosition() {
    assertSame(0, myStrategy.check(" abc", 0, 4));
    assertSame(1, myStrategy.check("  abc", 1, 3));
  }

  @Test
  public void match() {
    assertSame(3, myStrategy.check("abc", 0, 3));
    assertSame(4, myStrategy.check(" abcde", 1, 5));
  }

  @Test
  public void withoutEnd() {
    assertSame(0, myStrategy.check("abc", 0, 2));
    assertSame(1, myStrategy.check(" abc", 1, 3));
  }
}


text:
#import "HFAppDelegate.h"

#import "HFViewController.h"
#import <FacebookSDK/FacebookSDK.h>

@implementation HFAppDelegate

@synthesize window = _window;
@synthesize rootViewController = _rootViewController;

// FBSample logic
// If we have a valid session at the time of openURL call, we handle Facebook transitions
// by passing the url argument to handleOpenURL; see the "Just Login" sample application for
// a more detailed discussion of handleOpenURL
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    // attempt to extract a token from the url
    return [FBSession.activeSession handleOpenURL:url];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // FBSample logic
    // if the app is going away, we close the session object
    [FBSession.activeSession close];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // If you have not added the -ObjC linker flag, you may need to uncomment the following line because
    // Nib files require the type to have been loaded before they can do the wireup successfully.
    // http://stackoverflow.com/questions/1725881/unknown-class-myclass-in-interface-builder-file-error-at-runtime
    // [FBProfilePictureView class];

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        self.window.rootViewController = [[HFViewController alloc] initWithNibName:@"HFViewController_iPhone" bundle:nil];
    } else {
        self.window.rootViewController = [[HFViewController alloc] initWithNibName:@"HFViewController_iPad" bundle:nil];
    }

    [self.window makeKeyAndVisible];

    return YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application	{
    // FBSample logic
    // We need to properly handle activation of the application with regards to SSO
    //  (e.g., returning from iOS 6.0 authorization dialog or from fast app switching).
    [FBSession.activeSession handleDidBecomeActive];
}

@end


text:
using Management.Storage.ScenarioTest.Common;
using Management.Storage.ScenarioTest.Util;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MS.Test.Common.MsTestLib;

namespace Management.Storage.ScenarioTest.BVT.HTTP
{
    /// <summary>
    /// bvt cases for anonymous storage account
    /// </summary>
    [TestClass]
    class AnonymousBVT : Management.Storage.ScenarioTest.BVT.HTTPS.AnonymousBVT
    {
        [ClassInitialize()]
        public static void AnonymousHTTPBVTClassInitialize(TestContext testContext)
        {
            TestBase.TestClassInitialize(testContext);
            string StorageAccountName = Test.Data.Get("StorageAccountName");
            useHttps = false;
            PowerShellAgent.SetAnonymousStorageContext(StorageAccountName, useHttps);
            downloadDirRoot = Test.Data.Get("DownloadDir");
            SetupDownloadDir();
        }

        [ClassCleanup()]
        public static void AnonymousHTTPBVTClassCleanup()
        {
            FileUtil.CleanDirectory(downloadDirRoot);
            TestBase.TestClassCleanup();
        }
    }
}


text:
using System.Diagnostics;
using NUnit.Framework;
using Shouldly;
using StructureMap.Testing.Widget3;

namespace StructureMap.Testing.Graph
{
    [TestFixture]
    public class ConventionBasedSetterInjectionTester
    {
        public class ClassWithNamedProperties
        {
            public int Age { get; set; }
            public string LastName { get; set; }
            public string FirstName { get; set; }
            public IGateway Gateway { get; set; }
            public IService Service { get; set; }
        }

        [Test]
        public void specify_setter_policy_and_construct_an_object()
        {
            var theService = new ColorService("red");

            var container = new Container(x =>
            {
                x.For<IService>().Use(theService);
                x.For<IGateway>().Use<DefaultGateway>();

                x.ForConcreteType<ClassWithNamedProperties>().Configure.Setter<int>().Is(5);

                x.Policies.SetAllProperties(
                    policy => { policy.WithAnyTypeFromNamespace("StructureMap.Testing.Widget3"); });
            });

            var description = container.Model.For<ClassWithNamedProperties>().Default.DescribeBuildPlan();
            Debug.WriteLine(description);

            var target = container.GetInstance<ClassWithNamedProperties>();
            target.Service.ShouldBeTheSameAs(theService);
            target.Gateway.ShouldBeOfType<DefaultGateway>();
        }

        [Test]
        public void specify_setter_policy_by_of_type_and_construct_an_object()
        {
            var theService = new ColorService("red");

            var container = new Container(x =>
            {
                x.For<IService>().Use(theService);
                x.For<IGateway>().Use<DefaultGateway>();

                x.ForConcreteType<ClassWithNamedProperties>().Configure.Setter<int>().Is(5);

                x.Policies.SetAllProperties(policy => policy.OfType<IService>());
            });

            var description = container.Model.For<ClassWithNamedProperties>().Default.DescribeBuildPlan();
            Debug.WriteLine(description);

            var target = container.GetInstance<ClassWithNamedProperties>();
            target.Service.ShouldBeTheSameAs(theService);
            target.Gateway.ShouldBeNull();
        }

        [Test]
        public void specify_setter_policy_by_a_predicate_on_property_type()
        {
            var theService = new ColorService("red");

            var container = new Container(x =>
            {
                x.For<IService>().Use(theService);
                x.For<IGateway>().Use<DefaultGateway>();

                x.Policies.SetAllProperties(policy => { policy.TypeMatches(type => type == typeof (IService)); });
            });

            var target = container.GetInstance<ClassWithNamedProperties>();
            target.Service.ShouldBeTheSameAs(theService);
            target.Gateway.ShouldBeNull();
        }
    }
}


text:
from fabric.api import *
from fabric.contrib.files import exists
import fabric

counter = 0

@roles('master')
def start_spark():
    run('/home/mdindex/scripts/startSystems.sh')

@roles('master')
def stop_spark():
    run('/home/mdindex/scripts/stopSystems.sh')

@roles('master')
def start_zookeeper():
    run('/home/mdindex/scripts/startZookeeper.sh')

@roles('master')
def stop_zookeeper():
    run('/home/mdindex/scripts/stopZookeeper.sh')

def run_bg(cmd, before=None, sockname="dtach", use_sudo=False):
    """Run a command in the background using dtach

    :param cmd: The command to run
    :param output_file: The file to send all of the output to.
    :param before: The command to run before the dtach. E.g. exporting
                   environment variable
    :param sockname: The socket name to use for the temp file
    :param use_sudo: Whether or not to use sudo
    """
    if not exists("/usr/bin/dtach"):
        print "Install dtach first !"
        return
    if before:
        cmd = "{}; dtach -n `mktemp -u /tmp/{}.XXXX` {}".format(
            before, sockname, cmd)
    else:
        cmd = "dtach -n `mktemp -u /tmp/{}.XXXX` {}".format(sockname, cmd)
    if use_sudo:
        return sudo(cmd)
    else:
        return run(cmd)

@runs_once
def build_jar():
    local('cd /Users/anil/Dev/repos/mdindex/; gradle shadowJar')

@parallel
def update_jar():
    if not exists('/data/mdindex/jars'):
        run('mkdir -p /data/mdindex/jars')
    put('../build/libs/amoeba-all.jar', '/data/mdindex/jars/')

@roles('master')
def update_master_jar():
    if not exists('/data/mdindex/jars'):
        run('mkdir -p /data/mdindex/jars')
    put('../build/libs/amoeba-all.jar', '/data/mdindex/jars/')

@serial
def update_config():
    global counter
    put('server/server.properties', '/home/mdindex/amoeba.properties')
    run('echo "MACHINE_ID = %d" >> /home/mdindex/amoeba.properties' % counter)
    counter += 1

@parallel
def clean_cluster():
  run('rm -R /data/mdindex/logs/hadoop/')
  run('rm -R /home/mdindex/spark-1.6.0-bin-hadoop2.6/logs/')
  run('rm -R /home/mdindex/spark-1.6.0-bin-hadoop2.6/work/')

@parallel
def parallel_shell():
  run('mv /data/mdindex/tpchd100/download_data.sh ~/')


text:
<?php

/**
 * Require a filesystem config file, where all filesystem configurations should reside.
 */
require __DIR__ . '/bootstrap/filesystem.php';

?>


text:
package com.google.cloud.bigtable.hbase.mirroring.utils;

import com.google.cloud.bigtable.mirroring.core.utils.DefaultSecondaryWriteErrorConsumer;
import com.google.cloud.bigtable.mirroring.core.utils.SecondaryWriteErrorConsumer;
import com.google.cloud.bigtable.mirroring.core.utils.faillog.FailedMutationLogger;
import com.google.cloud.bigtable.mirroring.core.utils.mirroringmetrics.MirroringSpanConstants.HBaseOperation;
import com.google.common.base.Preconditions;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.hadoop.hbase.client.Mutation;
import org.apache.hadoop.hbase.client.Row;
import org.apache.hadoop.hbase.client.RowMutations;

public class TestWriteErrorConsumer implements SecondaryWriteErrorConsumer {
  static AtomicInteger errorCount = new AtomicInteger(0);
  private final DefaultSecondaryWriteErrorConsumer secondaryWriteErrorConsumer;

  public TestWriteErrorConsumer(FailedMutationLogger failedMutationLogger) {
    this.secondaryWriteErrorConsumer = new DefaultSecondaryWriteErrorConsumer(failedMutationLogger);
  }

  public static int getErrorCount() {
    return errorCount.get();
  }

  public static void clearErrors() {
    errorCount.set(0);
  }

  @Override
  public void consume(HBaseOperation operation, Row row, Throwable cause) {
    Preconditions.checkArgument(row instanceof Mutation || row instanceof RowMutations);
    errorCount.addAndGet(1);
    this.secondaryWriteErrorConsumer.consume(operation, row, cause);
  }

  @Override
  public void consume(HBaseOperation operation, List<? extends Row> operations, Throwable cause) {
    for (Row row : operations) {
      Preconditions.checkArgument(row instanceof Mutation || row instanceof RowMutations);
    }
    errorCount.addAndGet(operations.size());
    this.secondaryWriteErrorConsumer.consume(operation, operations, cause);
  }

  public static class Factory implements SecondaryWriteErrorConsumer.Factory {
    @Override
    public SecondaryWriteErrorConsumer create(FailedMutationLogger failedMutationLogger) {
      return new TestWriteErrorConsumer(failedMutationLogger);
    }
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.5"/>
<title>ARPhysics: Spring Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

ARPhysics
    1.0

A 2D physics engine written in C++

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

 All Classes Functions Variables Enumerations

Public Member Functions |
Static Public Attributes |
List of all members

Spring Class Reference

#include <Spring.h>

Inheritance diagram for Spring:

  <map id="Spring_map" name="Spring_map">
<area href="class_constraint.html" alt="Constraint" shape="rect" coords="0,56,69,80"/>
<area href="class_object.html" alt="Object" shape="rect" coords="0,0,69,24"/>
</map>

Public Member Functions

 	Spring (Body *a, Body *b, float stiffness, float restLength, float failLength=SpringDoNotFail)

 	~Spring ()

void 	solve (float dt)

void 	setCallBack (std::function< void(Spring *)> failCallBack)

 Public Member Functions inherited from Constraint

 	Constraint (Body *a, Body *b)

 	~Constraint ()

Body * 	getA ()

Body * 	getB ()

 Public Member Functions inherited from Object

 	Object ()

virtual 	~Object ()

void 	retain ()

void 	release ()

int 	getRetainCount ()

Static Public Attributes

static const float 	SpringDoNotFail = INFINITY

Additional Inherited Members

 Protected Attributes inherited from Constraint

Body * 	a

Body * 	b

Detailed Description

A constraint that acts like a spring allowing a body to be attached to a static point or another body.

Constructor & Destructor Documentation

          Spring::Spring
          (
          Body *
          a,

          Body *
          b,

          float
          stiffness,

          float
          restLength,

          float
          failLength = SpringDoNotFail

          )

Constructs a new spring that attaches two bodies.

Parameters

a	The first body.

b	The second body.

stiffness	The stiffness of the spring.

restLength	The length at which the spring is at rest.

failLength	The length at which the spring should fail and call the fail callback.  The spring can not remove itself when it fails; the specfied failCallBack must remove it.

          Spring::~Spring
          (
          	)

Spring destructor.

Member Function Documentation

          void Spring::setCallBack
          (
          std::function< void(Spring *)>
          failCallBack	)

Set the function to be called in the event that the spring extends past the fail length.

Parameters

failCallBack	The function to call if/when the spring extends past the fail length.

          void Spring::solve
          (
          float
          dt	)

virtual

Solve the constraint.

Parameters

dt	The delta time to solve the constaint for.

Implements Constraint.

Member Data Documentation

          const float Spring::SpringDoNotFail = INFINITY

static

The value to give as fail length if you do not want to spring to ever fail.

The documentation for this class was generated from the following files:

/Engine/Spring.h

/Engine/Spring.cpp

<address class="footer">
Generated on Sun Apr 20 2014 20:47:07 for ARPhysics by

 1.8.5
</address>


text:
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.template import RequestContext
from django.contrib.auth.decorators import login_required

from chat.models import AppModel
from cortex import SessionPool, Channel, WebsocketHandler
Sessions = SessionPool();

# Establish a correspondance between the `.type` attribute
# attached to Backbone models and their counterpart in the
# Django ORM.
CapsuleModels = {
    'AppModel': AppModel
}

# The initial `app` model created upon a `session` event call.
app = {
    'type': 'AppModel',
    'attributes': {
        'toggler': False,
    },
    'id': 1
}

class Chatroom(Channel):

    name = 'chatroom'
    users = set([])

    def userlist(self):
        userlst = ''
        for user in self.users:
            userlst += user.username + '\n'
        return userlst

    def subscribe(self, user, socket):
        # Add a socket subscription to this channel
        self.add_subscriber(socket)

        # Add a user to users set
        self.users.add(user)

        # Push the new userlist to all clients
        self.call(app,'userlist',self.userlist())

        # Send a message that a new user is connected
        self.send('Server: User %s connected.' % user.username)

    def unsubscribe(self, user, socket):
        # Remove socket subscription
        self.del_subscriber(socket)

        # Remove the user
        self.users.discard(user.username)

        # Push the new userlist to all clients
        self.call(app,'userlist',self.userlist())

        # Send a message that the user disconnected
        self.send('Server: User %s disconnected.' % user.username)

    def message(self, msg, user, socket):
        # Publish a chat message on this channel
        self.send("%s: %s" % (user.username,msg))

# ----------
# HTTP Views
# ----------

@login_required
def home(request, room_name=None, template_name='home.html'):
    context = {'session_key':request.session.session_key}

    return render_to_response(template_name, context,
            context_instance=RequestContext(request))

# List of active users
def users(request):

    users = ''
    for user in Sessions.iter_users():
        user_type, user_obj = user
        users += "(%s,%s)" % (user_type, user_obj.username)

    return HttpResponse(users,mimetype='text')

# ---------------
# Socket Handlers
# ---------------

Room = Chatroom(Sessions)

Websocket = WebsocketHandler(pool=Sessions,
                             models=CapsuleModels)
Websocket.app_fixture = app

Websocket.on_connect    = Room.subscribe
Websocket.on_disconnect = Room.unsubscribe
Websocket.on_message    = Room.message

# Hook that is passed to urls.py to handle socketio events
socketio = Websocket.make_handle()


text:
import cv2, time
import urllib2, base64
import numpy as np

class ipCamera(object):

    def __init__(self,url, user = None, password = None):
        self.url = url
        auth_encoded = base64.encodestring('%s:%s' % (user, password))[:-1]

        self.req = urllib2.Request(self.url)
        self.req.add_header('Authorization', 'Basic %s' % auth_encoded)

    def get_frame(self):
        response = urllib2.urlopen(self.req)
        img_array = np.asarray(bytearray(response.read()), dtype=np.uint8)
        frame = cv2.imdecode(img_array, 1)
        return frame

class Camera(object):

    def __init__(self, camera = 0):
        self.cam = cv2.VideoCapture(camera)
        if not self.cam:
            raise Exception("Camera not accessible")

        self.shape = self.get_frame().shape

    def get_frame(self):
        _,frame = self.cam.read()
        return frame

    def release(self):
        self.cam.release()


text:
namespace System.Security.Cryptography.Rsa.Tests
{
    public class DefaultRSAProvider : IRSAProvider
    {
        public RSA Create()
        {
            return RSA.Create();
        }

        public RSA Create(int keySize)
        {
            RSA rsa = Create();
            rsa.KeySize = keySize;
            return rsa;
        }
    }

    public partial class RSAFactory
    {
        private static readonly IRSAProvider s_provider = new DefaultRSAProvider();
    }
}


text:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using dexih.functions;
using dexih.transforms.Poco;
using Xunit;

namespace dexih.transforms.tests
{
    public class PocoTests
    {
        [Fact]
        public async Task PocoTest_Open()
        {
            await Task.Run(() =>
            {

                var reader = Helpers.CreateSortedTestData();
                var poco = new PocoLoader<SamplePocoClass>();
                poco.Open(reader);

                var count = 0;
                foreach (var item in poco)
                {
                    count++;
                    Assert.Equal("value" + count.ToString().PadLeft(2, '0'), item.StringColumn);
                    Assert.Equal(count, item.IntColumn);
                    Assert.Equal(Convert.ToDateTime("2015-01-" + count), item.TheDate);
                }

                Assert.Equal(10, count);
            });
        }

        [Fact]
        public async Task PocoTest_OpenCached()
        {
            await Task.Run(() =>
            {

                var reader = Helpers.CreateSortedTestData();
                var poco = new PocoLoader<SamplePocoClass>();
                poco.OpenCached(reader);

                var count = 0;
                foreach (var item in poco)
                {
                    count++;
                    Assert.Equal("value" + count.ToString().PadLeft(2, '0'), item.StringColumn);
                    Assert.Equal(count, item.IntColumn);
                    Assert.Equal(Convert.ToDateTime("2015-01-" + count), item.TheDate);
                }

                Assert.Equal(10, count);

                var oldItem = poco[5];
                Assert.Equal("value06", oldItem.StringColumn);

                Assert.Equal(10, poco.Count);
            });
        }

        [Fact]
        public async Task PocoTest_ToListAsync()
        {
            var reader = Helpers.CreateSortedTestData();
            var poco = new PocoLoader<SamplePocoClass>();
            var list = await poco.ToListAsync(reader);

            var count = 0;
            foreach (var item in list)
            {
                count++;
                Assert.Equal("value" + count.ToString().PadLeft(2, '0'), item.StringColumn);
                Assert.Equal(count, item.IntColumn);
                Assert.Equal(Convert.ToDateTime("2015-01-" + count), item.TheDate);
            }

            Assert.Equal(10, count);

        }

        [Fact]
        public async Task PocoTest_Reader()
        {
            var items = new List<SamplePocoClass>
            {
                new SamplePocoClass("column1", 1, new DateTime(2000, 01, 02)),
                new SamplePocoClass("column2", 2, new DateTime(2000, 01, 03)),
                new SamplePocoClass("column3", 3, new DateTime(2000, 01, 04))
            };

            var pocoReader = new PocoReader<SamplePocoClass>(items);
            await pocoReader.Open();

            var count = 0;
            while (await pocoReader.ReadAsync())
            {
                count++;
                Assert.Equal("column" + count, pocoReader["StringColumn"]);
                Assert.Equal(count, pocoReader["IntColumn"]);
                Assert.Equal(new DateTime(2000, 01, 01).AddDays(count), pocoReader["DateColumn"]);
            }

            Assert.Equal(3, count);
        }

        [Fact]
        public async Task PocoTest_Insert()
        {
            var items = new List<SamplePocoClass>
            {
                new SamplePocoClass("column1", 1, new DateTime(2000, 01, 02)),
                new SamplePocoClass("column2", 2, new DateTime(2000, 01, 03)),
                new SamplePocoClass("column3", 3, new DateTime(2000, 01, 04))
            };

            var pocoTable = new PocoTable<SamplePocoClass>();
            var connection = new ConnectionMemory();

            await pocoTable.CreateTable(connection, true, CancellationToken.None);
            await pocoTable.ExecuteInsert(connection, items[0], CancellationToken.None);
            Assert.Equal(1, items[0].Incremental);
            await pocoTable.ExecuteInsert(connection, items[1], CancellationToken.None);
            await pocoTable.ExecuteInsert(connection, items[2], CancellationToken.None);

            var reader = connection.GetTransformReader(pocoTable.Table);

            var count = 0;
            while (await reader.ReadAsync())
            {
                count++;
                Assert.Equal("column" + count, reader["StringColumn"]);
                Assert.Equal(count, reader["IntColumn"]);
                Assert.Equal(new DateTime(2000, 01, 01).AddDays(count), reader["DateColumn"]);
            }

            Assert.Equal(3, count);
        }

        [Fact]
        public async Task PocoTest_InsertBulk()
        {
            var items = new List<SamplePocoClass>
            {
                new SamplePocoClass("column1", 1, new DateTime(2000, 01, 02)),
                new SamplePocoClass("column2", 2, new DateTime(2000, 01, 03)),
                new SamplePocoClass("column3", 3, new DateTime(2000, 01, 04))
            };

            var pocoTable = new PocoTable<SamplePocoClass>();
            var connection = new ConnectionMemory();

            await pocoTable.CreateTable(connection, true, CancellationToken.None);
            await pocoTable.ExecuteInsertBulk(connection, items, CancellationToken.None);

            var reader = connection.GetTransformReader(pocoTable.Table);
            await reader.Open();

            var count = 0;
            while (await reader.ReadAsync())
            {
                count++;
                Assert.Equal("column" + count, reader["StringColumn"]);
                Assert.Equal(count, reader["IntColumn"]);
                Assert.Equal(new DateTime(2000, 01, 01).AddDays(count), reader["DateColumn"]);
            }

            Assert.Equal(3, count);
        }

        [Fact]
        public async Task PocoTest_Update()
        {
            var item = new SamplePocoClass("column1", 1, new DateTime(2000, 01, 02));
            var updateItem = new SamplePocoClass("column1", 2, new DateTime(2000, 01, 03));

            var pocoTable = new PocoTable<SamplePocoClass>();
            var connection = new ConnectionMemory();

            // creat table, insert sample column, and then update.
            await pocoTable.CreateTable(connection, true, CancellationToken.None);
            await pocoTable.ExecuteInsert(connection, item, CancellationToken.None);
            await pocoTable.ExecuteUpdate(connection, updateItem, CancellationToken.None);

            var reader = connection.GetTransformReader(pocoTable.Table);

            await reader.ReadAsync();
            Assert.Equal("column1", reader["StringColumn"]);
            Assert.Equal(2, reader["IntColumn"]);
            Assert.Equal(new DateTime(2000, 01, 03), reader["DateColumn"]);
        }

        [Fact]
        public async Task PocoTest_Delete()
        {
            var item = new SamplePocoClass("column1", 1, new DateTime(2000, 01, 02));

            var pocoTable = new PocoTable<SamplePocoClass>();
            var connection = new ConnectionMemory();

            // creat table, insert sample column, and then delete.
            await pocoTable.CreateTable(connection, true, CancellationToken.None);
            await pocoTable.ExecuteInsert(connection, item, CancellationToken.None);
            await pocoTable.ExecuteDelete(connection, item, CancellationToken.None);

            var reader = connection.GetTransformReader(pocoTable.Table);

            var moreRecords = await reader.ReadAsync();
            Assert.False(moreRecords);
        }

        [Fact]
        public async Task PocoTest_Processor()
        {

            var item = new SamplePocoClass("column1", 1, new DateTime(2000, 01, 02));

            var connection = new ConnectionMemory();
            var pocoTable = new PocoTable<SamplePocoClass>();
            await pocoTable.CreateTable(connection, true, CancellationToken.None);

            var pocoProcessor = new PocoProcessor<SamplePocoClass>();

            for (var i = 0; i < 1000; i++)
            {
                pocoProcessor.EnqueueMessage(EPocoOperation.Insert, connection, item);
            }

            pocoProcessor.Dispose();

            var reader = connection.GetTransformReader(pocoTable.Table);

            var count = 0;
            while (await reader.ReadAsync())
            {
                count++;
            }

            Assert.Equal(1000, count);
        }

    }

    public class SamplePocoClass
    {
        public SamplePocoClass()
        {
        }

        public SamplePocoClass(string stringColumn, int intColumn, DateTime theDate)
        {
            StringColumn = stringColumn;
            IntColumn = intColumn;
            TheDate = theDate;
        }

        [PocoColumn(DeltaType = EDeltaType.DbAutoIncrement)]
        public long Incremental { get; set; }

        [PocoColumn(DeltaType = EDeltaType.NaturalKey)]
        public string StringColumn { get; set; }

        public int IntColumn { get; set; }

        // this uses the field attribute which will read the incoming field "DateColumn" rather then "TheDate"
        [PocoColumn("DateColumn")]
        public DateTime TheDate { get; set; }
    }
}


text:
var Schema = require("mongoose").Schema;
console.log("exporting buildstatus schema");

module.exports = new Schema({
	name:		{ type: String, unique: true, index: true },
	status:		Schema.Types.Mixed,
	created_at: { type: Date, default: Date.now },
	updated_at: { type: Date, default: Date.now }
});


text:
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/views/desktop_capture/desktop_media_tab_list.h"

#include "base/memory/raw_ptr.h"
#include "base/numerics/safe_conversions.h"
#include "chrome/browser/media/webrtc/desktop_media_list_layout_config.h"
#include "chrome/browser/ui/color/chrome_color_id.h"
#include "chrome/grit/generated_resources.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/color/color_provider.h"
#include "ui/gfx/favicon_size.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/background.h"
#include "ui/views/border.h"
#include "ui/views/controls/scroll_view.h"
#include "ui/views/controls/table/table_view.h"
#include "ui/views/controls/table/table_view_observer.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/view.h"

using content::BrowserThread;

namespace {

// Max stored length for the title of a previewed tab. The actual displayed
// length is likely shorter than this, as the Label will elide it to fit the UI.
constexpr const int kMaxPreviewTitleLength = 500;

// TODO(crbug.com/1224342): Refer to central Desktop UI constants rather than
// hardcoding this.
const int kListWidth = 346;

// Delay after the selection is changed before clearing the preview, to allow a
// direct switch from the old preview to the new one without flashing grey in
// between.
const base::TimeDelta kClearPreviewDelay = base::Milliseconds(200);

// ui::TableModel that wraps a DesktopMediaListController and listens for
// updates from it.
class TabListModel : public ui::TableModel,
                     public DesktopMediaListController::SourceListListener {
 public:
  explicit TabListModel(
      DesktopMediaListController* controller,
      base::RepeatingCallback<void(size_t)> preview_updated_callback);

  // ui::TableModel:
  size_t RowCount() override;
  std::u16string GetText(size_t row, int column) override;
  ui::ImageModel GetIcon(size_t row) override;
  void SetObserver(ui::TableModelObserver* observer) override;

  // DesktopMediaListController::SourceListListener:
  void OnSourceAdded(size_t index) override;
  void OnSourceRemoved(size_t index) override;
  void OnSourceMoved(size_t old_index, size_t new_index) override;
  void OnSourceNameChanged(size_t index) override;
  void OnSourceThumbnailChanged(size_t index) override;
  void OnSourcePreviewChanged(size_t index) override;
  void OnDelegatedSourceListSelection() override;

 private:
  TabListModel(const TabListModel&) = delete;
  TabListModel operator=(const TabListModel&) = delete;

  raw_ptr<DesktopMediaListController> controller_;
  raw_ptr<ui::TableModelObserver> observer_ = nullptr;
  base::RepeatingCallback<void(size_t)> preview_updated_callback_;
};

TabListModel::TabListModel(
    DesktopMediaListController* controller,
    base::RepeatingCallback<void(size_t)> preview_updated_callback)
    : controller_(controller),
      preview_updated_callback_(preview_updated_callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
}

size_t TabListModel::RowCount() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  return controller_->GetSourceCount();
}

std::u16string TabListModel::GetText(size_t row, int column) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  return controller_->GetSource(row).name;
}

ui::ImageModel TabListModel::GetIcon(size_t row) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  return ui::ImageModel::FromImageSkia(controller_->GetSource(row).thumbnail);
}

void TabListModel::SetObserver(ui::TableModelObserver* observer) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  observer_ = observer;
}

void TabListModel::OnSourceAdded(size_t index) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  observer_->OnItemsAdded(index, 1);
}

void TabListModel::OnSourceRemoved(size_t index) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  observer_->OnItemsRemoved(index, 1);
}

void TabListModel::OnSourceMoved(size_t old_index, size_t new_index) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  observer_->OnItemsMoved(old_index, 1, new_index);
}

void TabListModel::OnSourceNameChanged(size_t index) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  observer_->OnItemsChanged(index, 1);
  // Also invoke the preview updated callback, to ensure the preview's use of
  // the source's name is updated.
  preview_updated_callback_.Run(index);
}

void TabListModel::OnSourceThumbnailChanged(size_t index) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  observer_->OnItemsChanged(index, 1);
}

void TabListModel::OnSourcePreviewChanged(size_t index) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  preview_updated_callback_.Run(index);
}

void TabListModel::OnDelegatedSourceListSelection() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  NOTREACHED()
      << "Tab Lists are not delegated, so should not get a selection event.";
}

// TableViewObserver implementation that bridges between the actual TableView
// listing tabs and the DesktopMediaTabList.
class TabListViewObserver : public views::TableViewObserver {
 public:
  TabListViewObserver(DesktopMediaListController* controller,
                      base::RepeatingClosure selection_changed_callback);

  void OnSelectionChanged() override;
  void OnKeyDown(ui::KeyboardCode virtual_keycode) override;

 private:
  TabListViewObserver(const TabListViewObserver&) = delete;
  TabListViewObserver operator=(const TabListViewObserver&) = delete;

  const raw_ptr<DesktopMediaListController> controller_;
  base::RepeatingClosure selection_changed_callback_;
};

TabListViewObserver::TabListViewObserver(
    DesktopMediaListController* controller,
    base::RepeatingClosure selection_changed_callback)
    : controller_(controller),
      selection_changed_callback_(std::move(selection_changed_callback)) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
}

void TabListViewObserver::OnSelectionChanged() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  controller_->OnSourceSelectionChanged();
  selection_changed_callback_.Run();
}

void TabListViewObserver::OnKeyDown(ui::KeyboardCode virtual_keycode) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  if (virtual_keycode == ui::VKEY_RETURN)
    controller_->AcceptSource();
}

}  // namespace

DesktopMediaTabList::DesktopMediaTabList(DesktopMediaListController* controller,
                                         const std::u16string& accessible_name)
    : controller_(controller) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  // The thumbnail size isn't allowed to be smaller than gfx::kFaviconSize by
  // the underlying media list. TableView requires that the icon size be exactly
  // ui::TableModel::kIconSize; if it's not, rendering of the TableView breaks.
  // This DCHECK enforces that kIconSize is an acceptable size for the source
  // list.
  DCHECK_GE(ui::TableModel::kIconSize, gfx::kFaviconSize);

  controller_->SetThumbnailSize(
      gfx::Size(ui::TableModel::kIconSize, ui::TableModel::kIconSize));

  SetLayoutManager(std::make_unique<views::FillLayout>());

  model_ = std::make_unique<TabListModel>(
      controller_, base::BindRepeating(&DesktopMediaTabList::OnPreviewUpdated,
                                       weak_factory_.GetWeakPtr()));
  auto selection_changed_callback = base::BindRepeating(
      &DesktopMediaTabList::OnSelectionChanged, weak_factory_.GetWeakPtr());
  view_observer_ = std::make_unique<TabListViewObserver>(
      controller_, selection_changed_callback);

  auto list = std::make_unique<views::TableView>(
      model_.get(), std::vector<ui::TableColumn>(1), views::ICON_AND_TEXT,
      true);
  list->set_observer(view_observer_.get());
  list->GetViewAccessibility().OverrideName(accessible_name);
  list_ = list.get();

  AddChildView(BuildUI(std::move(list)));
}

std::unique_ptr<views::View> DesktopMediaTabList::BuildUI(
    std::unique_ptr<views::TableView> list) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  auto preview_wrapper = std::make_unique<views::View>();
  preview_wrapper->SetPreferredSize(desktopcapture::kPreviewSize);

  auto preview = std::make_unique<views::ImageView>();
  preview->SetVisible(false);
  preview->SetSize(desktopcapture::kPreviewSize);
  preview->SetAccessibleName(l10n_util::GetStringUTF16(
      IDS_DESKTOP_MEDIA_PICKER_PREVIEW_ACCESSIBLE_NAME));
  preview_ = preview_wrapper->AddChildView(std::move(preview));

  auto empty_preview_label = std::make_unique<views::Label>();
  empty_preview_label->SetText(
      l10n_util::GetStringUTF16(IDS_DESKTOP_MEDIA_PICKER_EMPTY_PREVIEW));
  empty_preview_label->SetMultiLine(true);
  empty_preview_label->SetPreferredSize(desktopcapture::kPreviewSize);
  empty_preview_label->SetSize(desktopcapture::kPreviewSize);
  empty_preview_label_ =
      preview_wrapper->AddChildView(std::move(empty_preview_label));

  auto preview_label = std::make_unique<views::Label>();
  preview_label->SetMultiLine(true);
  preview_label->SetMaximumWidth(desktopcapture::kPreviewSize.width());
  preview_label->SetMaxLines(2);
  preview_label->SetHorizontalAlignment(gfx::HorizontalAlignment::ALIGN_LEFT);

  auto preview_sidebar = std::make_unique<views::View>();
  preview_wrapper_ = preview_sidebar->AddChildView(std::move(preview_wrapper));
  preview_label_ = preview_sidebar->AddChildView(std::move(preview_label));

  preview_sidebar->SetLayoutManager(std::make_unique<views::BoxLayout>(
      views::BoxLayout::Orientation::kVertical, gfx::Insets(),
      /*between_child_spacing=*/11));

  std::unique_ptr<views::View> full_panel = std::make_unique<views::View>();

  View* scroll_view = full_panel->AddChildView(
      views::TableView::CreateScrollViewWithTable(std::move(list)));
  scroll_view->SetPreferredSize(gfx::Size(kListWidth, 0));
  full_panel->AddChildView(std::move(preview_sidebar));

  full_panel->SetLayoutManager(std::make_unique<views::BoxLayout>(
      views::BoxLayout::Orientation::kHorizontal,
      gfx::Insets::TLBR(15, 0, 0, 0),
      /*between_child_spacing=*/12, true));

  auto container = std::make_unique<View>();
  container->SetUseDefaultFillLayout(true);
  container->AddChildView(std::move(full_panel));
  return container;
}

DesktopMediaTabList::~DesktopMediaTabList() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  list_->SetModel(nullptr);
}

gfx::Size DesktopMediaTabList::CalculatePreferredSize() const {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  // The picker should have a fixed height of 10 rows.
  return gfx::Size(0, list_->GetRowHeight() * 10);
}

int DesktopMediaTabList::GetHeightForWidth(int width) const {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  // If this method isn't overridden here, the default implementation would fall
  // back to FillLayout's GetHeightForWidth, which would ask the TableView,
  // which would return something based on the total number of rows, since
  // TableView expects to always be sized by its container. Avoid even asking it
  // by using the same height as CalculatePreferredSize().
  return CalculatePreferredSize().height();
}

void DesktopMediaTabList::OnThemeChanged() {
  DesktopMediaListController::ListView::OnThemeChanged();

  const ui::ColorProvider* const color_provider = GetColorProvider();
  list_->SetBorder(views::CreateSolidBorder(
      /*thickness=*/1,
      color_provider->GetColor(kColorDesktopMediaTabListBorder)));
  const SkColor background_color =
      color_provider->GetColor(kColorDesktopMediaTabListPreviewBackground);
  preview_wrapper_->SetBackground(
      views::CreateSolidBackground(background_color));
  empty_preview_label_->SetBackground(
      views::CreateSolidBackground(background_color));
  empty_preview_label_->SetBackgroundColor(background_color);
}

absl::optional<content::DesktopMediaID> DesktopMediaTabList::GetSelection() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  absl::optional<size_t> row = list_->GetFirstSelectedRow();
  if (!row.has_value())
    return absl::nullopt;
  return controller_->GetSource(row.value()).id;
}

DesktopMediaListController::SourceListListener*
DesktopMediaTabList::GetSourceListListener() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  return model_.get();
}

void DesktopMediaTabList::ClearSelection() {
  // Changing the selection in the list will ensure that all appropriate change
  // events are fired.
  list_->Select(absl::nullopt);
}

void DesktopMediaTabList::ClearPreview() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  preview_label_->SetText(u"");
  preview_->SetImage(nullptr);
  preview_->SetVisible(false);
  empty_preview_label_->SetVisible(true);
}

void DesktopMediaTabList::OnSelectionChanged() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  absl::optional<size_t> row = list_->GetFirstSelectedRow();
  if (!row.has_value()) {
    ClearPreview();
    controller_->SetPreviewedSource(absl::nullopt);
    return;
  }
  const DesktopMediaList::Source& source = controller_->GetSource(row.value());

  const std::u16string truncated_title =
      source.name.substr(0, kMaxPreviewTitleLength);
  preview_label_->SetText(truncated_title);

  // Trigger a preview update to either show a previous snapshot for this source
  // if we have one, or clear it if we don't.
  OnPreviewUpdated(row.value());

  // Update the source for which previews are generated.
  controller_->SetPreviewedSource(source.id);

  preview_->SetVisible(true);
  empty_preview_label_->SetVisible(false);
}

void DesktopMediaTabList::ClearPreviewImageIfUnchanged(
    size_t previous_preview_set_count) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  if (preview_set_count_ == previous_preview_set_count) {
    // preview_ has not been set to a new image since this was scheduled. Clear
    // it.
    preview_->SetImage(nullptr);
  }
}

void DesktopMediaTabList::OnPreviewUpdated(size_t index) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  if (index != list_->GetFirstSelectedRow()) {
    return;
  }

  const DesktopMediaList::Source& source = controller_->GetSource(index);
  if (!source.preview.isNull()) {
    preview_->SetImage(source.preview);
    ++preview_set_count_;
  } else {
    // Clear the preview after a short time.
    base::SequencedTaskRunnerHandle::Get()->PostDelayedTask(
        FROM_HERE,
        base::BindOnce(&DesktopMediaTabList::ClearPreviewImageIfUnchanged,
                       weak_factory_.GetWeakPtr(), preview_set_count_),
        kClearPreviewDelay);
  }
  preview_label_->SetText(source.name.substr(0, kMaxPreviewTitleLength));
}

BEGIN_METADATA(DesktopMediaTabList, DesktopMediaListController::ListView)
END_METADATA


text:
/**
 * php tests
 *
 * @author Craig Campbell
 */
RainbowTester.startTest('php');

RainbowTester.run(
    'echo',

    'echo \'hello world\';',

    'echo \'hello world\';'
);

RainbowTester.run(
    'variable',

    '$foo = true;',

    '$foo = true;'
);

RainbowTester.run(
    'variable variable',

    '$$foo = true;',

    '$$foo = true;'
);

RainbowTester.run(
    'string concatenation',

    "$foo = 'test' . 'string' . 'concatenation';",

    '$foo = \'test\' . \'string\' . \'concatenation\';'
);

RainbowTester.run(
    'include 1',

    "include 'App.php';",

    'include \'App.php\';'
);

RainbowTester.run(
    'include 2',

    "include_once('App.php');",

    'include_once(\'App.php\');'
);

RainbowTester.run(
    'instanceof',

    "$is_array_object = $collection instanceof ArrayObject;",

    '$is_array_object = $collection instanceof ArrayObject;'
);

RainbowTester.run(
    'instanceof namespace class',

    "$is_user = $object instanceof App\\User;",

    '$is_user = $object instanceof App\\User;'
);

RainbowTester.run(
    'array stuff',

    '$turtles = array(\n' +
    '   \'leonardo\',\n' +
    '   \'michaelangelo\',\n' +
    '   \'donatello\',\n' +
    '   \'raphael\'\n' +
    ');\n' +
    '\n' +
    '$exists = array_key_exists(0, $turtles);',

    '$turtles = array(\n' +
    '   \'leonardo\',\n' +
    '   \'michaelangelo\',\n' +
    '   \'donatello\',\n' +
    '   \'raphael\'\n' +
    ');\n' +
    '\n' +
    '$exists = array_key_exists(0, $turtles);'
);

RainbowTester.run(
    'php tag',

    '<?php echo $foo; ?>',

    '<?php echo $foo; ?>'
);

RainbowTester.run(
    'php tag 2',

    '<?php echo \'?>\'; ?>',

    '<?php echo \'?>\'; ?>'
);

RainbowTester.run(
    'namespace declaration',

    'namespace Sonic\\Database;',

    'namespace Sonic\\Database;'
);

RainbowTester.run(
    'use declaration',

    'use Sonic;',

    'use Sonic;'
);

RainbowTester.run(
    'class declaration',

    'class MyClass {}',

    'class MyClass {}'
);

RainbowTester.run(
    'trait declaration',

    'trait MyClass {}',

    'trait MyClass {}'
);

RainbowTester.run(
    'interface declaration',

    'interface IMyClass {}',

    'interface IMyClass {}'
);

RainbowTester.run(
    'abstract class declaration',

    'abstract class MyClass {}',

    'abstract class MyClass {}'
);

RainbowTester.run(
    'final class declaration',

    'final class TestClass\n' +
    '{\n' +
    '}',

    'final class TestClass\n' +
    '{\n' +
    '}'
);

RainbowTester.run(
    'class with an implementation declaration',

    'class Collection implements IList {}',

    'class Collection implements IList {}'
);

RainbowTester.run(
    'child class declaration',

    'class Collection extends ArrayObject {}',

    'class Collection extends ArrayObject {}'
);

RainbowTester.run(
    'child class with an implementation declaration',

    'class Collection extends ArrayObject implements IList {}',

    'class Collection extends ArrayObject implements IList {}'
);

RainbowTester.run(
    'final child class declaration',

    'final class TestClass extends \\Some\\Other\\Class {}',

    'final class TestClass extends \\Some\\Other\\Class {}'
);

RainbowTester.run(
    'test static',

    'self::_doSomething();\n' +
    'static::_doSomethingElse();',

    'self::_doSomething();\n' +
    'static::_doSomethingElse();'
);

RainbowTester.run(
    'test magic function',

    'function __autoload($class)\n' +
    '{\n' +
    '   // do whatever\n' +
    '}',

    'function __autoload($class)\n' +
    '{\n' +
    '   // do whatever\n' +
    '}'
);

RainbowTester.run(
    'test magic method',

    'class SomeThing\n' +
    '{\n' +
    '   protected $_foo;\n' +
    '\n' +
    '   public function __construct($foo)\n' +
    '   {\n' +
    '       $this->_foo = $foo;\n' +
    '   }\n' +
    '}',

    'class SomeThing\n' +
    '{\n' +
    '   protected $_foo;\n' +
    '\n' +
    '   public function __construct($foo)\n' +
    '   {\n' +
    '       $this->_foo = $foo;\n' +
    '   }\n' +
    '}'
);

RainbowTester.run(
    'test new class',

    'new SomeClass();',

    'new SomeClass();'
);

RainbowTester.run(
    'test new namespace class',

    'new Sonic\\Database\\Query();',

    'new Sonic\\Database\\Query();'
);

RainbowTester.run(
    'test new class without parenthesis',

    'new Sonic\\Controller;',

    'new Sonic\\Controller;'
);

RainbowTester.run(
    'test static class call',

    '$path = Sonic\\App::getInstance()->getPath();',

    '$path = Sonic\\App::getInstance()->getPath();'
);

RainbowTester.run(
    'constant language',

    'true; TRUE;',

    'true; TRUE;'
);

RainbowTester.run(
    'constant',

    'TEST_CONSTANT',

    'TEST_CONSTANT'
);

RainbowTester.run(
    'constant 2',

    '(TEST_CONSTANT_2)',

    '(TEST_CONSTANT_2)'
);

RainbowTester.run(
    'class constant',

    '$version = Sonic\\App::VERSION',

    '$version = Sonic\\App::VERSION'
);

RainbowTester.run(
    'static variable access',

    '$foo = Sonic\\App::$static_property;',

    '$foo = Sonic\\App::$static_property;'
);

RainbowTester.run(
    'type hint',

    'public static function getForUser(User $user, Sort $sort) {}',

    'public static function getForUser(User $user, Sort $sort) {}'
);

RainbowTester.run(
    'type hint with namespace',

    'public static function getForUser(\\SomeApp\\User $user) {}',

    'public static function getForUser(\\SomeApp\\User $user) {}'
);
RainbowTester.endTest('php');