text:
package tunnel

import (
	"context"
	"testing"

	"reflect"

	core "k8s.io/api/core/v1"
	meta "k8s.io/apimachinery/pkg/apis/meta/v1"
	typed_core "k8s.io/client-go/kubernetes/typed/core/v1"
	fake "k8s.io/client-go/kubernetes/typed/core/v1/fake"
	"k8s.io/client-go/rest"
)

type stubCoreClient struct {
	fake.FakeCoreV1
	servicesList *core.ServiceList
	restClient   *rest.RESTClient
}

func (c *stubCoreClient) Services(namespace string) typed_core.ServiceInterface {
	return &stubServices{
		fake.FakeServices{Fake: &c.FakeCoreV1},
		c.servicesList,
	}
}

func (c *stubCoreClient) RESTClient() rest.Interface {
	return c.restClient
}

type stubServices struct {
	fake.FakeServices
	servicesList *core.ServiceList
}

func (s *stubServices) List(ctx context.Context, opts meta.ListOptions) (*core.ServiceList, error) {
	return s.servicesList, nil
}

func newStubCoreClient(servicesList *core.ServiceList) *stubCoreClient {
	if servicesList == nil {
		servicesList = &core.ServiceList{
			Items: []core.Service{}}
	}
	return &stubCoreClient{
		servicesList: servicesList,
		restClient:   nil,
	}
}

type countingRequestSender struct {
	requests int
}

func (s *countingRequestSender) send(request *rest.Request) (result []byte, err error) {
	s.requests++
	return nil, nil
}

type recordingPatchConverter struct {
	patches []*Patch
}

func (r *recordingPatchConverter) convert(restClient rest.Interface, patch *Patch) *rest.Request {
	r.patches = append(r.patches, patch)
	return nil
}

func TestEmptyListOfServicesDoesNothing(t *testing.T) {
	client := newStubCoreClient(&core.ServiceList{
		Items: []core.Service{}})

	patcher := NewLoadBalancerEmulator(client)

	serviceNames, err := patcher.PatchServices()

	if len(serviceNames) > 0 || err != nil {
		t.Errorf("Expected: [], nil\n Got: %v, %s", serviceNames, err)
	}

}

func TestServicesWithNoLoadbalancerType(t *testing.T) {
	client := newStubCoreClient(&core.ServiceList{
		Items: []core.Service{
			{
				Spec: core.ServiceSpec{
					Type: "ClusterIP",
				},
			},
			{
				Spec: core.ServiceSpec{
					Type: "NodeIP",
				},
			},
		},
	})

	patcher := NewLoadBalancerEmulator(client)

	serviceNames, err := patcher.PatchServices()

	if len(serviceNames) > 0 || err != nil {
		t.Errorf("Expected: [], nil\n Got: %v, %s", serviceNames, err)
	}

}

func TestServicesWithLoadbalancerType(t *testing.T) {
	client := newStubCoreClient(&core.ServiceList{
		Items: []core.Service{
			{
				ObjectMeta: meta.ObjectMeta{
					Name:      "svc1-up-to-date",
					Namespace: "ns1",
				},
				Spec: core.ServiceSpec{
					Type:      "LoadBalancer",
					ClusterIP: "10.96.0.3",
				},
				Status: core.ServiceStatus{
					LoadBalancer: core.LoadBalancerStatus{
						Ingress: []core.LoadBalancerIngress{
							{
								IP: "10.96.0.3",
							},
						},
					},
				},
			},
			{
				ObjectMeta: meta.ObjectMeta{
					Name:      "svc2-out-of-date",
					Namespace: "ns2",
				},
				Spec: core.ServiceSpec{
					Type:      "LoadBalancer",
					ClusterIP: "10.96.0.4",
				},
				Status: core.ServiceStatus{
					LoadBalancer: core.LoadBalancerStatus{
						Ingress: []core.LoadBalancerIngress{
							{
								IP: "10.96.0.5",
							},
						},
					},
				},
			},
			{
				ObjectMeta: meta.ObjectMeta{
					Name:      "svc3-empty-ingress",
					Namespace: "ns3",
				},
				Spec: core.ServiceSpec{
					Type:      "LoadBalancer",
					ClusterIP: "10.96.0.2",
				},
				Status: core.ServiceStatus{
					LoadBalancer: core.LoadBalancerStatus{
						Ingress: []core.LoadBalancerIngress{},
					},
				},
			},
			{
				ObjectMeta: meta.ObjectMeta{
					Name: "svc4-not-lb",
				},
				Spec: core.ServiceSpec{
					Type: "NodeIP",
				},
			},
		},
	})

	expectedPatches := []*Patch{
		{
			Type:         "application/json-patch+json",
			NameSpace:    "ns2",
			NameSpaceSet: true,
			Resource:     "services",
			Subresource:  "status",
			ResourceName: "svc2-out-of-date",
			BodyContent:  `[{"op": "add", "path": "/status/loadBalancer/ingress", "value":  [ { "ip": "10.96.0.4" } ] }]`,
		},
		{
			Type:         "application/json-patch+json",
			NameSpace:    "ns3",
			NameSpaceSet: true,
			Resource:     "services",
			Subresource:  "status",
			ResourceName: "svc3-empty-ingress",
			BodyContent:  `[{"op": "add", "path": "/status/loadBalancer/ingress", "value":  [ { "ip": "10.96.0.2" } ] }]`,
		},
	}

	requestSender := &countingRequestSender{}
	patchConverter := &recordingPatchConverter{}

	patcher := NewLoadBalancerEmulator(client)
	patcher.requestSender = requestSender
	patcher.patchConverter = patchConverter

	serviceNames, err := patcher.PatchServices()

	expectedServices := []string{"svc1-up-to-date", "svc2-out-of-date", "svc3-empty-ingress"}

	if !reflect.DeepEqual(serviceNames, expectedServices) || err != nil {
		t.Errorf("error.\nExpected: %s, <nil>\nGot: %v, %v", expectedServices, serviceNames, err)
	}

	if !reflect.DeepEqual(patchConverter.patches, expectedPatches) {
		t.Errorf("error in patches.\nExpected: %v, <nil>\nGot: %v", expectedPatches, patchConverter.patches)
	}

	if requestSender.requests != 2 {
		t.Errorf("error in number of requests sent.\nExpected: %v, <nil>\nGot: %v", 2, requestSender.requests)
	}

}

func TestCleanupPatchedIPs(t *testing.T) {
	expectedPatches := []*Patch{
		{
			Type:         "application/json-patch+json",
			NameSpace:    "ns1",
			NameSpaceSet: true,
			Resource:     "services",
			Subresource:  "status",
			ResourceName: "svc1-up-to-date",
			BodyContent:  `[{"op": "remove", "path": "/status/loadBalancer/ingress" }]`,
		},

		{
			Type:         "application/json-patch+json",
			NameSpace:    "ns2",
			NameSpaceSet: true,
			Resource:     "services",
			Subresource:  "status",
			ResourceName: "svc2-out-of-date",
			BodyContent:  `[{"op": "remove", "path": "/status/loadBalancer/ingress" }]`,
		},
	}

	client := newStubCoreClient(&core.ServiceList{
		Items: []core.Service{
			{
				ObjectMeta: meta.ObjectMeta{
					Name:      "svc1-up-to-date",
					Namespace: "ns1",
				},
				Spec: core.ServiceSpec{
					Type:      "LoadBalancer",
					ClusterIP: "10.96.0.3",
				},
				Status: core.ServiceStatus{
					LoadBalancer: core.LoadBalancerStatus{
						Ingress: []core.LoadBalancerIngress{
							{
								IP: "10.96.0.3",
							},
						},
					},
				},
			},
			{
				ObjectMeta: meta.ObjectMeta{
					Name:      "svc2-out-of-date",
					Namespace: "ns2",
				},
				Spec: core.ServiceSpec{
					Type:      "LoadBalancer",
					ClusterIP: "10.96.0.4",
				},
				Status: core.ServiceStatus{
					LoadBalancer: core.LoadBalancerStatus{
						Ingress: []core.LoadBalancerIngress{
							{
								IP: "10.96.0.5",
							},
						},
					},
				},
			},
			{
				ObjectMeta: meta.ObjectMeta{
					Name:      "svc3-empty-ingress",
					Namespace: "ns3",
				},
				Spec: core.ServiceSpec{
					Type:      "LoadBalancer",
					ClusterIP: "10.96.0.2",
				},
				Status: core.ServiceStatus{
					LoadBalancer: core.LoadBalancerStatus{
						Ingress: []core.LoadBalancerIngress{},
					},
				},
			},
			{
				ObjectMeta: meta.ObjectMeta{
					Name: "svc4-not-lb",
				},
				Spec: core.ServiceSpec{
					Type: "NodeIP",
				},
			},
		},
	})

	requestSender := &countingRequestSender{}
	patchConverter := &recordingPatchConverter{}

	patcher := NewLoadBalancerEmulator(client)
	patcher.requestSender = requestSender
	patcher.patchConverter = patchConverter

	serviceNames, err := patcher.Cleanup()
	expectedServices := []string{"svc1-up-to-date", "svc2-out-of-date", "svc3-empty-ingress"}

	if !reflect.DeepEqual(serviceNames, expectedServices) || err != nil {
		t.Errorf("error.\nExpected: %s, <nil>\nGot: %v, %v", expectedServices, serviceNames, err)
	}
	if !reflect.DeepEqual(patchConverter.patches, expectedPatches) {
		t.Errorf("error in patches.\nExpected: %v, <nil>\nGot: %v", expectedPatches, patchConverter.patches)
	}
	if requestSender.requests != 2 {
		t.Errorf("error in number of requests sent.\nExpected: %v, <nil>\nGot: %v", 2, requestSender.requests)
	}
}


text:
from django.conf.urls import patterns, url

from . import views

