text:
"""Unit tests for functions and classes for image transfer."""

import io
from unittest import mock

from oslo_vmware import exceptions
from oslo_vmware import image_transfer
from oslo_vmware.tests import base

class ImageTransferUtilityTest(base.TestCase):
    """Tests for image_transfer utility methods."""

    def test_start_transfer(self):
        data = b'image-data-here'
        read_handle = io.BytesIO(data)
        write_handle = mock.Mock()
        image_transfer._start_transfer(read_handle, write_handle, None)
        write_handle.write.assert_called_once_with(data)

    @mock.patch('oslo_vmware.rw_handles.FileWriteHandle')
    @mock.patch('oslo_vmware.rw_handles.ImageReadHandle')
    @mock.patch.object(image_transfer, '_start_transfer')
    def test_download_flat_image(
            self,
            fake_transfer,
            fake_rw_handles_ImageReadHandle,
            fake_rw_handles_FileWriteHandle):

        context = mock.Mock()
        image_id = mock.Mock()
        image_service = mock.Mock()
        image_service.download = mock.Mock()
        image_service.download.return_value = 'fake_iter'

        fake_ImageReadHandle = 'fake_ImageReadHandle'
        fake_FileWriteHandle = 'fake_FileWriteHandle'
        cookies = []
        timeout_secs = 10
        image_size = 1000
        host = '127.0.0.1'
        port = 443
        dc_path = 'dc1'
        ds_name = 'ds1'
        file_path = '/fake_path'

        fake_rw_handles_ImageReadHandle.return_value = fake_ImageReadHandle
        fake_rw_handles_FileWriteHandle.return_value = fake_FileWriteHandle

        image_transfer.download_flat_image(
            context,
            timeout_secs,
            image_service,
            image_id,
            image_size=image_size,
            host=host,
            port=port,
            data_center_name=dc_path,
            datastore_name=ds_name,
            cookies=cookies,
            file_path=file_path)

        image_service.download.assert_called_once_with(context, image_id)

        fake_rw_handles_ImageReadHandle.assert_called_once_with('fake_iter')

        fake_rw_handles_FileWriteHandle.assert_called_once_with(
            host,
            port,
            dc_path,
            ds_name,
            cookies,
            file_path,
            image_size,
            cacerts=None)

        fake_transfer.assert_called_once_with(
            fake_ImageReadHandle,
            fake_FileWriteHandle,
            timeout_secs)

    @mock.patch('oslo_vmware.rw_handles.FileWriteHandle')
    @mock.patch.object(image_transfer, '_start_transfer')
    def test_download_file(self, start_transfer, file_write_handle_cls):
        write_handle = mock.sentinel.write_handle
        file_write_handle_cls.return_value = write_handle

        read_handle = mock.sentinel.read_handle
        host = mock.sentinel.host
        port = mock.sentinel.port
        dc_name = mock.sentinel.dc_name
        ds_name = mock.sentinel.ds_name
        cookies = mock.sentinel.cookies
        upload_file_path = mock.sentinel.upload_file_path
        file_size = mock.sentinel.file_size
        cacerts = mock.sentinel.cacerts
        timeout_secs = mock.sentinel.timeout_secs
        image_transfer.download_file(
            read_handle, host, port, dc_name, ds_name, cookies,
            upload_file_path, file_size, cacerts, timeout_secs)

        file_write_handle_cls.assert_called_once_with(
            host, port, dc_name, ds_name, cookies, upload_file_path,
            file_size, cacerts=cacerts)
        start_transfer.assert_called_once_with(
            read_handle, write_handle, timeout_secs)

    @mock.patch('oslo_vmware.rw_handles.VmdkWriteHandle')
    @mock.patch.object(image_transfer, '_start_transfer')
    def test_download_stream_optimized_data(self, fake_transfer,
                                            fake_rw_handles_VmdkWriteHandle):

        context = mock.Mock()
        session = mock.Mock()
        read_handle = mock.Mock()
        timeout_secs = 10
        image_size = 1000
        host = '127.0.0.1'
        port = 443
        resource_pool = 'rp-1'
        vm_folder = 'folder-1'
        vm_import_spec = None

        fake_VmdkWriteHandle = mock.Mock()
        fake_VmdkWriteHandle.get_imported_vm = mock.Mock()
        fake_rw_handles_VmdkWriteHandle.return_value = fake_VmdkWriteHandle

        image_transfer.download_stream_optimized_data(
            context,
            timeout_secs,
            read_handle,
            session=session,
            host=host,
            port=port,
            resource_pool=resource_pool,
            vm_folder=vm_folder,
            vm_import_spec=vm_import_spec,
            image_size=image_size)

        fake_rw_handles_VmdkWriteHandle.assert_called_once_with(
            session,
            host,
            port,
            resource_pool,
            vm_folder,
            vm_import_spec,
            image_size,
            'PUT')

        fake_transfer.assert_called_once_with(read_handle,
                                              fake_VmdkWriteHandle,
                                              timeout_secs)

        fake_VmdkWriteHandle.get_imported_vm.assert_called_once_with()

    @mock.patch('tarfile.open')
    @mock.patch('oslo_vmware.image_util.get_vmdk_name_from_ovf')
    def test_get_vmdk_handle(self, get_vmdk_name_from_ovf, tar_open):

        ovf_info = mock.Mock()
        ovf_info.name = 'test.ovf'
        vmdk_info = mock.Mock()
        vmdk_info.name = 'test.vmdk'
        tar = mock.Mock()
        tar.__iter__ = mock.Mock(return_value=iter([ovf_info, vmdk_info]))
        tar.__enter__ = mock.Mock(return_value=tar)
        tar.__exit__ = mock.Mock(return_value=None)
        tar_open.return_value = tar

        ovf_handle = mock.Mock()
        get_vmdk_name_from_ovf.return_value = 'test.vmdk'
        vmdk_handle = mock.Mock()
        tar.extractfile.side_effect = [ovf_handle, vmdk_handle]

        ova_handle = mock.sentinel.ova_handle
        ret = image_transfer._get_vmdk_handle(ova_handle)

        self.assertEqual(vmdk_handle, ret)
        tar_open.assert_called_once_with(mode="r|", fileobj=ova_handle)
        self.assertEqual([mock.call(ovf_info), mock.call(vmdk_info)],
                         tar.extractfile.call_args_list)
        get_vmdk_name_from_ovf.assert_called_once_with(ovf_handle)

    @mock.patch('tarfile.open')
    def test_get_vmdk_handle_with_invalid_ova(self, tar_open):

        tar = mock.Mock()
        tar.__iter__ = mock.Mock(return_value=iter([]))
        tar.__enter__ = mock.Mock(return_value=tar)
        tar.__exit__ = mock.Mock(return_value=None)
        tar_open.return_value = tar

        ova_handle = mock.sentinel.ova_handle
        ret = image_transfer._get_vmdk_handle(ova_handle)

        self.assertIsNone(ret)
        tar_open.assert_called_once_with(mode="r|", fileobj=ova_handle)
        self.assertFalse(tar.extractfile.called)

    @mock.patch('oslo_vmware.rw_handles.ImageReadHandle')
    @mock.patch.object(image_transfer, 'download_stream_optimized_data')
    @mock.patch.object(image_transfer, '_get_vmdk_handle')
    def _test_download_stream_optimized_image(
            self,
            get_vmdk_handle,
            download_stream_optimized_data,
            image_read_handle,
            container=None,
            invalid_ova=False):

        image_service = mock.Mock()
        if container:
            image_service.show.return_value = {'container_format': container}
        read_iter = mock.sentinel.read_iter
        image_service.download.return_value = read_iter
        read_handle = mock.sentinel.read_handle
        image_read_handle.return_value = read_handle

        if container == 'ova':
            if invalid_ova:
                get_vmdk_handle.return_value = None
            else:
                vmdk_handle = mock.sentinel.vmdk_handle
                get_vmdk_handle.return_value = vmdk_handle

        imported_vm = mock.sentinel.imported_vm
        download_stream_optimized_data.return_value = imported_vm

        context = mock.sentinel.context
        timeout_secs = mock.sentinel.timeout_secs
        image_id = mock.sentinel.image_id
        session = mock.sentinel.session
        image_size = mock.sentinel.image_size
        host = mock.sentinel.host
        port = mock.sentinel.port
        resource_pool = mock.sentinel.port
        vm_folder = mock.sentinel.vm_folder
        vm_import_spec = mock.sentinel.vm_import_spec

        if container == 'ova' and invalid_ova:
            self.assertRaises(exceptions.ImageTransferException,
                              image_transfer.download_stream_optimized_image,
                              context,
                              timeout_secs,
                              image_service,
                              image_id,
                              session=session,
                              host=host,
                              port=port,
                              resource_pool=resource_pool,
                              vm_folder=vm_folder,
                              vm_import_spec=vm_import_spec,
                              image_size=image_size)
        else:
            ret = image_transfer.download_stream_optimized_image(
                context,
                timeout_secs,
                image_service,
                image_id,
                session=session,
                host=host,
                port=port,
                resource_pool=resource_pool,
                vm_folder=vm_folder,
                vm_import_spec=vm_import_spec,
                image_size=image_size)

            self.assertEqual(imported_vm, ret)
            image_service.show.assert_called_once_with(context, image_id)
            image_service.download.assert_called_once_with(context, image_id)
            image_read_handle.assert_called_once_with(read_iter)
            if container == 'ova':
                get_vmdk_handle.assert_called_once_with(read_handle)
                exp_read_handle = vmdk_handle
            else:
                exp_read_handle = read_handle
            download_stream_optimized_data.assert_called_once_with(
                context,
                timeout_secs,
                exp_read_handle,
                session=session,
                host=host,
                port=port,
                resource_pool=resource_pool,
                vm_folder=vm_folder,
                vm_import_spec=vm_import_spec,
                image_size=image_size)

    def test_download_stream_optimized_image(self):
        self._test_download_stream_optimized_image()

    def test_download_stream_optimized_image_ova(self):
        self._test_download_stream_optimized_image(container='ova')

    def test_download_stream_optimized_image_invalid_ova(self):
        self._test_download_stream_optimized_image(container='ova',
                                                   invalid_ova=True)

    @mock.patch.object(image_transfer, '_start_transfer')
    @mock.patch('oslo_vmware.rw_handles.VmdkReadHandle')
    @mock.patch('oslo_vmware.common.loopingcall.FixedIntervalLoopingCall')
    def test_copy_stream_optimized_disk(
            self, loopingcall, vmdk_read_handle, start_transfer):

        read_handle = mock.Mock()
        vmdk_read_handle.return_value = read_handle

        updater = mock.Mock()
        loopingcall.return_value = updater

        context = mock.sentinel.context
        timeout = mock.sentinel.timeout
        write_handle = mock.Mock(name='/cinder/images/tmpAbcd.vmdk')
        session = mock.sentinel.session
        host = mock.sentinel.host
        port = mock.sentinel.port
        vm = mock.sentinel.vm
        vmdk_file_path = mock.sentinel.vmdk_file_path
        vmdk_size = mock.sentinel.vmdk_size

        image_transfer.copy_stream_optimized_disk(
            context, timeout, write_handle, session=session, host=host,
            port=port, vm=vm, vmdk_file_path=vmdk_file_path,
            vmdk_size=vmdk_size)

        vmdk_read_handle.assert_called_once_with(
            session, host, port, vm, vmdk_file_path, vmdk_size)
        loopingcall.assert_called_once_with(read_handle.update_progress)
        updater.start.assert_called_once_with(
            interval=image_transfer.NFC_LEASE_UPDATE_PERIOD)
        start_transfer.assert_called_once_with(read_handle, write_handle,
                                               timeout)
        updater.stop.assert_called_once_with()

    @mock.patch('oslo_vmware.rw_handles.VmdkReadHandle')
    @mock.patch.object(image_transfer, '_start_transfer')
    def test_upload_image(self, fake_transfer, fake_rw_handles_VmdkReadHandle):

        context = mock.sentinel.context
        image_id = mock.sentinel.image_id
        owner_id = mock.sentinel.owner_id
        session = mock.sentinel.session
        vm = mock.sentinel.vm
        image_service = mock.Mock()

        timeout_secs = 10
        image_size = 1000
        host = '127.0.0.1'
        port = 443
        file_path = '/fake_path'

        # TODO(vbala) Remove this after we delete the keyword argument
        # 'is_public' from all client code.
        is_public = False

        image_name = 'fake_image'
        image_version = 1
        store_id = 'fake_store'
        base_image_ref = 'e79161cd-5f9d-4007-8823-81a807a64332'

        fake_VmdkReadHandle = mock.Mock()
        fake_rw_handles_VmdkReadHandle.return_value = fake_VmdkReadHandle

        image_transfer.upload_image(context,
                                    timeout_secs,
                                    image_service,
                                    image_id,
                                    owner_id,
                                    session=session,
                                    host=host,
                                    port=port,
                                    vm=vm,
                                    vmdk_file_path=file_path,
                                    vmdk_size=image_size,
                                    is_public=is_public,
                                    image_name=image_name,
                                    image_version=image_version,
                                    store_id=store_id,
                                    base_image_ref=base_image_ref)

        fake_rw_handles_VmdkReadHandle.assert_called_once_with(session,
                                                               host,
                                                               port,
                                                               vm,
                                                               file_path,
                                                               image_size)

        ver_str = str(image_version)
        image_metadata = {'disk_format': 'vmdk',
                          'name': image_name,
                          'properties': {'vmware_image_version': ver_str,
                                         'vmware_disktype': 'streamOptimized',
                                         'owner_id': owner_id}}

        image_service.update.assert_called_once_with(
            context,
            image_id,
            image_metadata,
            data=fake_VmdkReadHandle,
            store_id=store_id,
            base_image_ref=base_image_ref)


