text:
package org.gedcomx.agent;

import org.gedcomx.common.CustomEntity;
import org.gedcomx.common.ResourceReference;
import org.gedcomx.common.TextValue;
import org.gedcomx.common.URI;
import org.gedcomx.conclusion.Identifier;
import org.gedcomx.rt.json.GedcomJacksonModule;
import org.junit.Test;

import javax.xml.bind.JAXBContext;
import java.util.ArrayList;
import java.util.Arrays;

import static org.gedcomx.rt.SerializationUtil.processThroughJson;
import static org.gedcomx.rt.SerializationUtil.processThroughXml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

public class AgentTest {
  @Test
  public void testExtensionsThruXML() throws Exception {
    Agent agent = new Agent();
    agent.setId("1234");
    agent.addExtensionElement(new CustomEntity("4321"));
    agent.addExtensionElement(new CustomEntity("5432"));
    agent.getExtensionElements().add(new CustomEntity("6543"));
    agent = processThroughXml(agent, Agent.class, JAXBContext.newInstance(Agent.class, CustomEntity.class));
    assertEquals(agent.getExtensionElements().size(), 3);
    assertNull(agent.findExtensionOfType(String.class));
    assertEquals(agent.findExtensionOfType(CustomEntity.class).getId(), "4321");
    assertEquals(agent.findExtensionsOfType(String.class).size(), 0);
    assertEquals(agent.findExtensionsOfType(CustomEntity.class).size(), 3);
    assertEquals(agent.findExtensionsOfType(CustomEntity.class).get(1).getId(), "5432");
    assertEquals(((CustomEntity) agent.getExtensionElements().get(2)).getId(), "6543");

    agent.setExtensionElements(null);
    assertNull(agent.getExtensionElements());
    assertNull(agent.findExtensionOfType(CustomEntity.class));
    assertEquals(agent.findExtensionsOfType(CustomEntity.class).size(), 0);
  }

  @Test
  public void testExtensionsThruJSON() throws Exception {
    Agent agent = new Agent();
    agent.setId("1234");
    agent.addExtensionElement(new CustomEntity("4321"));
    agent.addExtensionElement(new CustomEntity("5432"));
    agent.getExtensionElements().add(new CustomEntity("6543"));
    agent = processThroughJson(agent, Agent.class, GedcomJacksonModule.createObjectMapper(Agent.class, CustomEntity.class));
    assertEquals(agent.getExtensionElements().size(), 3);
    assertEquals(agent.findExtensionOfType(CustomEntity.class).getId(), "4321");
    assertEquals(agent.findExtensionsOfType(String.class).size(), 0);
    assertEquals(agent.findExtensionsOfType(CustomEntity.class).size(), 3);
    assertEquals(agent.findExtensionsOfType(CustomEntity.class).get(1).getId(), "5432");
    assertEquals(((CustomEntity) agent.getExtensionElements().get(2)).getId(), "6543");

    agent.setExtensionElements(null);
    assertNull(agent.getExtensionElements());
    assertNull(agent.findExtensionOfType(CustomEntity.class));
    assertEquals(agent.findExtensionsOfType(CustomEntity.class).size(), 0);
  }

  @Test
  public void testPersonXml() throws Exception {
    Agent person = createPerson();
    person = processThroughXml(person);
    assertPerson(person);
  }

  /**
   * tests id json
   */
  @Test
  public void testPersonJson() throws Exception {
    Agent person = createPerson();
    person = processThroughJson(person);
    assertPerson(person);
  }

  private Agent createPerson() {
    Agent person = new Agent();
    person.setAccounts(new ArrayList<OnlineAccount>());
    OnlineAccount account = new OnlineAccount();
    account.setAccountName("account name");
    account.setServiceHomepage(new ResourceReference());
    account.getServiceHomepage().setResource(URI.create("http://familysearch.org"));
    person.getAccounts().add(account);
    person.setAddresses(new ArrayList<Address>());
    Address address = new Address();
    address.setValue("street1\nstreet2\nstreet3\ncity UT, 88888\ncountry");
    address.setCity("city");
    address.setCountry("country");
    address.setPostalCode("88888");
    address.setStateOrProvince("UT");
    address.setStreet("street1");
    address.setStreet2("street2");
    address.setStreet3("street3");
    person.getAddresses().add(address);
    person.setEmails(new ArrayList<ResourceReference>());
    ResourceReference email = new ResourceReference();
    email.setResource(URI.create("mailto:heatonra@familysearch.org"));
    person.getEmails().add(email);
    person.setHomepage(new ResourceReference(URI.create("http://familysearch.org/heatonra")));
    person.setNames(Arrays.asList(new TextValue("Ryan Heaton")));
    person.setOpenid(new ResourceReference(URI.create("openid")));
    person.setPhones(new ArrayList<ResourceReference>());
    Identifier identifier = new Identifier();
    identifier.setValue(URI.create("identifier"));
    person.setIdentifiers(Arrays.asList(identifier));
    ResourceReference phone = new ResourceReference();
    phone.setResource(URI.create("tel:+18012401000"));
    person.getPhones().add(phone);
    return person;
  }

  private void assertPerson(Agent person) {
    assertEquals(1, person.getAccounts().size());
    assertEquals("account name", person.getAccounts().get(0).getAccountName());
    assertEquals("http://familysearch.org", person.getAccounts().get(0).getServiceHomepage().getResource().toString());
    assertEquals(1, person.getAddresses().size());
    assertEquals("street1\nstreet2\nstreet3\ncity UT, 88888\ncountry", person.getAddresses().get(0).getValue());
    assertEquals("city", person.getAddresses().get(0).getCity());
    assertEquals("country", person.getAddresses().get(0).getCountry());
    assertEquals("88888", person.getAddresses().get(0).getPostalCode());
    assertEquals("UT", person.getAddresses().get(0).getStateOrProvince());
    assertEquals("street1", person.getAddresses().get(0).getStreet());
    assertEquals("street2", person.getAddresses().get(0).getStreet2());
    assertEquals("street3", person.getAddresses().get(0).getStreet3());
    assertEquals(1, person.getEmails().size());
    assertEquals("mailto:heatonra@familysearch.org", person.getEmails().get(0).getResource().toString());
    assertEquals("http://familysearch.org/heatonra", person.getHomepage().getResource().toString());
    assertEquals("Ryan Heaton", person.getName().getValue());
    assertEquals("openid", person.getOpenid().getResource().toString());
    assertEquals(1, person.getPhones().size());
    assertEquals("tel:+18012401000", person.getPhones().get(0).getResource().toString());
    assertEquals("identifier", person.getIdentifiers().get(0).getValue().toString());
  }
}


text:
package ameba.message.internal;

import ameba.message.internal.streaming.*;

import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;

/**
 *
ExtendedMessageFeature class.

 *
 * @author icode
 *
 */
public class ExtendedMessageFeature implements Feature {
    /**
     * {@inheritDoc}
     */
    @Override
    public boolean configure(FeatureContext context) {
        if (!context.getConfiguration().isRegistered(TextMessageBodyWriter.class)) {
            context.register(TextMessageBodyWriter.class);
        }

        if (!context.getConfiguration().isRegistered(CaptchaWriterInterceptor.class)) {
            context.register(CaptchaWriterInterceptor.class);
        }

        if (!context.getConfiguration().isRegistered(PathMessageBodyWriter.class)) {
            context.register(PathMessageBodyWriter.class);
        }

        if (!context.getConfiguration().isRegistered(ContentLengthWriterInterceptor.class)) {
            context.register(ContentLengthWriterInterceptor.class);
        }

        if (!context.getConfiguration().isRegistered(StreamingWriterInterceptor.class)) {
            context.register(StreamingWriterInterceptor.class);
            // streaming process
            context.register(BlobStreamingProcess.class);
            context.register(BytesStreamingProcess.class);
            context.register(ClobStreamingProcess.class);
            context.register(FileStreamingProcess.class);
            context.register(InputStreamingProcess.class);
            context.register(PathStreamingProcess.class);
        }

        return false;
    }
}

redpajama_set_name: RedPajamaGithub