urlpatterns = patterns(
    '',
    url(r'^openid/$', views.begin, name='openid_begin'),
    url(r'^openid/complete/$', views.callback, name='openid_callback'),
)

redpajama_set_name: RedPajamaGithub


text:
require('./dist/paginate-anything-tpls.js');
module.exports = 'bgf.paginateAnything';


text:
from modules.data.routes import TradeRoutes
from modules.data.pairs import TradePairs
from utilities.helper import Util

class DataManager:
    def __init__(self):
        self.util = Util()

    def get_cx_names(self):
        """ generate exchange names """
        self.pairs = TradePairs()

        self.cx_names = {"exchanges": self.pairs.get_exchange_names()}
        self.util.write_json_to_file(self.cx_names, self.util.FILE_NAMES)

        print("#### INFO: Generated exchange names")
        return

    def create_cx_pairs(self):
        """ generate exchange trading pairs """
        self.pairs = TradePairs()

        self.cx_pairs = self.pairs.get_trade_pairs()
        self.util.write_json_to_file(self.cx_pairs, self.util.FILE_PAIRS)

        print("#### INFO: Generated exchange trading pairs")
        return

    def create_cx_routes(self):
        """ generate arbitrage routes between exchanges """
        self.routes = TradeRoutes()

        data = self.routes.get_arbitrage_routes()
        self.util.write_json_to_file(data, self.util.FILE_ROUTES)

        print("#### INFO: Generated arbitrage routes")
        return

    def reset_json_data(self):
        """ reset JSON data files """
        file_paths = [self.util.FILE_PAIRS, self.util.FILE_ROUTES, self.util.FILE_NAMES, self.util.FILE_PROFIT]

        [self.util.write_json_to_file({}, p) for p in file_paths]

        print("#### INFO: JSON data files reset")
        return


text:
namespace cc {

class ResourceProvider;

// This is the base class for code shared between the GL and software
// renderer implementations.  "Direct" refers to the fact that it does not
// delegate rendering to another compositor.
class CC_EXPORT DirectRenderer : public Renderer {
 public:
  virtual ~DirectRenderer();

  ResourceProvider* resource_provider() const { return resource_provider_; }

  virtual bool CanReadPixels() const OVERRIDE;
  virtual void DecideRenderPassAllocationsForFrame(
      const RenderPassList& render_passes_in_draw_order) OVERRIDE;
  virtual bool HasAllocatedResourcesForTesting(RenderPass::Id id) const
      OVERRIDE;
  virtual void DrawFrame(RenderPassList* render_passes_in_draw_order,
                         ContextProvider* offscreen_context_provider,
                         float device_scale_factor,
                         gfx::Rect device_viewport_rect,
                         gfx::Rect device_clip_rect,
                         bool allow_partial_swap,
                         bool disable_picture_quad_image_filtering) OVERRIDE;

  struct CC_EXPORT DrawingFrame {
    DrawingFrame();
    ~DrawingFrame();

    const RenderPass* root_render_pass;
    const RenderPass* current_render_pass;
    const ScopedResource* current_texture;

    gfx::RectF root_damage_rect;
    gfx::Rect device_viewport_rect;
    gfx::Rect device_clip_rect;

    gfx::Transform projection_matrix;
    gfx::Transform window_matrix;

    ContextProvider* offscreen_context_provider;

    bool disable_picture_quad_image_filtering;
  };

  void SetEnlargePassTextureAmountForTesting(gfx::Vector2d amount);

 protected:
  DirectRenderer(RendererClient* client,
                 const LayerTreeSettings* settings,
                 OutputSurface* output_surface,
                 ResourceProvider* resource_provider);

  static gfx::RectF QuadVertexRect();
  static void QuadRectTransform(gfx::Transform* quad_rect_transform,
                                const gfx::Transform& quad_transform,
                                const gfx::RectF& quad_rect);
  void InitializeViewport(DrawingFrame* frame,
                          gfx::Rect draw_rect,
                          gfx::Rect viewport_rect,
                          gfx::Size surface_size);
  gfx::Rect MoveFromDrawToWindowSpace(const gfx::RectF& draw_rect) const;

  bool NeedDeviceClip(const DrawingFrame* frame) const;
  gfx::Rect DeviceClipRectInWindowSpace(const DrawingFrame* frame) const;
  static gfx::RectF ComputeScissorRectForRenderPass(const DrawingFrame* frame);
  void SetScissorStateForQuad(const DrawingFrame* frame, const DrawQuad& quad);
  void SetScissorStateForQuadWithRenderPassScissor(
      const DrawingFrame* frame,
      const DrawQuad& quad,
      const gfx::RectF& render_pass_scissor,
      bool* should_skip_quad);
  void SetScissorTestRectInDrawSpace(const DrawingFrame* frame,
                                     gfx::RectF draw_space_rect);

  static gfx::Size RenderPassTextureSize(const RenderPass* render_pass);

  void DrawRenderPass(DrawingFrame* frame,
                      const RenderPass* render_pass,
                      bool allow_partial_swap);
  bool UseRenderPass(DrawingFrame* frame, const RenderPass* render_pass);

  virtual void BindFramebufferToOutputSurface(DrawingFrame* frame) = 0;
  virtual bool BindFramebufferToTexture(DrawingFrame* frame,
                                        const ScopedResource* resource,
                                        gfx::Rect target_rect) = 0;
  virtual void SetDrawViewport(gfx::Rect window_space_viewport) = 0;
  virtual void SetScissorTestRect(gfx::Rect scissor_rect) = 0;
  virtual void DiscardPixels(bool has_external_stencil_test,
                             bool draw_rect_covers_full_surface) = 0;
  virtual void ClearFramebuffer(DrawingFrame* frame,
                                bool has_external_stencil_test) = 0;
  virtual void DoDrawQuad(DrawingFrame* frame, const DrawQuad* quad) = 0;
  virtual void BeginDrawingFrame(DrawingFrame* frame) = 0;
  virtual void FinishDrawingFrame(DrawingFrame* frame) = 0;
  virtual void FinishDrawingQuadList();
  virtual bool FlippedFramebuffer() const = 0;
  virtual void EnsureScissorTestEnabled() = 0;
  virtual void EnsureScissorTestDisabled() = 0;
  virtual void DiscardBackbuffer() {}
  virtual void EnsureBackbuffer() {}

  virtual void CopyCurrentRenderPassToBitmap(
      DrawingFrame* frame,
      scoped_ptr<CopyOutputRequest> request) = 0;

  base::ScopedPtrHashMap<RenderPass::Id, ScopedResource> render_pass_textures_;
  OutputSurface* output_surface_;
  ResourceProvider* resource_provider_;

  // For use in coordinate conversion, this stores the output rect, viewport
  // rect (= unflipped version of glViewport rect), and the size of target
  // framebuffer. During a draw, this stores the values for the current render
  // pass; in between draws, they retain the values for the root render pass of
  // the last draw.
  gfx::Rect current_draw_rect_;
  gfx::Rect current_viewport_rect_;
  gfx::Size current_surface_size_;

 private:
  gfx::Vector2d enlarge_pass_texture_amount_;

  DISALLOW_COPY_AND_ASSIGN(DirectRenderer);
};

}  // namespace cc

#endif  // CC_OUTPUT_DIRECT_RENDERER_H_


text:
import logging
import re
import warnings

from elastic_transport import __version__ as _elastic_transport_version

from ._utils import fixup_module_metadata
from ._version import __versionstr__

# Ensure that a compatible version of elastic-transport is installed.
_version_groups = tuple(int(x) for x in re.search(r"^(\d+)\.(\d+)\.(\d+)", _elastic_transport_version).groups())  # type: ignore
if _version_groups < (8, 0, 0) or _version_groups > (9, 0, 0):
    raise ImportError(
        "An incompatible version of elastic-transport is installed. Must be between "
        "v8.0.0 and v9.0.0. Install the correct version with the following command: "
        "$ python -m pip install 'elastic-transport>=8, <9'"
    )

_version_groups = re.search(r"^(\d+)\.(\d+)\.(\d+)", __versionstr__).groups()  # type: ignore
_major, _minor, _patch = (int(x) for x in _version_groups)
VERSION = __version__ = (_major, _minor, _patch)

logger = logging.getLogger("elasticsearch")
logger.addHandler(logging.NullHandler())

from ._async.client import AsyncElasticsearch as AsyncElasticsearch
from ._sync.client import Elasticsearch as Elasticsearch
from .exceptions import ElasticsearchDeprecationWarning  # noqa: F401
from .exceptions import (
    ApiError,
    AuthenticationException,
    AuthorizationException,
    BadRequestError,
    ConflictError,
    ConnectionError,
    ConnectionTimeout,
    ElasticsearchWarning,
    NotFoundError,
    RequestError,
    SerializationError,
    SSLError,
    TransportError,
    UnsupportedProductError,
)
from .serializer import JSONSerializer, JsonSerializer

# Only raise one warning per deprecation message so as not
# to spam up the user if the same action is done multiple times.
warnings.simplefilter("default", category=ElasticsearchWarning, append=True)

__all__ = [
    "ApiError",
    "AsyncElasticsearch",
    "BadRequestError",
    "Elasticsearch",
    "JsonSerializer",
    "SerializationError",
    "TransportError",
    "NotFoundError",
    "ConflictError",
    "RequestError",
    "ConnectionError",
    "SSLError",
    "ConnectionTimeout",
    "AuthenticationException",
    "AuthorizationException",
    "UnsupportedProductError",
    "ElasticsearchWarning",
]

fixup_module_metadata(__name__, globals())
del fixup_module_metadata


text:
using NuPattern.Presentation;