text:
@implementation HandleDocumentInteractionCommand

// -----------------------------------------------------------------------------
/// @brief Executes this command. See the class documentation for details.
// -----------------------------------------------------------------------------
- (bool) doIt
{
  bool success = [self moveDocumentInteractionFileToArchive];
  if (success)
  {
    // UI changes must be made in the main thread context
    [self performSelectorOnMainThread:@selector(activateUIAreaArchive) withObject:nil waitUntilDone:YES];
  }
  return success;
}

// -----------------------------------------------------------------------------
/// @brief Private helper for doIt().
// -----------------------------------------------------------------------------
- (bool) moveDocumentInteractionFileToArchive
{
  ApplicationDelegate* delegate = [ApplicationDelegate sharedDelegate];
  if (! delegate.documentInteractionURL)
    return false;
  NSString* documentInteractionFilePath = [delegate.documentInteractionURL path];
  NSString* documentInteractionFileName = [documentInteractionFilePath lastPathComponent];
  // The file always has an .sgf extension, iOS makes sure of that. Tested
  // with a file downloaded via HTTP where the file has the proper MIME type,
  // but a non-standard extension (i.e. something else than .sgf). When the user
  // selects "Open in..." in Safari, the document interaction system passes the
  // file into the app with the extension .sgf tacked on.
  NSString* preferredGameName = [documentInteractionFileName stringByDeletingPathExtension];
  ArchiveViewModel* model = delegate.archiveViewModel;
  NSString* uniqueGameName = [model uniqueGameNameForName:preferredGameName];
  NSString* uniqueFilePath = [model filePathForGameWithName:uniqueGameName];
  NSError* error;
  BOOL success = [PathUtilities moveItemAtPath:documentInteractionFilePath overwritePath:uniqueFilePath error:&error];

  NSString* alertMessage;
  if (success)
  {
    alertMessage = [NSString stringWithFormat:@"The game has been imported and stored in the archive under this name:\n\n%@",
                    uniqueGameName];
  }
  else
  {
    // We don't know what exactly went wrong, so we delete both files to be on
    // the safe side
    [PathUtilities deleteItemIfExists:documentInteractionFilePath];
    [PathUtilities deleteItemIfExists:uniqueFilePath];

    alertMessage = [NSString stringWithFormat:@"The game could not be imported. Reason for the failure: %@",
                    [error localizedDescription]];
  }

  [self performSelectorOnMainThread:@selector(showAlert:) withObject:alertMessage waitUntilDone:YES];

  return success;
}

// -----------------------------------------------------------------------------
/// @brief Private helper for moveDocumentInteractionFileToArchive().
// -----------------------------------------------------------------------------
- (void) showAlert:(NSString*)alertMessage
{
  [[ApplicationDelegate sharedDelegate].window.rootViewController presentOkAlertWithTitle:@"Game imported"
                                                                                message:alertMessage];
}