text:
define(['jquery', 'asyncStorage', 'recorder', 'streamer', 'local'],
  function ($, asyncStorage, Recorder, Streamer, local) {
  'use strict';

  // This is where we change the time lapse count
  var interval = 0.2; // In seconds
  var canvas = document.createElement('canvas');
  var streamer = new Streamer();
  var recorder = new Recorder();

  var preview = $('#video-preview');
  var previewEl = $('.previews');
  var debug = $('.debugger');

  var media = [];

  streamer.startVideo(function (err, data) {
    if (err) {
      console.log(err);
    } else {
      streamer.video = data.videoElement;
      streamer.video.width = data.videoElement.width;
      streamer.video.height = data.videoElement.height;
      preview.append(streamer.video);
      streamer.video.play();
    }
  });

  var saveFrame = function (img, callback) {
    media.push({
      frame: img.src,
      geo: recorder.lat + ',' + recorder.lon,
      description: '',
      created: Math.round(new Date().getTime() / 1000)
    });

    callback();
  };

  var captureFrame = function (pendingFrames, callback) {
    pendingFrames --;
    var currFrame = (pendingFrames - 1) + pendingFrames;
    var img = document.createElement('img');

    canvas.getContext('2d').drawImage(streamer.video, 0, 0, canvas.width, canvas.height);
    img.src = canvas.toDataURL('image/jpeg', 0.4);

    if (pendingFrames > 0) {
      setTimeout(function () {
        saveFrame(img, function () {
          captureFrame(pendingFrames, callback);
        });
      }, interval * 1000); // timeouts are in milliseconds
    } else {
      var created = Date.now();
      asyncStorage.getItem('frameList', function (frames) {
        if (frames) {
          frames.unshift(created);
          asyncStorage.setItem('frameList', frames);
        } else {
          asyncStorage.setItem('frameList', [created]);
        }
      });

      recorder.videoFrames.id = created;
      asyncStorage.setItem('frames[' + recorder.videoFrames.id + ']', recorder.videoFrames);
      callback(true);
    }
  };

  var getScreenshot = function (callback) {
    var pendingFrames = 49;

    if (streamer.video) {
      canvas.width = streamer.video.width;
      canvas.height = streamer.video.height;

      captureFrame(pendingFrames, callback);
    }
  };

  $('#record').click(function (ev) {
    ev.preventDefault();
    var self = $(this);

    previewEl.empty();
    self.addClass('on');
    debug.append('
start recording
');
    recorder.video = streamer.video;
    recorder.getScreenshot(function () {
      self.removeClass('on');
    }, 100, recorder.interval);
  });

  $('.uploader').click(function (ev) {
    ev.preventDefault();

    var isDeleted = false;

    asyncStorage.getItem('frameList', function (frames) {
      console.log(frames)
      frames.forEach(function (f) {
        asyncStorage.getItem('frames[' + f + ']', function (data) {
          $.ajax({
            url: local.url + '/api/add/post',
            crossDomain: true,
            data: { api: local.apiKey, frames: data },
            dataType: 'json',
            success: function (d) {
              console.log('uploaded: ', d);
              asyncStorage.removeItem('frames[' + f + ']');
              isDeleted = true;
            },
            error: function (xhr, status, error) {
              console.log(status);
            }
          });
        });
      });

      if (isDeleted) {
        asyncStorage.removeItem('frameList');
      }
    });
  });
});


text:
VERSION = 0.1.17
BROWSERIFY = node ./node_modules/browserify/bin/cmd.js
MOCHA = ./node_modules/.bin/mocha
UGLIFYJS = ./node_modules/.bin/uglifyjs
BANNER = "/*! lil-http - v$(VERSION) - MIT License - https://github.com/lil-js/http */"
MOCHA_PHANTOM = ./node_modules/.bin/mocha-phantomjs

define release
	VERSION=`node -pe "require('./bower.json').version"` && \
	NEXT_VERSION=`node -pe "require('semver').inc(\"$$VERSION\", '$(1)')"` && \
	node -e "\
		var j = require('./bower.json');\
		j.version = \"$$NEXT_VERSION\";\
		var s = JSON.stringify(j, null, 2);\
		require('fs').writeFileSync('./bower.json', s);" && \
	node -e "\
		var j = require('./component.json');\
		j.version = \"$$NEXT_VERSION\";\
		var s = JSON.stringify(j, null, 2);\
		require('fs').writeFileSync('./component.json', s);" && \
	git commit -am "release $$NEXT_VERSION" && \
	git tag "$$NEXT_VERSION" -m "Version $$NEXT_VERSION"
endef

default: all
all: test
browser: uglify
test: browser mocha

uglify:
	$(UGLIFYJS) http.js --mangle --preamble $(BANNER) --source-map http.min.js.map --source-map-url http://cdn.rawgit.com/lil-js/http/$(VERSION)/http.min.js.map > http.min.js

mocha:
	bash ./test/run.sh 8888

loc:
	wc -l http.js

gzip:
	gzip -c http.js | wc -c

release:
	@$(call release, patch)

release-minor:
	@$(call release, minor)

publish: browser release
	git push --tags origin HEAD:master


text:
import ctypes

from os_win.utils.winapi import wintypes

lib_handle = None

class VIRTUAL_STORAGE_TYPE(ctypes.Structure):
    _fields_ = [
        ('DeviceId', wintypes.DWORD),
        ('VendorId', wintypes.GUID)
    ]

PVIRTUAL_STORAGE_TYPE = ctypes.POINTER(VIRTUAL_STORAGE_TYPE)

class _RESIZE_VIRTUAL_DISK_PARAMETERS_V1(ctypes.Structure):
    _fields_ = [
        ('NewSize', wintypes.ULONGLONG)
    ]

# Only V1 is used, we avoid defining a union.
class RESIZE_VIRTUAL_DISK_PARAMETERS(ctypes.Structure):
    _fields_ = [
        ('Version', wintypes.DWORD),
        ('Version1', _RESIZE_VIRTUAL_DISK_PARAMETERS_V1)
    ]

PRESIZE_VIRTUAL_DISK_PARAMETERS = ctypes.POINTER(
    RESIZE_VIRTUAL_DISK_PARAMETERS)

class _OPEN_VIRTUAL_DISK_PARAMETERS_V1(ctypes.Structure):
    _fields_ = [
        ('RWDepth', wintypes.ULONG),
    ]

class _OPEN_VIRTUAL_DISK_PARAMETERS_V2(ctypes.Structure):
    _fields_ = [
        ('GetInfoOnly', wintypes.BOOL),
        ('ReadOnly', wintypes.BOOL),
        ('ResiliencyGuid', wintypes.GUID)
    ]

class _OPEN_VIRTUAL_DISK_PARAMETERS_U(ctypes.Union):
    _fields_ = [
        ('Version1', _OPEN_VIRTUAL_DISK_PARAMETERS_V1),
        ('Version2', _OPEN_VIRTUAL_DISK_PARAMETERS_V2)
    ]

class OPEN_VIRTUAL_DISK_PARAMETERS(ctypes.Structure):
    _anonymous_ = ['_parameters']
    _fields_ = [
        ('Version', wintypes.DWORD),
        ('_parameters', _OPEN_VIRTUAL_DISK_PARAMETERS_U)
    ]

POPEN_VIRTUAL_DISK_PARAMETERS = ctypes.POINTER(
    OPEN_VIRTUAL_DISK_PARAMETERS)

class _MERGE_VIRTUAL_DISK_PARAMETERS_V1(ctypes.Structure):
    _fields_ = [
        ('MergeDepth', wintypes.ULONG)
    ]

# Only V1 is used, we avoid defining a union.
class MERGE_VIRTUAL_DISK_PARAMETERS(ctypes.Structure):
    _fields_ = [
        ('Version', wintypes.DWORD),
        ('Version1', _MERGE_VIRTUAL_DISK_PARAMETERS_V1)
    ]

PMERGE_VIRTUAL_DISK_PARAMETERS = ctypes.POINTER(
    MERGE_VIRTUAL_DISK_PARAMETERS)

class _CREATE_VIRTUAL_DISK_PARAMETERS_V2(ctypes.Structure):
    _fields_ = [
        ('UniqueId', wintypes.GUID),
        ('MaximumSize', wintypes.ULONGLONG),
        ('BlockSizeInBytes', wintypes.ULONG),
        ('SectorSizeInBytes', wintypes.ULONG),
        ('PhysicalSectorSizeInBytes', wintypes.ULONG),
        ('ParentPath', wintypes.LPCWSTR),
        ('SourcePath', wintypes.LPCWSTR),
        ('OpenFlags', wintypes.DWORD),
        ('ParentVirtualStorageType', VIRTUAL_STORAGE_TYPE),
        ('SourceVirtualStorageType', VIRTUAL_STORAGE_TYPE),
        ('ResiliencyGuid', wintypes.GUID)
    ]

# Only V2 is used, we avoid defining a union.
class CREATE_VIRTUAL_DISK_PARAMETERS(ctypes.Structure):
    _fields_ = [
        ('Version', wintypes.DWORD),
        ('Version2', _CREATE_VIRTUAL_DISK_PARAMETERS_V2)
    ]

PCREATE_VIRTUAL_DISK_PARAMETERS = ctypes.POINTER(
    CREATE_VIRTUAL_DISK_PARAMETERS)

class _VHD_INFO_SIZE(ctypes.Structure):
    _fields_ = [
        ("VirtualSize", wintypes.ULARGE_INTEGER),
        ("PhysicalSize", wintypes.ULARGE_INTEGER),
        ("BlockSize", wintypes.ULONG),
        ("SectorSize", wintypes.ULONG)
    ]

class _VHD_INFO_PARENT_LOCATION(ctypes.Structure):
    _fields_ = [
        ('ParentResolved', wintypes.BOOL),
        ('ParentPath', wintypes.WCHAR * 512)
    ]

class _VHD_INFO_PHYSICAL_DISK(ctypes.Structure):
    _fields_ = [
        ("LogicalSectorSize", wintypes.ULONG),
        ("PhysicalSectorSize", wintypes.ULONG),
        ("IsRemote", wintypes.BOOL)
    ]

class _VHD_INFO(ctypes.Union):
    _fields_ = [
        ("Size", _VHD_INFO_SIZE),
        ("Identifier", wintypes.GUID),
        ("ParentLocation", _VHD_INFO_PARENT_LOCATION),
        ("ParentIdentifier", wintypes.GUID),
        ("ParentTimestamp", wintypes.ULONG),
        ("VirtualStorageType", VIRTUAL_STORAGE_TYPE),
        ("ProviderSubtype", wintypes.ULONG),
        ("Is4kAligned", wintypes.BOOL),
        ("IsLoaded", wintypes.BOOL),
        ("PhysicalDisk", _VHD_INFO_PHYSICAL_DISK),
        ("VhdPhysicalSectorSize", wintypes.ULONG),
        ("SmallestSafeVirtualSize", wintypes.ULARGE_INTEGER),
        ("FragmentationPercentage", wintypes.ULONG)
    ]

class GET_VIRTUAL_DISK_INFO(ctypes.Structure):
    _anonymous_ = ['_vhdinfo']
    _fields_ = [
        ("Version", wintypes.UINT),
        ("_vhdinfo", _VHD_INFO)
    ]

PGET_VIRTUAL_DISK_INFO = ctypes.POINTER(GET_VIRTUAL_DISK_INFO)

class _SET_VIRTUAL_DISK_INFO_U(ctypes.Union):
    _fields_ = [
        ('ParentFilePath', wintypes.LPCWSTR),
        ('UniqueIdentifier', wintypes.GUID),
        ('VirtualDiskId', wintypes.GUID),
    ]

class SET_VIRTUAL_DISK_INFO(ctypes.Structure):
    _anonymous_ = ['_setinfo']
    _fields_ = [
        ('Version', wintypes.DWORD),
        ('_setinfo', _SET_VIRTUAL_DISK_INFO_U)
    ]

PSET_VIRTUAL_DISK_INFO = ctypes.POINTER(SET_VIRTUAL_DISK_INFO)

def register():
    global lib_handle
    lib_handle = ctypes.windll.virtdisk

    lib_handle.CreateVirtualDisk.argtypes = [
        PVIRTUAL_STORAGE_TYPE,
        wintypes.LPCWSTR,
        wintypes.INT,
        wintypes.PVOID,
        wintypes.INT,
        wintypes.ULONG,
        PCREATE_VIRTUAL_DISK_PARAMETERS,
        wintypes.LPOVERLAPPED,
        wintypes.PHANDLE
    ]
    lib_handle.CreateVirtualDisk.restype = wintypes.DWORD

    lib_handle.GetVirtualDiskInformation.argtypes = [
        wintypes.HANDLE,
        wintypes.PULONG,
        PGET_VIRTUAL_DISK_INFO,
        wintypes.PULONG
    ]
    lib_handle.GetVirtualDiskInformation.restype = wintypes.DWORD

    lib_handle.MergeVirtualDisk.argtypes = [
        wintypes.HANDLE,
        wintypes.INT,
        PMERGE_VIRTUAL_DISK_PARAMETERS,
        wintypes.LPOVERLAPPED
    ]
    lib_handle.MergeVirtualDisk.restype = wintypes.DWORD

    lib_handle.OpenVirtualDisk.argtypes = [
        PVIRTUAL_STORAGE_TYPE,
        wintypes.LPCWSTR,
        wintypes.INT,
        wintypes.INT,
        POPEN_VIRTUAL_DISK_PARAMETERS,
        wintypes.PHANDLE
    ]
    lib_handle.OpenVirtualDisk.restype = wintypes.DWORD

    lib_handle.ResizeVirtualDisk.argtypes = [
        wintypes.HANDLE,
        wintypes.INT,
        PRESIZE_VIRTUAL_DISK_PARAMETERS,
        wintypes.LPOVERLAPPED
    ]
    lib_handle.ResizeVirtualDisk.restype = wintypes.DWORD

    lib_handle.SetVirtualDiskInformation.argtypes = [
        wintypes.HANDLE,
        PSET_VIRTUAL_DISK_INFO
    ]
    lib_handle.SetVirtualDiskInformation.restype = wintypes.DWORD

    lib_handle.AttachVirtualDisk.argtypes = [
        wintypes.HANDLE,
        wintypes.PVOID,
        wintypes.INT,
        wintypes.ULONG,
        wintypes.PVOID,
        wintypes.LPOVERLAPPED
    ]
    lib_handle.AttachVirtualDisk.restype = wintypes.DWORD

    lib_handle.DetachVirtualDisk.argtypes = [
        wintypes.HANDLE,
        wintypes.INT,
        wintypes.ULONG
    ]
    lib_handle.DetachVirtualDisk.restype = wintypes.DWORD

    lib_handle.GetVirtualDiskPhysicalPath.argtypes = [
        wintypes.HANDLE,
        wintypes.PULONG,
        wintypes.PWSTR
    ]
    lib_handle.GetVirtualDiskPhysicalPath.restype = wintypes.DWORD


text:
package org.uclab.mm.datamodel.sc;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author Taqdir Ali
 */
@Entity
public class RecommendationException implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private Long recommendationExceptionID;
    private Long recommendationID;
    private String exception;
    private String customRule;
    private String exceptionReason;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof RecommendationException)) {
            return false;
        }
        RecommendationException other = (RecommendationException) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.uclab.mm.datamodel.sc.RecommendationException[ id=" + id + " ]";
    }

    /**
     * @return the recommendationExceptionID
     */
    public Long getRecommendationExceptionID() {
        return recommendationExceptionID;
    }

    /**
     * @param recommendationExceptionID the recommendationExceptionID to set
     */
    public void setRecommendationExceptionID(Long recommendationExceptionID) {
        this.recommendationExceptionID = recommendationExceptionID;
    }

    /**
     * @return the recommendationID
     */
    public Long getRecommendationID() {
        return recommendationID;
    }

    /**
     * @param recommendationID the recommendationID to set
     */
    public void setRecommendationID(Long recommendationID) {
        this.recommendationID = recommendationID;
    }

    /**
     * @return the exception
     */
    public String getException() {
        return exception;
    }

    /**
     * @param exception the exception to set
     */
    public void setException(String exception) {
        this.exception = exception;
    }

    /**
     * @return the customRule
     */
    public String getCustomRule() {
        return customRule;
    }

    /**
     * @param customRule the customRule to set
     */
    public void setCustomRule(String customRule) {
        this.customRule = customRule;
    }

    /**
     * @return the exceptionReason
     */
    public String getExceptionReason() {
        return exceptionReason;
    }

    /**
     * @param exceptionReason the exceptionReason to set
     */
    public void setExceptionReason(String exceptionReason) {
        this.exceptionReason = exceptionReason;
    }

}


text:
title: RadPanelBar Object
page_title: RadPanelBar Object - RadPanelBar
description: Check our Web Forms article about RadPanelBar Object.
slug: panelbar/client-side-programming/radpanelbar-object
tags: radpanelbar,object
published: True
position: 1
---

# RadPanelBar Object

##

The following table lists the most important methods of the **RadPanelBar** client-side object:

>caption

