text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using bv.model.BLToolkit;
using bv.model.Model.Core;
using eidss.mobileclient.Attributes;
using eidss.mobileclient.Utils;
using eidss.model.Core;
using eidss.model.Enums;
using eidss.model.Resources;
using eidss.model.Schema;

namespace eidss.mobileclient.Controllers
{
    [Authorize]
    public class FarmController : Controller
    {
        [SessionExpireFilter]
        public ActionResult FarmDetails(FarmPanel farm, int? caseType = null)
        {
            VetCase.Accessor vetCaseAccessor = VetCase.Accessor.Instance(null);
            ViewBag.CanUpdate = vetCaseAccessor.CanUpdate;
            if (!caseType.HasValue)
            {
                caseType = (int)HACode.Livestock;
            }
            IObject initObject;
            using (DbManagerProxy manager = DbManagerFactory.Factory.Create(EidssUserContext.Instance))
            {
                initObject = vetCaseAccessor.CreateNew(manager, null, caseType.Value);
            }
            ViewBag.IsHiddenPersonalData = initObject.IsHiddenPersonalData("Vet_Farm");
            ViewBag.RootKey = farm.idfCase.Value;
            ViewBag.CaseType = caseType.Value;
            ModelStorage.Put(Session.SessionID, farm.idfCase.Value, farm.idfFarm, null, farm);
            return PartialView(farm);
        }

        [HttpGet]
        [SessionExpireFilter]
        public ActionResult EpidemiologicalInformation(long root)
        {
            var vc = ModelStorage.Get(Session.SessionID, root, null) as VetCase;
            if (vc.Farm.idfsFormTemplate.HasValue && vc.Farm.FFPresenterEpi != null)
            {
                vc.Farm.FFPresenterEpi.ReadOnly = vc.ReadOnly || vc.IsClosed;
            }
            VetCase.Accessor vetCaseAccessor = VetCase.Accessor.Instance(null);
            ViewBag.CanUpdate = vetCaseAccessor.CanUpdate;
            ViewBag.RootKey = vc.idfCase;
            Session["ReturnUrl"] = Url.Action("EpidemiologicalInformation", "Farm", new { root = vc.idfCase });
            return PartialView(vc.Farm);
        }

        [HttpGet]
        [SessionExpireFilter]
        public ActionResult FarmsList(long rootKey, long farmId)
        {
            ViewBag.IdfCase = rootKey;
            ViewBag.FarmId = farmId;
            var farmPanel = (FarmPanel)ModelStorage.Get(Session.SessionID, farmId, null);
            List<FarmListItem> farms = GetFarmsList(farmPanel);
            ViewBag.ItemsCount = farms == null ? 0 : farms.Count;
            List<FarmListItem> resultList = farms == null ? farms : farms.Take(100).ToList();
            return View(resultList);
        }

        private static List<FarmListItem> GetFarmsList(FarmPanel farmInfoForSearch)
        {
            var accessor = FarmListItem.Accessor.Instance(null);
            FilterParams filter = GetFilterForFarmsList(farmInfoForSearch);
            using (var dbmanager = DbManagerFactory.Factory.Create(ModelUserContext.Instance))
            {
                List<FarmListItem> farms = accessor.SelectListT(dbmanager, filter);
                return farms;
            }
        }

        private static FilterParams GetFilterForFarmsList(FarmPanel farmInfoForSearch)
        {
            var filter = new FilterParams();
            if (!string.IsNullOrEmpty(farmInfoForSearch.strContactPhone))
            {
                filter.Add("strContactPhone", "like", String.Format("%{0}%", farmInfoForSearch.strContactPhone));
            }
            if (farmInfoForSearch.idfsOwnershipStructure.HasValue)
            {
                filter.Add("idfsOwnershipStructure", "=", farmInfoForSearch.idfsOwnershipStructure);
            }
            if (farmInfoForSearch.idfsLivestockProductionType.HasValue)
            {
                filter.Add("idfsLivestockProductionType", "=", farmInfoForSearch.idfsLivestockProductionType);
            }
            if (farmInfoForSearch.Address.idfsCountry.HasValue)
            {
                filter.Add("idfsCountry", "=", farmInfoForSearch.Address.idfsCountry);
            }
            if (farmInfoForSearch.Address.idfsRegion.HasValue)
            {
                filter.Add("idfsRegion", "=", farmInfoForSearch.Address.idfsRegion);
            }
            if (farmInfoForSearch.Address.idfsRayon.HasValue)
            {
                filter.Add("idfsRayon", "=", farmInfoForSearch.Address.idfsRayon);
            }
            if (farmInfoForSearch.Address.idfsSettlement.HasValue)
            {
                filter.Add("idfsSettlement", "=", farmInfoForSearch.Address.idfsSettlement);
            }
            if (farmInfoForSearch.Address.idfsSettlement.HasValue)
            {
                filter.Add("idfsSettlement", "=", farmInfoForSearch.Address.idfsSettlement);
            }
            if (!string.IsNullOrEmpty(farmInfoForSearch.strOwnerFirstName))
            {
                filter.Add("strFirstName", "like", String.Format("%{0}%", farmInfoForSearch.strOwnerFirstName));
            }
            if (!string.IsNullOrEmpty(farmInfoForSearch.strOwnerMiddleName))
            {
                filter.Add("strSecondName", "like", String.Format("%{0}%", farmInfoForSearch.strOwnerMiddleName));
            }
            if (!string.IsNullOrEmpty(farmInfoForSearch.strOwnerLastName))
            {
                filter.Add("strLastName", "like", String.Format("%{0}%", farmInfoForSearch.strOwnerLastName));
            }
            if (!string.IsNullOrEmpty(farmInfoForSearch.strNationalName))
            {
                filter.Add("strNationalName", "like", String.Format("%{0}%", farmInfoForSearch.strNationalName));
            }
            return filter;
        }