namespace NuPattern.Runtime.UI.Views
{
    /// <summary>
    /// The view for the <see cref="SolutionPicker"/>.
    /// </summary>
    partial class SolutionPickerView : CommonDialogWindow, IDialogWindow
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="SolutionPickerView"/> class.
        /// </summary>
        public SolutionPickerView()
            : base()
        {
            this.InitializeComponent();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using log4net.Config;
using OneApi.Client.Impl;
using OneApi.Config;
using OneApi.Model;

namespace OneApi.Examples.CustomerProfiles
{
	class GetCustomerProfileClients
	{
		public static void Execute()
		{
			// Configure in the 'app.config' which Logger levels are enabled(all levels are enabled in the example)
			// Check http://logging.apache.org/log4net/release/manual/configuration.html for more informations about the log4net configuration
			XmlConfigurator.Configure(new FileInfo("OneApiExamples.exe.config"));

			// Initialize Configuration object
			Configuration configuration = new Configuration(System.Configuration.ConfigurationManager.AppSettings.Get("Username"),
															System.Configuration.ConfigurationManager.AppSettings.Get("Password"));
			// Initialize SMSClient using the Configuration object
			SMSClient smsClient = new SMSClient(configuration);

			CustomerProfile[] customerProfiles = smsClient.CustomerProfileClient.GetClients();
			Console.WriteLine(string.Join("Customer Profile: ", customerProfiles.Select<CustomerProfile, string>(cProfile => cProfile != null ? cProfile.ToString() : "{}").ToArray()));
			Console.WriteLine();
		}
	}
}


text:
<?php

/**
 * Swift Mailer Cache Factory class
 * Please read the LICENSE file
 * @author Chris Corbyn <chris@w3style.co.uk>
 * @package Swift_Cache
 * @license GNU Lesser General Public License
 */

require_once dirname(__FILE__) . "/ClassLoader.php";

$GLOBALS["_SWIFT_CACHE_CLASS_"] = "Swift_Cache_Memory";

/**
 * Makes instances of the cache the user has defined
 * @package Swift_Cache
 * @author Chris Corbyn <chris@w3style.co.uk>
 */
class Swift_CacheFactory
{
  /**
   * Set the name of the class which is supposed to be used
   * This also includes the file
   * @param string The class name
   */
  function setClassName($name)
  {
    Swift_ClassLoader::load($name);
    $GLOBALS["_SWIFT_CACHE_CLASS_"] = $name;
  }
  /**
   * Return a new instance of the cache object
   * @return Swift_Cache
   */
  function &getCache()
  {
    $className = $GLOBALS["_SWIFT_CACHE_CLASS_"];
    Swift_ClassLoader::load($className);
    $instance =& new $className();
    return $instance;
  }
}


text:
<?php
/**
 * The template for displaying the footer.
 *
 * Contains the closing of the #content div and all content after
 *
 * @package Canard
 */
?>

	<?php get_sidebar( 'footer' ); ?>

	<?php if ( has_nav_menu( 'footer' ) ) : ?>

			<?php
				wp_nav_menu( array(
					'theme_location'  => 'footer',
					'depth'           => 1,
				) );
			?>

	<?php endif; ?>

	<?php if ( has_nav_menu( 'secondary' ) ) : ?>

			<?php
				wp_nav_menu( array(
					'theme_location'  => 'secondary',
					'depth'           => 1,
				) );
			?>

	<?php endif; ?>

	<?php if ( has_nav_menu( 'social' ) ) : ?>

			<?php
				wp_nav_menu( array(
					'theme_location'  => 'social',
					'link_before'     => '',
					'link_after'      => '',
					'depth'           => 1,
				) );
			?>

	<?php endif; ?>

			<a href="<?php echo esc_url( __( 'http://wordpress.org/', 'canard' ) ); ?>"><?php printf( __( 'Proudly powered by %s', 'canard' ), 'WordPress' ); ?>

			<?php printf( __( 'Theme: %1$s by %2$s.', 'canard' ), 'Canard', 'Automattic' ); ?>

<?php wp_footer(); ?>


text:
<?php

/**
 * Base static class for performing query and update operations on the 'biblio' table.
 *
 *
 *
 * @package propel.generator.fbapp.om
 */
abstract class BaseBiblioPeer
{

    /** the default database name for this class */
    const DATABASE_NAME = 'fbapp';

    /** the table name for this class */
    const TABLE_NAME = 'biblio';

    /** the related Propel class for this table */
    const OM_CLASS = 'Biblio';

    /** the related TableMap class for this table */
    const TM_CLASS = 'BiblioTableMap';

    /** The total number of columns. */
    const NUM_COLUMNS = 16;

    /** The number of lazy-loaded columns. */
    const NUM_LAZY_LOAD_COLUMNS = 0;

    /** The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS) */
    const NUM_HYDRATE_COLUMNS = 16;

    /** the column name for the autoctr field */
    const AUTOCTR = 'biblio.autoctr';

    /** the column name for the RefNo field */
    const REFNO = 'biblio.RefNo';

    /** the column name for the SpecCode field */
    const SPECCODE = 'biblio.SpecCode';

    /** the column name for the SynCode field */
    const SYNCODE = 'biblio.SynCode';

    /** the column name for the RefPage field */
    const REFPAGE = 'biblio.RefPage';

    /** the column name for the PageFirst field */
    const PAGEFIRST = 'biblio.PageFirst';

    /** the column name for the PageInSort field */
    const PAGEINSORT = 'biblio.PageInSort';

    /** the column name for the Locality field */
    const LOCALITY = 'biblio.Locality';

    /** the column name for the Distribution field */
    const DISTRIBUTION = 'biblio.Distribution';

    /** the column name for the Comment field */
    const COMMENT = 'biblio.Comment';

    /** the column name for the Quote field */
    const QUOTE = 'biblio.Quote';

    /** the column name for the Entered field */
    const ENTERED = 'biblio.Entered';

    /** the column name for the DateEntered field */
    const DATEENTERED = 'biblio.DateEntered';

    /** the column name for the Modified field */
    const MODIFIED = 'biblio.Modified';

    /** the column name for the DateModified field */
    const DATEMODIFIED = 'biblio.DateModified';

    /** the column name for the TS field */
    const TS = 'biblio.TS';

    /** The default string format for model objects of the related table **/
    const DEFAULT_STRING_FORMAT = 'YAML';

    /**
     * An identity map to hold any loaded instances of Biblio objects.
     * This must be public so that other peer classes can access this when hydrating from JOIN
     * queries.
     * @var        array Biblio[]
     */
    public static $instances = array();

    /**
     * holds an array of fieldnames
     *
     * first dimension keys are the type constants
     * e.g. BiblioPeer::$fieldNames[BiblioPeer::TYPE_PHPNAME][0] = 'Id'
     */
    protected static $fieldNames = array (
        BasePeer::TYPE_PHPNAME => array ('Autoctr', 'Refno', 'Speccode', 'Syncode', 'Refpage', 'Pagefirst', 'Pageinsort', 'Locality', 'Distribution', 'Comment', 'Quote', 'Entered', 'Dateentered', 'Modified', 'Datemodified', 'Ts', ),
        BasePeer::TYPE_STUDLYPHPNAME => array ('autoctr', 'refno', 'speccode', 'syncode', 'refpage', 'pagefirst', 'pageinsort', 'locality', 'distribution', 'comment', 'quote', 'entered', 'dateentered', 'modified', 'datemodified', 'ts', ),
        BasePeer::TYPE_COLNAME => array (BiblioPeer::AUTOCTR, BiblioPeer::REFNO, BiblioPeer::SPECCODE, BiblioPeer::SYNCODE, BiblioPeer::REFPAGE, BiblioPeer::PAGEFIRST, BiblioPeer::PAGEINSORT, BiblioPeer::LOCALITY, BiblioPeer::DISTRIBUTION, BiblioPeer::COMMENT, BiblioPeer::QUOTE, BiblioPeer::ENTERED, BiblioPeer::DATEENTERED, BiblioPeer::MODIFIED, BiblioPeer::DATEMODIFIED, BiblioPeer::TS, ),
        BasePeer::TYPE_RAW_COLNAME => array ('AUTOCTR', 'REFNO', 'SPECCODE', 'SYNCODE', 'REFPAGE', 'PAGEFIRST', 'PAGEINSORT', 'LOCALITY', 'DISTRIBUTION', 'COMMENT', 'QUOTE', 'ENTERED', 'DATEENTERED', 'MODIFIED', 'DATEMODIFIED', 'TS', ),
        BasePeer::TYPE_FIELDNAME => array ('autoctr', 'RefNo', 'SpecCode', 'SynCode', 'RefPage', 'PageFirst', 'PageInSort', 'Locality', 'Distribution', 'Comment', 'Quote', 'Entered', 'DateEntered', 'Modified', 'DateModified', 'TS', ),
        BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, )
    );

    /**
     * holds an array of keys for quick access to the fieldnames array
     *
     * first dimension keys are the type constants
     * e.g. BiblioPeer::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0
     */
    protected static $fieldKeys = array (
        BasePeer::TYPE_PHPNAME => array ('Autoctr' => 0, 'Refno' => 1, 'Speccode' => 2, 'Syncode' => 3, 'Refpage' => 4, 'Pagefirst' => 5, 'Pageinsort' => 6, 'Locality' => 7, 'Distribution' => 8, 'Comment' => 9, 'Quote' => 10, 'Entered' => 11, 'Dateentered' => 12, 'Modified' => 13, 'Datemodified' => 14, 'Ts' => 15, ),
        BasePeer::TYPE_STUDLYPHPNAME => array ('autoctr' => 0, 'refno' => 1, 'speccode' => 2, 'syncode' => 3, 'refpage' => 4, 'pagefirst' => 5, 'pageinsort' => 6, 'locality' => 7, 'distribution' => 8, 'comment' => 9, 'quote' => 10, 'entered' => 11, 'dateentered' => 12, 'modified' => 13, 'datemodified' => 14, 'ts' => 15, ),
        BasePeer::TYPE_COLNAME => array (BiblioPeer::AUTOCTR => 0, BiblioPeer::REFNO => 1, BiblioPeer::SPECCODE => 2, BiblioPeer::SYNCODE => 3, BiblioPeer::REFPAGE => 4, BiblioPeer::PAGEFIRST => 5, BiblioPeer::PAGEINSORT => 6, BiblioPeer::LOCALITY => 7, BiblioPeer::DISTRIBUTION => 8, BiblioPeer::COMMENT => 9, BiblioPeer::QUOTE => 10, BiblioPeer::ENTERED => 11, BiblioPeer::DATEENTERED => 12, BiblioPeer::MODIFIED => 13, BiblioPeer::DATEMODIFIED => 14, BiblioPeer::TS => 15, ),
        BasePeer::TYPE_RAW_COLNAME => array ('AUTOCTR' => 0, 'REFNO' => 1, 'SPECCODE' => 2, 'SYNCODE' => 3, 'REFPAGE' => 4, 'PAGEFIRST' => 5, 'PAGEINSORT' => 6, 'LOCALITY' => 7, 'DISTRIBUTION' => 8, 'COMMENT' => 9, 'QUOTE' => 10, 'ENTERED' => 11, 'DATEENTERED' => 12, 'MODIFIED' => 13, 'DATEMODIFIED' => 14, 'TS' => 15, ),
        BasePeer::TYPE_FIELDNAME => array ('autoctr' => 0, 'RefNo' => 1, 'SpecCode' => 2, 'SynCode' => 3, 'RefPage' => 4, 'PageFirst' => 5, 'PageInSort' => 6, 'Locality' => 7, 'Distribution' => 8, 'Comment' => 9, 'Quote' => 10, 'Entered' => 11, 'DateEntered' => 12, 'Modified' => 13, 'DateModified' => 14, 'TS' => 15, ),
        BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, )
    );