| Name | Parameters | Return Type | Description |
| ------ | ------ | ------ | ------ |
| **trackChanges** |none|none|Begins tracking changes to the panel items. Only changes to the items that occur between a call to **trackChanges** and **commitChanges** persist after a postback. See **Example 1**. |
| **commitChanges** |none|none|Ends tracking changes to the panel items. Only changes to the items that occur between a call to **trackChanges** and **commitChanges** persist after a postback. Client side changes are available on the server side after postback. You can use the [ClientChanges]({%slug panelbar/client-side-programming/accessing-client-changes-on-the-server%}) property to access them. See **Example 1**. |
| **disable** | none | none | Disables all items in the panel. Clicking on any item has no effect, child items cannot be opened. See **Example 2**. |
| **enable** | none | none | Enables all items in the panel. |
| **get_enabled** | none | boolean | True if the panel is enabled. To enable a panel, use the enable() method.|
| **findItemByValue** |(string value)|[RadPanelItem]({%slug panelbar/client-side-programming/radpanelitem-object%})|Returns the first **RadPanelBarItem** object whose **Value** property is equal to the passed parameter.|
| **findItemByText** |(string text)|[RadPanelItem]({%slug panelbar/client-side-programming/radpanelitem-object%})|Returns the first **RadPanelBarItem** object whose **Text** property is equal to the passed parameter.|
| **findItemByUrl** |(string URL)|[RadPanelItem]({%slug panelbar/client-side-programming/radpanelitem-object%})|Returns the first **RadPanelBarItem** object whose **NavigateUrl** property is equal to the passed parameter.|
| **findItemByAbsoluteUrl** |(string URL)|[RadPanelItem]({%slug panelbar/client-side-programming/radpanelitem-object%})|Returns the first **RadPanelBarItem** object whose **NavigateUrl** property is equal to the passed parameter. Note that the parameter should end with '/' like:var item = sender.findItemByAbsoluteUrl('http://www.test.com/');|
| **findItemByAttribute** |(string attributeName, string value)|[RadPanelItem]({%slug panelbar/client-side-programming/radpanelitem-object%})|Returns the first **RadPanelBarItem** object with a custom attribute of the specified name that has the specified value.|
| **get_items** |none|[RadPanelItemCollection]({%slug panelbar/client-side-programming/radpanelitemcollection-object%})|Returns the collection of root level items. See **Example 3**. |
| **get_allItems** | none | Array | Gets a linear collection of all items. This includes all root and child items in the panel. See **Example 4**. |
| **get_focusedItem** | none | [RadPanelItem]({%slug panelbar/client-side-programming/radpanelitem-object%}) | Returns the focused root level item. Null if no root level item has focus. |
| **get_expandedItem** |none|[RadPanelItem]({%slug panelbar/client-side-programming/radpanelitem-object%})|Returns the last root level item that was expanded. Null if no root level items are expanded.|
| **get_expandedItems** |none|Array|Returns an array of the **RadPanelBarItem** objects for every expanded item in the panel bar (including expanded child items).|
| **get_selectedItem** |none|[RadPanelItem]({%slug panelbar/client-side-programming/radpanelitem-object%})|Returns the selected item if it exists. (It does not have to be a root level item). Null if the panel does not have a selected item.|
| **get_selectedItems** |none|Array|Returns an array containing the selected items in the panel. Because the panel bar does not allow more than one item to be selected, the array always has 0 or 1 elements.|
| **get_attributes** |none|Collection|Returns the collection of custom attributes for the panel.|
| **get_element** |none|HTML Element|Gets the DOM element for the panel.  See **Example 5**. |
| **get_childListElement** | none | HTML Element | Gets the DOM element for the list of items in the panel. |
| **enableEvents** |none|none|Enables the panel bar's client-side event emitting. Events are enabled by default.|
| **disableEvents** |none|none|Disables the panel bar's client-side event emitting.|
| **add_`<EventName>`** |(mixed eventHandler)|none|Attaches an eventHandler to the event with the name `<EventName>`. Note that client-side event names differ from their server-side counterparts. For more information, see [Client-Side Events]({%slug panelbar/client-side-programming/events%}). See **Example 6**. |
| **remove_`<EventName>`** | (mixed eventHandler) | Boolean | Detaches an eventHandler from the event with the name `<EventName>`.Returns "True" if the eventHandler is found and detached, false otherwise.Note that client-side event names differ from their server-side counterparts. For more information, see [Client-Side Events]({%slug panelbar/client-side-programming/events%}). See **Example 7**. |

>caption Example 1: Add a new item and persist it after a postback.
````JavaScript

function AddNewItem() {
    var panel = $find("<%= RadPanelBar1.ClientID %>");
    var panelItem = new Telerik.Web.UI.RadPanelItem();
    panelItem.set_text("New Item");
    panel.trackChanges();
    panel.get_items().add(panelItem);
    panel.commitChanges();
}

````

>caption Example 2: Disable the **RadPanelBar**.
````JavaScript

function Disablepanel() {
    var panel = $find("<%= RadPanelBar1.ClientID %>");
    panel.disable();
}

````

>caption Example 3: Get all root items and display their text value.
````JavaScript

function showRootItems() {
    var panel = $find("<%= RadPanelBar1.ClientID %>");
    var items = panel.get_items();
    for (var i = 0; i < items.get_count(); i++) {
        alert(items.getItem(i).get_text());
    }
}

````

>caption Example 4: Get all items and display their text value.
````JavaScript

function showAllItems() {
    var panel = $find("<%=RadPanelBar1.ClientID %>");
    for (var i = 0; i < panel.get_allItems().length; i++) {
        alert(panel.get_allItems()[i].get_text());
    }
}

````

>caption Example 5: Hide/show the **RadPanelBar**.
````JavaScript

// hide the panel
// note this change does not persist after a postback
function hidepanel() {
    var panel = $find("<%= RadPanelBar1.ClientID %>");
    panel.get_element().style.display = "none";
}

// show the panel
function showpanel() {
    var panel = $find("<%= RadPanelBar1.ClientID %>");
    panel.get_element().style.display = "";
}

````

>caption Example 6: Add a handler to the OnClientItemBlur event.
````JavaScript

function OnClientItemBlurHandler() {
    alert("goodbye");
}

function AttachBlurHandler() {
    var panel = $find("<%=RadPanelBar1.ClientID %>");
    panel.add_itemBlur(OnClientItemBlurHandler);
}

````

>caption Example 7: Remove the OnClientItemBlur event's handler.
````JavaScript

function OnClientItemBlurHandler() {
    alert("goodbye");
}

function DetachBlurHandler() {
    var panel = $find("<%=RadPanelBar1.ClientID %>");
    panel.remove_itemBlur(OnClientItemBlurHandler);
}

````

# See Also

 * [Client-side Programming Overview]({%slug panelbar/client-side-programming/overview%})

 * [Events]({%slug panelbar/client-side-programming/events%})

 * [Working With Items at the Client]({%slug panelbar/radpanelbar-items/working-with-items-at-the-client%})


text:
package com.iappsam.servlet.item;

public interface ItemParameter {
	public static final String CATEGORY = "itemCategory";
	public static final String CONDITION = "itemCondition";
	public static final String STATUS = "itemStatus";
	public static final String PROPERTY_NUM = "itemPropertyNumber";
	public static final String INVENTORY_ITEM_NUM = "inventoryItemNum";
	// public static final String YEAR = "year";
	// public static final String MONTH = "month";
	// public static final String DAY = "day";
	public static final String PRICE = "itemPrice";
	public static final String UNIT = "unit";
	public static final String STOCK_NUMBER = "stockNumber";
	public static final String DESCRIPTION = "description";
	public static final String ITEM_ID = "id";
	public static final String QUERY = "q";
	public static final String NEW_ITEM = "new";
}


text:
<?php

namespace Phalcon\Assets;

interface FilterInterface
{

	/**
	 * Filters the content returning a string with the filtered content
	 *
	 * @param string $content
	 *
	 * @return string
	 */
	public function filter($content);

}


text:
module OmertaLogger
  class BusinessObjectProtectionHistory < ApplicationRecord
    belongs_to :business_object
  end
end


text:
<?php
/**
 * Created by PhpStorm.
 * User: Jonathan
 * Email: jianyang1209@outlook.com
 * Date: 2016/9/26
 * Time: 23:15
 */

namespace backend\modules\ajax\controllers;

class HeaderController extends AjaxController
{

    public function actionNotification()
    {
        return $this->render('notification');
    }

    public function actionInbox()
    {
        return $this->render('inbox');
    }

    public function actionTask()
    {
        return $this->render('task');
    }
}


text:
/*	$NetBSD: aic79xx_inline.h,v 1.22 2013/04/27 13:25:09 kardel Exp $	*/

/*
 * Inline routines shareable across OS platforms.
 *
 * Copyright (c) 1994-2001 Justin T. Gibbs.
 * Copyright (c) 2000-2003 Adaptec Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions, and the following disclaimer,
 *    without modification.
 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
 *    substantially similar to the "NO WARRANTY" disclaimer below
 *    ("Disclaimer") and any redistribution must be conditioned upon
 *    including a substantially similar Disclaimer requirement for further
 *    binary redistribution.
 * 3. Neither the names of the above-listed copyright holders nor the names
 *    of any contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * Alternatively, this software may be distributed under the terms of the
 * GNU General Public License ("GPL") version 2 as published by the Free
 * Software Foundation.
 *
 * NO WARRANTY
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 *
 * Id: //depot/aic7xxx/aic7xxx/aic79xx_inline.h#51 $
 *
 * $FreeBSD: src/sys/dev/aic7xxx/aic79xx_inline.h,v 1.12 2003/06/28 04:43:19 gibbs Exp $
 */
/*
 * Ported from FreeBSD by Pascal Renauld, Network Storage Solutions, Inc. - April 2003
 */

#ifndef _AIC79XX_INLINE_H_
#define _AIC79XX_INLINE_H_

/******************************** Debugging ***********************************/
static __inline const char *ahd_name(struct ahd_softc *);

static __inline const char *
ahd_name(struct ahd_softc *ahd)
{
	return (ahd->name);
}

/************************ Sequencer Execution Control *************************/
static __inline void ahd_known_modes(struct ahd_softc *, ahd_mode, ahd_mode);
static __inline ahd_mode_state ahd_build_mode_state(struct ahd_softc *,
    ahd_mode, ahd_mode);
static __inline void ahd_extract_mode_state(struct ahd_softc *,
    ahd_mode_state, ahd_mode *, ahd_mode *);
static __inline void ahd_set_modes(struct ahd_softc *, ahd_mode, ahd_mode);
static __inline void ahd_update_modes(struct ahd_softc *);
static __inline void ahd_assert_modes(struct ahd_softc *, ahd_mode,
    ahd_mode, const char *, int);
static __inline ahd_mode_state ahd_save_modes(struct ahd_softc *);
static __inline void ahd_restore_modes(struct ahd_softc *, ahd_mode_state);
static __inline int  ahd_is_paused(struct ahd_softc *);
static __inline void ahd_pause(struct ahd_softc *);
static __inline void ahd_unpause(struct ahd_softc *);

static __inline void
ahd_known_modes(struct ahd_softc *ahd, ahd_mode src, ahd_mode dst)
{
	ahd->src_mode = src;
	ahd->dst_mode = dst;
	ahd->saved_src_mode = src;
	ahd->saved_dst_mode = dst;
}

static __inline ahd_mode_state
ahd_build_mode_state(struct ahd_softc *ahd, ahd_mode src, ahd_mode dst)
{
	return ((src << SRC_MODE_SHIFT) | (dst << DST_MODE_SHIFT));
}

static __inline void
ahd_extract_mode_state(struct ahd_softc *ahd, ahd_mode_state state,
		       ahd_mode *src, ahd_mode *dst)
{
	*src = (state & SRC_MODE) >> SRC_MODE_SHIFT;
	*dst = (state & DST_MODE) >> DST_MODE_SHIFT;
}

static __inline void
ahd_set_modes(struct ahd_softc *ahd, ahd_mode src, ahd_mode dst)
{
	if (ahd->src_mode == src && ahd->dst_mode == dst)
		return;
#ifdef AHD_DEBUG
	if (ahd->src_mode == AHD_MODE_UNKNOWN
	 || ahd->dst_mode == AHD_MODE_UNKNOWN)
		panic("Setting mode prior to saving it.\n");
	if ((ahd_debug & AHD_SHOW_MODEPTR) != 0)
		printf("%s: Setting mode 0x%x\n", ahd_name(ahd),
		       ahd_build_mode_state(ahd, src, dst));
#endif
	ahd_outb(ahd, MODE_PTR, ahd_build_mode_state(ahd, src, dst));
	ahd->src_mode = src;
	ahd->dst_mode = dst;
}

static __inline void
ahd_update_modes(struct ahd_softc *ahd)
{
	ahd_mode_state mode_ptr;
	ahd_mode src;
	ahd_mode dst;

	mode_ptr = ahd_inb(ahd, MODE_PTR);
#ifdef AHD_DEBUG
	if ((ahd_debug & AHD_SHOW_MODEPTR) != 0)
		printf("Reading mode 0x%x\n", mode_ptr);
#endif
	ahd_extract_mode_state(ahd, mode_ptr, &src, &dst);
	ahd_known_modes(ahd, src, dst);
}

static __inline void
ahd_assert_modes(struct ahd_softc *ahd, ahd_mode srcmode,
     ahd_mode dstmode, const char *file, int line)
{
#ifdef AHD_DEBUG
	if ((srcmode & AHD_MK_MSK(ahd->src_mode)) == 0
	 || (dstmode & AHD_MK_MSK(ahd->dst_mode)) == 0) {
		panic("%s:%s:%d: Mode assertion failed.\n",
		       ahd_name(ahd), file, line);
	}
#endif
}

static __inline ahd_mode_state
ahd_save_modes(struct ahd_softc *ahd)
{
	if (ahd->src_mode == AHD_MODE_UNKNOWN
	 || ahd->dst_mode == AHD_MODE_UNKNOWN)
		ahd_update_modes(ahd);

	return (ahd_build_mode_state(ahd, ahd->src_mode, ahd->dst_mode));
}

static __inline void
ahd_restore_modes(struct ahd_softc *ahd, ahd_mode_state state)
{
	ahd_mode src;
	ahd_mode dst;

	ahd_extract_mode_state(ahd, state, &src, &dst);
	ahd_set_modes(ahd, src, dst);
}

#define AHD_ASSERT_MODES(ahd, source, dest) \
	ahd_assert_modes(ahd, source, dest, __FILE__, __LINE__);

/*
 * Determine whether the sequencer has halted code execution.
 * Returns non-zero status if the sequencer is stopped.
 */
