text:
cask "tableplus" do
  version "4.6.6,422"
  sha256 "7ac9d738cbbe3e2601b54ca0ca1bb027599c03aa2b9a8942d6068a2e15185226"

  url "https://download.tableplus.com/macos/#{version.csv.second}/TablePlus.dmg"
  name "TablePlus"
  desc "Native GUI tool for relational databases"
  homepage "https://tableplus.com/"

  livecheck do
    url "https://tableplus.com/osx/version.xml"
    strategy :sparkle
  end

  auto_updates true
  depends_on macos: ">= :el_capitan"

  app "TablePlus.app"

  zap trash: [
    "~/Library/Application Support/com.tinyapp.TablePlus",
    "~/Library/Caches/com.tinyapp.TablePlus",
    "~/Library/Cookies/com.tinyapp.TablePlus.binarycookies",
    "~/Library/Preferences/com.tinyapp.TablePlus.plist",
    "~/Library/Saved Application State/com.tinyapp.TablePlus.savedState",
  ]
end

redpajama_set_name: RedPajamaGithub


text:
/**
 * @file   FWApplication.h
 * @author Sebastian Maisch <sebastian.maisch@googlemail.com>
 * @date   2016.10.27
 *
 * @brief  Contains the definition of FWApplication.
 */

#pragma once

#include <app/ApplicationBase.h>
#include <gfx/VertexFormats.h>
#include <gfx/vk/memory/MemoryGroup.h>
#include <gfx/vk/UniformBufferObject.h>
#include <core/math/primitives.h>

namespace vku::gfx {
    class DeviceBuffer;
    class GraphicsPipeline;
    class Texture2D;
    class AssImpScene;
    class Mesh;
    class UniformBufferObject;
    class UserControlledCamera;
}

namespace vkuapp {

    struct CameraMatrixUBO
    {
        glm::mat4 view_;
        glm::mat4 proj_;
    };

    class FWApplication final : public vku::ApplicationBase
    {
    public:
        explicit FWApplication();
        virtual ~FWApplication() override;

        bool HandleKeyboard(int key, int scancode, int action, int mods, vku::VKWindow* sender) override;
        bool HandleMouseApp(int button, int action, int mods, float mouseWheelDelta, vku::VKWindow* sender) override;
        void Resize(const glm::uvec2& screenSize, const vku::VKWindow* window) override;

    private:
        /** Holds the descriptor set layouts for the demo pipeline. */
        vk::DescriptorSetLayout vkImageSampleDescriptorSetLayout_;
        /** Holds the pipeline layout for demo rendering. */
        vk::UniquePipelineLayout vkPipelineLayout_;
        /** Holds the descriptor pool for the UBO binding. */
        vk::UniqueDescriptorPool vkUBODescriptorPool_;
        /** Holds the descriptor set for the image/sampler binding. */
        vk::DescriptorSet vkImageSamplerDescritorSet_;
        /** Holds the graphics pipeline for demo rendering. */
        std::unique_ptr<vku::gfx::GraphicsPipeline> demoPipeline_;
        /** Holds the graphics pipeline for transparent demo rendering. */
        std::unique_ptr<vku::gfx::GraphicsPipeline> demoTransparentPipeline_;
        /** Holds vertex information. */
        std::vector<SimpleVertex> vertices_;
        /** Holds index information. */
        std::vector<std::uint32_t> indices_;
        /** Holds the vertex and index buffer. */
        vku::gfx::MemoryGroup memGroup_;
        /** Holds the memory group index of the complete buffer. */
        unsigned int completeBufferIdx_ = vku::gfx::MemoryGroup::INVALID_INDEX;

        /** The world matrix of the two rotating planes. */
        glm::mat4 planesWorldMatrix_;
        vku::math::AABB3<float> planesAABB_;

        /** The uniform buffer object for the camera matrices. */
        vku::gfx::UniformBufferObject cameraUBO_;
        /** The uniform buffer object for the world matrices. */
        vku::gfx::UniformBufferObject worldUBO_;

        /** The command pool for the transfer cmd buffers. */
        vk::UniqueCommandPool transferCmdPool_; // TODO: at some point we may need one per buffer? [10/19/2018 Sebastian Maisch]
        /** Holds the command buffers for transferring the uniform buffers. */
        std::vector<vk::UniqueCommandBuffer> vkTransferCommandBuffers_;

        /** The camera model used. */
        std::unique_ptr<vku::gfx::UserControlledCamera> camera_;

        /** Holds the texture used. */
        std::shared_ptr<vku::gfx::Texture2D> demoTexture_;
        /** Holds the texture sampler. */
        vk::UniqueSampler vkDemoSampler_;

        /** Holds the AssImp demo model. */
        std::shared_ptr<vku::gfx::AssImpScene> meshInfo_;
        /** Holds the mesh to be rendered. */
        std::unique_ptr<vku::gfx::Mesh> mesh_;
        /** The world matrix of the mesh. */
        glm::mat4 meshWorldMatrix_;

        /** Holds the screen text to render fps. */
        // std::unique_ptr<ScreenText> fpsText_;

    protected:
        void FrameMove(float time, float elapsed, const vku::VKWindow* window) override;
        void RenderScene(const vku::VKWindow* window) override;
        void RenderGUI(const vku::VKWindow* window) override;
    };
}


text:
@protocol AnimatedTransitionProtected <NSObject>
- (void)animateTransitionForDismission:(id <UIViewControllerContextTransitioning>)transitionContext;
- (void)animateTransitionForPresenting:(id <UIViewControllerContextTransitioning>)transitionContext;
@end

@interface AnimatedTransition : NSObject <AnimatedTransitionProtected, UIViewControllerAnimatedTransitioning>
{
@protected
    UIViewController *fromViewController;
    UIViewController *toViewController;
}
@property (nonatomic) BOOL presenting;
@end


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width; initial-scale=1.0">
	<title>Ejemplo de diseño adaptativo</title>
	<link rel="stylesheet" type="text/css" href="colors.css">
	<link rel="stylesheet" type="text/css" href="base.css">
	<link rel="stylesheet" type="text/css" href="mini.css" media = "screen and (max-width: 480px)">
	<link rel="stylesheet" type="text/css" href="medium.css" media = "screen and (min-width: 480px)">
	<link rel="stylesheet" type="text/css" href="great.css" media = "screen and (min-width: 980px)">

El título de mi sitio web

Grande

Mediano

Mini

Mi menú

Uno

Dos

Tres

			<select class="display-mini">
				<option>Uno</option>
				<option>Dos</option>
				<option>Tres</option>
			</select>

Mi contenido

Entrada 1

Un lorem ipsum resumindo...

Entrada 2

Un lorem ipsum resumindo...

Entrada 3

Un lorem ipsum resumindo...

El típico pie que nadie lee

			<select class="display-mini">
				<option>Uno</option>
				<option>Dos</option>
				<option>Tres</option>
			</select>


text:
@interface SSHolidayManager ()
{
    SSHolidayRegion _region;
    SSHolidayCountry *_country;
}

@property (readonly) SSHolidayCountry *country;
@end

@implementation SSHolidayManager

- (id) initWithRegion:(SSHolidayRegion)region
{
    self = [super init];
    if (self) {
        _region = region;
        _country = [self allocateHolidayAlgoByRegion:region];
    }
    return self;
}

- (SSHolidayCountry *) allocateHolidayAlgoByRegion:(SSHolidayRegion)r {
    switch (r) {
    case SSHolidayRegionChina:
        return [[SSHolidayChina alloc] init];
    case SSHolidayRegionHongkong:
        return [[SSHolidayHK alloc] init];
    case SSHolidayRegionTaiwan:
        return [[SSHolidayTW alloc] init];
    case SSHolidayRegionUS:
        return [[SSHolidayUS alloc] init];
    case SSHolidayRegionCanadia:
        return [[SSHolidayCA alloc] init];
    case SSHolidayRegionUK:
        return [[SSHolidayUK alloc] init];
    default:
        NSAssert(false, @"should not be here");
        return [[SSHolidayChina alloc] init];
    }
}

- (NSArray *) getHolidayListForDate:(NSDate *)date
{
    return [_country getHolidayListForDate:date];
}

@end


text:
<template name="User_Opportunity_Component">

      OPPORTUNITIES