        [HttpPost]
        [SessionExpireFilter]
        public ActionResult SetSelectedFarm(string root, string selectedId)
        {
            long key = long.Parse(root);
            long rootKey = (long)((IObject)ModelStorage.GetRoot(Session.SessionID, key, null)).Key;
            var vetCase = ModelStorage.Get(Session.SessionID, rootKey, null) as VetCase;
            using (DbManagerProxy manager = DbManagerFactory.Factory.Create(EidssUserContext.Instance))
            {
                var cloneVetCase = (VetCase)vetCase.CloneWithSetup(manager);
                long idfFarm = string.IsNullOrEmpty(selectedId) ? 0 : long.Parse(selectedId);
                if (idfFarm == 0)
                {
                    var accessor = FarmPanel.Accessor.Instance(null);
                    vetCase.Farm = accessor.CreateByCase(manager, vetCase, vetCase);
                }
                else
                {
                    vetCase.Farm.idfRootFarm = idfFarm;
                }
                CompareModel data = vetCase.Compare(cloneVetCase);
                return new JsonResult {JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = data};
            }
        }
    }
}


text:
namespace VersionAttribute
{
    using System;

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Method)]
    public class VersionAttribute : System.Attribute
    {
        private string version;

        public VersionAttribute(string version)
        {
            this.Version = version;
        }

        public string Version
        {
            get
            {
                return this.version;
            }

            private set
            {
                this.version = value;
            }
        }

        public override string ToString()
        {
            return string.Format("Version: {0}", this.Version);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
module Groupwise
  class PostOfficeAgent
    attr_reader :endpoint, :client

    def initialize(endpoint, username, app_name, app_key)
      @endpoint, @username, @app_name, @app_key = endpoint, username, app_name, app_key
      @client = Savon.client(wsdl: wsdl, endpoint: endpoint)
      login
    end

    def version
      @version ||= begin
        body = HTTPI.get(HTTPI::Request.new(endpoint)).body
        version = body.match(/(?<=POA )([^\n\r]*)/).captures.first
      end
    end

    def wsdl
      @wsdl ||= begin
        wsdl_version = Groupwise.wsdl_version(version)
        File.expand_path("../../../contrib/novell/GW#{wsdl_version}/groupwise.wsdl", __FILE__)
      end
    end

    def logout
      response = authenticated_request(:logout)
      @session = nil if response[:status][:code] == '0'
      return response
    end

    def free_busy(email_addresses, wait_time = 0, start_time = nil, end_time = nil)
      message = { free_busy_session_id: free_busy_session(email_addresses, start_time, end_time) }
      sleep wait_time
      response = authenticated_request(:get_free_busy, message)[:free_busy_info]
    end

    private

    def login
      message = {
        auth: { username: @username, name: @app_name, key: @app_key },
        version: '1.05', language: 'en',
        attributes!: { auth: { 'xsi:type' => 'q1:TrustedApplication' } }
      }
      response = @client.call(:login_request, message: message)
      @session = response.body[:login_response][:session]
      response.body[:login_response]
    end

    def authenticated_request(method, message = nil)
      response = @client.call(
        "#{method}_request".to_sym,
        message: message,
        soap_header: { session: @session }
      )
      response.body["#{method}_response".to_sym]
    end

    def free_busy_session(email_addresses, start_time = nil, end_time = nil)
      @free_busy_session ||= begin
        message = FreeBusySessionMessage.new(email_addresses, start_time, end_time)
        response = authenticated_request(:start_free_busy_session, message)
        response[:free_busy_session_id]
      end
    end

  end
end


text:
Highlights code by scope.  Top-level scopes are one color, second-level scopes
are another color, and so on.  Variables retain the color of the scope in which
they are defined.  A variable defined in an outer scope referenced by an inner
scope is colored the same as the outer scope.

By default, comments and strings are still highlighted syntactically.

## Features

- Light and dark customizable color schemes.
- JavaScript support:
  - Script, function and block scopes (and even `catch` block scopes).
  - Node.js "file-level" scope detection.
- Emacs Lisp support:
  - `defun`, `lambda`, `let`, `let*`, `cond`, `condition-case`, `defadvice`,
    `dolist`, `quote`, `backquote` and backquote splicing.
  - Works in `eval-expression` too.

## Installation

Requires Emacs 24.3+.  JavaScript language support requires
[js2-mode](https://github.com/mooz/js2-mode) (or, if you use
[Tern](http://ternjs.net/), you may be interested in
[tern-context-coloring](https://github.com/jacksonrayhamilton/tern-context-coloring)).

To install, run the command `M-x package-install RET context-coloring RET`, and
then add the following to your init file:

```lisp
;; JavaScript:
(add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
(add-hook 'js2-mode-hook #'context-coloring-mode)

;; Emacs Lisp:
(add-hook 'emacs-lisp-mode-hook #'context-coloring-mode)

;; eval-expression:
(add-hook 'eval-expression-minibuffer-setup-hook #'context-coloring-mode) ; 24.4+
(add-hook 'minibuffer-setup-hook #'context-coloring-mode)                 ; 24.3
```

## Color Schemes

The [Zenburn](https://github.com/bbatsov/zenburn-emacs) theme, featured in the
screenshot above, now supports context coloring.

You can define your own colors by customizing faces like
`context-coloring-level-N-face`, where N is a number starting from 0.

[See here](https://gist.github.com/jacksonrayhamilton/6b89ca3b85182c490816) for
some color schemes for popular custom themes.

## Options

- `context-coloring-syntactic-comments` (default: `t`): If non-nil, also color
  comments using `font-lock`.
- `context-coloring-syntactic-strings` (default: `t`): If non-nil, also color
  strings using `font-lock`.
- `context-coloring-javascript-block-scopes` (default: `nil`): If non-nil, also
  color block scopes in the scope hierarchy in JavaScript.
- `context-coloring-javascript-detect-top-level-scope` (default: `t`): If
  non-nil, detect when to use file-level scope.


text:
package ua.in.quireg.chan.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

import timber.log.Timber;
import ua.in.quireg.chan.common.utils.StringUtils;

public class FavoritesDataSource {

    private static final String TABLE = DvachSqlHelper.TABLE_FAVORITES;
    private static final String[] ALL_COLUMNS = {
            DvachSqlHelper.COLUMN_ID,
            DvachSqlHelper.COLUMN_WEBSITE,
            DvachSqlHelper.COLUMN_BOARD_NAME,
            DvachSqlHelper.COLUMN_THREAD_NUMBER,
            DvachSqlHelper.COLUMN_TITLE
    };

    private SQLiteDatabase mDatabase;

    public FavoritesDataSource(DvachSqlHelper dbHelper) {
        mDatabase = dbHelper.getWritableDatabase();
    }

    public void addToFavorites(String website, String board, String thread, String title) {

        if (!hasFavorites(website, board, thread)) {
            ContentValues values = new ContentValues();
            values.put(DvachSqlHelper.COLUMN_WEBSITE, website);
            values.put(DvachSqlHelper.COLUMN_BOARD_NAME, board);
            values.put(DvachSqlHelper.COLUMN_THREAD_NUMBER, StringUtils.emptyIfNull(thread));
            values.put(DvachSqlHelper.COLUMN_TITLE, title);

            try {
                mDatabase.insertOrThrow(TABLE, null, values);
            } catch (Exception e) {
                Timber.e(e);
            }
        }
    }

    public void removeFromFavorites(String website, String board, String thread) {

        mDatabase.delete(TABLE,
                String.format("%s = ? and %s = ? and %s = ?",
                        DvachSqlHelper.COLUMN_WEBSITE,
                        DvachSqlHelper.COLUMN_BOARD_NAME,
                        DvachSqlHelper.COLUMN_THREAD_NUMBER),
                new String[]{website, board, StringUtils.emptyIfNull(thread)});
    }

    private List<FavoritesEntity> getAllFavorites() {

        List<FavoritesEntity> favorites = new ArrayList<>();

        Cursor cursor = mDatabase.query(TABLE, ALL_COLUMNS, null, null, null, null, DvachSqlHelper.COLUMN_ID + " ASC");
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            FavoritesEntity he = createFavoritesEntity(cursor);
            favorites.add(he);

            cursor.moveToNext();
        }
        cursor.close();

        return favorites;
    }

    public List<FavoritesEntity> getFavoriteThreads() {
        List<FavoritesEntity> threadFavorites = new ArrayList<>();

        for (FavoritesEntity f : getAllFavorites()) {
            if (!StringUtils.isEmpty(f.getThread())) {
                threadFavorites.add(f);
            }
        }
        return threadFavorites;
    }

    public List<FavoritesEntity> getFavoriteBoards() {
        List<FavoritesEntity> boardFavorites = new ArrayList<>();

        for (FavoritesEntity f : getAllFavorites()) {
            if (StringUtils.isEmpty(f.getThread())) {
                boardFavorites.add(f);
            }
        }
        return boardFavorites;
    }

    public boolean hasFavorites(String website, String board, String thread) {

        Cursor cursor = mDatabase.rawQuery(
                String.format("SELECT count(*) FROM %s WHERE %s = ? and %s = ? and %s = ?",
                        TABLE,
                        DvachSqlHelper.COLUMN_WEBSITE,
                        DvachSqlHelper.COLUMN_BOARD_NAME,
                        DvachSqlHelper.COLUMN_THREAD_NUMBER),
                new String[]{website, board, StringUtils.emptyIfNull(thread)}
        );

        cursor.moveToFirst();
        long count = cursor.getLong(0);
        cursor.close();

        return count > 0;
    }

    private FavoritesEntity createFavoritesEntity(Cursor c) {
        long id = c.getLong(c.getColumnIndex(DvachSqlHelper.COLUMN_ID));
        String website = c.getString(c.getColumnIndex(DvachSqlHelper.COLUMN_WEBSITE));
        String board = c.getString(c.getColumnIndex(DvachSqlHelper.COLUMN_BOARD_NAME));
        String thread = c.getString(c.getColumnIndex(DvachSqlHelper.COLUMN_THREAD_NUMBER));
        String title = c.getString(c.getColumnIndex(DvachSqlHelper.COLUMN_TITLE));
        return createFavoritesEntity(id, website, board, thread, title);
    }

    private FavoritesEntity createFavoritesEntity(long id, String website, String board, String thread, String title) {
        FavoritesEntity result = new FavoritesEntity();
        result.setId(id);
        result.setWebsite(website);
        result.setBoard(board);
        result.setThread(thread);
        result.setTitle(title);

        return result;
    }
}


text: Optimal Payments Node.js SDK


text:
<?php

namespace Magento\CatalogRule\Block\Adminhtml\Promo\Catalog\Edit\Tab;

/**
 * Test class for \Magento\CatalogRule\Block\Adminhtml\Promo\Catalog\Edit\Tab\Main
 *
 * @magentoAppArea adminhtml
 */
class MainTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @magentoAppIsolation enabled
     */
    public function testPrepareForm()
    {
        /** @var $objectManager \Magento\TestFramework\ObjectManager */
        $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
        $objectManager->get(
            'Magento\Framework\View\DesignInterface'
        )->setArea(
            \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE
        )->setDefaultDesignTheme();
        $rule = $objectManager->create('Magento\CatalogRule\Model\Rule');
        $objectManager->get('Magento\Framework\Registry')->register('current_promo_catalog_rule', $rule);

        $block = $objectManager->create('Magento\CatalogRule\Block\Adminhtml\Promo\Catalog\Edit\Tab\Main');
        $block->setLayout($objectManager->create('Magento\Framework\View\Layout'));
        $prepareFormMethod = new \ReflectionMethod(
            'Magento\CatalogRule\Block\Adminhtml\Promo\Catalog\Edit\Tab\Main',
            '_prepareForm'
        );
        $prepareFormMethod->setAccessible(true);
        $prepareFormMethod->invoke($block);

        $form = $block->getForm();
        foreach (['customer_group_ids', 'from_date', 'to_date'] as $id) {
            $element = $form->getElement($id);
            $this->assertNotNull($element);
            $actual = ($id == 'customer_group_ids') ? $element->getValues() : $element->getDateFormat();
            $this->assertNotEmpty($actual);
        }
    }
}


text:
/*jshint browser: true, jasmine: true */
/*global inject, module, $ */

describe('Select field directive', function () {
    'use strict';

    var bbFormat,
        bbResources,
        $animate,
        $compile,
        $filter,
        $rootScope,
        $templateCache;

    function closeCurrentModal() {
        $('.bb-modal .close').click();

        // This has to be called twice to force the modal to be removed from the DOM.
        $animate.flush();
        $animate.flush();
    }

    beforeEach(module(
        'ngMock',
        'ngAnimateMock',
        'sky.selectfield',
        'sky.templates'
    ));

    beforeEach(inject(function (_$animate_, _$compile_, _$filter_, _$rootScope_, _$templateCache_, _bbFormat_, _bbResources_) {
        $animate = _$animate_;
        $compile = _$compile_;
        $filter = _$filter_;
        $rootScope = _$rootScope_;
        $templateCache = _$templateCache_;
        bbFormat = _bbFormat_;
        bbResources = _bbResources_;
    }));

    beforeEach(function () {
        $templateCache.put(
            'bbSelectField/single/test.html',
            ''
        );
    });

    describe('single-select', function () {

        it('should show the search icon when specified', function () {
            var $scope = $rootScope.$new(),
                el;

            el = $compile('<bb-select-field bb-select-field-style="single" bb-select-field-icon="search" ng-model="selectedItems"></bb-select-field>')($scope);
            $scope.$digest();

            expect(el.find('.bb-select-field-single-icon i')).toHaveClass('fa-search');
        });

        function findClearEl(el) {
            return el.find('.bb-select-field-clear');
        }

        it('should show the close icon when bbSelectFieldClear is specified and an item is selected and clear properly when used', function () {
            var $scope = $rootScope.$new(),
                clearEl,
                e,
                el;

            el = $compile('<bb-select-field bb-select-field-style="single" bb-select-field-clear ng-model="selectedItems"></bb-select-field>')($scope);

            el.appendTo(document.body);

            $scope.$digest();

            clearEl = findClearEl(el);

            expect(clearEl).not.toBeVisible();

            $scope.selectedItems = [
                {
                    title: 'Selected item'
                }
            ];

            $scope.$digest();

            expect(clearEl).toBeVisible();

            clearEl.click();
            $scope.$digest();

            expect(clearEl).not.toBeVisible();
            expect($scope.selectedItems).toEqual([]);
            $animate.flush();
            expect('.bb-modal').not.toExist();

            $scope.selectedItems = [
                {
                    title: 'Selected item'
                }
            ];

            $scope.$digest();

            e = $.Event('keypress');
            e.which = 13;
            e.keyCode = 13;

            clearEl.trigger(e);

            $scope.$digest();
            expect(clearEl).not.toBeVisible();
            expect($scope.selectedItems).toEqual([]);

            el.remove();
        });

        it('should display the selected value in the button used to invoke the picker', function () {
            var $scope = $rootScope.$new(),
                el;

            el = $compile('<bb-select-field bb-select-field-style="single" ng-model="selectedItems"></bb-select-field>')($scope);

            $scope.$digest();

            $scope.selectedItems = [
                {
                    title: 'Selected item'
                }
            ];

            $scope.$digest();

            expect(el.find('.bb-select-field-single-title').text()).toBe('Selected item');
        });

        it('should display a dialog with one footer button when clicked', function () {
            var $scope = $rootScope.$new(),
                el;

            el = $compile(
                '<bb-select-field bb-select-field-style="single">' +
                    '<bb-select-field-picker bb-select-field-picker-template="bbSelectField/single/test.html"></bb-select-field-picker>' +
                '</bb-select-field>'
            )($scope);

            el.appendTo(document.body);

            $scope.$digest();

            el.find('.bb-select-field-single').click();

            $animate.flush();

            expect('.bb-modal').toExist();
            expect('.bb-modal .modal-footer').toExist();
            expect('.bb-modal .modal-footer button.bb-btn-secondary').toHaveText('Clear selection');

            closeCurrentModal();

            el.remove();
        });

        it('should display a dialog with one footer button when enter key pressed', function () {
            var $scope = $rootScope.$new(),
                e,
                selectEl,
                el;

            el = $compile(
                '<bb-select-field bb-select-field-style="single">' +
                    '<bb-select-field-picker bb-select-field-picker-template="bbSelectField/single/test.html"></bb-select-field-picker>' +
                '</bb-select-field>'
            )($scope);

            el.appendTo(document.body);

            $scope.$digest();

            selectEl = el.find('.bb-select-field-single');

            e = $.Event('keypress');
            e.which = 13;
            e.keyCode = 13;

            selectEl.trigger(e);

            $animate.flush();

            expect('.bb-modal').toExist();
            expect('.bb-modal .modal-footer').toExist();
            expect('.bb-modal .modal-footer button.bb-btn-secondary').toHaveText('Clear selection');

            closeCurrentModal();

            el.remove();
        });

        it('should not cause an error if the user clicks the field and no picker is defined', function () {
            var $scope = $rootScope.$new(),
                el;

            el = $compile('<bb-select-field bb-select-field-style="single"></bb-select-field>')($scope);

            $scope.$digest();

            el.find('.bb-select-field-single').click();
        });

        it('should display placeholder text when no items are selected and bb-select-field-text is defined', function () {
            var $scope = $rootScope.$new(),
                el;

            el = $compile('<bb-select-field bb-select-field-style="single" bb-select-field-text="{{placeholderText}}" ng-model="selectedItems"></bb-select-field>')($scope);

            $scope.$digest();

            $scope.placeholderText = 'Select an item';

            $scope.$digest();

            expect(el.find('.bb-select-field-single-title').text()).toBe($scope.placeholderText);
        });

        it('should call bbSelectFieldClick when the select picker is clicked', function () {
            var $scope = $rootScope.$new(),
                el,
                wasClicked = false;

            function pickerClicked() {
                wasClicked = true;
            }

            el = $compile('<bb-select-field bb-select-field-style="single" bb-select-field-click="pickerClicked()" ng-model="selectedItems">' +
            '<bb-select-field-picker bb-select-field-picker-template="bbSelectField/single/test.html"></bb-select-field-picker>' +
            '</bb-select-field>')($scope);
            el.appendTo(document.body);

            $scope.$digest();

            $scope.pickerClicked = pickerClicked;

            $scope.$digest();

            el.find('.bb-select-field-single').click();

            $animate.flush();

            expect(wasClicked).toBe(true);

            closeCurrentModal();
            el.remove();
        });

        it('should set valid and touched state appropriately for ng-model when the field is required', function () {
            var $scope = $rootScope.$new(),
                el;

            el = $compile('<form name="myForm"> <bb-select-field name="myField" bb-select-field-style="single" ng-model="selectedItems" required>' +
            '<bb-select-field-picker bb-select-field-picker-template="bbSelectField/single/test.html"></bb-select-field-picker>' +
            '</bb-select-field>')($scope);

            el.appendTo(document.body);

            $scope.$digest();

            expect($scope.myForm.$valid).toBe(false);
            expect($scope.myForm.myField.$touched).toBe(false);
            expect($scope.myForm.myField.$error.required).toBe(true);

            $scope.selectedItems = [
                {
                    title: 'Selected item'
                }
            ];

            $scope.$digest();

            expect($scope.myForm.$valid).toBe(true);
            expect($scope.myForm.myField.$touched).toBe(false);

            el.find('.bb-select-field-single').click();

            $animate.flush();

            closeCurrentModal();

            $scope.$digest();

            expect($scope.myForm.$valid).toBe(true);
            expect($scope.myForm.myField.$touched).toBe(true);

            $scope.selectedItems = [
            ];
            $scope.$digest();

            expect($scope.myForm.$valid).toBe(false);
            expect($scope.myForm.myField.$touched).toBe(true);
            expect($scope.myForm.myField.$error.required).toBe(true);

            el.remove();
        });

        it('should set touched on clear', function () {
            var $scope = $rootScope.$new(),
                clearEl,
                el;

            el = $compile('<form name="myForm"> <bb-select-field name="myField" bb-select-field-style="single" ng-model="selectedItems" bb-select-field-clear required>' +
            '<bb-select-field-picker bb-select-field-picker-template="bbSelectField/single/test.html"></bb-select-field-picker>' +
            '</bb-select-field>')($scope);

            el.appendTo(document.body);

            $scope.$digest();

            $scope.selectedItems = [
                {
                    title: 'Selected item'
                }
            ];

            $scope.$digest();

            clearEl = findClearEl(el);
            clearEl.click();
            $scope.$digest();

            expect($scope.myForm.$valid).toBe(false);
            expect($scope.myForm.myField.$touched).toBe(true);
            expect($scope.myForm.myField.$error.required).toBe(true);

            el.remove();
        });

        it('should allow binding with ngRequired', function () {
            var $scope = $rootScope.$new();

            $compile('<form name="myForm"> <bb-select-field name="myField" bb-select-field-style="single" ng-model="selectedItems" ng-required="required">' +
                '<bb-select-field-picker bb-select-field-picker-template="bbSelectField/single/test.html"></bb-select-field-picker>' +
                '</bb-select-field>')($scope);

            // Not required, no value
            $scope.$apply('required = false');
            expect($scope.myForm.myField.$error.required).toBeUndefined();

            // Required, no value
            $scope.$apply('required = true');
            expect($scope.myForm.myField.$error.required).toBe(true);

            // Required, with value
            $scope.$apply(function () {
                $scope.selectedItems = [
                    {
                        title: 'Selected item'
                    }
                ];
            });
            expect($scope.myForm.myField.$error.required).toBeUndefined();
        });

        describe('select field container', function () {
            it('removes the select field container from tab ordering when specified', function () {
                var $scope = $rootScope.$new(),
                    el,
                    selectFieldEl;

                el = $compile('<bb-select-field name="myField" bb-select-field-style="single" ng-model="selectedItems" bb-select-field-skip-while-tabbing="true"></bb-select-field>')($scope);

                el.appendTo(document.body);

                $scope.$digest();
                selectFieldEl = el.find(".bb-select-field-single")[0];
                expect(selectFieldEl).toHaveAttr('tabindex', '-1');
                el.remove();
            });

            it('should not remove the select field container from tab ordering when not specified', function () {
                var $scope = $rootScope.$new(),
                    el,
                    selectFieldEl;

                el = $compile('<bb-select-field bb-select-field-style="single" bb-select-field-clear ng-model="selectedItems"></bb-select-field>')($scope);
                el.appendTo(document.body);

                $scope.$digest();
                selectFieldEl = el.find(".bb-select-field-single")[0];
                expect(selectFieldEl).toHaveAttr('tabindex', '0');
                el.remove();
            });
        });
    });

    describe('multi-select', function () {
        function createItems(count) {
            var i,
                items = [];

            for (i = 0; i < count; i++) {
                items.push({
                    title: 'Title ' + (i + 1)
                });
            }

            return items;
        }

        it('should display appropriate text for the button', function () {
            var $scope = $rootScope.$new(),
                el;

            el = $compile('<bb-select-field bb-select-field-text="{{placeholderText}}" ng-model="selectedItems"></bb-select-field>')($scope);

            $scope.$digest();

            $scope.placeholderText = 'Select items';

            $scope.$digest();

            expect(el.find('.bb-select-field-multiple-title').text()).toBe($scope.placeholderText);
        });

        it('should call bbSelectFieldClick when the select picker is clicked', function () {
            var $scope = $rootScope.$new(),
                el,
                wasClicked = false;

            function pickerClicked() {
                wasClicked = true;
            }

            el = $compile('<bb-select-field bb-select-field-click="pickerClicked()" ng-model="selectedItems">' +
            '<bb-select-field-picker bb-select-field-picker-template="bbSelectField/single/test.html"></bb-select-field-picker>' +
            '</bb-select-field>')($scope);
            el.appendTo(document.body);

            $scope.$digest();

            $scope.pickerClicked = pickerClicked;

            $scope.$digest();

            el.find('.bb-select-field-multiple').click();

            $animate.flush();

            expect(wasClicked).toBe(true);

            closeCurrentModal();
            el.remove();
        });

        it('should set valid and touched state appropriately for ng-model when the field is required', function () {
            var $scope = $rootScope.$new(),
                el;

            el = $compile('<form name="myForm"> <bb-select-field name="myField" ng-model="selectedItems" required>' +
            '<bb-select-field-picker bb-select-field-picker-template="bbSelectField/single/test.html"></bb-select-field-picker>' +
            '</bb-select-field>')($scope);

            $scope.$digest();

            expect($scope.myForm.$valid).toBe(false);
            expect($scope.myForm.myField.$touched).toBe(false);
            expect($scope.myForm.myField.$error.required).toBe(true);

            $scope.selectedItems = [
                {
                    title: 'Selected item'
                }
            ];

            $scope.$digest();

            expect($scope.myForm.$valid).toBe(true);
            expect($scope.myForm.myField.$touched).toBe(false);

            el.find('.bb-select-field-multiple-item-delete').click();

            $scope.$digest();

            expect($scope.myForm.$valid).toBe(false);
            expect($scope.myForm.myField.$touched).toBe(true);
            expect($scope.myForm.myField.$error.required).toBe(true);

        });

        it('should display up to 5 selected values as individual items', function () {
            var $scope = $rootScope.$new(),
                el,
                i,
                itemEls,
                totalItems = 5;

            el = $compile('<bb-select-field ng-model="selectedItems"></bb-select-field')($scope);

            $scope.selectedItems = createItems(totalItems);

            $scope.$digest();

            itemEls = el.find('.bb-select-field-multiple-item');

            expect(itemEls.length).toBe(totalItems);

            for (i = 0; i < totalItems; i++) {
                expect(itemEls.eq(i).find('.bb-select-field-multiple-item-title')).toHaveText($scope.selectedItems[i].title);
            }
        });

        it('should display 6 or more selected values as one localizable summary item', function () {
            var $scope = $rootScope.$new(),
                el,
                title,
                totalItems = 1000; // Using 1,000 items so that we can test that the count is formatted properly.

            bbResources.selectfield_summary_text = '{0} #BD#N%#%#()HB&DSFRHW$#@';

            el = $compile('<bb-select-field ng-model="selectedItems"></bb-select-field')($scope);

            $scope.selectedItems = createItems(totalItems);

            $scope.$digest();

            title = bbFormat.formatText(bbResources.selectfield_summary_text, '1,000');

            expect(el.find('.bb-select-field-multiple-summary')).toHaveText(title);
        });

        it('should remove a selected item when its corresponding delete button is clicked', function () {
            var $scope = $rootScope.$new(),
                el;

            el = $compile('<bb-select-field ng-model="selectedItems"></bb-select-field')($scope);

            $scope.selectedItems = createItems(2);

            $scope.$digest();

            el.find('.bb-select-field-multiple-item').eq(1).find('button.bb-select-field-multiple-item-delete').click();

            expect($scope.selectedItems).toEqual([$scope.selectedItems[0]]);
        });

        it('should remove all selected items when the summary item\'s delete button is clicked', function () {
            var $scope = $rootScope.$new(),
                el;

            el = $compile('<bb-select-field ng-model="selectedItems"></bb-select-field')($scope);

            $scope.selectedItems = createItems(6);

            $scope.$digest();

            el.find('.bb-select-field-multiple-item').eq(0).find('button.bb-select-field-multiple-item-delete').click();

            expect($scope.selectedItems).toEqual([]);
        });
    });

    describe('API exposed to dependent directives', function () {
        it('should allow a picker to be specified', function () {
            var $scope = $rootScope.$new(),
                el,
                elScope,
                picker = {};

            el = $compile('<bb-select-field></bb-select-field')($scope);

            $scope.$digest();

            elScope = el.scope();

            elScope.bbSelectField.setPicker(picker);

            expect(elScope.bbSelectField.picker).toBe(picker);
        });

        describe('selectedItems method', function () {
            it('should return an empty array when no selected items are present', function () {
                var $scope = $rootScope.$new(),
                    el,
                    elScope;

                el = $compile('<bb-select-field ng-model="selectedItems"></bb-select-field')($scope);

                $scope.$digest();

                elScope = el.scope();

                expect(elScope.bbSelectField.getSelectedItems()).toEqual([]);
            });

            it('should return a copy of the selected items when selected items are present so that changes to the selected items in child directives do not make their way back up to the parent scope', function () {
                var $scope = $rootScope.$new(),
                    el,
                    elScope;

                el = $compile('<bb-select-field ng-model="selectedItems"></bb-select-field')($scope);

                $scope.$digest();

                $scope.selectedItems = [
                    {
                        title: 'Selected item'
                    }
                ];

                $scope.$digest();

                elScope = el.scope();

                expect(elScope.bbSelectField.getSelectedItems()).not.toBe($scope.selectedItems);
                expect(elScope.bbSelectField.getSelectedItems()).toEqual($scope.selectedItems);
            });
        });
    });
});


text:
package gautocloud

import (
	"github.com/cloudfoundry-community/gautocloud/cloudenv"
	"github.com/cloudfoundry-community/gautocloud/loader"
)

var defaultLoader loader.Loader = loader.NewLoader(
	[]cloudenv.CloudEnv{
		cloudenv.NewCfCloudEnv(),
		cloudenv.NewHerokuCloudEnv(),
		cloudenv.NewKubernetesCloudEnv(),
		cloudenv.NewLocalCloudEnv(),
	},
)


text:
@interface SwiftAddressBookObserver()

@property (nonatomic, copy) ChangeCallback changeCallback;
@property (nonatomic, readonly) ABAddressBookRef addressBook;

@end

@implementation SwiftAddressBookObserver

-(id)init {
	self = [super init];
	if (self) {

		CFErrorRef *error = NULL;
		_addressBook = ABAddressBookCreateWithOptions(NULL, error);
		if (error)
		{
			NSLog(@"%@", (__bridge_transfer NSString *)CFErrorCopyFailureReason(*error));
			return nil;
		}
	}
	return self;
}

- (void)startObserveChangesWithCallback:(ChangeCallback)callback
{
	if (callback)
	{
		if (!self.changeCallback)
		{
			ABAddressBookRegisterExternalChangeCallback(self.addressBook,
														APAddressBookExternalChangeCallback,
														(__bridge void *)(self));
		}
		self.changeCallback = callback;
	}
}

- (void)stopObserveChanges
{
	if (self.changeCallback)
	{
		self.changeCallback = nil;
		ABAddressBookUnregisterExternalChangeCallback(self.addressBook,
													  APAddressBookExternalChangeCallback,
													  (__bridge void *)(self));
	}
}

#pragma mark - external change callback

void APAddressBookExternalChangeCallback(ABAddressBookRef __unused addressBookRef,
										 CFDictionaryRef __unused info,
										 void *context)
{
	SwiftAddressBookObserver *addressBook = (__bridge SwiftAddressBookObserver *)(context);
	addressBook.changeCallback ? addressBook.changeCallback(addressBookRef) : nil;
}

@end