    /**
     * Translates a fieldname to another type
     *
     * @param      string $name field name
     * @param      string $fromType One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME
     *                         BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM
     * @param      string $toType   One of the class type constants
     * @return string          translated name of the field.
     * @throws PropelException - if the specified name could not be found in the fieldname mappings.
     */
    public static function translateFieldName($name, $fromType, $toType)
    {
        $toNames = BiblioPeer::getFieldNames($toType);
        $key = isset(BiblioPeer::$fieldKeys[$fromType][$name]) ? BiblioPeer::$fieldKeys[$fromType][$name] : null;
        if ($key === null) {
            throw new PropelException("'$name' could not be found in the field names of type '$fromType'. These are: " . print_r(BiblioPeer::$fieldKeys[$fromType], true));
        }

        return $toNames[$key];
    }

    /**
     * Returns an array of field names.
     *
     * @param      string $type The type of fieldnames to return:
     *                      One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME
     *                      BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM
     * @return array           A list of field names
     * @throws PropelException - if the type is not valid.
     */
    public static function getFieldNames($type = BasePeer::TYPE_PHPNAME)
    {
        if (!array_key_exists($type, BiblioPeer::$fieldNames)) {
            throw new PropelException('Method getFieldNames() expects the parameter $type to be one of the class constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. ' . $type . ' was given.');
        }

        return BiblioPeer::$fieldNames[$type];
    }

    /**
     * Convenience method which changes table.column to alias.column.
     *
     * Using this method you can maintain SQL abstraction while using column aliases.
     * <code>
     *		$c->addAlias("alias1", TablePeer::TABLE_NAME);
     *		$c->addJoin(TablePeer::alias("alias1", TablePeer::PRIMARY_KEY_COLUMN), TablePeer::PRIMARY_KEY_COLUMN);
     * </code>
     * @param      string $alias The alias for the current table.
     * @param      string $column The column name for current table. (i.e. BiblioPeer::COLUMN_NAME).
     * @return string
     */
    public static function alias($alias, $column)
    {
        return str_replace(BiblioPeer::TABLE_NAME.'.', $alias.'.', $column);
    }

    /**
     * Add all the columns needed to create a new object.
     *
     * Note: any columns that were marked with lazyLoad="true" in the
     * XML schema will not be added to the select list and only loaded
     * on demand.
     *
     * @param      Criteria $criteria object containing the columns to add.
     * @param      string   $alias    optional table alias
     * @throws PropelException Any exceptions caught during processing will be
     *		 rethrown wrapped into a PropelException.
     */
    public static function addSelectColumns(Criteria $criteria, $alias = null)
    {
        if (null === $alias) {
            $criteria->addSelectColumn(BiblioPeer::AUTOCTR);
            $criteria->addSelectColumn(BiblioPeer::REFNO);
            $criteria->addSelectColumn(BiblioPeer::SPECCODE);
            $criteria->addSelectColumn(BiblioPeer::SYNCODE);
            $criteria->addSelectColumn(BiblioPeer::REFPAGE);
            $criteria->addSelectColumn(BiblioPeer::PAGEFIRST);
            $criteria->addSelectColumn(BiblioPeer::PAGEINSORT);
            $criteria->addSelectColumn(BiblioPeer::LOCALITY);
            $criteria->addSelectColumn(BiblioPeer::DISTRIBUTION);
            $criteria->addSelectColumn(BiblioPeer::COMMENT);
            $criteria->addSelectColumn(BiblioPeer::QUOTE);
            $criteria->addSelectColumn(BiblioPeer::ENTERED);
            $criteria->addSelectColumn(BiblioPeer::DATEENTERED);
            $criteria->addSelectColumn(BiblioPeer::MODIFIED);
            $criteria->addSelectColumn(BiblioPeer::DATEMODIFIED);
            $criteria->addSelectColumn(BiblioPeer::TS);
        } else {
            $criteria->addSelectColumn($alias . '.autoctr');
            $criteria->addSelectColumn($alias . '.RefNo');
            $criteria->addSelectColumn($alias . '.SpecCode');
            $criteria->addSelectColumn($alias . '.SynCode');
            $criteria->addSelectColumn($alias . '.RefPage');
            $criteria->addSelectColumn($alias . '.PageFirst');
            $criteria->addSelectColumn($alias . '.PageInSort');
            $criteria->addSelectColumn($alias . '.Locality');
            $criteria->addSelectColumn($alias . '.Distribution');
            $criteria->addSelectColumn($alias . '.Comment');
            $criteria->addSelectColumn($alias . '.Quote');
            $criteria->addSelectColumn($alias . '.Entered');
            $criteria->addSelectColumn($alias . '.DateEntered');
            $criteria->addSelectColumn($alias . '.Modified');
            $criteria->addSelectColumn($alias . '.DateModified');
            $criteria->addSelectColumn($alias . '.TS');
        }
    }

    /**
     * Returns the number of rows matching criteria.
     *
     * @param      Criteria $criteria
     * @param      boolean $distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead.
     * @param      PropelPDO $con
     * @return int Number of matching rows.
     */
    public static function doCount(Criteria $criteria, $distinct = false, PropelPDO $con = null)
    {
        // we may modify criteria, so copy it first
        $criteria = clone $criteria;

        // We need to set the primary table name, since in the case that there are no WHERE columns
        // it will be impossible for the BasePeer::createSelectSql() method to determine which
        // tables go into the FROM clause.
        $criteria->setPrimaryTableName(BiblioPeer::TABLE_NAME);

        if ($distinct && !in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) {
            $criteria->setDistinct();
        }

        if (!$criteria->hasSelectClause()) {
            BiblioPeer::addSelectColumns($criteria);
        }

        $criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count
        $criteria->setDbName(BiblioPeer::DATABASE_NAME); // Set the correct dbName

        if ($con === null) {
            $con = Propel::getConnection(BiblioPeer::DATABASE_NAME, Propel::CONNECTION_READ);
        }
        // BasePeer returns a PDOStatement
        $stmt = BasePeer::doCount($criteria, $con);

        if ($row = $stmt->fetch(PDO::FETCH_NUM)) {
            $count = (int) $row[0];
        } else {
            $count = 0; // no rows returned; we infer that means 0 matches.
        }
        $stmt->closeCursor();

        return $count;
    }
    /**
     * Selects one object from the DB.
     *
     * @param      Criteria $criteria object used to create the SELECT statement.
     * @param      PropelPDO $con
     * @return Biblio
     * @throws PropelException Any exceptions caught during processing will be
     *		 rethrown wrapped into a PropelException.
     */
    public static function doSelectOne(Criteria $criteria, PropelPDO $con = null)
    {
        $critcopy = clone $criteria;
        $critcopy->setLimit(1);
        $objects = BiblioPeer::doSelect($critcopy, $con);
        if ($objects) {
            return $objects[0];
        }

        return null;
    }
    /**
     * Selects several row from the DB.
     *
     * @param      Criteria $criteria The Criteria object used to build the SELECT statement.
     * @param      PropelPDO $con
     * @return array           Array of selected Objects
     * @throws PropelException Any exceptions caught during processing will be
     *		 rethrown wrapped into a PropelException.
     */
    public static function doSelect(Criteria $criteria, PropelPDO $con = null)
    {
        return BiblioPeer::populateObjects(BiblioPeer::doSelectStmt($criteria, $con));
    }
    /**
     * Prepares the Criteria object and uses the parent doSelect() method to execute a PDOStatement.
     *
     * Use this method directly if you want to work with an executed statement directly (for example
     * to perform your own object hydration).
     *
     * @param      Criteria $criteria The Criteria object used to build the SELECT statement.
     * @param      PropelPDO $con The connection to use
     * @throws PropelException Any exceptions caught during processing will be
     *		 rethrown wrapped into a PropelException.
     * @return PDOStatement The executed PDOStatement object.
     * @see        BasePeer::doSelect()
     */
    public static function doSelectStmt(Criteria $criteria, PropelPDO $con = null)
    {
        if ($con === null) {
            $con = Propel::getConnection(BiblioPeer::DATABASE_NAME, Propel::CONNECTION_READ);
        }

        if (!$criteria->hasSelectClause()) {
            $criteria = clone $criteria;
            BiblioPeer::addSelectColumns($criteria);
        }

        // Set the correct dbName
        $criteria->setDbName(BiblioPeer::DATABASE_NAME);

        // BasePeer returns a PDOStatement
        return BasePeer::doSelect($criteria, $con);
    }
    /**
     * Adds an object to the instance pool.
     *
     * Propel keeps cached copies of objects in an instance pool when they are retrieved
     * from the database.  In some cases -- especially when you override doSelect*()
     * methods in your stub classes -- you may need to explicitly add objects
     * to the cache in order to ensure that the same objects are always returned by doSelect*()
     * and retrieveByPK*() calls.
     *
     * @param Biblio $obj A Biblio object.
     * @param      string $key (optional) key to use for instance map (for performance boost if key was already calculated externally).
     */
    public static function addInstanceToPool($obj, $key = null)
    {
        if (Propel::isInstancePoolingEnabled()) {
            if ($key === null) {
                $key = serialize(array((string) $obj->getRefno(), (string) $obj->getSpeccode(), (string) $obj->getSyncode()));
            } // if key === null
            BiblioPeer::$instances[$key] = $obj;
        }
    }