COMPLETED {{> Widget_Header_Number inputValue=(count true)}}

            {{#each oi in opportunitiesCompleted}}

{{opportunityName oi}}

            {{/each}}

PLANNED {{> Widget_Header_Number inputValue=(count false)}}

            {{#each oi in opportunitiesPlanned}}

{{opportunityName oi}}

            {{/each}}

</template>


text:
// Copyright (c) 2016 The vulkano developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.

use super::{
    CommandBufferInheritanceInfo, CommandBufferResourcesUsage, CommandBufferState,
    CommandBufferUsage, SecondaryCommandBufferResourcesUsage, SemaphoreSubmitInfo, SubmitInfo,
};
use crate::{
    buffer::sys::Buffer,
    device::{Device, DeviceOwned, Queue},
    image::{sys::Image, ImageLayout},
    swapchain::Swapchain,
    sync::{
        future::{
            now, AccessCheckError, AccessError, FlushError, GpuFuture, NowFuture, SubmitAnyBuilder,
        },
        PipelineStages,
    },
    DeviceSize, SafeDeref, VulkanObject,
};
use parking_lot::{Mutex, MutexGuard};
use std::{
    borrow::Cow,
    error::Error,
    fmt::{Debug, Display, Error as FmtError, Formatter},
    ops::Range,
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    },
};

pub unsafe trait PrimaryCommandBufferAbstract:
    VulkanObject<Handle = ash::vk::CommandBuffer> + DeviceOwned + Send + Sync
{
    /// Returns the usage of this command buffer.
    fn usage(&self) -> CommandBufferUsage;

    /// Executes this command buffer on a queue.
    ///
    /// This function returns an object that implements the `GpuFuture` trait. See the
    /// documentation of the `sync` module for more information.
    ///
    /// The command buffer is not actually executed until you call `flush()` on the object.
    /// You are encouraged to chain together as many futures as possible before calling `flush()`,
    /// and call `.then_signal_future()` before doing so. Note however that once you called
    /// `execute()` there is no way to cancel the execution, even if you didn't flush yet.
    ///
    /// > **Note**: In the future this function may return `-> impl GpuFuture` instead of a
    /// > concrete type.
    ///
    /// > **Note**: This is just a shortcut for `execute_after(vulkano::sync::now(), queue)`.
    ///
    /// # Panics
    ///
    /// - Panics if the device of the command buffer is not the same as the device of the future.
    #[inline]
    fn execute(
        self,
        queue: Arc<Queue>,
    ) -> Result<CommandBufferExecFuture<NowFuture>, CommandBufferExecError>
    where
        Self: Sized + 'static,
    {
        let device = queue.device().clone();
        self.execute_after(now(device), queue)
    }

    /// Executes the command buffer after an existing future.
    ///
    /// This function returns an object that implements the `GpuFuture` trait. See the
    /// documentation of the `sync` module for more information.
    ///
    /// The command buffer is not actually executed until you call `flush()` on the object.
    /// You are encouraged to chain together as many futures as possible before calling `flush()`,
    /// and call `.then_signal_future()` before doing so. Note however that once you called
    /// `execute()` there is no way to cancel the execution, even if you didn't flush yet.
    ///
    /// > **Note**: In the future this function may return `-> impl GpuFuture` instead of a
    /// > concrete type.
    ///
    /// This function requires the `'static` lifetime to be on the command buffer. This is because
    /// this function returns a `CommandBufferExecFuture` whose job is to lock resources and keep
    /// them alive while they are in use by the GPU. If `'static` wasn't required, you could call
    /// `std::mem::forget` on that object and "unlock" these resources. For more information about
    /// this problem, search the web for "rust thread scoped leakpocalypse".
    ///
    /// # Panics
    ///
    /// - Panics if the device of the command buffer is not the same as the device of the future.
    fn execute_after<F>(
        self,
        future: F,
        queue: Arc<Queue>,
    ) -> Result<CommandBufferExecFuture<F>, CommandBufferExecError>
    where
        Self: Sized + 'static,
        F: GpuFuture,
    {
        assert_eq!(self.device().handle(), future.device().handle());

        if !future.queue_change_allowed() {
            assert!(future.queue().unwrap() == queue);
        }

        Ok(CommandBufferExecFuture {
            previous: future,
            command_buffer: Arc::new(self),
            queue,
            submitted: Mutex::new(false),
            finished: AtomicBool::new(false),
        })
    }

    #[doc(hidden)]
    fn state(&self) -> MutexGuard<'_, CommandBufferState>;

    #[doc(hidden)]
    fn resources_usage(&self) -> &CommandBufferResourcesUsage;
}

impl Debug for dyn PrimaryCommandBufferAbstract {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
        Debug::fmt(&self.handle(), f)
    }
}

unsafe impl<T> PrimaryCommandBufferAbstract for T
where
    T: VulkanObject<Handle = ash::vk::CommandBuffer> + SafeDeref + Send + Sync,
    T::Target: PrimaryCommandBufferAbstract,
{
    fn usage(&self) -> CommandBufferUsage {
        (**self).usage()
    }

    fn state(&self) -> MutexGuard<'_, CommandBufferState> {
        (**self).state()
    }

    fn resources_usage(&self) -> &CommandBufferResourcesUsage {
        (**self).resources_usage()
    }
}

pub unsafe trait SecondaryCommandBufferAbstract:
    VulkanObject<Handle = ash::vk::CommandBuffer> + DeviceOwned + Send + Sync
{
    /// Returns the usage of this command buffer.
    fn usage(&self) -> CommandBufferUsage;

    /// Returns a `CommandBufferInheritance` value describing the properties that the command
    /// buffer inherits from its parent primary command buffer.
    fn inheritance_info(&self) -> &CommandBufferInheritanceInfo;

    /// Checks whether this command buffer is allowed to be recorded to a command buffer,
    /// and if so locks it.
    ///
    /// If you call this function, then you should call `unlock` afterwards.
    fn lock_record(&self) -> Result<(), CommandBufferExecError>;

    /// Unlocks the command buffer. Should be called once for each call to `lock_record`.
    ///
    /// # Safety
    ///
    /// Must not be called if you haven't called `lock_record` before.
    unsafe fn unlock(&self);

    #[doc(hidden)]
    fn resources_usage(&self) -> &SecondaryCommandBufferResourcesUsage;
}

unsafe impl<T> SecondaryCommandBufferAbstract for T
where
    T: VulkanObject<Handle = ash::vk::CommandBuffer> + SafeDeref + Send + Sync,
    T::Target: SecondaryCommandBufferAbstract,
{
    fn usage(&self) -> CommandBufferUsage {
        (**self).usage()
    }

    fn inheritance_info(&self) -> &CommandBufferInheritanceInfo {
        (**self).inheritance_info()
    }

    fn lock_record(&self) -> Result<(), CommandBufferExecError> {
        (**self).lock_record()
    }

    unsafe fn unlock(&self) {
        (**self).unlock();
    }

    fn resources_usage(&self) -> &SecondaryCommandBufferResourcesUsage {
        (**self).resources_usage()
    }
}

/// Represents a command buffer being executed by the GPU and the moment when the execution
/// finishes.
#[derive(Debug)]
#[must_use = "Dropping this object will immediately block the thread until the GPU has finished processing the submission"]
pub struct CommandBufferExecFuture<F>
where
    F: GpuFuture,
{
    previous: F,
    command_buffer: Arc<dyn PrimaryCommandBufferAbstract>,
    queue: Arc<Queue>,
    // True if the command buffer has already been submitted.
    // If flush is called multiple times, we want to block so that only one flushing is executed.
    // Therefore we use a `Mutex<bool>` and not an `AtomicBool`.
    submitted: Mutex<bool>,
    finished: AtomicBool,
}

impl<F> CommandBufferExecFuture<F>
where
    F: GpuFuture,
{
    // Implementation of `build_submission`. Doesn't check whenever the future was already flushed.
    // You must make sure to not submit same command buffer multiple times.
    unsafe fn build_submission_impl(&self) -> Result<SubmitAnyBuilder, FlushError> {
        Ok(match self.previous.build_submission()? {
            SubmitAnyBuilder::Empty => SubmitAnyBuilder::CommandBuffer(
                SubmitInfo {
                    command_buffers: vec![self.command_buffer.clone()],
                    ..Default::default()
                },
                None,
            ),
            SubmitAnyBuilder::SemaphoresWait(semaphores) => {
                SubmitAnyBuilder::CommandBuffer(
                    SubmitInfo {
                        wait_semaphores: semaphores
                            .into_iter()
                            .map(|semaphore| {
                                SemaphoreSubmitInfo {
                                    // TODO: correct stages ; hard
                                    stages: PipelineStages::ALL_COMMANDS,
                                    ..SemaphoreSubmitInfo::semaphore(semaphore)
                                }
                            })
                            .collect(),
                        command_buffers: vec![self.command_buffer.clone()],
                        ..Default::default()
                    },
                    None,
                )
            }
            SubmitAnyBuilder::CommandBuffer(mut submit_info, fence) => {
                // FIXME: add pipeline barrier
                submit_info
                    .command_buffers
                    .push(self.command_buffer.clone());
                SubmitAnyBuilder::CommandBuffer(submit_info, fence)
            }
            SubmitAnyBuilder::QueuePresent(_) | SubmitAnyBuilder::BindSparse(_, _) => {
                unimplemented!() // TODO:
                                 /*present.submit();     // TODO: wrong
                                 let mut builder = SubmitCommandBufferBuilder::new();
                                 builder.add_command_buffer(self.command_buffer.inner());
                                 SubmitAnyBuilder::CommandBuffer(builder)*/
            }
        })
    }
}

unsafe impl<F> GpuFuture for CommandBufferExecFuture<F>
where
    F: GpuFuture,
{
    fn cleanup_finished(&mut self) {
        self.previous.cleanup_finished();
    }

    unsafe fn build_submission(&self) -> Result<SubmitAnyBuilder, FlushError> {
        if *self.submitted.lock() {
            return Ok(SubmitAnyBuilder::Empty);
        }

        self.build_submission_impl()
    }

    fn flush(&self) -> Result<(), FlushError> {
        unsafe {
            let mut submitted = self.submitted.lock();
            if *submitted {
                return Ok(());
            }

            match self.build_submission_impl()? {
                SubmitAnyBuilder::Empty => {}
                SubmitAnyBuilder::CommandBuffer(submit_info, fence) => {
                    self.queue.with(|mut q| {
                        q.submit_with_future(submit_info, fence, &self.previous, &self.queue)
                    })?;
                }
                _ => unreachable!(),
            };

            // Only write `true` here in order to try again next time if we failed to submit.
            *submitted = true;
            Ok(())
        }
    }

    unsafe fn signal_finished(&self) {
        self.finished.store(true, Ordering::SeqCst);
        self.previous.signal_finished();
    }

    fn queue_change_allowed(&self) -> bool {
        false
    }

    fn queue(&self) -> Option<Arc<Queue>> {
        Some(self.queue.clone())
    }

    fn check_buffer_access(
        &self,
        buffer: &Buffer,
        range: Range<DeviceSize>,
        exclusive: bool,
        queue: &Queue,
    ) -> Result<(), AccessCheckError> {
        let resources_usage = self.command_buffer.resources_usage();
        let usage = match resources_usage.buffer_indices.get(buffer) {
            Some(&index) => &resources_usage.buffers[index],
            None => return Err(AccessCheckError::Unknown),
        };

        // TODO: check the queue family

        let result = usage
            .ranges
            .range(&range)
            .try_fold((), |_, (_range, range_usage)| {
                if !range_usage.mutable && exclusive {
                    Err(AccessCheckError::Unknown)
                } else {
                    Ok(())
                }
            });

        match result {
            Ok(()) => Ok(()),
            Err(AccessCheckError::Denied(err)) => Err(AccessCheckError::Denied(err)),
            Err(AccessCheckError::Unknown) => self
                .previous
                .check_buffer_access(buffer, range, exclusive, queue),
        }
    }

    fn check_image_access(
        &self,
        image: &Image,
        range: Range<DeviceSize>,
        exclusive: bool,
        expected_layout: ImageLayout,
        queue: &Queue,
    ) -> Result<(), AccessCheckError> {
        let resources_usage = self.command_buffer.resources_usage();
        let usage = match resources_usage.image_indices.get(image) {
            Some(&index) => &resources_usage.images[index],
            None => return Err(AccessCheckError::Unknown),
        };

        // TODO: check the queue family

        let result = usage
            .ranges
            .range(&range)
            .try_fold((), |_, (_range, range_usage)| {
                if expected_layout != ImageLayout::Undefined
                    && range_usage.final_layout != expected_layout
                {
                    return Err(AccessCheckError::Denied(
                        AccessError::UnexpectedImageLayout {
                            allowed: range_usage.final_layout,
                            requested: expected_layout,
                        },
                    ));
                }

                if !range_usage.mutable && exclusive {
                    Err(AccessCheckError::Unknown)
                } else {
                    Ok(())
                }
            });

        match result {
            Ok(()) => Ok(()),
            Err(AccessCheckError::Denied(err)) => Err(AccessCheckError::Denied(err)),
            Err(AccessCheckError::Unknown) => {
                self.previous
                    .check_image_access(image, range, exclusive, expected_layout, queue)
            }
        }
    }

    #[inline]
    fn check_swapchain_image_acquired(
        &self,
        swapchain: &Swapchain,
        image_index: u32,
        _before: bool,
    ) -> Result<(), AccessCheckError> {
        self.previous
            .check_swapchain_image_acquired(swapchain, image_index, false)
    }
}

unsafe impl<F> DeviceOwned for CommandBufferExecFuture<F>
where
    F: GpuFuture,
{
    fn device(&self) -> &Arc<Device> {
        self.command_buffer.device()
    }
}

impl<F> Drop for CommandBufferExecFuture<F>
where
    F: GpuFuture,
{
    fn drop(&mut self) {
        unsafe {
            if !*self.finished.get_mut() {
                // TODO: handle errors?
                self.flush().unwrap();
                // Block until the queue finished.
                self.queue.with(|mut q| q.wait_idle()).unwrap();
                self.previous.signal_finished();
            }
        }
    }
}

/// Error that can happen when attempting to execute a command buffer.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CommandBufferExecError {
    /// Access to a resource has been denied.
    AccessError {
        error: AccessError,
        command_name: Cow<'static, str>,
        command_param: Cow<'static, str>,
        command_offset: usize,
    },

    /// The command buffer or one of the secondary command buffers it executes was created with the
    /// "one time submit" flag, but has already been submitted it the past.
    OneTimeSubmitAlreadySubmitted,

    /// The command buffer or one of the secondary command buffers it executes is already in use by
    /// the GPU and was not created with the "concurrent" flag.
    ExclusiveAlreadyInUse,
    // TODO: missing entries (eg. wrong queue family, secondary command buffer)
}