static __inline int
ahd_is_paused(struct ahd_softc *ahd)
{
	return ((ahd_inb(ahd, HCNTRL) & PAUSE) != 0);
}

/*
 * Request that the sequencer stop and wait, indefinitely, for it
 * to stop.  The sequencer will only acknowledge that it is paused
 * once it has reached an instruction boundary and PAUSEDIS is
 * cleared in the SEQCTL register.  The sequencer may use PAUSEDIS
 * for critical sections.
 */
static __inline void
ahd_pause(struct ahd_softc *ahd)
{
	ahd_outb(ahd, HCNTRL, ahd->pause);

	/*
	 * Since the sequencer can disable pausing in a critical section, we
	 * must loop until it actually stops.
	 */
	while (ahd_is_paused(ahd) == 0)
		;
}

/*
 * Allow the sequencer to continue program execution.
 * We check here to ensure that no additional interrupt
 * sources that would cause the sequencer to halt have been
 * asserted.  If, for example, a SCSI bus reset is detected
 * while we are fielding a different, pausing, interrupt type,
 * we don't want to release the sequencer before going back
 * into our interrupt handler and dealing with this new
 * condition.
 */
static __inline void
ahd_unpause(struct ahd_softc *ahd)
{
	/*
	 * Automatically restore our modes to those saved
	 * prior to the first change of the mode.
	 */
	if (ahd->saved_src_mode != AHD_MODE_UNKNOWN
	 && ahd->saved_dst_mode != AHD_MODE_UNKNOWN) {
		if ((ahd->flags & AHD_UPDATE_PEND_CMDS) != 0)
			ahd_reset_cmds_pending(ahd);
		ahd_set_modes(ahd, ahd->saved_src_mode, ahd->saved_dst_mode);
	}

	if ((ahd_inb(ahd, INTSTAT) & ~CMDCMPLT) == 0)
		ahd_outb(ahd, HCNTRL, ahd->unpause);

	ahd_known_modes(ahd, AHD_MODE_UNKNOWN, AHD_MODE_UNKNOWN);
}

/*********************** Scatter Gather List Handling *************************/
static __inline void	*ahd_sg_setup(struct ahd_softc *, struct scb *,
			    void *, bus_addr_t, bus_size_t, int);
static __inline void	 ahd_setup_scb_common(struct ahd_softc *, struct scb *);
static __inline void	 ahd_setup_data_scb(struct ahd_softc *, struct scb *);
static __inline void	 ahd_setup_noxfer_scb(struct ahd_softc *, struct scb *);

static __inline void *
ahd_sg_setup(struct ahd_softc *ahd, struct scb *scb,
	     void *sgptr, bus_addr_t addr, bus_size_t len, int last)
{
	scb->sg_count++;
	if (sizeof(bus_addr_t) > 4
	 && (ahd->flags & AHD_64BIT_ADDRESSING) != 0) {
		struct ahd_dma64_seg *sg;

		sg = (struct ahd_dma64_seg *)sgptr;
		sg->addr = ahd_htole64(addr);
		sg->len = ahd_htole32(len | (last ? AHD_DMA_LAST_SEG : 0));
		return (sg + 1);
	} else {
		struct ahd_dma_seg *sg;

		sg = (struct ahd_dma_seg *)sgptr;
		sg->addr = ahd_htole32(addr & 0xFFFFFFFF);
		sg->len = ahd_htole32(len | ((addr >> 8) & 0x7F000000)
				    | (last ? AHD_DMA_LAST_SEG : 0));
		return (sg + 1);
	}
}

static __inline void
ahd_setup_scb_common(struct ahd_softc *ahd, struct scb *scb)
{
	/* XXX Handle target mode SCBs. */
	scb->crc_retry_count = 0;
	if ((scb->flags & SCB_PACKETIZED) != 0) {
		/* XXX what about ACA??  It is type 4, but TAG_TYPE == 0x3. */
		scb->hscb->task_attribute = scb->hscb->control & SCB_TAG_TYPE;
	} else {
		if (ahd_get_transfer_length(scb) & 0x01)
			scb->hscb->task_attribute = SCB_XFERLEN_ODD;
		else
			scb->hscb->task_attribute = 0;
	}

	if (scb->hscb->cdb_len <= MAX_CDB_LEN_WITH_SENSE_ADDR
	 || (scb->hscb->cdb_len & SCB_CDB_LEN_PTR) != 0)
		scb->hscb->shared_data.idata.cdb_plus_saddr.sense_addr =
		    ahd_htole32(scb->sense_busaddr);
}

static __inline void
ahd_setup_data_scb(struct ahd_softc *ahd, struct scb *scb)
{
	/*
	 * Copy the first SG into the "current" data ponter area.
	 */
	if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0) {
		struct ahd_dma64_seg *sg;

		sg = (struct ahd_dma64_seg *)scb->sg_list;
		scb->hscb->dataptr = sg->addr;
		scb->hscb->datacnt = sg->len;
	} else {
		struct ahd_dma_seg *sg;
		uint32_t *dataptr_words;

		sg = (struct ahd_dma_seg *)scb->sg_list;
		dataptr_words = (uint32_t*)&scb->hscb->dataptr;
		dataptr_words[0] = sg->addr;
		dataptr_words[1] = 0;
		if ((ahd->flags & AHD_39BIT_ADDRESSING) != 0) {
			uint64_t high_addr;

			high_addr = ahd_le32toh(sg->len) & 0x7F000000;
			scb->hscb->dataptr |= ahd_htole64(high_addr << 8);
		}
		scb->hscb->datacnt = sg->len;
	}
	/*
	 * Note where to find the SG entries in bus space.
	 * We also set the full residual flag which the
	 * sequencer will clear as soon as a data transfer
	 * occurs.
	 */
	scb->hscb->sgptr = ahd_htole32(scb->sg_list_busaddr|SG_FULL_RESID);
}

static __inline void
ahd_setup_noxfer_scb(struct ahd_softc *ahd, struct scb *scb)
{
	scb->hscb->sgptr = ahd_htole32(SG_LIST_NULL);
	scb->hscb->dataptr = 0;
	scb->hscb->datacnt = 0;
}

/************************** Memory mapping routines ***************************/
static __inline size_t	ahd_sg_size(struct ahd_softc *);
static __inline void *
			ahd_sg_bus_to_virt(struct ahd_softc *, struct scb *,
			    uint32_t);
static __inline uint32_t
			ahd_sg_virt_to_bus(struct ahd_softc *, struct scb *,
			    void *);
static __inline void	ahd_sync_scb(struct ahd_softc *, struct scb *, int);
static __inline void	ahd_sync_sglist(struct ahd_softc *, struct scb *, int);
static __inline void	ahd_sync_sense(struct ahd_softc *, struct scb *, int);
static __inline uint32_t
			ahd_targetcmd_offset(struct ahd_softc *, u_int);

static __inline size_t
ahd_sg_size(struct ahd_softc *ahd)
{
	if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0)
		return (sizeof(struct ahd_dma64_seg));
	return (sizeof(struct ahd_dma_seg));
}

static __inline void *
ahd_sg_bus_to_virt(struct ahd_softc *ahd, struct scb *scb, uint32_t sg_busaddr)
{
	bus_addr_t sg_offset;

	/* sg_list_phys points to entry 1, not 0 */
	sg_offset = sg_busaddr - (scb->sg_list_busaddr - ahd_sg_size(ahd));
	return ((uint8_t *)scb->sg_list + sg_offset);
}

static __inline uint32_t
ahd_sg_virt_to_bus(struct ahd_softc *ahd, struct scb *scb, void *sg)
{
	bus_addr_t sg_offset;

	/* sg_list_phys points to entry 1, not 0 */
	sg_offset = ((uint8_t *)sg - (uint8_t *)scb->sg_list)
		  - ahd_sg_size(ahd);

	return (scb->sg_list_busaddr + sg_offset);
}

static __inline void
ahd_sync_scb(struct ahd_softc *ahd, struct scb *scb, int op)
{
	ahd_dmamap_sync(ahd, ahd->parent_dmat, scb->hscb_map->dmamap,
			/*offset*/(uint8_t*)scb->hscb - scb->hscb_map->vaddr,
			/*len*/sizeof(*scb->hscb), op);
}

static __inline void
ahd_sync_sglist(struct ahd_softc *ahd, struct scb *scb, int op)
{
	if (scb->sg_count == 0)
		return;

	ahd_dmamap_sync(ahd, ahd->parent_dmat, scb->sg_map->dmamap,
			/*offset*/scb->sg_list_busaddr - ahd_sg_size(ahd),
			/*len*/ahd_sg_size(ahd) * scb->sg_count, op);
}

static __inline void
ahd_sync_sense(struct ahd_softc *ahd, struct scb *scb, int op)
{
	ahd_dmamap_sync(ahd, ahd->parent_dmat,
			scb->sense_map->dmamap,
			/*offset*/scb->sense_busaddr - scb->sense_map->physaddr,
			/*len*/AHD_SENSE_BUFSIZE, op);
}

static __inline uint32_t
ahd_targetcmd_offset(struct ahd_softc *ahd, u_int index)
{
	return (((uint8_t *)&ahd->targetcmds[index])
	       - (uint8_t *)ahd->qoutfifo);
}

/*********************** Miscellaneous Support Functions ***********************/
static __inline void	ahd_complete_scb(struct ahd_softc *, struct scb *);
static __inline void	ahd_update_residual(struct ahd_softc *, struct scb *);
static __inline struct ahd_initiator_tinfo *
			ahd_fetch_transinfo(struct ahd_softc *, char, u_int,
			    u_int, struct ahd_tmode_tstate **);
static __inline uint16_t
			ahd_inw(struct ahd_softc *, u_int);
static __inline void	ahd_outw(struct ahd_softc *, u_int, u_int);
static __inline uint32_t
			ahd_inl(struct ahd_softc *, u_int);
static __inline void	ahd_outl(struct ahd_softc *, u_int, uint32_t);
static __inline uint64_t
			ahd_inq(struct ahd_softc *, u_int);
static __inline void	ahd_outq(struct ahd_softc *, u_int, uint64_t);
static __inline u_int	ahd_get_scbptr(struct ahd_softc *);
static __inline void	ahd_set_scbptr(struct ahd_softc *, u_int);
static __inline u_int	ahd_get_hnscb_qoff(struct ahd_softc *);
static __inline void	ahd_set_hnscb_qoff(struct ahd_softc *, u_int);
static __inline u_int	ahd_get_hescb_qoff(struct ahd_softc *);
static __inline void	ahd_set_hescb_qoff(struct ahd_softc *, u_int);
static __inline u_int	ahd_get_snscb_qoff(struct ahd_softc *);
static __inline void	ahd_set_snscb_qoff(struct ahd_softc *, u_int);
static __inline u_int	ahd_get_sescb_qoff(struct ahd_softc *);
static __inline void	ahd_set_sescb_qoff(struct ahd_softc *, u_int);
static __inline u_int	ahd_get_sdscb_qoff(struct ahd_softc *);
static __inline void	ahd_set_sdscb_qoff(struct ahd_softc *, u_int);
static __inline u_int	ahd_inb_scbram(struct ahd_softc *, u_int);
static __inline u_int	ahd_inw_scbram(struct ahd_softc *, u_int);
static __inline uint32_t
			ahd_inl_scbram(struct ahd_softc *, u_int);
static __inline uint64_t
			ahd_inq_scbram(struct ahd_softc *ahd, u_int offset);
static __inline void	ahd_swap_with_next_hscb(struct ahd_softc *,
	struct scb *);
static __inline void	ahd_queue_scb(struct ahd_softc *, struct scb *);
static __inline uint8_t *
			ahd_get_sense_buf(struct ahd_softc *, struct scb *);
static __inline uint32_t
			ahd_get_sense_bufaddr(struct ahd_softc *, struct scb *);
static __inline void	ahd_post_scb(struct ahd_softc *, struct scb *);

static __inline void
ahd_post_scb(struct ahd_softc *ahd, struct scb *scb)
{
	uint32_t sgptr;

	sgptr = ahd_le32toh(scb->hscb->sgptr);
	if ((sgptr & SG_STATUS_VALID) != 0)
		ahd_handle_scb_status(ahd, scb);
	else
		ahd_done(ahd, scb);
}

static __inline void
ahd_complete_scb(struct ahd_softc *ahd, struct scb *scb)
{
	uint32_t sgptr;

	sgptr = ahd_le32toh(scb->hscb->sgptr);
	if ((sgptr & SG_STATUS_VALID) != 0)
		ahd_handle_scb_status(ahd, scb);
	else
		ahd_done(ahd, scb);
}

/*
 * Determine whether the sequencer reported a residual
 * for this SCB/transaction.
 */
static __inline void
ahd_update_residual(struct ahd_softc *ahd, struct scb *scb)
{
	uint32_t sgptr;

	sgptr = ahd_le32toh(scb->hscb->sgptr);
	if ((sgptr & SG_STATUS_VALID) != 0)
		ahd_calc_residual(ahd, scb);
}

/*
 * Return pointers to the transfer negotiation information
 * for the specified our_id/remote_id pair.
 */