    /**
     * Removes an object from the instance pool.
     *
     * Propel keeps cached copies of objects in an instance pool when they are retrieved
     * from the database.  In some cases -- especially when you override doDelete
     * methods in your stub classes -- you may need to explicitly remove objects
     * from the cache in order to prevent returning objects that no longer exist.
     *
     * @param      mixed $value A Biblio object or a primary key value.
     *
     * @return void
     * @throws PropelException - if the value is invalid.
     */
    public static function removeInstanceFromPool($value)
    {
        if (Propel::isInstancePoolingEnabled() && $value !== null) {
            if (is_object($value) && $value instanceof Biblio) {
                $key = serialize(array((string) $value->getRefno(), (string) $value->getSpeccode(), (string) $value->getSyncode()));
            } elseif (is_array($value) && count($value) === 3) {
                // assume we've been passed a primary key
                $key = serialize(array((string) $value[0], (string) $value[1], (string) $value[2]));
            } else {
                $e = new PropelException("Invalid value passed to removeInstanceFromPool().  Expected primary key or Biblio object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value,true)));
                throw $e;
            }

            unset(BiblioPeer::$instances[$key]);
        }
    } // removeInstanceFromPool()

    /**
     * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table.
     *
     * For tables with a single-column primary key, that simple pkey value will be returned.  For tables with
     * a multi-column primary key, a serialize()d version of the primary key will be returned.
     *
     * @param      string $key The key (@see getPrimaryKeyHash()) for this instance.
     * @return Biblio Found object or null if 1) no instance exists for specified key or 2) instance pooling has been disabled.
     * @see        getPrimaryKeyHash()
     */
    public static function getInstanceFromPool($key)
    {
        if (Propel::isInstancePoolingEnabled()) {
            if (isset(BiblioPeer::$instances[$key])) {
                return BiblioPeer::$instances[$key];
            }
        }

        return null; // just to be explicit
    }

    /**
     * Clear the instance pool.
     *
     * @return void
     */
    public static function clearInstancePool($and_clear_all_references = false)
    {
      if ($and_clear_all_references) {
        foreach (BiblioPeer::$instances as $instance) {
          $instance->clearAllReferences(true);
        }
      }
        BiblioPeer::$instances = array();
    }

    /**
     * Method to invalidate the instance pool of all tables related to biblio
     * by a foreign key with ON DELETE CASCADE
     */
    public static function clearRelatedInstancePool()
    {
    }

    /**
     * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table.
     *
     * For tables with a single-column primary key, that simple pkey value will be returned.  For tables with
     * a multi-column primary key, a serialize()d version of the primary key will be returned.
     *
     * @param      array $row PropelPDO resultset row.
     * @param      int $startcol The 0-based offset for reading from the resultset row.
     * @return string A string version of PK or null if the components of primary key in result array are all null.
     */
    public static function getPrimaryKeyHashFromRow($row, $startcol = 0)
    {
        // If the PK cannot be derived from the row, return null.
        if ($row[$startcol + 1] === null && $row[$startcol + 2] === null && $row[$startcol + 3] === null) {
            return null;
        }

        return serialize(array((string) $row[$startcol + 1], (string) $row[$startcol + 2], (string) $row[$startcol + 3]));
    }

    /**
     * Retrieves the primary key from the DB resultset row
     * For tables with a single-column primary key, that simple pkey value will be returned.  For tables with
     * a multi-column primary key, an array of the primary key columns will be returned.
     *
     * @param      array $row PropelPDO resultset row.
     * @param      int $startcol The 0-based offset for reading from the resultset row.
     * @return mixed The primary key of the row
     */
    public static function getPrimaryKeyFromRow($row, $startcol = 0)
    {

        return array((int) $row[$startcol + 1], (int) $row[$startcol + 2], (int) $row[$startcol + 3]);
    }

    /**
     * The returned array will contain objects of the default type or
     * objects that inherit from the default.
     *
     * @throws PropelException Any exceptions caught during processing will be
     *		 rethrown wrapped into a PropelException.
     */
    public static function populateObjects(PDOStatement $stmt)
    {
        $results = array();

        // set the class once to avoid overhead in the loop
        $cls = BiblioPeer::getOMClass();
        // populate the object(s)
        while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
            $key = BiblioPeer::getPrimaryKeyHashFromRow($row, 0);
            if (null !== ($obj = BiblioPeer::getInstanceFromPool($key))) {
                // We no longer rehydrate the object, since this can cause data loss.
                // See http://www.propelorm.org/ticket/509
                // $obj->hydrate($row, 0, true); // rehydrate
                $results[] = $obj;
            } else {
                $obj = new $cls();
                $obj->hydrate($row);
                $results[] = $obj;
                BiblioPeer::addInstanceToPool($obj, $key);
            } // if key exists
        }
        $stmt->closeCursor();

        return $results;
    }
    /**
     * Populates an object of the default type or an object that inherit from the default.
     *
     * @param      array $row PropelPDO resultset row.
     * @param      int $startcol The 0-based offset for reading from the resultset row.
     * @throws PropelException Any exceptions caught during processing will be
     *		 rethrown wrapped into a PropelException.
     * @return array (Biblio object, last column rank)
     */
    public static function populateObject($row, $startcol = 0)
    {
        $key = BiblioPeer::getPrimaryKeyHashFromRow($row, $startcol);
        if (null !== ($obj = BiblioPeer::getInstanceFromPool($key))) {
            // We no longer rehydrate the object, since this can cause data loss.
            // See http://www.propelorm.org/ticket/509
            // $obj->hydrate($row, $startcol, true); // rehydrate
            $col = $startcol + BiblioPeer::NUM_HYDRATE_COLUMNS;
        } else {
            $cls = BiblioPeer::OM_CLASS;
            $obj = new $cls();
            $col = $obj->hydrate($row, $startcol);
            BiblioPeer::addInstanceToPool($obj, $key);
        }

        return array($obj, $col);
    }

    /**
     * Returns the TableMap related to this peer.
     * This method is not needed for general use but a specific application could have a need.
     * @return TableMap
     * @throws PropelException Any exceptions caught during processing will be
     *		 rethrown wrapped into a PropelException.
     */
    public static function getTableMap()
    {
        return Propel::getDatabaseMap(BiblioPeer::DATABASE_NAME)->getTable(BiblioPeer::TABLE_NAME);
    }

    /**
     * Add a TableMap instance to the database for this peer class.
     */
    public static function buildTableMap()
    {
      $dbMap = Propel::getDatabaseMap(BaseBiblioPeer::DATABASE_NAME);
      if (!$dbMap->hasTable(BaseBiblioPeer::TABLE_NAME)) {
        $dbMap->addTableObject(new \BiblioTableMap());
      }
    }

    /**
     * The class that the Peer will make instances of.
     *
     *
     * @return string ClassName
     */
    public static function getOMClass($row = 0, $colnum = 0)
    {
        return BiblioPeer::OM_CLASS;
    }