impl Error for CommandBufferExecError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            CommandBufferExecError::AccessError { error, .. } => Some(error),
            _ => None,
        }
    }
}

impl Display for CommandBufferExecError {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
        write!(
            f,
            "{}",
            match self {
                CommandBufferExecError::AccessError { .. } =>
                    "access to a resource has been denied",
                CommandBufferExecError::OneTimeSubmitAlreadySubmitted => {
                    "the command buffer or one of the secondary command buffers it executes was \
                    created with the \"one time submit\" flag, but has already been submitted in \
                    the past"
                }
                CommandBufferExecError::ExclusiveAlreadyInUse => {
                    "the command buffer or one of the secondary command buffers it executes is \
                    already in use was not created with the \"concurrent\" flag"
                }
            }
        )
    }
}


text:
import cookielib
import urllib
import urllib2

# creates a cookie for the rtserver with the credentials given at initialization.
# define your credentials here
access_user = 'biju.ch'
access_password = '1qaz@wsx'

# here is the RequestTracker URI we try to access
uri = 'https://sysrt.ops.directi.com/REST/1.0/ticket/123/show'

# trying login on rt server
cj = cookielib.LWPCookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)
data = {'user': access_user, 'pass': access_password}
ldata = urllib.urlencode(data)
login = urllib2.Request(uri, ldata)
try:
   response = urllib2.urlopen(login)
   print response.read()
   print "login successful"
except urllib2.URLError:
   # could not connect to server
   print "Not able to login"


text:
import sys

import numpy as np
from numpy.testing import assert_array_almost_equal, assert_equal

from .. import SparsePCA, MiniBatchSparsePCA, dict_learning_online
from ..sparse_pca import _update_code, _update_code_parallel
from ...utils import check_random_state

def generate_toy_data(n_atoms, n_samples, image_size, random_state=None):
    n_features = image_size[0] * image_size[1]

    rng = check_random_state(random_state)
    U = rng.randn(n_samples, n_atoms)
    V = rng.randn(n_atoms, n_features)

    centers = [(3, 3), (6, 7), (8, 1)]
    sz = [1, 2, 1]
    for k in range(n_atoms):
        img = np.zeros(image_size)
        xmin, xmax = centers[k][0] - sz[k], centers[k][0] + sz[k]
        ymin, ymax = centers[k][1] - sz[k], centers[k][1] + sz[k]
        img[xmin:xmax][:, ymin:ymax] = 1.0
        V[k, :] = img.ravel()

    # Y is defined by : Y = UV + noise
    Y = np.dot(U, V)
    Y += 0.1 * rng.randn(Y.shape[0], Y.shape[1])  # Add noise
    return Y, U, V

# SparsePCA can be a bit slow. To avoid having test times go up, we
# test different aspects of the code in the same test

def test_correct_shapes():
    rng = np.random.RandomState(0)
    X = rng.randn(12, 10)
    spca = SparsePCA(n_components=8, random_state=rng)
    U = spca.fit_transform(X)
    assert_equal(spca.components_.shape, (8, 10))
    assert_equal(U.shape, (12, 8))
    # test overcomplete decomposition
    spca = SparsePCA(n_components=13, random_state=rng)
    U = spca.fit_transform(X)
    assert_equal(spca.components_.shape, (13, 10))
    assert_equal(U.shape, (12, 13))

def test_fit_transform():
    rng = np.random.RandomState(0)
    Y, _, _ = generate_toy_data(3, 10, (8, 8), random_state=rng)  # wide array
    spca_lars = SparsePCA(n_components=3, method='lars', random_state=rng)
    spca_lars.fit(Y)
    U1 = spca_lars.transform(Y)
    # Test multiple CPUs
    if sys.platform == 'win32':  # fake parallelism for win32
        import sklearn.externals.joblib.parallel as joblib_par
        _mp = joblib_par.multiprocessing
        joblib_par.multiprocessing = None
        try:
            spca = SparsePCA(n_components=3, n_jobs=2, random_state=rng).fit(Y)
            U2 = spca.transform(Y)
        finally:
            joblib_par.multiprocessing = _mp
    else:  # we can efficiently use parallelism
        spca = SparsePCA(n_components=3, n_jobs=2, random_state=rng).fit(Y)
        U2 = spca.transform(Y)
    assert_array_almost_equal(U1, U2)
    # Test that CD gives similar results
    spca_lasso = SparsePCA(n_components=3, method='cd', random_state=rng)
    spca_lasso.fit(Y)
    assert_array_almost_equal(spca_lasso.components_, spca_lars.components_)

def test_fit_transform_tall():
    rng = np.random.RandomState(0)
    Y, _, _ = generate_toy_data(3, 65, (8, 8), random_state=rng)  # tall array
    spca_lars = SparsePCA(n_components=3, method='lars', random_state=rng)
    U1 = spca_lars.fit_transform(Y)
    spca_lasso = SparsePCA(n_components=3, method='cd', random_state=rng)
    U2 = spca_lasso.fit(Y).transform(Y)
    assert_array_almost_equal(U1, U2)

def test_sparse_code():
    rng = np.random.RandomState(0)
    dictionary = rng.randn(10, 3)
    real_code = np.zeros((3, 5))
    real_code.ravel()[rng.randint(15, size=6)] = 1.0
    Y = np.dot(dictionary, real_code)
    est_code_1 = _update_code(dictionary, Y, alpha=1.0)
    est_code_2 = _update_code_parallel(dictionary, Y, alpha=1.0)
    assert_equal(est_code_1.shape, real_code.shape)
    assert_equal(est_code_1, est_code_2)
    assert_equal(est_code_1.nonzero(), real_code.nonzero())

def test_initialization():
    rng = np.random.RandomState(0)
    U_init = rng.randn(5, 3)
    V_init = rng.randn(3, 4)
    model = SparsePCA(n_components=3, U_init=U_init, V_init=V_init, max_iter=0,
                      random_state=rng)
    model.fit(rng.randn(5, 4))
    assert_equal(model.components_, V_init)

def test_dict_learning_online_shapes():
    rng = np.random.RandomState(0)
    X = rng.randn(12, 10)
    dictionaryT, codeT = dict_learning_online(X.T, n_atoms=8, alpha=1,
                                              random_state=rng)
    assert_equal(codeT.shape, (8, 12))
    assert_equal(dictionaryT.shape, (10, 8))
    assert_equal(np.dot(codeT.T, dictionaryT.T).shape, X.shape)

def test_mini_batch_correct_shapes():
    rng = np.random.RandomState(0)
    X = rng.randn(12, 10)
    pca = MiniBatchSparsePCA(n_components=8, random_state=rng)
    U = pca.fit_transform(X)
    assert_equal(pca.components_.shape, (8, 10))
    assert_equal(U.shape, (12, 8))
    # test overcomplete decomposition
    pca = MiniBatchSparsePCA(n_components=13, random_state=rng)
    U = pca.fit_transform(X)
    assert_equal(pca.components_.shape, (13, 10))
    assert_equal(U.shape, (12, 13))

def test_mini_batch_fit_transform():
    rng = np.random.RandomState(0)
    Y, _, _ = generate_toy_data(3, 10, (8, 8), random_state=rng)  # wide array
    spca_lars = MiniBatchSparsePCA(n_components=3, random_state=rng).fit(Y)
    U1 = spca_lars.transform(Y)
    # Test multiple CPUs
    if sys.platform == 'win32':  # fake parallelism for win32
        import sklearn.externals.joblib.parallel as joblib_par
        _mp = joblib_par.multiprocessing
        joblib_par.multiprocessing = None
        try:
            U2 = MiniBatchSparsePCA(n_components=3, n_jobs=2,
                                    random_state=rng).fit(Y).transform(Y)
        finally:
            joblib_par.multiprocessing = _mp
    else:  # we can efficiently use parallelism
        U2 = MiniBatchSparsePCA(n_components=3, n_jobs=2,
                                random_state=rng).fit(Y).transform(Y)
    assert_array_almost_equal(U1, U2)
    # Test that CD gives similar results
    spca_lasso = MiniBatchSparsePCA(n_components=3, method='cd',
                                    random_state=rng).fit(Y)
    assert_array_almost_equal(spca_lasso.components_, spca_lars.components_)


text:
/**
 * 支持mouse,pointer,drag,touch事件;
 * 根据浏览器具体的支持情况选择相应的事件类型;
 * 以mouse事件为例down,move,enter,leave,up
 * touch无对用的enter,leave事件需特殊处理
 *
 * 每次拖拽设计到相应事件的绑定和结束的事件解绑
 *
 * Created by Administrator on 2017/9/18.
 */

/**
 * EndEvent: {item, from, to, oldIndex, newIndex}
 */
import { throttle, closest, index, on, off, find, toggleClass, css, hasClass} from './utils'

/**
 * 分发事件
 * @param draggable 当前实例
 * @param name 事件名称
 * @param targetEl 目标元素
 * @param fromEl 来源容器元素
 * @param toEl 存放容器元素
 * @param oldIndex 起始位置
 * @param newIndex 结束位置
 * @private
 */
function _dispatchEvent(draggable, rootEl, name, targetEl, fromEl, toEl, oldIndex, newIndex) {
    let evt = document.createEvent('Event')
    let options = draggable.options
    let onName = 'on' + name.charAt(0).toUpperCase() + name.substr(1)

    evt.initEvent(name, true, true)
    evt.item = targetEl || fromEl
    evt.clone = draggable.cloneEl
    evt.from = fromEl
    evt.to = toEl
    evt.oldIndex = oldIndex
    evt.newIndex = newIndex

    rootEl.dispatchEvent(evt)

    if (options[onName]) {
        options[onName].call(draggable, evt)
    }
}