// -----------------------------------------------------------------------------
/// @brief Private helper for doIt().
// -----------------------------------------------------------------------------
- (void) activateUIAreaArchive
{
  [[NSNotificationCenter defaultCenter] postNotificationName:archiveContentChanged object:nil];
  [MainUtility activateUIArea:UIAreaArchive];
}

@end

redpajama_set_name: RedPajamaGithub


text:
require 'midilib/sequence'

#DEFAULT_MIDI_TEST_FILE = 'NoFences.mid'

#DEFAULT_MIDI_TEST_FILE = 'C:\cygwin\home\Mark\composer-sketch-tool\test\midi-to-midi-event\eighths-time-signature.mid'
#DEFAULT_MIDI_TEST_FILE = 'C:\cygwin\home\Mark\composer-sketch-tool\test\midi-to-midi-event\held-over.mid'
#DEFAULT_MIDI_TEST_FILE = 'C:\cygwin\home\Mark\composer-sketch-tool\test\midi-to-midi-event\metronome-60.mid'
#DEFAULT_MIDI_TEST_FILE = 'C:\cygwin\home\Mark\composer-sketch-tool\test\midi-to-midi-event\rest-note.mid'
#DEFAULT_MIDI_TEST_FILE = 'C:\cygwin\home\Mark\composer-sketch-tool\test\midi-to-midi-event\rest-rest-eighth.mid'
DEFAULT_MIDI_TEST_FILE = 'C:\cygwin\home\Mark\composer-sketch-tool\test\midi-to-midi-event\single-note-G2.mid'
#DEFAULT_MIDI_TEST_FILE = 'C:\cygwin\home\Mark\composer-sketch-tool\test\midi-to-midi-event\syncopated-two-measures.mid'
#DEFAULT_MIDI_TEST_FILE = 'C:\cygwin\home\Mark\composer-sketch-tool\test\midi-to-midi-event\syncopated-two-tracks.mid'
#DEFAULT_MIDI_TEST_FILE = 'C:\cygwin\home\Mark\composer-sketch-tool\test\midi-to-midi-event\tempo-meter.mid'
#DEFAULT_MIDI_TEST_FILE = 'C:\cygwin\home\Mark\composer-sketch-tool\test\midi-to-midi-event\test-nonet.mid'
#DEFAULT_MIDI_TEST_FILE = 'C:\cygwin\home\Mark\composer-sketch-tool\test\midi-to-midi-event\two-channel.mid'
#DEFAULT_MIDI_TEST_FILE = 'C:\cygwin\home\Mark\composer-sketch-tool\test\midi-to-midi-event\two-measures.mid'

# Read from MIDI file
seq = MIDI::Sequence.new()

File.open(ARGV[0] || DEFAULT_MIDI_TEST_FILE, 'rb') { | file |
    # The block we pass in to Sequence.read is called at the end of every
    # track read. It is optional, but is useful for progress reports.
    seq.read(file) { | track, num_tracks, i |
	puts "read track #{track ? track.name : ''} (#{i} of #{num_tracks})"
    }
}

seq.each { | track |
    puts "*** track name \"#{track.name}\""
    puts "instrument name \"#{track.instrument}\""
    puts "#{track.events.length} events"
    track.each { | e |
	e.print_decimal_numbers = true # default = false (print hex)
	e.print_note_names = true # default = false (print note numbers)
	puts e
    }
}


text:
.pmd-checkbox-ripple-effect {
  -ms-transform: translateZ(0px);
  -webkit-transform: translateZ(0px);
  transform: translateZ(0px);
}

.checkbox .pmd-checkbox-ripple-effect {
  padding-left: 0;
}

.checkbox .pmd-checkbox {
  padding-left: 0;
}

.pmd-checkbox [type="checkbox"] {
  /* Disabled checkbox */
}

.pmd-checkbox [type="checkbox"]:not(:checked), .pmd-checkbox [type="checkbox"]:checked {
  position: absolute;
  left: -9999px;
}

.pmd-checkbox [type="checkbox"]:not(:checked) + .pmd-checkbox-label, .pmd-checkbox [type="checkbox"]:checked + .pmd-checkbox-label {
  position: relative;
  padding-left: 1.5625rem;
  cursor: pointer;
}

.pmd-checkbox [type="checkbox"]:not(:checked) + .pmd-checkbox-label:before, .pmd-checkbox [type="checkbox"]:checked + .pmd-checkbox-label:before {
  content: '';
  position: absolute;
  left: 0;
  top: 1px;
  width: 18px;
  height: 18px;
  border-width: 0.125rem;
  border-style: solid;
  border-radius: 0.125rem;
  border-color: rgba(0, 0, 0, 0.54);
}

.pmd-checkbox [type="checkbox"]:not(:checked) + .pmd-checkbox-label:after, .pmd-checkbox [type="checkbox"]:checked + .pmd-checkbox-label:after {
  color: #ffffff;
  border-image: none;
  border-style: none solid solid none;
  border-width: 0 0.125rem 0.125rem 0;
  content: "";
  display: table;
  height: 12px;
  left: 6px;
  position: absolute;
  top: 2px;
  width: 6px;
  transition: all .2s;
}

.pmd-checkbox [type="checkbox"]:checked + .pmd-checkbox-label:before {
  background-color: #4285f4;
  border-color: #4285f4;
}

.pmd-checkbox [type="checkbox"]:checked + .pmd-checkbox-label:after {
  opacity: 1;
  -ms-transform: rotate(45deg);
  -webkit-transform: rotate(45deg);
  transform: rotate(45deg);
}

.pmd-checkbox [type="checkbox"]:not(:checked) + .pmd-checkbox-label:after {
  opacity: 0;
  -ms-transform: rotate(45deg);
  -webkit-transform: rotate(45deg);
  transform: rotate(45deg);
}

.pmd-checkbox [type="checkbox"]:disabled:not(:checked) + .pmd-checkbox-label:before, .pmd-checkbox [type="checkbox"]:disabled:checked + .pmd-checkbox-label:before {
  box-shadow: none;
  border-color: rgba(0, 0, 0, 0.26);
  cursor: not-allowed;
}

.checkbox.disabled label.pmd-checkbox,
fieldset[disabled] .checkbox label.pmd-checkbox {
  color: rgba(0, 0, 0, 0.26);
}

/* hover style just for information */
.pmd-checkbox label:hover:before {
  border: 1px solid #4778d9;
}

.pmd-checkbox.pmd-checkbox-ripple-effect {
  position: relative;
}

.pmd-checkbox .pmd-checkboxwrap {
  position: absolute;
  z-index: -1;
  height: 40px;
  width: 40px;
  border-radius: 50%;
  overflow: hidden;
  top: -8px;
  left: -11px;
}

.checkbox-inline.pmd-checkbox {
  padding-left: 0;
}

.pmd-checkbox-ripple-effect .ink {
  background-color: rgba(0, 0, 0, 0.2);
}

.pmd-card-inverse .pmd-checkbox [type="checkbox"]:not(:checked) + .pmd-checkbox-label:before,
.pmd-card-inverse .pmd-checkbox [type="checkbox"] :checked + .pmd-checkbox-label:before {
  border-color: rgba(255, 255, 255, 0.54);
}

.pmd-card-inverse .pmd-checkbox [type="checkbox"]:checked + .pmd-checkbox-label:before {
  background-color: #4285f4;
}

.pmd-card-inverse .checkbox.disabled label.pmd-checkbox,
.pmd-card-inverse fieldset[disabled] .checkbox label.pmd-checkbox {
  color: rgba(255, 255, 255, 0.54);
}

/*# sourceMappingURL=checkbox.css.map */


text:
<!DOCTYPE html>

<link rel="import" href="../../../packages/spark_widgets/common/spark_widget.html"/>

<polymer-element name="spark-overlay"
     extends="spark-widget"
     attributes="arrow
                 modal
                 autoClose
                 animation
                 opened">

  <template>
    <link rel="stylesheet" href="spark_overlay.css">

    <template if="{{arrow != 'none'}}">

    </template>

    <content></content>
  </template>

</polymer-element>