static __inline struct ahd_initiator_tinfo *
ahd_fetch_transinfo(struct ahd_softc *ahd, char channel, u_int our_id,
		    u_int remote_id, struct ahd_tmode_tstate **tstate)
{
	/*
	 * Transfer data structures are stored from the perspective
	 * of the target role.  Since the parameters for a connection
	 * in the initiator role to a given target are the same as
	 * when the roles are reversed, we pretend we are the target.
	 */
	if (channel == 'B')
		our_id += 8;
	*tstate = ahd->enabled_targets[our_id];
	return (&(*tstate)->transinfo[remote_id]);
}

#define AHD_COPY_COL_IDX(dst, src)				\
do {								\
	dst->hscb->scsiid = src->hscb->scsiid;			\
	dst->hscb->lun = src->hscb->lun;			\
} while (0)

static __inline uint16_t
ahd_inw(struct ahd_softc *ahd, u_int port)
{
	return ((ahd_inb(ahd, port+1) << 8) | ahd_inb(ahd, port));
}

static __inline void
ahd_outw(struct ahd_softc *ahd, u_int port, u_int value)
{
	ahd_outb(ahd, port, value & 0xFF);
	ahd_outb(ahd, port+1, (value >> 8) & 0xFF);
}

static __inline uint32_t
ahd_inl(struct ahd_softc *ahd, u_int port)
{
	return ((ahd_inb(ahd, port))
	      | (ahd_inb(ahd, port+1) << 8)
	      | (ahd_inb(ahd, port+2) << 16)
	      | (ahd_inb(ahd, port+3) << 24));
}

static __inline void
ahd_outl(struct ahd_softc *ahd, u_int port, uint32_t value)
{
	ahd_outb(ahd, port, (value) & 0xFF);
	ahd_outb(ahd, port+1, ((value) >> 8) & 0xFF);
	ahd_outb(ahd, port+2, ((value) >> 16) & 0xFF);
	ahd_outb(ahd, port+3, ((value) >> 24) & 0xFF);
}

static __inline uint64_t
ahd_inq(struct ahd_softc *ahd, u_int port)
{
	return ((ahd_inb(ahd, port))
	      | (ahd_inb(ahd, port+1) << 8)
	      | (ahd_inb(ahd, port+2) << 16)
	      | (ahd_inb(ahd, port+3) << 24)
	      | (((uint64_t)ahd_inb(ahd, port+4)) << 32)
	      | (((uint64_t)ahd_inb(ahd, port+5)) << 40)
	      | (((uint64_t)ahd_inb(ahd, port+6)) << 48)
	      | (((uint64_t)ahd_inb(ahd, port+7)) << 56));
}

static __inline void
ahd_outq(struct ahd_softc *ahd, u_int port, uint64_t value)
{
	ahd_outb(ahd, port, value & 0xFF);
	ahd_outb(ahd, port+1, (value >> 8) & 0xFF);
	ahd_outb(ahd, port+2, (value >> 16) & 0xFF);
	ahd_outb(ahd, port+3, (value >> 24) & 0xFF);
	ahd_outb(ahd, port+4, (value >> 32) & 0xFF);
	ahd_outb(ahd, port+5, (value >> 40) & 0xFF);
	ahd_outb(ahd, port+6, (value >> 48) & 0xFF);
	ahd_outb(ahd, port+7, (value >> 56) & 0xFF);
}

static __inline u_int
ahd_get_scbptr(struct ahd_softc *ahd)
{
	AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK),
			 ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK));
	return (ahd_inb(ahd, SCBPTR) | (ahd_inb(ahd, SCBPTR + 1) << 8));
}

static __inline void
ahd_set_scbptr(struct ahd_softc *ahd, u_int scbptr)
{
	AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK),
			 ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK));
	ahd_outb(ahd, SCBPTR, scbptr & 0xFF);
	ahd_outb(ahd, SCBPTR+1, (scbptr >> 8) & 0xFF);
}

static __inline u_int
ahd_get_hnscb_qoff(struct ahd_softc *ahd)
{
	return (ahd_inw_atomic(ahd, HNSCB_QOFF));
}

static __inline void
ahd_set_hnscb_qoff(struct ahd_softc *ahd, u_int value)
{
	ahd_outw_atomic(ahd, HNSCB_QOFF, value);
}

static __inline u_int
ahd_get_hescb_qoff(struct ahd_softc *ahd)
{
	return (ahd_inb(ahd, HESCB_QOFF));
}

static __inline void
ahd_set_hescb_qoff(struct ahd_softc *ahd, u_int value)
{
	ahd_outb(ahd, HESCB_QOFF, value);
}

static __inline u_int
ahd_get_snscb_qoff(struct ahd_softc *ahd)
{
	u_int oldvalue;

	AHD_ASSERT_MODES(ahd, AHD_MODE_CCHAN_MSK, AHD_MODE_CCHAN_MSK);
	oldvalue = ahd_inw(ahd, SNSCB_QOFF);
	ahd_outw(ahd, SNSCB_QOFF, oldvalue);
	return (oldvalue);
}

static __inline void
ahd_set_snscb_qoff(struct ahd_softc *ahd, u_int value)
{
	AHD_ASSERT_MODES(ahd, AHD_MODE_CCHAN_MSK, AHD_MODE_CCHAN_MSK);
	ahd_outw(ahd, SNSCB_QOFF, value);
}

static __inline u_int
ahd_get_sescb_qoff(struct ahd_softc *ahd)
{
	AHD_ASSERT_MODES(ahd, AHD_MODE_CCHAN_MSK, AHD_MODE_CCHAN_MSK);
	return (ahd_inb(ahd, SESCB_QOFF));
}

static __inline void
ahd_set_sescb_qoff(struct ahd_softc *ahd, u_int value)
{
	AHD_ASSERT_MODES(ahd, AHD_MODE_CCHAN_MSK, AHD_MODE_CCHAN_MSK);
	ahd_outb(ahd, SESCB_QOFF, value);
}

static __inline u_int
ahd_get_sdscb_qoff(struct ahd_softc *ahd)
{
	AHD_ASSERT_MODES(ahd, AHD_MODE_CCHAN_MSK, AHD_MODE_CCHAN_MSK);
	return (ahd_inb(ahd, SDSCB_QOFF) | (ahd_inb(ahd, SDSCB_QOFF + 1) << 8));
}

static __inline void
ahd_set_sdscb_qoff(struct ahd_softc *ahd, u_int value)
{
	AHD_ASSERT_MODES(ahd, AHD_MODE_CCHAN_MSK, AHD_MODE_CCHAN_MSK);
	ahd_outb(ahd, SDSCB_QOFF, value & 0xFF);
	ahd_outb(ahd, SDSCB_QOFF+1, (value >> 8) & 0xFF);
}

static __inline u_int
ahd_inb_scbram(struct ahd_softc *ahd, u_int offset)
{
	u_int value;

	/*
	 * Workaround PCI-X Rev A. hardware bug.
	 * After a host read of SCB memory, the chip
	 * may become confused into thinking prefetch
	 * was required.  This starts the discard timer
	 * running and can cause an unexpected discard
	 * timer interrupt.  The work around is to read
	 * a normal register prior to the exhaustion of
	 * the discard timer.  The mode pointer register
	 * has no side effects and so serves well for
	 * this purpose.
	 *
	 * Razor #528
	 */
	value = ahd_inb(ahd, offset);
	if ((ahd->flags & AHD_PCIX_SCBRAM_RD_BUG) != 0)
		ahd_inb(ahd, MODE_PTR);
	return (value);
}

static __inline u_int
ahd_inw_scbram(struct ahd_softc *ahd, u_int offset)
{
	return (ahd_inb_scbram(ahd, offset)
	      | (ahd_inb_scbram(ahd, offset+1) << 8));
}

static __inline uint32_t
ahd_inl_scbram(struct ahd_softc *ahd, u_int offset)
{
	return (ahd_inw_scbram(ahd, offset)
	      | (ahd_inw_scbram(ahd, offset+2) << 16));
}

static __inline uint64_t
ahd_inq_scbram(struct ahd_softc *ahd, u_int offset)
{
	return (ahd_inl_scbram(ahd, offset)
	      | ((uint64_t)ahd_inl_scbram(ahd, offset+4)) << 32);
}

static __inline struct scb *
ahd_lookup_scb(struct ahd_softc *ahd, u_int tag)
{
	struct scb* scb;

	if (tag >= AHD_SCB_MAX)
		return (NULL);
	scb = ahd->scb_data.scbindex[tag];
	if (scb != NULL)
		ahd_sync_scb(ahd, scb,
			     BUS_DMASYNC_POSTREAD|BUS_DMASYNC_POSTWRITE);
	return (scb);
}

static __inline void
ahd_swap_with_next_hscb(struct ahd_softc *ahd, struct scb *scb)
{
	struct hardware_scb *q_hscb;
	struct map_node *q_hscb_map;
	uint32_t saved_hscb_busaddr;

	/*
	 * Our queuing method is a bit tricky.  The card
	 * knows in advance which HSCB (by address) to download,
	 * and we can't disappoint it.  To achieve this, the next
	 * HSCB to download is saved off in ahd->next_queued_hscb.
	 * When we are called to queue "an arbitrary scb",
	 * we copy the contents of the incoming HSCB to the one
	 * the sequencer knows about, swap HSCB pointers and
	 * finally assign the SCB to the tag indexed location
	 * in the scb_array.  This makes sure that we can still
	 * locate the correct SCB by SCB_TAG.
	 */
	q_hscb = ahd->next_queued_hscb;
	q_hscb_map = ahd->next_queued_hscb_map;
	saved_hscb_busaddr = q_hscb->hscb_busaddr;
	memcpy(q_hscb, scb->hscb, sizeof(*scb->hscb));
	q_hscb->hscb_busaddr = saved_hscb_busaddr;
	q_hscb->next_hscb_busaddr = scb->hscb->hscb_busaddr;

	/* Now swap HSCB pointers. */
	ahd->next_queued_hscb = scb->hscb;
	ahd->next_queued_hscb_map = scb->hscb_map;
	scb->hscb = q_hscb;
	scb->hscb_map = q_hscb_map;

	KASSERT((vaddr_t)scb->hscb >= (vaddr_t)scb->hscb_map->vaddr &&
		(vaddr_t)scb->hscb < (vaddr_t)scb->hscb_map->vaddr + PAGE_SIZE);

	/* Now define the mapping from tag to SCB in the scbindex */
	ahd->scb_data.scbindex[SCB_GET_TAG(scb)] = scb;
}

/*
 * Tell the sequencer about a new transaction to execute.
 */
static __inline void
ahd_queue_scb(struct ahd_softc *ahd, struct scb *scb)
{
	ahd_swap_with_next_hscb(ahd, scb);

	if (SCBID_IS_NULL(SCB_GET_TAG(scb)))
		panic("Attempt to queue invalid SCB tag %x\n",
		      SCB_GET_TAG(scb));

	/*
	 * Keep a history of SCBs we've downloaded in the qinfifo.
	 */
	ahd->qinfifo[AHD_QIN_WRAP(ahd->qinfifonext)] = SCB_GET_TAG(scb);
	ahd->qinfifonext++;

	if (scb->sg_count != 0)
		ahd_setup_data_scb(ahd, scb);
	else
		ahd_setup_noxfer_scb(ahd, scb);
	ahd_setup_scb_common(ahd, scb);

	/*
	 * Make sure our data is consistent from the
	 * perspective of the adapter.
	 */
	ahd_sync_scb(ahd, scb, BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);

#ifdef AHD_DEBUG
	if ((ahd_debug & AHD_SHOW_QUEUE) != 0) {
		uint64_t host_dataptr;

		host_dataptr = ahd_le64toh(scb->hscb->dataptr);
		printf("%s: Queueing SCB 0x%x bus addr 0x%x - 0x%x%x/0x%x\n",
		       ahd_name(ahd),
		       SCB_GET_TAG(scb), ahd_le32toh(scb->hscb->hscb_busaddr),
		       (u_int)((host_dataptr >> 32) & 0xFFFFFFFF),
		       (u_int)(host_dataptr & 0xFFFFFFFF),
		       ahd_le32toh(scb->hscb->datacnt));
	}
#endif
	/* Tell the adapter about the newly queued SCB */
	ahd_set_hnscb_qoff(ahd, ahd->qinfifonext);
}

static __inline uint8_t *
ahd_get_sense_buf(struct ahd_softc *ahd, struct scb *scb)
{
	return (scb->sense_data);
}

static __inline uint32_t
ahd_get_sense_bufaddr(struct ahd_softc *ahd, struct scb *scb)
{
	return (scb->sense_busaddr);
}

/************************** Interrupt Processing ******************************/
static __inline void	ahd_sync_qoutfifo(struct ahd_softc *, int);
static __inline void	ahd_sync_tqinfifo(struct ahd_softc *, int);
static __inline u_int	ahd_check_cmdcmpltqueues(struct ahd_softc *);
static __inline int	ahd_intr(void *);
static __inline void	ahd_minphys(struct buf *);

static __inline void
ahd_sync_qoutfifo(struct ahd_softc *ahd, int op)
{
	ahd_dmamap_sync(ahd, ahd->parent_dmat, ahd->shared_data_map.dmamap,
			/*offset*/0, /*len*/AHD_SCB_MAX * sizeof(uint16_t), op);
}