/**
 * 将对应元素设置成不可拖拽
 * @param el
 * @private
 */
function _disableDraggable(el) {
    el.draggable = false
}

function _globalDragOver(evt) {
    if (evt.dataTransfer) {
        evt.dataTransfer.dropEffect = 'move'
    }
    evt.preventDefault()
}

/**
 * 获取当前的相对元素,可能为占位符
 * @param x
 * @param y
 * @param dorEl
 * @param dorClass
 * @param relClass
 * @returns {*}
 * @private
 */
function _getRelEl (x, y, dorEl, dorClass, relClass) {
    // document.elementFromPoint(x, y)
    let child = dorEl.firstElementChild
    while (child) {
        let rect = child.getBoundingClientRect()
        if (rect.top <= y && y <= (rect.top + rect.height)) {
            if (hasClass(child, dorClass)) { // 存在子容器
                //
                let subDorEls = child.getElementsByClassName(dorClass)
                child = subDorEls.length > 0 ? subDorEls[0] : child
                break
            }
            return child
        }
        child = child.nextElementSibling
    }
    // 不存在相对元素,返回容器元素
    if (!child) return dorEl
    return _getRelEl(x, y, child, dorClass, relClass)
}

/**
 * 获取当前坐标在相对元素上的方位
 * @param x
 * @param y
 * @param relEl
 * @returns {string} lt,lb,rt,rb
 * @private
 */
function _getPosition (x, y, relEl) {
    let rect = relEl.getBoundingClientRect()
    let position = ''
    if (x < (rect.left + rect.width / 2)) {
        position = y < (rect.top + rect.height / 2) ? 'lt' : 'lb'
    } else {
        position = y < (rect.top + rect.height / 2) ? 'rt' : 'rb'
    }
    return position
}

/**
 * 判断是否进入容器
 * @param x
 * @param y
 * @param container
 * @returns {boolean}
 * @private
 */
function _isEntered (x, y, container) {
    if (container) {
        let rect = container.getBoundingClientRect()
        return rect.left < x && x < (rect.left + rect.width) &&
            rect.top < y && y < (rect.top + rect.height)
    }
    return false
}

/**
 * 容器自动滚动
 * @param container
 * @param options
 * @param evt
 * @private
 */
let _autoScroll = throttle(function (evt, inst) {
    if (inst && inst.dorEl && inst.options.scroll) {
        let options = inst.options
        let x = evt.clientX
        let y = evt.clientY
        let scrollOffsetX
        let scrollOffsetY
        let sens = options.scrollSensitivity
        let scrollCustomFn = options.scrollFn
        let speed = options.scrollSpeed
        let rect = inst.dorEl.getBoundingClientRect()
        let vx
        let vy
        if (inst.dorEl === window) {
            vx = ( window.innerWidth - x <= sens) - (x <= sens)
            vy = (window.innerHeight - y <= sens) - (y <= sens)
        } else {
            vx = (Math.abs(rect.right - x) <= sens) - (Math.abs(rect.left - x) <= sens)
            vy = (Math.abs(rect.bottom - y) <= sens) - (Math.abs(rect.top - y) <= sens)
        }

        if (inst.vx !== vx || inst.vy !== vy) {
            inst.vx = vx
            inst.vy = vy

            clearInterval(inst.pid)

            inst.pid = setInterval(function () {
                scrollOffsetY = vy ? vy * speed : 0
                scrollOffsetX = vx ? vx * speed : 0

                if ('function' === typeof(scrollCustomFn)) {
                    return scrollCustomFn.call(inst, scrollOffsetX, scrollOffsetY, evt)
                }

                if (inst.dorEl === window) {
                    window.scrollTo(window.pageXOffset + scrollOffsetX, window.pageYOffset + scrollOffsetY)
                } else {
                    inst.dorEl.scrollTop += scrollOffsetY
                    inst.dorEl.scrollLeft += scrollOffsetX
                }
            }, 24)
        }
    }
}, 30)

export function eventMixin (Draggable) {
    /**
     * 判断元素是否可拖动
     * @param evt Event|TouchEvent
     * @private
     */
    Draggable.prototype._onTapStart = function (evt) {
        const darEl = this.darEl
        let options = this.options
        let preventOnFilter = options.preventOnFilter
        let type = evt.type
        let touch = evt.touches && evt.touches[0]
        let target = (touch || evt).target
        let originalTarget = evt.target.shadowRoot && (evt.path && evt.path[0]) || target
        let filter = options.filter

        // 禁止同时触发两个拖拽事件
        if (this.dragEl) {
            return
        }

        // 鼠标事件必须同时按下鼠标左键;用户手动设置禁止拖拽
        if (/mousedown|pointerdown/.test(type) && evt.button !== 0 || options.disabled) {
            return
        }

        // 判断是否为可拖拽元素
        target = closest(target, options.draggable, darEl)
        if (!target) {
            return
        }
        // 获取元素起始位置
        this.oldIndex = index(target, options.draggable)

        // 过滤元素
        if (filter) {
            const _this = this
            let fromEl = hasClass(target, options.darClass) ? darEl : closest(target, `.${options.darClass}`, darEl)
            filter = filter.split(',').some(function (criteria) {
                criteria = closest(originalTarget, criteria.trim(), darEl)
                if (criteria) {
                    _dispatchEvent(_this, criteria, 'filter', target, fromEl, null, null, null)
                    return true
                }
            })

            if (filter) {
                preventOnFilter && evt.preventDefault()
                return
            }
        }

        // 判断是否设置了handle
        if (options.handle && !closest(originalTarget, options.handle, darEl)) {
            return
        }

        this._prepareDragStart(evt, touch, target)
    }

    /**
     * 拖拽元素前的准备工作
     * @param evt
     * @param touch
     * @param target
     * @param startIndex
     * @private
     */
    Draggable.prototype._prepareDragStart = function (evt, touch, target) {
        const _this = this
        let darEl = _this.darEl
        let options = _this.options
        let dragStartFn

        // 不强制要求draggable为darEl的直接子元素
        if (target && !_this.dragEl) {
            _this.tapEvt = evt

            _this.dragEl = target
            // 这时需要为fromEl复制,确定来源
            _this.fromEl = hasClass(_this.dragEl, options.darClass) ? darEl : closest(_this.dragEl, `.${options.darClass}`, darEl)

            dragStartFn = function () {
                toggleClass(_this.dragEl, options.chosenClass, true)
                _this.dragEl.draggable = _this.nativeDraggable
                _this._triggerDragStart(evt, touch)
                _dispatchEvent(_this, darEl, 'choose', _this.dragEl, _this.fromEl, null, null, null)
            }

            options.ignore.split(',').forEach(function (criteria) {
                find(_this.dragEl, criteria.trim(), _disableDraggable)
            })
            on(document, 'selectstart', _this)
            dragStartFn()
        }
    }

    /**
     *
     * @param evt
     * @param touch
     * @private
     */
    Draggable.prototype._triggerDragStart = function (evt, touch) {
        // pointerType: mouse, pen, touch
        touch = touch || (evt.pointerType === 'touch' ? evt : null)
        if (touch) { // 手势
            this.tapEvt = {
                target: this.dragEl,
                clientX: touch.clientX,
                clientY: touch.clientY
            }
            this._onDragStart(this.tapEvt, 'touch')
        } else if (!this.nativeDraggable) { // 鼠标事件
            this._onDragStart(this.tapEvt, true)
        } else { // H5拖拽
            on(this.darEl, 'dragstart', this._onDragStart)
        }
        // 处理selection
        try {
            if (document.selection) { // IE
                setTimeout(function () {
                    document.selection.empty()
                }, 0)
            } else {
                window.getSelection().removeAllRanges()
            }
        } catch (err) {
        }
    }

    /**
     * 拖拽开始
     * @param evt
     * @param useFallback
     * @private
     */
    Draggable.prototype._onDragStart = function (evt, useFallback) {
        if (useFallback) {
            if (useFallback === 'touch') { // 手势事件
                on(document, 'touchmove', this._onMove)
                on(document, 'touchend', this._onDrop)
                on(document, 'touchcancel', this._onDrop)
                on(document, 'pointermove', this._onMove)
                on(document, 'pointerup', this._onDrop)
            } else { // 鼠标事件
                on(document, 'mousemove', this._onMove)
                on(document, 'mouseup', this._onDrop)
            }
        } else {
            on(this.dorEl, 'dragover', this)
            on(document, 'drop', this)
        }
        setTimeout(this._dragStarted, 0)
    }

    Draggable.prototype._dragStarted = function () {
        if (this.dragEl && this.darEl) {
            let options = this.options

            toggleClass(this.dragEl, options.chosenClass, true)

            _dispatchEvent(this, this.darEl, 'start', this.dragEl, this.fromEl, null, null, null)
        } else {
            this._nulling()
        }
    }

    /**
     * 处理非H5拖拽是ghost元素
     * 对应mousemove,pointermove,drag事件
     * @param evt
     * @private
     */
    Draggable.prototype._onMove = function (evt) {
        if (this.tapEvt && this.moved) {
            evt = evt.touches ? evt.touches[0] : evt
            this._appendGhost()
            this._onDrag(evt)
            // 进入容器显示占位符
            let rect = this.ghostEl.getBoundingClientRect()
            css(this.ghostEl, 'left', `${evt.clientX - rect.width / 2 - document.body.scrollLeft}px`)
            css(this.ghostEl, 'top', `${evt.clientY - rect.height / 2 - document.body.scrollTop}px`)
        }
        this.moved = true
    }

    /**
     *
     * @param evt
     * @private
     */
    Draggable.prototype._onDrag = function (evt) {
        this.entered = _isEntered(evt.clientX, evt.clientY, this.dorEl)
        this.entered && this._appendPlaceholder(evt)
        // 非H5拖拽且进入容器
        !this.nativeDraggable && this.entered && _autoScroll(evt, this)
    }

    Draggable.prototype._onDrop = function (evt) {
        console.log('onDrop')
        // 解绑事件
        if (evt.touches || evt.type === 'pointerup') {
            off(document, 'touchmove', this._onMove)
            off(document, 'touchend', this._onDrop)
            off(document, 'touchcancel', this._onDrop)
            off(document, 'pointermove', this._onMove)
            off(document, 'pointerup', this._onDrop)
        } else if (!this.nativeDraggable) {
            off(document, 'mousemove', this._onMove)
            off(document, 'mouseup', this._onDrop)
        } else {
            off(this.darEl, 'dragstart', this._onDragStart)
            off(this.dorEl, 'dragover', this)
            off(this.dragEl, 'dragend', this)
            off(document, 'drop', this)
        }
        // 清除自动滚动的定时器
        clearInterval(this.pid)
        let options = this.options
        if (this.entered) {
            this.toEl = closest(this.phEl, `.${options.dorClass}`, this.dorEl)
            // 获取newIndex
            this.newIndex = index(this.phEl, `.${options.relClass}`)
            if (this.oldIndex > -1 && this.newIndex > -1) {
                _dispatchEvent(this, this.darEl, 'end', this.dragEl, this.fromEl, this.toEl, this.oldIndex, this.newIndex)
            }
        }
        this._nulling()
    }

    /**
     * 生成ghost元素
     * @private
     */
    Draggable.prototype._appendGhost = function () {
        if (!this.ghostEl) {
            let options = this.options
            let ghostEl = document.createElement('div')
            ghostEl.appendChild(this.dragEl.cloneNode(true))

            toggleClass(ghostEl, options.ghostClass, true)

            css(ghostEl, 'zIndex', '100000')

            document.body.appendChild(ghostEl)
            this.ghostEl = ghostEl
        }
    }

    /**
     * 生成占位符
     * @param evt
     * @private
     */
    Draggable.prototype._appendPlaceholder = function (evt) {
        let options = this.options
        if (!this.phEl) {
            // 生成占位符元素
            let placeholderEl = document.createElement('div')
            toggleClass(placeholderEl, options.phClass, true)
            this.phEl = placeholderEl
        }
        let relEl = _getRelEl(evt.clientX, evt.clientY, this.dorEl, options.dorClass, options.relClass)
        //获取的相对元素为占位符
        if (relEl === this.phEl) {
            console.log('draggable-phEl:relEl equals phEl')
            return
        }
        let position = _getPosition(evt.clientX, evt.clientY, relEl)
        // 需要根据relEl和position判断是否需要处理phEl
        let insertType = (options.direction === 'row' && (position === 'rt' || position === 'rb')) ||
            (options.direction === 'column' && (position === 'lb' || position === 'rb')) ? 'after' : 'before'
        // 相对元素和显示位置不变
        if (relEl === this.relEl && insertType === this.insertType) {
            return
        }
        this.relEl = relEl
        this.insertType = insertType
        if (hasClass(relEl, options.dorClass) || relEl === this.dorEl) {
            this.phEl.parentNode !== relEl && relEl.appendChild(this.phEl)
            return
        }
        let container = closest(relEl, `.${options.dorClass}`, this.dorEl) || this.dorEl
        if (insertType === 'before') {
            container.insertBefore(this.phEl, relEl)
        } else {
            let nextEl = relEl.nextElementSibling
            nextEl ? container.insertBefore(this.phEl, nextEl) : container.appendChild(this.phEl)
        }
    }

    /**
     * 拖拽事件分发
     * @param evt
     */
    Draggable.prototype.handleEvent = function (evt) {
        switch (evt.type) {
            case 'drop':
            case 'dragend':
                this._onDrop(evt)
                break
            case 'dragover':
                this._onDrag(evt)
                _globalDragOver(evt)
                break
            case 'selectstart':
                evt.preventDefault()
                break
        }
    }
}

