text:
            {{ territorio.denominazione }}

        {# incarichi attivi        #}
        {% if incarichi_attivi|length > 0 %}

             {% include 'bilanci/_miniclass_incarichi.html' with incarichi_attivi=incarichi_attivi territorio=territorio %}

        {% endif %}

                INDICATORI {{ last_indicatore_yr  }}
                POSIZIONE IN CLASSIFICA SU {{ n_comuni_cluster }} COMUNI {{ territorio_cluster }}

                {% for ip in indicatore_position %}

                            <form name="miniclass_form_{{ territorio.pk|safe }}_{{ ip.indicatore_pk|safe }}" class="" action="{% url 'classifiche-search' %}" method="get">
                                <input id="id_selected_year" name="selected_year" type="hidden" value="{{ last_indicatore_yr|safe }}" />
                                <input id="id_selected_par_type" name="selected_par_type" type="hidden" value="indicatori" />
                                <input id="id_selected_parameter_id" name="selected_parameter_id" type="hidden" value="{{ ip.indicatore_pk|safe }}" />
                                <input id="id_selected_regioni" name="selected_regioni" type="hidden" value="{{ selected_regioni_str|safe }}" />
                                <input id="id_selected_cluster" name="selected_cluster" type="hidden" value="{{ selected_cluster_str|safe }}" />
                                <input id="id_territorio_id" name="territorio_id" type="hidden" value="{{ territorio.pk|safe }}" />

                                        {{ ip.indicatore_denominazione|upper }}

                                    {{ ip.position }}°

                            </form>

{#                        #}
                            {#  ranking graph    #}
{#

#}
{#                        	#}

                {% endfor %}


text: export { SendToBack20 as default } from "../../";

redpajama_set_name: RedPajamaGithub


text:
def yelp_api_search(coordinates)
  client = Yelp::Client.new({ consumer_key: ENV['YELP_CONSUMER_KEY'],
    consumer_secret: ENV['YELP_CONSUMER_SECRET'],
    token: ENV['YELP_ACCESS_TOKEN'],
    token_secret: ENV['YELP_ACCESS_SECRET']
    })
  params = { term: 'restaurant', limit: 5, sort: 2, radius_filter: 1800 }
  client.search_by_coordinates(coordinates, params)
end


text:
ActiveRecord::Schema.define(version: 20150716053018) do

  create_table "admins", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
  end

  add_index "admins", ["email"], name: "index_admins_on_email", unique: true
  add_index "admins", ["reset_password_token"], name: "index_admins_on_reset_password_token", unique: true

  create_table "cms_configs", force: :cascade do |t|
    t.string "source_symbol"
    t.text   "target_text"
  end

  create_table "door_monitor_records", force: :cascade do |t|
    t.integer  "requestor_id"
    t.integer  "door_response"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "invoices", force: :cascade do |t|
    t.integer  "payer_id"
    t.float    "amount"
    t.integer  "invoice_status"
    t.datetime "pay_by"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "navbar_entries", force: :cascade do |t|
    t.string   "title"
    t.string   "url"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "user_id"
  end

  create_table "paid_sessions", force: :cascade do |t|
    t.integer  "user_id"
    t.datetime "started_at"
    t.boolean  "active"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "invoice_id"
    t.datetime "ended_at"
  end

  create_table "payment_token_records", force: :cascade do |t|
    t.integer  "user_id"
    t.string   "token_processor"
    t.string   "token_value"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "customer_id"
    t.boolean  "disabled",        default: false
  end

  create_table "payments", force: :cascade do |t|
    t.integer  "payment_token_record_id"
    t.integer  "amount"
    t.datetime "payment_date"
    t.string   "payment_for"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "secret_links", force: :cascade do |t|
    t.integer  "user_id"
    t.string   "secret"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: ""
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.boolean  "admin"
    t.string   "confirmation_token"
    t.string   "unconfirmed_email"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    t.string   "phone_number"
    t.boolean  "invalid_phone_number"
    t.string   "first_name"
    t.string   "last_name"
    t.boolean  "is_international"
  end

  add_index "users", ["email"], name: "index_users_on_email"
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

end


text:
package service_config_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/pivotal-cf-experimental/service-config"
)

var _ = Describe("ConfigReader", func() {
	const invalidYAML = `Count: INVALID`
	const simpleYAML = `Name: test-user`
	const nestedYAML = `---
Name: userName
Password: ppp
School:
  Name: UB
  Location: Buffalo
`
	const partialYAML = `---
Name: yaml-name
`
	const nestedPartialYAML = `---
Name: user-name
Password: password
School:
  Location: nested-partialYAML
`

	type ConfigSimple struct {
		Name string
	}
	type ConfigInvalid struct {
		Count int
	}
	type School struct {
		Name     string
		Location string
	}

	type ConfigNested struct {
		Name     string
		Password string
		School   School
	}

	Describe("Read", func() {

		It("unmarshal a config with one field", func() {
			reader := service_config.NewReader([]byte(simpleYAML))

			var simpleConfig ConfigSimple
			err := reader.Read(&simpleConfig)
			Expect(err).NotTo(HaveOccurred())

			Expect(simpleConfig).To(Equal(ConfigSimple{
				Name: "test-user",
			}))
		})

		It("unmarshal a config with nested fields", func() {
			reader := service_config.NewReader([]byte(nestedYAML))

			var nestedConfig ConfigNested
			err := reader.Read(&nestedConfig)
			Expect(err).NotTo(HaveOccurred())

			Expect(nestedConfig).To(Equal(ConfigNested{
				Name:     "userName",
				Password: "ppp",
				School: School{
					Name:     "UB",
					Location: "Buffalo",
				},
			}))
		})

		It("returns an error for unmarshalling a config without a valid YAML syntax", func() {
			reader := service_config.NewReader([]byte(invalidYAML))

			var invalidConfig ConfigInvalid
			err := reader.Read(&invalidConfig)
			Expect(err).To(HaveOccurred())
			Expect(err.Error()).To(ContainSubstring("Unmarshaling config"))
		})
	})

	Describe("ReadWithDefaults", func() {

		Context("with empty defaults", func() {

			var defaultConfig ConfigSimple

			BeforeEach(func() {
				defaultConfig = ConfigSimple{}
			})

			It("returns unmodified config", func() {
				reader := service_config.NewReader([]byte(simpleYAML))

				var simpleConfig ConfigSimple
				err := reader.ReadWithDefaults(&simpleConfig, defaultConfig)
				Expect(err).NotTo(HaveOccurred())

				Expect(simpleConfig).To(Equal(ConfigSimple{
					Name: "test-user",
				}))
			})
		})

		It("adds default top-level field when property is not present", func() {

			defaultConfig := School{
				Name:     "default-name",
				Location: "default-location",
			}
			reader := service_config.NewReader([]byte(partialYAML))

			var schoolConfig School
			err := reader.ReadWithDefaults(&schoolConfig, defaultConfig)
			Expect(err).NotTo(HaveOccurred())

			Expect(schoolConfig).To(Equal(School{
				Name:     "yaml-name",
				Location: "default-location",
			}))
		})

		It("adds default nested field when property is not present", func() {

			defaultConfig := ConfigNested{
				Name:     "default-username",
				Password: "default-password",
				School: School{
					Name:     "default-schoolname",
					Location: "default-schoolLocation",
				},
			}

			reader := service_config.NewReader([]byte(nestedPartialYAML))

			var nestedConfig ConfigNested
			err := reader.ReadWithDefaults(&nestedConfig, defaultConfig)
			Expect(err).NotTo(HaveOccurred())

			Expect(nestedConfig).To(Equal(ConfigNested{
				Name:     "user-name",
				Password: "password",
				School: School{
					Name:     "default-schoolname",
					Location: "nested-partialYAML",
				},
			}))
		})
	})
})


text:
<?xml version="1.0" encoding="UTF-8"?>
<section name="Workbench">
	<item value="183" key="org.eclipse.jdt.debug.ui.jre_preference_page_context.columnWidth0"/>
	<item value="1" key="org.eclipse.jdt.debug.ui.jre_preference_page_context.sortColumn"/>
	<item value="374" key="org.eclipse.jdt.debug.ui.jre_preference_page_context.columnWidth1"/>
	<item value="71" key="org.eclipse.jdt.debug.ui.jre_preference_page_context.columnWidth2"/>
</section>


text:
using Microsoft.Xna.Framework.Graphics;
using Farmhand.Registries.Containers;
using System.Collections.Generic;

namespace Farmhand.Registries
{
    /// <summary>
    /// Holds a reference to loaded textures. This class stores ordinary textures passed through but it primarily used to store mod textures
    /// </summary>
    public static class TextureRegistry
    {
        private static Registry<string, Texture2D> _textureRegistryInstance;
        private static Registry<string, Texture2D> RegistryInstance => _textureRegistryInstance ?? (_textureRegistryInstance = new Registry<string, Texture2D>());

        private static Registry<string, ModTexture> _modTextureRegistryInstance;
        private static Registry<string, ModTexture> ModTextureRegistryInstance => _modTextureRegistryInstance ?? (_modTextureRegistryInstance = new Registry<string, ModTexture>());

        #region Standard Texture Registry

        /// <summary>
        /// Returns all registered textures
        /// </summary>
        /// <returns>All registered textures</returns>
        public static IEnumerable<Texture2D> GetRegisteredTextures()
        {
            return RegistryInstance.GetRegisteredItems();
        }

        /// <summary>
        /// Returns item with matching id
        /// </summary>
        /// <param name="itemId"></param>
        /// <returns>Matching texture</returns>
        public static Texture2D GetItem(string itemId)
        {
            return RegistryInstance.GetItem(itemId);
        }

        /// <summary>
        /// Registers item with it
        /// </summary>
        /// <param name="itemId">Id of item to register</param>
        /// <param name="item">Texture to register</param>
        public static void RegisterItem(string itemId, Texture2D item)
        {
            RegistryInstance.RegisterItem(itemId, item);
        }

        /// <summary>
        /// Removes an item with id
        /// </summary>
        /// <param name="itemId">Id to remove</param>
        public static void UnregisterItem(string itemId)
        {
            RegistryInstance.UnregisterItem(itemId);
        }

        #endregion
        #region ModTexture Registry

        /// <summary>
        /// Gets all registered mod textures
        /// </summary>
        /// <returns>All registered mod textures</returns>
        public static IEnumerable<Texture2D> GetRegisteredModTextures()
        {
            return RegistryInstance.GetRegisteredItems();
        }

        /// <summary>
        /// Registers new mod texture
        /// </summary>
        /// <param name="mod">Mod which this texture belongs to</param>
        /// <param name="itemId">Id of texture</param>
        /// <param name="item">Texture to register</param>
        public static void RegisterItem(ModManifest mod, string itemId, ModTexture item)
        {
            ModTextureRegistryInstance.RegisterItem(GetModSpecificItemId(mod, itemId), item);
        }

        /// <summary>
        /// Removes a mod texture
        /// </summary>
        /// <param name="mod">Mod which this texture belongs to</param>
        /// <param name="itemId">Id of texture</param>
        public static void UnregisterItem(ModManifest mod, string itemId)
        {
            ModTextureRegistryInstance.UnregisterItem(GetModSpecificItemId(mod, itemId));
        }

        /// <summary>
        /// Gets a mod's texture
        /// </summary>
        /// <param name="mod">Mod which this texture belongs to</param>
        /// <param name="itemId">Id of texture</param>
        /// <returns>Matching mod texture</returns>
        public static ModTexture GetItem(ModManifest mod, string itemId)
        {
            return ModTextureRegistryInstance.GetItem(GetModSpecificItemId(mod, itemId));
        }

        #endregion
        #region Helper Functions
        private static string GetModSpecificPrefix(ModManifest mod)
        {
            return $"\\{mod.UniqueId}\\";
        }

        private static string GetModSpecificItemId(ModManifest mod, string itemId)
        {
            var modPrefix = GetModSpecificPrefix(mod);
            return $"{modPrefix}{itemId}";
        }
        #endregion
    }
}


text:
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;

/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model app\models\LoginForm */

$this->title = 'Login';
// $this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

Please fill out the following fields to login:

        <?php $form = ActiveForm::begin([
            'id' => 'login-form',
            'options' => ['class' => ''],
            'fieldConfig' => [
                'template' => "{label}\n
{input}
\n
{error}
",
                'labelOptions' => ['class' => 'control-label'],
            ],
        ]); ?>

        <?= $form->field($model, 'username') ?>

        <?= $form->field($model, 'password')->passwordInput() ?>

        <?= $form->field($model, 'rememberMe', [
            'template' => "
{input}
\n
{error}
",
        ])->checkbox() ?>

                <?= Html::submitButton('Login', ['class' => 'buggly-button', 'name' => 'login-button']) ?>

        <?php ActiveForm::end(); ?>


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.camunda.bpm.engine.test.api.multitenancy.tenantcheck;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import java.util.Collections;

import org.camunda.bpm.engine.IdentityService;
import org.camunda.bpm.engine.authorization.Groups;
import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.camunda.bpm.engine.impl.interceptor.Command;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.test.ProcessEngineRule;
import org.camunda.bpm.engine.test.util.ProvidedProcessEngineRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

public class MultiTenancyCommandTenantCheckTest {

  @Rule
  public ProcessEngineRule engineRule = new ProvidedProcessEngineRule();

  protected ProcessEngineConfigurationImpl processEngineConfiguration;
  protected IdentityService identityService;

  @Before
  public void init() {
    processEngineConfiguration = engineRule.getProcessEngineConfiguration();
    identityService = engineRule.getIdentityService();

    identityService.setAuthentication("user", null, null);
  }

  @Test
  public void disableTenantCheckForProcessEngine() {
    // disable tenant check for process engine
    processEngineConfiguration.setTenantCheckEnabled(false);

    processEngineConfiguration.getCommandExecutorTxRequired().execute(new Command<Void>() {

      @Override
      public Void execute(CommandContext commandContext) {
        // cannot enable tenant check for command when it is disabled for process engine
        commandContext.enableTenantCheck();
        assertThat(commandContext.getTenantManager().isTenantCheckEnabled(), is(false));

        return null;
      }
    });
  }

  @Test
  public void disableTenantCheckForCommand() {

    processEngineConfiguration.getCommandExecutorTxRequired().execute(new Command<Void>() {

      @Override
      public Void execute(CommandContext commandContext) {
        // disable tenant check for the current command
        commandContext.disableTenantCheck();
        assertThat(commandContext.isTenantCheckEnabled(), is(false));
        assertThat(commandContext.getTenantManager().isTenantCheckEnabled(), is(false));

        return null;
      }
    });

    processEngineConfiguration.getCommandExecutorTxRequired().execute(new Command<Void>() {

      @Override
      public Void execute(CommandContext commandContext) {
        // assert that it is enabled again for further commands
        assertThat(commandContext.isTenantCheckEnabled(), is(true));
        assertThat(commandContext.getTenantManager().isTenantCheckEnabled(), is(true));

        return null;
      }
    });
  }

  @Test
  public void disableAndEnableTenantCheckForCommand() {

    processEngineConfiguration.getCommandExecutorTxRequired().execute(new Command<Void>() {

      @Override
      public Void execute(CommandContext commandContext) {

        commandContext.disableTenantCheck();
        assertThat(commandContext.getTenantManager().isTenantCheckEnabled(), is(false));

        commandContext.enableTenantCheck();
        assertThat(commandContext.getTenantManager().isTenantCheckEnabled(), is(true));

        return null;
      }
    });
  }

  @Test
  public void disableTenantCheckForCamundaAdmin() {
    identityService.setAuthentication("user", Collections.singletonList(Groups.CAMUNDA_ADMIN), null);

    processEngineConfiguration.getCommandExecutorTxRequired().execute(new Command<Void>() {

      @Override
      public Void execute(CommandContext commandContext) {
        // camunda-admin should access data from all tenants
        assertThat(commandContext.getTenantManager().isTenantCheckEnabled(), is(false));

        return null;
      }
    });
  }

}


text:
package ch.gbssg.projects.java.railway;

/**
 * Class for forked rails, extending the BaseRail
 * @author Jan Biasi
 * @version 1.0.1
 */
public class ForkRail extends BaseRail {
	private String currentDirection;

	/**
	 * Empty constructor for the ForkRail
	 * @author Jan Biasi
	 */
	public ForkRail() {
		super();
	}

	/**
	 * Constructor with the length as parameter
	 * @author Jan Biasi
	 * @param length the length of rail
	 */
	public ForkRail(double length) {
		super(length);
	}

	/**
	 * Constructor with length and current direction
	 * @author Jan Biasi
	 * @param length the length of rail
	 * @param dir current direction
	 */
	public ForkRail(double length, String dir) {
		super(length);
		this.currentDirection = dir;
	}

	/**
	 * Switch to a direction
	 * @author Julia Tanner
	 * @param dirA UUID of first rail
     * @param dirB UUID of second rail
	 */
	public void switchDirection (String dirA, String dirB) {
		if(this.connectionPairExists(dirA, dirB)) {
			this.currentDirection = dirB;
		}
	}

	/**
	 * Gets the current direction (UUID)
	 * @return String current direction
	 */
	public String getCurrentDirection() {
		return this.currentDirection;
	}
}


text:
"""Unit tests for the NetApp-specific NFS driver module."""

from lxml import etree
import mox
from mox import IgnoreArg
from mox import IsA
import os
import socket

from cinder import context
from cinder import exception
from cinder.image import image_utils
from cinder.openstack.common import log as logging
from cinder import test
from cinder.volume import configuration as conf
from cinder.volume.drivers.netapp import api
from cinder.volume.drivers.netapp import nfs as netapp_nfs

from oslo.config import cfg
CONF = cfg.CONF

LOG = logging.getLogger(__name__)

def create_configuration():
    configuration = mox.MockObject(conf.Configuration)
    configuration.append_config_values(mox.IgnoreArg())
    configuration.nfs_mount_point_base = '/mnt/test'
    configuration.nfs_mount_options = None
    return configuration

class FakeVolume(object):
    def __init__(self, size=0):
        self.size = size
        self.id = hash(self)
        self.name = None

    def __getitem__(self, key):
        return self.__dict__[key]

    def __setitem__(self, key, val):
        self.__dict__[key] = val

class FakeSnapshot(object):
    def __init__(self, volume_size=0):
        self.volume_name = None
        self.name = None
        self.volume_id = None
        self.volume_size = volume_size
        self.user_id = None
        self.status = None

    def __getitem__(self, key):
        return self.__dict__[key]

class FakeResponce(object):
    def __init__(self, status):
        """Initialize FakeResponce.

        :param status: Either 'failed' or 'passed'
        """
        self.Status = status

        if status == 'failed':
            self.Reason = 'Sample error'

class NetappDirectCmodeNfsDriverTestCase(test.TestCase):
    """Test direct NetApp C Mode driver."""
    def setUp(self):
        super(NetappDirectCmodeNfsDriverTestCase, self).setUp()
        self._custom_setup()

    def test_create_snapshot(self):
        """Test snapshot can be created and deleted."""
        mox = self.mox
        drv = self._driver

        mox.StubOutWithMock(drv, '_clone_volume')
        drv._clone_volume(IgnoreArg(), IgnoreArg(), IgnoreArg())
        mox.ReplayAll()

        drv.create_snapshot(FakeSnapshot())

        mox.VerifyAll()

    def test_create_volume_from_snapshot(self):
        """Tests volume creation from snapshot."""
        drv = self._driver
        mox = self.mox
        volume = FakeVolume(1)
        snapshot = FakeSnapshot(1)

        location = '127.0.0.1:/nfs'
        expected_result = {'provider_location': location}
        mox.StubOutWithMock(drv, '_clone_volume')
        mox.StubOutWithMock(drv, '_get_volume_location')
        mox.StubOutWithMock(drv, 'local_path')
        mox.StubOutWithMock(drv, '_discover_file_till_timeout')
        mox.StubOutWithMock(drv, '_set_rw_permissions_for_all')
        drv._clone_volume(IgnoreArg(), IgnoreArg(), IgnoreArg())
        drv._get_volume_location(IgnoreArg()).AndReturn(location)
        drv.local_path(IgnoreArg()).AndReturn('/mnt')
        drv._discover_file_till_timeout(IgnoreArg()).AndReturn(True)
        drv._set_rw_permissions_for_all(IgnoreArg())

        mox.ReplayAll()

        loc = drv.create_volume_from_snapshot(volume, snapshot)

        self.assertEqual(loc, expected_result)

        mox.VerifyAll()

    def _prepare_delete_snapshot_mock(self, snapshot_exists):
        drv = self._driver
        mox = self.mox

        mox.StubOutWithMock(drv, '_get_provider_location')
        mox.StubOutWithMock(drv, '_volume_not_present')

        if snapshot_exists:
            mox.StubOutWithMock(drv, '_execute')
            mox.StubOutWithMock(drv, '_get_volume_path')

        drv._get_provider_location(IgnoreArg())
        drv._volume_not_present(IgnoreArg(), IgnoreArg())\
            .AndReturn(not snapshot_exists)

        if snapshot_exists:
            drv._get_volume_path(IgnoreArg(), IgnoreArg())
            drv._execute('rm', None, run_as_root=True)

        mox.ReplayAll()

        return mox

    def test_delete_existing_snapshot(self):
        drv = self._driver
        mox = self._prepare_delete_snapshot_mock(True)

        drv.delete_snapshot(FakeSnapshot())

        mox.VerifyAll()

    def test_delete_missing_snapshot(self):
        drv = self._driver
        mox = self._prepare_delete_snapshot_mock(False)

        drv.delete_snapshot(FakeSnapshot())

        mox.VerifyAll()

    def _custom_setup(self):
        kwargs = {}
        kwargs['netapp_mode'] = 'proxy'
        kwargs['configuration'] = create_configuration()
        self._driver = netapp_nfs.NetAppDirectCmodeNfsDriver(**kwargs)

    def test_check_for_setup_error(self):
        mox = self.mox
        drv = self._driver
        required_flags = [
            'netapp_transport_type',
            'netapp_login',
            'netapp_password',
            'netapp_server_hostname',
            'netapp_server_port']

        # set required flags
        for flag in required_flags:
            setattr(drv.configuration, flag, None)
        # check exception raises when flags are not set
        self.assertRaises(exception.CinderException,
                          drv.check_for_setup_error)

        # set required flags
        for flag in required_flags:
            setattr(drv.configuration, flag, 'val')

        mox.ReplayAll()

        drv.check_for_setup_error()

        mox.VerifyAll()

        # restore initial FLAGS
        for flag in required_flags:
            delattr(drv.configuration, flag)

    def test_do_setup(self):
        mox = self.mox
        drv = self._driver

        mox.StubOutWithMock(netapp_nfs.NetAppNFSDriver, 'do_setup')
        mox.StubOutWithMock(drv, '_get_client')
        mox.StubOutWithMock(drv, '_do_custom_setup')

        netapp_nfs.NetAppNFSDriver.do_setup(IgnoreArg())
        drv._get_client()
        drv._do_custom_setup(IgnoreArg())

        mox.ReplayAll()

        drv.do_setup(IsA(context.RequestContext))

        mox.VerifyAll()

    def _prepare_clone_mock(self, status):
        drv = self._driver
        mox = self.mox

        volume = FakeVolume()
        setattr(volume, 'provider_location', '127.0.0.1:/nfs')

        mox.StubOutWithMock(drv, '_get_host_ip')
        mox.StubOutWithMock(drv, '_get_export_path')
        mox.StubOutWithMock(drv, '_get_if_info_by_ip')
        mox.StubOutWithMock(drv, '_get_vol_by_junc_vserver')
        mox.StubOutWithMock(drv, '_clone_file')

        drv._get_host_ip(IgnoreArg()).AndReturn('127.0.0.1')
        drv._get_export_path(IgnoreArg()).AndReturn('/nfs')
        drv._get_if_info_by_ip('127.0.0.1').AndReturn(
            self._prepare_info_by_ip_response())
        drv._get_vol_by_junc_vserver('openstack', '/nfs').AndReturn('nfsvol')
        drv._clone_file('nfsvol', 'volume_name', 'clone_name',
                        'openstack')
        return mox

    def _prepare_info_by_ip_response(self):
        res = """<attributes-list>
        <net-interface-info>
        <address>127.0.0.1</address>
        <administrative-status>up</administrative-status>
        <current-node>fas3170rre-cmode-01</current-node>
        <current-port>e1b-1165</current-port>
        <data-protocols>
          <data-protocol>nfs</data-protocol>
        </data-protocols>
        <dns-domain-name>none</dns-domain-name>
        <failover-group/>
        <failover-policy>disabled</failover-policy>
        <firewall-policy>data</firewall-policy>
        <home-node>fas3170rre-cmode-01</home-node>
        <home-port>e1b-1165</home-port>
        <interface-name>nfs_data1</interface-name>
        <is-auto-revert>false</is-auto-revert>
        <is-home>true</is-home>
        <netmask>255.255.255.0</netmask>
        <netmask-length>24</netmask-length>
        <operational-status>up</operational-status>
        <role>data</role>
        <routing-group-name>c10.63.165.0/24</routing-group-name>
        <use-failover-group>disabled</use-failover-group>
        <vserver>openstack</vserver>
      </net-interface-info></attributes-list>"""
        response_el = etree.XML(res)
        return api.NaElement(response_el).get_children()

    def test_clone_volume(self):
        drv = self._driver
        mox = self._prepare_clone_mock('pass')

        mox.ReplayAll()

        volume_name = 'volume_name'
        clone_name = 'clone_name'
        volume_id = volume_name + str(hash(volume_name))

        drv._clone_volume(volume_name, clone_name, volume_id)

        mox.VerifyAll()

    def test_register_img_in_cache_noshare(self):
        volume = {'id': '1', 'name': 'testvol'}
        volume['provider_location'] = '10.61.170.1:/share/path'
        drv = self._driver
        mox = self.mox
        mox.StubOutWithMock(drv, '_do_clone_rel_img_cache')

        drv._do_clone_rel_img_cache('testvol', 'img-cache-12345',
                                    '10.61.170.1:/share/path',
                                    'img-cache-12345')

        mox.ReplayAll()
        drv._register_image_in_cache(volume, '12345')
        mox.VerifyAll()

    def test_register_img_in_cache_with_share(self):
        volume = {'id': '1', 'name': 'testvol'}
        volume['provider_location'] = '10.61.170.1:/share/path'
        drv = self._driver
        mox = self.mox
        mox.StubOutWithMock(drv, '_do_clone_rel_img_cache')

        drv._do_clone_rel_img_cache('testvol', 'img-cache-12345',
                                    '10.61.170.1:/share/path',
                                    'img-cache-12345')

        mox.ReplayAll()
        drv._register_image_in_cache(volume, '12345')
        mox.VerifyAll()

    def test_find_image_in_cache_no_shares(self):
        drv = self._driver
        drv._mounted_shares = []
        result = drv._find_image_in_cache('image_id')
        if not result:
            pass
        else:
            self.fail('Return result is unexpected')

    def test_find_image_in_cache_shares(self):
        drv = self._driver
        mox = self.mox
        drv._mounted_shares = ['testshare']
        mox.StubOutWithMock(drv, '_get_mount_point_for_share')
        mox.StubOutWithMock(os.path, 'exists')

        drv._get_mount_point_for_share('testshare').AndReturn('/mnt')
        os.path.exists('/mnt/img-cache-id').AndReturn(True)
        mox.ReplayAll()
        result = drv._find_image_in_cache('id')
        (share, file_name) = result[0]
        mox.VerifyAll()
        drv._mounted_shares.remove('testshare')

        if (share == 'testshare' and file_name == 'img-cache-id'):
                pass
        else:
            LOG.warn(_("Share %(share)s and file name %(file_name)s")
                     % {'share': share, 'file_name': file_name})
            self.fail('Return result is unexpected')

    def test_find_old_cache_files_notexists(self):
        drv = self._driver
        mox = self.mox
        cmd = ['find', '/mnt', '-maxdepth', '1', '-name',
               'img-cache*', '-amin', '+720']
        setattr(drv.configuration, 'expiry_thres_minutes', 720)
        mox.StubOutWithMock(drv, '_get_mount_point_for_share')
        mox.StubOutWithMock(drv, '_execute')

        drv._get_mount_point_for_share(IgnoreArg()).AndReturn('/mnt')
        drv._execute(*cmd, run_as_root=True).AndReturn((None, ''))
        mox.ReplayAll()
        res = drv._find_old_cache_files('share')
        mox.VerifyAll()
        if len(res) == 0:
            pass
        else:
            self.fail('No files expected but got return values.')

    def test_find_old_cache_files_exists(self):
        drv = self._driver
        mox = self.mox
        cmd = ['find', '/mnt', '-maxdepth', '1', '-name',
               'img-cache*', '-amin', '+720']
        setattr(drv.configuration, 'expiry_thres_minutes', '720')
        files = '/mnt/img-id1\n/mnt/img-id2\n'
        r_files = ['img-id1', 'img-id2']
        mox.StubOutWithMock(drv, '_get_mount_point_for_share')
        mox.StubOutWithMock(drv, '_execute')
        mox.StubOutWithMock(drv, '_shortlist_del_eligible_files')

        drv._get_mount_point_for_share('share').AndReturn('/mnt')
        drv._execute(*cmd, run_as_root=True).AndReturn((files, None))
        drv._shortlist_del_eligible_files(
            IgnoreArg(), r_files).AndReturn(r_files)
        mox.ReplayAll()
        res = drv._find_old_cache_files('share')
        mox.VerifyAll()
        if len(res) == len(r_files):
            for f in res:
                r_files.remove(f)
        else:
            self.fail('Returned files not same as expected.')

    def test_delete_files_till_bytes_free_success(self):
        drv = self._driver
        mox = self.mox
        files = [('img-cache-1', 230), ('img-cache-2', 380)]
        mox.StubOutWithMock(drv, '_get_mount_point_for_share')
        mox.StubOutWithMock(drv, '_delete_file')

        drv._get_mount_point_for_share(IgnoreArg()).AndReturn('/mnt')
        drv._delete_file('/mnt/img-cache-2').AndReturn(True)
        drv._delete_file('/mnt/img-cache-1').AndReturn(True)
        mox.ReplayAll()
        drv._delete_files_till_bytes_free(files, 'share', bytes_to_free=1024)
        mox.VerifyAll()

    def test_clean_image_cache_exec(self):
        drv = self._driver
        mox = self.mox
        drv.configuration.thres_avl_size_perc_start = 20
        drv.configuration.thres_avl_size_perc_stop = 50
        drv._mounted_shares = ['testshare']

        mox.StubOutWithMock(drv, '_find_old_cache_files')
        mox.StubOutWithMock(drv, '_delete_files_till_bytes_free')
        mox.StubOutWithMock(drv, '_get_capacity_info')

        drv._get_capacity_info('testshare').AndReturn((100, 19, 81))
        drv._find_old_cache_files('testshare').AndReturn(['f1', 'f2'])
        drv._delete_files_till_bytes_free(
            ['f1', 'f2'], 'testshare', bytes_to_free=31)
        mox.ReplayAll()
        drv._clean_image_cache()
        mox.VerifyAll()
        drv._mounted_shares.remove('testshare')
        if not drv.cleaning:
            pass
        else:
            self.fail('Clean image cache failed.')

    def test_clean_image_cache_noexec(self):
        drv = self._driver
        mox = self.mox
        drv.configuration.thres_avl_size_perc_start = 20
        drv.configuration.thres_avl_size_perc_stop = 50
        drv._mounted_shares = ['testshare']

        mox.StubOutWithMock(drv, '_get_capacity_info')

        drv._get_capacity_info('testshare').AndReturn((100, 30, 70))
        mox.ReplayAll()
        drv._clean_image_cache()
        mox.VerifyAll()
        drv._mounted_shares.remove('testshare')
        if not drv.cleaning:
            pass
        else:
            self.fail('Clean image cache failed.')

    def test_clone_image_fromcache(self):
        drv = self._driver
        mox = self.mox
        volume = {'name': 'vol', 'size': '20'}
        mox.StubOutWithMock(drv, '_find_image_in_cache')
        mox.StubOutWithMock(drv, '_do_clone_rel_img_cache')
        mox.StubOutWithMock(drv, '_post_clone_image')
        mox.StubOutWithMock(drv, '_is_share_vol_compatible')

        drv._find_image_in_cache(IgnoreArg()).AndReturn(
            [('share', 'file_name')])
        drv._is_share_vol_compatible(IgnoreArg(), IgnoreArg()).AndReturn(True)
        drv._do_clone_rel_img_cache('file_name', 'vol', 'share', 'file_name')
        drv._post_clone_image(volume)

        mox.ReplayAll()
        drv. clone_image(volume, ('image_location', None), 'image_id')
        mox.VerifyAll()

    def get_img_info(self, format):
        class img_info(object):
            def __init__(self, fmt):
                self.file_format = fmt

        return img_info(format)

    def test_clone_image_cloneableshare_nospace(self):
        drv = self._driver
        mox = self.mox
        volume = {'name': 'vol', 'size': '20'}
        mox.StubOutWithMock(drv, '_find_image_in_cache')
        mox.StubOutWithMock(drv, '_is_cloneable_share')
        mox.StubOutWithMock(drv, '_is_share_vol_compatible')

        drv._find_image_in_cache(IgnoreArg()).AndReturn([])
        drv._is_cloneable_share(IgnoreArg()).AndReturn('127.0.0.1:/share')
        drv._is_share_vol_compatible(IgnoreArg(), IgnoreArg()).AndReturn(False)

        mox.ReplayAll()
        (prop, cloned) = drv. clone_image(
            volume, ('nfs://127.0.0.1:/share/img-id', None), 'image_id')
        mox.VerifyAll()
        if not cloned and not prop['provider_location']:
            pass
        else:
            self.fail('Expected not cloned, got cloned.')

    def test_clone_image_cloneableshare_raw(self):
        drv = self._driver
        mox = self.mox
        volume = {'name': 'vol', 'size': '20'}
        mox.StubOutWithMock(drv, '_find_image_in_cache')
        mox.StubOutWithMock(drv, '_is_cloneable_share')
        mox.StubOutWithMock(drv, '_get_mount_point_for_share')
        mox.StubOutWithMock(image_utils, 'qemu_img_info')
        mox.StubOutWithMock(drv, '_clone_volume')
        mox.StubOutWithMock(drv, '_discover_file_till_timeout')
        mox.StubOutWithMock(drv, '_set_rw_permissions_for_all')
        mox.StubOutWithMock(drv, '_resize_image_file')
        mox.StubOutWithMock(drv, '_is_share_vol_compatible')

        drv._find_image_in_cache(IgnoreArg()).AndReturn([])
        drv._is_cloneable_share(IgnoreArg()).AndReturn('127.0.0.1:/share')
        drv._is_share_vol_compatible(IgnoreArg(), IgnoreArg()).AndReturn(True)
        drv._get_mount_point_for_share(IgnoreArg()).AndReturn('/mnt')
        image_utils.qemu_img_info('/mnt/img-id').AndReturn(
            self.get_img_info('raw'))
        drv._clone_volume(
            'img-id', 'vol', share='127.0.0.1:/share', volume_id=None)
        drv._get_mount_point_for_share(IgnoreArg()).AndReturn('/mnt')
        drv._discover_file_till_timeout(IgnoreArg()).AndReturn(True)
        drv._set_rw_permissions_for_all('/mnt/vol')
        drv._resize_image_file({'name': 'vol'}, IgnoreArg())

        mox.ReplayAll()
        drv. clone_image(
            volume, ('nfs://127.0.0.1:/share/img-id', None), 'image_id')
        mox.VerifyAll()

    def test_clone_image_cloneableshare_notraw(self):
        drv = self._driver
        mox = self.mox
        volume = {'name': 'vol', 'size': '20'}
        mox.StubOutWithMock(drv, '_find_image_in_cache')
        mox.StubOutWithMock(drv, '_is_cloneable_share')
        mox.StubOutWithMock(drv, '_get_mount_point_for_share')
        mox.StubOutWithMock(image_utils, 'qemu_img_info')
        mox.StubOutWithMock(drv, '_clone_volume')
        mox.StubOutWithMock(drv, '_discover_file_till_timeout')
        mox.StubOutWithMock(drv, '_set_rw_permissions_for_all')
        mox.StubOutWithMock(drv, '_resize_image_file')
        mox.StubOutWithMock(image_utils, 'convert_image')
        mox.StubOutWithMock(drv, '_register_image_in_cache')
        mox.StubOutWithMock(drv, '_is_share_vol_compatible')

        drv._find_image_in_cache(IgnoreArg()).AndReturn([])
        drv._is_cloneable_share('nfs://127.0.0.1/share/img-id').AndReturn(
            '127.0.0.1:/share')
        drv._is_share_vol_compatible(IgnoreArg(), IgnoreArg()).AndReturn(True)
        drv._get_mount_point_for_share('127.0.0.1:/share').AndReturn('/mnt')
        image_utils.qemu_img_info('/mnt/img-id').AndReturn(
            self.get_img_info('notraw'))
        image_utils.convert_image(IgnoreArg(), IgnoreArg(), 'raw')
        image_utils.qemu_img_info('/mnt/vol').AndReturn(
            self.get_img_info('raw'))
        drv._register_image_in_cache(IgnoreArg(), IgnoreArg())
        drv._get_mount_point_for_share('127.0.0.1:/share').AndReturn('/mnt')
        drv._discover_file_till_timeout(IgnoreArg()).AndReturn(True)
        drv._set_rw_permissions_for_all('/mnt/vol')
        drv._resize_image_file({'name': 'vol'}, IgnoreArg())

        mox.ReplayAll()
        drv. clone_image(
            volume, ('nfs://127.0.0.1/share/img-id', None), 'image_id')
        mox.VerifyAll()

    def test_clone_image_file_not_discovered(self):
        drv = self._driver
        mox = self.mox
        volume = {'name': 'vol', 'size': '20'}
        mox.StubOutWithMock(drv, '_find_image_in_cache')
        mox.StubOutWithMock(drv, '_is_cloneable_share')
        mox.StubOutWithMock(drv, '_get_mount_point_for_share')
        mox.StubOutWithMock(image_utils, 'qemu_img_info')
        mox.StubOutWithMock(drv, '_clone_volume')
        mox.StubOutWithMock(drv, '_discover_file_till_timeout')
        mox.StubOutWithMock(image_utils, 'convert_image')
        mox.StubOutWithMock(drv, '_register_image_in_cache')
        mox.StubOutWithMock(drv, '_is_share_vol_compatible')
        mox.StubOutWithMock(drv, 'local_path')
        mox.StubOutWithMock(os.path, 'exists')
        mox.StubOutWithMock(drv, '_delete_file')

        drv._find_image_in_cache(IgnoreArg()).AndReturn([])
        drv._is_cloneable_share('nfs://127.0.0.1/share/img-id').AndReturn(
            '127.0.0.1:/share')
        drv._is_share_vol_compatible(IgnoreArg(), IgnoreArg()).AndReturn(True)
        drv._get_mount_point_for_share('127.0.0.1:/share').AndReturn('/mnt')
        image_utils.qemu_img_info('/mnt/img-id').AndReturn(
            self.get_img_info('notraw'))
        image_utils.convert_image(IgnoreArg(), IgnoreArg(), 'raw')
        image_utils.qemu_img_info('/mnt/vol').AndReturn(
            self.get_img_info('raw'))
        drv._register_image_in_cache(IgnoreArg(), IgnoreArg())
        drv.local_path(IgnoreArg()).AndReturn('/mnt/vol')
        drv._discover_file_till_timeout(IgnoreArg()).AndReturn(False)
        drv.local_path(IgnoreArg()).AndReturn('/mnt/vol')
        os.path.exists('/mnt/vol').AndReturn(True)
        drv._delete_file('/mnt/vol')

        mox.ReplayAll()
        vol_dict, result = drv. clone_image(
            volume, ('nfs://127.0.0.1/share/img-id', None), 'image_id')
        mox.VerifyAll()
        self.assertFalse(result)
        self.assertFalse(vol_dict['bootable'])
        self.assertIsNone(vol_dict['provider_location'])

    def test_clone_image_resizefails(self):
        drv = self._driver
        mox = self.mox
        volume = {'name': 'vol', 'size': '20'}
        mox.StubOutWithMock(drv, '_find_image_in_cache')
        mox.StubOutWithMock(drv, '_is_cloneable_share')
        mox.StubOutWithMock(drv, '_get_mount_point_for_share')
        mox.StubOutWithMock(image_utils, 'qemu_img_info')
        mox.StubOutWithMock(drv, '_clone_volume')
        mox.StubOutWithMock(drv, '_discover_file_till_timeout')
        mox.StubOutWithMock(drv, '_set_rw_permissions_for_all')
        mox.StubOutWithMock(drv, '_resize_image_file')
        mox.StubOutWithMock(image_utils, 'convert_image')
        mox.StubOutWithMock(drv, '_register_image_in_cache')
        mox.StubOutWithMock(drv, '_is_share_vol_compatible')
        mox.StubOutWithMock(drv, 'local_path')
        mox.StubOutWithMock(os.path, 'exists')
        mox.StubOutWithMock(drv, '_delete_file')

        drv._find_image_in_cache(IgnoreArg()).AndReturn([])
        drv._is_cloneable_share('nfs://127.0.0.1/share/img-id').AndReturn(
            '127.0.0.1:/share')
        drv._is_share_vol_compatible(IgnoreArg(), IgnoreArg()).AndReturn(True)
        drv._get_mount_point_for_share('127.0.0.1:/share').AndReturn('/mnt')
        image_utils.qemu_img_info('/mnt/img-id').AndReturn(
            self.get_img_info('notraw'))
        image_utils.convert_image(IgnoreArg(), IgnoreArg(), 'raw')
        image_utils.qemu_img_info('/mnt/vol').AndReturn(
            self.get_img_info('raw'))
        drv._register_image_in_cache(IgnoreArg(), IgnoreArg())
        drv.local_path(IgnoreArg()).AndReturn('/mnt/vol')
        drv._discover_file_till_timeout(IgnoreArg()).AndReturn(True)
        drv._set_rw_permissions_for_all('/mnt/vol')
        drv._resize_image_file(
            IgnoreArg(), IgnoreArg()).AndRaise(exception.InvalidResults())
        drv.local_path(IgnoreArg()).AndReturn('/mnt/vol')
        os.path.exists('/mnt/vol').AndReturn(True)
        drv._delete_file('/mnt/vol')

        mox.ReplayAll()
        vol_dict, result = drv. clone_image(
            volume, ('nfs://127.0.0.1/share/img-id', None), 'image_id')
        mox.VerifyAll()
        self.assertFalse(result)
        self.assertFalse(vol_dict['bootable'])
        self.assertIsNone(vol_dict['provider_location'])

    def test_is_cloneable_share_badformats(self):
        drv = self._driver
        strgs = ['10.61.666.22:/share/img',
                 'nfs://10.61.666.22:/share/img',
                 'nfs://10.61.666.22//share/img',
                 'nfs://com.netapp.com:/share/img',
                 'nfs://com.netapp.com//share/img',
                 'com.netapp.com://share/im\g',
                 'http://com.netapp.com://share/img',
                 'nfs://com.netapp.com:/share/img',
                 'nfs://com.netapp.com:8080//share/img'
                 'nfs://com.netapp.com//img',
                 'nfs://[ae::sr::ty::po]/img']
        for strg in strgs:
            res = drv._is_cloneable_share(strg)
            if res:
                msg = 'Invalid format matched for url %s.' % strg
                self.fail(msg)

    def test_is_cloneable_share_goodformat1(self):
        drv = self._driver
        mox = self.mox
        strg = 'nfs://10.61.222.333/share/img'
        mox.StubOutWithMock(drv, '_check_share_in_use')
        drv._check_share_in_use(IgnoreArg(), IgnoreArg()).AndReturn('share')
        mox.ReplayAll()
        drv._is_cloneable_share(strg)
        mox.VerifyAll()

    def test_is_cloneable_share_goodformat2(self):
        drv = self._driver
        mox = self.mox
        strg = 'nfs://10.61.222.333:8080/share/img'
        mox.StubOutWithMock(drv, '_check_share_in_use')
        drv._check_share_in_use(IgnoreArg(), IgnoreArg()).AndReturn('share')
        mox.ReplayAll()
        drv._is_cloneable_share(strg)
        mox.VerifyAll()

    def test_is_cloneable_share_goodformat3(self):
        drv = self._driver
        mox = self.mox
        strg = 'nfs://com.netapp:8080/share/img'
        mox.StubOutWithMock(drv, '_check_share_in_use')
        drv._check_share_in_use(IgnoreArg(), IgnoreArg()).AndReturn('share')
        mox.ReplayAll()
        drv._is_cloneable_share(strg)
        mox.VerifyAll()

    def test_is_cloneable_share_goodformat4(self):
        drv = self._driver
        mox = self.mox
        strg = 'nfs://netapp.com/share/img'
        mox.StubOutWithMock(drv, '_check_share_in_use')
        drv._check_share_in_use(IgnoreArg(), IgnoreArg()).AndReturn('share')
        mox.ReplayAll()
        drv._is_cloneable_share(strg)
        mox.VerifyAll()

    def test_is_cloneable_share_goodformat5(self):
        drv = self._driver
        mox = self.mox
        strg = 'nfs://netapp.com/img'
        mox.StubOutWithMock(drv, '_check_share_in_use')
        drv._check_share_in_use(IgnoreArg(), IgnoreArg()).AndReturn('share')
        mox.ReplayAll()
        drv._is_cloneable_share(strg)
        mox.VerifyAll()

    def test_check_share_in_use_no_conn(self):
        drv = self._driver
        share = drv._check_share_in_use(None, '/dir')
        if share:
            self.fail('Unexpected share detected.')

    def test_check_share_in_use_invalid_conn(self):
        drv = self._driver
        share = drv._check_share_in_use(':8989', '/dir')
        if share:
            self.fail('Unexpected share detected.')

    def test_check_share_in_use_incorrect_host(self):
        drv = self._driver
        mox = self.mox
        mox.StubOutWithMock(socket, 'gethostbyname')
        socket.gethostbyname(IgnoreArg()).AndRaise(Exception())
        mox.ReplayAll()
        share = drv._check_share_in_use('incorrect:8989', '/dir')
        mox.VerifyAll()
        if share:
            self.fail('Unexpected share detected.')

    def test_check_share_in_use_success(self):
        drv = self._driver
        mox = self.mox
        drv._mounted_shares = ['127.0.0.1:/dir/share']
        mox.StubOutWithMock(socket, 'gethostbyname')
        mox.StubOutWithMock(drv, '_share_match_for_ip')
        socket.gethostbyname(IgnoreArg()).AndReturn('10.22.33.44')
        drv._share_match_for_ip(
            '10.22.33.44', ['127.0.0.1:/dir/share']).AndReturn('share')
        mox.ReplayAll()
        share = drv._check_share_in_use('127.0.0.1:8989', '/dir/share')
        mox.VerifyAll()
        if not share:
            self.fail('Expected share not detected')

    def test_construct_image_url_loc(self):
        drv = self._driver
        img_loc = (None,
                   [{'metadata':
                     {'share_location': 'nfs://host/path',
                      'mount_point': '/opt/stack/data/glance',
                      'type': 'nfs'},
                     'url': 'file:///opt/stack/data/glance/image-id'}])
        location = drv._construct_image_nfs_url(img_loc)
        if location != "nfs://host/path/image-id":
            self.fail("Unexpected direct url.")

    def test_construct_image_url_direct(self):
        drv = self._driver
        img_loc = ("nfs://host/path/image-id", None)
        location = drv._construct_image_nfs_url(img_loc)
        if location != "nfs://host/path/image-id":
            self.fail("Unexpected direct url.")

class NetappDirect7modeNfsDriverTestCase(NetappDirectCmodeNfsDriverTestCase):
    """Test direct NetApp C Mode driver."""
    def _custom_setup(self):
        self._driver = netapp_nfs.NetAppDirect7modeNfsDriver(
            configuration=create_configuration())

    def test_check_for_setup_error_version(self):
        drv = self._driver
        drv._client = api.NaServer("127.0.0.1")

        # check exception raises when version not found
        self.assertRaises(exception.VolumeBackendAPIException,
                          drv.check_for_setup_error)

        drv._client.set_api_version(1, 8)

        # check exception raises when not supported version
        self.assertRaises(exception.VolumeBackendAPIException,
                          drv.check_for_setup_error)

    def test_check_for_setup_error(self):
        mox = self.mox
        drv = self._driver
        drv._client = api.NaServer("127.0.0.1")
        drv._client.set_api_version(1, 9)
        required_flags = [
            'netapp_transport_type',
            'netapp_login',
            'netapp_password',
            'netapp_server_hostname',
            'netapp_server_port']

        # set required flags
        for flag in required_flags:
            setattr(drv.configuration, flag, None)
        # check exception raises when flags are not set
        self.assertRaises(exception.CinderException,
                          drv.check_for_setup_error)

        # set required flags
        for flag in required_flags:
            setattr(drv.configuration, flag, 'val')

        mox.ReplayAll()

        drv.check_for_setup_error()

        mox.VerifyAll()

        # restore initial FLAGS
        for flag in required_flags:
            delattr(drv.configuration, flag)

    def test_do_setup(self):
        mox = self.mox
        drv = self._driver
        mox.StubOutWithMock(netapp_nfs.NetAppNFSDriver, 'do_setup')
        mox.StubOutWithMock(drv, '_get_client')
        mox.StubOutWithMock(drv, '_do_custom_setup')
        netapp_nfs.NetAppNFSDriver.do_setup(IgnoreArg())
        drv._get_client()
        drv._do_custom_setup(IgnoreArg())

        mox.ReplayAll()

        drv.do_setup(IsA(context.RequestContext))

        mox.VerifyAll()

    def _prepare_clone_mock(self, status):
        drv = self._driver
        mox = self.mox

        volume = FakeVolume()
        setattr(volume, 'provider_location', '127.0.0.1:/nfs')

        mox.StubOutWithMock(drv, '_get_export_ip_path')
        mox.StubOutWithMock(drv, '_get_actual_path_for_export')
        mox.StubOutWithMock(drv, '_start_clone')
        mox.StubOutWithMock(drv, '_wait_for_clone_finish')
        if status == 'fail':
            mox.StubOutWithMock(drv, '_clear_clone')

        drv._get_export_ip_path(
            IgnoreArg(), IgnoreArg()).AndReturn(('127.0.0.1', '/nfs'))
        drv._get_actual_path_for_export(IgnoreArg()).AndReturn('/vol/vol1/nfs')
        drv._start_clone(IgnoreArg(), IgnoreArg()).AndReturn(('1', '2'))
        if status == 'fail':
            drv._wait_for_clone_finish('1', '2').AndRaise(
                api.NaApiError('error', 'error'))
            drv._clear_clone('1')
        else:
            drv._wait_for_clone_finish('1', '2')
        return mox

    def test_clone_volume_clear(self):
        drv = self._driver
        mox = self._prepare_clone_mock('fail')

        mox.ReplayAll()

        volume_name = 'volume_name'
        clone_name = 'clone_name'
        volume_id = volume_name + str(hash(volume_name))
        try:
            drv._clone_volume(volume_name, clone_name, volume_id)
        except Exception as e:
            if isinstance(e, api.NaApiError):
                pass
            else:
                raise

        mox.VerifyAll()


text:
namespace pp {

NetworkListObserverPrivate::NetworkListObserverPrivate(
    const InstanceHandle& instance)
    : PP_ALLOW_THIS_IN_INITIALIZER_LIST(
        monitor_(instance,
                 &NetworkListObserverPrivate::NetworkListCallbackHandler,
                 this)) {
}

NetworkListObserverPrivate::~NetworkListObserverPrivate() {
}

// static
void NetworkListObserverPrivate::NetworkListCallbackHandler(
    void* user_data,
    PP_Resource list_resource) {
  NetworkListObserverPrivate* object =
      static_cast<NetworkListObserverPrivate*>(user_data);
  NetworkListPrivate list(list_resource);
  object->OnNetworkListChanged(list);
  Module::Get()->core()->ReleaseResource(list_resource);
}

}  // namespace pp


text:
class CreateFaqEntriesTable < ActiveRecord::Migration
  def self.up
    create_table :faqs_page_faq_entries do |t|
      t.text     "question"
      t.text     "answer"
      t.integer  "position"
      t.datetime "created_at"
      t.datetime "updated_at"
      t.integer  "category_id"
    end

    create_table :faqs_page_categories do |t|
      t.text     "name"
    end
  end

  def self.down
    drop_table :faq_entries
  end
end


text:
#ifndef SHARE_VM_MEMORY_GENREMSET_HPP
#define SHARE_VM_MEMORY_GENREMSET_HPP

#include "oops/oop.hpp"

// A GenRemSet provides ways of iterating over pointers accross generations.
// (This is especially useful for older-to-younger.)

class Generation;
class BarrierSet;
class OopsInGenClosure;
class CardTableRS;

class GenRemSet: public CHeapObj<mtGC> {
  friend class Generation;

  BarrierSet* _bs;

public:
  enum Name {
    CardTable,
    Other
  };

  GenRemSet(BarrierSet * bs) : _bs(bs) {}
  GenRemSet() : _bs(NULL) {}

  virtual Name rs_kind() = 0;

  // These are for dynamic downcasts.  Unfortunately that it names the
  // possible subtypes (but not that they are subtypes!)  Return NULL if
  // the cast is invalide.
  virtual CardTableRS* as_CardTableRS() { return NULL; }

  // Return the barrier set associated with "this."
  BarrierSet* bs() { return _bs; }

  // Set the barrier set.
  void set_bs(BarrierSet* bs) { _bs = bs; }

  // Do any (sequential) processing necessary to prepare for (possibly
  // "parallel", if that arg is true) calls to younger_refs_iterate.
  virtual void prepare_for_younger_refs_iterate(bool parallel) = 0;

  // Apply the "do_oop" method of "blk" to (exactly) all oop locations
  //  1) that are in objects allocated in "g" at the time of the last call
  //     to "save_Marks", and
  //  2) that point to objects in younger generations.
  virtual void younger_refs_iterate(Generation* g, OopsInGenClosure* blk) = 0;

  virtual void younger_refs_in_space_iterate(Space* sp,
                                             OopsInGenClosure* cl) = 0;

  // This method is used to notify the remembered set that "new_val" has
  // been written into "field" by the garbage collector.
  void write_ref_field_gc(void* field, oop new_val);
protected:
  virtual void write_ref_field_gc_work(void* field, oop new_val) = 0;
public:

  // A version of the above suitable for use by parallel collectors.
  virtual void write_ref_field_gc_par(void* field, oop new_val) = 0;

  // Resize one of the regions covered by the remembered set.
  virtual void resize_covered_region(MemRegion new_region) = 0;

  // If the rem set imposes any alignment restrictions on boundaries
  // within the heap, this function tells whether they are met.
  virtual bool is_aligned(HeapWord* addr) = 0;

  // If the RS (or BS) imposes an aligment constraint on maximum heap size.
  // (This must be static, and dispatch on "nm", because it is called
  // before an RS is created.)
  static uintx max_alignment_constraint(Name nm);

  virtual void verify() = 0;

  // Verify that the remembered set has no entries for
  // the heap interval denoted by mr.  If there are any
  // alignment constraints on the remembered set, only the
  // part of the region that is aligned is checked.
  //
  //   alignment boundaries
  //   +--------+-------+--------+-------+
  //         [ region mr              )
  //            [ part checked   )
  virtual void verify_aligned_region_empty(MemRegion mr) = 0;

  // If appropriate, print some information about the remset on "tty".
  virtual void print() {}

  // Informs the RS that the given memregion contains no references to
  // younger generations.
  virtual void clear(MemRegion mr) = 0;

  // Informs the RS that there are no references to generations
  // younger than gen from generations gen and older.
  // The parameter clear_perm indicates if the perm_gen's
  // remembered set should also be processed/cleared.
  virtual void clear_into_younger(Generation* gen, bool clear_perm) = 0;

  // Informs the RS that refs in the given "mr" may have changed
  // arbitrarily, and therefore may contain old-to-young pointers.
  // If "whole heap" is true, then this invalidation is part of an
  // invalidation of the whole heap, which an implementation might
  // handle differently than that of a sub-part of the heap.
  virtual void invalidate(MemRegion mr, bool whole_heap = false) = 0;

  // Informs the RS that refs in this generation
  // may have changed arbitrarily, and therefore may contain
  // old-to-young pointers in arbitrary locations. The parameter
  // younger indicates if the same should be done for younger generations
  // as well. The parameter perm indicates if the same should be done for
  // perm gen as well.
  virtual void invalidate_or_clear(Generation* gen, bool younger, bool perm) = 0;
};

#endif // SHARE_VM_MEMORY_GENREMSET_HPP


text:
=head1 Matrixy

=head2 INTRODUCTION

This is a port of the MATLAB/Octave programming language to Parrot. See the
ROADMAP file for more information on the status of this project, and what else
needs to be done.

=head2 ABOUT

Primary goals are:

=over 4

=item * Create a working compiler that understands the majority of the
MATLAB/Octave programming language.

=back

=head2 IMPLEMENTATION

This project is broken into three primary components:

=over 4

=item * The first is the parser, located in the C<src/parser/> directory. The
parser proper is composed of three source files, F<grammar.pg> which is a
Perl6Grammar file, and F<actions.pm> which is the associated actions file
written in NQP, and F<grammar-oper.pm> which is the operator precedence parser.
In addition, several helper functions used by the parser are located in
C<src/internals>.

=item * The second component is the library of builtin functions in the
C<src/builtins/> directory. These functions are, currently, written primarily in
PIR. Function names prefixed with an underscore are "private" functions for use
with the parser. Other functions should have names which are the same as names
for regular MATLAB or Octave functions, since they will be available to the
HLL. These are also separated into different namespaces depending on visibility
and utility.

=item * A number of library functions are written in M, or mostly M with some
inline PIR code in C<toolbox/>.

=back

=head2 DEPENDENCIES

Matrixy depends on these dependencies:

=head3 Parrot

To get a proper version of Parrot to build Matrixy, you will need to check out
and build Parrot from source:

    svn co http://svn.parrot.org/parrot/trunk parrot
    cd parrot
    perl Configure.pl
    make && make test && make install-dev

=head3 Parrot-Linear-Algebra

The linear algebra package for Parrot is available separately and provides
functionality required by Matrixy. This includes matrix data types and matrix
manipulation libraries

=head2 BUILDING

Once all dependencies are in place, you can build Matrixy using this sequence of
commands:

    perl Configure.pl
    nmake test

=head2 TODO

    * Parser
    * Standard Builtins
    * Test against Octave Test Suite.

=head2 BUGS

Lots!

=head2 CONTACT

If you need to contact the Matrixy team, go to the project home page at:

www.github.com\Whiteknight\matrixy


text:
from __future__ import absolute_import, unicode_literals

import datetime
from decimal import Decimal

from django import test
from django import forms
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models.fields.files import FieldFile
from django.utils import unittest

from .models import (Foo, Bar, Whiz, BigD, BigS, Image, BigInt, Post,
    NullBooleanModel, BooleanModel, Document, RenamedField)

from .imagefield import (ImageFieldTests, ImageFieldTwoDimensionsTests,
    TwoImageFieldTests, ImageFieldNoDimensionsTests,
    ImageFieldOneDimensionTests, ImageFieldDimensionsFirstTests,
    ImageFieldUsingFileTests)

class BasicFieldTests(test.TestCase):
    def test_show_hidden_initial(self):
        """
        Regression test for #12913. Make sure fields with choices respect
        show_hidden_initial as a kwarg to models.Field.formfield()
        """
        choices = [(0, 0), (1, 1)]
        model_field = models.Field(choices=choices)
        form_field = model_field.formfield(show_hidden_initial=True)
        self.assertTrue(form_field.show_hidden_initial)

        form_field = model_field.formfield(show_hidden_initial=False)
        self.assertFalse(form_field.show_hidden_initial)

    def test_nullbooleanfield_blank(self):
        """
        Regression test for #13071: NullBooleanField should not throw
        a validation error when given a value of None.

        """
        nullboolean = NullBooleanModel(nbfield=None)
        try:
            nullboolean.full_clean()
        except ValidationError as e:
            self.fail("NullBooleanField failed validation with value of None: %s" % e.messages)

    def test_field_repr(self):
        """
        Regression test for #5931: __repr__ of a field also displays its name
        """
        f = Foo._meta.get_field('a')
        self.assertEqual(repr(f), '<django.db.models.fields.CharField: a>')
        f = models.fields.CharField()
        self.assertEqual(repr(f), '<django.db.models.fields.CharField>')

    def test_field_name(self):
        """
        Regression test for #14695: explicitly defined field name overwritten
        by model's attribute name.
        """
        instance = RenamedField()
        self.assertTrue(hasattr(instance, 'get_fieldname_display'))
        self.assertFalse(hasattr(instance, 'get_modelname_display'))

class DecimalFieldTests(test.TestCase):
    def test_to_python(self):
        f = models.DecimalField(max_digits=4, decimal_places=2)
        self.assertEqual(f.to_python(3), Decimal("3"))
        self.assertEqual(f.to_python("3.14"), Decimal("3.14"))
        self.assertRaises(ValidationError, f.to_python, "abc")

    def test_default(self):
        f = models.DecimalField(default=Decimal("0.00"))
        self.assertEqual(f.get_default(), Decimal("0.00"))

    def test_format(self):
        f = models.DecimalField(max_digits=5, decimal_places=1)
        self.assertEqual(f._format(f.to_python(2)), '2.0')
        self.assertEqual(f._format(f.to_python('2.6')), '2.6')
        self.assertEqual(f._format(None), None)

    def test_get_db_prep_lookup(self):
        from django.db import connection
        f = models.DecimalField(max_digits=5, decimal_places=1)
        self.assertEqual(f.get_db_prep_lookup('exact', None, connection=connection), [None])

    def test_filter_with_strings(self):
        """
        We should be able to filter decimal fields using strings (#8023)
        """
        Foo.objects.create(id=1, a='abc', d=Decimal("12.34"))
        self.assertEqual(list(Foo.objects.filter(d='1.23')), [])

    def test_save_without_float_conversion(self):
        """
        Ensure decimals don't go through a corrupting float conversion during
        save (#5079).
        """
        bd = BigD(d="12.9")
        bd.save()
        bd = BigD.objects.get(pk=bd.pk)
        self.assertEqual(bd.d, Decimal("12.9"))

    def test_lookup_really_big_value(self):
        """
        Ensure that really big values can be used in a filter statement, even
        with older Python versions.
        """
        # This should not crash. That counts as a win for our purposes.
        Foo.objects.filter(d__gte=100000000000)

class ForeignKeyTests(test.TestCase):
    def test_callable_default(self):
        """Test the use of a lazy callable for ForeignKey.default"""
        a = Foo.objects.create(id=1, a='abc', d=Decimal("12.34"))
        b = Bar.objects.create(b="bcd")
        self.assertEqual(b.a, a)

class DateTimeFieldTests(unittest.TestCase):
    def test_datetimefield_to_python_usecs(self):
        """DateTimeField.to_python should support usecs"""
        f = models.DateTimeField()
        self.assertEqual(f.to_python('2001-01-02 03:04:05.000006'),
                         datetime.datetime(2001, 1, 2, 3, 4, 5, 6))
        self.assertEqual(f.to_python('2001-01-02 03:04:05.999999'),
                         datetime.datetime(2001, 1, 2, 3, 4, 5, 999999))

    def test_timefield_to_python_usecs(self):
        """TimeField.to_python should support usecs"""
        f = models.TimeField()
        self.assertEqual(f.to_python('01:02:03.000004'),
                         datetime.time(1, 2, 3, 4))
        self.assertEqual(f.to_python('01:02:03.999999'),
                         datetime.time(1, 2, 3, 999999))

class BooleanFieldTests(unittest.TestCase):
    def _test_get_db_prep_lookup(self, f):
        from django.db import connection
        self.assertEqual(f.get_db_prep_lookup('exact', True, connection=connection), [True])
        self.assertEqual(f.get_db_prep_lookup('exact', '1', connection=connection), [True])
        self.assertEqual(f.get_db_prep_lookup('exact', 1, connection=connection), [True])
        self.assertEqual(f.get_db_prep_lookup('exact', False, connection=connection), [False])
        self.assertEqual(f.get_db_prep_lookup('exact', '0', connection=connection), [False])
        self.assertEqual(f.get_db_prep_lookup('exact', 0, connection=connection), [False])
        self.assertEqual(f.get_db_prep_lookup('exact', None, connection=connection), [None])

    def _test_to_python(self, f):
        self.assertTrue(f.to_python(1) is True)
        self.assertTrue(f.to_python(0) is False)

    def test_booleanfield_get_db_prep_lookup(self):
        self._test_get_db_prep_lookup(models.BooleanField())

    def test_nullbooleanfield_get_db_prep_lookup(self):
        self._test_get_db_prep_lookup(models.NullBooleanField())

    def test_booleanfield_to_python(self):
        self._test_to_python(models.BooleanField())

    def test_nullbooleanfield_to_python(self):
        self._test_to_python(models.NullBooleanField())

    def test_booleanfield_choices_blank(self):
        """
        Test that BooleanField with choices and defaults doesn't generate a
        formfield with the blank option (#9640, #10549).
        """
        choices = [(1, 'Si'), (2, 'No')]
        f = models.BooleanField(choices=choices, default=1, null=True)
        self.assertEqual(f.formfield().choices, [('', '---------')] + choices)

        f = models.BooleanField(choices=choices, default=1, null=False)
        self.assertEqual(f.formfield().choices, choices)

    def test_return_type(self):
        b = BooleanModel()
        b.bfield = True
        b.save()
        b2 = BooleanModel.objects.get(pk=b.pk)
        self.assertTrue(isinstance(b2.bfield, bool))
        self.assertEqual(b2.bfield, True)

        b3 = BooleanModel()
        b3.bfield = False
        b3.save()
        b4 = BooleanModel.objects.get(pk=b3.pk)
        self.assertTrue(isinstance(b4.bfield, bool))
        self.assertEqual(b4.bfield, False)

        b = NullBooleanModel()
        b.nbfield = True
        b.save()
        b2 = NullBooleanModel.objects.get(pk=b.pk)
        self.assertTrue(isinstance(b2.nbfield, bool))
        self.assertEqual(b2.nbfield, True)

        b3 = NullBooleanModel()
        b3.nbfield = False
        b3.save()
        b4 = NullBooleanModel.objects.get(pk=b3.pk)
        self.assertTrue(isinstance(b4.nbfield, bool))
        self.assertEqual(b4.nbfield, False)

        # http://code.djangoproject.com/ticket/13293
        # Verify that when an extra clause exists, the boolean
        # conversions are applied with an offset
        b5 = BooleanModel.objects.all().extra(
            select={'string_col': 'string'})[0]
        self.assertFalse(isinstance(b5.pk, bool))

class ChoicesTests(test.TestCase):
    def test_choices_and_field_display(self):
        """
        Check that get_choices and get_flatchoices interact with
        get_FIELD_display to return the expected values (#7913).
        """
        self.assertEqual(Whiz(c=1).get_c_display(), 'First')    # A nested value
        self.assertEqual(Whiz(c=0).get_c_display(), 'Other')    # A top level value
        self.assertEqual(Whiz(c=9).get_c_display(), 9)          # Invalid value
        self.assertEqual(Whiz(c=None).get_c_display(), None)    # Blank value
        self.assertEqual(Whiz(c='').get_c_display(), '')        # Empty value

class SlugFieldTests(test.TestCase):
    def test_slugfield_max_length(self):
        """
        Make sure SlugField honors max_length (#9706)
        """
        bs = BigS.objects.create(s = 'slug'*50)
        bs = BigS.objects.get(pk=bs.pk)
        self.assertEqual(bs.s, 'slug'*50)

class ValidationTest(test.TestCase):
    def test_charfield_raises_error_on_empty_string(self):
        f = models.CharField()
        self.assertRaises(ValidationError, f.clean, "", None)

    def test_charfield_cleans_empty_string_when_blank_true(self):
        f = models.CharField(blank=True)
        self.assertEqual('', f.clean('', None))

    def test_integerfield_cleans_valid_string(self):
        f = models.IntegerField()
        self.assertEqual(2, f.clean('2', None))

    def test_integerfield_raises_error_on_invalid_intput(self):
        f = models.IntegerField()
        self.assertRaises(ValidationError, f.clean, "a", None)

    def test_charfield_with_choices_cleans_valid_choice(self):
        f = models.CharField(max_length=1, choices=[('a','A'), ('b','B')])
        self.assertEqual('a', f.clean('a', None))

    def test_charfield_with_choices_raises_error_on_invalid_choice(self):
        f = models.CharField(choices=[('a','A'), ('b','B')])
        self.assertRaises(ValidationError, f.clean, "not a", None)

    def test_choices_validation_supports_named_groups(self):
        f = models.IntegerField(choices=(('group',((10,'A'),(20,'B'))),(30,'C')))
        self.assertEqual(10, f.clean(10, None))

    def test_nullable_integerfield_raises_error_with_blank_false(self):
        f = models.IntegerField(null=True, blank=False)
        self.assertRaises(ValidationError, f.clean, None, None)

    def test_nullable_integerfield_cleans_none_on_null_and_blank_true(self):
        f = models.IntegerField(null=True, blank=True)
        self.assertEqual(None, f.clean(None, None))

    def test_integerfield_raises_error_on_empty_input(self):
        f = models.IntegerField(null=False)
        self.assertRaises(ValidationError, f.clean, None, None)
        self.assertRaises(ValidationError, f.clean, '', None)

    def test_charfield_raises_error_on_empty_input(self):
        f = models.CharField(null=False)
        self.assertRaises(ValidationError, f.clean, None, None)

    def test_datefield_cleans_date(self):
        f = models.DateField()
        self.assertEqual(datetime.date(2008, 10, 10), f.clean('2008-10-10', None))

    def test_boolean_field_doesnt_accept_empty_input(self):
        f = models.BooleanField()
        self.assertRaises(ValidationError, f.clean, None, None)

class BigIntegerFieldTests(test.TestCase):
    def test_limits(self):
        # Ensure that values that are right at the limits can be saved
        # and then retrieved without corruption.
        maxval = 9223372036854775807
        minval = -maxval - 1
        BigInt.objects.create(value=maxval)
        qs = BigInt.objects.filter(value__gte=maxval)
        self.assertEqual(qs.count(), 1)
        self.assertEqual(qs[0].value, maxval)
        BigInt.objects.create(value=minval)
        qs = BigInt.objects.filter(value__lte=minval)
        self.assertEqual(qs.count(), 1)
        self.assertEqual(qs[0].value, minval)

    def test_types(self):
        b = BigInt(value = 0)
        self.assertTrue(isinstance(b.value, (int, long)))
        b.save()
        self.assertTrue(isinstance(b.value, (int, long)))
        b = BigInt.objects.all()[0]
        self.assertTrue(isinstance(b.value, (int, long)))

    def test_coercing(self):
        BigInt.objects.create(value ='10')
        b = BigInt.objects.get(value = '10')
        self.assertEqual(b.value, 10)

class TypeCoercionTests(test.TestCase):
    """
    Test that database lookups can accept the wrong types and convert
    them with no error: especially on Postgres 8.3+ which does not do
    automatic casting at the DB level. See #10015.

    """
    def test_lookup_integer_in_charfield(self):
        self.assertEqual(Post.objects.filter(title=9).count(), 0)

    def test_lookup_integer_in_textfield(self):
        self.assertEqual(Post.objects.filter(body=24).count(), 0)

class FileFieldTests(unittest.TestCase):
    def test_clearable(self):
        """
        Test that FileField.save_form_data will clear its instance attribute
        value if passed False.

        """
        d = Document(myfile='something.txt')
        self.assertEqual(d.myfile, 'something.txt')
        field = d._meta.get_field('myfile')
        field.save_form_data(d, False)
        self.assertEqual(d.myfile, '')

    def test_unchanged(self):
        """
        Test that FileField.save_form_data considers None to mean "no change"
        rather than "clear".

        """
        d = Document(myfile='something.txt')
        self.assertEqual(d.myfile, 'something.txt')
        field = d._meta.get_field('myfile')
        field.save_form_data(d, None)
        self.assertEqual(d.myfile, 'something.txt')

    def test_changed(self):
        """
        Test that FileField.save_form_data, if passed a truthy value, updates
        its instance attribute.

        """
        d = Document(myfile='something.txt')
        self.assertEqual(d.myfile, 'something.txt')
        field = d._meta.get_field('myfile')
        field.save_form_data(d, 'else.txt')
        self.assertEqual(d.myfile, 'else.txt')


text:
double key = 0.0;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    mRecordManager.reset(new RecordManager);

    initialize();
}

MainWindow::~MainWindow()
{
    delete ui;
    mRecordManager->closeActuatorSerialPort();

    delete mWarningSound;
}

void MainWindow::initialize()
{
    // Bindings
    bindings();

    setButtonState(RunningStateStandBy);

    mWarningSound = new QMediaPlayer(this);
    mWarningSound->setMedia(QUrl::fromLocalFile(QCoreApplication::applicationDirPath() + "/" + CONST_WARNING_SOUND_PATH));
    mWarningSound->setVolume(100);

    QSettings settings;
    settings.beginGroup(CONST_SETTING_CURRENT);
    // Record Settings
    float fDiameter = settings.value("diameter").toFloat();
    float fError = settings.value("error").toFloat();
    int nInterval = settings.value("interval").toInt();
    bool bCheckErrorDetection = settings.value("checkError").toBool();
    setUIRecordSetting(nInterval, fDiameter, fError);

    // Actuator Setting
    QString currentAcutatorSerialPortName = settings.value("serial2").toString();
    settings.endGroup();

    ui->checkErrorDetection->setChecked(bCheckErrorDetection);
    mRecordManager->enableErrorCheck(bCheckErrorDetection);

    if(mRecordManager->isAvailableSerialPortName(currentAcutatorSerialPortName))
    {
        mRecordManager->setSerialPortActuator(currentAcutatorSerialPortName);
        mRecordManager->openActuatorSerialPort();
    }
}

void MainWindow::bindings()
{
    connect(ui->btnSetting, SIGNAL(clicked()), this, SLOT(showSettingDialog()));
    connect(ui->btnList, SIGNAL(clicked()), this, SLOT(showRecordListDialog()));
    connect(ui->btnStart, SIGNAL(clicked()), this, SLOT(recordStart()));
    connect(ui->btnStop, SIGNAL(clicked()), this, SLOT(recordStop()));

    if(!(mRecordManager.isNull()))
    {
        connect(mRecordManager.data(), SIGNAL(detectedCurrent(float)), this, SLOT(setUICurrentValue(float)));
        connect(mRecordManager.data(), SIGNAL(changedElapsedTime(int,int,int)), this, SLOT(setUIElapsedTime(int,int,int)));
        connect(mRecordManager.data(), SIGNAL(detectedError(float,float)), this, SLOT(processError(float,float)));
    }

    // FIXME : Rework the UI
    QCustomPlot* customPlot = ui->graphCurrent;
    customPlot->addGraph(); // blue line
    customPlot->graph(0)->setPen(QPen(Qt::blue));
//    customPlot->graph(0)->setBrush(QBrush(QColor(240, 255, 200)));
//    customPlot->graph(0)->setAntialiasedFill(false);

    customPlot->addGraph(); // blue dot
    customPlot->graph(1)->setPen(QPen(Qt::blue));
    customPlot->graph(1)->setLineStyle(QCPGraph::lsNone);
    customPlot->graph(1)->setScatterStyle(QCPScatterStyle::ssDisc);

    customPlot->xAxis->setTickLabelType(QCPAxis::ltNumber);
//    customPlot->xAxis->setDateTimeFormat("hh:mm:ss");
    customPlot->xAxis->setAutoTickStep(false);
    customPlot->xAxis->setTickStep(1);
    customPlot->axisRect()->setupFullAxesBox();

    customPlot->xAxis->setRange(0, 8, Qt::AlignLeft);

    // make left and bottom axes transfer their ranges to right and top axes:
//    connect(customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->xAxis2, SLOT(setRange(QCPRange)));
}

void MainWindow::setButtonState(const RunningState &state)
{
    switch(state)
    {
        case RunningStateRecord:
        {
            ui->btnStop->setEnabled(true);
            ui->btnStart->setEnabled(false);
            ui->btnList->setEnabled(false);
            ui->btnSetting->setEnabled(false);

            ui->actionStop->setEnabled(true);
            ui->actionStart->setEnabled(false);
            ui->actionList->setEnabled(false);
            ui->actionSetting->setEnabled(false);
        }
        break;
        case RunningStateStandBy:
        {
            ui->btnStop->setEnabled(false);
            ui->btnStart->setEnabled(true);
            ui->btnList->setEnabled(true);
            ui->btnSetting->setEnabled(true);

            ui->actionStop->setEnabled(false);
            ui->actionStart->setEnabled(true);
            ui->actionList->setEnabled(true);
            ui->actionSetting->setEnabled(true);
        }
        break;
        default:
        break;
    }
}

void MainWindow::setUIRecordSetting(const int &interval, const float &diameter, const float &error)
{
    ui->dispFilament->setText(QString::number(diameter) + QString(" mm"));
    ui->dispError->setText(QString::number(error) + QString(" mm"));
    ui->dispInterval->setText(QString::number(interval) + QString(tr(" 초")));
}

void MainWindow::processError(const float& diameter, const float& error)
{
#ifdef _DEBUG_
    qDebug() << __FUNCTION__ << ": " << QString::number(diameter) << ", " << QString::number(error);
#endif
    mRecordManager->sendActuatorCmd(RecordManager::ActuatorCmdRelayOn);
    mWarningSound->play();

    QMessageBox msgBox;
    msgBox.setText(tr("오류 검출"));
    msgBox.setWindowTitle(tr("필라민트 측정기"));
    msgBox.setInformativeText(tr("오류가 검출 되었습니다.\n확인을 누르면 기록을 다시 시작 합니다."));
    msgBox.setStandardButtons(QMessageBox::Ok);
    msgBox.setDefaultButton(QMessageBox::Ok);
    msgBox.setButtonText(QMessageBox::Ok, tr("확인"));
    msgBox.setIcon(QMessageBox::Critical);

    QSpacerItem* horizontalSpacer = new QSpacerItem(200, 0, QSizePolicy::Minimum, QSizePolicy::Expanding);
    QGridLayout* layout = (QGridLayout*)msgBox.layout();
    layout->addItem(horizontalSpacer, layout->rowCount(), 0, 1, layout->columnCount());

    msgBox.exec();

    mWarningSound->stop();
    mRecordManager->sendActuatorCmd(RecordManager::ActuatorCmdRelayOff);
    mRecordManager->recordResume();
}

void MainWindow::setUIElapsedTime(const int& hour, const int& minute, const int& sec)
{
    // QString elapsed = QString::number(hour) + ":" + QString::number(minute) + ":" + QString::number(sec);
    QString elapsed = QString("%1").arg(hour, 2, 10, QChar('0')) + ":" + QString("%1").arg(minute, 2, 10, QChar('0')) + ":" + QString("%1").arg(sec, 2, 10, QChar('0'));
    ui->dispElapsedTime->setText(elapsed);
}

void MainWindow::setUICurrentValue(const float &current)
{
    // FIXME : Rework the UI
    key += 0.1;

    // set data of line
    ui->graphCurrent->graph(0)->addData(key, current);
    // set data of dots
    ui->graphCurrent->graph(1)->clearData();
    ui->graphCurrent->graph(1)->addData(key, current);
    // remove data of lines that's outside visible range:
    ui->graphCurrent->graph(0)->removeDataBefore(key-8);

    // make key axis range scroll with the data (at a constant range size of 8):
    if(key > 8.0)
        ui->graphCurrent->xAxis->setRange(key + 0.25, 8, Qt::AlignRight);

    ui->graphCurrent->replot();

    // ui->valueCurrent->setText(QString::number(current));
    QString currentValue("0.0");

    if(current > 0.f)
    {
        currentValue = QString::number(current) + "00";
        currentValue = currentValue.left(currentValue.indexOf(".")+4);
    }

    ui->valueCurrent->setText(currentValue);
}

void MainWindow::showSettingDialog()
{
    SettingDialog setting;
    if(setting.exec() == QDialog::Accepted)
    {
        QSettings settings;
        settings.beginGroup(CONST_SETTING_CURRENT);
        float fDiameter = settings.value("diameter").toFloat();
        float fError = settings.value("error").toFloat();
        int nInterval = settings.value("interval").toInt();
        settings.endGroup();

        setUIRecordSetting(nInterval, fDiameter, fError);
    }
}

int MainWindow::showExitMsgBox()
{
    QMessageBox msgBox;
    msgBox.setText(tr("종료"));
    msgBox.setWindowTitle(tr("필라민트 측정기"));
    msgBox.setInformativeText(tr("프로그램을 종료합니다."));
    msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
    msgBox.setDefaultButton(QMessageBox::Cancel);
    msgBox.setButtonText(QMessageBox::Ok, tr("확인"));
    msgBox.setButtonText(QMessageBox::Cancel, tr("취소"));
    msgBox.setIcon(QMessageBox::Question);

    QSpacerItem* horizontalSpacer = new QSpacerItem(200, 0, QSizePolicy::Minimum, QSizePolicy::Expanding);
    QGridLayout* layout = (QGridLayout*)msgBox.layout();
    layout->addItem(horizontalSpacer, layout->rowCount(), 0, 1, layout->columnCount());

    return msgBox.exec();
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if(showExitMsgBox() == QMessageBox::Ok)
    {
        mRecordManager->recordStop();
        event->accept();
    }
    else
        event->ignore();
}

void MainWindow::showRecordListDialog()
{
    RecordListDialog recordList;
    recordList.exec();
}

void MainWindow::recordStart()
{
    QMessageBox msgBox;
    msgBox.setText(tr("시작"));
    msgBox.setWindowTitle(tr("기록 시작"));
    msgBox.setInformativeText(tr("확인을 누르면 기록을 시작합니다."));
    msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
    msgBox.setDefaultButton(QMessageBox::Cancel);
    msgBox.setButtonText(QMessageBox::Ok, tr("확인"));
    msgBox.setButtonText(QMessageBox::Cancel, tr("취소"));
    msgBox.setIcon(QMessageBox::Question);

    QSpacerItem* horizontalSpacer = new QSpacerItem(250, 0, QSizePolicy::Minimum, QSizePolicy::Expanding);
    QGridLayout* layout = (QGridLayout*)msgBox.layout();
    layout->addItem(horizontalSpacer, layout->rowCount(), 0, 1, layout->columnCount());

    int ret = msgBox.exec();
    if(ret == QMessageBox::Ok)
    {
        QSettings settings;
        settings.beginGroup(CONST_SETTING_CURRENT);
        float fDiameter = settings.value("diameter").toFloat();
        float fError = settings.value("error").toFloat();
        int nInterval = settings.value("interval").toInt();
        QString currentSensorSerialPortName = settings.value("serial").toString();
        settings.endGroup();

        if(mRecordManager->isAvailableSerialPortName(currentSensorSerialPortName))
        {
            key = 0.0;
            ui->graphCurrent->xAxis->setRange(0, 8, Qt::AlignLeft);
            ui->graphCurrent->graph(0)->clearData();
            ui->graphCurrent->graph(1)->clearData();
            ui->graphCurrent->replot();

            mRecordManager->setSerialPortSensor(currentSensorSerialPortName);
            mRecordManager->setRecordSetting(nInterval, fDiameter, fError);
            mRecordManager->recordStart();

            setButtonState(RunningStateRecord);
        }
        else
        {
            QMessageBox errorMsg;
            errorMsg.setText(tr("오류"));
            errorMsg.setInformativeText(tr("시리얼 포트를 연결 할 수 없습니다.\n설정을 확인 하세요."));
            errorMsg.setStandardButtons(QMessageBox::Ok);
            errorMsg.setDefaultButton(QMessageBox::Ok);
            errorMsg.setButtonText(QMessageBox::Ok, tr("확인"));
            errorMsg.setIcon(QMessageBox::Information);

            QSpacerItem* horizontalSpacer = new QSpacerItem(350, 0, QSizePolicy::Minimum, QSizePolicy::Expanding);
            QGridLayout* layout = (QGridLayout*)msgBox.layout();
            layout->addItem(horizontalSpacer, layout->rowCount(), 0, 1, layout->columnCount());

            errorMsg.exec();
        }
    }
}

void MainWindow::recordStop()
{
    QMessageBox msgBox;
    msgBox.setText(tr("정지"));
    msgBox.setWindowTitle(tr("기록 정지"));
    msgBox.setInformativeText(tr("확인을 누르면 기록을 정지합니다."));
    msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
    msgBox.setDefaultButton(QMessageBox::Cancel);
    msgBox.setButtonText(QMessageBox::Ok, tr("확인"));
    msgBox.setButtonText(QMessageBox::Cancel, tr("취소"));
    msgBox.setIcon(QMessageBox::Question);

    QSpacerItem* horizontalSpacer = new QSpacerItem(250, 0, QSizePolicy::Minimum, QSizePolicy::Expanding);
    QGridLayout* layout = (QGridLayout*)msgBox.layout();
    layout->addItem(horizontalSpacer, layout->rowCount(), 0, 1, layout->columnCount());

    int ret = msgBox.exec();
    if(ret == QMessageBox::Ok)
    {
        setButtonState(RunningStateStandBy);
        mRecordManager->recordStop();
    }
}

void MainWindow::on_actionSetting_triggered()
{
    showSettingDialog();
}

void MainWindow::on_actionStart_triggered()
{
    recordStart();
}

void MainWindow::on_actionStop_triggered()
{
    recordStop();
}

void MainWindow::on_actionList_triggered()
{
    showRecordListDialog();
}

void MainWindow::on_actionSerial_triggered()
{
    SerialSetupDialog serialSetup;

    QStringList serialList = mRecordManager->getSupportedSerailPorts();
    serialSetup.setItems(serialList);

    int bResult = serialSetup.exec();
    if(bResult == QDialog::Accepted)
    {
        // Sensor
        QString portName = serialSetup.getSensorPortName();
        if(portName.length() > 0)
            mRecordManager->setSerialPortSensor(portName);

        // Actuator
        portName = serialSetup.getActuatorPortName();
        if(portName.length() > 0)
        {
            mRecordManager->setSerialPortActuator(portName);
            mRecordManager->openActuatorSerialPort();
        }
    }
}

void MainWindow::on_actionExit_triggered()
{
    this->close();
}

void MainWindow::on_actionAbout_triggered()
{
    QMessageBox msgBox;
    msgBox.setText(tr("필라민트 측정기"));
    msgBox.setWindowTitle(tr("정보"));
    //msgBox.setInformativeText(tr("프로그램의 저작권은 D-Factory에 있습니다."));
    msgBox.setIcon(QMessageBox::Information);

    QSpacerItem* horizontalSpacer = new QSpacerItem(200, 0, QSizePolicy::Minimum, QSizePolicy::Expanding);
    QGridLayout* layout = (QGridLayout*)msgBox.layout();
    layout->addItem(horizontalSpacer, layout->rowCount(), 0, 1, layout->columnCount());

    msgBox.exec();
}

void MainWindow::on_checkErrorDetection_toggled(bool checked)
{
#ifdef _DEBUG_
    qDebug() << __FUNCTION__ << ": " << ((checked) ? "checked" : "unchecked");
#endif
    QSettings settings;
    settings.beginGroup(CONST_SETTING_CURRENT);
    settings.setValue("checkError", checked);
    settings.endGroup();

    mRecordManager->enableErrorCheck(checked);
}


text:
import * as React from "react";

// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface IBaseProps {
    menuId: string;
    open: boolean;
    toggle: () => void;
    focusMenuButton?: (ref: React.RefObject<HTMLButtonElement>, menuID: string) => void;
}

// IProps may typically extend:
// RouteComponentProps
// ReturnType<typeof mapStateToProps>
// ReturnType<typeof mapDispatchToProps>
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface IProps extends IBaseProps {
}

export default class MenuButton extends React.Component<IProps, undefined> {
    private menuButtonRef: React.RefObject<HTMLButtonElement>;

    constructor(props: IProps) {
        super(props);
        this.menuButtonRef = React.createRef<HTMLButtonElement>();

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

    public render(): React.ReactElement<{}> {
        const { toggle, open, menuId, children } = this.props;
        return (
            <button
                aria-expanded={open}
                aria-controls={menuId}
                onClick={toggle}
                ref={this.menuButtonRef}
            >
                {this.getFocusBack()}
                {children}
            </button>
        );
    }

    public getFocusBack() {
        if (this.menuButtonRef?.current && this.props.open) {
            this.props.focusMenuButton(this.menuButtonRef, this.props.menuId);
        }
    }
}


text:
package com.spectralogic.ds3autogen.python.generators.response;

import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class GetObjectResponseGenerator_Test {

    private final static GetObjectResponseGenerator generator = new GetObjectResponseGenerator();

    @Test
    public void toParseResponsePayloadTest() {
        final String expected = "stream = self.request.stream\n" +
                "        try:\n" +
                "            bytes_read = response.read(self.buffer_size)\n" +
                "            while bytes_read:\n" +
                "                stream.write(bytes_read)\n" +
                "                bytes_read = response.read(self.buffer_size)\n" +
                "        finally:\n" +
                "            stream.close()\n" +
                "            response.close()\n";
        final String result = generator.toParseResponsePayload(null);
        assertThat(result, is(expected));
    }

    @Test
    public void toInitResponseTest() {
        final String expected = "def __init__(self, response, request, buffer_size=None):\n" +
                "        self.buffer_size = buffer_size\n" +
                "        super(self.__class__, self).__init__(response, request)\n";

        final String result = generator.toInitResponse();
        assertThat(result, is(expected));
    }
}


text:
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Navigate } from '@ngxs/router-plugin';
import { Store } from '@ngxs/store';
import { Task } from '@task/models/task';
import { GetTasks, GetTask } from '@task/store/task.actions';
import { TaskSelector } from '@task/store/task.selector';

@Injectable({
  providedIn: 'root'
})
export class TaskFacadeService {
  constructor(private store: Store) {}

  selectedTask(): Task | null {
    return this.store.selectSnapshot(TaskSelector.selectedTask);
  }

  getTasks(): void {
    this.store.dispatch(new GetTasks());
  }

  // distinguish between select a task (what happens to UI?) and the action of getting information of a task from a taskID
  selectTask(taskId: string): void {
    this.store.dispatch(new Navigate([`/taskana/workplace/tasks/taskdetail/${taskId}`]));
  }

  getTask(taskId: string): void {
    this.store.dispatch(new GetTask(taskId));
  }

  /**
   * @TODO Discuss potential method "deselectTask" if feature is present
   */
}


text:
package org.apache.http.entity;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.apache.http.Consts;
import org.junit.Assert;
import org.junit.Test;

/**
 * Unit tests for {@link BasicHttpEntity}.
 *
 */
public class TestBasicHttpEntity {

    @Test
    public void testBasics() throws Exception {

        final byte[] bytes = "Message content".getBytes(Consts.ASCII);
        final InputStream content = new ByteArrayInputStream(bytes);
        final BasicHttpEntity httpentity = new BasicHttpEntity();
        httpentity.setContent(content);
        httpentity.setContentLength(bytes.length);

        Assert.assertEquals(bytes.length, httpentity.getContentLength());
        Assert.assertFalse(httpentity.isRepeatable());
        Assert.assertTrue(httpentity.isStreaming());
    }

    @Test
    public void testContent() throws Exception {
        final byte[] bytes = "Message content".getBytes(Consts.ASCII);
        final InputStream content = new ByteArrayInputStream(bytes);
        final BasicHttpEntity httpentity = new BasicHttpEntity();
        try {
            httpentity.getContent();
            Assert.fail("IllegalStateException should have been thrown");
        } catch (final IllegalStateException ex) {
            // expected
        }
        httpentity.setContent(content);
        Assert.assertEquals(content, httpentity.getContent());

        httpentity.setContent(null);
        try {
            httpentity.getContent();
            Assert.fail("IllegalStateException should have been thrown");
        } catch (final IllegalStateException ex) {
            // expected
        }
    }

    @Test
    public void testWriteTo() throws Exception {
        final byte[] bytes = "Message content".getBytes(Consts.ASCII);
        final InputStream content = new ByteArrayInputStream(bytes);
        final BasicHttpEntity httpentity = new BasicHttpEntity();
        httpentity.setContent(content);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        httpentity.writeTo(out);
        final byte[] bytes2 = out.toByteArray();
        Assert.assertNotNull(bytes2);
        Assert.assertEquals(bytes.length, bytes2.length);
        for (int i = 0; i < bytes.length; i++) {
            Assert.assertEquals(bytes[i], bytes2[i]);
        }
        httpentity.setContent(null);
        out = new ByteArrayOutputStream();
        try {
            httpentity.writeTo(out);
            Assert.fail("IllegalStateException should have been thrown");
        } catch (final IllegalStateException ex) {
            // expected
        }

        try {
            httpentity.writeTo(null);
            Assert.fail("IllegalArgumentException should have been thrown");
        } catch (final IllegalArgumentException ex) {
            // expected
        }
    }

}


text:
package dnsserver

import (
	"fmt"
	"os"
	"strings"
)

// RegisterDevDirective splices name into the list of directives
// immediately before another directive. This function is ONLY
// for plugin development purposes! NEVER use it for a plugin
// that you are not currently building. If before is empty,
// the directive will be appended to the end of the list.
//
// It is imperative that directives execute in the proper
// order, and hard-coding the list of directives guarantees
// a correct, absolute order every time. This function is
// convenient when developing a plugin, but it does not
// guarantee absolute ordering. Multiple plugins registering
// directives with this function will lead to non-
// deterministic builds and buggy software.
//
// Directive names must be lower-cased and unique. Any errors
// here are fatal, and even successful calls print a message
// to stdout as a reminder to use it only in development.
func RegisterDevDirective(name, before string) {
	if name == "" {
		fmt.Println("[FATAL] Cannot register empty directive name")
		os.Exit(1)
	}
	if strings.ToLower(name) != name {
		fmt.Printf("[FATAL] %s: directive name must be lowercase\n", name)
		os.Exit(1)
	}
	for _, dir := range directives {
		if dir == name {
			fmt.Printf("[FATAL] %s: directive name already exists\n", name)
			os.Exit(1)
		}
	}
	if before == "" {
		directives = append(directives, name)
	} else {
		var found bool
		for i, dir := range directives {
			if dir == before {
				directives = append(directives[:i], append([]string{name}, directives[i:]...)...)
				found = true
				break
			}
		}
		if !found {
			fmt.Printf("[FATAL] %s: directive not found\n", before)
			os.Exit(1)
		}
	}
	msg := fmt.Sprintf("Registered directive '%s' ", name)
	if before == "" {
		msg += "at end of list"
	} else {
		msg += fmt.Sprintf("before '%s'", before)
	}
	fmt.Printf("[INFO] %s\n", msg)
}

// Add here, and in core/coredns.go to use them.

// Directives are registered in the order they should be
// executed.
//
// Ordering is VERY important. Every middleware will
// feel the effects of all other middleware below
// (after) them during a request, but they must not
// care what middleware above them are doing.
var directives = []string{
	"root",
	"bind",
	"health",
	"pprof",

	"prometheus",
	"errors",
	"log",
	"chaos",
	"cache",

	"rewrite",
	"loadbalance",

	"dnssec",
	"file",
	"auto",
	"secondary",
	"etcd",
	"kubernetes",
	"proxy",
	"whoami",
}


text:
import {Element} from './element';

export interface Item {
  id?: string;
  text?: string;
  selected?: boolean;
}

export class Option<T> extends Element {

  _ref = true;

  constructor(item: Item) {
    super('option');
    const {id, text, selected} = item;
    this.prop({value: (id !== undefined ? id : text)});
    this.child(text !== undefined ? text : id);
    if (selected) {
      this.select();
    }
  }

  select(): this {
    return this.prop({selected: 'selected'});
  }

  disable(): this {
    return this.prop({disabled: 'disabled'});
  }

}


text:
module MathRootHelper
  VERSION = "0.0.4"
end


text:
All Orders

                Order
                Order Amount
                Order Date

                {{order._id}}
                {{order.totalCost | currency:"&#8377"}}
                {{order.created}}