text:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Drawing;
using System.Threading;
using System.Threading.Tasks;

using Foundation;
using CoreFoundation;
using AVFoundation;
using CoreGraphics;
using CoreMedia;
using CoreVideo;
using ObjCRuntime;
using UIKit;

using ZXing.Common;
using ZXing.Mobile;

namespace ZXing.Mobile
{
	public class ZXingScannerView : UIView, IZXingScanner<UIView>, IScannerSessionHost
	{
		public delegate void ScannerSetupCompleteDelegate();
		public event ScannerSetupCompleteDelegate OnScannerSetupComplete;

		public ZXingScannerView()
		{
		}

		public ZXingScannerView(IntPtr handle) : base(handle)
		{
		}

		public ZXingScannerView(CGRect frame) : base(frame)
		{
		}

		AVCaptureSession session;
		AVCaptureDevice captureDevice = null;
		AVCaptureVideoPreviewLayer previewLayer;
		AVCaptureVideoDataOutput output;
		OutputRecorder outputRecorder;
		DispatchQueue queue;
		Action<ZXing.Result> resultCallback;
		volatile bool stopped = true;

		UIView layerView;
		UIView overlayView = null;

		public MobileBarcodeScanningOptions ScanningOptions { get; set; }

		public event Action OnCancelButtonPressed;

		public string CancelButtonText { get; set; }
		public string FlashButtonText { get; set; }

		bool shouldRotatePreviewBuffer = false;

		AVConfigs captureDeviceOriginalConfig;

		void Setup()
		{
			var started = DateTime.UtcNow;

			if (overlayView != null)
				overlayView.RemoveFromSuperview();

			if (UseCustomOverlayView)
				overlayView = CustomOverlayView;
			else
			{
				overlayView = new ZXingDefaultOverlayView(new CGRect(0, 0, Frame.Width, Frame.Height),
					TopText, BottomText, CancelButtonText, FlashButtonText,
					() =>
					{
						var evt = OnCancelButtonPressed;
						if (evt != null)
							evt();
					}, ToggleTorch);
			}

			if (overlayView != null)
			{
				overlayView.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height);
				overlayView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
			}

			var total = DateTime.UtcNow - started;
			Console.WriteLine("ZXingScannerView.Setup() took {0} ms.", total.TotalMilliseconds);
		}

		bool torch = false;
		bool analyzing = true;

		bool SetupCaptureSession()
		{
			var started = DateTime.UtcNow;

			var availableResolutions = new List<CameraResolution>();

			var consideredResolutions = new Dictionary<NSString, CameraResolution> {
				{ AVCaptureSession.Preset352x288, new CameraResolution   { Width = 352,  Height = 288 } },
				{ AVCaptureSession.PresetMedium, new CameraResolution    { Width = 480,  Height = 360 } },	//480x360
				{ AVCaptureSession.Preset640x480, new CameraResolution   { Width = 640,  Height = 480 } },
				{ AVCaptureSession.Preset1280x720, new CameraResolution  { Width = 1280, Height = 720 } },
				{ AVCaptureSession.Preset1920x1080, new CameraResolution { Width = 1920, Height = 1080 } }
			};

			// configure the capture session for low resolution, change this if your code
			// can cope with more data or volume
			session = new AVCaptureSession()
			{
				SessionPreset = AVCaptureSession.Preset640x480
			};

			// create a device input and attach it to the session
			var devices = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video);
			foreach (var device in devices)
			{
				captureDevice = device;
				if (ScanningOptions.UseFrontCameraIfAvailable.HasValue &&
					ScanningOptions.UseFrontCameraIfAvailable.Value &&
					device.Position == AVCaptureDevicePosition.Front)

					break; //Front camera successfully set
				else if (device.Position == AVCaptureDevicePosition.Back && (!ScanningOptions.UseFrontCameraIfAvailable.HasValue || !ScanningOptions.UseFrontCameraIfAvailable.Value))
					break; //Back camera succesfully set
			}
			if (captureDevice == null)
			{
				Console.WriteLine("No captureDevice - this won't work on the simulator, try a physical device");
				if (overlayView != null)
				{
					AddSubview(overlayView);
					BringSubviewToFront(overlayView);
				}
				return false;
			}

			CameraResolution resolution = null;

			// Find resolution
			// Go through the resolutions we can even consider
			foreach (var cr in consideredResolutions)
			{
				// Now check to make sure our selected device supports the resolution
				// so we can add it to the list to pick from
				if (captureDevice.SupportsAVCaptureSessionPreset(cr.Key))
					availableResolutions.Add(cr.Value);
			}

			resolution = ScanningOptions.GetResolution(availableResolutions);

			// See if the user selected a resolution
			if (resolution != null)
			{
				// Now get the preset string from the resolution chosen
				var preset = (from c in consideredResolutions
							  where c.Value.Width == resolution.Width
								&& c.Value.Height == resolution.Height
							  select c.Key).FirstOrDefault();

				// If we found a matching preset, let's set it on the session
				if (!string.IsNullOrEmpty(preset))
					session.SessionPreset = preset;
			}

			var input = AVCaptureDeviceInput.FromDevice(captureDevice);
			if (input == null)
			{
				Console.WriteLine("No input - this won't work on the simulator, try a physical device");
				if (overlayView != null)
				{
					AddSubview(overlayView);
					BringSubviewToFront(overlayView);
				}
				return false;
			}
			else
				session.AddInput(input);

			var startedAVPreviewLayerAlloc = PerformanceCounter.Start();

			previewLayer = new AVCaptureVideoPreviewLayer(session);

			PerformanceCounter.Stop(startedAVPreviewLayerAlloc, "Alloc AVCaptureVideoPreviewLayer took {0} ms.");

			var perf2 = PerformanceCounter.Start();

			previewLayer.VideoGravity = AVLayerVideoGravity.ResizeAspectFill;
			previewLayer.Frame = new CGRect(0, 0, Frame.Width, Frame.Height);
			previewLayer.Position = new CGPoint(Layer.Bounds.Width / 2, (Layer.Bounds.Height / 2));

			layerView = new UIView(new CGRect(0, 0, Frame.Width, Frame.Height));
			layerView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
			layerView.Layer.AddSublayer(previewLayer);

			AddSubview(layerView);

			ResizePreview(UIApplication.SharedApplication.StatusBarOrientation);

			if (overlayView != null)
			{
				AddSubview(overlayView);
				BringSubviewToFront(overlayView);
			}

			PerformanceCounter.Stop(perf2, "PERF: Setting up layers took {0} ms");

			var perf3 = PerformanceCounter.Start();

			session.StartRunning();

			PerformanceCounter.Stop(perf3, "PERF: session.StartRunning() took {0} ms");

			var perf4 = PerformanceCounter.Start();

			var videoSettings = NSDictionary.FromObjectAndKey(new NSNumber((int)CVPixelFormatType.CV32BGRA),
				CVPixelBuffer.PixelFormatTypeKey);

			// create a VideoDataOutput and add it to the sesion
			output = new AVCaptureVideoDataOutput
			{
				WeakVideoSettings = videoSettings
			};

			// configure the output
			queue = new DispatchQueue("ZxingScannerView"); // (Guid.NewGuid().ToString());

			var barcodeReader = ScanningOptions.BuildBarcodeReader();

			outputRecorder = new OutputRecorder(this, img =>
			{
				var ls = img;

				if (!IsAnalyzing)
					return false;

				try
				{
					var perfDecode = PerformanceCounter.Start();

					if (shouldRotatePreviewBuffer)
						ls = ls.rotateCounterClockwise();

					var result = barcodeReader.Decode(ls);

					PerformanceCounter.Stop(perfDecode, "Decode Time: {0} ms");

					if (result != null)
					{
						resultCallback(result);
						return true;
					}
				}
				catch (Exception ex)
				{
					Console.WriteLine("DECODE FAILED: " + ex);
				}

				return false;
			});

			output.AlwaysDiscardsLateVideoFrames = true;
			output.SetSampleBufferDelegate(outputRecorder, queue);

			PerformanceCounter.Stop(perf4, "PERF: SetupCamera Finished.  Took {0} ms.");

			session.AddOutput(output);

			var perf5 = PerformanceCounter.Start();