export function initEvents (inst) {
    const darEl = inst.darEl
    // 绑定初始点击事件
    on(darEl, 'mousedown', inst._onTapStart)
    on(darEl, 'touchstart', inst._onTapStart)
    on(darEl, 'pointerdown', inst._onTapStart)
}


text:
package com.conscious.it.dao;

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

import org.springframework.stereotype.Repository;

import com.conscious.it.model.User;

@Repository
public class UserDao {

	static List<User> users = new ArrayList<User>();
	static int i = 0;

	public void save(User user) {
		user.setId(++i);
		users.add(user);
	}

	public List<User> getAll() {
		return users;
	}

	public User getById(Integer id) {
		for (User user : users) {
			if(user.getId().equals(id)) {
				return user;
			}
		}
		return null;
	}

}


text:
#include"spc_eq_resolution.h"

namespace spc {

    /**
       \brief Apply equality resolution rule on the given clause.
       Store the produced clauses in new_clauses.
    */
    void eq_resolution::operator()(clause * cls, ptr_vector<clause> & new_clauses) {
        m_subst.reserve_vars(cls->get_num_vars());
        unsigned num = cls->get_num_literals();
        for (unsigned i = 0; i < num; i++) {
            literal const & l = cls->get_literal(i);
            expr * atom = l.atom();
            if (l.sign() && m_manager.is_eq(atom)) {
                expr * lhs = to_app(atom)->get_arg(0);
                expr * rhs = to_app(atom)->get_arg(1);
                m_subst.reset();
                if (m_unifier(lhs, rhs, m_subst, false) && cls->is_eligible_for_resolution(m_order, l, 0, &m_subst)) {
                    m_stats.m_num_eq_resolution++;
                    new_clauses.push_back(mk_result(cls, i));
                }
            }
        }
    }
};


text:
Using non-null assertions cancels the benefits of the strict null-checking mode.

Examples of **incorrect** code for this rule:

```ts
interface Foo {
    bar?: string;
}

const foo: Foo = getFoo();
const includesBaz: boolean = foo.bar!.includes("baz");
```

Examples of **correct** code for this rule:

```ts
interface Foo {
    bar?: string;
}

const foo: Foo = getFoo();
const includesBaz: boolean = foo.bar && foo.bar.includes("baz");
```

## When Not To Use It

If you don't care about strict null-checking, then you will not need this rule.

## Further Reading

* [`no-non-null-assertion`](https://palantir.github.io/tslint/rules/no-non-null-assertion/) in [TSLint](https://palantir.github.io/tslint/)


text:
<?php

/**
 * RengTax filter form base class.
 *
 * @package    gesser
 * @subpackage filter
 * @author     Luis Hernández
 * @version    SVN: $Id: sfDoctrineFormFilterGeneratedTemplate.php 29570 2010-05-21 14:49:47Z Kris.Wallsmith $
 */
abstract class BaseRengTaxFormFilter extends BaseFormFilterDoctrine
{
  public function setup()
  {
    $this->setWidgets(array(
      'tax_id'   => new sfWidgetFormDoctrineChoice(array('model' => $this->getRelatedModelName('Tax'), 'add_empty' => true)),
      'tasa1'    => new sfWidgetFormFilterInput(array('with_empty' => false)),
      'tasa2'    => new sfWidgetFormFilterInput(array('with_empty' => false)),
      'tasa3'    => new sfWidgetFormFilterInput(array('with_empty' => false)),
      'formula'  => new sfWidgetFormChoice(array('choices' => array('' => 'yes or no', 1 => 'yes', 0 => 'no'))),
      'limite'   => new sfWidgetFormFilterInput(array('with_empty' => false)),
      'porc1'    => new sfWidgetFormFilterInput(array('with_empty' => false)),
      'porc2'    => new sfWidgetFormFilterInput(array('with_empty' => false)),
      'rowguid'  => new sfWidgetFormFilterInput(array('with_empty' => false)),
    ));

    $this->setValidators(array(
      'tax_id'   => new sfValidatorDoctrineChoice(array('required' => false, 'model' => $this->getRelatedModelName('Tax'), 'column' => 'tax_id')),
      'tasa1'    => new sfValidatorSchemaFilter('text', new sfValidatorNumber(array('required' => false))),
      'tasa2'    => new sfValidatorSchemaFilter('text', new sfValidatorNumber(array('required' => false))),
      'tasa3'    => new sfValidatorSchemaFilter('text', new sfValidatorNumber(array('required' => false))),
      'formula'  => new sfValidatorChoice(array('required' => false, 'choices' => array('', 1, 0))),
      'limite'   => new sfValidatorSchemaFilter('text', new sfValidatorNumber(array('required' => false))),
      'porc1'    => new sfValidatorSchemaFilter('text', new sfValidatorNumber(array('required' => false))),
      'porc2'    => new sfValidatorSchemaFilter('text', new sfValidatorNumber(array('required' => false))),
      'rowguid'  => new sfValidatorPass(array('required' => false)),
    ));

    $this->widgetSchema->setNameFormat('reng_tax_filters[%s]');

    $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);

    $this->setupInheritance();

    parent::setup();
  }

  public function getModelName()
  {
    return 'RengTax';
  }

  public function getFields()
  {
    return array(
      'tax_num'  => 'Number',
      'reng_num' => 'Number',
      'tax_id'   => 'ForeignKey',
      'tasa1'    => 'Number',
      'tasa2'    => 'Number',
      'tasa3'    => 'Number',
      'formula'  => 'Boolean',
      'limite'   => 'Number',
      'porc1'    => 'Number',
      'porc2'    => 'Number',
      'rowguid'  => 'Text',
    );
  }
}


text:
//
// stream.c
// 27-Jan-99
//
// VOID    streamReturnBuffer(STREAM *streamPtr);
// VOID    streamReturnBuffers(STREAM *streamPtr);
// USHORT  streamPauseTime(STREAM *streamPtr);
// USHORT  streamResumeTime(STREAM *streamPtr);
// USHORT  streamRegister(DDCMDREGISTER __far *cmdPtr, STREAM *streamPtr);
// VOID    streamDeregister(STREAM *streamPtr);
// USHORT  streamRead(UCHAR __far *bufferPtr, ULONG length, STREAM *streamPtr);
// USHORT  streamWrite(UCHAR __far *bufferPtr, ULONG length, STREAM *streamPtr);
// USHORT  streamInit(USHORT streamType, STREAM *streamPtr);
// USHORT  streamDeinit(STREAM *streamPtr);
// STREAM *streamFindActive(USHORT streamType);
// STREAM *streamFindStreamSFN(ULONG SFN);
// STREAM *streamFindStreamHandle(HSTREAM streamH);
// STREAM_BUFFER *sbHead(STREAM_BUFFER_ANCHOR *sbaPtr);
// STREAM_BUFFER *sbTail(STREAM_BUFFER_ANCHOR *sbaPtr);
// VOID    sbPushOnHead(STREAM_BUFFER *sbPtr, STREAM_BUFFER_ANCHOR *sbaPtr);
// VOID    sbPushOnTail(STREAM_BUFFER *sbPtr, STREAM_BUFFER_ANCHOR *sbaPtr);
// STREAM_BUFFER *sbPopHead(STREAM_BUFFER_ANCHOR *sbaPtr);
// STREAM_BUFFER *sbPopTail(STREAM_BUFFER_ANCHOR *sbaPtr);
// USHORT  sbDestroyElement(STREAM_BUFFER *sbPtr, STREAM_BUFFER_ANCHOR *sbaPtr);
// STREAM_BUFFER *sbPopElement(STREAM_BUFFER *match_sbPtr, STREAM_BUFFER_ANCHOR *sbaPtr);
// USHORT  sbNotEmpty(STREAM_BUFFER_ANCHOR *sbaPtr);
// STREAM *streamHead(VOID);
// STREAM *streamTail(VOID);
// VOID    streamPushOnHead(STREAM *sPtr);
// VOID    streamPushOnTail(STREAM *sPtr);
// STREAM *streamPopHead(VOID);
// STREAM *streamPopTail(VOID);
// USHORT  streamDestroyElement(STREAM *sPtr);
// STREAM *streamPopElement(STREAM *match_sPtr);
// USHORT  streamNotEmpty(VOID);
//
// to init queue set headPtr/tailPtr = 0
// which is accomplished by simply MEMSET()'ing the allocation
// ie, the contructor (doesn't seem to be a destructor for the QUEUE class)
//
// ----------------------------------------- NOTE -------------------------------------------
// the following event-support routines are not yet done (stubs, all now have STREAM * as parm)
// parm list subject change (:
//
//VOID streamProcessEvents(STREAM *streamPtr) ;
//VOID streamEnableEvent(DDCMDCONTROL __far *ddcmdPtr, STREAM *streamPtr);
//VOID streamDisableEvent(DDCMDCONTROL __far *ddcmdPtr, STREAM *streamPtr);
//VOID streamSetNextEvent(STREAM *streamPtr);

