text:
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include <dev/isci/isci.h>

#include <sys/conf.h>
#include <sys/malloc.h>

#include <cam/cam_periph.h>
#include <cam/cam_xpt_periph.h>

#include <dev/isci/scil/sci_memory_descriptor_list.h>
#include <dev/isci/scil/sci_memory_descriptor_list_decorator.h>

#include <dev/isci/scil/scif_controller.h>
#include <dev/isci/scil/scif_library.h>
#include <dev/isci/scil/scif_io_request.h>
#include <dev/isci/scil/scif_task_request.h>
#include <dev/isci/scil/scif_remote_device.h>
#include <dev/isci/scil/scif_domain.h>
#include <dev/isci/scil/scif_user_callback.h>
#include <dev/isci/scil/scic_sgpio.h>

#include <dev/led/led.h>

void isci_action(struct cam_sim *sim, union ccb *ccb);
void isci_poll(struct cam_sim *sim);

#define ccb_sim_ptr sim_priv.entries[0].ptr

/**
 * @brief This user callback will inform the user that the controller has
 *        had a serious unexpected error.  The user should not the error,
 *        disable interrupts, and wait for current ongoing processing to
 *        complete.  Subsequently, the user should reset the controller.
 *
 * @param[in]  controller This parameter specifies the controller that had
 *                        an error.
 *
 * @return none
 */
void scif_cb_controller_error(SCI_CONTROLLER_HANDLE_T controller,
    SCI_CONTROLLER_ERROR error)
{

	isci_log_message(0, "ISCI", "scif_cb_controller_error: 0x%x\n",
	    error);
}

/**
 * @brief This user callback will inform the user that the controller has
 *        finished the start process.
 *
 * @param[in]  controller This parameter specifies the controller that was
 *             started.
 * @param[in]  completion_status This parameter specifies the results of
 *             the start operation.  SCI_SUCCESS indicates successful
 *             completion.
 *
 * @return none
 */
void scif_cb_controller_start_complete(SCI_CONTROLLER_HANDLE_T controller,
    SCI_STATUS completion_status)
{
	uint32_t index;
	struct ISCI_CONTROLLER *isci_controller = (struct ISCI_CONTROLLER *)
	    sci_object_get_association(controller);

	isci_controller->is_started = TRUE;

	/* Set bits for all domains.  We will clear them one-by-one once
	 *  the domains complete discovery, or return error when calling
	 *  scif_domain_discover.  Once all bits are clear, we will register
	 *  the controller with CAM.
	 */
	isci_controller->initial_discovery_mask = (1 << SCI_MAX_DOMAINS) - 1;

	for(index = 0; index < SCI_MAX_DOMAINS; index++) {
		SCI_STATUS status;
		SCI_DOMAIN_HANDLE_T domain =
		    isci_controller->domain[index].sci_object;

		status = scif_domain_discover(
			domain,
			scif_domain_get_suggested_discover_timeout(domain),
			DEVICE_TIMEOUT
		);

		if (status != SCI_SUCCESS)
		{
			isci_controller_domain_discovery_complete(
			    isci_controller, &isci_controller->domain[index]);
		}
	}
}

/**
 * @brief This user callback will inform the user that the controller has
 *        finished the stop process. Note, after user calls
 *        scif_controller_stop(), before user receives this controller stop
 *        complete callback, user should not expect any callback from
 *        framework, such like scif_cb_domain_change_notification().
 *
 * @param[in]  controller This parameter specifies the controller that was
 *             stopped.
 * @param[in]  completion_status This parameter specifies the results of
 *             the stop operation.  SCI_SUCCESS indicates successful
 *             completion.
 *
 * @return none
 */
void scif_cb_controller_stop_complete(SCI_CONTROLLER_HANDLE_T controller,
    SCI_STATUS completion_status)
{
	struct ISCI_CONTROLLER *isci_controller = (struct ISCI_CONTROLLER *)
	    sci_object_get_association(controller);

	isci_controller->is_started = FALSE;
}

static void
isci_single_map(void *arg, bus_dma_segment_t *seg, int nseg, int error)
{
	SCI_PHYSICAL_ADDRESS *phys_addr = arg;

	*phys_addr = seg[0].ds_addr;
}

/**
 * @brief This method will be invoked to allocate memory dynamically.
 *
 * @param[in]  controller This parameter represents the controller
 *             object for which to allocate memory.
 * @param[out] mde This parameter represents the memory descriptor to
 *             be filled in by the user that will reference the newly
 *             allocated memory.
 *
 * @return none
 */
void scif_cb_controller_allocate_memory(SCI_CONTROLLER_HANDLE_T controller,
    SCI_PHYSICAL_MEMORY_DESCRIPTOR_T *mde)
{
	struct ISCI_CONTROLLER *isci_controller = (struct ISCI_CONTROLLER *)
	    sci_object_get_association(controller);

	/*
	 * Note this routine is only used for buffers needed to translate
	 * SCSI UNMAP commands to ATA DSM commands for SATA disks.
	 *
	 * We first try to pull a buffer from the controller's pool, and only
	 * call contigmalloc if one isn't there.
	 */
	if (!sci_pool_empty(isci_controller->unmap_buffer_pool)) {
		sci_pool_get(isci_controller->unmap_buffer_pool,
		    mde->virtual_address);
	} else
		mde->virtual_address = contigmalloc(PAGE_SIZE,
		    M_ISCI, M_NOWAIT, 0, BUS_SPACE_MAXADDR,
		    mde->constant_memory_alignment, 0);

	if (mde->virtual_address != NULL)
		bus_dmamap_load(isci_controller->buffer_dma_tag,
		    NULL, mde->virtual_address, PAGE_SIZE,
		    isci_single_map, &mde->physical_address,
		    BUS_DMA_NOWAIT);
}

/**
 * @brief This method will be invoked to allocate memory dynamically.
 *
 * @param[in]  controller This parameter represents the controller
 *             object for which to allocate memory.
 * @param[out] mde This parameter represents the memory descriptor to
 *             be filled in by the user that will reference the newly
 *             allocated memory.
 *
 * @return none
 */
void scif_cb_controller_free_memory(SCI_CONTROLLER_HANDLE_T controller,
    SCI_PHYSICAL_MEMORY_DESCRIPTOR_T * mde)
{
	struct ISCI_CONTROLLER *isci_controller = (struct ISCI_CONTROLLER *)
	    sci_object_get_association(controller);

	/*
	 * Put the buffer back into the controller's buffer pool, rather
	 * than invoking configfree.  This helps reduce chance we won't
	 * have buffers available when system is under memory pressure.
	 */
	sci_pool_put(isci_controller->unmap_buffer_pool,
	    mde->virtual_address);
}

void isci_controller_construct(struct ISCI_CONTROLLER *controller,
    struct isci_softc *isci)
{
	SCI_CONTROLLER_HANDLE_T scif_controller_handle;

	scif_library_allocate_controller(isci->sci_library_handle,
	    &scif_controller_handle);

	scif_controller_construct(isci->sci_library_handle,
	    scif_controller_handle, NULL);

	controller->isci = isci;
	controller->scif_controller_handle = scif_controller_handle;

	/* This allows us to later use
	 *  sci_object_get_association(scif_controller_handle)
	 * inside of a callback routine to get our struct ISCI_CONTROLLER object
	 */
	sci_object_set_association(scif_controller_handle, (void *)controller);

	controller->is_started = FALSE;
	controller->is_frozen = FALSE;
	controller->release_queued_ccbs = FALSE;
	controller->sim = NULL;
	controller->initial_discovery_mask = 0;

	sci_fast_list_init(&controller->pending_device_reset_list);

	mtx_init(&controller->lock, "isci", NULL, MTX_DEF);

	uint32_t domain_index;

	for(domain_index = 0; domain_index < SCI_MAX_DOMAINS; domain_index++) {
		isci_domain_construct( &controller->domain[domain_index],
		    domain_index, controller);
	}

	controller->timer_memory = malloc(
	    sizeof(struct ISCI_TIMER) * SCI_MAX_TIMERS, M_ISCI,
	    M_NOWAIT | M_ZERO);

	sci_pool_initialize(controller->timer_pool);

	struct ISCI_TIMER *timer = (struct ISCI_TIMER *)
	    controller->timer_memory;

	for ( int i = 0; i < SCI_MAX_TIMERS; i++ ) {
		sci_pool_put(controller->timer_pool, timer++);
	}

	sci_pool_initialize(controller->unmap_buffer_pool);
}

static void isci_led_fault_func(void *priv, int onoff)
{
	struct ISCI_PHY *phy = priv;

	/* map onoff to the fault LED */
	phy->led_fault = onoff;
	scic_sgpio_update_led_state(phy->handle, 1 << phy->index,
		phy->led_fault, phy->led_locate, 0);
}

static void isci_led_locate_func(void *priv, int onoff)
{
	struct ISCI_PHY *phy = priv;

	/* map onoff to the locate LED */
	phy->led_locate = onoff;
	scic_sgpio_update_led_state(phy->handle, 1 << phy->index,
		phy->led_fault, phy->led_locate, 0);
}

SCI_STATUS isci_controller_initialize(struct ISCI_CONTROLLER *controller)
{
	SCIC_USER_PARAMETERS_T scic_user_parameters;
	SCI_CONTROLLER_HANDLE_T scic_controller_handle;
	char led_name[64];
	unsigned long tunable;
	uint32_t io_shortage;
	uint32_t fail_on_timeout;
	int i;

	scic_controller_handle =
	    scif_controller_get_scic_handle(controller->scif_controller_handle);

	if (controller->isci->oem_parameters_found == TRUE)
	{
		scic_oem_parameters_set(
		    scic_controller_handle,
		    &controller->oem_parameters,
		    (uint8_t)(controller->oem_parameters_version));
	}

	scic_user_parameters_get(scic_controller_handle, &scic_user_parameters);

	if (TUNABLE_ULONG_FETCH("hw.isci.no_outbound_task_timeout", &tunable))
		scic_user_parameters.sds1.no_outbound_task_timeout =
		    (uint8_t)tunable;

	if (TUNABLE_ULONG_FETCH("hw.isci.ssp_max_occupancy_timeout", &tunable))
		scic_user_parameters.sds1.ssp_max_occupancy_timeout =
		    (uint16_t)tunable;

	if (TUNABLE_ULONG_FETCH("hw.isci.stp_max_occupancy_timeout", &tunable))
		scic_user_parameters.sds1.stp_max_occupancy_timeout =
		    (uint16_t)tunable;

	if (TUNABLE_ULONG_FETCH("hw.isci.ssp_inactivity_timeout", &tunable))
		scic_user_parameters.sds1.ssp_inactivity_timeout =
		    (uint16_t)tunable;

	if (TUNABLE_ULONG_FETCH("hw.isci.stp_inactivity_timeout", &tunable))
		scic_user_parameters.sds1.stp_inactivity_timeout =
		    (uint16_t)tunable;

	if (TUNABLE_ULONG_FETCH("hw.isci.max_speed_generation", &tunable))
		for (i = 0; i < SCI_MAX_PHYS; i++)
			scic_user_parameters.sds1.phys[i].max_speed_generation =
			    (uint8_t)tunable;

	scic_user_parameters_set(scic_controller_handle, &scic_user_parameters);

	/* Scheduler bug in SCU requires SCIL to reserve some task contexts as a
	 *  a workaround - one per domain.
	 */
	controller->queue_depth = SCI_MAX_IO_REQUESTS - SCI_MAX_DOMAINS;

	if (TUNABLE_INT_FETCH("hw.isci.controller_queue_depth",
	    &controller->queue_depth)) {
		controller->queue_depth = max(1, min(controller->queue_depth,
		    SCI_MAX_IO_REQUESTS - SCI_MAX_DOMAINS));
	}

	/* Reserve one request so that we can ensure we have one available TC
	 *  to do internal device resets.
	 */
	controller->sim_queue_depth = controller->queue_depth - 1;

	/* Although we save one TC to do internal device resets, it is possible
	 *  we could end up using several TCs for simultaneous device resets
	 *  while at the same time having CAM fill our controller queue.  To
	 *  simulate this condition, and how our driver handles it, we can set
	 *  this io_shortage parameter, which will tell CAM that we have a
	 *  large queue depth than we really do.
	 */
	io_shortage = 0;
	TUNABLE_INT_FETCH("hw.isci.io_shortage", &io_shortage);
	controller->sim_queue_depth += io_shortage;

	fail_on_timeout = 1;
	TUNABLE_INT_FETCH("hw.isci.fail_on_task_timeout", &fail_on_timeout);
	controller->fail_on_task_timeout = fail_on_timeout;

	/* Attach to CAM using xpt_bus_register now, then immediately freeze
	 *  the simq.  It will get released later when initial domain discovery
	 *  is complete.
	 */
	controller->has_been_scanned = FALSE;
	mtx_lock(&controller->lock);
	isci_controller_attach_to_cam(controller);
	xpt_freeze_simq(controller->sim, 1);
	mtx_unlock(&controller->lock);

	for (i = 0; i < SCI_MAX_PHYS; i++) {
		controller->phys[i].handle = scic_controller_handle;
		controller->phys[i].index = i;

		/* fault */
		controller->phys[i].led_fault = 0;
		sprintf(led_name, "isci.bus%d.port%d.fault", controller->index, i);
		controller->phys[i].cdev_fault = led_create(isci_led_fault_func,
		    &controller->phys[i], led_name);

		/* locate */
		controller->phys[i].led_locate = 0;
		sprintf(led_name, "isci.bus%d.port%d.locate", controller->index, i);
		controller->phys[i].cdev_locate = led_create(isci_led_locate_func,
		    &controller->phys[i], led_name);
	}

	return (scif_controller_initialize(controller->scif_controller_handle));
}