			if (captureDevice.LockForConfiguration(out var err))
			{
				captureDeviceOriginalConfig = new AVConfigs
				{
					FocusMode = captureDevice.FocusMode,
					ExposureMode = captureDevice.ExposureMode,
					WhiteBalanceMode = captureDevice.WhiteBalanceMode,
					AutoFocusRangeRestriction = captureDevice.AutoFocusRangeRestriction,
				};

				if (captureDevice.HasFlash)
					captureDeviceOriginalConfig.FlashMode = captureDevice.FlashMode;
				if (captureDevice.HasTorch)
					captureDeviceOriginalConfig.TorchMode = captureDevice.TorchMode;
				if (captureDevice.FocusPointOfInterestSupported)
					captureDeviceOriginalConfig.FocusPointOfInterest = captureDevice.FocusPointOfInterest;
				if (captureDevice.ExposurePointOfInterestSupported)
					captureDeviceOriginalConfig.ExposurePointOfInterest = captureDevice.ExposurePointOfInterest;

				if (ScanningOptions.DisableAutofocus)
				{
					captureDevice.FocusMode = AVCaptureFocusMode.Locked;
				}
				else
				{
					if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus))
						captureDevice.FocusMode = AVCaptureFocusMode.ContinuousAutoFocus;
					else if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.AutoFocus))
						captureDevice.FocusMode = AVCaptureFocusMode.AutoFocus;
				}

				if (captureDevice.IsExposureModeSupported(AVCaptureExposureMode.ContinuousAutoExposure))
					captureDevice.ExposureMode = AVCaptureExposureMode.ContinuousAutoExposure;
				else if (captureDevice.IsExposureModeSupported(AVCaptureExposureMode.AutoExpose))
					captureDevice.ExposureMode = AVCaptureExposureMode.AutoExpose;

				if (captureDevice.IsWhiteBalanceModeSupported(AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance))
					captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance;
				else if (captureDevice.IsWhiteBalanceModeSupported(AVCaptureWhiteBalanceMode.AutoWhiteBalance))
					captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.AutoWhiteBalance;

				if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0) && captureDevice.AutoFocusRangeRestrictionSupported)
				{
					captureDevice.AutoFocusRangeRestriction = AVCaptureAutoFocusRangeRestriction.Near;
				}

				if (captureDevice.FocusPointOfInterestSupported)
					captureDevice.FocusPointOfInterest = new PointF(0.5f, 0.5f);

				if (captureDevice.ExposurePointOfInterestSupported)
					captureDevice.ExposurePointOfInterest = new PointF(0.5f, 0.5f);

				captureDevice.UnlockForConfiguration();
			}
			else
				Console.WriteLine("Failed to Lock for Config: " + err.Description);

			PerformanceCounter.Stop(perf5, "PERF: Setup Focus in {0} ms.");

			return true;
		}

		public void DidRotate(UIInterfaceOrientation orientation)
		{
			ResizePreview(orientation);

			LayoutSubviews();
		}

		public void ResizePreview(UIInterfaceOrientation orientation)
		{
			shouldRotatePreviewBuffer = orientation == UIInterfaceOrientation.Portrait || orientation == UIInterfaceOrientation.PortraitUpsideDown;

			if (previewLayer == null)
				return;

			previewLayer.Frame = new CGRect(0, 0, Frame.Width, Frame.Height);

			if (previewLayer.RespondsToSelector(new Selector("connection")) && previewLayer.Connection != null)
			{
				switch (orientation)
				{
					case UIInterfaceOrientation.LandscapeLeft:
						previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.LandscapeLeft;
						break;
					case UIInterfaceOrientation.LandscapeRight:
						previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.LandscapeRight;
						break;
					case UIInterfaceOrientation.Portrait:
						previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.Portrait;
						break;
					case UIInterfaceOrientation.PortraitUpsideDown:
						previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.PortraitUpsideDown;
						break;
				}
			}
		}

		public void Focus(PointF pointOfInterest)
		{
			//Get the device
			if (AVMediaType.Video == null)
				return;

			var device = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video);

			if (device == null)
				return;

			//See if it supports focusing on a point
			if (device.FocusPointOfInterestSupported && !device.AdjustingFocus)
			{
				NSError err = null;

				//Lock device to config
				if (device.LockForConfiguration(out err))
				{
					Console.WriteLine("Focusing at point: " + pointOfInterest.X + ", " + pointOfInterest.Y);

					//Focus at the point touched
					device.FocusPointOfInterest = pointOfInterest;
					device.FocusMode = AVCaptureFocusMode.ContinuousAutoFocus;
					device.UnlockForConfiguration();
				}
			}
		}

		public class OutputRecorder : AVCaptureVideoDataOutputSampleBufferDelegate
		{
			public OutputRecorder(IScannerSessionHost scannerHost, Func<LuminanceSource, bool> handleImage) : base()
			{
				this.handleImage = handleImage;
				this.scannerHost = scannerHost;
			}

			IScannerSessionHost scannerHost;
			Func<LuminanceSource, bool> handleImage;

			DateTime lastAnalysis = DateTime.MinValue;
			volatile bool working = false;
			volatile bool wasScanned = false;

			[Export("captureOutput:didDropSampleBuffer:fromConnection:")]
			public override void DidDropSampleBuffer(AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, AVCaptureConnection connection)
			{
			}

			public CancellationTokenSource CancelTokenSource = new CancellationTokenSource();

			public override void DidOutputSampleBuffer(AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, AVCaptureConnection connection)
			{
				var msSinceLastPreview = (DateTime.UtcNow - lastAnalysis).TotalMilliseconds;

				if (msSinceLastPreview < scannerHost.ScanningOptions.DelayBetweenAnalyzingFrames
					|| (wasScanned && msSinceLastPreview < scannerHost.ScanningOptions.DelayBetweenContinuousScans)
					|| working
					|| CancelTokenSource.IsCancellationRequested)
				{

					if (msSinceLastPreview < scannerHost.ScanningOptions.DelayBetweenAnalyzingFrames)
						Console.WriteLine("Too soon between frames");
					if (wasScanned && msSinceLastPreview < scannerHost.ScanningOptions.DelayBetweenContinuousScans)
						Console.WriteLine("Too soon since last scan");

					if (sampleBuffer != null)
					{
						sampleBuffer.Dispose();
						sampleBuffer = null;
					}
					return;
				}

				wasScanned = false;
				working = true;
				lastAnalysis = DateTime.UtcNow;

				try
				{
					// Get the CoreVideo image
					using (var pixelBuffer = sampleBuffer.GetImageBuffer() as CVPixelBuffer)
					{
						// Lock the base address
						pixelBuffer.Lock(CVPixelBufferLock.ReadOnly); // MAYBE NEEDS READ/WRITE

						LuminanceSource luminanceSource;

						// Let's access the raw underlying data and create a luminance source from it
						unsafe
						{
							var rawData = (byte*)pixelBuffer.BaseAddress.ToPointer();
							var rawDatalen = (int)(pixelBuffer.Height * pixelBuffer.Width * 4); //This drops 8 bytes from the original length to give us the expected length

							luminanceSource = new CVPixelBufferBGRA32LuminanceSource(rawData, rawDatalen, (int)pixelBuffer.Width, (int)pixelBuffer.Height);
						}

						if (handleImage(luminanceSource))
							wasScanned = true;

						pixelBuffer.Unlock(CVPixelBufferLock.ReadOnly);
					}

					//
					// Although this looks innocent "Oh, he is just optimizing this case away"
					// this is incredibly important to call on this callback, because the AVFoundation
					// has a fixed number of buffers and if it runs out of free buffers, it will stop
					// delivering frames.
					//
					sampleBuffer.Dispose();
					sampleBuffer = null;

				}
				catch (Exception e)
				{
					Console.WriteLine(e);
				}
				finally
				{
					working = false;
				}

			}
		}

		#region IZXingScanner implementation
		public void StartScanning(Action<Result> scanResultHandler, MobileBarcodeScanningOptions options = null)
		{
			if (!stopped)
				return;

			stopped = false;

			var perf = PerformanceCounter.Start();

			Setup();

			ScanningOptions = options ?? MobileBarcodeScanningOptions.Default;
			resultCallback = scanResultHandler;

			Console.WriteLine("StartScanning");

			InvokeOnMainThread(() =>
			{
				if (!SetupCaptureSession())
				{
					//Setup 'simulated' view:
					Console.WriteLine("Capture Session FAILED");
				}

				if (Runtime.Arch == Arch.SIMULATOR)
				{
					InsertSubview(new UIView(new CGRect(0, 0, this.Frame.Width, this.Frame.Height))
					{
						BackgroundColor = UIColor.LightGray,
						AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
					}, 0);

				}
			});

			if (!analyzing)
				analyzing = true;

			PerformanceCounter.Stop(perf, "PERF: StartScanning() Took {0} ms.");

			OnScannerSetupComplete?.Invoke();
		}

		public void StopScanning()
		{
			if (overlayView != null)
			{
				if (overlayView is ZXingDefaultOverlayView)
					(overlayView as ZXingDefaultOverlayView).Destroy();

				overlayView = null;
			}

			if (stopped)
				return;

			Console.WriteLine("Stopping...");

			if (outputRecorder != null)
				outputRecorder.CancelTokenSource.Cancel();

			// Revert camera settings to original
			if (captureDevice != null && captureDevice.LockForConfiguration(out var err))
			{
				captureDevice.FocusMode = captureDeviceOriginalConfig.FocusMode;
				captureDevice.ExposureMode = captureDeviceOriginalConfig.ExposureMode;
				captureDevice.WhiteBalanceMode = captureDeviceOriginalConfig.WhiteBalanceMode;

				if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0) && captureDevice.AutoFocusRangeRestrictionSupported)
					captureDevice.AutoFocusRangeRestriction = captureDeviceOriginalConfig.AutoFocusRangeRestriction;

				if (captureDevice.FocusPointOfInterestSupported)
					captureDevice.FocusPointOfInterest = captureDeviceOriginalConfig.FocusPointOfInterest;

				if (captureDevice.ExposurePointOfInterestSupported)
					captureDevice.ExposurePointOfInterest = captureDeviceOriginalConfig.ExposurePointOfInterest;

				if (captureDevice.HasFlash)
					captureDevice.FlashMode = captureDeviceOriginalConfig.FlashMode;
				if (captureDevice.HasTorch)
					captureDevice.TorchMode = captureDeviceOriginalConfig.TorchMode;

				captureDevice.UnlockForConfiguration();
			}

			//Try removing all existing outputs prior to closing the session
			try
			{
				while (session.Outputs.Length > 0)
					session.RemoveOutput(session.Outputs[0]);
			}
			catch { }

			//Try to remove all existing inputs prior to closing the session
			try
			{
				while (session.Inputs.Length > 0)
					session.RemoveInput(session.Inputs[0]);
			}
			catch { }

			if (session.Running)
				session.StopRunning();

			stopped = true;
		}

		public void PauseAnalysis()
			=> analyzing = false;

		public void ResumeAnalysis()
			=> analyzing = true;

		public void Torch(bool on)
		{
			try
			{
				var device = captureDevice ?? AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video);
				if (device != null && (device.HasTorch || device.HasFlash))
				{
					device.LockForConfiguration(out var err);

					if (err != null)
					{
						if (on)
						{
							if (device.HasTorch)
								device.TorchMode = AVCaptureTorchMode.On;
							if (device.HasFlash)
								device.FlashMode = AVCaptureFlashMode.On;
						}
						else
						{
							if (device.HasTorch)
								device.TorchMode = AVCaptureTorchMode.Off;
							if (device.HasFlash)
								device.FlashMode = AVCaptureFlashMode.Off;
						}
					}

					try
					{
						device.UnlockForConfiguration();
					}
					catch { }
				}

				torch = on;
			}
			catch { }
		}

		public void ToggleTorch()
			=> Torch(!IsTorchOn);

		public void AutoFocus()
		{
			//Doesn't do much on iOS :(
		}

		public void AutoFocus(int x, int y)
		{
			//Doesn't do much on iOS :(
		}

		public string TopText { get; set; }
		public string BottomText { get; set; }

		public UIView CustomOverlayView { get; set; }
		public bool UseCustomOverlayView { get; set; }
		public bool IsAnalyzing { get { return analyzing; } }
		public bool IsTorchOn { get { return torch; } }

		bool? hasTorch = null;
		public bool HasTorch
		{
			get
			{
				if (hasTorch.HasValue)
					return hasTorch.Value;

				var device = captureDevice ?? AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video);
				hasTorch = device.HasFlash || device.HasTorch;
				return hasTorch.Value;
			}
		}
		#endregion
	}

	struct AVConfigs
	{
		public AVCaptureFocusMode FocusMode;
		public AVCaptureExposureMode ExposureMode;
		public AVCaptureWhiteBalanceMode WhiteBalanceMode;
		public AVCaptureAutoFocusRangeRestriction AutoFocusRangeRestriction;
		public CGPoint FocusPointOfInterest;
		public CGPoint ExposurePointOfInterest;
		public AVCaptureFlashMode FlashMode;
		public AVCaptureTorchMode TorchMode;
	}
}


text:
/*
Package hekametrics adds an output for https://github.com/rcrowley/go-metrics/

hekametrics encodes all metrics from a registry into a Heka protobuf message
and sends to a Heka server on it's native listener port.
*/
package hekametrics

import (
	"code.google.com/p/go-uuid/uuid"
	"fmt"
	"github.com/mozilla-services/heka/client"
	"github.com/mozilla-services/heka/message"
	"github.com/rcrowley/go-metrics"
	"log"
	"net/url"
	"os"
	"time"
)

var logger = log.New(os.Stderr, "[hekametrics]", log.LstdFlags)

type HekaClient struct {
	pid               int32
	hostname, msgtype string

	client    client.Client
	encoder   client.StreamEncoder
	sender    client.Sender
	connect_s *url.URL
	stop      chan struct{}
}

//NewHekaClient creates and returns a HekaClient
//
//connect string like 'tcp://127.0.0.1:5564' and 'udp://127.0.0.1:5564'
//
//msgtype sets the 'Type' field on a Heka message
func NewHekaClient(connect, msgtype string) (hc *HekaClient, err error) {
	hc = &HekaClient{}
	hc.connect_s, err = url.ParseRequestURI(connect)
	if err != nil {
		return nil, err
	}
	switch hc.connect_s.Scheme {
	case "tcp", "udp":
	default:
		return nil, fmt.Errorf("scheme: '%s' not supported, try 'tcp://<host>:<port>' or 'udp://<host>:<port>'", hc.connect_s.Scheme)
	}
	hc.msgtype = msgtype
	hc.encoder = client.NewProtobufEncoder(nil)
	hc.pid = int32(os.Getpid())
	hc.hostname, err = os.Hostname()
	if err != nil {
		hc.hostname = "<no hostname>"
	}
	hc.stop = make(chan struct{})
	return
}

func (hc *HekaClient) write(b []byte) error {
	var err error
	reconnect := func() (e error) {
		if hc.sender != nil {
			hc.sender.Close()
			hc.sender = nil
		}

		logger.Printf("Connecting: %s\n", hc.connect_s)
		hc.sender, e = client.NewNetworkSender(hc.connect_s.Scheme, hc.connect_s.Host)
		if e != nil {
			hc.sender = nil
			logger.Printf("Err Connecting: %s %v\n", hc.connect_s, e)
		}
		return e
	}

	if hc.sender == nil {
		err = reconnect()
		if err != nil {
			return err
		}

	}

	err = hc.sender.SendMessage(b)
	if err != nil {
		logger.Printf("Inject: [error] send message: %s\n", err)
		err = reconnect()
		if err != nil {
			return err
		}
		err = hc.sender.SendMessage(b)
		if err != nil {
			return err
		}

	}
	return err
}