#include "cs40.h"

static STREAM_ANCHOR streamList = {0,0}; // head of list (has .headPtr and .tailPtr to STREAM structures)

// ---------------------------------------------------------------------
// in: streamPtr -> stream from which to remove head buffer of done list
//out: n/a
//nts: frees stream buffer that was at head of done list

VOID streamReturnBuffer(STREAM *streamPtr) {

 static SHD_REPORTINT shdri = {SHD_REPORT_INT,0,0,0,0,0};  // structure to return buffers to SHD

 STREAM_BUFFER *tsbPtr = sbPopHead(&streamPtr->sbaDone);  // was STREAM_BUFFER *tsbPtr = (PSTREAMBUFFER)qhDone.PopHead();

// !!!
//ddprintf("@streamReturnBuffer, streamPtr=%x\n",streamPtr);

 if (tsbPtr) {

    if (streamPtr->streamType & STREAM_WRITE) {

       // this is a write (playback): tell stream handler that we played all of the buffer

       shdri.ulFlag = SHD_WRITE_COMPLETE;
       shdri.ulStatus = tsbPtr->bufferSize;
    }
    else {

       // this is a capture: tell stream hamdler how much data we wrote to the buffer

       shdri.ulFlag = SHD_READ_COMPLETE;
       shdri.ulStatus = tsbPtr->bufferCurrPos;
    }

    shdri.hStream = streamPtr->streamH;
    shdri.pBuffer = tsbPtr->bufferPtr;

    // wavestreamGetCurrentTime() needs to access stream's parent WAVESTREAM structure --
    // this is the only case (so far) where a stream operation needs to look at what's
    // in WAVSTREAM (specifically, abPtr, needed by this get time call) -- had to add
    // this member to the STREAM structure (1-Feb-99), and set it up in streamInit(),
    // which is called by wavestreamInit() (WAVESTREAM constructor) by IoctlAudioInit()...
    // ugh, the driver docs just plain suck

    shdri.ulStreamTime = wavestreamGetCurrentTime(streamPtr->wsParentPtr);

#ifdef TRACE_RETBUFFER
 tracePerf(TRACE_RETBUFFER_IN, _IF());
#endif

    streamPtr->pfnSHD(&shdri);  // function call

#ifdef TRACE_RETBUFFER
 tracePerf(TRACE_RETBUFFER_OUT,_IF());
#endif

    free(tsbPtr); // this is what lots and lots of allocations come from

// !!!
//ddprintf("~streamReturnBuffer:free:%x\n",tsbPtr);

 }

 return;
}

// --------------------------------------------------------
// in: streamPtr -> stream from which to remove head buffer
//out: n/a
//nts: returns (and frees) all stream buffers

VOID streamReturnBuffers(STREAM *streamPtr) {

 STREAM_BUFFER *tsbPtr;

 while(sbNotEmpty(&streamPtr->sbaProc)) {       // likely gets inlined so use sbNotEmpty()
    tsbPtr = sbPopHead(&streamPtr->sbaProc);    // rather than sbPopHead() until it returns 0
    sbPushOnTail(tsbPtr, &streamPtr->sbaDone);  // pop from proc list and push on done list since...
 }

 while(sbNotEmpty(&streamPtr->sbaDone)) {       // stream buffers were moved to the done list
    streamReturnBuffer(streamPtr);              // because that's what streamReturnBuffer() uses
 }                                              // namely, the head of the done list

 return;
}

// ---------------------------------------------------
// in: streamPtr -> stream to pause/resume time counter
//out: always 0, for okay
//nts: returns USHORT though caller (ssm_idc.c) expects ULONG to return back to MMPM

USHORT streamPauseTime(STREAM *streamPtr) {
 streamPtr->counterIncFlag = 0;
 return 0;
}

USHORT streamResumeTime(STREAM *streamPtr) {
 streamPtr->counterIncFlag = 1;
 return 0;
}

// ---------------------------------------------------
// in: cmdPtr -> DDCMDREGISTER pack (far ptr)
//     streamPtr -> stream working on
//out: always 0, for okay
//nts: returns USHORT though caller (ssm_idc.c) expects ULONG to return back to MMPM
//
// ulBufSize: Specifies VSD or PDD output buffer size in bytes that will be sent to
//            the driver. The caller will fill in a default value. If the device driver
//            does not override this value, it will be used to determine the buffer size.
//
// Note:  The device driver sets this field to indicate the buffer size that it would like to
// receive from the streaming subsystem. For MIDI, this field is usually set to 512. For DMA-based
// audio or other systems where the interrupt rate equals the buffer rate, this field should
// be set to about 1/30 the quantity of data consumed or produced per second. This field supplies
// the system with a minimal buffer size for wave audio. Because other system elements also
// negotiate to determine buffer size and for software motion video, the system might provide
// buffers smaller than the size requested.

USHORT streamRegister(DDCMDREGISTER __far *cmdPtr, STREAM *streamPtr) {

 streamPtr->streamH = cmdPtr->hStream;
 streamPtr->pfnSHD =  (T_PFNSHD) cmdPtr->pSHDEntryPoint;  // need cast since using a __cdecl cc

 cmdPtr->ulAddressType = ADDRESS_TYPE_VIRTUAL;  // type of buffer pointer want to get from SSM
 cmdPtr->mmtimePerUnit = 0;     // not used
 cmdPtr->ulBytesPerUnit = 0;    // not used

 // suggestions:
 cmdPtr->ulNumBufs = 0x00000006;  // 6 default buffers, at 60K each, is about 2 secs
 cmdPtr->ulBufSize = 0x0000F000;  // see Note above

 return 0;
}

// ---------------------------------------------------
// in: streamPtr -> stream to deregister
//out: n/a
//nts:

VOID streamDeregister(STREAM *streamPtr) {

 streamPtr->streamH = 0;
 streamPtr->pfnSHD = 0;

 return;
}

// ---------------------------------------------
// in: bufferPtr -> stream buffer data (far ptr)
//     bufferSize = size of empty buffer (passed down as ULONG from kernel, org was short)
//     wsPtr -> WAVESTREAM structure
//out: 0 if okay, else rc (no memory, eg)
//nts: called by DDCMD_READ
//     original was getting length as "unsigned" as in USHORT
//     similar to streamWrite()
//     was called Read(), was also in wavestrm.c but why?  so moved here, to stream.c
//     (when it was in wavestrm.c, it was using &wsPtr->streamPtr->sbaProc... otherwise same)

USHORT streamRead(UCHAR __far *bufferPtr, ULONG length, STREAM *streamPtr) {

 USHORT rc = 0;
 STREAM_BUFFER *newsbPtr = malloc(sizeof(STREAM_BUFFER));

// !!!
//ddprintf("@streamRead:newsbPtr=%x\n",newsbPtr);

 if (newsbPtr) {
    newsbPtr->nextPtr = 0;
    newsbPtr->rsv2 = 0;
    newsbPtr->bufferPtr = bufferPtr;
    newsbPtr->bufferSize = length;
    newsbPtr->bufferCurrPos = 0;
    newsbPtr->bufferDonePos = 0;

    sbPushOnTail(newsbPtr, &streamPtr->sbaProc);
 }
 else {
    rc = 8;
 }

 return rc;
}

// ---------------------------------------------------
// in: bufferPtr -> streaming buffer to add
//     length = size of streaming buffer to add
//     streamPtr -> stream to add stream buffer to
//out: 0 if okay, else rc (no memory, eg)
//nts: original was getting length as "unsigned" as in USHORT
//     org was also always in stream.c, unlike Read() which was in wavestrm.c

USHORT streamWrite(UCHAR __far *bufferPtr, ULONG length, STREAM *streamPtr) {

 USHORT rc = 0;
 STREAM_BUFFER *newsbPtr = malloc(sizeof(STREAM_BUFFER));

// !!!
//ddprintf("@streamWrite:newsbPtr=%x\n",newsbPtr);

 if (newsbPtr) {
    newsbPtr->nextPtr = 0;
    newsbPtr->rsv2 = 0;
    newsbPtr->bufferPtr = bufferPtr;
    newsbPtr->bufferSize = length;
    newsbPtr->bufferCurrPos = 0;
    newsbPtr->bufferDonePos = 0;

    sbPushOnTail(newsbPtr, &streamPtr->sbaProc);
 }
 else {
    rc = 8;
 }

 return rc;
}

// ---------------------------------------------------
// in: streamType = eg, STREAM_WAVE_CAPTURE (==AUDIOHW_WAVE_CAPTURE)(org ULONG)
//     streamPtr -> stream structure
//out: always 0 for now
//nts:
//
// actually, STREAM constructor is called as part of WAVESTREAM constructor (STREAM
// constructor is done first, though) so this (streamInit()) will be called by
// wavestreamInit()...

USHORT streamInit(USHORT streamType, STREAM *streamPtr) {

 streamPushOnTail(streamPtr);
 streamPtr->streamType = streamType;

 // already have verified that streamType is a supported type in IOCtl audio init
 // so ahwPtr will be valid (so don't need to check here)

 streamPtr->streamH = 0;        // ensure won't match yet on FindStream()
 streamPtr->SFN = 0;            // ditto (since these are not yet operational streams)
 streamPtr->counterIncFlag = 1;
 streamPtr->currentTime = 0;    // this is updated when DDCMD_STATUS gotten
 streamPtr->streamState = STREAM_STOPPED;

 return 0;
}

// ---------------------------------------------------
// in: streamPtr -> stream structure
//out: always 0 for now
//nts: stream destructor (does not free(streamPtr) though...that's done in wavestreamDeinit)