static __inline void
ahd_sync_tqinfifo(struct ahd_softc *ahd, int op)
{
#ifdef AHD_TARGET_MODE
	if ((ahd->flags & AHD_TARGETROLE) != 0) {
		ahd_dmamap_sync(ahd, ahd->parent_dmat /*shared_data_dmat*/,
				ahd->shared_data_map.dmamap,
				ahd_targetcmd_offset(ahd, 0),
				sizeof(struct target_cmd) * AHD_TMODE_CMDS,
				op);
	}
#endif
}

/*
 * See if the firmware has posted any completed commands
 * into our in-core command complete fifos.
 */
#define AHD_RUN_QOUTFIFO 0x1
#define AHD_RUN_TQINFIFO 0x2
static __inline u_int
ahd_check_cmdcmpltqueues(struct ahd_softc *ahd)
{
	u_int retval;

	retval = 0;
	ahd_dmamap_sync(ahd, ahd->parent_dmat /*shared_data_dmat*/, ahd->shared_data_map.dmamap,
			/*offset*/ahd->qoutfifonext, /*len*/2,
			BUS_DMASYNC_POSTREAD);
	if ((ahd->qoutfifo[ahd->qoutfifonext]
	     & QOUTFIFO_ENTRY_VALID_LE) == ahd->qoutfifonext_valid_tag)
		retval |= AHD_RUN_QOUTFIFO;
#ifdef AHD_TARGET_MODE
	if ((ahd->flags & AHD_TARGETROLE) != 0
	 && (ahd->flags & AHD_TQINFIFO_BLOCKED) == 0) {
		ahd_dmamap_sync(ahd, ahd->parent_dmat /*shared_data_dmat*/,
				ahd->shared_data_map.dmamap,
				ahd_targetcmd_offset(ahd, ahd->tqinfifofnext),
				/*len*/sizeof(struct target_cmd),
				BUS_DMASYNC_POSTREAD);
		if (ahd->targetcmds[ahd->tqinfifonext].cmd_valid != 0)
			retval |= AHD_RUN_TQINFIFO;
	}
#endif
	return (retval);
}

/*
 * Catch an interrupt from the adapter
 */
static __inline int
ahd_intr(void *arg)
{
	struct ahd_softc *ahd = arg;
	u_int	intstat;

	if ((ahd->pause & INTEN) == 0) {
		/*
		 * Our interrupt is not enabled on the chip
		 * and may be disabled for re-entrancy reasons,
		 * so just return.  This is likely just a shared
		 * interrupt.
		 */
		return (0);
	}

	/*
	 * Instead of directly reading the interrupt status register,
	 * infer the cause of the interrupt by checking our in-core
	 * completion queues.  This avoids a costly PCI bus read in
	 * most cases.
	 */
	if ((ahd->flags & AHD_ALL_INTERRUPTS) == 0
	    && (ahd_check_cmdcmpltqueues(ahd) != 0))
		intstat = CMDCMPLT;
	else
		intstat = ahd_inb(ahd, INTSTAT);

	if ((intstat & INT_PEND) == 0)
		return (0);

	if (intstat & CMDCMPLT) {
		ahd_outb(ahd, CLRINT, CLRCMDINT);

		/*
		 * Ensure that the chip sees that we've cleared
		 * this interrupt before we walk the output fifo.
		 * Otherwise, we may, due to posted bus writes,
		 * clear the interrupt after we finish the scan,
		 * and after the sequencer has added new entries
		 * and asserted the interrupt again.
		 */
		if ((ahd->bugs & AHD_INTCOLLISION_BUG) != 0) {
			if (ahd_is_paused(ahd)) {
				/*
				 * Potentially lost SEQINT.
				 * If SEQINTCODE is non-zero,
				 * simulate the SEQINT.
				 */
				if (ahd_inb(ahd, SEQINTCODE) != NO_SEQINT)
					intstat |= SEQINT;
			}
		} else {
			ahd_flush_device_writes(ahd);
		}
		scsipi_channel_freeze(&ahd->sc_channel, 1);
		ahd_run_qoutfifo(ahd);
		scsipi_channel_thaw(&ahd->sc_channel, 1);
		ahd->cmdcmplt_counts[ahd->cmdcmplt_bucket]++;
		ahd->cmdcmplt_total++;
#ifdef AHD_TARGET_MODE
		if ((ahd->flags & AHD_TARGETROLE) != 0)
			ahd_run_tqinfifo(ahd, /*paused*/FALSE);
#endif
		if (intstat == CMDCMPLT)
			return 1;
	}

	/*
	 * Handle statuses that may invalidate our cached
	 * copy of INTSTAT separately.
	 */
	if (intstat == 0xFF && (ahd->features & AHD_REMOVABLE) != 0) {
		/* Hot eject.  Do nothing */
	} else if (intstat & HWERRINT) {
		ahd_handle_hwerrint(ahd);
	} else if ((intstat & (PCIINT|SPLTINT)) != 0) {
		ahd->bus_intr(ahd);
	} else {

		if ((intstat & SEQINT) != 0)
			ahd_handle_seqint(ahd, intstat);

		if ((intstat & SCSIINT) != 0)
			ahd_handle_scsiint(ahd, intstat);
	}

	return (1);
}

static __inline void
ahd_minphys(struct buf *bp)
{
/*
 * Even though the card can transfer up to 16megs per command
 * we are limited by the number of segments in the DMA segment
 * list that we can hold.  The worst case is that all pages are
 * discontinuous physically, hence the "page per segment" limit
 * enforced here.
 */
	if (bp->b_bcount > AHD_MAXTRANSFER_SIZE) {
		bp->b_bcount = AHD_MAXTRANSFER_SIZE;
	}
	minphys(bp);
}

static __inline u_int32_t scsi_4btoul(u_int8_t *);

static __inline u_int32_t
scsi_4btoul(u_int8_t *bytes)
{
	u_int32_t rv;

	rv = (bytes[0] << 24) |
	     (bytes[1] << 16) |
	     (bytes[2] << 8) |
	     bytes[3];
	return (rv);
}

#endif  /* _AIC79XX_INLINE_H_ */


text:
@implementation MKMapItem (CSExtension)

+ (void)navigateForDriving:(double)lat :(double)lng :(NSString *)name {
    [MKMapItem navigateForDriving:CLLocationCoordinate2DMake(lat, lng) :name];
}

+ (void)navigateForDriving:(CLLocationCoordinate2D)coordinate :(NSString *)name {
    let destinationMapItem = [MKMapItem.alloc initWithPlacemark:
            [MKPlacemark.alloc initWithCoordinate:coordinate addressDictionary:nil]];
    destinationMapItem.name = name;
    [MKMapItem openMapsWithItems:@[destinationMapItem] launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving}];
}

@end


text:
package com.google.cloud.tools.jib.image.json;

import com.google.cloud.tools.jib.api.DescriptorDigest;
import com.google.cloud.tools.jib.image.json.BuildableManifestTemplate.ContentDescriptorTemplate;
import com.google.cloud.tools.jib.json.JsonTemplateMapper;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.Resources;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.DigestException;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;

/** Tests for {@link V22ManifestTemplate}. */
public class V22ManifestTemplateTest {

  @Test
  public void testToJson() throws DigestException, IOException, URISyntaxException {
    // Loads the expected JSON string.
    Path jsonFile = Paths.get(Resources.getResource("core/json/v22manifest.json").toURI());
    String expectedJson = new String(Files.readAllBytes(jsonFile), StandardCharsets.UTF_8);

    // Creates the JSON object to serialize.
    V22ManifestTemplate manifestJson = new V22ManifestTemplate();

    manifestJson.setContainerConfiguration(
        1000,
        DescriptorDigest.fromDigest(
            "sha256:8c662931926fa990b41da3c9f42663a537ccd498130030f9149173a0493832ad"));

    manifestJson.addLayer(
        1000_000,
        DescriptorDigest.fromHash(
            "4945ba5011739b0b98c4a41afe224e417f47c7c99b2ce76830999c9a0861b236"));

    // Serializes the JSON object.
    Assert.assertEquals(expectedJson, JsonTemplateMapper.toUtf8String(manifestJson));
  }

  @Test
  public void testFromJson() throws IOException, URISyntaxException, DigestException {
    // Loads the JSON string.
    Path jsonFile = Paths.get(Resources.getResource("core/json/v22manifest.json").toURI());

    // Deserializes into a manifest JSON object.
    V22ManifestTemplate manifestJson =
        JsonTemplateMapper.readJsonFromFile(jsonFile, V22ManifestTemplate.class);

    Assert.assertEquals(
        DescriptorDigest.fromDigest(
            "sha256:8c662931926fa990b41da3c9f42663a537ccd498130030f9149173a0493832ad"),
        manifestJson.getContainerConfiguration().getDigest());

    Assert.assertEquals(1000, manifestJson.getContainerConfiguration().getSize());

    Assert.assertEquals(
        DescriptorDigest.fromHash(
            "4945ba5011739b0b98c4a41afe224e417f47c7c99b2ce76830999c9a0861b236"),
        manifestJson.getLayers().get(0).getDigest());

    Assert.assertEquals(1000_000, manifestJson.getLayers().get(0).getSize());
  }

  @Test
  public void testFromJson_optionalProperties() throws IOException, URISyntaxException {
    Path jsonFile =
        Paths.get(Resources.getResource("core/json/v22manifest_optional_properties.json").toURI());

    V22ManifestTemplate manifestJson =
        JsonTemplateMapper.readJsonFromFile(jsonFile, V22ManifestTemplate.class);

    List<ContentDescriptorTemplate> layers = manifestJson.getLayers();
    Assert.assertEquals(4, layers.size());
    Assert.assertNull(layers.get(0).getUrls());
    Assert.assertNull(layers.get(0).getAnnotations());

    Assert.assertEquals(Arrays.asList("url-foo", "url-bar"), layers.get(1).getUrls());
    Assert.assertNull(layers.get(1).getAnnotations());

    Assert.assertNull(layers.get(2).getUrls());
    Assert.assertEquals(ImmutableMap.of("key-foo", "value-foo"), layers.get(2).getAnnotations());

    Assert.assertEquals(Arrays.asList("cool-url"), layers.get(3).getUrls());
    Assert.assertEquals(
        ImmutableMap.of("key1", "value1", "key2", "value2"), layers.get(3).getAnnotations());
  }
}


text:
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using CacheAspect;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Rhino.Mocks;

namespace TestCache
{
    [TestClass]
    public class TestUserRepository
    {

        UserRepository target;
        IUserDal dal;
        ICache cache;

        // Use TestInitialize to run code before running each test
        [TestInitialize]
        public void SetUp()
        {
            dal = MockRepository.GenerateStrictMock<IUserDal>();
            cache = new InProcessMemoryCache();

            CacheService.Cache = cache;
            target = new UserRepository();
            target.Dal = dal;
        }

        [TestMethod]
        public void GetAllUsers_TryRetrievingDataTwice_DalShouldBeHitOnce()
        {
            //Arrange
            dal.Expect(d => d.GetAllUsers()).Return(GetUsers());
            dal.Expect(d => d.DeleteUserById(1234)).IgnoreArguments();

            target.DeleteUserById(1234);

            //Act
            target.GetAllUsers();
            target.GetAllUsers();

            //Assert
            dal.VerifyAllExpectations();

        }

        [TestMethod]
        public void GetUserById_TryRetrievingDataTwice_DalShouldBeHitOnce()
        {
            //Arrange
            int id = 1;
            dal.Expect(d => d.GetUserById(id)).Return(GetUsers().First());
            dal.Expect(d => d.DeleteUserById(id)).IgnoreArguments();

            target.DeleteUserById(id);

            //Act
            target.GetUserById(id);
            target.GetUserById(id);

            //Assert
            dal.VerifyAllExpectations();
        }

        [TestMethod]
        public void GetUserById_TryRetrievingUsingDifferentIds_DalShouldBeHitTwice()
        {
            //Arrange
            int id1 = 1;
            int id2 = 2;
            dal.Expect(d => d.GetUserById(id1)).Return(GetUsers().First());
            dal.Expect(d => d.GetUserById(id2)).Return(GetUsers().Last());
            dal.Expect(d => d.DeleteUserById(id1)).IgnoreArguments();
            dal.Expect(d => d.DeleteUserById(id2)).IgnoreArguments();

            //Act
            target.DeleteUserById(id1);
            target.DeleteUserById(id2);
            target.GetUserById(id1);
            target.GetUserById(id2);

            //Assert
            dal.VerifyAllExpectations();
        }

        [TestMethod]
        public void GetAllUsers_AddUserAfterCaching_CacheShouldBeInvalidated()
        {
            //Arrange
            dal.Expect(d => d.GetAllUsers())
                .Return(GetUsers())
                .Repeat.Twice();                    //Second call expected after cache is invalidated
            dal.Expect(d => d.AddUser(null)).IgnoreArguments();
            dal.Expect(d => d.DeleteUserById(5678)).IgnoreArguments();

            //Act
            target.DeleteUserById(5678);
            target.GetAllUsers();
            target.AddUser(new User{ Id = 1234});   //Should trigger invalidation
            target.GetAllUsers();

            //Assert
            dal.VerifyAllExpectations();
        }