int isci_controller_allocate_memory(struct ISCI_CONTROLLER *controller)
{
	int error;
	device_t device =  controller->isci->device;
	uint32_t max_segment_size = isci_io_request_get_max_io_size();
	uint32_t status = 0;
	struct ISCI_MEMORY *uncached_controller_memory =
	    &controller->uncached_controller_memory;
	struct ISCI_MEMORY *cached_controller_memory =
	    &controller->cached_controller_memory;
	struct ISCI_MEMORY *request_memory =
	    &controller->request_memory;
	POINTER_UINT virtual_address;
	bus_addr_t physical_address;

	controller->mdl = sci_controller_get_memory_descriptor_list_handle(
	    controller->scif_controller_handle);

	uncached_controller_memory->size = sci_mdl_decorator_get_memory_size(
	    controller->mdl, SCI_MDE_ATTRIBUTE_PHYSICALLY_CONTIGUOUS);

	error = isci_allocate_dma_buffer(device, uncached_controller_memory);

	if (error != 0)
	    return (error);

	sci_mdl_decorator_assign_memory( controller->mdl,
	    SCI_MDE_ATTRIBUTE_PHYSICALLY_CONTIGUOUS,
	    uncached_controller_memory->virtual_address,
	    uncached_controller_memory->physical_address);

	cached_controller_memory->size = sci_mdl_decorator_get_memory_size(
	    controller->mdl,
	    SCI_MDE_ATTRIBUTE_CACHEABLE | SCI_MDE_ATTRIBUTE_PHYSICALLY_CONTIGUOUS
	);

	error = isci_allocate_dma_buffer(device, cached_controller_memory);

	if (error != 0)
	    return (error);

	sci_mdl_decorator_assign_memory(controller->mdl,
	    SCI_MDE_ATTRIBUTE_CACHEABLE | SCI_MDE_ATTRIBUTE_PHYSICALLY_CONTIGUOUS,
	    cached_controller_memory->virtual_address,
	    cached_controller_memory->physical_address);

	request_memory->size =
	    controller->queue_depth * isci_io_request_get_object_size();

	error = isci_allocate_dma_buffer(device, request_memory);

	if (error != 0)
	    return (error);

	/* For STP PIO testing, we want to ensure we can force multiple SGLs
	 *  since this has been a problem area in SCIL.  This tunable parameter
	 *  will allow us to force DMA segments to a smaller size, ensuring
	 *  that even if a physically contiguous buffer is attached to this
	 *  I/O, the DMA subsystem will pass us multiple segments in our DMA
	 *  load callback.
	 */
	TUNABLE_INT_FETCH("hw.isci.max_segment_size", &max_segment_size);

	/* Create DMA tag for our I/O requests.  Then we can create DMA maps based off
	 *  of this tag and store them in each of our ISCI_IO_REQUEST objects.  This
	 *  will enable better performance than creating the DMA maps everytime we get
	 *  an I/O.
	 */
	status = bus_dma_tag_create(bus_get_dma_tag(device), 0x1, 0x0,
	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL,
	    isci_io_request_get_max_io_size(),
	    SCI_MAX_SCATTER_GATHER_ELEMENTS, max_segment_size, 0, NULL, NULL,
	    &controller->buffer_dma_tag);

	sci_pool_initialize(controller->request_pool);

	virtual_address = request_memory->virtual_address;
	physical_address = request_memory->physical_address;

	for (int i = 0; i < controller->queue_depth; i++) {
		struct ISCI_REQUEST *request =
		    (struct ISCI_REQUEST *)virtual_address;

		isci_request_construct(request,
		    controller->scif_controller_handle,
		    controller->buffer_dma_tag, physical_address);

		sci_pool_put(controller->request_pool, request);

		virtual_address += isci_request_get_object_size();
		physical_address += isci_request_get_object_size();
	}

	uint32_t remote_device_size = sizeof(struct ISCI_REMOTE_DEVICE) +
	    scif_remote_device_get_object_size();

	controller->remote_device_memory = (uint8_t *) malloc(
	    remote_device_size * SCI_MAX_REMOTE_DEVICES, M_ISCI,
	    M_NOWAIT | M_ZERO);

	sci_pool_initialize(controller->remote_device_pool);

	uint8_t *remote_device_memory_ptr = controller->remote_device_memory;

	for (int i = 0; i < SCI_MAX_REMOTE_DEVICES; i++) {
		struct ISCI_REMOTE_DEVICE *remote_device =
		    (struct ISCI_REMOTE_DEVICE *)remote_device_memory_ptr;

		controller->remote_device[i] = NULL;
		remote_device->index = i;
		remote_device->is_resetting = FALSE;
		remote_device->frozen_lun_mask = 0;
		sci_fast_list_element_init(remote_device,
		    &remote_device->pending_device_reset_element);
		TAILQ_INIT(&remote_device->queued_ccbs);
		remote_device->release_queued_ccb = FALSE;
		remote_device->queued_ccb_in_progress = NULL;

		/*
		 * For the first SCI_MAX_DOMAINS device objects, do not put
		 *  them in the pool, rather assign them to each domain.  This
		 *  ensures that any device attached directly to port "i" will
		 *  always get CAM target id "i".
		 */
		if (i < SCI_MAX_DOMAINS)
			controller->domain[i].da_remote_device = remote_device;
		else
			sci_pool_put(controller->remote_device_pool,
			    remote_device);
		remote_device_memory_ptr += remote_device_size;
	}

	return (0);
}

void isci_controller_start(void *controller_handle)
{
	struct ISCI_CONTROLLER *controller =
	    (struct ISCI_CONTROLLER *)controller_handle;
	SCI_CONTROLLER_HANDLE_T scif_controller_handle =
	    controller->scif_controller_handle;

	scif_controller_start(scif_controller_handle,
	    scif_controller_get_suggested_start_timeout(scif_controller_handle));

	scic_controller_enable_interrupts(
	    scif_controller_get_scic_handle(controller->scif_controller_handle));
}

void isci_controller_domain_discovery_complete(
    struct ISCI_CONTROLLER *isci_controller, struct ISCI_DOMAIN *isci_domain)
{
	if (!isci_controller->has_been_scanned)
	{
		/* Controller has not been scanned yet.  We'll clear
		 *  the discovery bit for this domain, then check if all bits
		 *  are now clear.  That would indicate that all domains are
		 *  done with discovery and we can then proceed with initial
		 *  scan.
		 */

		isci_controller->initial_discovery_mask &=
		    ~(1 << isci_domain->index);

		if (isci_controller->initial_discovery_mask == 0) {
			struct isci_softc *driver = isci_controller->isci;
			uint8_t next_index = isci_controller->index + 1;

			isci_controller->has_been_scanned = TRUE;

			/* Unfreeze simq to allow initial scan to proceed. */
			xpt_release_simq(isci_controller->sim, TRUE);

#if __FreeBSD_version < 800000
			/* When driver is loaded after boot, we need to
			 *  explicitly rescan here for versions <8.0, because
			 *  CAM only automatically scans new buses at boot
			 *  time.
			 */
			union ccb *ccb = xpt_alloc_ccb_nowait();

			xpt_create_path(&ccb->ccb_h.path, NULL,
			    cam_sim_path(isci_controller->sim),
			    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);

			xpt_rescan(ccb);
#endif

			if (next_index < driver->controller_count) {
				/*  There are more controllers that need to
				 *   start.  So start the next one.
				 */
				isci_controller_start(
				    &driver->controllers[next_index]);
			}
			else
			{
				/* All controllers have been started and completed discovery.
				 *  Disestablish the config hook while will signal to the
				 *  kernel during boot that it is safe to try to find and
				 *  mount the root partition.
				 */
				config_intrhook_disestablish(
				    &driver->config_hook);
			}
		}
	}
}

