text:
infakt-api
============

**DISCLAIMER:** This library is not properly tested (neither is it well documented), use at own risk!

---

This is a PHP 5.3+ API wrapper for the [InFakt API](http://infakt.pl/)

* Author: Jan Kondratowicz
* Created for project: [Fokus](http://getfokus.com)

---

##Requirements
* PHP 5.3+
* [CURL](http://php.net/manual/en/book.curl.php)
* API credentials.

##Installation

###Composer
Add the following package to `composer.json`:
```
"getfokus/infakt-api": "*"
```

##Basic usage

To call API just use method:
```
$response = $client->get($action, array $params);
```

###Example
```
<?php

$apiKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

try {
    $client = new InfaktApi\Client($apiKey);
    $response = $client->get('invoices');
    $parsed = json_decode($response);
    var_dump($parsed);
} catch (InfaktApi\Exception\UnauthorizedException $e) {
    echo 'Bad credentials';
}

```


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>

    <color name="color_red">#de1414</color>
    <color name="color_blue">#4950d7</color>
    <color name="color_green">#33cc25</color>
    <color name="color_orange">#ffffbb33</color>
</resources>

redpajama_set_name: RedPajamaGithub


text:
// This file is part of SNMP#NET.
//
// SNMP#NET is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// SNMP#NET is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with SNMP#NET.  If not, see <http://www.gnu.org/licenses/>.
//
using System;
using System.Security.Cryptography;
using System.Net;

namespace SnmpSharpNet
{
	/// <summary>AES privacy protocol implementation class.</summary>
	public class PrivacyAES : IPrivacyProtocol
	{
		/// <summary>
		/// Salt value
		/// </summary>
		protected Int64 _salt = 0;
		/// <summary>
		/// AES protocol key bytes. Valid values are 16 (for AES128), 24 (AES192) or 32 (AES256).
		/// </summary>
		protected int _keyBytes = 16; // Default is 128bit AES protocol

		/// <summary>
		/// Standard constructor.
		/// </summary>
		/// <param name="keyBytes">Key size in bytes. Acceptable values are
		/// 16 = 128-bit key size, 24 = 192-bit key size, or 32 = 256-bit key size.</param>
		public PrivacyAES(int keyBytes)
		{
			if (keyBytes != 16 && keyBytes != 24 && keyBytes != 32)
				throw new ArgumentOutOfRangeException("keyBytes", "Valid key sizes are 16, 24 and 32 bytes.");
			_keyBytes = keyBytes;
			// initialize salt generator
			Random rand = new Random();
			_salt = Convert.ToInt64(rand.Next(1, Int32.MaxValue));
		}

		/// <summary>
		/// Get next salt Int64 value. Used internally to encrypt data.
		/// </summary>
		/// <returns>Random Int64 value</returns>
		protected Int64 NextSalt()
		{
			if (_salt == Int64.MaxValue)
				_salt = 1;
			else
				_salt += 1;
			return _salt;
		}

		/// <summary>
		/// Encrypt <see cref="ScopedPdu"/> data BER encoded in a byte array.
		/// </summary>
		/// <param name="unencryptedData">BER encoded <see cref="ScopedPdu"/> byte array that needs to be encrypted</param>
		/// <param name="offset">Offset within the BER encoded byte array to start encryption operation from.</param>
		/// <param name="length">Length of data to encrypt</param>
		/// <param name="key">Encryption key</param>
		/// <param name="engineBoots">Authoritative engine boots value. Retrieved as part of SNMP v3 discovery process.</param>
		/// <param name="engineTime">Authoritative engine time value. Retrieved as part of SNMP v3 discovery process.</param>
		/// <param name="privacyParameters">Byte array that will receive privacy parameters information that is the result of the
		/// encryption procedure.</param>
		/// <param name="authDigest">Authentication digest reference. Not used by AES protocol and can be null</param>
		/// <returns>Byte array containing encrypted <see cref="ScopedPdu"/> BER encoded data</returns>
		public byte[] Encrypt(byte[] unencryptedData, int offset, int length, byte[] key, int engineBoots, int engineTime, out byte[] privacyParameters, IAuthenticationDigest authDigest)
		{
			// check the key before doing anything else
			if (key == null || key.Length < _keyBytes)
				throw new ArgumentOutOfRangeException("encryptionKey", "Invalid key length");

			byte[] iv = new byte[16];
			Int64 salt = NextSalt();
			privacyParameters = new byte[PrivacyParametersLength];
			byte[] bootsBytes = BitConverter.GetBytes(engineBoots);
			iv[0] = bootsBytes[3];
			iv[1] = bootsBytes[2];
			iv[2] = bootsBytes[1];
			iv[3] = bootsBytes[0];
			byte[] timeBytes = BitConverter.GetBytes(engineTime);
			iv[4] = timeBytes[3];
			iv[5] = timeBytes[2];
			iv[6] = timeBytes[1];
			iv[7] = timeBytes[0];

			// Set privacy parameters to the local 64 bit salt value
			byte[] saltBytes = BitConverter.GetBytes(salt);
			privacyParameters[0] = saltBytes[7];
			privacyParameters[1] = saltBytes[6];
			privacyParameters[2] = saltBytes[5];
			privacyParameters[3] = saltBytes[4];
			privacyParameters[4] = saltBytes[3];
			privacyParameters[5] = saltBytes[2];
			privacyParameters[6] = saltBytes[1];
			privacyParameters[7] = saltBytes[0];

			// Copy salt value to the iv array
			Buffer.BlockCopy(privacyParameters, 0, iv, 8, 8);

			Rijndael rm = new RijndaelManaged();
			rm.KeySize = _keyBytes * 8;
			rm.FeedbackSize = 128;
			rm.BlockSize = 128;
			// we have to use Zeros padding otherwise we get encrypt buffer size exception
			rm.Padding = PaddingMode.Zeros;
			rm.Mode = CipherMode.CFB;
			// make sure we have the right key length
			byte[] pkey = new byte[MinimumKeyLength];
			Buffer.BlockCopy(key, 0, pkey, 0, MinimumKeyLength);
			rm.Key = pkey;
			rm.IV = iv;
			ICryptoTransform cryptor = rm.CreateEncryptor();
			byte[] encryptedData = cryptor.TransformFinalBlock(unencryptedData, offset, length);
			// check if encrypted data is the same length as source data
			if (encryptedData.Length != unencryptedData.Length)
			{
				// cut out the padding
				byte[] tmp = new byte[unencryptedData.Length];
				Buffer.BlockCopy(encryptedData, 0, tmp, 0, unencryptedData.Length);
				return tmp;
			}
			return encryptedData;
		}

		/// <summary>
		/// Decrypt <see cref="ScopedPdu"/> BER encoded byte array.
		/// </summary>
		/// <param name="cryptedData">Encrypted data byte array</param>
		/// <param name="offset">Offset within the buffer to start decryption process from</param>
		/// <param name="length">Length of data to decrypt</param>
		/// <param name="key">Decryption key</param>
		/// <param name="engineBoots">Authoritative engine boots value. Retrieved as part of SNMP v3 discovery procedure</param>
		/// <param name="engineTime">Authoritative engine time value. Retrieved as part of SNMP v3 discovery procedure</param>
		/// <param name="privacyParameters">Privacy parameters parsed from the incoming packet.</param>
		/// <returns>Byte array containing decrypted <see cref="ScopedPdu"/> in BER encoded format.</returns>
		public byte[] Decrypt(byte[] cryptedData, int offset, int length, byte[] key, int engineBoots, int engineTime, byte[] privacyParameters)
		{
			if (key == null || key.Length < _keyBytes)
				throw new ArgumentOutOfRangeException("decryptionKey", "Invalid key length");

			byte[] iv = new byte[16];

			byte[] bootsBytes = BitConverter.GetBytes(engineBoots);
			iv[0] = bootsBytes[3];
			iv[1] = bootsBytes[2];
			iv[2] = bootsBytes[1];
			iv[3] = bootsBytes[0];
			byte[] timeBytes = BitConverter.GetBytes(engineTime);
			iv[4] = timeBytes[3];
			iv[5] = timeBytes[2];
			iv[6] = timeBytes[1];
			iv[7] = timeBytes[0];

			// Copy salt value to the iv array
			Buffer.BlockCopy(privacyParameters, 0, iv, 8, 8);

			byte[] decryptedData = null;

			// now do CFB decryption of the encrypted data
			Rijndael rm = Rijndael.Create();
			rm.KeySize = _keyBytes * 8;
			rm.FeedbackSize = 128;
			rm.BlockSize = 128;
			rm.Padding = PaddingMode.Zeros;
			rm.Mode = CipherMode.CFB;
			if (key.Length > MinimumKeyLength)
			{
				byte[] normKey = new byte[MinimumKeyLength];
				Buffer.BlockCopy(key, 0, normKey, 0, MinimumKeyLength);
				rm.Key = normKey;
			}
			else
			{
				rm.Key = key;
			}
			rm.IV = iv;
			System.Security.Cryptography.ICryptoTransform cryptor;
			cryptor = rm.CreateDecryptor();

			// We need to make sure that cryptedData is a collection of 128 byte blocks
			if ((cryptedData.Length % _keyBytes) != 0)
			{
				byte[] buffer = new byte[length];
				Buffer.BlockCopy(cryptedData, offset, buffer, 0, length);
				int div = (int)Math.Floor(buffer.Length / (double)16);
				int newLength = (div + 1) * 16;
				byte[] decryptBuffer = new byte[newLength];
				Buffer.BlockCopy(buffer, 0, decryptBuffer, 0, buffer.Length);
				decryptedData = cryptor.TransformFinalBlock(decryptBuffer, 0, decryptBuffer.Length);
				// now remove padding
				Buffer.BlockCopy(decryptedData, 0, buffer, 0, length);
				return buffer;
			}

			decryptedData = cryptor.TransformFinalBlock(cryptedData, offset, length);

			return decryptedData;
		}

		/// <summary>
		/// Get minimum encryption/decryption key length required by the protocol.
		/// </summary>
		public int MinimumKeyLength
		{
			get { return _keyBytes; }
		}

		/// <summary>
		/// Get maximum encryption/decryption key length required by the protocol.
		/// </summary>
		public int MaximumKeyLength
		{
			get { return _keyBytes; }
		}

		/// <summary>
		/// Get length of the privacy parameters byte array that is generated by the encryption method and used by the
		/// decryption method.
		/// </summary>
		public int PrivacyParametersLength
		{
			get { return 8; }
		}

		/// <summary>
		/// Calculates and returns length of the buffer that is the result of the encryption method.
		/// </summary>
		/// <param name="scopedPduLength">Length of the buffer that is needs to be encrypted.</param>
		/// <returns>Length of the encrypted byte array after the call to Encrypt method.</returns>
		public int GetEncryptedLength(int scopedPduLength)
		{
			return scopedPduLength;
		}

		/// <summary>
		/// Some protocols support a method to extend the encryption or decryption key when supplied key
		/// is too short.
		/// </summary>
		/// <param name="shortKey">Key that needs to be extended</param>
		/// <param name="password">Privacy password as configured on the SNMP agent.</param>
		/// <param name="engineID">Authoritative engine id. Value is retrieved as part of SNMP v3 discovery procedure</param>
		/// <param name="authProtocol">Authentication protocol class instance cast as <see cref="IAuthenticationDigest"/></param>
		/// <returns>Extended key value</returns>
		public byte[] ExtendShortKey(byte[] shortKey, byte[] password, byte[] engineID, IAuthenticationDigest authProtocol)
		{
			byte[] extKey = new byte[MinimumKeyLength];
			byte[] lastKeyBuf = new byte[shortKey.Length];
			Array.Copy(shortKey, lastKeyBuf, shortKey.Length);
			int keyLen = shortKey.Length > MinimumKeyLength ? MinimumKeyLength : shortKey.Length;
			Array.Copy(shortKey, extKey, keyLen);
			while (keyLen < MinimumKeyLength)
			{
				byte[] tmpBuf = authProtocol.PasswordToKey(lastKeyBuf, engineID);
				if (tmpBuf == null)
				{
					return null;
				}
				if (tmpBuf.Length <= (MinimumKeyLength - keyLen))
				{
					Array.Copy(tmpBuf, 0, extKey, keyLen, tmpBuf.Length);
					keyLen += tmpBuf.Length;
				}
				else
				{
					Array.Copy(tmpBuf, 0, extKey, keyLen, MinimumKeyLength - keyLen);
					keyLen += (MinimumKeyLength - keyLen);
				}
				lastKeyBuf = new byte[tmpBuf.Length];
				Array.Copy(tmpBuf, lastKeyBuf, tmpBuf.Length);
			}
			return extKey;
		}

		/// <summary>
		/// Privacy protocol name. Returns string "AES"
		/// </summary>
		public virtual string Name
		{
			get { return "AES"; }
		}

		/// <summary>
		/// AES implementation supports extending of a short encryption key. Always returns true.
		/// </summary>
		public bool CanExtendShortKey
		{
			get
			{
				return true;
			}
		}
		/// <summary>
		/// Convert privacy password into encryption key using packet authentication hash.
		/// </summary>
		/// <param name="secret">Privacy user secret</param>
		/// <param name="engineId">Authoritative engine id of the snmp agent</param>
		/// <param name="authProtocol">Authentication protocol</param>
		/// <returns>Encryption key</returns>
		/// <exception cref="SnmpPrivacyException">Thrown when key size is shorter then MinimumKeyLength</exception>
		public byte[] PasswordToKey(byte[] secret, byte[] engineId, IAuthenticationDigest authProtocol)
		{
			if (secret == null || secret.Length < 8)
				throw new SnmpPrivacyException("Invalid privacy secret length.");
			byte[] key = authProtocol.PasswordToKey(secret, engineId);
			if (key.Length < MinimumKeyLength)
			{
				key = ExtendShortKey(key, secret, engineId, authProtocol);
			}
			return key;
		}
	}
}


text:
namespace Graph3D.Vrml.Fields {
    public class SFFloat : Field {

        public SFFloat() {
        }

        public SFFloat(float value) {
            Value = value;
        }

        public float Value { get; set; }

        public static implicit operator SFFloat(float value) {
            return new SFFloat(value);
        }

        public override void AcceptVisitor(IFieldVisitor visitor) {
            visitor.visit(this);
        }

        public override Field Clone() {
            return new SFFloat(Value);
        }

        public override FieldType Type {
            get { return FieldType.SFFloat; }
        }

        public override string ToString() {
            return Value.ToString();
        }

    }
}


text:
<?php

namespace OC\PlatformBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller;
use Symfony\Component\HttpFoundation\Response;
class ServiceController extends Controller {

    public function serviceAction(){
        return new Response('Hello word');
    }
}


text:
using System.ComponentModel.DataAnnotations;
using Orchard.ContentManagement;

namespace Contrib.Taxonomies.Models {
    /// <summary>
    /// Represents the part for the Taxonomy Menu Widget
    /// </summary>
    public class TaxonomyMenuPart : ContentPart<TaxonomyMenuPartRecord> {

        /// <summary>
        /// The taxonomy to display
        /// </summary>

        [Required]
        public TaxonomyPartRecord TaxonomyPartRecord {
            get { return Record.TaxonomyPartRecord; }
            set { Record.TaxonomyPartRecord = value; }
        }

        /// <summary>
        /// Top term to display in the menu.
        /// If null, the taxonomy is supposed to be the top term.
        /// </summary>
        public TermPartRecord TermPartRecord {
            get { return Record.TermPartRecord; }
            set { Record.TermPartRecord = value; }
        }

        /// <summary>
        /// Whether to display the root node or not.
        /// If <c>False</c>, the menu will have a flat first level.
        /// </summary>
        public bool DisplayTopMenuItem {
            get { return Record.DisplayTopMenuItem; }
            set { Record.DisplayTopMenuItem = value; }
        }

        /// <summary>
        /// How many sub-levels to display.
        /// If 0, then there will be only one level displayed (default)
        /// </summary>
        public int LevelsToDisplay {
            get { return Record.LevelsToDisplay; }
            set { Record.LevelsToDisplay = value; }
        }

        /// <summary>
        /// Whether to display the number of content items
        /// associated with this term, in the generated menu item text
        /// </summary>
        public bool DisplayContentCount {
            get { return Record.DisplayContentCount; }
            set { Record.DisplayContentCount = value; }
        }

        /// <summary>
        /// Whether to hide the terms without any associated content
        /// </summary>
        public bool HideEmptyTerms {
            get { return Record.HideEmptyTerms; }
            set { Record.HideEmptyTerms = value; }
        }
    }
}


text:
package com.speedment.generator.standard.internal;

import static com.speedment.common.injector.State.INITIALIZED;
import static com.speedment.generator.standard.StandardTranslatorKey.APPLICATION;
import static com.speedment.generator.standard.StandardTranslatorKey.APPLICATION_BUILDER;
import static com.speedment.generator.standard.StandardTranslatorKey.APPLICATION_IMPL;
import static com.speedment.generator.standard.StandardTranslatorKey.ENTITY;
import static com.speedment.generator.standard.StandardTranslatorKey.ENTITY_IMPL;
import static com.speedment.generator.standard.StandardTranslatorKey.ENTRY_POINT;
import static com.speedment.generator.standard.StandardTranslatorKey.GENERATED_APPLICATION;
import static com.speedment.generator.standard.StandardTranslatorKey.GENERATED_APPLICATION_BUILDER;
import static com.speedment.generator.standard.StandardTranslatorKey.GENERATED_APPLICATION_IMPL;
import static com.speedment.generator.standard.StandardTranslatorKey.GENERATED_ENTITY;
import static com.speedment.generator.standard.StandardTranslatorKey.GENERATED_ENTITY_IMPL;
import static com.speedment.generator.standard.StandardTranslatorKey.GENERATED_MANAGER;
import static com.speedment.generator.standard.StandardTranslatorKey.GENERATED_MANAGER_IMPL;
import static com.speedment.generator.standard.StandardTranslatorKey.GENERATED_METADATA;
import static com.speedment.generator.standard.StandardTranslatorKey.GENERATED_SQL_ADAPTER;
import static com.speedment.generator.standard.StandardTranslatorKey.INJECTOR_PROXY;
import static com.speedment.generator.standard.StandardTranslatorKey.MANAGER;
import static com.speedment.generator.standard.StandardTranslatorKey.MANAGER_IMPL;
import static com.speedment.generator.standard.StandardTranslatorKey.SQL_ADAPTER;

import com.speedment.common.injector.annotation.ExecuteBefore;
import com.speedment.common.injector.annotation.WithState;
import com.speedment.generator.standard.entity.EntityImplTranslator;
import com.speedment.generator.standard.entity.EntityTranslator;
import com.speedment.generator.standard.entity.GeneratedEntityImplTranslator;
import com.speedment.generator.standard.entity.GeneratedEntityTranslator;
import com.speedment.generator.standard.lifecycle.ApplicationBuilderTranslator;
import com.speedment.generator.standard.lifecycle.ApplicationImplTranslator;
import com.speedment.generator.standard.lifecycle.ApplicationTranslator;
import com.speedment.generator.standard.lifecycle.EntryPointTranslator;
import com.speedment.generator.standard.lifecycle.GeneratedApplicationBuilderTranslator;
import com.speedment.generator.standard.lifecycle.GeneratedApplicationImplTranslator;
import com.speedment.generator.standard.lifecycle.GeneratedApplicationTranslator;
import com.speedment.generator.standard.lifecycle.GeneratedMetadataTranslator;
import com.speedment.generator.standard.lifecycle.InjectorProxyTranslator;
import com.speedment.generator.standard.manager.GeneratedManagerImplTranslator;
import com.speedment.generator.standard.manager.GeneratedManagerTranslator;
import com.speedment.generator.standard.manager.GeneratedSqlAdapterTranslator;
import com.speedment.generator.standard.manager.ManagerImplTranslator;
import com.speedment.generator.standard.manager.ManagerTranslator;
import com.speedment.generator.standard.manager.SqlAdapterTranslator;
import com.speedment.generator.translator.component.CodeGenerationComponent;
import com.speedment.runtime.config.Project;
import com.speedment.runtime.config.Table;

/**
 *
 * @author Emil Forslund
 * @since 3.0.1
 */
public final class StandardTranslatorComponent {

    @ExecuteBefore(INITIALIZED)
    public void installTranslators(@WithState(INITIALIZED) CodeGenerationComponent codeGen) {
        codeGen.put(Table.class, ENTITY, EntityTranslator::new);
        codeGen.put(Table.class, ENTITY_IMPL, EntityImplTranslator::new);
        codeGen.put(Table.class, MANAGER, ManagerTranslator::new);
        codeGen.put(Table.class, MANAGER_IMPL, ManagerImplTranslator::new);
        codeGen.put(Table.class, SQL_ADAPTER, SqlAdapterTranslator::new);
        codeGen.put(Table.class, GENERATED_ENTITY, GeneratedEntityTranslator::new);
        codeGen.put(Table.class, GENERATED_ENTITY_IMPL, GeneratedEntityImplTranslator::new);
        codeGen.put(Table.class, GENERATED_MANAGER, GeneratedManagerTranslator::new);
        codeGen.put(Table.class, GENERATED_MANAGER_IMPL, GeneratedManagerImplTranslator::new);
        codeGen.put(Table.class, GENERATED_SQL_ADAPTER, GeneratedSqlAdapterTranslator::new);
        codeGen.put(Project.class, APPLICATION, ApplicationTranslator::new);
        codeGen.put(Project.class, APPLICATION_IMPL, ApplicationImplTranslator::new);
        codeGen.put(Project.class, APPLICATION_BUILDER, ApplicationBuilderTranslator::new);
        codeGen.put(Project.class, GENERATED_APPLICATION, GeneratedApplicationTranslator::new);
        codeGen.put(Project.class, GENERATED_APPLICATION_IMPL, GeneratedApplicationImplTranslator::new);
        codeGen.put(Project.class, GENERATED_APPLICATION_BUILDER, GeneratedApplicationBuilderTranslator::new);
        codeGen.put(Project.class, GENERATED_METADATA, GeneratedMetadataTranslator::new);
        codeGen.put(Project.class, INJECTOR_PROXY, InjectorProxyTranslator::new);
        codeGen.put(Project.class, ENTRY_POINT, EntryPointTranslator::new);
    }
}


text:
// DESCRIPTION = disallow usage of expressions in statement position
// STATUS = 2

/* eslint require-jsdoc: 0*/
/* eslint no-undef: 0*/
// <!START
// Bad
/*
a && b();
*/
// END!>


text:
require "cases/helper"
require "models/developer"
require "models/project"
require "models/company"
require "models/topic"
require "models/reply"
require "models/computer"
require "models/post"
require "models/author"
require "models/tag"
require "models/tagging"
require "models/comment"
require "models/sponsor"
require "models/member"
require "models/essay"
require "models/toy"
require "models/invoice"
require "models/line_item"
require "models/column"
require "models/record"
require "models/admin"
require "models/admin/user"
require "models/ship"
require "models/treasure"
require "models/parrot"

class BelongsToAssociationsTest < ActiveRecord::TestCase
  fixtures :accounts, :companies, :developers, :projects, :topics,
           :developers_projects, :computers, :authors, :author_addresses,
           :posts, :tags, :taggings, :comments, :sponsors, :members

  def test_belongs_to
    firm = Client.find(3).firm
    assert_not_nil firm
    assert_equal companies(:first_firm).name, firm.name
  end

  def test_assigning_belongs_to_on_destroyed_object
    client = Client.create!(name: "Client")
    client.destroy!
    assert_raise(frozen_error_class) { client.firm = nil }
    assert_raise(frozen_error_class) { client.firm = Firm.new(name: "Firm") }
  end

  def test_missing_attribute_error_is_raised_when_no_foreign_key_attribute
    assert_raises(ActiveModel::MissingAttributeError) { Client.select(:id).first.firm }
  end

  def test_belongs_to_does_not_use_order_by
    ActiveRecord::SQLCounter.clear_log
    Client.find(3).firm
  ensure
    assert ActiveRecord::SQLCounter.log_all.all? { |sql| /order by/i !~ sql }, "ORDER BY was used in the query"
  end

  def test_belongs_to_with_primary_key
    client = Client.create(name: "Primary key client", firm_name: companies(:first_firm).name)
    assert_equal companies(:first_firm).name, client.firm_with_primary_key.name
  end

  def test_belongs_to_with_primary_key_joins_on_correct_column
    sql = Client.joins(:firm_with_primary_key).to_sql
    if current_adapter?(:Mysql2Adapter)
      assert_no_match(/`firm_with_primary_keys_companies`\.`id`/, sql)
      assert_match(/`firm_with_primary_keys_companies`\.`name`/, sql)
    elsif current_adapter?(:OracleAdapter)
      # on Oracle aliases are truncated to 30 characters and are quoted in uppercase
      assert_no_match(/"firm_with_primary_keys_compani"\."id"/i, sql)
      assert_match(/"firm_with_primary_keys_compani"\."name"/i, sql)
    else
      assert_no_match(/"firm_with_primary_keys_companies"\."id"/, sql)
      assert_match(/"firm_with_primary_keys_companies"\."name"/, sql)
    end
  end

  def test_optional_relation
    original_value = ActiveRecord::Base.belongs_to_required_by_default
    ActiveRecord::Base.belongs_to_required_by_default = true

    model = Class.new(ActiveRecord::Base) do
      self.table_name = "accounts"
      def self.name; "Temp"; end
      belongs_to :company, optional: true
    end

    account = model.new
    assert_predicate account, :valid?
  ensure
    ActiveRecord::Base.belongs_to_required_by_default = original_value
  end

  def test_not_optional_relation
    original_value = ActiveRecord::Base.belongs_to_required_by_default
    ActiveRecord::Base.belongs_to_required_by_default = true

    model = Class.new(ActiveRecord::Base) do
      self.table_name = "accounts"
      def self.name; "Temp"; end
      belongs_to :company, optional: false
    end

    account = model.new
    assert_not_predicate account, :valid?
    assert_equal [{ error: :blank }], account.errors.details[:company]
  ensure
    ActiveRecord::Base.belongs_to_required_by_default = original_value
  end

  def test_required_belongs_to_config
    original_value = ActiveRecord::Base.belongs_to_required_by_default
    ActiveRecord::Base.belongs_to_required_by_default = true

    model = Class.new(ActiveRecord::Base) do
      self.table_name = "accounts"
      def self.name; "Temp"; end
      belongs_to :company
    end

    account = model.new
    assert_not_predicate account, :valid?
    assert_equal [{ error: :blank }], account.errors.details[:company]
  ensure
    ActiveRecord::Base.belongs_to_required_by_default = original_value
  end

  def test_default
    david = developers(:david)
    jamis = developers(:jamis)

    model = Class.new(ActiveRecord::Base) do
      self.table_name = "ships"
      def self.name; "Temp"; end
      belongs_to :developer, default: -> { david }
    end

    ship = model.create!
    assert_equal david, ship.developer

    ship = model.create!(developer: jamis)
    assert_equal jamis, ship.developer

    ship.update!(developer: nil)
    assert_equal david, ship.developer
  end

  def test_default_with_lambda
    model = Class.new(ActiveRecord::Base) do
      self.table_name = "ships"
      def self.name; "Temp"; end
      belongs_to :developer, default: -> { default_developer }

      def default_developer
        Developer.first
      end
    end

    ship = model.create!
    assert_equal developers(:david), ship.developer

    ship = model.create!(developer: developers(:jamis))
    assert_equal developers(:jamis), ship.developer
  end

  def test_default_scope_on_relations_is_not_cached
    counter = 0

    comments = Class.new(ActiveRecord::Base) {
      self.table_name = "comments"
      self.inheritance_column = "not_there"

      posts = Class.new(ActiveRecord::Base) {
        self.table_name = "posts"
        self.inheritance_column = "not_there"

        default_scope -> {
          counter += 1
          where("id = :inc", inc: counter)
        }

        has_many :comments, anonymous_class: comments
      }
      belongs_to :post, anonymous_class: posts, inverse_of: false
    }

    assert_equal 0, counter
    comment = comments.first
    assert_equal 0, counter
    sql = capture_sql { comment.post }
    comment.reload
    assert_not_equal sql, capture_sql { comment.post }
  end

  def test_proxy_assignment
    account = Account.find(1)
    assert_nothing_raised { account.firm = account.firm }
  end

  def test_type_mismatch
    assert_raise(ActiveRecord::AssociationTypeMismatch) { Account.find(1).firm = 1 }
    assert_raise(ActiveRecord::AssociationTypeMismatch) { Account.find(1).firm = Project.find(1) }
  end

  def test_raises_type_mismatch_with_namespaced_class
    assert_nil defined?(Region), "This test requires that there is no top-level Region class"

    ActiveRecord::Base.connection.instance_eval do
      create_table(:admin_regions) { |t| t.string :name }
      add_column :admin_users, :region_id, :integer
    end
    Admin.const_set "RegionalUser", Class.new(Admin::User) { belongs_to(:region) }
    Admin.const_set "Region", Class.new(ActiveRecord::Base)

    e = assert_raise(ActiveRecord::AssociationTypeMismatch) {
      Admin::RegionalUser.new(region: "wrong value")
    }
    assert_match(/^Region\([^)]+\) expected, got "wrong value" which is an instance of String\([^)]+\)$/, e.message)
  ensure
    Admin.send :remove_const, "Region" if Admin.const_defined?("Region")
    Admin.send :remove_const, "RegionalUser" if Admin.const_defined?("RegionalUser")

    ActiveRecord::Base.connection.instance_eval do
      remove_column :admin_users, :region_id if column_exists?(:admin_users, :region_id)
      drop_table :admin_regions, if_exists: true
    end

    Admin::User.reset_column_information
  end

  def test_natural_assignment
    apple = Firm.create("name" => "Apple")
    citibank = Account.create("credit_limit" => 10)
    citibank.firm = apple
    assert_equal apple.id, citibank.firm_id
  end

  def test_id_assignment
    apple = Firm.create("name" => "Apple")
    citibank = Account.create("credit_limit" => 10)
    citibank.firm_id = apple
    assert_nil citibank.firm_id
  end

  def test_natural_assignment_with_primary_key
    apple = Firm.create("name" => "Apple")
    citibank = Client.create("name" => "Primary key client")
    citibank.firm_with_primary_key = apple
    assert_equal apple.name, citibank.firm_name
  end

  def test_eager_loading_with_primary_key
    Firm.create("name" => "Apple")
    Client.create("name" => "Citibank", :firm_name => "Apple")
    citibank_result = Client.all.merge!(where: { name: "Citibank" }, includes: :firm_with_primary_key).first
    assert_predicate citibank_result.association(:firm_with_primary_key), :loaded?
  end

  def test_eager_loading_with_primary_key_as_symbol
    Firm.create("name" => "Apple")
    Client.create("name" => "Citibank", :firm_name => "Apple")
    citibank_result = Client.all.merge!(where: { name: "Citibank" }, includes: :firm_with_primary_key_symbols).first
    assert_predicate citibank_result.association(:firm_with_primary_key_symbols), :loaded?
  end

  def test_creating_the_belonging_object
    citibank = Account.create("credit_limit" => 10)
    apple    = citibank.create_firm("name" => "Apple")
    assert_equal apple, citibank.firm
    citibank.save
    citibank.reload
    assert_equal apple, citibank.firm
  end

  def test_creating_the_belonging_object_with_primary_key
    client = Client.create(name: "Primary key client")
    apple  = client.create_firm_with_primary_key("name" => "Apple")
    assert_equal apple, client.firm_with_primary_key
    client.save
    client.reload
    assert_equal apple, client.firm_with_primary_key
  end

  def test_building_the_belonging_object
    citibank = Account.create("credit_limit" => 10)
    apple    = citibank.build_firm("name" => "Apple")
    citibank.save
    assert_equal apple.id, citibank.firm_id
  end

  def test_building_the_belonging_object_with_implicit_sti_base_class
    account = Account.new
    company = account.build_firm
    assert_kind_of Company, company, "Expected #{company.class} to be a Company"
  end

  def test_building_the_belonging_object_with_explicit_sti_base_class
    account = Account.new
    company = account.build_firm(type: "Company")
    assert_kind_of Company, company, "Expected #{company.class} to be a Company"
  end

  def test_building_the_belonging_object_with_sti_subclass
    account = Account.new
    company = account.build_firm(type: "Firm")
    assert_kind_of Firm, company, "Expected #{company.class} to be a Firm"
  end

  def test_building_the_belonging_object_with_an_invalid_type
    account = Account.new
    assert_raise(ActiveRecord::SubclassNotFound) { account.build_firm(type: "InvalidType") }
  end

  def test_building_the_belonging_object_with_an_unrelated_type
    account = Account.new
    assert_raise(ActiveRecord::SubclassNotFound) { account.build_firm(type: "Account") }
  end

  def test_building_the_belonging_object_with_primary_key
    client = Client.create(name: "Primary key client")
    apple  = client.build_firm_with_primary_key("name" => "Apple")
    client.save
    assert_equal apple.name, client.firm_name
  end

  def test_create!
    client  = Client.create!(name: "Jimmy")
    account = client.create_account!(credit_limit: 10)
    assert_equal account, client.account
    assert_predicate account, :persisted?
    client.save
    client.reload
    assert_equal account, client.account
  end

  def test_failing_create!
    client = Client.create!(name: "Jimmy")
    assert_raise(ActiveRecord::RecordInvalid) { client.create_account! }
    assert_not_nil client.account
    assert_predicate client.account, :new_record?
  end

  def test_reloading_the_belonging_object
    odegy_account = accounts(:odegy_account)

    assert_equal "Odegy", odegy_account.firm.name
    Company.where(id: odegy_account.firm_id).update_all(name: "ODEGY")
    assert_equal "Odegy", odegy_account.firm.name

    assert_equal "ODEGY", odegy_account.reload_firm.name
  end

  def test_natural_assignment_to_nil
    client = Client.find(3)
    client.firm = nil
    client.save
    client.association(:firm).reload
    assert_nil client.firm
    assert_nil client.client_of
  end

  def test_natural_assignment_to_nil_with_primary_key
    client = Client.create(name: "Primary key client", firm_name: companies(:first_firm).name)
    client.firm_with_primary_key = nil
    client.save
    client.association(:firm_with_primary_key).reload
    assert_nil client.firm_with_primary_key
    assert_nil client.client_of
  end

  def test_with_different_class_name
    assert_equal Company.find(1).name, Company.find(3).firm_with_other_name.name
    assert_not_nil Company.find(3).firm_with_other_name, "Microsoft should have a firm"
  end

  def test_with_condition
    assert_equal Company.find(1).name, Company.find(3).firm_with_condition.name
    assert_not_nil Company.find(3).firm_with_condition, "Microsoft should have a firm"
  end

  def test_polymorphic_association_class
    sponsor = Sponsor.new
    assert_nil sponsor.association(:sponsorable).send(:klass)
    sponsor.association(:sponsorable).reload
    assert_nil sponsor.sponsorable

    sponsor.sponsorable_type = "" # the column doesn't have to be declared NOT NULL
    assert_nil sponsor.association(:sponsorable).send(:klass)
    sponsor.association(:sponsorable).reload
    assert_nil sponsor.sponsorable

    sponsor.sponsorable = Member.new name: "Bert"
    assert_equal Member, sponsor.association(:sponsorable).send(:klass)
  end

  def test_with_polymorphic_and_condition
    sponsor = Sponsor.create
    member = Member.create name: "Bert"
    sponsor.sponsorable = member

    assert_equal member, sponsor.sponsorable
    assert_nil sponsor.sponsorable_with_conditions
  end

  def test_with_select
    assert_equal 1, Company.find(2).firm_with_select.attributes.size
    assert_equal 1, Company.all.merge!(includes: :firm_with_select).find(2).firm_with_select.attributes.size
  end

  def test_belongs_to_without_counter_cache_option
    # Ship has a conventionally named `treasures_count` column, but the counter_cache
    # option is not given on the association.
    ship = Ship.create(name: "Countless")

    assert_no_difference lambda { ship.reload.treasures_count }, "treasures_count should not be changed unless counter_cache is given on the relation" do
      treasure = Treasure.new(name: "Gold", ship: ship)
      treasure.save
    end

    assert_no_difference lambda { ship.reload.treasures_count }, "treasures_count should not be changed unless counter_cache is given on the relation" do
      treasure = ship.treasures.first
      treasure.destroy
    end
  end

  def test_belongs_to_counter
    debate = Topic.create("title" => "debate")
    assert_equal 0, debate.read_attribute("replies_count"), "No replies yet"

    trash = debate.replies.create("title" => "blah!", "content" => "world around!")
    assert_equal 1, Topic.find(debate.id).read_attribute("replies_count"), "First reply created"

    trash.destroy
    assert_equal 0, Topic.find(debate.id).read_attribute("replies_count"), "First reply deleted"
  end

  def test_belongs_to_counter_with_assigning_nil
    post = Post.find(1)
    comment = Comment.find(1)

    assert_equal post.id, comment.post_id
    assert_equal 2, Post.find(post.id).comments.size

    comment.post = nil

    assert_equal 1, Post.find(post.id).comments.size
  end

  def test_belongs_to_with_primary_key_counter
    debate  = Topic.create("title" => "debate")
    debate2 = Topic.create("title" => "debate2")
    reply   = Reply.create("title" => "blah!", "content" => "world around!", "parent_title" => "debate")

    assert_equal 1, debate.reload.replies_count
    assert_equal 0, debate2.reload.replies_count

    reply.topic_with_primary_key = debate2

    assert_equal 0, debate.reload.replies_count
    assert_equal 1, debate2.reload.replies_count

    reply.topic_with_primary_key = nil

    assert_equal 0, debate.reload.replies_count
    assert_equal 0, debate2.reload.replies_count
  end

  def test_belongs_to_counter_with_reassigning
    topic1 = Topic.create("title" => "t1")
    topic2 = Topic.create("title" => "t2")
    reply1 = Reply.new("title" => "r1", "content" => "r1")
    reply1.topic = topic1

    assert reply1.save
    assert_equal 1, Topic.find(topic1.id).replies.size
    assert_equal 0, Topic.find(topic2.id).replies.size

    reply1.topic = Topic.find(topic2.id)

    assert_no_queries do
      reply1.topic = topic2
    end

    assert reply1.save
    assert_equal 0, Topic.find(topic1.id).replies.size
    assert_equal 1, Topic.find(topic2.id).replies.size

    reply1.topic = nil

    assert_equal 0, Topic.find(topic1.id).replies.size
    assert_equal 0, Topic.find(topic2.id).replies.size

    reply1.topic = topic1

    assert_equal 1, Topic.find(topic1.id).replies.size
    assert_equal 0, Topic.find(topic2.id).replies.size

    reply1.destroy

    assert_equal 0, Topic.find(topic1.id).replies.size
    assert_equal 0, Topic.find(topic2.id).replies.size
  end

  def test_belongs_to_reassign_with_namespaced_models_and_counters
    topic1 = Web::Topic.create("title" => "t1")
    topic2 = Web::Topic.create("title" => "t2")
    reply1 = Web::Reply.new("title" => "r1", "content" => "r1")
    reply1.topic = topic1

    assert reply1.save
    assert_equal 1, Web::Topic.find(topic1.id).replies.size
    assert_equal 0, Web::Topic.find(topic2.id).replies.size

    reply1.topic = Web::Topic.find(topic2.id)

    assert reply1.save
    assert_equal 0, Web::Topic.find(topic1.id).replies.size
    assert_equal 1, Web::Topic.find(topic2.id).replies.size
  end

  def test_belongs_to_counter_after_save
    topic = Topic.create!(title: "monday night")
    topic.replies.create!(title: "re: monday night", content: "football")
    assert_equal 1, Topic.find(topic.id)[:replies_count]

    topic.save!
    assert_equal 1, Topic.find(topic.id)[:replies_count]
  end

  def test_belongs_to_with_touch_option_on_touch
    line_item = LineItem.create!
    Invoice.create!(line_items: [line_item])

    assert_queries(1) { line_item.touch }
  end

  def test_belongs_to_with_touch_on_multiple_records
    line_item = LineItem.create!(amount: 1)
    line_item2 = LineItem.create!(amount: 2)
    Invoice.create!(line_items: [line_item, line_item2])

    assert_queries(1) do
      LineItem.transaction do
        line_item.touch
        line_item2.touch
      end
    end

    assert_queries(2) do
      line_item.touch
      line_item2.touch
    end
  end

  def test_belongs_to_with_touch_option_on_touch_without_updated_at_attributes
    assert_not LineItem.column_names.include?("updated_at")

    line_item = LineItem.create!
    invoice = Invoice.create!(line_items: [line_item])
    initial = invoice.updated_at
    travel(1.second) do
      line_item.touch
    end

    assert_not_equal initial, invoice.reload.updated_at
  end

  def test_belongs_to_with_touch_option_on_touch_and_removed_parent
    line_item = LineItem.create!
    Invoice.create!(line_items: [line_item])

    line_item.invoice = nil

    assert_queries(2) { line_item.touch }
  end

  def test_belongs_to_with_touch_option_on_update
    line_item = LineItem.create!
    Invoice.create!(line_items: [line_item])

    assert_queries(2) { line_item.update amount: 10 }
  end

  def test_belongs_to_with_touch_option_on_empty_update
    line_item = LineItem.create!
    Invoice.create!(line_items: [line_item])

    assert_queries(0) { line_item.save }
  end

  def test_belongs_to_with_touch_option_on_destroy
    line_item = LineItem.create!
    Invoice.create!(line_items: [line_item])

    assert_queries(2) { line_item.destroy }
  end

  def test_belongs_to_with_touch_option_on_destroy_with_destroyed_parent
    line_item = LineItem.create!
    invoice   = Invoice.create!(line_items: [line_item])
    invoice.destroy

    assert_queries(1) { line_item.destroy }
  end

  def test_belongs_to_with_touch_option_on_touch_and_reassigned_parent
    line_item = LineItem.create!
    Invoice.create!(line_items: [line_item])

    line_item.invoice = Invoice.create!

    assert_queries(3) { line_item.touch }
  end

  def test_belongs_to_counter_after_update
    topic = Topic.create!(title: "37s")
    topic.replies.create!(title: "re: 37s", content: "rails")
    assert_equal 1, Topic.find(topic.id)[:replies_count]

    topic.update(title: "37signals")
    assert_equal 1, Topic.find(topic.id)[:replies_count]
  end

  def test_belongs_to_counter_when_update_columns
    topic = Topic.create!(title: "37s")
    topic.replies.create!(title: "re: 37s", content: "rails")
    assert_equal 1, Topic.find(topic.id)[:replies_count]

    topic.update_columns(content: "rails is wonderful")
    assert_equal 1, Topic.find(topic.id)[:replies_count]
  end

  def test_assignment_before_child_saved
    final_cut = Client.new("name" => "Final Cut")
    firm = Firm.find(1)
    final_cut.firm = firm
    assert_not_predicate final_cut, :persisted?
    assert final_cut.save
    assert_predicate final_cut, :persisted?
    assert_predicate firm, :persisted?
    assert_equal firm, final_cut.firm
    final_cut.association(:firm).reload
    assert_equal firm, final_cut.firm
  end

  def test_assignment_before_child_saved_with_primary_key
    final_cut = Client.new("name" => "Final Cut")
    firm = Firm.find(1)
    final_cut.firm_with_primary_key = firm
    assert_not_predicate final_cut, :persisted?
    assert final_cut.save
    assert_predicate final_cut, :persisted?
    assert_predicate firm, :persisted?
    assert_equal firm, final_cut.firm_with_primary_key
    final_cut.association(:firm_with_primary_key).reload
    assert_equal firm, final_cut.firm_with_primary_key
  end

  def test_new_record_with_foreign_key_but_no_object
    client = Client.new("firm_id" => 1)
    assert_equal Firm.first, client.firm_with_basic_id
  end

  def test_setting_foreign_key_after_nil_target_loaded
    client = Client.new
    client.firm_with_basic_id
    client.firm_id = 1

    assert_equal companies(:first_firm), client.firm_with_basic_id
  end

  def test_polymorphic_setting_foreign_key_after_nil_target_loaded
    sponsor = Sponsor.new
    sponsor.sponsorable
    sponsor.sponsorable_id = 1
    sponsor.sponsorable_type = "Member"

    assert_equal members(:groucho), sponsor.sponsorable
  end

  def test_dont_find_target_when_foreign_key_is_null
    tagging = taggings(:thinking_general)
    assert_queries(0) { tagging.super_tag }
  end

  def test_dont_find_target_when_saving_foreign_key_after_stale_association_loaded
    client = Client.create!(name: "Test client", firm_with_basic_id: Firm.find(1))
    client.firm_id = Firm.create!(name: "Test firm").id
    assert_queries(1) { client.save! }
  end

  def test_field_name_same_as_foreign_key
    computer = Computer.find(1)
    assert_not_nil computer.developer, ":foreign key == attribute didn't lock up" # '
  end

  def test_counter_cache
    topic = Topic.create title: "Zoom-zoom-zoom"
    assert_equal 0, topic[:replies_count]

    reply = Reply.create(title: "re: zoom", content: "speedy quick!")
    reply.topic = topic

    assert_equal 1, topic.reload[:replies_count]
    assert_equal 1, topic.replies.size

    topic[:replies_count] = 15
    assert_equal 15, topic.replies.size
  end

  def test_counter_cache_double_destroy
    topic = Topic.create title: "Zoom-zoom-zoom"

    5.times do
      topic.replies.create(title: "re: zoom", content: "speedy quick!")
    end

    assert_equal 5, topic.reload[:replies_count]
    assert_equal 5, topic.replies.size

    reply = topic.replies.first

    reply.destroy
    assert_equal 4, topic.reload[:replies_count]

    reply.destroy
    assert_equal 4, topic.reload[:replies_count]
    assert_equal 4, topic.replies.size
  end

  def test_concurrent_counter_cache_double_destroy
    topic = Topic.create title: "Zoom-zoom-zoom"

    5.times do
      topic.replies.create(title: "re: zoom", content: "speedy quick!")
    end

    assert_equal 5, topic.reload[:replies_count]
    assert_equal 5, topic.replies.size

    reply = topic.replies.first
    reply_clone = Reply.find(reply.id)

    reply.destroy
    assert_equal 4, topic.reload[:replies_count]

    reply_clone.destroy
    assert_equal 4, topic.reload[:replies_count]
    assert_equal 4, topic.replies.size
  end

  def test_custom_counter_cache
    reply = Reply.create(title: "re: zoom", content: "speedy quick!")
    assert_equal 0, reply[:replies_count]

    silly = SillyReply.create(title: "gaga", content: "boo-boo")
    silly.reply = reply

    assert_equal 1, reply.reload[:replies_count]
    assert_equal 1, reply.replies.size

    reply[:replies_count] = 17
    assert_equal 17, reply.replies.size
  end

  def test_replace_counter_cache
    topic = Topic.create(title: "Zoom-zoom-zoom")
    reply = Reply.create(title: "re: zoom", content: "speedy quick!")

    reply.topic = topic
    reply.save
    topic.reload

    assert_equal 1, topic.replies_count
  end

  def test_association_assignment_sticks
    post = Post.first

    author1, author2 = Author.all.merge!(limit: 2).to_a
    assert_not_nil author1
    assert_not_nil author2

    # make sure the association is loaded
    post.author

    # set the association by id, directly
    post.author_id = author2.id

    # save and reload
    post.save!
    post.reload

    # the author id of the post should be the id we set
    assert_equal post.author_id, author2.id
  end

  def test_cant_save_readonly_association
    assert_raise(ActiveRecord::ReadOnlyRecord) { companies(:first_client).readonly_firm.save! }
    assert_predicate companies(:first_client).readonly_firm, :readonly?
  end

  def test_polymorphic_assignment_foreign_key_type_string
    comment = Comment.first
    comment.author   = Author.first
    comment.resource = Member.first
    comment.save

    assert_equal Comment.all.to_a,
      Comment.includes(:author).to_a

    assert_equal Comment.all.to_a,
      Comment.includes(:resource).to_a
  end

  def test_polymorphic_assignment_foreign_type_field_updating
    # should update when assigning a saved record
    sponsor = Sponsor.new
    member = Member.create
    sponsor.sponsorable = member
    assert_equal "Member", sponsor.sponsorable_type

    # should update when assigning a new record
    sponsor = Sponsor.new
    member = Member.new
    sponsor.sponsorable = member
    assert_equal "Member", sponsor.sponsorable_type
  end

  def test_polymorphic_assignment_with_primary_key_foreign_type_field_updating
    # should update when assigning a saved record
    essay = Essay.new
    writer = Author.create(name: "David")
    essay.writer = writer
    assert_equal "Author", essay.writer_type

    # should update when assigning a new record
    essay = Essay.new
    writer = Author.new
    essay.writer = writer
    assert_equal "Author", essay.writer_type
  end

  def test_polymorphic_assignment_updates_foreign_id_field_for_new_and_saved_records
    sponsor = Sponsor.new
    saved_member = Member.create
    new_member = Member.new

    sponsor.sponsorable = saved_member
    assert_equal saved_member.id, sponsor.sponsorable_id

    sponsor.sponsorable = new_member
    assert_nil sponsor.sponsorable_id
  end

  def test_assignment_updates_foreign_id_field_for_new_and_saved_records
    client = Client.new
    saved_firm = Firm.create name: "Saved"
    new_firm = Firm.new

    client.firm = saved_firm
    assert_equal saved_firm.id, client.client_of

    client.firm = new_firm
    assert_nil client.client_of
  end

  def test_polymorphic_assignment_with_primary_key_updates_foreign_id_field_for_new_and_saved_records
    essay = Essay.new
    saved_writer = Author.create(name: "David")
    new_writer = Author.new

    essay.writer = saved_writer
    assert_equal saved_writer.name, essay.writer_id

    essay.writer = new_writer
    assert_nil essay.writer_id
  end

  def test_polymorphic_assignment_with_nil
    essay = Essay.new
    assert_nil essay.writer_id
    assert_nil essay.writer_type

    essay.writer_id = 1
    essay.writer_type = "Author"

    essay.writer = nil
    assert_nil essay.writer_id
    assert_nil essay.writer_type
  end

  def test_belongs_to_proxy_should_not_respond_to_private_methods
    assert_raise(NoMethodError) { companies(:first_firm).private_method }
    assert_raise(NoMethodError) { companies(:second_client).firm.private_method }
  end

  def test_belongs_to_proxy_should_respond_to_private_methods_via_send
    companies(:first_firm).send(:private_method)
    companies(:second_client).firm.send(:private_method)
  end

  def test_save_of_record_with_loaded_belongs_to
    @account = companies(:first_firm).account

    assert_nothing_raised do
      Account.find(@account.id).save!
      Account.all.merge!(includes: :firm).find(@account.id).save!
    end

    @account.firm.delete

    assert_nothing_raised do
      Account.find(@account.id).save!
      Account.all.merge!(includes: :firm).find(@account.id).save!
    end
  end

  def test_dependent_delete_and_destroy_with_belongs_to
    AuthorAddress.destroyed_author_address_ids.clear

    author_address = author_addresses(:david_address)
    author_address_extra = author_addresses(:david_address_extra)
    assert_equal [], AuthorAddress.destroyed_author_address_ids

    assert_difference "AuthorAddress.count", -2 do
      authors(:david).destroy
    end

    assert_equal [], AuthorAddress.where(id: [author_address.id, author_address_extra.id])
    assert_equal [author_address.id], AuthorAddress.destroyed_author_address_ids
  end

  def test_belongs_to_invalid_dependent_option_raises_exception
    error = assert_raise ArgumentError do
      Class.new(Author).belongs_to :special_author_address, dependent: :nullify
    end
    assert_equal error.message, "The :dependent option must be one of [:destroy, :delete], but is :nullify"
  end

  class DestroyableBook < ActiveRecord::Base
    self.table_name = "books"
    belongs_to :author, class_name: "UndestroyableAuthor", dependent: :destroy
  end

  class UndestroyableAuthor < ActiveRecord::Base
    self.table_name = "authors"
    has_one :book, class_name: "DestroyableBook", foreign_key: "author_id"
    before_destroy :dont

    def dont
      throw(:abort)
    end
  end

  def test_dependency_should_halt_parent_destruction
    author = UndestroyableAuthor.create!(name: "Test")
    book = DestroyableBook.create!(author: author)

    assert_no_difference ["UndestroyableAuthor.count", "DestroyableBook.count"] do
      assert_not book.destroy
    end
  end

  def test_attributes_are_being_set_when_initialized_from_belongs_to_association_with_where_clause
    new_firm = accounts(:signals37).build_firm(name: "Apple")
    assert_equal new_firm.name, "Apple"
  end

  def test_attributes_are_set_without_error_when_initialized_from_belongs_to_association_with_array_in_where_clause
    new_account = Account.where(credit_limit: [ 50, 60 ]).new
    assert_nil new_account.credit_limit
  end

  def test_reassigning_the_parent_id_updates_the_object
    client = companies(:second_client)

    client.firm
    client.firm_with_condition
    firm_proxy                = client.send(:association_instance_get, :firm)
    firm_with_condition_proxy = client.send(:association_instance_get, :firm_with_condition)

    assert_not_predicate firm_proxy, :stale_target?
    assert_not_predicate firm_with_condition_proxy, :stale_target?
    assert_equal companies(:first_firm), client.firm
    assert_equal companies(:first_firm), client.firm_with_condition

    client.client_of = companies(:another_firm).id

    assert_predicate firm_proxy, :stale_target?
    assert_predicate firm_with_condition_proxy, :stale_target?
    assert_equal companies(:another_firm), client.firm
    assert_equal companies(:another_firm), client.firm_with_condition
  end

  def test_polymorphic_reassignment_of_associated_id_updates_the_object
    sponsor = sponsors(:moustache_club_sponsor_for_groucho)

    sponsor.sponsorable
    proxy = sponsor.send(:association_instance_get, :sponsorable)

    assert_not_predicate proxy, :stale_target?
    assert_equal members(:groucho), sponsor.sponsorable

    sponsor.sponsorable_id = members(:some_other_guy).id

    assert_predicate proxy, :stale_target?
    assert_equal members(:some_other_guy), sponsor.sponsorable
  end

  def test_polymorphic_reassignment_of_associated_type_updates_the_object
    sponsor = sponsors(:moustache_club_sponsor_for_groucho)

    sponsor.sponsorable
    proxy = sponsor.send(:association_instance_get, :sponsorable)

    assert_not_predicate proxy, :stale_target?
    assert_equal members(:groucho), sponsor.sponsorable

    sponsor.sponsorable_type = "Firm"

    assert_predicate proxy, :stale_target?
    assert_equal companies(:first_firm), sponsor.sponsorable
  end

  def test_reloading_association_with_key_change
    client = companies(:second_client)
    firm = client.association(:firm)

    client.firm = companies(:another_firm)
    firm.reload
    assert_equal companies(:another_firm), firm.target

    client.client_of = companies(:first_firm).id
    firm.reload
    assert_equal companies(:first_firm), firm.target
  end

  def test_polymorphic_counter_cache
    tagging = taggings(:welcome_general)
    post    = posts(:welcome)
    comment = comments(:greetings)

    assert_difference lambda { post.reload.tags_count }, -1 do
      assert_difference "comment.reload.tags_count", +1 do
        tagging.taggable = comment
      end
    end
  end

  def test_polymorphic_with_custom_foreign_type
    sponsor = sponsors(:moustache_club_sponsor_for_groucho)
    groucho = members(:groucho)
    other   = members(:some_other_guy)

    assert_equal groucho, sponsor.sponsorable
    assert_equal groucho, sponsor.thing

    sponsor.thing = other

    assert_equal other, sponsor.sponsorable
    assert_equal other, sponsor.thing

    sponsor.sponsorable = groucho

    assert_equal groucho, sponsor.sponsorable
    assert_equal groucho, sponsor.thing
  end

  def test_build_with_conditions
    client = companies(:second_client)
    firm   = client.build_bob_firm

    assert_equal "Bob", firm.name
  end

  def test_create_with_conditions
    client = companies(:second_client)
    firm   = client.create_bob_firm

    assert_equal "Bob", firm.name
  end

  def test_create_bang_with_conditions
    client = companies(:second_client)
    firm   = client.create_bob_firm!

    assert_equal "Bob", firm.name
  end

  def test_build_with_block
    client = Client.create(name: "Client Company")

    firm = client.build_firm { |f| f.name = "Agency Company" }
    assert_equal "Agency Company", firm.name
  end

  def test_create_with_block
    client = Client.create(name: "Client Company")

    firm = client.create_firm { |f| f.name = "Agency Company" }
    assert_equal "Agency Company", firm.name
  end

  def test_create_bang_with_block
    client = Client.create(name: "Client Company")

    firm = client.create_firm! { |f| f.name = "Agency Company" }
    assert_equal "Agency Company", firm.name
  end

  def test_should_set_foreign_key_on_create_association
    client = Client.create! name: "fuu"

    firm = client.create_firm name: "baa"
    assert_equal firm.id, client.client_of
  end

  def test_should_set_foreign_key_on_create_association!
    client = Client.create! name: "fuu"

    firm = client.create_firm! name: "baa"
    assert_equal firm.id, client.client_of
  end

  def test_self_referential_belongs_to_with_counter_cache_assigning_nil
    comment = Comment.create! post: posts(:thinking), body: "fuu"
    comment.parent = nil
    comment.save!

    assert_nil comment.reload.parent
    assert_equal 0, comments(:greetings).reload.children_count
  end

  def test_belongs_to_with_id_assigning
    post = posts(:welcome)
    comment = Comment.create! body: "foo", post: post
    parent = comments(:greetings)
    assert_equal 0, parent.reload.children_count
    comment.parent_id = parent.id

    comment.save!
    assert_equal 1, parent.reload.children_count
  end

  def test_belongs_to_with_out_of_range_value_assigning
    model = Class.new(Comment) do
      def self.name; "Temp"; end
      validates :post, presence: true
    end

    comment = model.new
    comment.post_id = 9223372036854775808 # out of range in the bigint

    assert_nil comment.post
    assert_not_predicate comment, :valid?
    assert_equal [{ error: :blank }], comment.errors.details[:post]
  end

  def test_polymorphic_with_custom_primary_key
    toy = Toy.create!
    sponsor = Sponsor.create!(sponsorable: toy)

    assert_equal toy, sponsor.reload.sponsorable
  end

  test "stale tracking doesn't care about the type" do
    apple = Firm.create("name" => "Apple")
    citibank = Account.create("credit_limit" => 10)

    citibank.firm_id = apple.id
    citibank.firm # load it

    citibank.firm_id = apple.id.to_s

    assert_not_predicate citibank.association(:firm), :stale_target?
  end

  def test_reflect_the_most_recent_change
    author1, author2 = Author.limit(2)
    post = Post.new(title: "foo", body: "bar")

    post.author    = author1
    post.author_id = author2.id

    assert post.save
    assert_equal post.author_id, author2.id
  end

  test "dangerous association name raises ArgumentError" do
    [:errors, "errors", :save, "save"].each do |name|
      assert_raises(ArgumentError, "Association #{name} should not be allowed") do
        Class.new(ActiveRecord::Base) do
          belongs_to name
        end
      end
    end
  end

  test "belongs_to works with model called Record" do
    record = Record.create!
    Column.create! record: record
    assert_equal 1, Column.count
  end

  def test_multiple_counter_cache_with_after_create_update
    post = posts(:welcome)
    parent = comments(:greetings)

    assert_difference "parent.reload.children_count", +1 do
      assert_difference "post.reload.comments_count", +1 do
        CommentWithAfterCreateUpdate.create(body: "foo", post: post, parent: parent)
      end
    end
  end
end

class BelongsToWithForeignKeyTest < ActiveRecord::TestCase
  fixtures :authors, :author_addresses

  def test_destroy_linked_models
    address = AuthorAddress.create!
    author = Author.create! name: "Author", author_address_id: address.id

    author.destroy!
  end
end


text:
#pragma once
#include <logger.hpp>

// Include most of the C stdlib for convenience
#include <cstdlib>
#include <cstdio>
#include <cstdint>
#include <cstdarg>
#include <climits>
#include <cmath>
#include <cstring>
#include <cassert>

// Include some of the C++ stdlib for convenience
#include <string>
#include <stdexcept>

namespace rack {

/** Deprecation notice for functions
E.g.

	DEPRECATED void foo();
*/
#if defined(__GNUC__) || defined(__clang__)
	#define DEPRECATED __attribute__ ((deprecated))
#elif defined(_MSC_VER)
	#define DEPRECATED __declspec(deprecated)
#endif

/** Concatenates two literals or two macros
Example:

	#define COUNT 42
	CONCAT(myVariable, COUNT)

expands to

	myVariable42
*/
#define CONCAT_LITERAL(x, y) x ## y
#define CONCAT(x, y) CONCAT_LITERAL(x, y)

/** Surrounds raw text with quotes
Example:

	#define NAME "world"
	printf("Hello " TOSTRING(NAME))

expands to

	printf("Hello " "world")

and of course the C++ lexer/parser then concatenates the string literals.
*/
#define TOSTRING_LITERAL(x) #x
#define TOSTRING(x) TOSTRING_LITERAL(x)

/** Produces the length of a static array in number of elements */
#define LENGTHOF(arr) (sizeof(arr) / sizeof((arr)[0]))

/** Reserve space for `count` enums starting with `name`.
Example:

	enum Foo {
		ENUMS(BAR, 14),
		BAZ
	};

`BAR + 0` to `BAR + 13` is reserved. `BAZ` has a value of 14.
*/
#define ENUMS(name, count) name, name ## _LAST = name + (count) - 1

/** References binary files compiled into the program.
For example, to include a file "Test.dat" directly into your program binary, add

	BINARIES += Test.dat

to your Makefile and declare

	BINARY(Test_dat);

at the root of a .c or .cpp source file. Note that special characters are replaced with "_". Then use

	BINARY_START(Test_dat)
	BINARY_END(Test_dat)

to reference the data beginning and end as a void* array, and

	BINARY_SIZE(Test_dat)

to get its size in bytes.
*/
#if defined ARCH_MAC
	// Use output from `xxd -i`
	#define BINARY(sym) extern unsigned char sym[]; extern unsigned int sym##_len
	#define BINARY_START(sym) ((const void*) sym)
	#define BINARY_END(sym) ((const void*) sym + sym##_len)
	#define BINARY_SIZE(sym) (sym##_len)
#else
	#define BINARY(sym) extern char _binary_##sym##_start, _binary_##sym##_end, _binary_##sym##_size
	#define BINARY_START(sym) ((const void*) &_binary_##sym##_start)
	#define BINARY_END(sym) ((const void*) &_binary_##sym##_end)
	// The symbol "_binary_##sym##_size" doesn't seem to be valid after a plugin is dynamically loaded, so simply take the difference between the two addresses.
	#define BINARY_SIZE(sym) ((size_t) (&_binary_##sym##_end - &_binary_##sym##_start))
#endif

/** C#-style property constructor
Example:

	Foo *foo = construct<Foo>(&Foo::greeting, "Hello world", &Foo::legs, 2);
*/
template <typename T>
T* construct() {
	return new T;
}

template <typename T, typename F, typename V, typename... Args>
T* construct(F f, V v, Args... args) {
	T* o = construct<T>(args...);
	o->*f = v;
	return o;
}

/** Defers code until the scope is destructed
From http://www.gingerbill.org/article/defer-in-cpp.html
Example:

	file = fopen(...);
	DEFER({
		fclose(file);
	});
*/
template <typename F>
struct DeferWrapper {
	F f;
	DeferWrapper(F f) : f(f) {}
	~DeferWrapper() {
		f();
	}
};

template <typename F>
DeferWrapper<F> deferWrapper(F f) {
	return DeferWrapper<F>(f);
}

#define DEFER(code) auto CONCAT(_defer_, __COUNTER__) = rack::deferWrapper([&]() code)

/** An exception meant to be shown to the user */
struct UserException : std::runtime_error {
	UserException(const std::string& msg) : std::runtime_error(msg) {}
};

} // namespace rack


text:
var logging = require("./logging");
var config = require("../config");
var crc = require("crc").crc32;

var human_status = {
  "-2": "user error",        // e.g. invalid size
  "-1": "server error",      // e.g. mojang/network issues
  0: "none",                 // cached as null (user has no skin)
  1: "cached",               // found on disk
  2: "downloaded",           // profile downloaded, skin downloaded from mojang servers
  3: "checked",              // profile re-downloaded (was too old), has no skin or skin cached
  4: "server error;cached" // tried to check but ran into server error, using cached version
};

// print these, but without stacktrace
var silent_errors = ["ETIMEDOUT", "ESOCKETTIMEDOUT", "ECONNRESET", "EHOSTUNREACH", "ECONNREFUSED", "HTTPERROR", "RATELIMIT"];

// handles HTTP responses
// +request+ a http.IncomingMessage
// +response+ a http.ServerResponse
// +result+ an object with:
//  * status:   see human_status, required for images without err
//  * redirect: redirect URL
//  * body:     file or message, required unless redirect is present or status is < 0
//  * type:     a valid Content-Type for the body, defaults to "text/plain"
//  * hash:     image hash, required when body is an image
//  * err:      a possible Error
//  * code:     override HTTP response code when status is < 0
module.exports = function(request, response, result) {
  // These headers are the same for every response
  var headers = {
    "Content-Type": result.body && result.type || "text/plain",
    "Content-Length": Buffer.from(result.body || "").length,
    "Cache-Control": "max-age=" + config.caching.browser,
    "Response-Time": Date.now() - request.start,
    "X-Request-ID": request.id,
    "Access-Control-Allow-Origin": "*",
  };

  response.on("finish", function() {
    logging.log(request.id, request.method, request.url.href, response.statusCode, headers["Response-Time"] + "ms", "(" + (human_status[result.status] || "-") + ")");
  });

  response.on("error", function(err) {
    logging.error(request.id, err);
  });

  if (result.err) {
    var silent = silent_errors.indexOf(result.err.code) !== -1;
    if (result.err.stack && !silent) {
      logging.error(request.id, result.err.stack);
    } else if (silent) {
      logging.warn(request.id, result.err);
    } else {
      logging.error(request.id, result.err);
    }
    result.status = -1;
  }

  if (result.status !== undefined && result.status !== null) {
    headers["X-Storage-Type"] = human_status[result.status];
  }

  // use crc32 as a hash function for Etag
  var etag = "\"" + crc(result.body || "") + "\"";

  // handle etag caching
  var incoming_etag = request.headers["if-none-match"];
  // also respond with 304 on server error (use client's version)
  // don't respond with 304 when debugging is enabled
  if (incoming_etag && (incoming_etag === etag || result.status === -1 && !config.server.debug_enabled)) {
    response.writeHead(304, headers);
    response.end();
    return;
  }

  if (result.redirect) {
    headers.Location = result.redirect;
    response.writeHead(307, headers);
    response.end();
    return;
  }

  if (result.status === -2) {
    response.writeHead(result.code || 422, headers);
  } else if (result.status === -1) {
    // server errors shouldn't be cached
    headers["Cache-Control"] = "no-cache, max-age=0";
    if (result.body && result.hash && !result.hash.startsWith("mhf_")) {
      headers["Warning"] = '110 Crafatar "Response is Stale"'
      headers["Etag"] = etag;
      result.code = result.code || 200;
    }
    if (result.err && result.err.code === "ENOENT") {
      result.code = result.code || 500;
    }
    if (!result.code) {
      // Don't use 502 on Cloudflare
      // As they will show their own error page instead
      // https://support.cloudflare.com/hc/en-us/articles/200172706
      result.code = config.caching.cloudflare ? 500 : 502;
    }
    response.writeHead(result.code, headers);
  } else {
    if (result.body) {
      if (result.status === 4) {
        headers["Warning"] = '111 Crafatar "Revalidation Failed"'
      }
      headers["Etag"] = etag;
      response.writeHead(200, headers);
    } else {
      response.writeHead(404, headers);
    }
  }

  response.end(result.body);
};


text:
package org.liveontologies.puli.pinpointing.input.justifications;

import org.liveontologies.puli.pinpointing.BaseAxiomPinpointingTestInput;
import org.liveontologies.puli.pinpointing.input.Minimization;

public class MinimizationJustifications extends BaseAxiomPinpointingTestInput {

	@Override
	protected void build() {
		input(new Minimization());

		justification(1, 2);
	}

}


text:
let baiduMapIsLoaded = false;
export const baiduMapLoader = (): Promise<void> => {
  return new Promise<void>((resolve, reject) => {
    if (baiduMapIsLoaded) {
      resolve();
      return;
    }

    window['baiduMapLoaded'] = () => {
      baiduMapIsLoaded = true;
      resolve();
    };

    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'http://api.map.baidu.com/api?v=2.0&ak=DmMSdcEILbFTUHs4QvlcV2G0&callback=baiduMapLoaded';
    script.onerror = () => {
      document.body.removeChild(script);
      reject();
    };
    document.body.appendChild(script);
  });
};


text:
var http =          require('http');
var fs =            require('fs');
var download =      require('get-down');
var mkdirp =        require('mkdirp');
var ProgressBar =   require('progress');
var _ =             require('underscore');
var mongo =         require('mongodb');
var monk =          require('monk');
var rd =            require('readline');

var db = monk('localhost:27017/imdb');
var series = db.get('series');

var downloadURL = function(tmp, folder, name, extension, url)
{
    this.tmp = tmp + folder;
    this.name = name;
    this.file = name + extension;
    this.url = url + this.file;
};

var file = new downloadURL("tmp/", "release/", "release-dates.list", ".gz", "http://ftp.sunet.se/pub/tv+movies/imdb/");

var createFolder = function()
{
    console.log("Creating directory " + file.tmp + ", stand by...");
    mkdirp(file.tmp, function(err) {
        console.log("Checking for errors.");
        if (err)
        {
            console.log(err);
            return false;
        }

        console.log("No errors found, the directory " + file.tmpFo + " has now been created.");
        downloadFile();
    });
}

var downloadFile = function()
{
    // Download the file and save it locally.
    console.log("Downloading a file called " + file.name + " from the url " + file.url + " and saving it at " + file.tmp);
    var bar;
    var lastRec;
    download(file.url,
    {
        dest: file.tmp,
        extract: true
    }).on('progress', function(state)
    {
        console.log(state);
        if (state.retry) {
            var delay = Math.round(state.timeout / 1000) + 's';
            console.log('Download failed, retrying again in ' + delay);
        } else {
            if (!bar) {
                bar = new ProgressBar('  downloading [:bar] :percent :etas', {
                    complete: '=',
                    incomplete: ' ',
                    width: 20,
                    total: state.total
                });
                bar.tick(state.received);
            }
            bar.tick(state.received - lastRec);
            lastRec = state.received
        }
    }).on('error', function(err) {
        console.log(err);
    }).on('end', function(dest) {
        console.log("File has now been downloaded and extracted into the folder " + file.tmp);
        initilizeDB();
    });
}

var initilizeDB = function()
{
    console.log("Starting the process of inserting everything from the file to the db.");

    console.log("Starting to read the file " + file.name + "...");

    var i;
    var count = 0;
    var insertBar;
    var filestream = fs.createReadStream(file.tmp + file.name)
        .on('data', function(chunk)
            {
                for (i = 0; i < chunk.length; i++)
                {
                    if(chunk[i] == 10) count++;
                }
            })
        .on('end', function()
            {
                console.log("The file length is " + count);
                console.log("Starting to setup the insert progressbar!");
                insertBar = new ProgressBar('     reading [:bar] :percent :etas {:current/:total lines}', {
                    complete: '=',
                    incomplete: ' ',
                    width: 20,
                    total: count + 1
                });
                insertDB(insertBar);
            })

}

var insertDB = function(insertBar)
{
    var c = 0;
    var max = 1000;
    console.log("Starting to insert the data to the db.")

    var r = rd.createInterface({
        input: fs.createReadStream(file.tmp + file.name),
        output: process.stdout,
        terminal: false
    })
    r.on('line', function(data)
    {
        if (c >= max)
        {
            insertBar.tick(c);
            c = 0;
            max = Math.floor((Math.random() * 500) + 1);
        }
        else
        {
            c++;
        }
        var test = /(\".+\").+(\([0-9]+\)).+{(.+)?\(#([0-9]+)\.([0-9]+)\)}(.+)/g;
        var p = test.exec(data);

        if (p)
        {
            var title = p[1].replace(/\"/g, '');
            var year = p[2].replace('(', '').replace(')', '');
            var desc = p[3];
            var season = p[4];
            var episode = p[5];
            var date = p[6].replace(/\t/g, '');
            series.insert({
                title: title,
                year: year,
                desc: desc,
                season: season,
                episode: episode,
                date: date
            });
        }
    })

    r.on('close', function()
    {
        console.log("Closing the file");
        console.log("Closing the datbase");
        db.close();
    })
}

//createFolder();
initilizeDB();


text:
namespace SimpleInjector.Tests.Unit
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    /// <summary>Tests for full .NET framework version.</summary>
    public partial class RegisterBatchTestsFull
    {
        private static readonly IEnumerable<Assembly> Assemblies =
            new[] { typeof(RegisterBatchTestsFull).GetTypeInfo().Assembly };

        // This is the open generic interface that will be used as service type.
        public interface IServiceFull<TA, TB>
        {
        }

        [TestMethod]
        public void RegisterManyForOpenGeneric_IncludingInternalTypes_ReturnsExpectedType()
        {
            // Arrange
            var container = ContainerFactory.New();
            container.Register(typeof(IServiceFull<,>), Assemblies);

            // Act
            var impl = container.GetInstance<IServiceFull<decimal, decimal>>();

            // Assert
            AssertThat.IsInstanceOfType(typeof(InternalConcrete4Full), impl);
        }

        [TestMethod]
        public void RegisterManyForOpenGenericOverload1_AccessibilityOption_RegistersInternalTypes()
        {
            // Arrange
            var container = ContainerFactory.New();

            container.Register(typeof(IServiceFull<,>), Assemblies);

            // Act
            var impl = container.GetInstance<IServiceFull<decimal, decimal>>();

            // Assert
            AssertThat.IsInstanceOfType(typeof(InternalConcrete4Full), impl);
        }

        [TestMethod]
        public void RegisterManyForOpenGenericOverload2_AccessibilityOption_RegistersInternalTypes()
        {
            // Arrange
            var container = ContainerFactory.New();

            container.Register(typeof(IServiceFull<,>), Assemblies);

            // Act
            var impl = container.GetInstance<IServiceFull<decimal, decimal>>();

            // Assert
            AssertThat.IsInstanceOfType(typeof(InternalConcrete4Full), impl);
        }

        [TestMethod]
        public void RegisterManyForOpenGenericOverload5_AccessibilityOption_RegistersInternalTypes()
        {
            // Arrange
            var container = ContainerFactory.New();

            container.Register(typeof(IServiceFull<,>), Assemblies, Lifestyle.Transient);

            // Act
            var impl = container.GetInstance<IServiceFull<decimal, decimal>>();

            // Assert
            AssertThat.IsInstanceOfType(typeof(InternalConcrete4Full), impl);
        }

        [TestMethod]
        public void RegisterManyForOpenGenericOverload6_AccessibilityOption_RegistersInternalTypes()
        {
            // Arrange
            var container = ContainerFactory.New();

            container.Register(typeof(IServiceFull<,>), Assemblies, Lifestyle.Transient);

            // Act
            var impl = container.GetInstance<IServiceFull<decimal, decimal>>();

            // Assert
            AssertThat.IsInstanceOfType(typeof(InternalConcrete4Full), impl);
        }

        [TestMethod]
        public void GetTypesToRegisterOverload1_WithoutAccessibilityOption_ReturnsInternalTypes()
        {
            // Arrange
            var container = new Container();

            // Act
            var result = container.GetTypesToRegister(typeof(IServiceFull<,>), Assemblies);

            // Assert
            Assert.IsTrue(result.Contains(typeof(InternalConcrete4Full)));
        }

        [TestMethod]
        public void GetTypesToRegisterOverload2_WithoutAccessibilityOption_ReturnsInternalTypes()
        {
            // Arrange
            var container = new Container();

            // Act
            var result = container.GetTypesToRegister(typeof(IServiceFull<,>), Assemblies.ToArray());

            // Assert
            Assert.IsTrue(result.Contains(typeof(InternalConcrete4Full)));
        }

        #region IServiceFull

        public class ServiceImplFull<TA, TB> : IServiceFull<TA, TB>
        {
        }

        // An generic abstract class. Should not be used by the registration.
        public abstract class OpenGenericBaseFull<T> : IServiceFull<T, string>
        {
        }

        // A non-generic abstract class. Should not be used by the registration.
        public abstract class ClosedGenericBaseFull : IServiceFull<int, object>
        {
        }

        // A non-abstract generic type. Should not be used by the registration.
        public class OpenGenericFull<T> : OpenGenericBaseFull<T>
        {
        }

        // Instance of this type should be returned on container.GetInstance<IService<int, string>>()
        public class Concrete1Full : IServiceFull<string, object>
        {
        }

        // Instance of this type should be returned on container.GetInstance<IService<string, object>>()
        public class Concrete2Full : OpenGenericBaseFull<int>
        {
        }

        // Instance of this type should be returned on container.GetInstance<IService<float, double>>() and
        // on container.GetInstance<IService<Type, Type>>()
        public class Concrete3Full : IServiceFull<Type, Type>
        {
        }

        // Internal type.
        private class InternalConcrete4Full : IServiceFull<decimal, decimal>
        {
        }

        #endregion
    }
}


text:
using ecolab::Pango;
using ecolab::cairo::Surface;
using namespace std;

int main()
{
  Surface surface(cairo_recording_surface_create(CAIRO_CONTENT_COLOR,NULL));
  Pango pango(surface.cairo());
  pango.setMarkup("a test string");
  assert(pango.idxToPos(2)<pango.idxToPos(4));
//  for (size_t i=0; i<13; ++i)
//    cout << i << " " << pango.idxToPos(i) << " " << pango.posToIdx(pango.idxToPos(i)) << endl;
  assert(pango.posToIdx(pango.idxToPos(3))==3);
}


text:
using System.Web.Mvc;

namespace Contrive.Auth.Web.Mvc.Controllers
{
  public class HomeController : Controller
  {
    public ActionResult Index()
    {
      ViewBag.Message = "Welcome to ASP.NET MVC!";

      return View();
    }

    public ActionResult About()
    {
      return View();
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Define the background properties like color etc -->
    <item android:id="@android:id/background">
        <shape>
            <gradient
                android:startColor="#000001"
                android:centerColor="#0b131e"
                android:centerY="1.0"
                android:endColor="#0d15F2"
                android:angle="270"
                />
        </shape>
    </item>

    <!-- Define the progress properties like start color, end color etc -->
    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <gradient
                    android:startColor="#007A00"
                    android:centerColor="#000000"
                    android:centerY="1.0"
                    android:endColor="#000000"
                    android:angle="270"
                    />
            </shape>
        </clip>
    </item>
</layer-list>


text:
package io.github.olivierlemasle.caweb.api;

import static io.github.olivierlemasle.ca.CA.dn;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

import io.github.olivierlemasle.ca.DistinguishedName;
import io.github.olivierlemasle.ca.RootCertificate;

public class CertificateAuthority {
  private RootCertificate caCertificate;

  public CertificateAuthority() {
    // Jackson
  }

  public CertificateAuthority(final RootCertificate caCertificate) {
    this.caCertificate = caCertificate;
  }

  @JsonIgnore
  public RootCertificate getCaCertificate() {
    return caCertificate;
  }

  @JsonProperty
  public DistinguishedName getSubject() {
    return dn(caCertificate.getX509Certificate().getSubjectX500Principal());
  }

}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.spring.data.cosmos.core.query;

import org.springframework.data.repository.query.parser.Part;
import org.springframework.lang.NonNull;

import java.beans.ConstructorProperties;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Enum of criteria type
 */
public enum CriteriaType {

    ALL(""),
    IS_EQUAL("="),
    OR("OR"),
    AND("AND"),
    NOT("<>"),
    BEFORE("<"),
    AFTER(">"),
    IN("IN"),
    NOT_IN("NOT IN"),
    IS_NULL("IS_NULL"),
    IS_NOT_NULL("NOT IS_NULL"),
    LESS_THAN("<"),
    LESS_THAN_EQUAL("<="),
    GREATER_THAN(">"),
    GREATER_THAN_EQUAL(">="),
    CONTAINING("CONTAINS"),
    ENDS_WITH("ENDSWITH"),
    STARTS_WITH("STARTSWITH"),
    TRUE("= true"),
    FALSE("= false"),
    BETWEEN("BETWEEN"),
    ARRAY_CONTAINS("ARRAY_CONTAINS");

    private String sqlKeyword;

    private static final Map<Part.Type, CriteriaType> PART_TREE_TYPE_TO_CRITERIA;

    static {
        final Map<Part.Type, CriteriaType> map = new HashMap<>();

        map.put(Part.Type.NEGATING_SIMPLE_PROPERTY, CriteriaType.NOT);
        map.put(Part.Type.IS_NULL, CriteriaType.IS_NULL);
        map.put(Part.Type.IS_NOT_NULL, CriteriaType.IS_NOT_NULL);
        map.put(Part.Type.SIMPLE_PROPERTY, CriteriaType.IS_EQUAL);
        map.put(Part.Type.BEFORE, CriteriaType.BEFORE);
        map.put(Part.Type.AFTER, CriteriaType.AFTER);
        map.put(Part.Type.IN, CriteriaType.IN);
        map.put(Part.Type.NOT_IN, CriteriaType.NOT_IN);
        map.put(Part.Type.GREATER_THAN, CriteriaType.GREATER_THAN);
        map.put(Part.Type.CONTAINING, CriteriaType.CONTAINING);
        map.put(Part.Type.ENDING_WITH, CriteriaType.ENDS_WITH);
        map.put(Part.Type.STARTING_WITH, CriteriaType.STARTS_WITH);
        map.put(Part.Type.GREATER_THAN_EQUAL, CriteriaType.GREATER_THAN_EQUAL);
        map.put(Part.Type.LESS_THAN, CriteriaType.LESS_THAN);
        map.put(Part.Type.LESS_THAN_EQUAL, CriteriaType.LESS_THAN_EQUAL);
        map.put(Part.Type.TRUE, CriteriaType.TRUE);
        map.put(Part.Type.FALSE, CriteriaType.FALSE);
        map.put(Part.Type.BETWEEN, CriteriaType.BETWEEN);

        PART_TREE_TYPE_TO_CRITERIA = Collections.unmodifiableMap(map);
    }

    @ConstructorProperties({"sqlKeyword"})
    CriteriaType(String sqlKeyword) {
        this.sqlKeyword = sqlKeyword;
    }

    /**
     * To get sql keyword
     * @return String
     */
    public String getSqlKeyword() {
        return sqlKeyword;
    }

    /**
     * Check if PartType is NOT supported.
     *
     * @param partType PartType to be checked.
     * @return True if unsupported, or false.
     */
    public static boolean isPartTypeUnSupported(@NonNull Part.Type partType) {
        return !isPartTypeSupported(partType);
    }

    /**
     * Check if PartType is supported.
     *
     * @param partType PartType to be checked.
     * @return True if supported, or false.
     */
    public static boolean isPartTypeSupported(@NonNull Part.Type partType) {
        return PART_TREE_TYPE_TO_CRITERIA.containsKey(partType);
    }

    /**
     * Convert to criteria type.
     *
     * @param partType PartType to be converted.
     * @return CriteriaType
     * @throws UnsupportedOperationException for unsupported part type
     */
    @SuppressWarnings("")
    public static CriteriaType toCriteriaType(@NonNull Part.Type partType) {
        final CriteriaType criteriaType = PART_TREE_TYPE_TO_CRITERIA.get(partType);

        if (criteriaType == null) {
            throw new UnsupportedOperationException("Unsupported part type: "
                + partType);
        }

        return criteriaType;
    }

    /**
     * Check if CriteriaType operation is closure, with format of (A ops A -> A).
     * Example: AND, OR.
     *
     * @param type CriteriaType operation
     * @return True if match, or false.
     */
    public static boolean isClosed(CriteriaType type) {
        switch (type) {
            case AND:
            case OR:
                return true;
            default:
                return false;
        }
    }

    /**
     * Check if CriteriaType operation is binary, with format of (A ops A -> B).
     * Example: IS_EQUAL, AFTER.
     *
     * @param type CriteriaType operation
     * @return True if match, or false.
     */
    public static boolean isBinary(CriteriaType type) {
        switch (type) {
            case IN:
            case NOT_IN:
            case AND:
            case OR:
            case NOT:
            case IS_EQUAL:
            case BEFORE:
            case AFTER:
            case LESS_THAN:
            case LESS_THAN_EQUAL:
            case GREATER_THAN:
            case GREATER_THAN_EQUAL:
            case CONTAINING:
            case ENDS_WITH:
            case STARTS_WITH:
            case ARRAY_CONTAINS:
                return true;
            default:
                return false;
        }
    }

    /**
     * Check if CriteriaType operation is a function.
     *
     * @param type CriteriaType
     * @return True if match, or false.
     */
    public static boolean isFunction(CriteriaType type) {
        switch (type) {
            case CONTAINING:
            case ENDS_WITH:
            case STARTS_WITH:
            case IS_NULL:
            case IS_NOT_NULL:
            case ARRAY_CONTAINS:
                return true;
            default:
                return false;
        }
    }

    /**
     * Check if CriteriaType operation is unary, with format of (ops A -> B).
     *
     * @param type CriteriaType
     * @return True if match, or false.
     */
    public static boolean isUnary(CriteriaType type) {
        switch (type) {
            case IS_NULL:
            case IS_NOT_NULL:
            case TRUE:
            case FALSE:
                return true;
            default:
                return false;
        }
    }
}