        [TestMethod]
        public void GetUserById_EditUserAfterCaching_CacheShouldBeInvalidated() {
            //Arrange
            dal.Expect(d => d.GetUserById(1))
                .Return(GetUsers().First())
                .Repeat.Twice();                    //Second call expected after cache is invalidated
            dal.Expect(d => d.EditUser(GetUsers().First())).IgnoreArguments();
            dal.Expect(d => d.DeleteUserById(5678)).IgnoreArguments();

            //Act
            target.DeleteUserById(5678);
            target.GetUserById(1);
            target.EditUser(new User { Id = 1 });   //Should trigger invalidation
            target.GetUserById(1);

            //Assert
            dal.VerifyAllExpectations();
        }

        private TestContext testContextInstance;

        /// <summary>
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///</summary>
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }
        private List<User> GetUsers()
        {
            return new List<User>{
            new User{ Id = 1},
            new User{ Id = 2}
        };
        }
    }
}


text:
TT_TEST_BEGIN(copy_cv)
{
    BOOST_CHECK_TYPE3(tt::copy_cv<int, void>::type, int);
    BOOST_CHECK_TYPE3(tt::copy_cv<int const, void>::type, int const);
    BOOST_CHECK_TYPE3(tt::copy_cv<int volatile, void>::type, int volatile);
    BOOST_CHECK_TYPE3(tt::copy_cv<int const volatile, void>::type, int const volatile);

    BOOST_CHECK_TYPE3(tt::copy_cv<int, void const>::type, int const);
    BOOST_CHECK_TYPE3(tt::copy_cv<int const, void const>::type, int const);
    BOOST_CHECK_TYPE3(tt::copy_cv<int volatile, void const>::type, int const volatile);
    BOOST_CHECK_TYPE3(tt::copy_cv<int const volatile, void const>::type, int const volatile);

    BOOST_CHECK_TYPE3(tt::copy_cv<int, void volatile>::type, int volatile);
    BOOST_CHECK_TYPE3(tt::copy_cv<int const, void volatile>::type, int const volatile);
    BOOST_CHECK_TYPE3(tt::copy_cv<int volatile, void volatile>::type, int volatile);
    BOOST_CHECK_TYPE3(tt::copy_cv<int const volatile, void volatile>::type, int const volatile);

    BOOST_CHECK_TYPE3(tt::copy_cv<int, void const volatile>::type, int const volatile);
    BOOST_CHECK_TYPE3(tt::copy_cv<int const, void const volatile>::type, int const volatile);
    BOOST_CHECK_TYPE3(tt::copy_cv<int volatile, void const volatile>::type, int const volatile);
    BOOST_CHECK_TYPE3(tt::copy_cv<int const volatile, void const volatile>::type, int const volatile);

    BOOST_CHECK_TYPE3(tt::copy_cv<int&, void const volatile>::type, int&);

    BOOST_CHECK_TYPE3(tt::copy_cv<int const*, void volatile>::type, int const* volatile);

    BOOST_CHECK_TYPE3(tt::copy_cv<long, int const volatile&>::type, long);
}
TT_TEST_END


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>KDG Zoho Admin Panel | API Key</title>

        <link rel="shortcut icon" href="assets/images/favicon.ico">
        <link rel="apple-touch-icon" href="assets/images/favicon.ico">

        <link href="assets/css/lib/font-awesome.min.css" rel="stylesheet">
        <link href="assets/css/lib/themify-icons.css" rel="stylesheet">
        <link href="assets/css/lib/bootstrap.min.css" rel="stylesheet">
        <link href="assets/css/lib/unix.css" rel="stylesheet">
        <link href="assets/css/style.css" rel="stylesheet">

    							Zoho Admin Portal

                  <form>

Zoho Configuration

                      Zoho API Key *  Setup.">
                      <input type="text" class="form-control" placeholder="Enter Your API Key Number">

                    <button type="submit" class="btn btn-primary btn-flat m-b-15">Submit API Key</button>
                  </form>

Don't want to enter your API Key now? Log out


text:
#include <CoreFoundation/CoreFoundation.h>
#include "../OgrePrerequisites.h"

namespace Ogre {

    CFBundleRef mac_loadExeBundle(const char *path);
    void * mac_getBundleSym(CFBundleRef bundle, const char *name);
    bool mac_unloadExeBundle(CFBundleRef bundle);
    void* mac_loadDylib(const char* name);
    _OgreExport std::string macPluginPath();
    _OgreExport std::string macBundlePath();
}


text:
package tk.vikingcorp.occultMod.assist;

import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.stats.Achievement;
import net.minecraftforge.common.AchievementPage;
import tk.vikingcorp.occultMod.Achievements;
import tk.vikingcorp.occultMod.ModBlocks;
import tk.vikingcorp.occultMod.ModItems;
import tk.vikingcorp.occultMod.OccultWorldGen;

public class RegisterHelper
{

	public static void registerBlock(Block block)
	{
		GameRegistry.registerBlock(block, Reference.MODID + block.getUnlocalizedName().substring(5));
	}

	public static void registerItem(Item item)
	{
		GameRegistry.registerItem(item, item.getUnlocalizedName().substring(5));
	}

	public static void registerRecipes()
	{
		//Smelting Recipes
		GameRegistry.addSmelting(ModBlocks.occultOre, new ItemStack(ModItems.occultIngot), 2.0F);

		//Shaped Recipes
		GameRegistry.addRecipe(new ItemStack(ModBlocks.occultBlock), new Object[]{
		    	"III",
		    	"III",
		    	"III",
		    	'I', ModItems.occultIngot
		    	});

		GameRegistry.addRecipe(new ItemStack(ModItems.occultRod), new Object[]{
				"  I",
				" S ",
				"I  ",
				'I', ModItems.occultIngot,
				'S', Items.stick
		});

		GameRegistry.addRecipe(new ItemStack(ModItems.occultPickaxe), new Object[]{
				" II",
				" RI",
				"R  ",
				'I', ModItems.occultIngot,
				'R', ModItems.occultRod
		});

		GameRegistry.addRecipe(new ItemStack(ModItems.occultCrown), new Object[]{
				"BEB",
				"ISI",
				"BIB",
				'I', ModItems.occultIngot,
				'B', ModBlocks.occultBlock,
				'E', Blocks.dragon_egg,
				'S', Items.nether_star
		});

		//Shapeless Recipes
		GameRegistry.addShapelessRecipe(new ItemStack(ModItems.occultIngot, 9), new Object[]
		{
		    	new ItemStack(ModBlocks.occultBlock)
		});

	}

	public static void registerWorldGen()
	{
		GameRegistry.registerWorldGenerator(new OccultWorldGen(), 0);
	}

	public static CreativeTabs tabOccultMod = new CreativeTabs("tabOccultMod"){
		@Override
		public Item getTabIconItem(){
			return new ItemStack(ModItems.occultIngot).getItem();
		}
	};

	public static void registerAchievements(){
		AchievementPage.registerAchievementPage(new AchievementPage("Occult Achievements", new Achievement[] {Achievements.achievementBecomeGodlike}));
		Achievements.achievementBecomeGodlike.registerStat();
	}
}


text:
package starter

import (
	"fmt"
	"io/ioutil"
	"os"
	"testing"
	"time"

	convey2 "github.com/go-zero-boilerplate/more_goconvey_assertions"

	. "github.com/smartystreets/goconvey/convey"

	"github.com/go-zero-boilerplate/job-coordinator/context"
	"github.com/go-zero-boilerplate/job-coordinator/testing_utils"
	"github.com/go-zero-boilerplate/job-coordinator/testing_utils/mocks"
	"github.com/go-zero-boilerplate/job-coordinator/utils/host_details"
	"github.com/go-zero-boilerplate/job-coordinator/utils/remote_file_system"
)

type testingJob struct {
	id          string
	ctx         *context.Context
	hostDetails host_details.HostDetails

	remoteDirMocker *mocks.RemoteDirMocker
}

func (t *testingJob) Id() string                            { return t.id }
func (t *testingJob) HostDetails() host_details.HostDetails { return t.hostDetails }
func (t *testingJob) Commandline(remoteFileSystem remote_file_system.FileSystem) ([]string, error) {
	dummyCliFlagInterval := 100 * time.Millisecond
	dummyCliFlagNumber := 5
	failureMode := false
	t.remoteDirMocker = mocks.NewRemoteDirMocker(t.ctx, dummyCliFlagInterval, dummyCliFlagNumber, failureMode)
	if err := t.remoteDirMocker.CreateScriptFile(remoteFileSystem, t.hostDetails); err != nil {
		return nil, err
	}
	return []string{t.remoteDirMocker.FullScriptFilePath}, nil
}
func (t *testingJob) Timeout() *time.Duration {
	//TODO: Add test for testing timeout works as expected
	return nil
}
func (t *testingJob) RecordResourceUsage() bool {
	//TODO: Add test for testing resource-usage words as expected
	return false
}

func waitForProcess(pid int) {
	//TODO: This process is run via GoPsexec server remotely, but the remote is localhost
	if proc, err := os.FindProcess(pid); err == nil {
		proc.Wait()
	}
}

func TestCopyToWorker(t *testing.T) {
	Convey("Testing the copy-to worker", t, func() {
		ctx, err := testing_utils.NewContext(
			false, //Virtual FileSystem
		)
		So(err, ShouldBeNil)
		testingLogger := ctx.Logger.(*testing_utils.TestingLogger)

		remoteFSFactory := testing_utils.NewTestingRemoteFSFactory()
		hostDetails := testing_utils.NewTestingHostDetails("localhost", remoteFSFactory)

		job := &testingJob{id: "testing-starter-id-1", hostDetails: hostDetails, ctx: ctx}

		worker := &starter{}

		testingLogger.Clear()
		So(len(testingLogger.Handler.Lines), ShouldEqual, 0)

		jobCtx, err := worker.getJobContext(ctx, job)
		So(err, ShouldBeNil)
		err = os.RemoveAll(jobCtx.remoteJobPath) //Remove now
		So(err, ShouldBeNil)
		defer os.RemoveAll(jobCtx.remoteJobPath) //Remove at end

		startedDetails, err := worker.runJob(jobCtx, job)
		So(err, ShouldBeNil)
		So(startedDetails, ShouldNotBeNil)
		So(startedDetails.Pid, ShouldNotEqual, 0)

		waitForProcess(startedDetails.Pid)

		So(job.remoteDirMocker.FullScriptFilePath, convey2.AssertFileExistance, true)
		So(job.remoteDirMocker.FullLogFilePath, convey2.AssertFileExistance, true)

		logFileContent, err := ioutil.ReadFile(job.remoteDirMocker.FullLogFilePath)
		So(err, ShouldBeNil)
		for _, expectedLine := range job.remoteDirMocker.ExpectedLogLines {
			So(string(logFileContent), ShouldContainSubstring, expectedLine)
		}

		expectation := testing_utils.LogExpectation{
			LineCount: 1,
			Lines: []testing_utils.ExpectedLine{
				testing_utils.ExpectedLine{Index: 0, Info: true, RequiredSubstrings: []string{fmt.Sprintf("Started command with Pid %d", startedDetails.Pid)}},
			},
		}

		includeDebugLines := false
		err = expectation.MeetsExpectation(testingLogger, includeDebugLines)
		So(err, ShouldBeNil)
	})
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.github.kpavlov</groupId>
    <artifactId>json-service-starter</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>war</packaging>

    <name>JSON WebService Starter Maven Webapp</name>
    <url>https://github.com/kpavlov/json-service-starter</url>

    <properties>
        <failOnMissingWebXml>false</failOnMissingWebXml>
        <maven.compiler.optimize>true</maven.compiler.optimize>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.fork>true</maven.compiler.fork>
        <maven.compiler.showWarnings>true</maven.compiler.showWarnings>
        <maven.compiler.showDeprecation>true</maven.compiler.showDeprecation>
        <spring-boot.version>1.1.9.RELEASE</spring-boot.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <!-- Import dependency management from Spring Boot -->
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-bom</artifactId>
                <version>5.2.10.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jetty</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>

        <!-- Test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>

        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <compilerArguments>
                        <profile>compact3</profile>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${spring-boot.version}</version>
            </plugin>
        </plugins>
    </build>
</project>


text:
<?php

/**
 * Launches the symfony test suite.
 *
 * @package    symfony
 * @subpackage task
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @version    SVN: $Id: sfSymfonyTestTask.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class sfSymfonyTestTask extends sfTask
{
  /**
   * @see sfTask
   */
  protected function configure()
  {
    $this->addOptions(array(
      new sfCommandOption('update-autoloader', 'u', sfCommandOption::PARAMETER_NONE, 'Update the sfCoreAutoload class'),
      new sfCommandOption('only-failed', 'f', sfCommandOption::PARAMETER_NONE, 'Only run tests that failed last time'),
      new sfCommandOption('xml', null, sfCommandOption::PARAMETER_REQUIRED, 'The file name for the JUnit compatible XML log file'),
      new sfCommandOption('rebuild-all', null, sfCommandOption::PARAMETER_NONE, 'Rebuild all generated fixture files'),
    ));

    $this->namespace = 'symfony';
    $this->name = 'test';
    $this->briefDescription = 'Launches the symfony test suite';

    $this->detailedDescription = <<<EOF
The [test:all|INFO] task launches the symfony test suite:

  [./symfony symfony:test|INFO]
EOF;
  }

  /**
   * @see sfTask
   */
  protected function execute($arguments = array(), $options = array())
  {
    require_once(dirname(__FILE__).'/../../vendor/lime/lime.php');
    require_once(dirname(__FILE__).'/lime_symfony.php');

    // cleanup
    require_once(dirname(__FILE__).'/../../util/sfToolkit.class.php');
    if ($files = glob(sys_get_temp_dir().DIRECTORY_SEPARATOR.'/sf_autoload_unit_*'))
    {
      foreach ($files as $file)
      {
        unlink($file);
      }
    }

    // update sfCoreAutoload
    if ($options['update-autoloader'])
    {
      require_once(dirname(__FILE__).'/../../autoload/sfCoreAutoload.class.php');
      sfCoreAutoload::make();
    }

    $status = false;
    $statusFile = sys_get_temp_dir().DIRECTORY_SEPARATOR.sprintf('/.test_symfony_%s_status', md5(dirname(__FILE__)));
    if ($options['only-failed'])
    {
      if (file_exists($statusFile))
      {
        $status = unserialize(file_get_contents($statusFile));
      }
    }

    $h = new lime_symfony(array('force_colors' => $options['color'], 'verbose' => $options['trace']));
    $h->base_dir = realpath(dirname(__FILE__).'/../../../test');

    // remove generated files
    if ($options['rebuild-all'])
    {
      $finder = sfFinder::type('dir')->name(array('base', 'om', 'map'));
      foreach ($finder->in(glob($h->base_dir.'/../lib/plugins/*/test/functional/fixtures/lib')) as $dir)
      {
        sfToolkit::clearDirectory($dir);
      }
    }

    if ($status)
    {
      foreach ($status as $file)
      {
        $h->register($file);
      }
    }
    else
    {
      $h->register(sfFinder::type('file')->prune('fixtures')->name('*Test.php')->in(array_merge(
        // unit tests
        array($h->base_dir.'/unit'),
        glob($h->base_dir.'/../lib/plugins/*/test/unit'),

        // functional tests
        array($h->base_dir.'/functional'),
        glob($h->base_dir.'/../lib/plugins/*/test/functional'),

        // other tests
        array($h->base_dir.'/other')
      )));
    }

    $ret = $h->run() ? 0 : 1;

    file_put_contents($statusFile, serialize($h->get_failed_files()));

    if ($options['xml'])
    {
      file_put_contents($options['xml'], $h->to_xml());
    }

    return $ret;
  }
}