USHORT streamDeinit(STREAM *streamPtr) {

 USHORT rc = 0;
 STREAM_BUFFER *tsbPtr;

 if (streamPtr->streamState == STREAM_STREAMING) {

    // this has been replaced...
    // streamPtr->wsParentPtr->waPtr->ahwPtr->xStop(); // yipes, talk about an indirect function call
    // by this:

    if (streamPtr->wsParentPtr->waPtr->devType == AUDIOHW_WAVE_PLAY) {
       rc = waveplayStop(streamPtr->wsParentPtr);
    }
    else {
       rc = waverecStop(streamPtr->wsParentPtr);
    }
 }

 // destroy all stream buffers and events still associated with this stream

 while(sbNotEmpty(&streamPtr->sbaProc)) {
    tsbPtr = sbHead(&streamPtr->sbaProc);
    sbDestroyElement(tsbPtr, &streamPtr->sbaProc);
 }

 while(sbNotEmpty(&streamPtr->sbaDone)) {
    tsbPtr = sbHead(&streamPtr->sbaDone);
    sbDestroyElement(tsbPtr, &streamPtr->sbaDone);
 }

 // can do this event processing code now since won't do anything (always empty for now)

 while(sbNotEmpty(&streamPtr->sbaEvent)) {
    tsbPtr = sbHead(&streamPtr->sbaEvent);
    sbDestroyElement(tsbPtr, &streamPtr->sbaEvent);
 }

 streamPopElement(streamPtr);   // remove this stream from list

 return 0;
}

// ---------------------------------------------------
// in: streamType (was ULONG)
//out: streamPtr -> active stream
//nts: finds first active stream of matching type

STREAM *streamFindActive(USHORT streamType) {

 STREAM *streamPtr = streamList.headPtr;

 while (streamPtr) {
    if (streamPtr->streamType == streamType && streamPtr->streamState == STREAM_STREAMING) break;
    streamPtr = streamPtr->nextPtr;
 }

 return streamPtr;
}

// ---------------------------------------------------
// in: SFN (was ULONG)
//out: streamPtr -> stream with this SFN
//nts: map SFN to stream object

STREAM *streamFindStreamSFN(USHORT SFN) {

 STREAM *streamPtr = streamList.headPtr;

 while (streamPtr) {
    if (streamPtr->SFN == SFN) break;
    streamPtr = streamPtr->nextPtr;
 }

 return streamPtr;
}

// ---------------------------------------------------
// in: streamH
//out: streamPtr -> stream with this handle
//nts: map stream handle to stream object

STREAM *streamFindStreamHandle(HSTREAM streamH) {

 STREAM *streamPtr = streamList.headPtr;

 while (streamPtr) {
    if (streamPtr->streamH == streamH) break;
    streamPtr = streamPtr->nextPtr;
 }

 return streamPtr;
}

// -----------------------------------------------------------------------------
// Queue support for STREAM_BUFFER objects (STREAM objects follows this, below)
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// in: streamBufferAnchorPtr -> queue anchor to either proc, done, or event queues
//out: stream_buffer pointer -> head
//nts: sort of like PopHead() but doesn't remove head
//
// eg,
// STREAM_BUFFER *DoneHeadPtr = sbHead(&streamPtr->sbaDone);

STREAM_BUFFER *sbHead(STREAM_BUFFER_ANCHOR *sbaPtr) {

 STREAM_BUFFER *tempPtr = sbaPtr->headPtr;

 return tempPtr;
}

// -------------------------------------------------------------------
// in: streamBufferAnchorPtr -> queue anchor to either proc, done, or event queues
//out: stream_buffer pointer -> tail
//nts: sort of like PopTail() but doesn't remove tail
//
// eg,
// STREAM_BUFFER *DoneHeadPtr = sbTail(&streamPtr->sbaDone);

STREAM_BUFFER *sbTail(STREAM_BUFFER_ANCHOR *sbaPtr) {

 STREAM_BUFFER *tempPtr = sbaPtr->tailPtr;

 return tempPtr;
}

// -----------------------------------------------------------------------------
// in: stream buffer ptr -> stream buffer item to put on head of queue
//     streamBufferAnchorPtr -> queue anchor to either proc, done, or event queues
//out: n/a
//nts:
//
// eg,
// sbPushOnHead(sbPtr, &streamPtr->sbaDone);

VOID sbPushOnHead(STREAM_BUFFER *sbPtr, STREAM_BUFFER_ANCHOR *sbaPtr) {

 if (sbaPtr->headPtr == 0) {            // empty list so just put it on
    sbPtr->nextPtr = 0;
    sbaPtr->headPtr = sbPtr;
    sbaPtr->tailPtr = sbPtr;
 }
 else {
    sbPtr->nextPtr = sbaPtr->headPtr;   // set buffer's nextPtr to current head
    sbaPtr->headPtr = sbPtr;            // and make this buffer the new head
 }

 return;
}

// -----------------------------------------------------------------------------
// in: stream buffer ptr -> stream buffer item to put on tail of queue
//     streamBufferAnchorPtr -> queue anchor to either proc, done, or event queues
//out: n/a
//nts:
//
// eg,
// sbPushOnTail(sbPtr, &streamPtr->sbaDone);

VOID sbPushOnTail(STREAM_BUFFER *sbPtr, STREAM_BUFFER_ANCHOR *sbaPtr) {

 sbPtr->nextPtr = 0;
 if (sbaPtr->headPtr == 0) {            // empty list so just put it on
    sbaPtr->headPtr = sbPtr;
    sbaPtr->tailPtr = sbPtr;
 }
 else {
    sbaPtr->tailPtr->nextPtr = sbPtr;   // set current tail's nextPtr to new tail
    sbaPtr->tailPtr = sbPtr;            // and make this buffer the new tail
 }

 return;
}

// -----------------------------------------------------------------------------
// in: streamBufferAnchorPtr -> queue anchor to either proc, done, or event queues
//out: stream_buffer pointer -> what was at head of the queue
//nts:
//
// eg,
// STREAM_BUFFER *DoneHeadPtr = sbPopHead(&streamPtr->sbaDone);

STREAM_BUFFER *sbPopHead(STREAM_BUFFER_ANCHOR *sbaPtr) {

 STREAM_BUFFER *tempPtr = sbaPtr->headPtr;

 if (tempPtr) {
    sbaPtr->headPtr = tempPtr->nextPtr;
    if (sbaPtr->headPtr == 0) sbaPtr->tailPtr = 0;
    tempPtr->nextPtr = 0;
 }

 return tempPtr;
}

// -----------------------------------------------------------------------------
// in: streamBufferAnchorPtr -> queue anchor to either proc, done, or event queues
//out: stream_buffer pointer -> what was at tail of the queue
//nts:
//
// eg,
// STREAM_BUFFER *DoneTailPtr = sbPopTail(&streamPtr->sbaDone);

STREAM_BUFFER *sbPopTail(STREAM_BUFFER_ANCHOR *sbaPtr) {

 STREAM_BUFFER *tempPtr = sbaPtr->tailPtr;
 STREAM_BUFFER *temp2Ptr = sbaPtr->headPtr;

 if (tempPtr == temp2Ptr) {

    // only one item in list, or it's empty

    sbaPtr->headPtr = 0;
    sbaPtr->tailPtr = 0;
    if (tempPtr) tempPtr->nextPtr = 0;  // set the old tail's nextPtr to 0
 }
 else {
    if (tempPtr) {
       while (temp2Ptr->nextPtr != tempPtr) {
          temp2Ptr = temp2Ptr->nextPtr; // scan down list to just before tail
       }
       sbaPtr->tailPtr = temp2Ptr;      // set the new tail to be that one

       if (sbaPtr->tailPtr == 0) {      // hm, can this happen (seem like has to only
          sbaPtr->headPtr = 0;          // have one item for it to, and that's covered above)
       }
       else {
          sbaPtr->tailPtr->nextPtr = 0; // mark new tail's nextPtr as 0 (since it's the tail!)
       }
       tempPtr->nextPtr = 0;            // set the old tail's nextPtr to 0
    }
 }

 return tempPtr;
}

// -----------------------------------------------------------------------------
// in: sbPtr -> stream buffer to destroy
//     streamBufferAnchorPtr -> queue anchor to either proc, done, or event queues
//out: 1 if destroyed it, else not there
//nts: frees memory allocated at sbPtr
//
// eg,
// destroyedItFlag = sbDestroyElement(sbPtr, &streamPtr->sbaDone);

USHORT sbDestroyElement(STREAM_BUFFER *sbPtr, STREAM_BUFFER_ANCHOR *sbaPtr) {

 USHORT rc = 0;

 if (sbPopElement(sbPtr,sbaPtr)) {
    free(sbPtr);

// !!!
//ddprintf("@sbDestroyElement:free:%x\n",sbPtr);

    rc = 1;
 }

 return rc;
}

// -----------------------------------------------------------------------------
// in: match_sbPtr -> stream buffer to remove for queue (based on address)
//     streamBufferAnchorPtr -> queue anchor to either proc, done, or event queues
//out: returns match_sbPtr (same as entry) if found/removed, else 0 if not there
//nts: see below
//
// eg,
// sbPtr = sbPopElement(sbPtr, &streamPtr->sbaDone);

STREAM_BUFFER *sbPopElement(STREAM_BUFFER *match_sbPtr, STREAM_BUFFER_ANCHOR *sbaPtr) {

 STREAM_BUFFER *tempPtr = 0;

 if (sbaPtr->headPtr == 0) {            // empty queue
    return 0;
 }

 if (match_sbPtr == sbaPtr->headPtr) {  // if matches head, pop head
    tempPtr = sbPopHead(sbaPtr);
    return tempPtr;
 }

 if (match_sbPtr == sbaPtr->tailPtr) {  // if matches tail, pop tail
    tempPtr = sbPopTail(sbaPtr);
    return tempPtr;
 }

 // this next section scans items, check the nextPtrs of each -- when a nextPtr points
 // to the match_sbPtr it's known that the item is there, so set that nextPtr to point
 // to the item's nextPtr rather than the item itself (item is match_sbPtr in this case)
 // effectively removing the item from the list

 tempPtr = sbaPtr->headPtr;
 while (tempPtr->nextPtr != match_sbPtr && tempPtr->nextPtr != 0) {
    tempPtr = tempPtr->nextPtr;         // scan elements until find it in someone's nextPtr...
 }
 if (tempPtr == 0) return 0;            // not found at all

 tempPtr->nextPtr = match_sbPtr->nextPtr; // now set links so the item is removed from the list

 return match_sbPtr;
}

// -----------------------------------------------------------------------------
// in: streamBufferAnchorPtr -> queue anchor to either proc, done, or event queues
//out: 0 if the list is empty, otherwise 1
//nts: original returned a ULONG for some reason
//
// eg,
// notEmpty = sbNotEmpty(&streamPtr->sbaDone);

USHORT sbNotEmpty(STREAM_BUFFER_ANCHOR *sbaPtr) {

 USHORT rc = 0;

 if (sbaPtr->headPtr) rc = 1;

 return rc;
}