    /**
     * Performs an INSERT on the database, given a Biblio or Criteria object.
     *
     * @param      mixed $values Criteria or Biblio object containing data that is used to create the INSERT statement.
     * @param      PropelPDO $con the PropelPDO connection to use
     * @return mixed           The new primary key.
     * @throws PropelException Any exceptions caught during processing will be
     *		 rethrown wrapped into a PropelException.
     */
    public static function doInsert($values, PropelPDO $con = null)
    {
        if ($con === null) {
            $con = Propel::getConnection(BiblioPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
        }

        if ($values instanceof Criteria) {
            $criteria = clone $values; // rename for clarity
        } else {
            $criteria = $values->buildCriteria(); // build Criteria from Biblio object
        }

        // Set the correct dbName
        $criteria->setDbName(BiblioPeer::DATABASE_NAME);

        try {
            // use transaction because $criteria could contain info
            // for more than one table (I guess, conceivably)
            $con->beginTransaction();
            $pk = BasePeer::doInsert($criteria, $con);
            $con->commit();
        } catch (Exception $e) {
            $con->rollBack();
            throw $e;
        }

        return $pk;
    }

    /**
     * Performs an UPDATE on the database, given a Biblio or Criteria object.
     *
     * @param      mixed $values Criteria or Biblio object containing data that is used to create the UPDATE statement.
     * @param      PropelPDO $con The connection to use (specify PropelPDO connection object to exert more control over transactions).
     * @return int             The number of affected rows (if supported by underlying database driver).
     * @throws PropelException Any exceptions caught during processing will be
     *		 rethrown wrapped into a PropelException.
     */
    public static function doUpdate($values, PropelPDO $con = null)
    {
        if ($con === null) {
            $con = Propel::getConnection(BiblioPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
        }

        $selectCriteria = new Criteria(BiblioPeer::DATABASE_NAME);

        if ($values instanceof Criteria) {
            $criteria = clone $values; // rename for clarity

            $comparison = $criteria->getComparison(BiblioPeer::REFNO);
            $value = $criteria->remove(BiblioPeer::REFNO);
            if ($value) {
                $selectCriteria->add(BiblioPeer::REFNO, $value, $comparison);
            } else {
                $selectCriteria->setPrimaryTableName(BiblioPeer::TABLE_NAME);
            }

            $comparison = $criteria->getComparison(BiblioPeer::SPECCODE);
            $value = $criteria->remove(BiblioPeer::SPECCODE);
            if ($value) {
                $selectCriteria->add(BiblioPeer::SPECCODE, $value, $comparison);
            } else {
                $selectCriteria->setPrimaryTableName(BiblioPeer::TABLE_NAME);
            }

            $comparison = $criteria->getComparison(BiblioPeer::SYNCODE);
            $value = $criteria->remove(BiblioPeer::SYNCODE);
            if ($value) {
                $selectCriteria->add(BiblioPeer::SYNCODE, $value, $comparison);
            } else {
                $selectCriteria->setPrimaryTableName(BiblioPeer::TABLE_NAME);
            }

        } else { // $values is Biblio object
            $criteria = $values->buildCriteria(); // gets full criteria
            $selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s)
        }

        // set the correct dbName
        $criteria->setDbName(BiblioPeer::DATABASE_NAME);

        return BasePeer::doUpdate($selectCriteria, $criteria, $con);
    }

    /**
     * Deletes all rows from the biblio table.
     *
     * @param      PropelPDO $con the connection to use
     * @return int             The number of affected rows (if supported by underlying database driver).
     * @throws PropelException
     */
    public static function doDeleteAll(PropelPDO $con = null)
    {
        if ($con === null) {
            $con = Propel::getConnection(BiblioPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
        }
        $affectedRows = 0; // initialize var to track total num of affected rows
        try {
            // use transaction because $criteria could contain info
            // for more than one table or we could emulating ON DELETE CASCADE, etc.
            $con->beginTransaction();
            $affectedRows += BasePeer::doDeleteAll(BiblioPeer::TABLE_NAME, $con, BiblioPeer::DATABASE_NAME);
            // Because this db requires some delete cascade/set null emulation, we have to
            // clear the cached instance *after* the emulation has happened (since
            // instances get re-added by the select statement contained therein).
            BiblioPeer::clearInstancePool();
            BiblioPeer::clearRelatedInstancePool();
            $con->commit();

            return $affectedRows;
        } catch (Exception $e) {
            $con->rollBack();
            throw $e;
        }
    }

    /**
     * Performs a DELETE on the database, given a Biblio or Criteria object OR a primary key value.
     *
     * @param      mixed $values Criteria or Biblio object or primary key or array of primary keys
     *              which is used to create the DELETE statement
     * @param      PropelPDO $con the connection to use
     * @return int The number of affected rows (if supported by underlying database driver).  This includes CASCADE-related rows
     *				if supported by native driver or if emulated using Propel.
     * @throws PropelException Any exceptions caught during processing will be
     *		 rethrown wrapped into a PropelException.
     */
     public static function doDelete($values, PropelPDO $con = null)
     {
        if ($con === null) {
            $con = Propel::getConnection(BiblioPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
        }

        if ($values instanceof Criteria) {
            // invalidate the cache for all objects of this type, since we have no
            // way of knowing (without running a query) what objects should be invalidated
            // from the cache based on this Criteria.
            BiblioPeer::clearInstancePool();
            // rename for clarity
            $criteria = clone $values;
        } elseif ($values instanceof Biblio) { // it's a model object
            // invalidate the cache for this single object
            BiblioPeer::removeInstanceFromPool($values);
            // create criteria based on pk values
            $criteria = $values->buildPkeyCriteria();
        } else { // it's a primary key, or an array of pks
            $criteria = new Criteria(BiblioPeer::DATABASE_NAME);
            // primary key is composite; we therefore, expect
            // the primary key passed to be an array of pkey values
            if (count($values) == count($values, COUNT_RECURSIVE)) {
                // array is not multi-dimensional
                $values = array($values);
            }
            foreach ($values as $value) {
                $criterion = $criteria->getNewCriterion(BiblioPeer::REFNO, $value[0]);
                $criterion->addAnd($criteria->getNewCriterion(BiblioPeer::SPECCODE, $value[1]));
                $criterion->addAnd($criteria->getNewCriterion(BiblioPeer::SYNCODE, $value[2]));
                $criteria->addOr($criterion);
                // we can invalidate the cache for this single PK
                BiblioPeer::removeInstanceFromPool($value);
            }
        }

        // Set the correct dbName
        $criteria->setDbName(BiblioPeer::DATABASE_NAME);

        $affectedRows = 0; // initialize var to track total num of affected rows

        try {
            // use transaction because $criteria could contain info
            // for more than one table or we could emulating ON DELETE CASCADE, etc.
            $con->beginTransaction();

            $affectedRows += BasePeer::doDelete($criteria, $con);
            BiblioPeer::clearRelatedInstancePool();
            $con->commit();

            return $affectedRows;
        } catch (Exception $e) {
            $con->rollBack();
            throw $e;
        }
    }

    /**
     * Validates all modified columns of given Biblio object.
     * If parameter $columns is either a single column name or an array of column names
     * than only those columns are validated.
     *
     * NOTICE: This does not apply to primary or foreign keys for now.
     *
     * @param Biblio $obj The object to validate.
     * @param      mixed $cols Column name or array of column names.
     *
     * @return mixed TRUE if all columns are valid or the error message of the first invalid column.
     */
    public static function doValidate($obj, $cols = null)
    {
        $columns = array();

        if ($cols) {
            $dbMap = Propel::getDatabaseMap(BiblioPeer::DATABASE_NAME);
            $tableMap = $dbMap->getTable(BiblioPeer::TABLE_NAME);

            if (! is_array($cols)) {
                $cols = array($cols);
            }

            foreach ($cols as $colName) {
                if ($tableMap->hasColumn($colName)) {
                    $get = 'get' . $tableMap->getColumn($colName)->getPhpName();
                    $columns[$colName] = $obj->$get();
                }
            }
        } else {

        }

        return BasePeer::doValidate(BiblioPeer::DATABASE_NAME, BiblioPeer::TABLE_NAME, $columns);
    }

    /**
     * Retrieve object using using composite pkey values.
     * @param   int $refno
     * @param   int $speccode
     * @param   int $syncode
     * @param      PropelPDO $con
     * @return Biblio
     */
    public static function retrieveByPK($refno, $speccode, $syncode, PropelPDO $con = null) {
        $_instancePoolKey = serialize(array((string) $refno, (string) $speccode, (string) $syncode));
         if (null !== ($obj = BiblioPeer::getInstanceFromPool($_instancePoolKey))) {
             return $obj;
        }

        if ($con === null) {
            $con = Propel::getConnection(BiblioPeer::DATABASE_NAME, Propel::CONNECTION_READ);
        }
        $criteria = new Criteria(BiblioPeer::DATABASE_NAME);
        $criteria->add(BiblioPeer::REFNO, $refno);
        $criteria->add(BiblioPeer::SPECCODE, $speccode);
        $criteria->add(BiblioPeer::SYNCODE, $syncode);
        $v = BiblioPeer::doSelect($criteria, $con);

        return !empty($v) ? $v[0] : null;
    }
} // BaseBiblioPeer

// This is the static code needed to register the TableMap for this table with the main Propel class.
//
BaseBiblioPeer::buildTableMap();


text:
package com.adaptris.core.security.access;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.adaptris.core.CoreException;

public abstract class IdentityVerifierImpl implements IdentityVerifier {

  protected transient Logger log = LoggerFactory.getLogger(this.getClass());

  public IdentityVerifierImpl() {

  }

  @Override
  public void init() throws CoreException {
  }

  @Override
  public void start() throws CoreException {
  }

  @Override
  public void stop() {
  }

  @Override
  public void close() {
  }

}


text:
class TemplateController < Controller::Base

  include Snippets::Template

  def test_1(filename)
    create_file filename do |f| f.print "test_1"; end
  end

  def test_template_1(source, target)
    template source, target
  end

end


text:
<?php namespace Khill\Lavacharts\Traits;

use Khill\Lavacharts\Utils;
use Khill\Lavacharts\Exceptions\InvalidConfigValue;

trait AxisTitlesPosition
{
    /**
     * Where to place the axis titles, compared to the chart area. Supported values:
     * in   - Draw the axis titles inside the the chart area.
     * out  - Draw the axis titles outside the chart area.
     * none - Omit the axis titles.
     *
     * @param string $position The position of the axis titles
     *
     * @return Chart
     */
    public function axisTitlesPosition($position)
    {
        $values = array(
            'in',
            'out',
            'none'
        );

        if (in_array($position, $values)) {
            $this->addOption(array('axisTitlesPosition' => $position));
        } else {
            throw new InvalidConfigValue(
                $this->className,
                __FUNCTION__,
                'string',
                'with a value of '.Utils::arrayToPipedString($values)
            );
        }

        return $this;
    }
}


text:
package malictus.tagcorral.ui.viewer;

import java.awt.*;
import java.util.*;
import malictus.tagcorral.lib.chunk.MetaChunk;
import malictus.tagcorral.lib.file.TCFile;
import malictus.tagcorral.ui.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

public class TagListTable extends TCTable {

	TagListPanel parent;

	public TagListTable(TagListPanel parent) {
		super();
		this.parent = parent;
		//make the table cells a big bigger than normal for readability
		this.getTable().setRowHeight(18);
		this.getTable().setFont(new Font(this.getTable().getFont().getFontName(), Font.PLAIN, 12));
		this.getTable().setShowHorizontalLines(false);
        this.getTable().setShowVerticalLines(false);
		ListSelectionModel rowSM = this.getTable().getSelectionModel();;
        rowSM.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                if (e.getValueIsAdjusting()) return;
                newRowSelected();
            }
        });
	}