text:
/**
 * @module commutable
 */
/**
 *
 * This is the top level data structure for in memory data structures,
 * and allows converting from on-disk v4 and v3 Jupyter Notebooks
 *
 */
import * as v4 from "./v4";
import * as v3 from "./v3";

import { Map as ImmutableMap, List as ImmutableList, Record } from "immutable";

import { ImmutableCell } from "./cells";
import { JSONType, CellId } from "./primitives";

export type NotebookRecordParams = {
  cellOrder: ImmutableList<CellId>;
  cellMap: ImmutableMap<CellId, ImmutableCell>;
  nbformat_minor: number;
  nbformat: number;
  metadata: ImmutableMap<string, any>;
};

export const makeNotebookRecord = Record<NotebookRecordParams>({
  cellOrder: ImmutableList(),
  cellMap: ImmutableMap(),
  nbformat_minor: 0,
  nbformat: 4,
  metadata: ImmutableMap()
});

export type ImmutableNotebook = Record<NotebookRecordParams> &
  Readonly<NotebookRecordParams>;

const freezeReviver = <T extends JSONType>(_k: string, v: T) =>
  Object.freeze(v) as T;

export type Notebook = v4.Notebook | v3.Notebook;

/**
 * Converts a string representation of a notebook into a JSON representation.
 *
 * @param notebookString A string representation of a notebook.
 *
 * @returns A JSON representation of the same notebook.
 */
export const parseNotebook = (notebookString: string): Notebook =>
  JSON.parse(notebookString, freezeReviver);

export const fromJS = (
  notebook: v4.Notebook | v3.Notebook | ImmutableNotebook
) => {
  if (Record.isRecord(notebook)) {
    if (notebook.has("cellOrder") && notebook.has("cellMap")) {
      return notebook;
    }
    throw new TypeError(
      `commutable was passed an Immutable.Record structure that is not a notebook`
    );
  }

  if (notebook.nbformat === 4 && notebook.nbformat_minor >= 0) {
    var v4Notebook = notebook as v4.Notebook;

    if (
      Array.isArray(v4Notebook.cells) &&
      typeof notebook.metadata === "object"
    ) {
      return v4.fromJS(v4Notebook);
    }
  } else if (notebook.nbformat === 3 && notebook.nbformat_minor >= 0) {
    return v3.fromJS(notebook as v3.Notebook);
  }

  if (notebook.nbformat) {
    throw new TypeError(
      `nbformat v${notebook.nbformat}.${notebook.nbformat_minor} not recognized`
    );
  }

  throw new TypeError("This notebook format is not supported");
};
/**
 * Converts an immutable representation of a notebook to a JSON representation of the
 * notebook using the v4 of the nbformat specification.
 *
 * @param immnb The immutable representation of a notebook.
 *
 * @returns The JSON representation of a notebook.
 */
export const toJS = (immnb: ImmutableNotebook): v4.Notebook => {
  const minorVersion: null | number = immnb.get("nbformat_minor", null);

  if (
    immnb.get("nbformat") === 4 &&
    typeof minorVersion === "number" &&
    minorVersion >= 0
  ) {
    return v4.toJS(immnb);
  }
  throw new TypeError("Only notebook formats 3 and 4 are supported!");
};

/**
 * Converts a JSON representation of a notebook into a string representation.
 *
 * @param notebook The JSON representation of a notebook.
 *
 * @returns A string containing the notebook data.
 */
export const stringifyNotebook = (notebook: v4.Notebook) =>
  JSON.stringify(notebook, null, 2);


text:
<?php

declare(strict_types=1);

namespace ApiPlatform\Doctrine\Orm\Filter;

use ApiPlatform\Doctrine\Common\Filter\BooleanFilterTrait;
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use ApiPlatform\Metadata\Operation;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;

/**
 * Filters the collection by boolean values.
 *
 * Filters collection on equality of boolean properties. The value is specified
 * as one of ( "true" | "false" | "1" | "0" ) in the query.
 *
 * For each property passed, if the resource does not have such property or if
 * the value is not one of ( "true" | "false" | "1" | "0" ) the property is ignored.
 *
 * @author Amrouche Hamza <hamza.simperfit@gmail.com>
 * @author Teoh Han Hui <teohhanhui@gmail.com>
 */
final class BooleanFilter extends AbstractFilter
{
    use BooleanFilterTrait;

    public const DOCTRINE_BOOLEAN_TYPES = [
        Types::BOOLEAN => true,
    ];

    /**
     * {@inheritdoc}
     */
    protected function filterProperty(string $property, $value, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, Operation $operation = null, array $context = []): void
    {
        if (
            !$this->isPropertyEnabled($property, $resourceClass) ||
            !$this->isPropertyMapped($property, $resourceClass) ||
            !$this->isBooleanField($property, $resourceClass)
        ) {
            return;
        }

        $value = $this->normalizeValue($value, $property);
        if (null === $value) {
            return;
        }

        $alias = $queryBuilder->getRootAliases()[0];
        $field = $property;

        if ($this->isPropertyNested($property, $resourceClass)) {
            [$alias, $field] = $this->addJoinsForNestedProperty($property, $alias, $queryBuilder, $queryNameGenerator, $resourceClass, Join::INNER_JOIN);
        }

        $valueParameter = $queryNameGenerator->generateParameterName($field);

        $queryBuilder
            ->andWhere(sprintf('%s.%s = :%s', $alias, $field, $valueParameter))
            ->setParameter($valueParameter, $value);
    }
}


text:
#ifndef SHD_FILESERVER_H_
#define SHD_FILESERVER_H_

#include <glib.h>
#include <stddef.h>
#include <stdio.h>
#include <netinet/in.h>
#include <glib-2.0/glib.h>

#include "shd-filetransfer-defs.h"

/*
 * A minimal http server.
 */

/* TODO explain what these codes mean.
 * Note - they MUST be synced with fileserver_code_strings */
enum fileserver_code {
	FS_SUCCESS, FS_CLOSED, FS_ERR_INVALID, FS_ERR_FATAL, FS_ERR_BADSD, FS_ERR_WOULDBLOCK, FS_ERR_BUFSPACE,
	FS_ERR_SOCKET, FS_ERR_BIND, FS_ERR_LISTEN, FS_ERR_ACCEPT, FS_ERR_RECV, FS_ERR_SEND, FS_ERR_CLOSE, FS_ERR_EPOLL,
};

enum fileserver_state {
	FS_IDLE, FS_REQUEST, FS_REPLY_404_START, FS_REPLY_FILE_START, FS_REPLY_FILE_CONTINUE, FS_REPLY_SEND
};

typedef struct fileserver_progress_s {
	gint sockd;
	gsize bytes_read;
	gsize bytes_written;
	gsize reply_length;
	gboolean request_done;
	gboolean reply_done;
	gboolean changed;
} fileserver_progress_t, *fileserver_progress_tp;

typedef struct fileserver_reply_s {
	FILE* f;
	size_t f_length;
	size_t f_read_offset;
	gchar buf[FT_BUF_SIZE];
	size_t buf_read_offset;
	size_t buf_write_offset;
	size_t bytes_sent;
	gboolean done;
} fileserver_reply_t, *fileserver_reply_tp;

typedef struct fileserver_request_s {
	gchar filepath[FT_STR_SIZE];
	gchar buf[FT_STR_SIZE];
	size_t buf_read_offset;
	size_t buf_write_offset;
	size_t bytes_received;
	gboolean done;
} fileserver_request_t, *fileserver_request_tp;

typedef struct fileserver_connection_s {
	/* this connections socket */
	gint sockd;
	/* the current request we are handling */
	fileserver_request_t request;
	/* the current reply we are sending */
	fileserver_reply_t reply;
	/* keep our state so we know what to do next */
	enum fileserver_state state;
} fileserver_connection_t, *fileserver_connection_tp;

typedef struct fileserver_s {
	in_addr_t listen_addr;
	in_port_t listen_port;
	gint listen_sockd;
	gint epolld;
	gchar docroot[FT_STR_SIZE];
	/* client connections keyed by sockd */
	GHashTable *connections;
	/* global stats for this server */
	size_t bytes_received;
	size_t bytes_sent;
	size_t replies_sent;
} fileserver_t, *fileserver_tp;

/* init and start the fileserver
 *
 * fs must not be null, addr and port are in network order, docroot must be at
 * most FS_STRBUFFER_SIZE including the null byte.
 */
enum fileserver_code fileserver_start(fileserver_tp fs, gint epolld, in_addr_t listen_addr, in_port_t listen_port,
		gchar* docroot, gint max_connections);

/* trys to accept a single connection from the listening socket.
 * if sockd_out is not NULL and the accept succeeds, the sockd will be copied there. */
enum fileserver_code fileserver_accept_one(fileserver_tp fs, gint* sockd_out);

/* if given the fileserver's listening sockd, will try to accept as many
 * connections as it can, and returns the result of the first attempt that does
 * not return FS_SUCCESS.
 *
 * otherwise, handles the connection associated with sockd, if any, by replying
 * with the requested content or 404 errors.
 */
enum fileserver_code fileserver_activate(fileserver_tp fs, gint sockd, fileserver_progress_tp progress);

/* close all connections and shutdown the fileserver */
enum fileserver_code fileserver_shutdown(fileserver_tp fs);

/* helpful function for getting a code as ascii. returns NULL on an invalid code. */
const gchar* fileserver_codetoa(enum fileserver_code fsc);

#endif /* SHD_FILESERVER_H_ */


text:
<?php

namespace MetaSyntactical\Icalendar\Property;

use Assert\Assertion;
use DateTime;
use DateTimeZone;

class DateStartProperty extends Property
{
    /**
     * @var DateTime
     */
    private $date;

    private $hasTime = true;

    private $renderTimeZone = false;

    public function __construct(DateTime $date, $hasTime = true, $renderTimeZone = false)
    {
        $this->configure();

        $this->setDate($date);
        $this->setHasTime($hasTime);
        $this->setRenderTimeZone($renderTimeZone);
    }

    public function setDate(DateTime $date)
    {
        $this->date = $date;

        return $this;
    }

    public function setHasTime($hasTime)
    {
        Assertion::boolean($hasTime);

        $this->hasTime = $hasTime;

        return $this;
    }

    public function setRenderTimeZone($renderTimeZone)
    {
        Assertion::boolean($renderTimeZone);

        $this->renderTimeZone = $renderTimeZone;

        return $this;
    }

    public function configure()
    {
        $this->setPropertyName("DTSTART");
        $this->setPropertyDelimiter(";");
    }

    protected function serializeValue()
    {
        $date = clone $this->date;
        $result = "";
        if ($this->renderTimeZone) {

        }
        $result .= ";VALUE=DATE:";
        $result .= $date->format("Ymd");
        if ($this->hasTime) {
            $result .= "T";
            $result .= $date->format("His");
            if (!$this->renderTimeZone) {
                $result .= "Z";
            }
        }

        return trim($result, ";");
    }

}