// Stops LogHeka from another goroutine
func (hc *HekaClient) Stop() {
	close(hc.stop)
}

// LogHeka is a blocking exporter function which encodes and sends metrics to a Heka server
//
// all metrics in metrics.Registry r are stored on message.Message.Fields
//
// flushing them every Duration d
func (hc *HekaClient) LogHeka(r metrics.Registry, d time.Duration) {

	var (
		stream  []byte
		err     error
		running bool = true
	)

	for running {
		select {
		case _, running = <-hc.stop:
		case <-time.After(d):
		}
		msg := make_message(r)
		msg.SetTimestamp(time.Now().UnixNano())
		msg.SetUuid(uuid.NewRandom())
		msg.SetLogger("go-metrics")
		msg.SetType(hc.msgtype)
		msg.SetPid(hc.pid)
		msg.SetSeverity(100)
		msg.SetHostname(hc.hostname)
		msg.SetPayload("")

		err = hc.encoder.EncodeMessageStream(msg, &stream)
		if err != nil {
			logger.Printf("Inject: [error] encode message: %s\n", err)
		}
		err = hc.write(stream)
		if err != nil {
			logger.Printf("Inject: [error] send message: %s\n", err)
		}

	}

}

func make_message(r metrics.Registry) *message.Message {

	msg := &message.Message{}
	add_float_mapping := func(pref string, names []string, vals []float64) {
		for i, n := range names {

			n = fmt.Sprintf("%s.%s", pref, n)

			if i+1 > len(vals) {
				logger.Println("skipping: %s no value\n", n)
				continue
			}
			f, e := message.NewField(n, vals[i], "")
			if e == nil {
				msg.AddField(f)
			} else {
				logger.Println("skipping: %s %v: %v\n", n, vals[i], e)
			}

		}

	}

	r.Each(func(name string, i interface{}) {

		switch metric := i.(type) {
		case metrics.Counter:
			message.NewInt64Field(msg, name, metric.Count(), "")
		case metrics.Gauge:
			message.NewInt64Field(msg, name, metric.Value(), "")

		case metrics.GaugeFloat64:
			f, e := message.NewField(name, metric.Value(), "")
			if e == nil {
				msg.AddField(f)
			} else {
				logger.Println("skipping: %s %v: %v\n", name, metric.Value(), e)
			}

		case metrics.Histogram:
			h := metric.Snapshot()
			vals_fl := h.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
			vals_fl = append(vals_fl, h.Mean(), h.StdDev())
			names := []string{"50-percentile", "75-percentile", "95-percentile",
				"99-percentile", "999-percentile", "mean", "std-dev"}
			add_float_mapping(fmt.Sprintf("%s.histogram", name), names, vals_fl)

			names = []string{"count", "min", "max"}
			vals_i := []int64{h.Count(), h.Min(), h.Max()}

			for i, n := range names {
				n = fmt.Sprintf("%s.histogram.%s", name, n)
				message.NewInt64Field(msg, n, vals_i[i], n)
			}

		case metrics.Meter:
			m := metric.Snapshot()
			message.NewInt64Field(msg, fmt.Sprintf("%s.count", name),
				m.Count(), "")
			names := []string{"one-minute", "five-minute", "fifteen-minute", "mean"}
			vals_fl := []float64{m.Rate1(), m.Rate5(), m.Rate15(), m.RateMean()}

			add_float_mapping(name, names, vals_fl)
		case metrics.Timer:
			h := metric.Snapshot()
			vals_fl := h.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
			vals_fl = append(vals_fl, h.Mean(), h.StdDev(), h.Rate1(),
				h.Rate5(), h.Rate15(), h.RateMean())
			names := []string{"50-percentile", "75-percentile", "95-percentile",
				"99-percentile", "999-percentile", "mean", "std-dev", "one-minute",
				"five-minute", "fifteen-minute", "mean-rate"}

			add_float_mapping(fmt.Sprintf("%s.timer", name), names, vals_fl)
			names = []string{"count", "min", "max"}
			vals_i := []int64{h.Count(), h.Min(), h.Max()}
			for i, n := range names {
				n = fmt.Sprintf("%s.timer.%s", name, n)
				message.NewInt64Field(msg, n, vals_i[i], "")
			}

		}
	})
	return msg

}

redpajama_set_name: RedPajamaGithub


text:
#include <assert.h>
#include <memory>

#ifndef MESSAGE_H
#define MESSAGE_H

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

class IMessage;

/**
* @brief Shared pointer for abstract interface @ref IMessage.
*
* @see @ref RAII "Resource Acquisition Is Initialization"
*
* @ingroup threading-high
*/
typedef std::shared_ptr<IMessage> Message;

/**
 * @brief Abstract class to be implemented to describe a Message that need to be
 * executed.
 *
 * @ingroup threading-high
 */
class IMessage
{

public:

    /**
     * @brief Destructor.
     */
    virtual ~IMessage()
    {
    }

};

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

#endif // MESSAGE_H


text:
<?php

/**
 * @see Zend_Validate_Abstract
 */
require_once 'Zend/Validate/Abstract.php';

/**
 * @category   Zend
 * @package    Zend_Validate
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Validate_GreaterThan extends Zend_Validate_Abstract
{

    const NOT_GREATER = 'notGreaterThan';

    /**
     * @var array
     */
    protected $_messageTemplates = array(
        self::NOT_GREATER => "'%value%' is not greater than '%min%'",
    );

    /**
     * @var array
     */
    protected $_messageVariables = array(
        'min' => '_min'
    );

    /**
     * Minimum value
     *
     * @var mixed
     */
    protected $_min;

    /**
     * Sets validator options
     *
     * @param  mixed|Zend_Config $min
     * @return void
     */
    public function __construct($min)
    {
        if ($min instanceof Zend_Config) {
            $min = $min->toArray();
        }

        if (is_array($min)) {
            if (array_key_exists('min', $min)) {
                $min = $min['min'];
            } else {
                require_once 'Zend/Validate/Exception.php';
                throw new Zend_Validate_Exception("Missing option 'min'");
            }
        }

        $this->setMin($min);
    }

    /**
     * Returns the min option
     *
     * @return mixed
     */
    public function getMin()
    {
        return $this->_min;
    }

    /**
     * Sets the min option
     *
     * @param  mixed $min
     * @return Zend_Validate_GreaterThan Provides a fluent interface
     */
    public function setMin($min)
    {
        $this->_min = $min;
        return $this;
    }

    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if and only if $value is greater than min option
     *
     * @param  mixed $value
     * @return boolean
     */
    public function isValid($value)
    {
        $this->_setValue($value);

        if ($this->_min >= $value) {
            $this->_error(self::NOT_GREATER);
            return false;
        }
        return true;
    }

}


text:
/* -*- Mode: C; c-basic-offset:4 ; -*- */
/*
 *  (C) 2001 by Argonne National Laboratory.
 *      See COPYRIGHT in top-level directory.
 */

#include "mpidimpl.h"

/* FIXME: Explain the contents of this file */
/*
 * A first guess.  This file contains routines to manage memory-to-memory
 * copies of buffers described by MPI datatypes
 */

/* MPIDI_COPY_BUFFER_SZ is the size of the buffer that is allocated when
   copying from one non-contiguous buffer to another.  In this case, an
   intermediate contiguous buffer is used of this size */
#if !defined(MPIDI_COPY_BUFFER_SZ)
#define MPIDI_COPY_BUFFER_SZ 16384
#endif

/* FIXME: Explain this routine .
Used indirectly by mpid_irecv, mpid_recv (through MPIDI_CH3_RecvFromSelf) and
 in mpidi_isend_self.c */

/* This routine appears to handle copying data from one buffer (described by
 the usual MPI triple (buf,count,datatype) to another, as is needed in send
 and receive from self.  We may want to put all of the "from self" routines
 into a single file, and make MPIDI_CH3U_Buffer_copy static to this file. */