// -------------------------------------
// to init queue set headPtr/tailPtr = 0
// which is accomplished by simply MEMSET()'ing the allocation
// ie, the contructor (doesn't seem to be a destructor for the QUEUE class)

// -----------------------------------------------------------------------------
// Queue support for STREAM objects
// -----------------------------------------------------------------------------
// note: unlike STREAM_BUFFER queue support, don't need to pass anchor pointer
//       since it's known to be streamList

// -----------------------------------------------------------------------------
// in: n/a
//out: stream pointer -> head
//nts: sort of like PopHead() but doesn't remove head
//
// eg,
// STREAM *HeadPtr = streamHead();

STREAM *streamHead(VOID) {

 STREAM *tempPtr = streamList.headPtr;

 return tempPtr;
}

// -------------------------------------------------------------------
// in: n/a
//out: stream pointer -> tail
//nts: sort of like PopTail() but doesn't remove tail
//
// eg,
// STREAM *TailPtr = streamTail();

STREAM *streamTail(VOID) {

 STREAM *tempPtr = streamList.tailPtr;

 return tempPtr;
}

// -----------------------------------------------------------------------------
// in: stream ptr -> stream item to put on head of queue
//out: n/a
//nts:
//
// eg,
// streamPushOnHead(sPtr);

VOID streamPushOnHead(STREAM *sPtr) {

 if (streamList.headPtr == 0) {         // empty list so just put it on
    sPtr->nextPtr = 0;
    streamList.headPtr = sPtr;
    streamList.tailPtr = sPtr;
 }
 else {
    sPtr->nextPtr = streamList.headPtr; // set stream's nextPtr to current head
    streamList.headPtr = sPtr;          // and make this buffer the new head
 }

 return;
}

// -----------------------------------------------------------------------------
// in: stream ptr -> stream item to put on tail of queue
//out: n/a
//nts:
//
// eg,
// streamPushOnTail(sPtr);

VOID streamPushOnTail(STREAM *sPtr) {

 sPtr->nextPtr = 0;
 if (streamList.headPtr == 0) {         // empty list so just put it on
    streamList.headPtr = sPtr;
    streamList.tailPtr = sPtr;
 }
 else {
    streamList.tailPtr->nextPtr = sPtr; // set current tail's nextPtr to new tail
    streamList.tailPtr = sPtr;          // and make this buffer the new tail
 }

 return;
}

// -----------------------------------------------------------------------------
// in: n/a
//out: stream pointer -> what was at head of the queue
//nts:
//
// eg,
// STREAM *HeadPtr = streamPopHead();

STREAM *streamPopHead(VOID) {

 STREAM *tempPtr = streamList.headPtr;

 if (tempPtr) {
    streamList.headPtr = tempPtr->nextPtr;
    if (streamList.headPtr == 0) streamList.tailPtr = 0;
    tempPtr->nextPtr = 0;
 }

 return tempPtr;
}

// -----------------------------------------------------------------------------
// in: n/a
//out: stream pointer -> what was at tail of the queue
//nts:
//
// eg,
// STREAM *TailPtr = streamPopTail();

STREAM *streamPopTail(VOID) {

 STREAM *tempPtr = streamList.tailPtr;
 STREAM *temp2Ptr = streamList.headPtr;

 if (tempPtr == temp2Ptr) {

    // only one item in list, or it's empty

    streamList.headPtr = 0;
    streamList.tailPtr = 0;
    if (tempPtr) tempPtr->nextPtr = 0;  // set the old tail's nextPtr to 0
 }
 else {
    if (tempPtr) {
       while (temp2Ptr->nextPtr != tempPtr) {
          temp2Ptr = temp2Ptr->nextPtr; // scan down list to just before tail
       }
       streamList.tailPtr = temp2Ptr;   // set the new tail to be that one

       if (streamList.tailPtr == 0) {   // hm, can this happen (seem like has to only
          streamList.headPtr = 0;       // have one item for it to, and that's covered above)
       }
       else {
          streamList.tailPtr->nextPtr = 0; // mark new tail's nextPtr as 0 (since it's the tail!)
       }
       tempPtr->nextPtr = 0;            // set the old tail's nextPtr to 0
    }
 }

 return tempPtr;
}

// -----------------------------------------------------------------------------
// in: sPtr -> stream to destroy
//out: 1 if destroyed it, else not there
//nts: frees memory allocated at sPtr
//
// eg,
// destroyedItFlag = streamDestroyElement(sPtr);

USHORT streamDestroyElement(STREAM *sPtr) {

 USHORT rc = 0;

 if (streamPopElement(sPtr)) {
    free(sPtr);

// !!!
//ddprintf("@streamDestroyElement:free:%x\n",sPtr);

    rc = 1;
 }

 return rc;
}

// -----------------------------------------------------------------------------
// in: match_sPtr -> stream to remove for queue (based on address)
//out: returns match_sPtr (same as entry) if found/removed, else 0 if not there
//nts: see below
//
// eg,
// sPtr = streamPopElement(sPtr);

STREAM *streamPopElement(STREAM *match_sPtr) {

 STREAM *tempPtr = 0;

 if (streamList.headPtr == 0) {         // empty queue
    return 0;
 }

 if (match_sPtr == streamList.headPtr) { // if matches head, pop head
    tempPtr = streamPopHead();
    return tempPtr;
 }

 if (match_sPtr == streamList.tailPtr) { // if matches tail, pop tail
    tempPtr = streamPopTail();
    return tempPtr;
 }

 // this next section scans items, check the nextPtrs of each -- when a nextPtr points
 // to the match_sPtr it's known that the item is there, so set that nextPtr to point
 // to the item's nextPtr rather than the item itself (item is match_sPtr in this case)
 // effectively removing the item from the list

 tempPtr = streamList.headPtr;
 while (tempPtr->nextPtr != match_sPtr && tempPtr->nextPtr != 0) {
    tempPtr = tempPtr->nextPtr;         // scan elements until find it in someone's nextPtr...
 }
 if (tempPtr == 0) return 0;            // not found at all

 tempPtr->nextPtr = match_sPtr->nextPtr; // now set links so the item is removed from the list

 return match_sPtr;
}

// -----------------------------------------------------------------------------
// in: n/a
//out: 0 if the list is empty, otherwise 1
//nts: original returned a ULONG for some reason
//
// eg,
// notEmpty = streamNotEmpty();

USHORT streamNotEmpty(VOID) {

 USHORT rc = 0;

 if (streamList.headPtr) rc = 1;

 return rc;
}

// ---------------------------------
// in: streamPtr -> stream structure
//out:
//nts:

VOID streamProcessEvents(STREAM *streamPtr) {

 return;
 streamPtr;
}

// --------------------------------------
// in: ddcmdPtr -> DDCMDCONTROL structure (far ptr)
//     streamPtr -> stream structure
//out:
//nts:

VOID streamEnableEvent(DDCMDCONTROL __far *ddcmdPtr, STREAM *streamPtr) {

 return;
 ddcmdPtr;
 streamPtr;
}

// --------------------------------------
// in: ddcmdPtr -> DDCMDCONTROL structure (far ptr)
//     streamPtr -> stream structure
//out:
//nts:

VOID streamDisableEvent(DDCMDCONTROL __far *ddcmdPtr, STREAM *streamPtr) {

 return;
 ddcmdPtr;
 streamPtr;
}

// --------------------------------------
// in: streamPtr -> stream structure
//out:
//nts:

VOID streamSetNextEvent(STREAM *streamPtr) {

 return;
 streamPtr;
}

#if 0

// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------

// the following event-support routines are not yet done
//  void STREAM::ProcessEvents(void)
//  ULONG STREAM::EnableEvent(PDDCMDCONTROL pControl)
//  ULONG STREAM::DisableEvent(PDDCMDCONTROL pControl)
//  void STREAM::SetNextEvent(void)

class EVENT;

// ProcessEvents
// called by the Process at interrupt time to see if there are
// any events that have timed out
//
void STREAM::ProcessEvents(void)
{
   if (qhEvent.IsElements()) {
      PEVENT pnextevent = (PEVENT)qhEvent.Head();
      ULONG time = GetCurrentTime();
      ULONG eventtime = pnextevent->GetEventTime();
      if (eventtime <= time)
         pnextevent->Report(time);
   }

}
ULONG STREAM::EnableEvent(PDDCMDCONTROL pControl)
{

   // see if the event already exists on the event queue
   // call FindEvent if we get back an address (event exists)
   // call the UpdateEvent member function and get the event info updated.
   // if Findevent returns NULL (no event on queue) then call the construct
   // a new event and put it on the tail of the event queue. then call
   // SetNextEvent to update the next event to time out....

   PEVENT pevent = FindEvent(pControl->hEvent, &qhEvent);
   if (pevent)
      pevent->UpdateEvent(this,pControl->hEvent,(PCONTROL_PARM)pControl->pParm);
   else {
      pevent= new EVENT(this,pControl->hEvent,(PCONTROL_PARM)pControl->pParm);
   }
   if (!pevent)
      return ERROR_TOO_MANY_EVENTS;

   SetNextEvent();
   return NO_ERROR;
}

ULONG STREAM::DisableEvent(PDDCMDCONTROL pControl)
{
   pTrace->vLog(DDCMD_DisableEvent,pControl->hEvent);
   PEVENT pevent = FindEvent(pControl->hEvent, &qhEvent);
   if (!pevent)
      return ERROR_INVALID_EVENT;

    // destroying an event may change things that get referenced in the ISR
    // so we really need to cli/sti around the call to DestroyElement
   _cli_();
   qhEvent.DestroyElement((PQUEUEELEMENT)pevent);
   if (qhEvent.Head() != qhEvent.Tail())
      SetNextEvent();
   _sti_();
   return NO_ERROR;
}

/**@internal SetNextEvent
 * @param    None
 * @return   None
 * @notes
 * the function walks the event list and finds the next event to timeout.
 * the event is moved to the head of the event queue.
 *
 */
void STREAM::SetNextEvent(void)
{

   // if there are no events or only one event on the
   // queue just return
   if ((qhEvent.Head()) == (qhEvent.Tail()))
       return;

   PQUEUEELEMENT pele1 = qhEvent.Head();
   PQUEUEELEMENT pele2 = NULL;
   ULONG ulTimeToBeat = -1;     // -1 equals 0xFFFFFFFF the maximum time

   while (pele1) {
      if (((PEVENT)pele1)->GetEventTime() <= ulTimeToBeat) {
         pele2 = pele1;
         ulTimeToBeat = ((PEVENT)pele1)->GetEventTime();
      }
      pele1 = pele1->pNext;
   }
   // pele2 should now contain the address of the next
   // event to time out.. if it is not already on
   // the head of the Event queue then put it there
   if (pele2 != qhEvent.Head()) {
      _cli_();
      qhEvent.PopElement(pele2);
      qhEvent.PushOnHead(pele2);
      _sti_();
   }
}

#endif