text:
//=============================================================================================================

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "digitizersettreeitem.h"

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "digitizertreeitem.h"
#include "../../3dhelpers/renderable3Dentity.h"

#include <fiff/fiff_constants.h>
#include <fiff/fiff_dig_point.h>
#include <fiff/fiff_dig_point_set.h>

//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <Qt3DCore/QEntity>

//*************************************************************************************************************
//=============================================================================================================
// Eigen INCLUDES
//=============================================================================================================

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace DISP3DLIB;

//*************************************************************************************************************
//=============================================================================================================
// DEFINE GLOBAL METHODS
//=============================================================================================================

//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

DigitizerSetTreeItem::DigitizerSetTreeItem(int iType, const QString& text)
: AbstractTreeItem(iType, text)
{
    this->setEditable(false);
    this->setCheckable(true);
    this->setCheckState(Qt::Checked);
    this->setToolTip("Digitizer set item");
}

//*************************************************************************************************************

DigitizerSetTreeItem::~DigitizerSetTreeItem()
{
}

//*************************************************************************************************************

QVariant DigitizerSetTreeItem::data(int role) const
{
    return AbstractTreeItem::data(role);
}

//*************************************************************************************************************

void  DigitizerSetTreeItem::setData(const QVariant& value, int role)
{
    AbstractTreeItem::setData(value, role);
}

//*************************************************************************************************************

void DigitizerSetTreeItem::addData(const FIFFLIB::FiffDigPointSet& tDigitizer, Qt3DCore::QEntity* parent)
{
    //Add data
    bool state = false;

    //parsing the digitizer List
    QList<FIFFLIB::FiffDigPoint> tNasion;
    QList<FIFFLIB::FiffDigPoint> tLAP;
    QList<FIFFLIB::FiffDigPoint> tRAP;
    QList<FIFFLIB::FiffDigPoint> tHpi;
    QList<FIFFLIB::FiffDigPoint> tEeg;
    QList<FIFFLIB::FiffDigPoint> tExtra;

    for(int i = 0; i < tDigitizer.size(); ++i){
        switch (tDigitizer[i].kind) {
        case FIFFV_POINT_CARDINAL:
            switch (tDigitizer[i].ident) {
            case FIFFV_POINT_LPA:
                tLAP.append(tDigitizer[i]);
            break;
            case FIFFV_POINT_NASION:
                tNasion.append(tDigitizer[i]);
            break;
            case FIFFV_POINT_RPA:
                tRAP.append(tDigitizer[i]);
            break;
            default:
            break;
            }
            break;
        case FIFFV_POINT_HPI:
            tHpi.append(tDigitizer[i]);
            break;
        case FIFFV_POINT_EEG:
            tEeg.append(tDigitizer[i]);
            break;
        case FIFFV_POINT_EXTRA:
            tExtra.append(tDigitizer[i]);
            break;
        default:
            break;
        }
    }

    //Create items all new - A bit more inefficient but we do not run into the problem that the QEntity
    //is delted with deleteLater() which could let to deletion after the new Qentity has been created
    //Delete all childs first. We do this because we always want to start fresh with the newly added digitizer data.
    if(this->hasChildren()) {
        this->removeRows(0, this->rowCount());
    }

    QList<QStandardItem*> itemList;

    if (!tLAP.empty()){
        //Create a LAP digitizer item
        DigitizerTreeItem* digitizerItem = new DigitizerTreeItem(Data3DTreeModelItemTypes::DigitizerItem,"LAP");
        state = digitizerItem->addData(tLAP, parent);
        itemList << digitizerItem;
        itemList << new QStandardItem(digitizerItem->toolTip());
        this->appendRow(itemList);
        itemList.clear();
    }
    if (!tNasion.empty()){
        //Create a Nasion digitizer item
        DigitizerTreeItem* digitizerItem = new DigitizerTreeItem(Data3DTreeModelItemTypes::DigitizerItem,"Nasion");
        state = digitizerItem->addData(tNasion, parent);
        itemList << digitizerItem;
        itemList << new QStandardItem(digitizerItem->toolTip());
        this->appendRow(itemList);
        itemList.clear();
    }
    if (!tRAP.empty()){
        //Create a RAO digitizer item
        DigitizerTreeItem* digitizerItem = new DigitizerTreeItem(Data3DTreeModelItemTypes::DigitizerItem,"RAP");
        state = digitizerItem->addData(tRAP, parent);
        itemList << digitizerItem;
        itemList << new QStandardItem(digitizerItem->toolTip());
        this->appendRow(itemList);
        itemList.clear();
    }
    if (!tHpi.empty()){
        //Create a HPI digitizer item
        DigitizerTreeItem* digitizerItem = new DigitizerTreeItem(Data3DTreeModelItemTypes::DigitizerItem,"HPI");
        state = digitizerItem->addData(tHpi, parent);
        itemList << digitizerItem;
        itemList << new QStandardItem(digitizerItem->toolTip());
        this->appendRow(itemList);
        itemList.clear();
    }
    if (!tEeg.empty()){
        //Create a EEG digitizer item
        DigitizerTreeItem* digitizerItem = new DigitizerTreeItem(Data3DTreeModelItemTypes::DigitizerItem,"EEG/ECG");
        state = digitizerItem->addData(tEeg, parent);
        itemList << digitizerItem;
        itemList << new QStandardItem(digitizerItem->toolTip());
        this->appendRow(itemList);
        itemList.clear();
    }
    if (!tExtra.empty()){
        //Create a extra digitizer item
        DigitizerTreeItem* digitizerItem = new DigitizerTreeItem(Data3DTreeModelItemTypes::DigitizerItem,"Extra");
        state = digitizerItem->addData(tExtra, parent);
        itemList << digitizerItem;
        itemList << new QStandardItem(digitizerItem->toolTip());
        this->appendRow(itemList);
        itemList.clear();
    }

//    //Find exiting Digitizer Items and add data respectivley
//    QList<QStandardItem*> itemList = this->findChildren(Data3DTreeModelItemTypes::DigitizerItem);
//    bool bFoundCardinalItem = false;
//    bool bFoundHPIItem = false;
//    bool bFoundEEGItem = false;
//    bool bFoundExtraItem = false;

//    for(int i = 0; i < itemList.size(); ++i) {
//        DigitizerTreeItem* item = dynamic_cast<DigitizerTreeItem*>(itemList.at(i));

//        if(item->text() == "Cardinal" && !tCardinal.empty()) {
//            item->addData(tCardinal, parent);
//            bFoundCardinalItem = true;
//        }

//        if(item->text() == "HPI" && !tHpi.empty()) {
//            item->addData(tHpi, parent);
//            bFoundHPIItem = true;
//        }

//        if(item->text() == "EEG/ECG" && !tEeg.empty()) {
//            item->addData(tEeg, parent);
//            bFoundEEGItem = true;
//        }

//        if(item->text() == "Extra" && !tExtra.empty()) {
//            item->addData(tExtra, parent);
//            bFoundExtraItem = true;
//        }
//    }

//    //If not existent yet create here
//    if (!bFoundCardinalItem && !tCardinal.empty()){
//        //Create a cardinal digitizer item
//        QList<QStandardItem*> itemListCardinal;
//        DigitizerTreeItem* digitizerItem = new DigitizerTreeItem(Data3DTreeModelItemTypes::DigitizerItem,"Cardinal");
//        state = digitizerItem->addData(tCardinal, parent);
//        itemListCardinal << digitizerItem;
//        itemListCardinal << new QStandardItem(digitizerItem->toolTip());
//        this->appendRow(itemListCardinal);
//    }

//    if (!bFoundHPIItem && !tHpi.empty()){
//        //Create a hpi digitizer item
//        QList<QStandardItem*> itemListHPI;
//        DigitizerTreeItem* digitizerItem = new DigitizerTreeItem(Data3DTreeModelItemTypes::DigitizerItem,"HPI");
//        state = digitizerItem->addData(tHpi, parent);
//        itemListHPI << digitizerItem;
//        itemListHPI << new QStandardItem(digitizerItem->toolTip());
//        this->appendRow(itemListHPI);
//    }

//    if (!bFoundEEGItem && !tEeg.empty()){
//        //Create a eeg ecg digitizer item
//        QList<QStandardItem*> itemListEEG;
//        DigitizerTreeItem* digitizerItem = new DigitizerTreeItem(Data3DTreeModelItemTypes::DigitizerItem,"EEG/ECG");
//        state = digitizerItem->addData(tEeg, parent);
//        itemListEEG << digitizerItem;
//        itemListEEG << new QStandardItem(digitizerItem->toolTip());
//        this->appendRow(itemListEEG);
//    }

//    if (!bFoundExtraItem && !tExtra.empty()){
//        //Create a extra digitizer item
//        QList<QStandardItem*> itemListExtra;
//        DigitizerTreeItem* digitizerItem = new DigitizerTreeItem(Data3DTreeModelItemTypes::DigitizerItem,"Extra");
//        state = digitizerItem->addData(tExtra, parent);
//        itemListExtra << digitizerItem;
//        itemListExtra << new QStandardItem(digitizerItem->toolTip());
//        this->appendRow(itemListExtra);
//    }
}