#undef FUNCNAME
#define FUNCNAME MPIDI_CH3U_Buffer_copy
#undef FCNAME
#define FCNAME MPIDI_QUOTE(FUNCNAME)
void MPIDI_CH3U_Buffer_copy(
    const void * const sbuf, int scount, MPI_Datatype sdt, int * smpi_errno,
    void * const rbuf, int rcount, MPI_Datatype rdt, MPIDI_msg_sz_t * rsz,
    int * rmpi_errno)
{
    int sdt_contig;
    int rdt_contig;
    MPI_Aint sdt_true_lb, rdt_true_lb;
    MPIDI_msg_sz_t sdata_sz;
    MPIDI_msg_sz_t rdata_sz;
    MPID_Datatype * sdt_ptr;
    MPID_Datatype * rdt_ptr;
    MPIDI_STATE_DECL(MPID_STATE_MPIDI_CH3U_BUFFER_COPY);
    MPIDI_STATE_DECL(MPID_STATE_MEMCPY);

    MPIDI_FUNC_ENTER(MPID_STATE_MPIDI_CH3U_BUFFER_COPY);
    *smpi_errno = MPI_SUCCESS;
    *rmpi_errno = MPI_SUCCESS;

    MPIDI_Datatype_get_info(scount, sdt, sdt_contig, sdata_sz, sdt_ptr, sdt_true_lb);
    MPIDI_Datatype_get_info(rcount, rdt, rdt_contig, rdata_sz, rdt_ptr, rdt_true_lb);

    /* --BEGIN ERROR HANDLING-- */
    if (sdata_sz > rdata_sz)
    {
	MPIU_DBG_MSG_FMT(CH3_OTHER,TYPICAL,(MPIU_DBG_FDEST,
	    "message truncated, sdata_sz=" MPIDI_MSG_SZ_FMT " rdata_sz=" MPIDI_MSG_SZ_FMT,
			  sdata_sz, rdata_sz));
	sdata_sz = rdata_sz;
	*rmpi_errno = MPIR_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE, FCNAME, __LINE__, MPI_ERR_TRUNCATE, "**truncate", "**truncate %d %d", sdata_sz, rdata_sz );
    }
    /* --END ERROR HANDLING-- */

    if (sdata_sz == 0)
    {
	*rsz = 0;
	goto fn_exit;
    }

    if (sdt_contig && rdt_contig)
    {
	MPIDI_FUNC_ENTER(MPID_STATE_MEMCPY);
	MPIU_Memcpy((char *)rbuf + rdt_true_lb, (const char *)sbuf + sdt_true_lb, sdata_sz);
	MPIDI_FUNC_EXIT(MPID_STATE_MEMCPY);
	*rsz = sdata_sz;
    }
    else if (sdt_contig)
    {
	MPID_Segment seg;
	MPI_Aint last;

	MPID_Segment_init(rbuf, rcount, rdt, &seg, 0);
	last = sdata_sz;
	MPIU_DBG_MSG_FMT(CH3_OTHER,VERBOSE,(MPIU_DBG_FDEST,
                          "pre-unpack last=" MPIDI_MSG_SZ_FMT, last ));
	MPID_Segment_unpack(&seg, 0, &last, (char*)sbuf + sdt_true_lb);
	MPIU_DBG_MSG_FMT(CH3_OTHER,VERBOSE,(MPIU_DBG_FDEST,
			 "pre-unpack last=" MPIDI_MSG_SZ_FMT, last ));
	/* --BEGIN ERROR HANDLING-- */
	if (last != sdata_sz)
	{
	    *rmpi_errno = MPIR_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE, FCNAME, __LINE__, MPI_ERR_TYPE, "**dtypemismatch", 0);
	}
	/* --END ERROR HANDLING-- */

	*rsz = last;
    }
    else if (rdt_contig)
    {
	MPID_Segment seg;
	MPI_Aint last;

	MPID_Segment_init(sbuf, scount, sdt, &seg, 0);
	last = sdata_sz;
	MPIU_DBG_MSG_FMT(CH3_OTHER,VERBOSE,(MPIU_DBG_FDEST,
			       "pre-pack last=" MPIDI_MSG_SZ_FMT, last ));
	MPID_Segment_pack(&seg, 0, &last, (char*)rbuf + rdt_true_lb);
	MPIU_DBG_MSG_FMT(CH3_OTHER,VERBOSE,(MPIU_DBG_FDEST,
			    "post-pack last=" MPIDI_MSG_SZ_FMT, last ));
	/* --BEGIN ERROR HANDLING-- */
	if (last != sdata_sz)
	{
	    *rmpi_errno = MPIR_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE, FCNAME, __LINE__, MPI_ERR_TYPE, "**dtypemismatch", 0);
	}
	/* --END ERROR HANDLING-- */

	*rsz = last;
    }
    else
    {
	char * buf;
	MPIDI_msg_sz_t buf_off;
	MPID_Segment sseg;
	MPIDI_msg_sz_t sfirst;
	MPID_Segment rseg;
	MPIDI_msg_sz_t rfirst;

	buf = MPIU_Malloc(MPIDI_COPY_BUFFER_SZ);
	/* --BEGIN ERROR HANDLING-- */
	if (buf == NULL)
	{
	    MPIU_DBG_MSG(CH3_OTHER,TYPICAL,"SRBuf allocation failure");
	    *smpi_errno = MPIR_Err_create_code(MPI_SUCCESS, MPIR_ERR_FATAL, FCNAME, __LINE__, MPI_ERR_OTHER, "**nomem", 0);
	    *rmpi_errno = *smpi_errno;
	    *rsz = 0;
	    goto fn_exit;
	}
	/* --END ERROR HANDLING-- */

	MPID_Segment_init(sbuf, scount, sdt, &sseg, 0);
	MPID_Segment_init(rbuf, rcount, rdt, &rseg, 0);

	sfirst = 0;
	rfirst = 0;
	buf_off = 0;

	for(;;)
	{
	    MPI_Aint last;
	    char * buf_end;

	    if (sdata_sz - sfirst > MPIDI_COPY_BUFFER_SZ - buf_off)
	    {
		last = sfirst + (MPIDI_COPY_BUFFER_SZ - buf_off);
	    }
	    else
	    {
		last = sdata_sz;
	    }

	    MPIU_DBG_MSG_FMT(CH3_OTHER,VERBOSE,(MPIU_DBG_FDEST,
               "pre-pack first=" MPIDI_MSG_SZ_FMT ", last=" MPIDI_MSG_SZ_FMT,
						sfirst, last ));
	    MPID_Segment_pack(&sseg, sfirst, &last, buf + buf_off);
	    MPIU_DBG_MSG_FMT(CH3_OTHER,VERBOSE,(MPIU_DBG_FDEST,
               "post-pack first=" MPIDI_MSG_SZ_FMT ", last=" MPIDI_MSG_SZ_FMT,
               sfirst, last ));
	    /* --BEGIN ERROR HANDLING-- */
	    MPIU_Assert(last > sfirst);
	    /* --END ERROR HANDLING-- */

	    buf_end = buf + buf_off + (last - sfirst);
	    sfirst = last;

	    MPIU_DBG_MSG_FMT(CH3_OTHER,VERBOSE,(MPIU_DBG_FDEST,
             "pre-unpack first=" MPIDI_MSG_SZ_FMT ", last=" MPIDI_MSG_SZ_FMT,
						rfirst, last ));
	    MPID_Segment_unpack(&rseg, rfirst, &last, buf);
	    MPIU_DBG_MSG_FMT(CH3_OTHER,VERBOSE,(MPIU_DBG_FDEST,
             "post-unpack first=" MPIDI_MSG_SZ_FMT ", last=" MPIDI_MSG_SZ_FMT,
						rfirst, last ));
	    /* --BEGIN ERROR HANDLING-- */
	    MPIU_Assert(last > rfirst);
	    /* --END ERROR HANDLING-- */

	    rfirst = last;

	    if (rfirst == sdata_sz)
	    {
		/* successful completion */
		break;
	    }

	    /* --BEGIN ERROR HANDLING-- */
	    if (sfirst == sdata_sz)
	    {
		/* datatype mismatch -- remaining bytes could not be unpacked */
		*rmpi_errno = MPIR_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE, FCNAME, __LINE__, MPI_ERR_TYPE, "**dtypemismatch", 0);
		break;
	    }
	    /* --END ERROR HANDLING-- */

	    buf_off = sfirst - rfirst;
	    if (buf_off > 0)
	    {
		MPIU_DBG_MSG_FMT(CH3_OTHER, VERBOSE, (MPIU_DBG_FDEST,
                  "moved " MPIDI_MSG_SZ_FMT " bytes to the beginning of the tmp buffer", buf_off));
		memmove(buf, buf_end - buf_off, buf_off);
	    }
	}

	*rsz = rfirst;
	MPIU_Free(buf);
    }

  fn_exit:
    MPIDI_FUNC_EXIT(MPID_STATE_MPIDI_CH3U_BUFFER_COPY);
}

/*
 * This routine is called by mpid_recv and mpid_irecv when a request
 * matches a send-to-self message
 */
int MPIDI_CH3_RecvFromSelf( MPID_Request *rreq, void *buf, int count,
			    MPI_Datatype datatype )
{
    MPID_Request * const sreq = rreq->partner_request;

    if (sreq != NULL)
    {
	MPIDI_msg_sz_t data_sz;

	MPIDI_CH3U_Buffer_copy(sreq->dev.user_buf, sreq->dev.user_count,
			       sreq->dev.datatype, &sreq->status.MPI_ERROR,
			       buf, count, datatype, &data_sz,
			       &rreq->status.MPI_ERROR);
	rreq->status.count = (int)data_sz;
	MPID_REQUEST_SET_COMPLETED(sreq);
	MPID_Request_release(sreq);
    }
    else
    {
	/* The sreq is missing which means an error occurred.
	   rreq->status.MPI_ERROR should have been set when the
	   error was detected. */
    }

    /* no other thread can possibly be waiting on rreq, so it is safe to
       reset ref_count and cc */
    /* FIXME DJG really? shouldn't we at least decr+assert? */
    MPID_cc_set(rreq->cc_ptr, 0);
    MPIU_Object_set_ref(rreq, 1);

    return MPI_SUCCESS;
}


text:
<!DOCTYPE html>

<title><#:C('sitename')#>--会员中心</title>
<meta name="keywords" content="<#:C('keyword')#>"/>
<meta name="description" content="<#:C('content')#>"/>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<include file="Pub:Css"/>

   <include file="Pub:top"/>
   <include file="Pub:nav"/>

 <a href="<#:U('user/index')#>" title="返回首页" class="tip-bottom">首页

网站设置

编辑

        <form action="<#:U('index/web/doset')#>" method="post" class="form-horizontal">

              网站名称 :

                <input type="text" class="span11" placeholder="网站名称"  name="shopname" id="shopname" value="<#$wapinfo.shopname#>" />
              	 微官网名称,显示在微官网顶部。

              联系电话 :

                <input type="text"  class="span11" placeholder="联系电话"  name="tel" id="tel" value="<#$wapinfo.tel#>" maxlength="15"/>

              联系地址 :

                <input type="text" class="span11" placeholder="店铺地址 " name="address" id="address" value="<#$wapinfo.address#>"/>

              店铺介绍/促销信息 :

                <textarea rows="4" class="span11" name="info" id="txta1"><#$wapinfo.info#></textarea>
             此信息将展示到首页认证页面。

              地图标识 :

               <input type="text" class="span4" placeholder="输入地址查询 " name="mapsearch" id="mapsearch" value="<#$wapinfo.address#>"/><button type="button" class="btn btn-info" onclick="GetAdd();">查询</button>

              坐标 :

                <input type="text" class="span6" placeholder="坐标 " name="point" id="point" readonly="true" value="<#$wapinfo.point_x#>,<#$wapinfo.point_y#>"/>

            <input type="hidden" name="point_x" id="point_x" readonly="true" value="<#$wapinfo.point_x#>"/>
                <input type="hidden"  name="point_y" id="point_y" readonly="true"  value="<#$wapinfo.point_y#>"/>

              <button type="submit" class="btn btn-success">保存</button>

          </form>

   <include file="Pub:foot"/>


text:
import GafferImageUI # For ImageReaderPathPreview
import GafferSceneUI # For SceneReaderPathPreview

try :
	import GafferCortexUI
except ImportError :
	pass


text:
tools
=====

Collection of different tools...

gem install
$ tools


text:
using C5;
using System;
using System.Collections.Generic;

namespace AI.Search.SearchFringes
{
    public abstract class PriorityQueueDrivenFringeBase<TState> : IFringeStrategy<TState>
    {
        private readonly IPriorityQueue<PriorityWrapper> items = new IntervalHeap<PriorityWrapper>(new OrderWrapperComparer());

        public abstract int GetQueueOrder(TState state);

        public void Add(TState state)
        {
            if (state == null)
            {
                throw new ArgumentNullException(nameof(state));
            }
            var order = GetQueueOrder(state);
            items.Add(new PriorityWrapper(state, order));
        }

        public TState GetNext()
        {
            if (IsEmpty())
            {
                throw new InvalidOperationException("Fringe is empty");
            }

            // Take lowest priority as we're defining priority to be it's order
            var wrapper = items.DeleteMin();
            return wrapper.State;
        }

        public bool IsEmpty()
        {
            return items.IsEmpty;
        }

        private class PriorityWrapper
        {
            public TState State { get; }
            public long Priority { get; }

            public PriorityWrapper(TState state, long priority)
            {
                State = state;
                Priority = priority;
            }
        }

        private class OrderWrapperComparer : IComparer<PriorityWrapper>
        {
            public int Compare(PriorityWrapper x, PriorityWrapper y)
            {
                return x.Priority.CompareTo(y.Priority);
            }
        }
    }
}


text:
"""
    Talon.One API

    Use the Talon.One API to integrate with your application and to manage applications and campaigns:  - Use the operations in the [Integration API section](#integration-api) are used to integrate with our platform - Use the operation in the [Management API section](#management-api) to manage applications and campaigns.  ## Determining the base URL of the endpoints  The API is available at the same hostname as your Campaign Manager deployment. For example, if you are reading this page at `https://mycompany.talon.one/docs/api/`, the URL for the [updateCustomerSession](https://docs.talon.one/integration-api/#operation/updateCustomerSessionV2) endpoint is `https://mycompany.talon.one/v2/customer_sessions/{Id}`   # noqa: E501

    The version of the OpenAPI document: 1.0.0
    Generated by: https://openapi-generator.tech
"""

from __future__ import absolute_import

import unittest
import datetime

import talon_one
from talon_one.models.inline_response20013 import InlineResponse20013  # noqa: E501
from talon_one.rest import ApiException

class TestInlineResponse20013(unittest.TestCase):
    """InlineResponse20013 unit test stubs"""

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def make_instance(self, include_optional):
        """Test InlineResponse20013
            include_option is a boolean, when False only required
            params are included, when True both required and
            optional params are included """
        # model = talon_one.models.inline_response20013.InlineResponse20013()  # noqa: E501
        if include_optional :
            return InlineResponse20013(
                has_more = True,
                data = [
                    talon_one.models.access_log_entry.AccessLogEntry(
                        uuid = '0',
                        status = 56,
                        method = '0',
                        request_uri = '0',
                        time = datetime.datetime.strptime('2013-10-20 19:20:30.00', '%Y-%m-%d %H:%M:%S.%f'),
                        request_payload = '0',
                        response_payload = '0', )
                    ]
            )
        else :
            return InlineResponse20013(
                has_more = True,
                data = [
                    talon_one.models.access_log_entry.AccessLogEntry(
                        uuid = '0',
                        status = 56,
                        method = '0',
                        request_uri = '0',
                        time = datetime.datetime.strptime('2013-10-20 19:20:30.00', '%Y-%m-%d %H:%M:%S.%f'),
                        request_payload = '0',
                        response_payload = '0', )
                    ],
        )

    def testInlineResponse20013(self):
        """Test InlineResponse20013"""
        inst_req_only = self.make_instance(include_optional=False)
        inst_req_and_optional = self.make_instance(include_optional=True)

if __name__ == '__main__':
    unittest.main()