	//caled by MainWindow when a new file selected; null when no file open
	protected void MSG_mainWindowFileOpened(TCFile file) {
		this.setTableData(getHeaders(), file);
	}

	protected void MSG_setInterfaceEnabled(boolean val) {
		this.getTable().setEnabled(val);
	}

	private String[] getHeaders() {
		String[] headers = new String[1];
		headers[0] = TCStrings.getStringFor("TLP_HEADER_TITLE");
		return headers;
	}

	private void setTableData(String[] headers, TCFile file) {
		if (file == null) {
			this.getTable().setModel(new TLPTableModel(headers, new Vector<MetaChunk>()));
		} else {
			this.getTable().setModel(new TLPTableModel(headers, file.getMetadataChunks()));
		}
		int counter = 0;
		while (counter < headers.length) {
			TableColumn column = this.getTable().getColumnModel().getColumn(counter);
			column.setCellRenderer(new TLPCellRenderer());
			counter = counter + 1;
		}
		if (this.getTable().getModel().getRowCount() > 0) {
			SwingUtilities.invokeLater( new Runnable() {
				public void run() {
					getTable().setRowSelectionInterval(0, 0);
				}
			});
		}
	}

	private void newRowSelected() {
		if (this.getTable().getSelectedRow() >= 0) {
			Object x = getTable().getModel().getValueAt(this.getTable().getSelectedRow(), 0);
			parent.MSG_tagListTableNewChunk((MetaChunk)x);
		}
	}

	private class TLPTableModel extends AbstractTableModel {

		private String[] columnNames;
		private Vector<MetaChunk> chunks;

		public TLPTableModel(String[] columnNames, Vector<MetaChunk> chunks) {
			super();
			this.columnNames = columnNames;
			this.chunks = chunks;
		}

		public int getColumnCount() {
			return columnNames.length;
		}

		public int getRowCount() {
			return chunks.size();
		}

		public String getColumnName(int col) {
			return columnNames[col];
		}

		public Object getValueAt(int row, int col) {
			return chunks.get(row);
		}

	}

	private class TLPCellRenderer extends DefaultTableCellRenderer {

		public Component getTableCellRendererComponent(JTable table, Object object,
				boolean isSelected, boolean hasFocus, int row, int column) {
			super.getTableCellRendererComponent(table, object, isSelected, hasFocus, row, column);
			//have to set it here in case it gets changed below
			this.setForeground(SystemColor.textText);
			MetaChunk theChunk = (MetaChunk)object;
			setText(UIUtils.getChunkTypeString(theChunk));
			if (!theChunk.chunkIsValid()) {
				this.setForeground(Color.red);
			}
			return this;
		}

	}

}


text:
@class UIColor;

@interface WCSKUButtonDisableBgView : UIView
{
    UIColor *_roundCornerColor;
}

@property(retain, nonatomic) UIColor *roundCornerColor; // @synthesize roundCornerColor=_roundCornerColor;
- (void).cxx_destruct;
- (void)drawRect:(struct CGRect)arg1;
- (id)initWithFrame:(struct CGRect)arg1;

@end


text:
<?php

namespace Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table()
 * @ORM\Entity()
 */
class Article
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id()
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /** @ORM\Column(type="string", length=255) */
    private $title;

    /** @ORM\Column(type="json_array", nullable=true) */
    private $marking;

    public function __construct($title = 'Title')
    {
        $this->title = $title;
    }

    public function getId()
    {
        return $this->id;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title)
    {
        $this->title = $title;
    }

    public function getMarking()
    {
        return $this->marking;
    }

    public function setMarking($marking)
    {
        $this->marking = $marking;
    }
}


text:
package com.example.computable_value_ref;

import arez.ComputableValue;
import arez.annotations.ArezComponent;
import arez.annotations.ComputableValueRef;
import arez.annotations.Memoize;
import javax.annotation.Nonnull;

@ArezComponent
public abstract class FinalModel
{
  @Memoize
  public long getTime()
  {
    return 0;
  }

  @Nonnull
  @ComputableValueRef
  final ComputableValue<Long> getTimeComputableValue()
  {
    throw new IllegalStateException();
  }
}


text:
#include <libusb.h>
#include <QDebug>

#include "unixpeperonidevice.h"
#include "unixioenumerator.h"
#include "peperonidefs.h"

UnixIOEnumerator::UnixIOEnumerator(QObject* parent)
    : IOEnumerator(parent)
    , m_ctx(NULL)
{
    qDebug() << Q_FUNC_INFO;

    int r = libusb_init(&m_ctx);
    if (r != 0)
        qWarning() << "Unable to initialize libusb context!";

    // libusb_set_debug(m_ctx, 3);
}

UnixIOEnumerator::~UnixIOEnumerator()
{
    qDebug() << Q_FUNC_INFO;

    if (m_ctx != NULL)
        libusb_exit(m_ctx);
}

void UnixIOEnumerator::extractData(struct libusb_device* device,
                                   struct libusb_device_descriptor* desc,
                                   QVariant* uid, QString* name)
{
    qDebug() << Q_FUNC_INFO;

    Q_ASSERT(device != NULL);
    Q_ASSERT(desc != NULL);
    Q_ASSERT(uid != NULL);
    Q_ASSERT(name != NULL);

    libusb_device_handle* handle = NULL;
    int r = libusb_open(device, &handle);
    if (r == 0)
    {
        char buf[128];
        int r = 0;

        // UID
        r = libusb_get_string_descriptor_ascii(handle, desc->iSerialNumber,
                                               (uchar*) &buf, sizeof(buf));
        if (r > 0)
            *uid = QByteArray(buf, r);
        else
            qWarning() << "Unable to get device serial:" << r;

        // Name
        r = libusb_get_string_descriptor_ascii(handle, desc->iProduct,
                                               (uchar*) &buf, sizeof(buf));
        if (r > 0)
            *name = QString(QByteArray(buf, r));
        else
            qWarning() << "Unable to get product name:" << r;

        // Close device
        libusb_close(handle);
    }
    else
    {
        qWarning() << "Unable to open device:" << r;
    }
}

bool UnixIOEnumerator::isPeperoniDevice(const struct libusb_device_descriptor* descriptor)
{
    Q_ASSERT(descriptor != NULL);

    /* If it's not manufactured by them, we're not interested in it */
    if (descriptor->idVendor != PEPERONI_VID)
        return false;

    if (descriptor->idProduct == PEPERONI_PID_RODIN1     ||
        descriptor->idProduct == PEPERONI_PID_RODIN1_MK3 ||
        descriptor->idProduct == PEPERONI_PID_RODIN2     ||
        descriptor->idProduct == PEPERONI_PID_RODINT     ||
        descriptor->idProduct == PEPERONI_PID_XSWITCH    ||
        descriptor->idProduct == PEPERONI_PID_USBDMX21)
    {
        return true;
    }
    else
    {
        return false;
    }
}

void UnixIOEnumerator::rescan()
{
    qDebug() << Q_FUNC_INFO;

    QList <OutputDevice*> destroyOutputs(m_outputDevices);
    bool changed = false;

    libusb_device** devices = NULL;
    ssize_t count = libusb_get_device_list(m_ctx, &devices);
    for (ssize_t i = 0; i < count; i++)
    {
        libusb_device* dev = devices[i];
        Q_ASSERT(dev != NULL);

        libusb_device_descriptor desc;
        int r = libusb_get_device_descriptor(dev, &desc);
        if (r < 0)
        {
            qWarning() << "Unable to get device descriptor:" << r;
            continue;
        }

        // We're only interested in Peperoni devices
        if (isPeperoniDevice(&desc) == false)
            continue;

        QVariant uid;
        QString name;
        extractData(dev, &desc, &uid, &name);

        OutputDevice* od = outputDevice(uid);
        if (od == NULL)
        {
            // New device
            od = new UnixPeperoniDevice(uid, name, dev, &desc, this);
            m_outputDevices << od;
            changed = true;
        }
        else
        {
            // Device is known and still present
            destroyOutputs.removeAll(od);
        }
    }

    // Release the list's references to the devices
    libusb_free_device_list(devices, 1);

    // Destroy all devices that are no longer present
    while (destroyOutputs.isEmpty() == false)
    {
        delete destroyOutputs.takeFirst();
        changed = true;
    }

    // Emit signal if something was changed
    if (changed == true)
        emit configurationChanged();
}

QList <OutputDevice*> UnixIOEnumerator::outputDevices() const
{
    return m_outputDevices;
}

QList <InputDevice*> UnixIOEnumerator::inputDevices() const
{
    return m_inputDevices;
}

OutputDevice* UnixIOEnumerator::outputDevice(const QVariant& uid) const
{
    QListIterator <OutputDevice*> it(m_outputDevices);
    while (it.hasNext() == true)
    {
        OutputDevice* dev(it.next());
        if (dev->uid() == uid)
            return dev;
    }

    return NULL;
}

InputDevice* UnixIOEnumerator::inputDevice(const QVariant& uid) const
{
    Q_UNUSED(uid);
    return NULL;
}


text:
<?php
/**
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 */

namespace Piwik\Plugins\CoreVisualizations;

use Piwik\Common;
use Piwik\ViewDataTable\Manager as ViewDataTableManager;

require_once PIWIK_INCLUDE_PATH . '/plugins/CoreVisualizations/JqplotDataGenerator.php';