//*************************************************************************************************************

void DigitizerSetTreeItem::onCheckStateChanged(const Qt::CheckState& checkState)
{
    for(int i = 0; i < this->rowCount(); ++i) {
        if(this->child(i)->isCheckable()) {
            this->child(i)->setCheckState(checkState);
        }
    }
}


text:
System.register(['../validation/utilities', '../validation/validation-locale'], function (_export) {
  'use strict';

  var Utilities, ValidationLocale, ValidationRulesCollection, SwitchCaseValidationRulesCollection;

  function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

  return {
    setters: [function (_validationUtilities) {
      Utilities = _validationUtilities.Utilities;
    }, function (_validationValidationLocale) {
      ValidationLocale = _validationValidationLocale.ValidationLocale;
    }],
    execute: function () {
      ValidationRulesCollection = (function () {
        function ValidationRulesCollection(config) {
          _classCallCheck(this, ValidationRulesCollection);

          this.isRequired = config ? config.getValue('allPropertiesAreMandatory') : false;
          this.validationRules = [];
          this.validationCollections = [];
          this.isRequiredMessage = null;
        }

        ValidationRulesCollection.prototype.validate = function validate(newValue, locale) {
          var _this = this;

          if (locale === undefined) {
            locale = ValidationLocale.Repository['default'];
          }
          newValue = Utilities.getValue(newValue);
          var executeRules = true;

          if (Utilities.isEmptyValue(newValue)) {
            if (this.isRequired) {
              return Promise.resolve({
                isValid: false,
                message: this.isRequiredMessage ? typeof this.isRequiredMessage === 'function' ? this.isRequiredMessage(newValue) : this.isRequiredMessage : locale.translate('isRequired'),
                failingRule: 'isRequired',
                latestValue: newValue
              });
            } else {
              executeRules = false;
            }
          }

          var checks = Promise.resolve({
            isValid: true,
            message: '',
            failingRule: null,
            latestValue: newValue
          });

          if (executeRules) {
            var _loop = function (i) {
              var rule = _this.validationRules[i];
              checks = checks.then(function (previousRuleResult) {
                if (previousRuleResult.isValid === false) {
                  return previousRuleResult;
                } else {
                  return rule.validate(newValue, locale).then(function (thisRuleResult) {
                    if (thisRuleResult === false) {
                      return {
                        isValid: false,
                        message: rule.explain(),
                        failingRule: rule.ruleName,
                        latestValue: newValue
                      };
                    } else {
                      if (!previousRuleResult.isValid) {
                        throw Error('ValidationRulesCollection.validate caught an unexpected result while validating it\'s chain of rules.');
                      }
                      return previousRuleResult;
                    }
                  });
                }
              });
            };

            for (var i = 0; i < this.validationRules.length; i++) {
              _loop(i);
            }
          }

          var _loop2 = function (i) {
            var validationCollection = _this.validationCollections[i];
            checks = checks.then(function (previousValidationResult) {
              if (previousValidationResult.isValid) return validationCollection.validate(newValue, locale);else return previousValidationResult;
            });
          };

          for (var i = 0; i < this.validationCollections.length; i++) {
            _loop2(i);
          }

          return checks;
        };

        ValidationRulesCollection.prototype.addValidationRule = function addValidationRule(validationRule) {
          if (validationRule.validate === undefined) throw new Error('That\'s not a valid validationRule');
          this.validationRules.push(validationRule);
        };

        ValidationRulesCollection.prototype.addValidationRuleCollection = function addValidationRuleCollection(validationRulesCollection) {
          this.validationCollections.push(validationRulesCollection);
        };

        ValidationRulesCollection.prototype.isNotEmpty = function isNotEmpty() {
          this.isRequired = true;
        };

        ValidationRulesCollection.prototype.canBeEmpty = function canBeEmpty() {
          this.isRequired = false;
        };

        ValidationRulesCollection.prototype.withMessage = function withMessage(message) {
          if (this.validationRules.length === 0) this.isRequiredMessage = message;else this.validationRules[this.validationRules.length - 1].withMessage(message);
        };

        return ValidationRulesCollection;
      })();

      _export('ValidationRulesCollection', ValidationRulesCollection);

      SwitchCaseValidationRulesCollection = (function () {
        function SwitchCaseValidationRulesCollection(conditionExpression, config) {
          _classCallCheck(this, SwitchCaseValidationRulesCollection);

          this.conditionExpression = conditionExpression;
          this.config = config;
          this.innerCollections = [];
          this.defaultCollection = new ValidationRulesCollection(this.config);
          this.caseLabel = '';
          this.defaultCaseLabel = { description: 'this is the case label for \'default\'' };
        }

        SwitchCaseValidationRulesCollection.prototype['case'] = function _case(caseLabel) {
          this.caseLabel = caseLabel;
          this.getCurrentCollection(caseLabel, true);
        };

        SwitchCaseValidationRulesCollection.prototype['default'] = function _default() {
          this.caseLabel = this.defaultCaseLabel;
        };

        SwitchCaseValidationRulesCollection.prototype.getCurrentCollection = function getCurrentCollection(caseLabel) {
          var createIfNotExists = arguments[1] === undefined ? false : arguments[1];

          if (caseLabel === this.defaultCaseLabel) return this.defaultCollection;
          var currentCollection = null;
          for (var i = 0; i < this.innerCollections.length; i++) {
            currentCollection = this.innerCollections[i];
            if (currentCollection.caseLabel === caseLabel) return currentCollection.collection;
          }
          if (createIfNotExists) {
            currentCollection = {
              caseLabel: caseLabel,
              collection: new ValidationRulesCollection(this.config)
            };
            this.innerCollections.push(currentCollection);
            return currentCollection.collection;
          }
          return null;
        };

        SwitchCaseValidationRulesCollection.prototype.validate = function validate(newValue, locale) {
          var collection = this.getCurrentCollection(this.conditionExpression(newValue));
          if (collection !== null) return collection.validate(newValue, locale);else return this.defaultCollection.validate(newValue, locale);
        };

        SwitchCaseValidationRulesCollection.prototype.addValidationRule = function addValidationRule(validationRule) {
          var currentCollection = this.getCurrentCollection(this.caseLabel, true);
          currentCollection.addValidationRule(validationRule);
        };

        SwitchCaseValidationRulesCollection.prototype.addValidationRuleCollection = function addValidationRuleCollection(validationRulesCollection) {
          var currentCollection = this.getCurrentCollection(this.caseLabel, true);
          currentCollection.addValidationRuleCollection(validationRulesCollection);
        };

        SwitchCaseValidationRulesCollection.prototype.isNotEmpty = function isNotEmpty() {
          var collection = this.getCurrentCollection(this.caseLabel);
          if (collection !== null) collection.isNotEmpty();else this.defaultCollection.isNotEmpty();
        };

        SwitchCaseValidationRulesCollection.prototype.canBeEmpty = function canBeEmpty() {
          var collection = this.getCurrentCollection(this.caseLabel);
          if (collection !== null) collection.canBeEmpty();else this.defaultCollection.canBeEmpty();
        };

        SwitchCaseValidationRulesCollection.prototype.withMessage = function withMessage(message) {
          var collection = this.getCurrentCollection(this.caseLabel);
          if (collection !== null) collection.withMessage(message);else this.defaultCollection.withMessage(message);
        };

        return SwitchCaseValidationRulesCollection;
      })();

      _export('SwitchCaseValidationRulesCollection', SwitchCaseValidationRulesCollection);
    }
  };
});