text:
alter table person add column gender varchar(10) not null default 'Unknown'
   check(gender = 'Unknown' or gender='Male' or gender='Female');

# --- !Downs

alter table person drop column gender;


text:
var fixture = '\

\

content
\

\

\

\

content
\

\
';

var ele2tagname = function ( ele ) { return ele.tagName; };

describe ( 'Manipulation', { beforeEach: getFixtureInit ( fixture ) }, function ( it ) {

  QUnit.test ( 'inserted script tags get executed', function ( assert ) { // For some reason we can't use our nice helpers for async assertions :(

    var sync = [
      ['', '__script_test__', 1],
      ['', '__script_test__', 2],
      ['', '__script_test__', 3],
      ['', '__script_test__', 4],
      ['', '__script_test__', 4],
      ['

', '__script_test__', 5],
      ['', '__script_test__', 6]
    ];

    sync.forEach ( function ( test ) {

      $(test[0]).appendTo ( '.anchor' );

      assert.is ( window[test[1]], test[2] );

    });

    var async = [
      ['', '__script_test_async2__', 2],
      ['', '__script_test_async1__', 1]
    ];

    if ( !/(mac\sos\sx)\s?([\w\s\.]*)/i.test ( navigator.userAgent ) && !/(macintosh|mac(?=_powerpc)\s)/i.test ( navigator.userAgent ) ) return; //FIXME: For some reason some browsers don't support some of these, and I don't think its our fault

    async.forEach ( function ( test ) {

      var done = assert.async ();

      $(test[0]).appendTo ( '.anchor' );

      setTimeout ( function () {
        assert.is ( window[test[1]], test[2] );
        done ();
      }, 100 );

    });

  });

  describe ( '$.fn.after', function ( it ) {

    it ( 'inserts a selector after', function ( t ) {

      $('.anchor').after ( '<c></c>' );

      var prev = $('.anchor').prevAll ();
      var next = $('.anchor').nextAll ();

      t.is ( prev.length, 0 );
      t.is ( next.length, 3 );
      t.deepEqual ( $('.parent').children ().slice ( 1 ).get ().map ( ele2tagname ), ['A', 'B', 'C'] );

    });

    it ( 'inserts multiple selectors after', function ( t ) {

      $('.anchor').after ( '', '<c></c>' );

      var prev = $('.anchor').prevAll ();
      var next = $('.anchor').nextAll ();

      t.is ( prev.length, 0 );
      t.is ( next.length, 3 );
      t.deepEqual ( $('.parent').children ().slice ( 1 ).get ().map ( ele2tagname ), ['A', 'B', 'C'] );

    });

    it ( 'supports non-element nodes', function ( t ) {

      var ele = $('
 dearworld
');

      ele.find ( 'span' ).after ( 'hello, ' );

      t.is ( ele.html (), ' dearhello, world' );

    });

  });

  describe ( '$.fn.append', function ( it ) {

    it ( 'appends a selector', function ( t ) {

      $('.parent').append ( '<c></c>' );

      var prev = $('.anchor').prevAll ();
      var next = $('.anchor').nextAll ();

      t.is ( prev.length, 0 );
      t.is ( next.length, 3 );
      t.deepEqual ( $('.parent').children ().slice ( 1 ).get ().map ( ele2tagname ), ['A', 'B', 'C'] );

    });

    it ( 'appends multiple selectors', function ( t ) {

      $('.parent').append ( '', '<c></c>' );

      var prev = $('.anchor').prevAll ();
      var next = $('.anchor').nextAll ();

      t.is ( prev.length, 0 );
      t.is ( next.length, 3 );
      t.deepEqual ( $('.parent').children ().slice ( 1 ).get ().map ( ele2tagname ), ['A', 'B', 'C'] );

    });

    it ( 'supports non-element nodes', function ( t ) {

      var ele = $('
world
');

      ele.append ( 'hello, ' );

      t.is ( ele.html (), 'worldhello, ' );

    });

    it ( 'doesn\'t throw with undefined', function ( t ) {

      $('.anchor').append ( undefined );

      t.pass ();

    });

  });

  describe ( '$.fn.appendTo', function ( it ) {

    it ( 'appends this to a selector', function ( t ) {

      $( '<c></c>' ).appendTo ( '.parent' );

      var prev = $('.anchor').prevAll ();
      var next = $('.anchor').nextAll ();

      t.is ( prev.length, 0 );
      t.is ( next.length, 3 );
      t.deepEqual ( $('.parent').children ().slice ( 1 ).get ().map ( ele2tagname ), ['A', 'B', 'C'] );

    });

  });

  describe ( '$.fn.before', function ( it ) {

    it ( 'inserts a selector before', function ( t ) {

      $('.anchor').before ( '<c></c>' );

      var prev = $('.anchor').prevAll ();
      var next = $('.anchor').nextAll ();

      t.is ( prev.length, 3 );
      t.is ( next.length, 0 );
      t.deepEqual ( $('.parent').children ().slice ( 0, 3 ).get ().map ( ele2tagname ), ['A', 'B', 'C'] );

    });

    it ( 'inserts multiple selectors after', function ( t ) {

      $('.anchor').before ( '', '<c></c>' );

      var prev = $('.anchor').prevAll ();
      var next = $('.anchor').nextAll ();

      t.is ( prev.length, 3 );
      t.is ( next.length, 0 );
      t.deepEqual ( $('.parent').children ().slice ( 0, 3 ).get ().map ( ele2tagname ), ['A', 'B', 'C'] );

    });

    it ( 'supports non-element nodes', function ( t ) {

      var ele = $('
world dear
');

      ele.find ( 'span' ).before ( 'hello, ' );

      t.is ( ele.html (), 'worldhello,  dear' );

    });

  });

  describe ( '$.fn.clone', function ( it ) {

    it ( 'clones all elements', function ( t ) {

      var original = $('#qunit-fixture *');
      var cloned = original.clone ();

      t.is ( original.length, cloned.length );
      t.not ( original[0], cloned[0] );
      t.is ( original[0].className, cloned[0].className );

    });

  });

  describe ( '$.fn.detach', function ( it ) {

    it ( 'detaches all elements and preserves their event handlers', function ( t ) {

      var count = 0;
      var anchor = $('.anchor');

      function handler () {
        count++;
      }

      anchor.on ( 'foo', handler );
      anchor.detach ();
      anchor.appendTo ( '.parent' );
      anchor.trigger ( 'foo' );
      anchor.detach ();
      anchor.trigger ( 'foo' );

      t.is ( $('.anchor').length, 0 );
      t.is ( count, 2 );

    });

    it ( 'supports an optional selector', function ( t ) {

      var eles = $('.parent').parent ().children ();

      eles.detach ( '.aunt' );

      t.is ( $('.parent').parent ().children ().length, 2 );
      t.is ( $('.aunt').length, 0 );

    });

  });

  describe ( '$.fn.empty', function ( it ) {

    it ( 'empties all elements', function ( t ) {

      var parent = $('.parent');

      parent.empty ();

      t.is ( parent.contents ().length, 0 );

    });

    it ( 'supports multiple elements in the collection', function ( t ) {

      var parent = $('.parent');
      var aunt = $('.aunt');
      var parents = parent.add ( aunt );

      parents.empty ();

      t.is ( parent.contents ().length, 0 );
      t.is ( aunt.contents ().length, 0 );

    });

  });

  describe ( '$.fn.html', function ( it ) {

    it ( 'gets the html', function ( t ) {

      var parent = $('.parent');

      t.is ( parent.html ().trim (), '
content
' );

    });

    it ( 'sets html strings', function ( t ) {

      var anchor = $('.anchor');
      var html = '

';

      anchor.html ( html );

      t.is ( anchor.html (), html );
      t.is ( $('.foo').length, 1 );

    });

    it ( 'sets plain string', function ( t ) {

      var anchor = $('.anchor');
      var html = 'foo';

      anchor.html ( html );

      t.is ( anchor.html (), html );

    });

    it ( 'sets numbers', function ( t ) {

      var anchor = $('.anchor');

      anchor.html ( 0 );

      t.is ( anchor.html (), '0' );

    });

    it ( 'ignores non-elements objects in the collections', function ( t ) {

      var eles = $('
hi there
');
      var actual = [];
      var expected = [];

      eles.contents ().html ( 'bold' ).each ( function ( i, ele ) {
        var html = $(ele).html ();
        expected.push ( this.nodeType === 1 ? 'bold' : undefined );
        actual.push ( html ? html.toLowerCase () : html );
      });

      t.deepEqual ( actual, expected );

    });

  });

  describe ( '$.fn.insertAfter', function ( it ) {

    it ( 'inserts this after a selector', function ( t ) {

      $('<c></c>').insertAfter ( '.anchor' );

      var prev = $('.anchor').prevAll ();
      var next = $('.anchor').nextAll ();

      t.is ( prev.length, 0 );
      t.is ( next.length, 3 );
      t.deepEqual ( $('.parent').children ().slice ( 1 ).get ().map ( ele2tagname ), ['A', 'B', 'C'] );

    });

  });

  describe ( '$.fn.insertBefore', function ( it ) {

    it ( 'inserts this before a selector', function ( t ) {

      $('<c></c>').insertBefore ( '.anchor' );

      var prev = $('.anchor').prevAll ();
      var next = $('.anchor').nextAll ();

      t.is ( prev.length, 3 );
      t.is ( next.length, 0 );
      t.deepEqual ( $('.parent').children ().slice ( 0, 3 ).get ().map ( ele2tagname ), ['A', 'B', 'C'] );

    });

  });

  describe ( '$.fn.prepend', function ( it ) {

    it ( 'prepends a selector', function ( t ) {

      $('.parent').prepend ( '<c></c>' );

      var prev = $('.anchor').prevAll ();
      var next = $('.anchor').nextAll ();

      t.is ( prev.length, 3 );
      t.is ( next.length, 0 );
      t.deepEqual ( $('.parent').children ().slice ( 0, 3 ).get ().map ( ele2tagname ), ['A', 'B', 'C'] );

    });

    it ( 'prepends multiple selectors', function ( t ) {

      $('.parent').prepend ( '', '<c></c>' );

      var prev = $('.anchor').prevAll ();
      var next = $('.anchor').nextAll ();

      t.is ( prev.length, 3 );
      t.is ( next.length, 0 );
      t.deepEqual ( $('.parent').children ().slice ( 0, 3 ).get ().map ( ele2tagname ), ['A', 'B', 'C'] );

    });

    it ( 'supports non-element nodes', function ( t ) {

      var ele = $('
world
');

      ele.prepend ( 'hello, ' );

      t.is ( ele.html (), 'hello, world' );

    });

    it ( 'doesn\'t throw with undefined', function ( t ) {

      $('.anchor').prepend ( undefined );

      t.pass ();

    });

  });

  describe ( '$.fn.prependTo', function ( it ) {

    it ( 'prepends this to a selector', function ( t ) {

      $('<c></c>').prependTo ( '.parent' );

      var prev = $('.anchor').prevAll ();
      var next = $('.anchor').nextAll ();

      t.is ( prev.length, 3 );
      t.is ( next.length, 0 );
      t.deepEqual ( $('.parent').children ().slice ( 0, 3 ).get ().map ( ele2tagname ), ['A', 'B', 'C'] );

    });

  });

  describe ( '$.fn.remove', function ( it ) {

    it ( 'detaches all elements and removes their event handlers', function ( t ) {

      var count = 0;
      var anchor = $('.anchor');

      function handler () {
        count++;
      }

      anchor.on ( 'foo', handler );
      anchor.remove ();
      anchor.prependTo ( '.form-fixture' );
      anchor.trigger ( 'foo' );
      anchor.remove ();
      anchor.trigger ( 'foo' );

      t.is ( $('.anchor').length, 0 );
      t.is ( count, 0 );

    });

    it ( 'supports an optional selector', function ( t ) {

      var eles = $('.parent').parent ().children ();

      eles.remove ( '.aunt' );

      t.is ( $('.parent').parent ().children ().length, 2 );
      t.is ( $('.aunt').length, 0 );

    });

  });

  describe ( '$.fn.replaceAll', function ( it ) {

    it ( 'replaces a selector with this', function ( t ) {

      var parent = $('.parent');
      var html = '

';

      $('
').replaceAll ( '.anchor' );

      t.is ( parent.html ().trim (), html );
      t.is ( $('.anchor').length, 0 );
      t.is ( $('.parent p').length, 1 );

    });

    it ( 'supports multiple elements', function ( t ) {

      var toReplace = $('.parent, .uncle, .aunt');
      var html = '

';

      $(html).replaceAll ( toReplace );

      t.is ( $('#qunit-fixture p').length, 3 );

    });

  });

  describe ( '$.fn.replaceWith', function ( it ) {

    it ( 'replaces this with a selector', function ( t ) {

      var parent = $('.parent');
      var anchor = $('.anchor');
      var html = '

';

      anchor.replaceWith ( html );

      t.is ( parent.html ().trim (), html );
      t.is ( $('.anchor').length, 0 );
      t.is ( $('.parent p').length, 1 );

    });

    it ( 'supports multiple elements', function ( t ) {

      var toReplace = $('.parent, .uncle, .aunt');
      var html = '

';

      toReplace.replaceWith ( html );

      t.is ( $('#qunit-fixture p').length, 3 );

    });

  });

  describe ( '$.fn.text', function ( it ) {

    it ( 'gets the text', function ( t ) {

      var anchor = $('.anchor');

      t.is ( anchor.text (), 'content' );

    });

    it ( 'sets html strings', function ( t ) {

      var anchor = $('.anchor');
      var text = '
foo
';

      anchor.text ( text );

      t.is ( anchor.text (), text );

    });

    it ( 'sets plain strings', function ( t ) {

      var anchor = $('.anchor');
      var text = 'foo';

      anchor.text ( text );

      t.is ( anchor.text (), text );

    });

    it ( 'sets numbers', function ( t ) {

      var anchor = $('.anchor');

      anchor.text ( 0 );

      t.is ( anchor.text (), '0' );

    });

    it ( 'supports empty collections', function ( t ) {

      var ele = $();

      t.is ( ele.text (), '' );

    });

  });

  describe ( '$.fn.unwrap', function ( it ) {

    it ( 'unwraps each element', function ( t ) {

      var anchor = $('.anchor');

      anchor.unwrap ();

      t.is ( $('.parent').length, 0 );
      t.deepEqual ( anchor.parent ().get (), $('#qunit-fixture').get () );

    });

    it ( 'doesn\'t unwrap immediate children of the body', function ( t ) {

      var ele = $('

').appendTo ( document.body );

      ele.unwrap ();

      t.is ( $('#foo').length, 1 );

      ele.remove ();

    });

  });

  describe ( '$.fn.wrap', function ( it ) {

    it ( 'wraps a structure around each element', function ( t ) {

      var eles = $('.uncle, .aunt');
      var wrapper = '

';

      eles.wrap ( wrapper );

      t.is ( eles.parent ().filter ( '.wrapper' ).length, 2 );

    });

    it ( 'supports nested structures', function ( t ) {

      var eles = $('.uncle, .aunt');
      var wrapper = '

';

      eles.wrap ( wrapper );

      t.is ( eles.parent ().filter ( '.nested' ).length, 2 );
      t.is ( eles.parent ().parent ().filter ( '.wrapper' ).length, 2 );

    });

    it ( 'supports non-element nodes', function ( t ) {

      var ele = $('
hi there
');
      var contents = ele.contents ();

      contents.wrap ( '' );

      t.is ( ele.find ( 'i' ).length, 3 );
      t.is ( ele.find ( 'i' ).text (), contents.text () );

    });

  });

  describe ( '$.fn.wrapAll', function ( it ) {

    it ( 'wraps a structure around all elements', function ( t ) {

      var eles = $('.uncle, .aunt');
      var wrapper = '

';

      eles.wrapAll ( wrapper );

      t.is ( eles.parent ().filter ( '.wrapper' ).length, 1 );

    });

    it ( 'supports nested structures', function ( t ) {

      var eles = $('.uncle, .aunt');
      var wrapper = '

';

      eles.wrapAll ( wrapper );

      t.is ( eles.parent ().filter ( '.nested' ).length, 1 );
      t.is ( eles.parent ().parent ().filter ( '.wrapper' ).length, 1 );

    });

    it ( 'doesn\'t clone elements', function ( t ) {

      var ele = $('

');

      ele.find ( 'a' ).wrapAll ( '' );

      t.is ( ele.html (), '' );

    });

  });

  describe ( '$.fn.wrapInner', function ( it ) {

    it ( 'wraps a struncture around all contents', function ( t ) {

      var eles = $('.anchor, .uncle');
      var wrapper = '

';

      eles.wrapInner ( wrapper );

      t.is ( $( eles[0] ).html ().trim (), '
content
' );
      t.is ( $( eles[1] ).html (), '

' );

    });

    it ( 'supports nested structures', function ( t ) {

      var eles = $('.anchor, .uncle');
      var wrapper = '

';

      eles.wrapInner ( wrapper );

      t.is ( $( eles[0] ).html ().trim (), '

content

' );
      t.is ( $( eles[1] ).html (), '

' );

    });

  });

});


text:
import { combineReducers } from 'redux';

import dataPopup from './dataPopup.js';
import slidePanel from './slidePanel.js';
import searchBar from './searchBar.js';
import map from './map.js';
import tweets from './tweets.js';
import language from './language.js';

import { routeReducer } from 'redux-simple-router';

export default combineReducers({
  dataPopup,
  slidePanel,
  searchBar,
  map,
  tweets,
  language,

  routing: routeReducer
});


text:
package io.getquill.context.jdbc

import io.getquill._
import io.getquill.context.sql.{ TestDecoders, TestEncoders }

package object oracle {

  object testContext extends OracleJdbcContext(Literal, "testOracleDB") with TestEntities with TestEncoders with TestDecoders

}


text:
<?xml version="1.0"?>
<entry type="method" name="jQuery.hasData" return="Boolean">
  <title>jQuery.hasData()</title>
  <signature>
    <added>1.5</added>
    <argument name="element" type="Element">
      <desc>A DOM element to be checked for data.</desc>
    </argument>
  </signature>
  <desc>Determine whether an element has any jQuery data associated with it.</desc>
  <longdesc>

The jQuery.hasData() method provides a way to determine if an element currently has any values that were set using jQuery.data(). If there is no data object associated with an element, the method returns false; otherwise it returns true.

The primary advantage of jQuery.hasData(element) is that it does not create and associate a data object with the element if none currently exists. In contrast, jQuery.data(element) always returns a data object to the caller, creating one if no data object previously existed.

Note that jQuery's event system uses the jQuery data API to store event handlers. Therefore, binding an event to an element using .on(), .bind(), .live(), .delegate(), or one of the shorthand event methods also associates a data object with that element.

  </longdesc>
  <example>
    <desc>Set data on an element and see the results of hasData.</desc>
    <![CDATA[
var $p = jQuery( "p" ), p = $p[ 0 ];
$p.append( jQuery.hasData( p ) + " " ); // false

$.data( p, "testing", 123 );
$p.append( jQuery.hasData( p ) + " " ); // true

$.removeData( p, "testing" );
$p.append( jQuery.hasData( p ) + " " ); // false

$p.on( "click", function() {} );
$p.append( jQuery.hasData( p ) + " " ); // true

$p.off( "click" );
$p.append( jQuery.hasData( p ) + " " ); // false
]]>
    <![CDATA[

Results:

]]>
  </example>
  <category slug="data"/>
  <category slug="version/1.5"/>
</entry>


text:
/**
 * Creates an ve.ui.Layout object.
 *
 * @class
 * @abstract
 * @extends ve.Element
 * @mixin OO.EventEmitter
 *
 * @constructor
 * @param {Object} [config] Configuration options
 */
ve.ui.Layout = function VeUiLayout( config ) {
	// Initialize config
	config = config || {};

	// Parent constructor
	ve.Element.call( this, config );

	// Mixin constructors
	OO.EventEmitter.call( this );

	// Initialization
	this.$.addClass( 've-ui-layout' );
};

/* Inheritance */

OO.inheritClass( ve.ui.Layout, ve.Element );

OO.mixinClass( ve.ui.Layout, OO.EventEmitter );


text:
[![CI Status](http://img.shields.io/travis/Joachim Schuster/PodInfoController.svg?style=flat)](https://travis-ci.org/Joachim Schuster/PodInfoController)
[![Version](https://img.shields.io/cocoapods/v/PodInfoController.svg?style=flat)](http://cocoadocs.org/docsets/PodInfoController)
[![License](https://img.shields.io/cocoapods/l/PodInfoController.svg?style=flat)](http://cocoadocs.org/docsets/PodInfoController)
[![Platform](https://img.shields.io/cocoapods/p/PodInfoController.svg?style=flat)](http://cocoadocs.org/docsets/PodInfoController)

## Usage

To run the example project, clone the repo, and run `pod install` from the Example directory first.

## Requirements

## Installation

PodInfoController is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

    pod "PodInfoController"

## Author

Joachim Schuster, joachim.schuster@venqoo.com

## License

PodInfoController is available under the MIT license. See the LICENSE file for more info.


text:
/*
 * decaffeinate suggestions:
 * DS102: Remove unnecessary code created because of implicit returns
 * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
 */
const benv = require("benv")
const Backbone = require("backbone")
const sinon = require("sinon")
const path = require("path")
const Artworks = require("../../../collections/artworks.coffee")
const FilterArtworks = require("../../../collections/filter_artworks.coffee")
const Artists = require("../../../collections/artists.coffee")
const Gene = require("../../../models/gene.coffee")
const { fabricate } = require("@artsy/antigravity")

xdescribe("GeneArtworksView", function () {
  // FIXME: conflicts with jsdom in beforeEach from filter2
  beforeEach(function (done) {
    return benv.setup(() => {
      // artworks = new Artworks [fabricate('artwork'), fabricate('artwork'), fabricate('artwork')]
      let module
      const artworks = new FilterArtworks([
        fabricate("artwork"),
        fabricate("artwork"),
        fabricate("artwork"),
      ])
      // artworks.url = "/api/v1/filter/artworks?gene_id=foo"
      // artworks.parse = sinon.stub()
      const gene = new Gene(fabricate("gene", { type: { name: "medium" } }))
      benv.render(path.resolve(__dirname, "../templates/index.jade"), {
        sd: { PARAMS: { gene_id: gene.id } },
        asset() {},
        gene,
      })
      benv.expose({ $: benv.require("jquery") })
      Backbone.$ = $
      $.fn.error = sinon.stub()
      this.e = new $.Event("click")
      sinon.stub(Backbone, "sync")
      const filename = path.resolve(__dirname, "../client.coffee")
      const { GeneArtworksView } = (module = benv.requireWithJadeify(filename, [
        "artworkColumnsTemplate",
      ]))
      this.PoliteInfiniteScrollView = module.__get__("PoliteInfiniteScrollView")
      this.politeScroll = sinon.stub(
        this.PoliteInfiniteScrollView.prototype,
        "initialize"
      )
      this.view = new GeneArtworksView({
        collection: artworks,
        el: $("body"),
        model: gene,
        params: {},
      })
      this.view.params = {}
      return done()
    })
  })

  afterEach(function () {
    benv.teardown()
    Backbone.sync.restore()
    return this.politeScroll.restore()
  })

  return describe("#readMore", function () {
    it("initially covers text with fade", () =>
      $(".gene-read-more-fade").css("display").should.not.containEql("none"))

    return it("shows rest of description on click", function () {
      this.view.readMore(this.e)
      return $(".gene-description-text")
        .css("max-height")
        .should.containEql(9999)
    })
  })
})

describe("GeneArtistsView", () => {
  let e
  let view
  let politeScroll
  beforeEach(done => {
    benv.setup(() => {
      let module
      const artists = new Artists([
        fabricate("artist"),
        fabricate("artist"),
        fabricate("artist"),
      ])
      artists.url = "/api/v1/search/filtered/gene/foo"
      const gene = new Gene(fabricate("gene"))
      benv.expose({ $: benv.require("jquery") })
      $.fn.error = sinon.stub()
      e = new $.Event("click")
      benv.render(path.resolve(__dirname, "../templates/index.jade"), {
        sd: {},
        asset() {},
        gene,
      })
      sinon.stub(Backbone, "sync")
      const filename = path.resolve(__dirname, "../client.coffee")
      const { GeneArtistsView } = (module = benv.requireWithJadeify(filename, [
        "artistTemplate",
      ]))
      const PoliteInfiniteScrollView = module.__get__(
        "PoliteInfiniteScrollView"
      )
      politeScroll = sinon.stub(
        PoliteInfiniteScrollView.prototype,
        "initialize"
      )
      Backbone.$ = $
      view = new GeneArtistsView({
        collection: artists,
        el: $("body"),
        model: gene,
        params: {},
      })
      view.params = {}
      done()
    })
  })

  afterEach(function () {
    benv.teardown()
    Backbone.sync.restore()
    politeScroll.restore()
  })

  describe("#initialize", () => {
    it("should fetch one more page", () => {
      view.onInitialFetch()
      Backbone.sync.callCount.should.equal(1)
    })
  })

  describe("#onSync", () => {
    it("shows correct message when no artists are available", () => {
      view.collection = []
      view.onSync()
      view
        .$("#gene-artists-empty-message")
        .css("display")
        .should.not.containEql("none")
    })

    it("adds collection to page when artists are available", () => {
      view.onSync()
      view.$("#gene-artists-empty-message").css("display").should.equal("none")
      view.$("#gene-artists-container a").length.should.equal(3)
    })
  })

  describe("#readMore", () => {
    it("initially covers text with fade", () => {
      view
        .$(".gene-read-more-fade")
        .css("display")
        .should.not.containEql("none")
    })

    it("shows rest of description on click", () => {
      view.readMore(e)
      view.$(".gene-description-text").css("max-height").should.containEql(9999)
    })
  })
})


text:
<carbon.widget.FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorSurface"
    android:clickable="true"
    android:focusable="true"
    app:carbon_rippleColor="?attr/carbon_rippleColor">

    <carbon.widget.LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/carbon_defaultHighlightColorPrimary"
        android:baselineAligned="false"
        android:duplicateParentState="true"
        android:orientation="horizontal"
        android:paddingLeft="@dimen/carbon_toolbarItemMargin"
        android:paddingRight="@dimen/carbon_toolbarItemMargin">

        <carbon.widget.CheckBox
            android:id="@+id/checkBox"
            style="@style/carbon_CheckBox.IconButton"
            android:layout_gravity="center"
            android:clickable="false"
            android:focusable="false"
            app:carbon_rippleColor="@null" />

        <carbon.widget.TextView
            android:id="@+id/text"
            android:layout_width="0dp"
            android:layout_height="@dimen/carbon_toolbarHeight"
            android:layout_weight="1"
            android:gravity="center_vertical"
            android:paddingLeft="@dimen/carbon_padding"
            android:paddingRight="@dimen/carbon_padding"
            android:textAppearance="?attr/carbon_textAppearanceBody2"
            tools:text="item name" />

        <carbon.widget.ImageView
            android:id="@+id/reorder"
            style="@style/carbon_ImageView.Icon"
            android:layout_width="@dimen/carbon_toolbarItemSize"
            android:layout_height="@dimen/carbon_toolbarItemSize"
            android:layout_gravity="center"
            app:carbon_src="@drawable/ic_drag_handle_black_24dp" />
    </carbon.widget.LinearLayout>
</carbon.widget.FrameLayout>


text:
using namespace ndnrtc;
using namespace webrtc;
using namespace std;

//******************************************************************************
//******************************************************************************
#pragma mark - construction/destruction
NdnAudioChannel::NdnAudioChannel(const ParamsStruct &params, VoiceEngine *voiceEngine):
NdnRtcObject(params)
{
    voe_network_ = VoENetwork::GetInterface(voiceEngine);
    voe_base_ = VoEBase::GetInterface(voiceEngine);
}
NdnAudioChannel::~NdnAudioChannel()
{
    voe_base_->DeleteChannel(channel_);
    voe_base_->Release();
    voe_network_->Release();
}

//******************************************************************************
#pragma mark - public
int NdnAudioChannel::init(shared_ptr<Face> &face)
{
    if (initialized_)
        return notifyError(RESULT_ERR, "audio channel already initialized");

    // setup voice channel
    channel_ = voe_base_->CreateChannel();

    if (channel_ < 0)
        return notifyError(RESULT_ERR, "can't instantiate WebRTC voice channel \
                           due to error (code: %d)", voe_base_->LastError());

    return RESULT_OK;
}

int NdnAudioChannel::start()
{
    if (!initialized_)
        return notifyError(RESULT_ERR, "audio channel was not initialized");

    if (started_)
        return notifyError(RESULT_ERR, "audio channel already started");

    return RESULT_OK;
}

int NdnAudioChannel::stop()
{
    if (!started_)
        return notifyError(RESULT_ERR, "audio channel was not started");

    return RESULT_OK;
}

//******************************************************************************
#pragma mark - intefaces realization - webrtc::Transport callbacks
int NdnAudioChannel::SendPacket(int channel, const void *data, int len)
{
    TRACE("sending RTP is not supposed to be called");
    return len;
}

int NdnAudioChannel::SendRTCPPacket(int channel, const void *data, int len)
{
    TRACE("sending RTCP is not supposed to be called");
    return len;
}

//******************************************************************************
//******************************************************************************
#pragma mark - construction/destruction
NdnAudioReceiveChannel::NdnAudioReceiveChannel(const ParamsStruct &params,
                                               webrtc::VoiceEngine *voiceEngine):
NdnAudioChannel(params, voiceEngine),
audioReceiver_(new NdnAudioReceiver(params))
{
    this->setLogger(new NdnLogger(NdnLoggerDetailLevelAll,
                                  "fetch-achannel-%s.log",
                                  params.producerId));
    isLoggerCreated_ = true;

    audioReceiver_->setObserver(this);
    audioReceiver_->setFrameConsumer(this);
    audioReceiver_->setLogger(logger_);
}

//******************************************************************************
#pragma mark - public
int NdnAudioReceiveChannel::init(shared_ptr<Face> &face)
{
    int res = NdnAudioChannel::init(face);

    if (RESULT_FAIL(res))
        return res;

    if (RESULT_GOOD((res = audioReceiver_->init(face))))
    {
        initialized_ = true;
        DBG("audio receive channel initialized");
    }

    return res;
}

int NdnAudioReceiveChannel::start()
{
    int res = NdnAudioChannel::start();

    if (RESULT_FAIL(res))
        return res;

    // register external transport in order to playback. however, we are not
    // going to set this channel for sending and should not be getting callback
    // on webrtc::Transport callbacks
    if (voe_network_->RegisterExternalTransport(channel_, *this) < 0)
        return notifyError(RESULT_ERR, "can't register external transport for "
                           "WebRTC due to error (code %d)",
                           voe_base_->LastError());

    if (voe_base_->StartReceive(channel_) < 0)
        return notifyError(RESULT_ERR, "can't start receiving channel due to "
                           "WebRTC error (code %d)", voe_base_->LastError());

    if (voe_base_->StartPlayout(channel_) < 0)
        return notifyError(RESULT_ERR, "can't start playout audio due to WebRTC "
                           "error (code %d)", voe_base_->LastError());

    if (audioReceiver_)
        res = audioReceiver_->startFetching();

    started_ = RESULT_GOOD(res);

    if (started_)
        DBG("audio receive channel started");

    return (started_)?RESULT_OK :
    notifyError(RESULT_ERR, "audio receiver was not initialized");
}

int NdnAudioReceiveChannel::stop()
{
    if (RESULT_FAIL(NdnAudioChannel::stop()))
        return RESULT_ERR;

    audioReceiver_->stopFetching();
    voe_base_->StopPlayout(channel_);
    voe_base_->StopReceive(channel_);
    voe_network_->DeRegisterExternalTransport(channel_);
    channel_ = -1;

    started_ = false;
    DBG("audio receive channel stopped");
    return RESULT_OK;
}

void NdnAudioReceiveChannel::getStatistics(ReceiverChannelPerformance &stat)
{
    stat.nBytesPerSec_ = audioReceiver_->getDataRate();
    stat.interestFrequency_ = audioReceiver_->getInterestFrequency();
    stat.segmentsFrequency_ = audioReceiver_->getSegmentFrequency();

    stat.rtt_ = audioReceiver_->getLastRtt();
    stat.srtt_ = audioReceiver_->getSrtt();

    stat.nPlayed_ = audioReceiver_->getNPlayed();
    stat.nMissed_ = audioReceiver_->getNMissed();
    stat.nLost_ = audioReceiver_->getNLost();
    stat.nReceived_ = audioReceiver_->getNReceived();

    stat.jitterSize_ = audioReceiver_->getJitterOccupancy();
    stat.rebufferingEvents_ = audioReceiver_->getRebufferingEvents();
    stat.actualProducerRate_ = audioReceiver_->getActualProducerRate();

    stat.nSent_ = audioReceiver_->getBufferStat(FrameBuffer::Slot::StateNew);
    stat.nAssembling_ = audioReceiver_->getBufferStat(FrameBuffer::Slot::StateAssembling);
}

//******************************************************************************
#pragma mark - intefaces realization - IAudioPacketConsumer
void NdnAudioReceiveChannel::onRTPPacketReceived(unsigned int len,
                                                 unsigned char *data)
{
    if (voe_network_->ReceivedRTPPacket(channel_, data, len) < 0)
        notifyError(RESULT_WARN, "can't playback audio packet (RTP) due to WebRTC error "
                    "(code %d)", voe_base_->LastError());
}

void NdnAudioReceiveChannel::onRTCPPacketReceived(unsigned int len,
                                                  unsigned char *data)
{
    if (voe_network_->ReceivedRTCPPacket(channel_, data, len) < 0)
        notifyError(RESULT_WARN, "can't playback audio packet (RTCP) due to WebRTC error "
                    "(code %d)", voe_base_->LastError());
}

//******************************************************************************
//******************************************************************************
#pragma mark - public
int NdnAudioSendChannel::init(shared_ptr<ndn::Transport> &transport)
{
    int res = RESULT_OK;
    shared_ptr<Face> nullFace(nullptr);

    if (RESULT_FAIL((res = NdnAudioChannel::init(nullFace))))
        return res;

    if (!audioSender_)
    {
        audioSender_ = new NdnAudioSender(params_);
        audioSender_->setObserver(this);
        audioSender_->setLogger(logger_);
    }

    if (RESULT_GOOD((res = audioSender_->init(transport))))
        initialized_ = true;

    DBG("initialized audio send channel");
    return res;
}

int NdnAudioSendChannel::start()
{
    int res = NdnAudioChannel::start();

    if (RESULT_FAIL(res))
        return res;

    res = voe_network_->RegisterExternalTransport(channel_, *this);

    if (res < 0)
        return notifyError(RESULT_ERR, "can't register external transport for "
                           "WebRTC due to error (code %d)",
                           voe_base_->LastError());

    if (voe_base_->StartSend(channel_) < 0)
        return notifyError(RESULT_ERR, "can't start send channel due to "
                           "WebRTC error (code %d)", voe_base_->LastError());

    started_ = true;
    DBG("started audio send channel");
    return RESULT_OK;
}

int NdnAudioSendChannel::stop()
{
    if (RESULT_FAIL(NdnAudioChannel::stop()))
        return RESULT_ERR;

    voe_base_->StopSend(channel_);
    voe_network_->DeRegisterExternalTransport(channel_);
    channel_ = -1;

    DBG("stopped audio send channel");
    return RESULT_OK;
}

//******************************************************************************
#pragma mark - intefaces realization - Transport
int NdnAudioSendChannel::SendPacket(int channel, const void *data, int len)
{
    TRACE("sending RTP packet of length %d", len);

    if (started_)
        audioSender_->publishRTPAudioPacket(len, (unsigned char*)data);
    else
        WARN("getting RTP packets while channel was not started");

    // return bytes sent or negative value on error
    return len;
}

int NdnAudioSendChannel::SendRTCPPacket(int channel, const void *data, int len)
{
    TRACE("sending RTCP packet of length %d", len);

    if (started_)
        audioSender_->publishRTCPAudioPacket(len, (unsigned char*)data);
    else
        WARN("getting RTCP packets while channel was not started");

    // return bytes sent or negative value on error
    return len;
}

void NdnAudioSendChannel::getStatistics(SenderChannelPerformance &stat)
{
    stat.nBytesPerSec_ = audioSender_->getDataRate();
    stat.nFramesPerSec_ = audioSender_->getCurrentPacketRate();
    stat.lastFrameNo_ = audioSender_->getPacketNo();
    stat.encodingRate_ = stat.nFramesPerSec_;
    stat.nDroppedByEncoder_ = 0;
}


text: <llist xmlns="urn:cesnet:mod2">TRUE</llist>


text:
package com.inktomi.cirrus.forecast;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Provides a mapping in case clients want to use their own icons instead of the provided NDFD ones.
 *
 * Created by mruno on 8/13/13.
 */
public enum Icon {
    FOG("Fog", "^n?(fg)\\d*$", "http://forecasts.weather.gov/weather/images/fcicons/fg.jpg"),
    SCATTERED_FOG("Scattered Fog", "^n?(sctfg)\\d*$", "http://forecasts.weather.gov/weather/images/fcicons/sctfg.jpg"),
    BROKEN_FOG("Broken Fog", "^n?(bknfg)\\d*$", "http://forecasts.weather.gov/weather/images/fcicons/sctfg.jpg"),
    BLIZZARD("Blizzard", "^n?(blizzard)\\d*$", "http://forecasts.weather.gov/weather/images/fcicons/blizzard.jpg"),
    DUST("Dust", "^n?(du)\\d*$", "http://forecasts.weather.gov/weather/images/fcicons/du.jpg"),
    SMOKE("Smoke", "^n?(fu)\\d*$", "http://forecasts.weather.gov/weather/images/fcicons/fu.jpg"),
    ICE_PELLET("Ice Pellets", "^n?(ip)\\d*$", "http://forecasts.weather.gov/weather/images/fcicons/ip.jpg"),
    HAIL("Hail", "^n?(ip)\\d*$", "http://forecasts.weather.gov/weather/images/fcicons/ip.jpg"),
    SHOWER("Showers", "^n?(shwrs)\\d*$", "http://forecasts.weather.gov/weather/images/fcicons/hi_shwrs.jpg"),
    SHOWERING_RAIN("Showering Rain", "^n?(shra)\\d*$", "http://forecasts.weather.gov/weather/images/fcicons/shra.jpg"),
    RAIN("Rain", "^n?(ra)\\d*$", "http://graphical.weather.gov/xml/xml_fields_icon_weather_conditions.php"),
    SNOW("Snow", "^n?(sn)\\d*$", "http://forecasts.weather.gov/weather/images/fcicons/sn.jpg"),
    RAIN_AND_SNOW("Rain & Snow", "^n?(rasn)\\d*$", "http://graphical.weather.gov/xml/xml_fields_icon_weather_conditions.php"),
    FREEZING_RAIN("Freezing Rain", "^n?(fzra)\\d*$", "http://forecasts.weather.gov/weather/images/fcicons/fzra.jpg"),
    MIXED("Mixed", "^n?(mix)\\d*$", "http://forecasts.weather.gov/weather/images/fcicons/mix.jpg"),
    RAIN_AND_ICE_PELLETS("Rain & Ice Pellets", "^n?(raip)\\d*$", "http://forecasts.weather.gov/weather/images/fcicons/raip.jpg"),
    THUNDERSTORM("Thunderstorms", "^n?(tsra)\\d*$", "http://forecasts.weather.gov/weather/images/fcicons/tsra.jpg"),
    SCATTERED_THUNDERSTORM("Scattered Thunderstorms", "^n?(scttsra)\\d*$", "http://forecasts.weather.gov/weather/images/fcicons/scttsra.jpg"),
    CLEAR("Clear", "^n?(skc)\\d*$", "http://forecasts.weather.gov/weather/images/fcicons/skc.jpg"),
    FEW_CLOUDS("Few Clouds", "^n?(few)\\d*$", "http://forecasts.weather.gov/weather/images/fcicons/few.jpg"),
    SCATTERED_CLOUDS("Scattered Clouds", "^n?(sct)\\d*$", "http://forecasts.weather.gov/weather/images/fcicons/sct.jpg"),
    BROKEN_CLOUDS("Broken Clouds", "^n?(bkn)\\d*$", "http://forecasts.weather.gov/weather/images/fcicons/bkn.jpg"),
    OVERCAST("Overcast", "^n?(ovc)\\d*$", "http://forecasts.weather.gov/weather/images/fcicons/ovc.jpg"),
    HOT("Hot", "^n?(hot)\\d*$", "http://forecasts.weather.gov/weather/images/fcicons/hot.jpg"),
    COLD("Cold", "^n?(cold)\\d*$", "http://forecasts.weather.gov/weather/images/fcicons/cold.jpg"),
    WIND("Windy", "^n?(wind)\\d*$", "http://forecasts.weather.gov/weather/images/fcicons/wind.jpg");

    private final String weatherType;
    private final String weatherRegex;
    private final String iconUrl;

    Icon(String weatherType, String weatherRegex, String iconUrl) {
        this.weatherType = weatherType;
        this.weatherRegex = weatherRegex;
        this.iconUrl = iconUrl;
    }

    public String getWeatherType() {
        return weatherType;
    }

    public Pattern getWeatherRegex() {
        return Pattern.compile(weatherRegex);
    }

    public String getIconUrl() {
        return iconUrl;
    }

    public static Icon getByIconName(String iconName){
        for( Icon condition : Icon.values() ) {
            Matcher matcher = condition.getWeatherRegex().matcher(iconName);

            if( matcher.matches() ){
                return condition;
            }
        }

        return null;
    }
}


text:
<?php

namespace backend\modules\common\models;

use common\models\Language;
use omgdef\multilingual\MultilingualBehavior;
use Yii;
use kartik\builder\Form;
use yii\behaviors\TimestampBehavior;
use yii\data\ActiveDataProvider;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%footer_link}}".
 *
 * @property integer $id
 * @property string $label
 * @property string $url
 * @property integer $column
 * @property integer $visible
 * @property integer $position
 * @property string $created
 * @property string $modified
 *
 * @property FooterLinkLang[] $footerLinkLangs
 */
class FooterLink extends \backend\components\BackModel
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%footer_link}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['label', 'url'], 'required'],
            ['url', 'url', 'defaultScheme' => 'http'],
            [['column', 'visible', 'position'], 'integer'],
            [['created', 'modified'], 'safe'],
            [['label', 'url'], 'string', 'max' => 255],
            [['id', 'label', 'url', 'column', 'visible', 'position', 'created', 'modified'], 'safe', 'on' => 'search']
        ];
    }

    /**
     * @inheritdoc
     */
    public static function find()
    {
        return parent::find()->with(['translations']);
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        $attributes = [
            'id' => 'ID',
            'label' => 'Название',
            'url' => 'Ссылка',
            'column' => 'Столбец',
            'visible' => 'Отображать',
            'position' => 'Позиция',
            'created' => 'Создано',
            'modified' => 'Обновлено',
        ];

        return $this->prepareAttributeLabels($attributes);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getFooterLinkLangs()
    {
        return $this->hasMany(FooterLinkLang::className(), ['model_id' => 'id']);
    }

    /**
    * @param $params
    *
    * @return ActiveDataProvider
    */
    public function search($params)
    {
        $query = static::find();
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => [
                'defaultOrder' => ['position' => SORT_DESC]
            ]
        ]);

        if (!empty($params)) {
            $this->load($params);
        }

            $query->andFilterWhere(['id' => $this->id]);
            $query->andFilterWhere(['like', 'label', $this->label]);
            $query->andFilterWhere(['like', 'url', $this->url]);
            $query->andFilterWhere(['column' => $this->column]);
            $query->andFilterWhere(['visible' => $this->visible]);
            $query->andFilterWhere(['position' => $this->position]);
            $query->andFilterWhere(['created' => $this->created]);
            $query->andFilterWhere(['modified' => $this->modified]);

        return $dataProvider;
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return ArrayHelper::merge(
            parent::behaviors(),
            [
                [
                    'class' => TimestampBehavior::className(),
                    'createdAtAttribute' => 'created',
                    'updatedAtAttribute' => 'modified',
                    'value' => function () {
                        return date("Y-m-d H:i:s");
                    }
                ],
                'ml' => [
                    'class' => MultilingualBehavior::className(),
                    'languages' => Language::getLangList(),
                    'languageField' => 'lang_id',
                    'defaultLanguage' => Language::getDefaultLang()->code,
                    'langForeignKey' => 'model_id',
                    'tableName' => FooterLinkLang::className(),
                    'attributes' => $this->getLocalizedAttributes()
                ],
            ]
        );
    }

    /**
     * @inheritdoc
     */
    public function getLocalizedAttributes()
    {
        return [
            'label', 'url'
        ];
    }

    /**
    * @param bool $viewAction
    *
    * @return array
    */
    public function getViewColumns($viewAction = false)
    {
        return $viewAction
            ? [
                'id',
                'label',
                'url',
                'column',
                'visible:boolean',
                'position',
                'created',
                'modified',
            ]
            : [
                [
                    'attribute' => 'id',
                    'headerOptions' => ['class' => 'col-sm-1']
                ],
                'label',
                [
                    'attribute' => 'column',
                    'filter' => [1 => 'Первый', 2 => 'Второй'],
                    'value' => function (self $data) {
                        return $data->column == 1 ? 'Первый' : ($data->column == 2 ? 'Второй' : null);
                    }
                ],
                'url',
                [
                    'attribute' => 'visible',
                    'filter' => ['Да', 'Нет'],
                    'value' => function (self $data) {
                        return $data->visible == 0 ? 'Нет' : 'Да';
                    }
                ],
                [
                    'class' => \yii\grid\ActionColumn::className()
                ]
            ];
    }

    /**
    * @return array
    */
    public function getFormRows()
    {
        return [
            'column' => [
                'type' => Form::INPUT_DROPDOWN_LIST,
                'items' => [1 => 'Первый', 2 => 'Второй']
            ],
            'label' => [
                'type' => Form::INPUT_TEXT,
            ],
            'url' => [
                'type' => Form::INPUT_TEXT,
            ],
            'visible' => [
                'type' => Form::INPUT_CHECKBOX,
            ]

        ];
    }

    /**
    * @inheritdoc
    */
    public function getColCount()
    {
        return 1;
    }

    /**
    * @return string
    */
    public function getBreadCrumbRoot()
    {
        return 'Ссылки в футере';
    }
}


text:
USE FilestreamDemoDB;
GO

-- Insert data into a FILESTREAM column, then query data from that column.

INSERT INTO [dbo].[FileStreamFiles]
            ([id], [description], [fileData])
       VALUES
	        (NEWID(), 'Test File', CAST('testdata' AS VARBINARY(MAX)));

SELECT *
  FROM [dbo].[FileStreamFiles];

SELECT CAST ([fileData] AS VARCHAR(MAX))
  FROM [dbo].[FileStreamFiles];

-- Find the file that was created when you inserted data into the FILESTREAM column.
--   Open the file and confirm that it has your data in it.

-- Change some data and see that the following query returns the changed results

SELECT CAST ([fileData] AS VARCHAR(MAX))
  FROM [dbo].[FileStreamFiles];

-- the .WRITE functionality does not work on FILESTREAM tables

UPDATE [dbo].[FileStreamFiles]
SET [fileData].WRITE(CAST('1234567890' AS VARBINARY), 20, 10);