/**
 * This plugin contains all core visualizations, such as the normal HTML table and
 * jqPlot graphs.
 */
class CoreVisualizations extends \Piwik\Plugin
{
    /**
     * @see Piwik\Plugin::getListHooksRegistered
     */
    public function getListHooksRegistered()
    {
        return array(
            'AssetManager.getStylesheetFiles'        => 'getStylesheetFiles',
            'AssetManager.getJavaScriptFiles'        => 'getJsFiles',
            'Translate.getClientSideTranslationKeys' => 'getClientSideTranslationKeys',
            'UsersManager.deleteUser'                => 'deleteUser',
            'ViewDataTable.addViewDataTable'         => 'addViewDataTable'
        );
    }

    public function deleteUser($userLogin)
    {
        ViewDataTableManager::clearUserViewDataTableParameters($userLogin);
    }

    public function addViewDataTable(&$viewDataTable)
    {
        // Both are the same HtmlTable, just the Pivot one has some extra logic in case Pivot is used.
        // We don't want to use the same HtmlTable twice in the UI. Therefore we always need to remove one.
        if (Common::getRequestVar('pivotBy', '')) {
            $tableToRemove = 'Visualizations\HtmlTable';
        } else {
            $tableToRemove = 'HtmlTable\PivotBy';
        }

        foreach ($viewDataTable as $index => $table) {
            if (Common::stringEndsWith($table, $tableToRemove)) {
                unset($viewDataTable[$index]);
            }
        }
    }

    public function getStylesheetFiles(&$stylesheets)
    {
        $stylesheets[] = "plugins/CoreVisualizations/stylesheets/dataTableVisualizations.less";
        $stylesheets[] = "plugins/CoreVisualizations/stylesheets/jqplot.css";
    }

    public function getJsFiles(&$jsFiles)
    {
        $jsFiles[] = "plugins/CoreVisualizations/javascripts/seriesPicker.js";
        $jsFiles[] = "plugins/CoreVisualizations/javascripts/jqplot.js";
        $jsFiles[] = "plugins/CoreVisualizations/javascripts/jqplotBarGraph.js";
        $jsFiles[] = "plugins/CoreVisualizations/javascripts/jqplotPieGraph.js";
        $jsFiles[] = "plugins/CoreVisualizations/javascripts/jqplotEvolutionGraph.js";
    }

    public function getClientSideTranslationKeys(&$translationKeys)
    {
        $translationKeys[] = 'General_MetricsToPlot';
        $translationKeys[] = 'General_MetricToPlot';
        $translationKeys[] = 'General_RecordsToPlot';
        $translationKeys[] = 'General_SaveImageOnYourComputer';
        $translationKeys[] = 'General_ExportAsImage';
        $translationKeys[] = 'General_NoDataForGraph';
    }
}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
*	======================
*	function load_ft_class
*	======================
*	Checks if Zenbu has support for a specific fieldtype and loads the class.
*	If the fieldtype is not bundled with Zenbu, tries to load fieldtype class from original file
*	@param	string	$ft_name	The name of the fieldtype class
*	@return	void
*/
function load_ft_class($ft_name)
{
	$ft_class		= ucfirst($ft_name);	// My_field_ft
	$ft_name		= substr($ft_name, 0, -3); // my_field
	$ft_filename	= $ft_name . '.php'; // my_field.php

	// if( ! class_exists($ft_class))
	// {
		$EE =& get_instance();
		$EE->load->library('api');
		$EE->load->helper('file');
		$EE->api->instantiate('channel_fields');
		$EE->api_channel_fields->include_handler($ft_name);

		if(read_file(PATH_THIRD.'zenbu/fieldtypes/'.$ft_filename) !== FALSE)
		{
			require_once PATH_THIRD.'zenbu/fieldtypes/'.$ft_filename;
		}
	// }
}

/**
 * =========================
 * function create_object
 * =========================
 * Check if the object we want to create is from a
 * Zenbu fieltype class (where the cool functions are).
 * If not, create an object from the official fieldtype class
 * (and hope they added cool Zenbu functions)
 * @param  string $ft_class 	The class name
 * @return object $ft_object 	The created object from the fieldtype class
 */
function create_object($ft_class)
{
	if(class_exists('zenbu_'.$ft_class))
	{
		$ft_class = 'zenbu_'.$ft_class;
		$ft_object 	= new $ft_class();
	} else {
		$ft_object 	= new $ft_class();
	}
	return $ft_object;
}

/**
 * ======================
 * function find_rule
 * ======================
 * Checks for the presence of a specific rule in Zenbu
 * @param  string 	$type  The type of rule element. Usually 'field', 'cond' or 'val'
 * @param  string 	$value The value of the rule element
 * @param  array 	$rules The passed Zenbu rules
 * @return bool
 */
function find_rule($type, $value, $rules)
{
	foreach ($rules as $key => $rule_arr)
	{
		if(isset($rule_arr[$type]) && $rule_arr[$type] == $value)
		{
			return TRUE;
		}
	}
	return FALSE;
}

/**
 * ======================
 * function get_action_id
 * ======================
 * Checks for the presence of a specific rule in Zenbu
 * @param  string 	$type  The type of rule element. Usually 'field', 'cond' or 'val'
 * @param  string 	$value The value of the rule element
 * @param  array 	$rules The passed Zenbu rules
 * @return bool
 */
function get_action_id($class, $method)
{
	$EE =& get_instance();

	// Return data if already cached
	if($EE->session->cache('zenbu', 'get_action_id_'.$method))
	{
		return $EE->session->cache('zenbu', 'get_action_id_'.$method);
	}

	$action_id = "";
	$EE->db->from("actions");
	$EE->db->where("actions.class", $class);
	$EE->db->where("actions.method", $method);
	$action_id_query = $EE->db->get();

	if($action_id_query->num_rows() > 0)
	{
		foreach($action_id_query->result_array() as $row)
		{
			$action_id = $row['action_id'];
		}
	}

	$EE->session->set_cache('zenbu', 'get_action_id_'.$method, $action_id);

	return $action_id;
}

?>


text:
package org.apache.jackrabbit.oak.osgi;

import java.util.List;

import javax.annotation.Nonnull;

import org.apache.jackrabbit.oak.plugins.index.CompositeIndexHookProvider;
import org.apache.jackrabbit.oak.plugins.index.IndexHook;
import org.apache.jackrabbit.oak.plugins.index.IndexHookProvider;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;

/**
 * This IndexHook provider combines all index hooks of all available OSGi
 * IndexHook providers.
 */
public class OsgiIndexHookProvider extends
        AbstractServiceTracker<IndexHookProvider> implements IndexHookProvider {

    public OsgiIndexHookProvider() {
        super(IndexHookProvider.class);
    }

    @Override @Nonnull
    public List<? extends IndexHook> getIndexHooks(String type,
            NodeBuilder builder) {
        IndexHookProvider composite = CompositeIndexHookProvider
                .compose(getServices());
        return composite.getIndexHooks(type, builder);
    }

}


text:
package com.cde.mihir.infogain;

import java.util.Comparator;

public class CompareUsingGainRatio implements Comparator<Attribute> {
	@Override
	public int compare(Attribute p1, Attribute p2) {

		   if(p1.getGain_ratio()>p2.getGain_ratio())
		   {
			   return -1;
		   }
		   else if(p1.getGain_ratio()<p2.getGain_ratio())
		   return 1;
		   else
			   return 0;
	}

}


text:
package org.apache.lucene.analysis.ru;

import org.apache.lucene.analysis.KeywordMarkerTokenFilter;// for javadoc
import org.apache.lucene.analysis.LowerCaseFilter; // for javadoc
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.KeywordAttribute;
import org.apache.lucene.analysis.tokenattributes.TermAttribute;
import org.apache.lucene.analysis.ru.RussianStemmer;//javadoc @link
import org.apache.lucene.analysis.snowball.SnowballFilter; // javadoc @link

import java.io.IOException;

/**
 * A {@link TokenFilter} that stems Russian words.
 *

 * The implementation was inspired by GermanStemFilter.
 * The input should be filtered by {@link LowerCaseFilter} before passing it to RussianStemFilter ,
 * because RussianStemFilter only works with lowercase characters.
 *

 *

 * To prevent terms from being stemmed use an instance of
 * {@link KeywordMarkerTokenFilter} or a custom {@link TokenFilter} that sets
 * the {@link KeywordAttribute} before this {@link TokenStream}.
 *

 * @see KeywordMarkerTokenFilter
 * @deprecated Use {@link SnowballFilter} with
 * {@link org.tartarus.snowball.ext.RussianStemmer} instead, which has the
 * same functionality. This filter will be removed in Lucene 4.0
 */
@Deprecated
public final class RussianStemFilter extends TokenFilter
{
    /**
     * The actual token in the input stream.
     */
    private RussianStemmer stemmer = null;

    private final TermAttribute termAtt;
    private final KeywordAttribute keywordAttr;

    public RussianStemFilter(TokenStream in)
    {
        super(in);
        stemmer = new RussianStemmer();
        termAtt = addAttribute(TermAttribute.class);
        keywordAttr = addAttribute(KeywordAttribute.class);
    }
    /**
     * Returns the next token in the stream, or null at EOS
     */
    @Override
    public final boolean incrementToken() throws IOException
    {
      if (input.incrementToken()) {
        if(!keywordAttr.isKeyword()) {
          final String term = termAtt.term();
          final String s = stemmer.stem(term);
          if (s != null && !s.equals(term))
            termAtt.setTermBuffer(s);
        }
        return true;
      } else {
        return false;
      }
    }

    /**
     * Set a alternative/custom {@link RussianStemmer} for this filter.
     */
    public void setStemmer(RussianStemmer stemmer)
    {
        if (stemmer != null)
        {
            this.stemmer = stemmer;
        }
    }
}