text:
<?php
	###################################################
	### expire_users.php							###
	### This program identifies users that have not	###
	### logged in recently and marks them expired.	###
	### A. Caravello 3/4/2016						###
	###################################################

	# Security - Only Register Module Operators or Managers can see other customers
	if ($GLOBALS['_SESSION_']->customer->can('expire customers')) {
		$expires = strtotime("-12 month", time());
		$date = date('m/d/Y',$expires);

		# Initialize Customers
		$customers = new RegisterCustomers();

		# Expire Aged Customers
		$count = $customers->expire($date);
		if ($customers->error)
			print "
Error expiring customers: ".$customers->error."
";
		else
			print "
$count Customers Expired before $date
";

		# Initialize Organizations
		$organizations = new RegisterOrganizations();

		# Expire Organizations w/o Active Users
		$count = $organizations->expire($date);
		if ($organizations->error)
			print "
Error expiring organizations: ".$organizations->error."
";
		else
			print "
$count Organizations Expired before $date
";
	}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Fregirardia vargasii Dunal

### Remarks
null


text:
/*
 * Do not modify this file. This file is generated from the sts-2011-06-15.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.SecurityToken.Model
{
    ///
    /// Contains the result of a successful call to the AssumeRole action, including
    /// temporary AWS credentials that can be used to make AWS requests.
    ///
    public partial class AssumeRoleResult : AmazonWebServiceResponse
    {
        private AssumedRoleUser _assumedRoleUser;
        private Credentials _credentials;
        private int? _packedPolicySize;

        ///
        /// Gets and sets the property AssumedRoleUser.
        /// <para>
        /// The Amazon Resource Name (ARN) and the assumed role ID, which are identifiers that
        /// you can use to refer to the resulting temporary security credentials. For example,
        /// you can reference these credentials as a principal in a resource-based policy by using
        /// the ARN or assumed role ID. The ARN and ID include the RoleSessionName
        /// that you specified when you called AssumeRole.
        /// </para>
        ///
        public AssumedRoleUser AssumedRoleUser
        {
            get { return this._assumedRoleUser; }
            set { this._assumedRoleUser = value; }
        }

        // Check to see if AssumedRoleUser property is set
        internal bool IsSetAssumedRoleUser()
        {
            return this._assumedRoleUser != null;
        }

        ///
        /// Gets and sets the property Credentials.
        /// <para>
        /// The temporary security credentials, which include an access key ID, a secret access
        /// key, and a security (or session) token.
        /// </para>
        ///
        public Credentials Credentials
        {
            get { return this._credentials; }
            set { this._credentials = value; }
        }

        // Check to see if Credentials property is set
        internal bool IsSetCredentials()
        {
            return this._credentials != null;
        }

        ///
        /// Gets and sets the property PackedPolicySize.
        /// <para>
        /// A percentage value that indicates the size of the policy in packed form. The service
        /// rejects any policy with a packed size greater than 100 percent, which means the policy
        /// exceeded the allowed space.
        /// </para>
        ///
        public int PackedPolicySize
        {
            get { return this._packedPolicySize.GetValueOrDefault(); }
            set { this._packedPolicySize = value; }
        }

        // Check to see if PackedPolicySize property is set
        internal bool IsSetPackedPolicySize()
        {
            return this._packedPolicySize.HasValue;
        }

    }
}


text:
@protocol PlayerDelegate;
@class Track;

@interface PlayerController : UITableViewController<RdioDelegate,RDPlayerDelegate>

@property (nonatomic, retain) RDPlayer *player;
@property (nonatomic, retain) Rdio *rdio;
@property (nonatomic, assign) id<PlayerDelegate> playerDelegate;
@property (nonatomic, assign) IBOutlet UIProgressView *progressView;
@property (nonatomic, assign) IBOutlet UIView *playerControlView;
@property (nonatomic, assign) IBOutlet UIButton *playButton;
@property (nonatomic, assign) IBOutlet UIButton *pauseButton;

- (id)initWithRdio:(Rdio *)rdio player:(RDPlayer *)player;

- (void)playTrack:(Track *)track;

- (IBAction)didTapPlayButton;
- (IBAction)didTapPauseButton;
@end


text:
This is an Objective-C wrapper around SQLite: http://sqlite.org/

## The FMDB Mailing List:
http://groups.google.com/group/fmdb

## Read the SQLite FAQ:
http://www.sqlite.org/faq.html

Since FMDB is built on top of SQLite, you're going to want to read this page top to bottom at least once.  And while you're there, make sure to bookmark the SQLite Documentation page: http://www.sqlite.org/docs.html

## Contributing
Do you have an awesome idea that deserves to be in FMDB?  You might consider pinging ccgus first to make sure he hasn't already ruled it out for some reason.  Otherwise pull requests are great, and make sure you stick to the local coding conventions.  However, please be patient and if you haven't heard anything from ccgus for a week or more, you might want to send a note asking what's up.

## CocoaPods

[![Dependency Status](https://www.versioneye.com/objective-c/fmdb/2.3/badge.svg?style=flat)](https://www.versioneye.com/objective-c/fmdb/2.3)
[![Reference Status](https://www.versioneye.com/objective-c/fmdb/reference_badge.svg?style=flat)](https://www.versioneye.com/objective-c/fmdb/references)

FMDB can be installed using [CocoaPods](https://cocoapods.org/).

```
pod 'FMDB'
# pod 'FMDB/FTS'   # FMDB with FTS
# pod 'FMDB/standalone'   # FMDB with latest SQLite amalgamation source
# pod 'FMDB/standalone/FTS'   # FMDB with latest SQLite amalgamation source and FTS
# pod 'FMDB/SQLCipher'   # FMDB with SQLCipher
```

**If using FMDB with [SQLCipher](https://www.zetetic.net/sqlcipher/) you must use the FMDB/SQLCipher subspec. The FMDB/SQLCipher subspec declares SQLCipher as a dependency, allowing FMDB to be compiled with the `-DSQLITE_HAS_CODEC` flag.**

## FMDB Class Reference:
http://ccgus.github.io/fmdb/html/index.html

## Automatic Reference Counting (ARC) or Manual Memory Management?
You can use either style in your Cocoa project.  FMDB will figure out which you are using at compile time and do the right thing.

## Usage
There are three main classes in FMDB:

1. `FMDatabase` - Represents a single SQLite database.  Used for executing SQL statements.
2. `FMResultSet` - Represents the results of executing a query on an `FMDatabase`.
3. `FMDatabaseQueue` - If you're wanting to perform queries and updates on multiple threads, you'll want to use this class.  It's described in the "Thread Safety" section below.

### Database Creation
An `FMDatabase` is created with a path to a SQLite database file.  This path can be one of these three:

1. A file system path.  The file does not have to exist on disk.  If it does not exist, it is created for you.
2. An empty string (`@""`).  An empty database is created at a temporary location.  This database is deleted with the `FMDatabase` connection is closed.
3. `NULL`.  An in-memory database is created.  This database will be destroyed with the `FMDatabase` connection is closed.

(For more information on temporary and in-memory databases, read the sqlite documentation on the subject: http://www.sqlite.org/inmemorydb.html)

```objc
FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];
```

### Opening

Before you can interact with the database, it must be opened.  Opening fails if there are insufficient resources or permissions to open and/or create the database.

```objc
if (![db open]) {
    [db release];
    return;
}
```

### Executing Updates

Any sort of SQL statement which is not a `SELECT` statement qualifies as an update.  This includes `CREATE`, `UPDATE`, `INSERT`, `ALTER`, `COMMIT`, `BEGIN`, `DETACH`, `DELETE`, `DROP`, `END`, `EXPLAIN`, `VACUUM`, and `REPLACE` statements (plus many more).  Basically, if your SQL statement does not begin with `SELECT`, it is an update statement.

Executing updates returns a single value, a `BOOL`.  A return value of `YES` means the update was successfully executed, and a return value of `NO` means that some error was encountered.  You may invoke the `-lastErrorMessage` and `-lastErrorCode` methods to retrieve more information.

### Executing Queries

A `SELECT` statement is a query and is executed via one of the `-executeQuery...` methods.

Executing queries returns an `FMResultSet` object if successful, and `nil` upon failure.  You should use the `-lastErrorMessage` and `-lastErrorCode` methods to determine why a query failed.

In order to iterate through the results of your query, you use a `while()` loop.  You also need to "step" from one record to the other.  With FMDB, the easiest way to do that is like this:

```objc
FMResultSet *s = [db executeQuery:@"SELECT * FROM myTable"];
while ([s next]) {
    //retrieve values for each record
}
```

You must always invoke `-[FMResultSet next]` before attempting to access the values returned in a query, even if you're only expecting one:

```objc
FMResultSet *s = [db executeQuery:@"SELECT COUNT(*) FROM myTable"];
if ([s next]) {
    int totalCount = [s intForColumnIndex:0];
}
```

`FMResultSet` has many methods to retrieve data in an appropriate format:

- `intForColumn:`
- `longForColumn:`
- `longLongIntForColumn:`
- `boolForColumn:`
- `doubleForColumn:`
- `stringForColumn:`
- `dateForColumn:`
- `dataForColumn:`
- `dataNoCopyForColumn:`
- `UTF8StringForColumnName:`
- `objectForColumnName:`

Each of these methods also has a `{type}ForColumnIndex:` variant that is used to retrieve the data based on the position of the column in the results, as opposed to the column's name.

Typically, there's no need to `-close` an `FMResultSet` yourself, since that happens when either the result set is deallocated, or the parent database is closed.

### Closing

When you have finished executing queries and updates on the database, you should `-close` the `FMDatabase` connection so that SQLite will relinquish any resources it has acquired during the course of its operation.

```objc
[db close];
```

### Transactions

`FMDatabase` can begin and commit a transaction by invoking one of the appropriate methods or executing a begin/end transaction statement.

### Multiple Statements and Batch Stuff

You can use `FMDatabase`'s executeStatements:withResultBlock: to do multiple statements in a string:

```objc
NSString *sql = @"create table bulktest1 (id integer primary key autoincrement, x text);"
                 "create table bulktest2 (id integer primary key autoincrement, y text);"
                 "create table bulktest3 (id integer primary key autoincrement, z text);"
                 "insert into bulktest1 (x) values ('XXX');"
                 "insert into bulktest2 (y) values ('YYY');"
                 "insert into bulktest3 (z) values ('ZZZ');";

success = [db executeStatements:sql];

sql = @"select count(*) as count from bulktest1;"
       "select count(*) as count from bulktest2;"
       "select count(*) as count from bulktest3;";

success = [self.db executeStatements:sql withResultBlock:^int(NSDictionary *dictionary) {
    NSInteger count = [dictionary[@"count"] integerValue];
    XCTAssertEqual(count, 1, @"expected one record for dictionary %@", dictionary);
    return 0;
}];
```

### Data Sanitization

When providing a SQL statement to FMDB, you should not attempt to "sanitize" any values before insertion.  Instead, you should use the standard SQLite binding syntax:

```sql
INSERT INTO myTable VALUES (?, ?, ?, ?)
```

The `?` character is recognized by SQLite as a placeholder for a value to be inserted.  The execution methods all accept a variable number of arguments (or a representation of those arguments, such as an `NSArray`, `NSDictionary`, or a `va_list`), which are properly escaped for you.

And, to use that SQL with the `?` placeholders from Objective-C:

```objc
NSInteger identifier = 42;
NSString *name = @"Liam O'Flaherty (\"the famous Irish author\")";
NSDate *date = [NSDate date];
NSString *comment = nil;

BOOL success = [db executeUpdate:@"INSERT INTO authors (identifier, name, date, comment) VALUES (?, ?, ?, ?)", @(identifier), name, date, comment ?: [NSNull null]];
if (!success) {
    NSLog(@"error = %@", [db lastErrorMessage]);
}
```

> **Note:** Fundamental data types, like the `NSInteger` variable `identifier`, should be as a `NSNumber` objects, achieved by using the `@` syntax, shown above. Or you can use the `[NSNumber numberWithInt:identifier]` syntax, too.
>
> Likewise, SQL `NULL` values should be inserted as `[NSNull null]`. For example, in the case of `comment` which might be `nil` (and is in this example), you can use the `comment ?: [NSNull null]` syntax, which will insert the string if `comment` is not `nil`, but will insert `[NSNull null]` if it is `nil`.

In Swift, you would use `executeUpdate(values:)`, which not only is a concise Swift syntax, but also `throws` errors for proper Swift 2 error handling:

```swift
do {
    let identifier = 42
    let name = "Liam O'Flaherty (\"the famous Irish author\")"
    let date = NSDate()
    let comment: String? = nil

    try db.executeUpdate("INSERT INTO authors (identifier, name, date, comment) VALUES (?, ?, ?, ?)", values: [identifier, name, date, comment ?? NSNull()])
} catch {
    print("error = \(error)")
}
```

> **Note:** In Swift, you don't have to wrap fundamental numeric types like you do in Objective-C. But if you are going to insert an optional string, you would probably use the `comment ?? NSNull()` syntax (i.e., if it is `nil`, use `NSNull`, otherwise use the string).

Alternatively, you may use named parameters syntax:

```sql
INSERT INTO authors (identifier, name, date, comment) VALUES (:identifier, :name, :date, :comment)
```

The parameters *must* start with a colon. SQLite itself supports other characters, but internally the dictionary keys are prefixed with a colon, do **not** include the colon in your dictionary keys.

```objc
NSDictionary *arguments = @{@"identifier": @(identifier), @"name": name, @"date": date, @"comment": comment ?: [NSNull null]};
BOOL success = [db executeUpdate:@"INSERT INTO authors (identifier, name, date, comment) VALUES (:identifier, :name, :date, :comment)" withParameterDictionary:arguments];
if (!success) {
    NSLog(@"error = %@", [db lastErrorMessage]);
}
```

The key point is that one should not use `NSString` method `stringWithFormat` to manually insert values into the SQL statement, itself. Nor should one Swift string interpolation to insert values into the SQL. Use `?` placeholders for values to be inserted into the database (or used in `WHERE` clauses in `SELECT` statements).

Using FMDatabaseQueue and Thread Safety.

Using a single instance of `FMDatabase` from multiple threads at once is a bad idea.  It has always been OK to make a `FMDatabase` object *per thread*.  Just don't share a single instance across threads, and definitely not across multiple threads at the same time.  Bad things will eventually happen and you'll eventually get something to crash, or maybe get an exception, or maybe meteorites will fall out of the sky and hit your Mac Pro.  *This would suck*.

**So don't instantiate a single `FMDatabase` object and use it across multiple threads.**

Instead, use `FMDatabaseQueue`. Instantiate a single `FMDatabaseQueue` and use it across multiple threads. The `FMDatabaseQueue` object will synchronize and coordinate access across the multiple threads. Here's how to use it:

First, make your queue.

```objc
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath];
```

Then use it like so:

```objc
[queue inDatabase:^(FMDatabase *db) {
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @1];
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @2];
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @3];

    FMResultSet *rs = [db executeQuery:@"select * from foo"];
    while ([rs next]) {
        …
    }
}];
```

An easy way to wrap things up in a transaction can be done like this:

```objc
[queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @1];
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @2];
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @3];

    if (whoopsSomethingWrongHappened) {
        *rollback = YES;
        return;
    }
    // etc…
    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @4];
}];
```

The Swift equivalent would be:

```swift
queue.inTransaction { db, rollback in
    do {
        try db.executeUpdate("INSERT INTO myTable VALUES (?)", values: [1])
        try db.executeUpdate("INSERT INTO myTable VALUES (?)", values: [2])
        try db.executeUpdate("INSERT INTO myTable VALUES (?)", values: [3])

        if whoopsSomethingWrongHappened {
            rollback.memory = true
            return
        }

        try db.executeUpdate("INSERT INTO myTable VALUES (?)", values: [4])
    } catch {
        rollback.memory = true
        print(error)
    }
}
```

`FMDatabaseQueue` will run the blocks on a serialized queue (hence the name of the class).  So if you call `FMDatabaseQueue`'s methods from multiple threads at the same time, they will be executed in the order they are received.  This way queries and updates won't step on each other's toes, and every one is happy.

**Note:** The calls to `FMDatabaseQueue`'s methods are blocking.  So even though you are passing along blocks, they will **not** be run on another thread.

## Making custom sqlite functions, based on blocks.

You can do this!  For an example, look for `-makeFunctionNamed:` in main.m

## Swift

You can use FMDB in Swift projects too.

To do this, you must:

1. Copy the relevant `.m` and `.h` files from the FMDB `src` folder into your project.

 You can copy all of them (which is easiest), or only the ones you need. Likely you will need [`FMDatabase`](http://ccgus.github.io/fmdb/html/Classes/FMDatabase.html) and [`FMResultSet`](http://ccgus.github.io/fmdb/html/Classes/FMResultSet.html) at a minimum. [`FMDatabaseAdditions`](http://ccgus.github.io/fmdb/html/Categories/FMDatabase+FMDatabaseAdditions.html) provides some very useful convenience methods, so you will likely want that, too. If you are doing multithreaded access to a database, [`FMDatabaseQueue`](http://ccgus.github.io/fmdb/html/Classes/FMDatabaseQueue.html) is quite useful, too. If you choose to not copy all of the files from the `src` directory, though, you may want to update `FMDB.h` to only reference the files that you included in your project.

 Note, if you're copying all of the files from the `src` folder into to your project (which is recommended), you may want to drag the individual files into your project, not the folder, itself, because if you drag the folder, you won't be prompted to add the bridging header (see next point).

2. If prompted to create a "bridging header", you should do so. If not prompted and if you don't already have a bridging header, add one.

 For more information on bridging headers, see [Swift and Objective-C in the Same Project](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-XID_76).

3. In your bridging header, add a line that says:
    ```objc
    #import "FMDB.h"
    ```

4. Use the variations of `executeQuery` and `executeUpdate` with the `sql` and `values` parameters with `try` pattern, as shown below. These renditions of `executeQuery` and `executeUpdate` both `throw` errors in true Swift 2 fashion.

If you do the above, you can then write Swift code that uses `FMDatabase`. For example:

```swift
let documents = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
let fileURL = documents.URLByAppendingPathComponent("test.sqlite")

let database = FMDatabase(path: fileURL.path)

if !database.open() {
    print("Unable to open database")
    return
}

do {
    try database.executeUpdate("create table test(x text, y text, z text)", values: nil)
    try database.executeUpdate("insert into test (x, y, z) values (?, ?, ?)", values: ["a", "b", "c"])
    try database.executeUpdate("insert into test (x, y, z) values (?, ?, ?)", values: ["e", "f", "g"])

    let rs = try database.executeQuery("select x, y, z from test", values: nil)
    while rs.next() {
        let x = rs.stringForColumn("x")
        let y = rs.stringForColumn("y")
        let z = rs.stringForColumn("z")
        print("x = \(x); y = \(y); z = \(z)")
    }
} catch let error as NSError {
    print("failed: \(error.localizedDescription)")
}

database.close()
```

## History

The history and changes are availbe on its [GitHub page](https://github.com/ccgus/fmdb) and are summarized in the "CHANGES_AND_TODO_LIST.txt" file.

## Contributors

The contributors to FMDB are contained in the "Contributors.txt" file.

## Additional projects using FMDB, which might be interesting to the discerning developer.

 * FMDBMigrationManager, A SQLite schema migration management system for FMDB: https://github.com/layerhq/FMDBMigrationManager
 * FCModel, An alternative to Core Data for people who like having direct SQL access: https://github.com/marcoarment/FCModel

## Quick notes on FMDB's coding style

Spaces, not tabs.  Square brackets, not dot notation.  Look at what FMDB already does with curly brackets and such, and stick to that style.

## Reporting bugs

Reduce your bug down to the smallest amount of code possible.  You want to make it super easy for the developers to see and reproduce your bug.  If it helps, pretend that the person who can fix your bug is active on shipping 3 major products, works on a handful of open source projects, has a newborn baby, and is generally very very busy.

And we've even added a template function to main.m (FMDBReportABugFunction) in the FMDB distribution to help you out:

* Open up fmdb project in Xcode.
* Open up main.m and modify the FMDBReportABugFunction to reproduce your bug.
    * Setup your table(s) in the code.
    * Make your query or update(s).
    * Add some assertions which demonstrate the bug.

Then you can bring it up on the FMDB mailing list by showing your nice and compact FMDBReportABugFunction, or you can report the bug via the github FMDB bug reporter.

**Optional:**

Figure out where the bug is, fix it, and send a patch in or bring that up on the mailing list.  Make sure all the other tests run after your modifications.

## Support

The support channels for FMDB are the mailing list (see above), filing a bug here, or maybe on Stack Overflow.  So that is to say, support is provided by the community and on a voluntary basis.

FMDB development is overseen by Gus Mueller of Flying Meat.  If FMDB been helpful to you, consider purchasing an app from FM or telling all your friends about it.

## License

The license for FMDB is contained in the "License.txt" file.

If you happen to come across either Gus Mueller or Rob Ryan in a bar, you might consider purchasing a drink of their choosing if FMDB has been useful to you.

(The drink is for them of course, shame on you for trying to keep it.)


text:
const { execSync, spawn } = require('child_process');
const { join } = require('path');

const ANNOUNCEMENT_FILENAME = join(__dirname, '../../assets/done.mp3');

function has(cmd) {
  try {
    execSync('which ' + cmd + ' 2>/dev/null 2>/dev/null');
    return true;
  } catch (err) {
    return false;
  }
}

module.exports.announce = () => {
  const args = [ANNOUNCEMENT_FILENAME];
  let bin = 'play';

  if (process.platform == 'darwin') {
    bin = 'afplay';
  }

  if (has('mplayer')) {
    bin = 'mplayer';
    args.unshift('-really-quiet');
  }

  spawn(bin, args);
};


text:
#if !defined(BOOST_PP_IS_ITERATING)
#if !defined(BOOST_FUSION_SEQUENCE_DEQUE_DETAIL_DEQUE_KEYED_VALUES_CALL_04122006_2211)
#define BOOST_FUSION_SEQUENCE_DEQUE_DETAIL_DEQUE_KEYED_VALUES_CALL_04122006_2211

#if defined(BOOST_FUSION_HAS_VARIADIC_DEQUE)
#error "C++03 only! This file should not have been included"
#endif

#include <boost/preprocessor/iterate.hpp>
#include <boost/preprocessor/repetition/enum_shifted_params.hpp>
#include <boost/preprocessor/repetition/enum_shifted.hpp>
#include <boost/preprocessor/repetition/enum_binary_params.hpp>

#define FUSION_HASH #
#define FUSION_DEQUE_KEYED_VALUES_FORWARD(z, n, _)    \
   std::forward<BOOST_PP_CAT(T_, n)>(BOOST_PP_CAT(t, n))

#define BOOST_PP_FILENAME_1 \
    <boost/fusion/container/deque/detail/cpp03/deque_keyed_values_call.hpp>
#define BOOST_PP_ITERATION_LIMITS (1, FUSION_MAX_DEQUE_SIZE)
#include BOOST_PP_ITERATE()

#undef FUSION_DEQUE_KEYED_VALUES_FORWARD
#undef FUSION_HASH
#endif
#else

#define N BOOST_PP_ITERATION()

        BOOST_FUSION_GPU_ENABLED
        static type construct(BOOST_PP_ENUM_BINARY_PARAMS(N, typename add_reference<typename add_const<T, >::type>::type t))
        {
            return type(t0,
                        deque_keyed_values_impl<
                        next_index
        #if N > 1
                        , BOOST_PP_ENUM_SHIFTED_PARAMS(N, T)
        #endif
                        >::construct(BOOST_PP_ENUM_SHIFTED_PARAMS(N, t)));
        }

#if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES)
FUSION_HASH if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
#endif
#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) || \
    (defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES))
        template <BOOST_PP_ENUM_PARAMS(N, typename T_)>
        BOOST_FUSION_GPU_ENABLED
        static type forward_(BOOST_PP_ENUM_BINARY_PARAMS(N, T_, && t))
        {
            return type(std::forward<T_0>(t0),
                        deque_keyed_values_impl<
                        next_index
        #if N > 1
                        , BOOST_PP_ENUM_SHIFTED_PARAMS(N, T_)
        #endif
                        >::forward_(BOOST_PP_ENUM_SHIFTED(N, FUSION_DEQUE_KEYED_VALUES_FORWARD, _)));
        }
#endif
#if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES)
FUSION_HASH endif
#endif

#undef N
#endif