int isci_controller_attach_to_cam(struct ISCI_CONTROLLER *controller)
{
	struct isci_softc *isci = controller->isci;
	device_t parent = device_get_parent(isci->device);
	int unit = device_get_unit(isci->device);
	struct cam_devq *isci_devq = cam_simq_alloc(controller->sim_queue_depth);

	if(isci_devq == NULL) {
		isci_log_message(0, "ISCI", "isci_devq is NULL \n");
		return (-1);
	}

	controller->sim = cam_sim_alloc(isci_action, isci_poll, "isci",
	    controller, unit, &controller->lock, controller->sim_queue_depth,
	    controller->sim_queue_depth, isci_devq);

	if(controller->sim == NULL) {
		isci_log_message(0, "ISCI", "cam_sim_alloc... fails\n");
		cam_simq_free(isci_devq);
		return (-1);
	}

	if(xpt_bus_register(controller->sim, parent, controller->index)
	    != CAM_SUCCESS) {
		isci_log_message(0, "ISCI", "xpt_bus_register...fails \n");
		cam_sim_free(controller->sim, TRUE);
		mtx_unlock(&controller->lock);
		return (-1);
	}

	if(xpt_create_path(&controller->path, NULL,
	    cam_sim_path(controller->sim), CAM_TARGET_WILDCARD,
	    CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
		isci_log_message(0, "ISCI", "xpt_create_path....fails\n");
		xpt_bus_deregister(cam_sim_path(controller->sim));
		cam_sim_free(controller->sim, TRUE);
		mtx_unlock(&controller->lock);
		return (-1);
	}

	return (0);
}

void isci_poll(struct cam_sim *sim)
{
	struct ISCI_CONTROLLER *controller =
	    (struct ISCI_CONTROLLER *)cam_sim_softc(sim);

	isci_interrupt_poll_handler(controller);
}

void isci_action(struct cam_sim *sim, union ccb *ccb)
{
	struct ISCI_CONTROLLER *controller =
	    (struct ISCI_CONTROLLER *)cam_sim_softc(sim);

	switch ( ccb->ccb_h.func_code ) {
	case XPT_PATH_INQ:
		{
			struct ccb_pathinq *cpi = &ccb->cpi;
			int bus = cam_sim_bus(sim);
			ccb->ccb_h.ccb_sim_ptr = sim;
			cpi->version_num = 1;
			cpi->hba_inquiry = PI_TAG_ABLE;
			cpi->target_sprt = 0;
			cpi->hba_misc = PIM_NOBUSRESET | PIM_SEQSCAN |
			    PIM_UNMAPPED;
			cpi->hba_eng_cnt = 0;
			cpi->max_target = SCI_MAX_REMOTE_DEVICES - 1;
			cpi->max_lun = ISCI_MAX_LUN;
#if __FreeBSD_version >= 800102
			cpi->maxio = isci_io_request_get_max_io_size();
#endif
			cpi->unit_number = cam_sim_unit(sim);
			cpi->bus_id = bus;
			cpi->initiator_id = SCI_MAX_REMOTE_DEVICES;
			cpi->base_transfer_speed = 300000;
			strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
			strncpy(cpi->hba_vid, "Intel Corp.", HBA_IDLEN);
			strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
			cpi->transport = XPORT_SAS;
			cpi->transport_version = 0;
			cpi->protocol = PROTO_SCSI;
			cpi->protocol_version = SCSI_REV_SPC2;
			cpi->ccb_h.status = CAM_REQ_CMP;
			xpt_done(ccb);
		}
		break;
	case XPT_GET_TRAN_SETTINGS:
		{
			struct ccb_trans_settings *general_settings = &ccb->cts;
			struct ccb_trans_settings_sas *sas_settings =
			    &general_settings->xport_specific.sas;
			struct ccb_trans_settings_scsi *scsi_settings =
			    &general_settings->proto_specific.scsi;
			struct ISCI_REMOTE_DEVICE *remote_device;

			remote_device = controller->remote_device[ccb->ccb_h.target_id];

			if (remote_device == NULL) {
				ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
				ccb->ccb_h.status &= ~CAM_STATUS_MASK;
				ccb->ccb_h.status |= CAM_DEV_NOT_THERE;
				xpt_done(ccb);
				break;
			}

			general_settings->protocol = PROTO_SCSI;
			general_settings->transport = XPORT_SAS;
			general_settings->protocol_version = SCSI_REV_SPC2;
			general_settings->transport_version = 0;
			scsi_settings->valid = CTS_SCSI_VALID_TQ;
			scsi_settings->flags = CTS_SCSI_FLAGS_TAG_ENB;
			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
			ccb->ccb_h.status |= CAM_REQ_CMP;

			sas_settings->bitrate =
			    isci_remote_device_get_bitrate(remote_device);

			if (sas_settings->bitrate != 0)
				sas_settings->valid = CTS_SAS_VALID_SPEED;

			xpt_done(ccb);
		}
		break;
	case XPT_SCSI_IO:
		isci_io_request_execute_scsi_io(ccb, controller);
		break;
#if __FreeBSD_version >= 900026
	case XPT_SMP_IO:
		isci_io_request_execute_smp_io(ccb, controller);
		break;
#endif
	case XPT_SET_TRAN_SETTINGS:
		ccb->ccb_h.status &= ~CAM_STATUS_MASK;
		ccb->ccb_h.status |= CAM_REQ_CMP;
		xpt_done(ccb);
		break;
	case XPT_CALC_GEOMETRY:
		cam_calc_geometry(&ccb->ccg, /*extended*/1);
		xpt_done(ccb);
		break;
	case XPT_RESET_DEV:
		{
			struct ISCI_REMOTE_DEVICE *remote_device =
			    controller->remote_device[ccb->ccb_h.target_id];

			if (remote_device != NULL)
				isci_remote_device_reset(remote_device, ccb);
			else {
				ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
				ccb->ccb_h.status &= ~CAM_STATUS_MASK;
				ccb->ccb_h.status |= CAM_DEV_NOT_THERE;
				xpt_done(ccb);
			}
		}
		break;
	case XPT_RESET_BUS:
		ccb->ccb_h.status = CAM_REQ_CMP;
		xpt_done(ccb);
		break;
	default:
		isci_log_message(0, "ISCI", "Unhandled func_code 0x%x\n",
		    ccb->ccb_h.func_code);
		ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
		ccb->ccb_h.status &= ~CAM_STATUS_MASK;
		ccb->ccb_h.status |= CAM_REQ_INVALID;
		xpt_done(ccb);
		break;
	}
}

/*
 * Unfortunately, SCIL doesn't cleanly handle retry conditions.
 *  CAM_REQUEUE_REQ works only when no one is using the pass(4) interface.  So
 *  when SCIL denotes an I/O needs to be retried (typically because of mixing
 *  tagged/non-tagged ATA commands, or running out of NCQ slots), we queue
 *  these I/O internally.  Once SCIL completes an I/O to this device, or we get
 *  a ready notification, we will retry the first I/O on the queue.
 *  Unfortunately, SCIL also doesn't cleanly handle starting the new I/O within
 *  the context of the completion handler, so we need to retry these I/O after
 *  the completion handler is done executing.
 */
void
isci_controller_release_queued_ccbs(struct ISCI_CONTROLLER *controller)
{
	struct ISCI_REMOTE_DEVICE *dev;
	struct ccb_hdr *ccb_h;
	int dev_idx;

	KASSERT(mtx_owned(&controller->lock), ("controller lock not owned"));

	controller->release_queued_ccbs = FALSE;
	for (dev_idx = 0;
	     dev_idx < SCI_MAX_REMOTE_DEVICES;
	     dev_idx++) {

		dev = controller->remote_device[dev_idx];
		if (dev != NULL &&
		    dev->release_queued_ccb == TRUE &&
		    dev->queued_ccb_in_progress == NULL) {
			dev->release_queued_ccb = FALSE;
			ccb_h = TAILQ_FIRST(&dev->queued_ccbs);

			if (ccb_h == NULL)
				continue;

			isci_log_message(1, "ISCI", "release %p %x\n", ccb_h,
			    ((union ccb *)ccb_h)->csio.cdb_io.cdb_bytes[0]);

			dev->queued_ccb_in_progress = (union ccb *)ccb_h;
			isci_io_request_execute_scsi_io(
			    (union ccb *)ccb_h, controller);
		}
	}
}


text:
namespace media {
class FileIOTestRunner;
class CdmVideoDecoder;
class DecoderBuffer;
class FFmpegCdmAudioDecoder;

// Clear key implementation of the cdm::ContentDecryptionModule interface.
class ClearKeyCdm : public ClearKeyCdmInterface {
 public:
  ClearKeyCdm(Host* host, const std::string& key_system);
  virtual ~ClearKeyCdm();

  // ContentDecryptionModule implementation.
  virtual void CreateSession(
      uint32 session_id,
      const char* type, uint32 type_size,
      const uint8* init_data, uint32 init_data_size) OVERRIDE;
  virtual void LoadSession(
      uint32_t session_id,
      const char* web_session_id, uint32_t web_session_id_length) OVERRIDE;
  virtual void UpdateSession(
      uint32 session_id,
      const uint8* response, uint32 response_size) OVERRIDE;
  virtual void ReleaseSession(uint32 session_id) OVERRIDE;
  virtual void TimerExpired(void* context) OVERRIDE;
  virtual cdm::Status Decrypt(const cdm::InputBuffer& encrypted_buffer,
                              cdm::DecryptedBlock* decrypted_block) OVERRIDE;
  virtual cdm::Status InitializeAudioDecoder(
      const cdm::AudioDecoderConfig& audio_decoder_config) OVERRIDE;
  virtual cdm::Status InitializeVideoDecoder(
      const cdm::VideoDecoderConfig& video_decoder_config) OVERRIDE;
  virtual void DeinitializeDecoder(cdm::StreamType decoder_type) OVERRIDE;
  virtual void ResetDecoder(cdm::StreamType decoder_type) OVERRIDE;
  virtual cdm::Status DecryptAndDecodeFrame(
      const cdm::InputBuffer& encrypted_buffer,
      cdm::VideoFrame* video_frame) OVERRIDE;
  virtual cdm::Status DecryptAndDecodeSamples(
      const cdm::InputBuffer& encrypted_buffer,
      cdm::AudioFrames* audio_frames) OVERRIDE;
  virtual void Destroy() OVERRIDE;
  virtual void OnPlatformChallengeResponse(
      const cdm::PlatformChallengeResponse& response) OVERRIDE;
  virtual void OnQueryOutputProtectionStatus(
      uint32_t link_mask, uint32_t output_protection_mask) OVERRIDE;

 private:
  // Emulates a session stored for |session_id_for_emulated_loadsession_|. This
  // is necessary since aes_decryptor.cc does not support storing sessions.
  void LoadLoadableSession();

  // ContentDecryptionModule callbacks.
  void OnSessionCreated(uint32 session_id, const std::string& web_session_id);
  void OnSessionMessage(uint32 session_id,
                        const std::vector<uint8>& message,
                        const std::string& destination_url);
  void OnSessionReady(uint32 session_id);
  void OnSessionClosed(uint32 session_id);
  void OnSessionError(uint32 session_id,
                      MediaKeys::KeyError error_code,
                      int system_code);

  // Prepares next heartbeat message and sets a timer for it.
  void ScheduleNextHeartBeat();

  // Decrypts the |encrypted_buffer| and puts the result in |decrypted_buffer|.
  // Returns cdm::kSuccess if decryption succeeded. The decrypted result is
  // put in |decrypted_buffer|. If |encrypted_buffer| is empty, the
  // |decrypted_buffer| is set to an empty (EOS) buffer.
  // Returns cdm::kNoKey if no decryption key was available. In this case
  // |decrypted_buffer| should be ignored by the caller.
  // Returns cdm::kDecryptError if any decryption error occurred. In this case
  // |decrypted_buffer| should be ignored by the caller.
  cdm::Status DecryptToMediaDecoderBuffer(
      const cdm::InputBuffer& encrypted_buffer,
      scoped_refptr<DecoderBuffer>* decrypted_buffer);

#if defined(CLEAR_KEY_CDM_USE_FAKE_AUDIO_DECODER)
  int64 CurrentTimeStampInMicroseconds() const;

  // Generates fake video frames with |duration_in_microseconds|.
  // Returns the number of samples generated in the |audio_frames|.
  int GenerateFakeAudioFramesFromDuration(int64 duration_in_microseconds,
                                          cdm::AudioFrames* audio_frames) const;

  // Generates fake video frames given |input_timestamp|.
  // Returns cdm::kSuccess if any audio frame is successfully generated.
  cdm::Status GenerateFakeAudioFrames(int64 timestamp_in_microseconds,
                                      cdm::AudioFrames* audio_frames);
#endif  // CLEAR_KEY_CDM_USE_FAKE_AUDIO_DECODER

  void StartFileIOTest();

  // Callback for CDM File IO test.
  void OnFileIOTestComplete(bool success);

  AesDecryptor decryptor_;

  ClearKeyCdmHost* host_;

  const std::string key_system_;

  uint32 last_session_id_;
  std::string next_heartbeat_message_;

  // TODO(xhwang): Extract testing code from main implementation.
  // See http://crbug.com/341751
  uint32 session_id_for_emulated_loadsession_;

  // Timer delay in milliseconds for the next host_->SetTimer() call.
  int64 timer_delay_ms_;

  // Indicates whether a heartbeat timer has been set to prevent multiple timers
  // from running.
  bool heartbeat_timer_set_;

#if defined(CLEAR_KEY_CDM_USE_FAKE_AUDIO_DECODER)
  int channel_count_;
  int bits_per_channel_;
  int samples_per_second_;
  int64 output_timestamp_base_in_microseconds_;
  int total_samples_generated_;
#endif  // CLEAR_KEY_CDM_USE_FAKE_AUDIO_DECODER

#if defined(CLEAR_KEY_CDM_USE_FFMPEG_DECODER)
  scoped_ptr<FFmpegCdmAudioDecoder> audio_decoder_;
#endif  // CLEAR_KEY_CDM_USE_FFMPEG_DECODER

  scoped_ptr<CdmVideoDecoder> video_decoder_;

  scoped_ptr<FileIOTestRunner> file_io_test_runner_;

  DISALLOW_COPY_AND_ASSIGN(ClearKeyCdm);
};

}  // namespace media

#endif  // MEDIA_CDM_PPAPI_EXTERNAL_CLEAR_KEY_CLEAR_KEY_CDM_H_

redpajama_set_name: RedPajamaGithub


text:
"""SeaMicro specific database schema/model."""
import sqlalchemy as sa

from neutron.db import model_base
from neutron.db import models_v2

class ML2_SeaMicroNetwork(model_base.BASEV2, models_v2.HasId,
                          models_v2.HasTenant):
    """Schema for SeaMicro network."""

    vlan = sa.Column(sa.String(10))
    segment_id = sa.Column(sa.String(36))
    network_type = sa.Column(sa.String(10))
    tenant_id = sa.Column(sa.String(36))

class ML2_SeaMicroPort(model_base.BASEV2, models_v2.HasId,
                       models_v2.HasTenant):
    """Schema for SeaMicro port."""
    network_id = sa.Column(sa.String(36),
                           nullable=False)
    vlan_id = sa.Column(sa.String(36))
    tenant_id = sa.Column(sa.String(36))

def create_network(context, net_id, vlan, segment_id, network_type, tenant_id):
    """Create a SeaMicro specific network."""

    # only network_type of vlan is supported
    session = context.session
    with session.begin(subtransactions=True):
        net = get_network(context, net_id, None)
        if not net:
            net = ML2_SeaMicroNetwork(id=net_id, vlan=vlan,
                                      segment_id=segment_id,
                                      network_type='vlan',
                                      tenant_id=tenant_id)
            session.add(net)
    return net

def delete_network(context, net_id):
    """Delete a SeaMicro specific network."""

    session = context.session
    with session.begin(subtransactions=True):
        net = get_network(context, net_id, None)
        if net:
            session.delete(net)
            return net

def get_network(context, net_id, fields=None):
    """Get SeaMicro specific network, with vlan extension."""

    session = context.session
    return session.query(ML2_SeaMicroNetwork).filter_by(id=net_id).first()

def get_networks(context, filters=None, fields=None):
    """Get all SeaMicro specific networks."""

    session = context.session
    return session.query(ML2_SeaMicroNetwork).all()

def create_port(context, port_id, network_id, vlan_id, tenant_id):
    """Create a SeaMicro specific port, has policy like vlan."""

    session = context.session
    with session.begin(subtransactions=True):
        port = get_port(context, port_id)
        if not port:
            port = ML2_SeaMicroPort(id=port_id,
                                    network_id=network_id,
                                    vlan_id=vlan_id,
                                    tenant_id=tenant_id)
            session.add(port)

    return port

def get_port(context, port_id):
    """get a SeaMicro specific port."""

    session = context.session
    return session.query(ML2_SeaMicroPort).filter_by(id=port_id).first()

def get_ports(context, network_id=None):
    """get a SeaMicro specific ports."""

    session = context.session
    return session.query(ML2_SeaMicroPort).filter_by(
        network_id=network_id).all()

def delete_port(context, port_id):
    """delete SeaMicro specific port."""

    session = context.session
    with session.begin(subtransactions=True):
        port = get_port(context, port_id)
        if port:
            session.delete(port)
            return port


text:
/**
 * @author Rupak Chakraborty
 * Implements the fuzzy k means algorithm
 */
package org.jcluster.fuzzykmeans;


text:
using System;
using System.Collections.Generic;
using System.Text;
using Google.GData.Extensions.Apps;
using Google.GData.Apps;

namespace GoogleAppsConsoleApplication
{
    class AppsMultiDomainDemo
    {
        private static string primaryDomain;
        private static string secondaryDomain;
        private static string adminEmail;
        private static string adminPassword;
        private static string testUserEmail;

        /// <summary>
        /// This console application demonstrates all the Google Apps
        /// MultiDomain Management APIs.
        /// </summary>
        /// <param name="args">Command-line arguments: args[0] is
        /// the primary domain, args[1] is the secondary domain,
        /// args[2] is the admin email address, args[3] is the admin
        /// password and args[4] is test user(email address)
        ///
        /// Example: AppsMultiDomainDemo example.com alias.com admin@example.com my_password test_user_email</param>
        public static void Main(string[] args)
        {
            if (args.Length != 5)
            {
                Console.WriteLine("Syntax: AppsMultiDomainDemo <primary_domain> <secondary_domain> <admin_email> <admin_password> <testUserEmail>");
            }
            else
            {
                primaryDomain = args[0];
                secondaryDomain = args[1];
                adminEmail = args[2];
                adminPassword = args[3];
                testUserEmail = args[4];

                MultiDomainManagementService service = new MultiDomainManagementService(primaryDomain, "multidomainapis-apps-demo");
                service.setUserCredentials(adminEmail, adminPassword);

                RunSample(service);
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="service"></param>
        private static void RunSample(MultiDomainManagementService service)
        {
            const String testUserHashFunction = "SHA-1";
            const String testUserPassword = "51eea05d46317fadd5cad6787a8f562be90b4446";
            const String testUserFirstName = "Liz";
            const String testUserLastName = "Smith";
            const bool testUserIsAdmin = true;
            const String testUserNewFirstName = "Elizabeth";
            String testUserNewEmail = "liz@" + secondaryDomain;
            String testUserAliasEmail = "helpdesk@" + secondaryDomain;

            try
            {
                // Create a new Domain User
                Console.WriteLine("\n-----------Creating domain user-----------");
                AppsExtendedEntry entry = service.CreateDomainUser(primaryDomain, testUserEmail, testUserPassword,
                    testUserHashFunction, testUserFirstName, testUserLastName, testUserIsAdmin);
                Console.WriteLine("Created: " +
                                  entry.getPropertyValueByName(AppsMultiDomainNameTable.UserEmail));

                // Update Domain User and list all properties
                Console.WriteLine("\n-----------Updating domain user----");
                IDictionary<MultiDomainManagementService.MultiDomainUserProperty, string> updates =
                    new Dictionary<MultiDomainManagementService.MultiDomainUserProperty, string>();
                updates[MultiDomainManagementService.MultiDomainUserProperty.FirstName] = testUserNewFirstName;
                entry = service.UpdateDomainUser(primaryDomain, testUserEmail, updates);
                foreach (PropertyElement element in entry.Properties)
                {
                    Console.WriteLine(String.Format("{0} - {1}", element.Name, element.Value));
                }

                // Create a new Domain User to be renamed
                Console.WriteLine("\n-----------Creating domain user to be renamed-----------");
                String tempEmail = "TOBERENAMED@" + primaryDomain;
                entry = service.CreateDomainUser(primaryDomain, tempEmail, testUserPassword,
                                                 testUserFirstName, testUserLastName, testUserIsAdmin);
                Console.WriteLine("Created: " +
                                  entry.getPropertyValueByName(AppsMultiDomainNameTable.UserEmail));

                // Rename Domain User
                Console.WriteLine("\n-----------Renaming domain user---------------------");
                entry = service.RenameDomainUser(primaryDomain, tempEmail, testUserNewEmail);
                Console.WriteLine("Renamed domain user: " +
                                  entry.getPropertyValueByName(AppsMultiDomainNameTable.NewEmail));

                // Retrieve Domain User
                Console.WriteLine("\n-----------Retrieving domain user----");
                entry = service.RetrieveDomainUser(primaryDomain, testUserEmail);
                String firstName =
                    entry.getPropertyValueByName(AppsMultiDomainNameTable.FirstName);
                Console.WriteLine("FirstName: " + firstName);

                // Retrieve all domain users unit and list the emails
                Console.WriteLine("\n-----------Retrieving all domain users----");
                AppsExtendedFeed feed = service.RetrieveAllDomainUsers(primaryDomain);
                foreach (AppsExtendedEntry unit in feed.Entries)
                {
                    Console.WriteLine(
                        unit.getPropertyValueByName(AppsMultiDomainNameTable.UserEmail));
                }

                // Create a new User Alias
                Console.WriteLine("\n-----------Creating user alias-----------");
                entry = service.CreateDomainUserAlias(primaryDomain, testUserEmail, testUserAliasEmail);
                Console.WriteLine("Created Alias: " +
                                  entry.getPropertyValueByName(AppsMultiDomainNameTable.AliasEmail));

                // Retrieve User Alias
                entry = service.RetrieveDomainUserAlias(primaryDomain, testUserAliasEmail);
                String userEmail =
                    entry.getPropertyValueByName(AppsMultiDomainNameTable.UserEmail);
                Console.WriteLine("UserEmail: " + userEmail);

                // Retrieve all user aliases for the domain
                Console.WriteLine("\n-----------Retrieving all user aliases----");
                feed = service.RetrieveAllDomainUserAlias(primaryDomain);
                foreach (AppsExtendedEntry unit in feed.Entries)
                {
                    Console.WriteLine(
                        unit.getPropertyValueByName(AppsMultiDomainNameTable.UserEmail));
                }

                // Retrieve all aliases for an user
                Console.WriteLine("\n-----------Retrieving all aliases for user----");
                feed = service.RetrieveAllDomainUserAliasForUser(primaryDomain, testUserEmail);
                foreach (AppsExtendedEntry unit in feed.Entries)
                {
                    Console.WriteLine(
                        unit.getPropertyValueByName(AppsMultiDomainNameTable.AliasEmail));
                }

                // Delete User Alias
                Console.WriteLine("\n-----------Deleting alias----");
                service.DeleteDomainUserAlias(primaryDomain, testUserAliasEmail);

                // Delete User
                Console.WriteLine("\n-----------Deleting user----");
                service.DeleteDomainUser(primaryDomain, testUserEmail);
            }
            catch (AppsException a)
            {
                Console.WriteLine("A Google Apps error occurred.");
                Console.WriteLine();
                Console.WriteLine("Error code: {0}", a.ErrorCode);
                Console.WriteLine("Invalid input: {0}", a.InvalidInput);
                Console.WriteLine("Reason: {0}", a.Reason);
            }
        }
    }
}


text:
package org.scaleborn.linereg.calculation.statistics;

import org.elasticsearch.test.ESTestCase;
import org.junit.Test;
import org.scaleborn.linereg.TestModels;
import org.scaleborn.linereg.TestModels.TestModel;
import org.scaleborn.linereg.estimation.DerivationEquationSolver.EstimationException;

/**
 * Tests for {@link StatsCalculator}.
 * Created by mbok on 19.03.17.
 */
public class StatsBuilderTests extends ESTestCase {

  @Test
  public void testStats() throws EstimationException {
    testStatsForModel(TestModels.SIMPLE_MODEL_1);
    testStatsForModel(TestModels.MULTI_FEATURES_2_MODEL_1);
    testStatsForModel(TestModels.MULTI_FEATURES_3_MODEL_1);
    testStatsForModel(TestModels.MULTI_FEATURES_6_LONGLEY);
  }

  private void testStatsForModel(final TestModel testModel) throws EstimationException {
    final StatsModel linearModel = testModel.evaluateModel();
    final Statistics statistics = new StatsCalculator().calculate(linearModel);
    testModel.assertStatistics(statistics);
  }
}


text:
import moment from 'moment-timezone';
import Tags from 'app/components/Tags';
import Tag from 'app/components/Tags/Tag';
import Time from 'app/components/Time';
import type { Event, Article } from 'app/models';
import { eventTypeToString } from 'app/routes/events/utils';
import truncateString from 'app/utils/truncateString';
import styles from './Overview.css';

export const renderMeta = (
  item: (Event | Article) & {
    documentType: string;
  }
) => {
  const isEvent = item.eventType ? true : false;
  return (

      <Time //$FlowFixMe[incompatible-type]
        time={isEvent ? item.startTime : item.createdAt}
        format={
          moment().year() === moment(item.startTime).year()
            ? 'DD. MMM HH:mm'
            : 'DD. MMM YYYY HH:mm'
        }
      />

      {item.location !== '-' && isEvent && (

           •
           {truncateString(item.location, 8)}

      )}

       •

        {' '}
        {isEvent ? eventTypeToString(item.eventType) : 'Artikkel'}{' '}

      {item.tags?.length > 0 && (
        <Tags className={styles.tagline}>
          {item.tags.slice(0, 3).map((tag) => (
            <Tag tag={tag} key={tag} />
          ))}
        </Tags>
      )}

  );
};


text:
module MyMongoid
  class Field
    attr_accessor :name
    attr_accessor :options

    def initialize(name, options={})
      @name = name
      @options = options
    end
  end
end


text:
// Code generated by client-gen. DO NOT EDIT.

package fake

import (
	rest "k8s.io/client-go/rest"
	testing "k8s.io/client-go/testing"
	v1 "k8s.io/ingress-gce/pkg/serviceattachment/client/clientset/versioned/typed/serviceattachment/v1"
)

type FakeNetworkingV1 struct {
	*testing.Fake
}

func (c *FakeNetworkingV1) ServiceAttachments(namespace string) v1.ServiceAttachmentInterface {
	return &FakeServiceAttachments{c, namespace}
}

// RESTClient returns a RESTClient that is used to communicate
// with API server by this client implementation.
func (c *FakeNetworkingV1) RESTClient() rest.Interface {
	var ret *rest.RESTClient
	return ret
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:paddingTop="13dp" >

    <TextView
        android:id="@+id/timestamp"
        style="@style/chat_text_date_style"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="right"
        android:layout_marginTop="@dimen/margin_chat_activity" >

        <ProgressBar
            android:id="@+id/progress_bar"
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:layout_gravity="center_vertical"
            android:visibility="gone" />

        <TextView
            android:id="@+id/tv_delivered"
            style="@style/chat_text_name_style"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:text="@string/text_delivered_msg"
            android:textSize="12sp"
            android:visibility="gone" />

        <TextView
            android:id="@+id/tv_ack"
            style="@style/chat_text_name_style"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:text="@string/text_ack_msg"
            android:textSize="12sp"
            android:visibility="gone" />

        <ImageView
            android:id="@+id/msg_status"
            android:layout_width="22dp"
            android:layout_height="22dp"
            android:layout_gravity="center_vertical"
            android:clickable="true"
            android:src="@drawable/hd_msg_state_fail"
            android:visibility="visible" />

        <RelativeLayout
            android:id="@+id/bubble"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="@dimen/margin_chat_activity"
            android:background="@drawable/hd_chatto_bg"
            >

            <TextView
                android:id="@+id/tv_chatcontent"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:autoLink="web"
                android:layout_centerInParent="true"
                android:gravity="center|left"
                android:paddingRight="6dp"
                android:paddingLeft="1dp"
                android:minHeight="38dp"
                android:lineSpacingExtra="2dp"
                android:textColor="#000000"
                android:maxWidth="225.0dip"
                android:textSize="15sp" />

        </RelativeLayout>

        <ImageView
            android:id="@+id/iv_userhead"
            android:layout_width="@dimen/size_avatar"
            android:layout_height="@dimen/size_avatar"
            android:layout_marginRight="@dimen/margin_chat_activity"
            android:background="@drawable/hd_default_avatar"
            android:scaleType="fitXY"/>

       <!--  <TextView
            android:id="@+id/tv_userid"
            android:visibility="gone"
            style="@style/chat_text_name_style"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="15dp"
            android:layout_toLeftOf="@id/iv_userhead"
            android:text="xxx" /> -->

    </LinearLayout>

</LinearLayout>


text:
/*
© 2017 Altavant Technologies Inc.
Web: http://www.altavant.com
*/

namespace Altavant.Fusion.Layouting
{
	using Fusion.Utils;
	using Fusion.Layouting.Data;

	internal class Placeholder : Element, IPlaceholder
	{
		private class Features
		{
			private Placeholder _placeholder;
			private Width _width;
			private Height _height;
			private Spacings _spacings;
			private Visibility? _visibility;

			public Features(Placeholder placeholder)
			{
				_placeholder = placeholder;
			}

			public Width Width
			{
				get
				{
					if (_width == null)
						_width = (Width)_placeholder.GetFeature(Element.Feature.Width);

					return _width;
				}
			}

			public Height Height
			{
				get
				{
					if (_height == null)
						_height = (Height)_placeholder.GetFeature(Element.Feature.Height);

					return _height;
				}
			}

			public Spacings Spacings
			{
				get
				{
					if (_spacings == null)
						_spacings = (Spacings)_placeholder.GetFeature(Element.Feature.Spacings);

					return _spacings;
				}
			}

			public Visibility Visibility
			{
				get
				{
					if (_visibility == null)
						_visibility = (Visibility?)_placeholder.GetFeature(Element.Feature.Visibility);

					return _visibility.Value;
				}
			}

			public void Reset(Feature feature)
			{
				switch (feature)
				{
					case Feature.Width:
						_width = null;

						break;

					case Feature.Height:
						_height = null;

						break;

					case Feature.Spacings:
						_spacings = null;

						break;

					case Feature.Visibility:
						_visibility = null;

						break;
				}
			}

			public void Reset()
			{
				_width = null;
				_height = null;
				_spacings = null;
				_visibility = null;
			}
		}

		private Width _width;
		private Height _height;
		private Spacings _spacings;
		private Visibility _visibility;
		private Features _features;

		public Placeholder(Layout layout, Element parent)
			: base(layout, parent)
		{
			_width = Width.Default;
			_height = Height.Default;
			_spacings = Spacings.Default;
			_visibility = Visibility.Visible;
			_features = new Features(this);
		}

		public override ElementType Type
		{
			get
			{
				return ElementType.Placeholder;
			}
		}

		public Width Width
		{
			get
			{
				if (_width == Width.Default)
					_width = new Width();

				return _features.Width;
			}
			set
			{
				if (value != null)
					_width = value;
				else
					_width = Width.Default;

				_features.Reset(Feature.Width);
			}
		}

		public Height Height
		{
			get
			{
				if (_height == Height.Default)
					_height = new Height();

				return _features.Height;
			}
			set
			{
				if (value != null)
					_height = value;
				else
					_height = Height.Default;

				_features.Reset(Feature.Height);
			}
		}

		public Spacings Spacings
		{
			get
			{
				if (_spacings == Spacings.Default)
					_spacings = new Spacings();

				return _features.Spacings;
			}
			set
			{
				if (value != null)
					_spacings = value;
				else
					_spacings = Spacings.Default;

				_features.Reset(Feature.Spacings);
			}
		}

		public Visibility Visibility
		{
			get
			{
				return _features.Visibility;
			}
			set
			{
				_visibility = value;

				_features.Reset(Feature.Visibility);
			}
		}

		public override object GetFeature(Feature feature)
		{
			switch (feature)
			{
				case Feature.Width:
					return DataBinding.Evaluate(this, "Width", DataContext, _width);

				case Feature.Height:
					return DataBinding.Evaluate(this, "Height", DataContext, _height);

				case Feature.Spacings:
					return DataBinding.Evaluate(this, "Spacings", DataContext, _spacings);

				case Feature.Visibility:
					return DataBinding.Evaluate(this, "Visibility", DataContext, _visibility);
			}

			return null;
		}

		protected override void ResetFeatures()
		{
			_features.Reset();
		}

		protected override void MeasureImpl(Fusion.Graphics.IGraphics graphics, Fusion.Graphics.Size size)
		{
			_features.Reset();

			float width = 0F;

			switch (_features.Width.Type)
			{
				case WidthType.Default:
					width = size.Width - _features.Spacings.Start - _features.Spacings.End;

					break;

				case WidthType.Direct:
					width = ((DirectWidth)_features.Width).Value;

					break;

				case WidthType.Relative:
					width = (size.Width - _features.Spacings.Start - _features.Spacings.End) * ((RelativeWidth)_features.Width).Value / 100F;

					width = Utils.Round(width, _layout.RenderingScale);

					Fusion.Graphics.Constraint constraint = ((RelativeWidth)_features.Width).Constraint;

					if (constraint != null)
						width = constraint.Apply(width);

					break;
			}

			if (width < 0F)
				width = 0F;

			float height = 0F;

			switch (_features.Height.Type)
			{
				case HeightType.Default:
					height = size.Height - _features.Spacings.Top - _features.Spacings.Bottom;

					break;

				case HeightType.Direct:
					height = ((DirectHeight)_features.Height).Value;

					break;

				case HeightType.Relative:
				{
					height = (size.Height - _features.Spacings.Top - _features.Spacings.Bottom) * ((RelativeHeight)_features.Height).Value / 100F;

					height = Utils.Round(height, _layout.RenderingScale);

					Fusion.Graphics.Constraint constraint = ((RelativeHeight)_features.Height).Constraint;

					if (constraint != null)
						height = constraint.Apply(height);

					break;
				}

				case HeightType.Aspect:
				{
					height = width * ((AspectHeight)_features.Height).Value / 100F;

					height = Utils.Round(height, _layout.RenderingScale);

					Fusion.Graphics.Constraint constraint = ((AspectHeight)_features.Height).Constraint;

					if (constraint != null)
						height = constraint.Apply(height);

					break;
				}
			}

			if (height < 0F)
				height = 0F;

			_size = new Fusion.Graphics.Size(width, height);
		}

		public override void Release()
		{
			_width = null;
			_height = null;
			_spacings = null;
			_features = null;

			base.Release();
		}

		public override Element Clone(Element parent)
		{
			Placeholder placeholder = new Placeholder(_layout, parent);

			CloneImpl(placeholder);

			return placeholder;
		}

		protected override void CloneImpl(Element clone)
		{
			Placeholder placeholder = (Placeholder)clone;

			placeholder.Width = _width;
			placeholder.Height = _height;
			placeholder.Spacings = _spacings;
			placeholder.Visibility = _visibility;

			base.CloneImpl(clone);
		}
	}
}


text:
#include "soomla/CCDomainHelper.h"

#include "soomla/CCCoreConsts.h"
#include "soomla/CCDomainFactory.h"
#include "soomla/CCJsonHelper.h"

using namespace soomla;
using namespace cocos2d;

static CCDomainHelper* s_SharedDomainFactory = nullptr;

CCDomainHelper* CCDomainHelper::getInstance() {
    if (!s_SharedDomainFactory) {
        s_SharedDomainFactory = new CCDomainHelper();
    }

    return s_SharedDomainFactory;
}

cocos2d::Vector<CCDomain*> soomla::CCDomainHelper::getDomainsFromValueVector(
    const cocos2d::ValueVector& dictArray, const std::string& type) {

    if (dictArray == ValueVectorNull) {
        return Vector<CCDomain*>();
    }

    Vector<CCDomain*> domainArray;

    for (auto& obj : dictArray) {
        CCDomain* domain = nullptr;
        if (type.length() == 0) {
            domain =
                soomla::CCDomainFactory::getInstance()->createWithValueMap(
                    obj.asValueMap());
        } else {
            domain = soomla::CCDomainFactory::getInstance()
                         ->createWithValueMapAndType(obj.asValueMap(), type);
        }
        domainArray.pushBack(domain);
    }

    return domainArray;
}

cocos2d::ValueVector soomla::CCDomainHelper::getValueVectorFromDomains(
    const cocos2d::Vector<CCDomain*>& domainArray) {
    if (domainArray.size() == 0) {
        return ValueVectorNull;
    }

    ValueVector dictArray;

    for (auto& obj : domainArray) {
        dictArray.push_back(Value(obj->toValueMap()));
    }

    return dictArray;
}


text:
class ActiveStorage::VariantsController < ActionController::Base
  def show
    if blob = ActiveStorage::Blob.find_signed(params[:signed_blob_id])
      expires_in ActiveStorage::Blob.service.url_expires_in
      redirect_to ActiveStorage::Variant.new(blob, params[:variation_key]).processed.service_url(disposition: params[:disposition])
    else
      head :not_found
    end
  end
end


text:
package jais.messages;

import jais.AISPacket;
import jais.exceptions.AISException;
import jais.messages.enums.AISMessageType;
import jais.messages.enums.BinaryBroadcastMessageType;
import jais.messages.enums.FieldMap;
import java.util.BitSet;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 *
 * @author Jonathan Machen
 */
public class BinaryBroadcastMessage extends AISMessageBase {

    private final static Logger LOG = LogManager.getLogger(BinaryBroadcastMessage.class );

    private int _dac; // designated area code
    private int _fid; // functional id
    private BitSet _data;

    /**
     *
     * @param source
     * @param packets
     */
    public BinaryBroadcastMessage( String source, AISPacket... packets ) {
        super( source, packets );
    }

    /**
     *
     * @param source
     * @param messageType
     * @param packets
     */
    public BinaryBroadcastMessage( String source, AISMessageType messageType, AISPacket... packets ) {
        super( source, messageType, packets );
    }

    /**
     *
     * @return
     */
    public int getSourceMmsi() {
        return super.getMmsi();
    }

    /**
     *
     * @return
     */
    public static Logger getLOG() {
        return LOG;
    }

    /**
     *
     * @return
     */
    public int getDac() {
        return _dac;
    }

    /**
     *
     * @return
     */
    public int getFid() {
        return _fid;
    }

    /**
     *
     * @return
     */
    public BitSet getData() {
        return _data;
    }

    /**
     *
     * @return
     */
    public BinaryBroadcastMessageType getSubType() {
        return BinaryBroadcastMessageType.UNKNOWN;
    }

    /**
     *
     * @throws jais.exceptions.AISException
     */
    @Override
    public void decode() throws AISException {
        super.decode();

        for( BinaryBroadcastMessageBaseFieldMap field : BinaryBroadcastMessageBaseFieldMap.values() ) {
            switch( field ) {
                case DAC:
                    if( _bits.size() >= field.getStartBit() )
                        _dac = AISMessageDecoder.decodeUnsignedInt( _bits, field.getStartBit(), field.getEndBit() );
                    break;
                case FID:
                    if( _bits.size() >= field.getStartBit() )
                        _fid = AISMessageDecoder.decodeUnsignedInt( _bits, field.getStartBit(), field.getEndBit() );
                    break;
                case DATA:
                    // store the undecoded portion of the BitSet in the data
                    // field for later decoding by subtype
                    if( _bits.length() > field.getStartBit() )
                        _data = _bits.get( field.getStartBit(), _bits.size() - 1 );
                    break;
            }
        }
    }

    /**
     *
     */
    private enum BinaryBroadcastMessageBaseFieldMap implements FieldMap {

        SEQUENCE_NUMBER( 38, 39 ),
        DESTINATION_MMSI( 40, 69 ),
        RETRANSMIT( 70, 70 ),
        SPARE( 71, 71 ),
        DAC( 72, 81 ), // designated area code
        FID( 82, 87 ), // Functional ID
        DATA( 88, -1 ) // -1 means from startBit to end of bitArray
        ;

        private final int _startBit;
        private final int _endBit;

        /**
         *
         * @param startBit
         * @param endBit
         */
        BinaryBroadcastMessageBaseFieldMap( int startBit, int endBit ) {
            _startBit = startBit;
            _endBit = endBit;
        }

        /**
         *
         * @return
         */
        @Override
        public int getStartBit() {
            return _startBit;
        }

        /**
         *
         * @return
         */
        @Override
        public int getEndBit() {
            return _endBit;
        }
    }
}


text:
class Workflow < ActiveRecord::Base
  include Linkable
  include Translatable
  include RoleControl::ParentalControlled
  include SubjectCounts
  include ExtendedCacheKey

  has_paper_trail only: [:tasks, :grouped, :pairwise, :prioritized]

  belongs_to :project
  has_many :subject_workflow_counts, dependent: :destroy
  has_many :subject_sets_workflows, dependent: :destroy
  has_many :subject_sets, through: :subject_sets_workflows
  has_many :set_member_subjects, through: :subject_sets
  has_many :classifications
  has_many :user_seen_subjects
  has_many :subject_queues, dependent: :destroy
  has_and_belongs_to_many :expert_subject_sets, -> { expert_sets }, class_name: "SubjectSet"
  belongs_to :tutorial_subject, class_name: "Subject"
  has_many :attached_images, -> { where(type: "workflow_attached_image") }, class_name: "Medium",
    as: :linked

  cache_by_association :workflow_contents
  cache_by_resource_method :subjects_count, :finished?

  DEFAULT_CRITERIA = 'classification_count'
  DEFAULT_OPTS = { 'count' => 15 }

  validates_presence_of :project

  validate do |workflow|
    criteria = %w(classification_count)
    unless workflow.retirement.empty? || criteria.include?(workflow.retirement['criteria'])
      workflow.errors.add(:"retirement.criteria", "Retirement criteria must be one of #{criteria.join(', ')}")
    end
  end

  can_through_parent :project, :update, :index, :show, :destroy, :update_links,
    :destroy_links, :translate, :versions, :version

  can_be_linked :subject_set, :same_project?, :model
  can_be_linked :subject_queue, :scope_for, :update, :user
  can_be_linked :aggregation, :scope_for, :update, :user

  def self.same_project?(subject_set)
    where(project: subject_set.project)
  end

  def tasks
    read_attribute(:tasks).with_indifferent_access
  end

  def retired_subjects
    subject_workflow_counts.retired.includes(:set_member_subject => :subject).map { |swc| swc.set_member_subject.subject }
  end

  def retire_subject(subject_id)
    set_member_subjects.where(subject_id: subject_id).each do |sms|
      count = subject_workflow_counts.where(set_member_subject_id: sms.id, workflow_id: id).first_or_create!
      count.retire!
    end
  end

  def retirement_scheme
    case retirement.fetch('criteria', DEFAULT_CRITERIA)
    when 'classification_count'
      params = retirement.fetch('options', DEFAULT_OPTS).values_at('count')
      RetirementSchemes::ClassificationCount.new(*params)
    else
      raise StandardError, 'invalid retirement scheme'
    end
  end

  def retired_subjects_count
    retired_set_member_subjects_count
  end
end


text:
package edu.harvard.iq.dataverse.dataaccess;

import com.amazonaws.services.s3.AmazonS3;
import edu.harvard.iq.dataverse.DataFile;
import edu.harvard.iq.dataverse.Dataset;
import edu.harvard.iq.dataverse.api.UtilIT;
import edu.harvard.iq.dataverse.mocks.MocksFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.junit.jupiter.api.Assertions.*;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import static org.mockito.Mockito.*;
import static org.mockito.BDDMockito.*;

import java.io.FileNotFoundException;
import java.io.IOException;

@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.STRICT_STUBS)
public class S3AccessIOTest {

    @Mock
    private AmazonS3 s3client;

    private S3AccessIO<Dataset> dataSetAccess;
    private S3AccessIO<DataFile> dataFileAccess;
    private Dataset dataSet;
    private DataFile dataFile;
    private String dataFileId;

    @BeforeEach
    public void setup() throws IOException {
        dataFile = MocksFactory.makeDataFile();
        dataSet = MocksFactory.makeDataset();
        dataFile.setOwner(dataSet);
        dataFileId = UtilIT.getRandomIdentifier();
        dataFile.setStorageIdentifier("s3://bucket:"+dataFileId);
        dataSetAccess = new S3AccessIO<>(dataSet, null, s3client);
        dataFileAccess = new S3AccessIO<>(dataFile, null, s3client);
    }

    /*
    createTempFile
    getStorageLocation
    getFileSystemPath
    exists?
    getWriteChannel
    getOutputStream
    getDestinationKey

    DONE
    ---------------------
    getMainFileKey
    getUrlExpirationMinutes
     */

    @Test
    void keyNull_getMainFileKey() throws IOException {
        // given
        String authOwner = dataSet.getAuthority();
        String idOwner = dataSet.getIdentifier();

        // when
        String key = dataFileAccess.getMainFileKey();

        // then
        assertEquals(authOwner+"/"+idOwner+"/"+dataFileId, key);
    }

    @Test
    void keyNullstorageIdNullOrEmpty_getMainFileKey() throws IOException {
        // given
        dataFile.setStorageIdentifier(null);
        // when & then
        assertThrows(FileNotFoundException.class, () -> {dataFileAccess.getMainFileKey(); });

        // given
        dataFile.setStorageIdentifier("");
        // when & then
        assertThrows(FileNotFoundException.class, () -> {dataFileAccess.getMainFileKey(); });
    }

    @Test
    void keyNullstorageIdNull_getMainFileKey() throws IOException {
        // given
        dataFile.setStorageIdentifier("invalid://abcd");
        // when & then
        assertThrows(IOException.class, () -> {dataFileAccess.getMainFileKey(); });
    }

    @Test
    void default_getUrlExpirationMinutes() {
        // given
        System.clearProperty("dataverse.files.s3-url-expiration-minutes");
        // when & then
        assertEquals(60, dataFileAccess.getUrlExpirationMinutes());
    }

    @Test
    void validSetting_getUrlExpirationMinutes() {
        // given
        System.setProperty("dataverse.files.s3-url-expiration-minutes", "120");
        // when & then
        assertEquals(120, dataFileAccess.getUrlExpirationMinutes());
    }

    @Test
    void invalidSetting_getUrlExpirationMinutes() {
        // given
        System.setProperty("dataverse.files.s3-url-expiration-minutes", "NaN");
        // when & then
        assertEquals(60, dataFileAccess.getUrlExpirationMinutes());
    }

}


text:
package com.xtremelabs.robolectric.shadows;

import android.os.Bundle;
import com.xtremelabs.robolectric.WithTestDefaultsRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

@RunWith(WithTestDefaultsRunner.class)
public class BundleTest {

    private Bundle bundle;

    @Before public void setUp() throws Exception {
        bundle = new Bundle();
    }

    @Test
    public void testContainsKey() throws Exception {
        assertFalse(bundle.containsKey("foo"));
        bundle.putString("foo", "bar");
        assertTrue(bundle.containsKey("foo"));
    }
}


text:
var Path = exports.Path = function(segments, options) {
		this.segments = segments || [];
		this.options = {};
		if (options) this.setOptions(options);
};
Path.prototype = {
	constructor: Path,
	x_fill: false,
	x_stroke: true,
	x_strokeType: 'solid',
	x_dashLength: 6,
	x_dotSpacing: 4,
	setOptions: function(options) {
		var keys = objectKeys(options);
		var keysLength = keys.length;
		for (var i = 0; i < keysLength; ++i) {
			var key = keys[i];
			if ('x_' == key.substr(0, 2)) {
				this[key] = options[key];
			} else {
				this.options[key] = options[key];
			}
		}
	},
	setupSegments: function() {},
	// Based on Oliver Steele's bezier.js library.
	addBezier: function(pointsOrBezier) {
		this.segments.push(pointsOrBezier instanceof Array ? new Bezier(pointsOrBezier) : pointsOrBezier);
	},
	offset: function(dx, dy) {
		if (0 == this.segments.length) this.setupSegments();
		var segmentsLength = this.segments.length;
		for (var i = 0; i < segmentsLength; ++i) {
			this.segments[i].offset(dx, dy);
		}
	},
	getBB: function() {
		if (0 == this.segments.length) this.setupSegments();
		var l, t, r, b, p = this.segments[0].points[0];
		l = r = p.x;
		t = b = p.y;
		var segmentsLength = this.segments.length;
		for (var i = 0; i < segmentsLength; ++i) {
			var points = this.segments[i].points;
			var pointsLength = points.length;
			for (var j = 0; j < pointsLength; ++j) {
				var point = this.segments[i].points[j];
				l = Math.min(l, point.x);
				t = Math.min(t, point.y);
				r = Math.max(r, point.x);
				b = Math.max(b, point.y);
			}
		}
		var rect = new Rect(l, t, r, b);
		return (this.getBB = function() {return rect;})();
	},
	isPointInBB: function(x, y, tolerance) {
		if ('undefined' === typeof tolerance) tolerance = 0;
		var bb = this.getBB();
		if (0 < tolerance) {
			bb = Object.clone(bb);
			bb.inset(-tolerance, -tolerance);
		}
		return !(x < bb.l || x > bb.r || y < bb.t || y > bb.b);
	},
	isPointOnPath: function(x, y, tolerance) {
		if ('undefined' === typeof tolerance) tolerance = 0;
		if (!this.isPointInBB(x, y, tolerance)) return false;
		var segmentsLength = this.segments.length;
		for (var i = 0; i < segmentsLength; ++i) {
			if (this.segments[i].isPointOnBezier(x, y, tolerance)) {
				return true;
			}
		}
		return false;
	},
	isPointInPath: function(x, y) {
		return false;
	},
	// Based on Oliver Steele's bezier.js library.
	makePath: function(ctx) {
		if (0 == this.segments.length) this.setupSegments();
		var segmentsLength = this.segments.length;
		for (var i = 0; i < segmentsLength; ++i) {
			this.segments[i].makePath(ctx, 0 == i);
		}
	},
	makeDashedPath: function(ctx, dashLength, firstDistance, drawFirst) {
		if (0 == this.segments.length) this.setupSegments();
		var info = {
			drawFirst: ('undefined' === typeof drawFirst) ? true : drawFirst,
			firstDistance: firstDistance || dashLength
		};
		var segmentsLength = this.segments.length;
		for (var i = 0; i < segmentsLength; ++i) {
			info = this.segments[i].makeDashedPath(ctx, dashLength, info.firstDistance, info.drawFirst);
		}
	},
	makeDottedPath: function(ctx, dotSpacing, firstDistance) {
		if (0 == this.segments.length) this.setupSegments();
		if (!firstDistance) firstDistance = dotSpacing;
		var segmentsLength = this.segments.length;
		for (var i = 0; i < segmentsLength; ++i ) {
			firstDistance = this.segments[i].makeDottedPath(ctx, dotSpacing, firstDistance);
		}
	},
	draw: function(ctx) {
		ctx.save();
		var keys = objectKeys(this.options);
		var keysLength = keys.length;
		for (var i = 0; i < keysLength; ++i) {
			var key = keys[i];
			ctx[key] = this.options[key];
		}
		if (this.x_fill) {
			ctx.beginPath();
			this.makePath(ctx);
			ctx.fill();
		}
		if (this.x_stroke) {
			switch (this.x_strokeType) {
				case 'dashed':
					ctx.beginPath();
					this.makeDashedPath(ctx, this.x_dashLength);
					break;
				case 'dotted':
					if (ctx.lineWidth < 2) ctx.lineWidth = 2;
					ctx.beginPath();
					this.makeDottedPath(ctx, this.x_dotSpacing);
					break;
				case 'solid':
				default:
					if (!this.x_fill) {
						ctx.beginPath();
						this.makePath(ctx);
					}
			}
			ctx.stroke();
		}
		ctx.restore();
	}
};


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


text:
layout: post
title: "Stad zoekt middenklasse: verslag"
---

Afgelopen donderdag 27 november vond er weer een nieuwe editie van Denken over
Links plaats. De avond stond deze keer in het teken van de komst van de
middenklasse naar de stad. Versterken zij de stad en wijken? En wat betekent
deze verandering voor stad en de stedelingen?

Elke stad lijkt op zoek te zijn naar een middenklasse. Stadsbesturen projecten
allerlei ambities op de komst van meer welgestelde bewoners in de stad. Die
gedroomde groep blijkt echter geen wonderen te verrichten. Bovendien worden en
de huidige bewoners van de stad – inclusief de middenklasse die er nu al woont
– makkelijk vergeten. Zo ook in Rotterdam en Gent, de twee steden die deze
avond centraal stonden. De stad is blijkbaar niet op zoek naar deze mensen,
maar naar een specifieke soort, een ideaal soort middenklasse.

Het thema werd op verschillende manieren belicht door de sprekers tijdens deze
aflevering van Denken over Links. Bart Van Bouchaute, die als politicoloog de
Gentse stadsvernieuwing heeft onderzocht, Joke van der Zwaard, die als
zelfstandig onderzoekster veel over Rotterdam en haar bewoners heeft geschreven
en Reinhout Kleinhans, die als stadsgeograaf de vernieuwing van Hoogvliet
uitgebreid heeft onderzocht waren te gast

Hoewel de komst van de middenklasse op verschillende manieren werd besproken
kunnen we een gezamenlijke conclusie trekken: het versterken van de
middenklasse heeft zeker voordelen. Het is goed voor de draagkracht van de
stad: met minder middenklassers hebben steden minder belastinginkomsten, en
juist meer druk op publieke voorzieningen. Ook zullen studenten en 'sociale
stijgers' met een aanbod gericht op de middenklasse in hun stad kunnen blijven
wonen.

Beleidsmakers en politici hangen echter teveel op aan de middenklasse. Volgens
hen zou de komst van de middenklasse ook goed zijn voor bewoners die lager op
de sociaal-economische ladder staan, e.g. door te zorgen voor sociale stijging
en sociale cohesie. Deze effecten zijn echter niet aangetoond. Sterker nog:
voor andere bewoners zijn aantoonbare negatieve effecten zoals verdringing en
tweedeling.

In het gentrificatie-beleid verliezen stadsbesturen en woningcorporaties de
huidige bewoners uit het zicht en waarderen de al aanwezige bewoners niet
(genoeg). Om van stadsvernieuwing een succes te maken is het zaak om te zorgen
dat mensen binnen de stad of binnen de wijk zelf carrière kunnen maken, ook wat
betreft wonen.

Een stad mag dus best op zoek gaan naar een middenklasse als het daarbij andere
stedelingen niet over het hoofd ziet (e.g. middels 'aankomstwijken'). En laten
we er eerst voor zorgen dat we huidige bewoners voor de stad behouden.

Lees hier verder voor het hele verhaal:

### Het perspectief van Bart Van Bouchaute

In België werden en worden de steden gezien als een poel van verderf en
criminaliteit, iets wat zich nu nog vertaald in een gebrekkige waardering van
de steden. Arbeiders werden in de 19e en 20e eeuw met actief beleid
aangemoedigd om de stad te verlaten en op het platteland te gaan wonen.
Tegenwoordig verlaten mensen het even kan nog steeds de stad om in de
omringende gemeenten te gaan wonen. Het is daarom voor een stad als Gent heel
moeilijk om die middenklasse aan zich te binden.

De herwaardering van de stad begint in Gent rond de tijd dat die ook in
Rotterdam van de grond komt, namelijk in de jaren 1970. Er wordt een strijd
voor een sociale stadsherwaardering gevoerd, die leidde tot een herwaardering
van de gordelwijken om de oude stad. Er werd gekozen voor invulbouw, wat
betekende dat er, anders dan elders vaak gebeurde, geen hele wijken werden
gesloopt. Bovendien mocht er geen sprake zijn van sociale verdringing. Hoewel
er door een gebrek aan middelen weinig resultaat werd geboekt, bleef deze vorm
van stadsvernieuwing een ijkpunt, ook voor later beleid.

In Gent heeft zich een stille gentrificatie voltrokken, zo blijkt uit het
onderzoek van Bart Van Bouchaute, waarbij er wel degelijk sprake was van
sociale verdringing. Deze vorm van verdringing, was een gevolg van het
uitblijven van flankerend beleid. Succesvol beleid met betrekking tot
stadsvernieuwing moet daarom gericht zijn op meer dan alleen stenen en moet
bestaan uit een sociale, functionele en ruimtelijke mix.

Het beleid dat nu wordt gevoerd is niet realistisch. Mensen in België zijn bang
om in de stad te wonen, vanwege de lage status en het idee dat de stad
voornamelijk bevolkt wordt door migranten, die vaak geassocieerd worden met
onveiligheid.

Progressieve mensen proberen echter tegen beter weten in de middenklasse naar
de stad te trekken als breekijzer om ghettovorming te voorkomen. Het overgrote
deel van de middenklasse in Belgie, anders dan in Nederland, wil echter
helemaal niet in de stad wonen. Er is een ander beleid nodig waarbij
gedepriveerde wijken worden gezien als plekken van aankomst. In deze wijken
moeten de beste voorzieningen komen voor onderwijs, moet geïnvesteerd worden in
sociale huisvesting en tewerkstellingsmogelijkheden, zodat mensen kunnen
doorstromen. Dat is een kwestie van rechtvaardigheid.

Download de volledige presentatie [hier] (/data/20141127_StadZoektMiddenklasse_BartVanBouchaute.pdf) (pdf).

### Het perspectief van Joke van der Zwaard

De titel van de avond, Stad zoekt middenklasse, kun je op vele manieren
interpreteren, aldus Joke van der Zwaard. Zij heeft de titel vooral opgevat als
een soort 'boer zoekt vrouw', waarbij de boer op zoek gaat naar de ideale vrouw
en de stad op zoek gaat naar de ideale middenklasse. Ze heeft de stad daar
altijd graag bij willen helpen en heeft bij meerdere gelegenheden meegezocht.
Die zoekresultaten heeft ze gedeeld met gemeente, corporaties en andere
instanties. Zij bleken echter niet zo geïnteresseerd in de middenklasse waar
Van Der Zwaard mee op de proppen kwam. Gemeenten en corporaties zijn op zoek
naar een bepaald soort en je kunt blijkbaar niet zomaar veronderstellen dat die
middenklasse die zich al in de stad ophoudt.

De al aanwezige middenklasse wordt dan ook vaak over het hoofd gezien, zo zeer
zelfs dat je bijna zou denken dat er in deze wijken alleen maar kwetsbare
mensen wonen. Dat dit een mythe is blijkt wel uit het feit dat er in een wijk
als het Oude Westen meer hoogopgeleide mensen wonen dan in Ommoord. Het gaat
dan wel over een bepaald type hoogopgeleide, die er niet in eerste instantie op
uit is om carrière te maken en zich op haar plek voelt in een wijk als het Oude
Westen. Iets waar beleidsmakers zich nauwelijks wat bij voor kunnen stellen.

In plaats van hardnekkig de ideale middenklasse tot middelpunt van beleid te
maken, zouden betrokkenen veel meer uit moeten gaan van de potentie van een
wijk. Corporaties zien dit potentieel echter vaak over het hoofd. Joke van der
Zwaard heeft daar vaak met ze over gesproken en zich afgevraagd of deze
gedroomde middenklasse wel kan brengen wat deze wijken nodig hebben en wat het
effect is van deze zoektocht op de mensen die er al wonen, die steeds maar te
horen krijgen dat het pas wat met de wijk wordt, als er nieuwe mensen komen.

Bij dat laatste kun je grote vraagtekens stellen, want die nieuwe bewoner
blijkt helemaal niet zoveel geld te hebben. Bovendien kun je niet verwachten
dat deze middenklassers de oude bewoners 'omhoog trekt', onder andere omdat ze
optrekken met hun eigen vrienden, binnen hun eigen netwerken. Tot slot worden
de nieuwe bewoners dikwijls gepresenteerd als de redders van de wijk. Oude
bewoners staan daarom bij voorbaat argwanend tegenover deze groep en sommige
nieuwkomers gaan zich hier ook naar gedragen, met alle gevolgen van dien.

### Het perspectief van Reinout Kleinhans

Wat zijn de heilzame effecten van "de middenklasse" voor een stad als
Rotterdam, zo vraagt Reinout Kleinhans zich af. Voor een bestuurder bestaan die
er vooral uit dat door de aanwezigheid van een grote middenklasse de stad
soepeler te besturen valt, dat deze klasse zorgt voor stabiele OZB-inkomsten en
toch niet het 'goudkustgedrag' vertoont van zeer mondige rijke bewoners.
Daarnaast heeft de middenklasse een economische meerwaarde voor de stad omdat
het zorgt voor draagvlak onder de winkels en andere voorzieningen in de stad,
wat weer voor een levendige stad zorgt. Momenteel gaan er veel dingen in
Rotterdam mis en voert de stad de verkeerde lijstjes aan, omdat die
middenklasse, vanuit het oogpunt van de bestuurder, niet een voldoende
substantieel aandeel van de bevolking vormt. Uit onderzoek naar het
stadsvernieuwingsbeleid in Rotterdam blijkt dat de herstructurering van de
naoorlogse wijken effectief is geweest als het gaat om de wooncarrière van de
(lagere) middenklasse en maar beperkte resultaten heeft opgeleverd met
betrekking tot het aantrekken van nieuwe middenklasse. Het laat ook zien dat
het zaak is de mensen die al in de stad aanwezig zijn te behouden. Veel van de
burgerinitiatieven in de stad komen voort uit deze groep.

De droge feiten wijzen op een aanzienlijk economisch en enig sociaal belang van
de middenklassers. Tegelijkertijd moet je deze groep niet opzadelen met
torenhoge beleidsambities, anders verzandt het beleid in zijn eigen retoriek en
neigt het naar hysterie.

Download de volledige presentatie [hier] (/data/20141127_StadZoektMiddenklasse_ReinoutKleinhans.pdf) (pdf).


text:
package com.web.common.web.common.util.poi;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;

import javax.servlet.http.HttpServletResponse;

/**
 * 文件操作
 *
 * @author cuiyan
 */
public class ExcelFileUtil {

  /**
   * 写文件
   *
   * @param path
   * @param content
   */
  public static void write(String path, String content) {
    String s = new String();
    String s1 = new String();

    try {
      File f = new File(path);

      // 删除
      if (f.isFile() && f.exists()) {
        f.delete();
      }

      if (!f.createNewFile()) {
        throw new RuntimeException("文件" + path + "创建失败!");
      }
      BufferedReader input = new BufferedReader(new FileReader(f));
      while ((s = input.readLine()) != null) {
        s1 += s + "\n";
      }

      input.close();
      s1 += content;
      BufferedWriter output = new BufferedWriter(new FileWriter(f));
      output.write(s1);
      output.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * 让浏览器下载指定的文件
   *
   * @param file 指定的文件
   * @param response Http响应
   * @param downloadFileName 下载的文件名
   */
  public static void downloadZip(File file, HttpServletResponse response, String downloadFileName) {
    try {
      BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
      byte[] buffer = new byte[fis.available()];
      fis.read(buffer);
      fis.close();
      // 清空response
      response.reset();

      OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
      response.setContentType("application/octet-stream");
      String tempfileName = URLEncoder.encode(downloadFileName, "UTF-8");
      response.setHeader("Content-Disposition", "attachment;filename=" + tempfileName);
      response.setCharacterEncoding("UTF-8");
      toClient.write(buffer);
      toClient.flush();
      toClient.close();
      file.delete();
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }

  /**
   * 获得指定文件的byte数组
   */
  public static byte[] getBytes(File file) {
    byte[] buffer = null;
    try {
      FileInputStream fis = new FileInputStream(file);
      ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
      byte[] b = new byte[(int) file.length()];
      int n;
      while ((n = fis.read(b)) != -1) {
        bos.write(b, 0, n);
      }
      fis.close();
      bos.close();
      buffer = bos.toByteArray();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return buffer;
  }

  /**
   * 根据byte数组,生成文件
   */
  public static void getFile(byte[] bfile, String filePath, String fileName) {
    BufferedOutputStream bos = null;
    FileOutputStream fos = null;
    File file = null;
    try {
      File dir = new File(filePath);
      if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
        dir.mkdirs();
      }
      file = new File(filePath + "\\" + fileName);
      fos = new FileOutputStream(file);
      bos = new BufferedOutputStream(fos);
      bos.write(bfile);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (bos != null) {
        try {
          bos.close();
        } catch (IOException e1) {
          e1.printStackTrace();
        }
      }
      if (fos != null) {
        try {
          fos.close();
        } catch (IOException e1) {
          e1.printStackTrace();
        }
      }
    }
  }

  public static String getMd5ByFile(File file) {
    String value = null;
    FileInputStream in = null;
    try {
      in = new FileInputStream(file);
      MappedByteBuffer byteBuffer =
          in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
      MessageDigest md5 = MessageDigest.getInstance("MD5");
      md5.update(byteBuffer);
      BigInteger bi = new BigInteger(1, md5.digest());
      value = bi.toString(16);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (null != in) {
        try {
          in.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return value;
  }
}


text:
package org.beetl.core;

import java.lang.ref.SoftReference;

/** 一个缓存的字节和字符数组,用于减少beetl渲染各个过程中渲染字符数组
 * @author joelli
 *
 */
public class ContextLocalBuffer
{
	/**
	 *  初始化的字符数组大小
	 */
	public static int charBufferSize = 256;

	/**
	 * 初始化的字节大小
	 */
	public static int byteBufferSize = 256;

	private char[] charBuffer = new char[charBufferSize];
	private byte[] byteBuffer = new byte[byteBufferSize];
	static ThreadLocal<SoftReference<ContextLocalBuffer>> threadLocal = new ThreadLocal<SoftReference<ContextLocalBuffer>>() {
		protected SoftReference<ContextLocalBuffer> initialValue()
		{
			return new SoftReference(new ContextLocalBuffer());
		}
	};

	public static ContextLocalBuffer get()
	{
		SoftReference<ContextLocalBuffer> re = threadLocal.get();
		ContextLocalBuffer ctxBuffer = re.get();
		if (ctxBuffer == null)
		{
			ctxBuffer = new ContextLocalBuffer();
			threadLocal.set(new SoftReference(ctxBuffer));
		}
		return ctxBuffer;
	}

	public char[] getCharBuffer()
	{
		return this.charBuffer;
	}

	public byte[] getByteBuffer()
	{
		return this.byteBuffer;
	}

	/** 得到一个期望长度的buffer
	 * @param expected
	 * @return
	 */
	public char[] getCharBuffer(int expected)
	{
		if (this.charBuffer.length >= expected)
		{
			return charBuffer;
		}
		else
		{
			//?预先设置多一点
			this.charBuffer = new char[(int) (expected * 1.2)];
		}
		return this.charBuffer;
	}

	/**得到期望字节数组大小
	 * @param expected
	 * @return
	 */
	public byte[] getByteBuffer(int expected)
	{
		if (this.byteBuffer.length >= expected)
		{
			return byteBuffer;
		}
		else
		{
			//?预先设置多一点
			this.byteBuffer = new byte[(int) (expected * 1.2)];
		}
		return this.byteBuffer;
	}

}


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

// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------

// for compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
    #pragma hdrstop
#endif

#if wxUSE_SOCKETS

#include "wx/app.h"
#include "wx/apptrait.h"
#include "wx/private/socket.h"
#include "wx/link.h"

// ============================================================================
// wxSocketFDBasedManager implementation
// ============================================================================

bool wxSocketFDBasedManager::OnInit()
{
    wxAppTraits * const traits = wxApp::GetTraitsIfExists();
    if ( !traits )
        return false;

    m_fdioManager = traits->GetFDIOManager();
    return m_fdioManager != NULL;
}

void wxSocketFDBasedManager::Install_Callback(wxSocketImpl *socket_,
                                              wxSocketNotify event)
{
    wxSocketImplUnix * const
        socket = static_cast<wxSocketImplUnix *>(socket_);

    wxCHECK_RET( socket->m_fd != -1,
                    "shouldn't be called on invalid socket" );

    const wxFDIOManager::Direction d = GetDirForEvent(socket, event);

    int& fd = FD(socket, d);
    if ( fd != -1 )
        m_fdioManager->RemoveInput(socket, fd, d);

    fd = m_fdioManager->AddInput(socket, socket->m_fd, d);
}

void wxSocketFDBasedManager::Uninstall_Callback(wxSocketImpl *socket_,
                                                wxSocketNotify event)
{
    wxSocketImplUnix * const
        socket = static_cast<wxSocketImplUnix *>(socket_);

    const wxFDIOManager::Direction d = GetDirForEvent(socket, event);

    int& fd = FD(socket, d);
    if ( fd != -1 )
    {
        m_fdioManager->RemoveInput(socket, fd, d);
        fd = -1;
    }
}

wxFDIOManager::Direction
wxSocketFDBasedManager::GetDirForEvent(wxSocketImpl *socket,
                                       wxSocketNotify event)
{
    switch ( event )
    {
        default:
            wxFAIL_MSG( "unknown socket event" );
            return wxFDIOManager::INPUT; // we must return something

        case wxSOCKET_LOST:
            wxFAIL_MSG( "unexpected socket event" );
            return wxFDIOManager::INPUT; // as above

        case wxSOCKET_INPUT:
            return wxFDIOManager::INPUT;

        case wxSOCKET_OUTPUT:
            return wxFDIOManager::OUTPUT;

        case wxSOCKET_CONNECTION:
            // for server sockets we're interested in events indicating
            // that a new connection is pending, i.e. that accept() will
            // succeed and this is indicated by socket becoming ready for
            // reading, while for the other ones we're interested in the
            // completion of non-blocking connect() which is indicated by
            // the socket becoming ready for writing
            return socket->IsServer() ? wxFDIOManager::INPUT
                                      : wxFDIOManager::OUTPUT;
    }
}

// set the wxBase variable to point to our wxSocketManager implementation
//
// see comments in wx/apptrait.h for the explanation of why do we do it
// like this
static struct ManagerSetter
{
    ManagerSetter()
    {
        static wxSocketFDBasedManager s_manager;
        wxAppTraits::SetDefaultSocketManager(&s_manager);
    }
} gs_managerSetter;

// see the relative linker macro in socket.cpp
wxFORCE_LINK_THIS_MODULE( socketiohandler );

#endif // wxUSE_SOCKETS


text:
<?php

namespace Kendo\UI;

class GanttPdf extends \Kendo\SerializableObject {
//>> Properties

    /**
    * The author of the PDF document.
    * @param string $value
    * @return \Kendo\UI\GanttPdf
    */
    public function author($value) {
        return $this->setProperty('author', $value);
    }

    /**
    * The creator of the PDF document.
    * @param string $value
    * @return \Kendo\UI\GanttPdf
    */
    public function creator($value) {
        return $this->setProperty('creator', $value);
    }

    /**
    * The date when the PDF document is created. Defaults to new Date().
    * @param date $value
    * @return \Kendo\UI\GanttPdf
    */
    public function date($value) {
        return $this->setProperty('date', $value);
    }

    /**
    * Specifies the file name of the exported PDF file.
    * @param string $value
    * @return \Kendo\UI\GanttPdf
    */
    public function fileName($value) {
        return $this->setProperty('fileName', $value);
    }

    /**
    * If set to true, the content will be forwarded to proxyURL even if the browser supports saving files locally.
    * @param boolean $value
    * @return \Kendo\UI\GanttPdf
    */
    public function forceProxy($value) {
        return $this->setProperty('forceProxy', $value);
    }

    /**
    * Specifies the keywords of the exported PDF file.
    * @param string $value
    * @return \Kendo\UI\GanttPdf
    */
    public function keywords($value) {
        return $this->setProperty('keywords', $value);
    }

    /**
    * Set to true to reverse the paper dimensions if needed such that width is the larger edge.
    * @param boolean $value
    * @return \Kendo\UI\GanttPdf
    */
    public function landscape($value) {
        return $this->setProperty('landscape', $value);
    }

    /**
    * Specifies the margins of the page (numbers or strings with units). Supported
units are "mm", "cm", "in" and "pt" (default).
    * @param \Kendo\UI\GanttPdfMargin|array $value
    * @return \Kendo\UI\GanttPdf
    */
    public function margin($value) {
        return $this->setProperty('margin', $value);
    }

    /**
    * Specifies the paper size of the PDF document.
The default "auto" means paper size is determined by content.Supported values:
    * @param string|array $value
    * @return \Kendo\UI\GanttPdf
    */
    public function paperSize($value) {
        return $this->setProperty('paperSize', $value);
    }

    /**
    * The URL of the server side proxy which will stream the file to the end user.A proxy will be used when the browser isn't capable of saving files locally.
Such browsers are IE version 9 and lower and Safari.The developer is responsible for implementing the server-side proxy.The proxy will receive a POST request with the following parameters in the request body:The proxy should return the decoded file with set "Content-Disposition" header.
    * @param string $value
    * @return \Kendo\UI\GanttPdf
    */
    public function proxyURL($value) {
        return $this->setProperty('proxyURL', $value);
    }

    /**
    * Sets the subject of the PDF file.
    * @param string $value
    * @return \Kendo\UI\GanttPdf
    */
    public function subject($value) {
        return $this->setProperty('subject', $value);
    }

    /**
    * Sets the title of the PDF file.
    * @param string $value
    * @return \Kendo\UI\GanttPdf
    */
    public function title($value) {
        return $this->setProperty('title', $value);
    }

//<< Properties
}

?>