text:
require "rails_helper"

RSpec.describe DocFile, type: :model do
  it { should have_many :doc_versions }
end


text:
class TransformTool : public Tool
{
public:
    TransformTool(SelectionManager& selectionManager, Canvas &canvas);
    void OnSelect() override;
    void OnUnselect() override;
    void OnCanvasLeftMouseButtonClick(const wxMouseEvent &event) override;
    void OnCanvasLeftMouseButtonRelease(const wxMouseEvent &event) override;
    void OnCanvasMouseMotion(const wxMouseEvent &event) override;
    void OnCanvasRightMouseButtonRelease(const wxMouseEvent &event) override;
    void OnCanvasKeyPress(const wxKeyEvent &event) override;
    void OnTimerTick() override;
    ~TransformTool() override = default;

private:
    void SetupOrigins();
    float Distance(const wxRealPoint &p1, const wxRealPoint &p2);
    float Angle(const wxRealPoint &p1, const wxRealPoint &p2);
    wxRealPoint Rotate(const wxRealPoint &origin, const wxRealPoint &p, float angle);
    wxRealPoint Scale(const wxRealPoint &origin, const wxRealPoint &p, const wxRealPoint &scale);

    SelectionManager& m_selectionManager;
    Canvas &m_canvas;

    wxRealPoint m_mousePositionOnMap;

    wxRealPoint m_bottomLeft;
    wxRealPoint m_bottomRight;
    wxRealPoint m_topLeft;
    wxRealPoint m_topRight;

    bool m_moving;
    bool m_scaling;
    bool m_rotating;
    bool m_temporarySelection;

    wxRealPoint m_origin;
    wxRealPoint m_current;
};

redpajama_set_name: RedPajamaGithub


text:
require 'samepage/zook/fake/zk'
require 'samepage/zook/client/zk'
require 'samepage/zook/data/service'

describe Samepage::Zook::Client::ZK do
	let(:zook) do
		Samepage::Zook::Fake::ZK.new(
			'/prefix/key1' => 'value1',
			'/prefix/node1/key2' => 'value2',
			'/prefix/node1/service1' => nil,
			'/prefix/node1/service2/id1' => '{"name":"service2","id":"id1","address":"1.2.3.4","port":null,"payload":{"@class":"java.util.Properties","some.property":"123"},"registrationTimeUTC":1452688341307}',
			'/prefix/node1/service2/id2' => '{"name":"service2","id":"id2","address":"1.2.3.5","port":1234,"payload":null,"registrationTimeUTC":1452688341307}',
			'/prefix/node1/service2/id3' => '{"name":"service2","id":"id3","address":"1.2.3.6","port":"4563"}',
		)
	end
	let(:client) { described_class.new(zook, '/prefix') }

	describe '#ensure' do
		it 'checks path parent keys and creates missing' do
			expect( zook ).to receive(:create).with('/prefix/node1/sub1').and_call_original
			expect( zook ).to receive(:create).with('/prefix/node1/sub1/sub2').and_call_original
			client.ensure('/prefix/node1/sub1/sub2')
		end
	end

	describe 'connected?' do
		it 'inverts return value of ZK.closed?' do
			expect(zook).to receive(:closed?).and_return(true)
			expect( client.connected? ).to eq false
		end
	end

	describe 'list_services' do
		context 'when service does not exist' do

			it 'returns empty list' do
				result = client.list_services('/prefix/node1/no_service')
				expect(result).to be_an Array
				expect(result).to be_empty
			end
		end

		context 'when 0 services are registered' do
			it 'returns empty list' do
				result = client.list_services('/prefix/node1/service1')
				expect(result).to be_an Array
				expect(result).to be_empty
			end
		end

		context 'when 3 services are registered' do
			it 'return 3 Services' do
				result = client.list_services('/prefix/node1/service2')
				expect(result).to be_an Array
				expect(result.size).to eq 3
				expect(result[0]).to be_a Samepage::Zook::Data::Service
				expect(result[1]).to be_a Samepage::Zook::Data::Service
				expect(result[2]).to be_a Samepage::Zook::Data::Service
			end
		end
	end
end


text:
Varnish VCL for standardized edge architecture
==============================================
Implementation of edge architecture in Varnish VCL
http://www.w3.org/TR/2001/NOTE-edge-arch-20010804 : Edge Architecture Specification


text:
using MatterHackers.Agg;
using MatterHackers.Agg.UI;
using MatterHackers.Agg.VertexSource;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.PrinterCommunication;
using MatterHackers.VectorMath;
using System;

namespace MatterHackers.MatterControl.ActionBar
{
	//Base widget for ActionBarRows
	public abstract class ActionRowBase : FlowLayoutWidget
	{
		public ActionRowBase()
			: base(FlowDirection.LeftToRight)
		{
			Initialize();
			SetDisplayAttributes();
			AddChildElements();
			AddHandlers();
		}

		protected virtual void Initialize()
		{
			//Placeholder for row-specific initialization
		}

		protected void SetDisplayAttributes()
		{
			this.HAnchor = HAnchor.ParentLeftRight;
		}

		protected abstract void AddChildElements();

		protected virtual void AddHandlers()
		{
			//Placeholder for row-specific handlers
		}
	}

	//Base widget for use in ButtonViewStates
	public class ControlButtonViewBase : GuiWidget
	{
		protected RGBA_Bytes fillColor;
		protected RGBA_Bytes borderColor;
		protected double borderWidth;
		protected double borderRadius;
		protected double padding;

		public ControlButtonViewBase(string label,
									 double width,
									 double height,
									 double textHeight,
									 double borderWidth,
									 double borderRadius,
									 double padding,
									 RGBA_Bytes textColor,
									 RGBA_Bytes fillColor,
									 RGBA_Bytes borderColor)
			: base(width, height)
		{
			this.borderRadius = borderRadius;
			this.borderWidth = borderWidth;
			this.fillColor = fillColor;
			this.borderColor = borderColor;
			this.padding = padding;

			TextWidget buttonText = new TextWidget(label, textHeight);
			buttonText.VAnchor = VAnchor.ParentCenter;
			buttonText.HAnchor = HAnchor.ParentCenter;
			buttonText.TextColor = textColor;

			//this.AnchorAll();
			this.AddChild(buttonText);
		}

		public override void OnDraw(Graphics2D graphics2D)
		{
			RectangleDouble Bounds = LocalBounds;
			RoundedRect rectBorder = new RoundedRect(Bounds, this.borderRadius);

			graphics2D.Render(rectBorder, borderColor);

			RectangleDouble insideBounds = Bounds;
			insideBounds.Inflate(-this.borderWidth);
			RoundedRect rectInside = new RoundedRect(insideBounds, Math.Max(this.borderRadius - this.borderWidth, 0));

			graphics2D.Render(rectInside, this.fillColor);

			base.OnDraw(graphics2D);
		}
	}

	//Base widget for use in ButtonViewStates
	public class PrinterSelectViewBase : GuiWidget
	{
		protected RGBA_Bytes fillColor;
		protected RGBA_Bytes borderColor;
		protected double borderWidth;
		protected double borderRadius;
		protected double padding;
		protected double statusTextHeight = 8;
		private TextWidget printerStatusText;
		private TextWidget printerNameText;

		private event EventHandler unregisterEvents;

		public PrinterSelectViewBase(
									 double width,
									 double height,
									 double textHeight,
									 double borderWidth,
									 double borderRadius,
									 double padding,
									 RGBA_Bytes textColor,
									 RGBA_Bytes fillColor,
									 RGBA_Bytes borderColor)
			: base(width, height)
		{
			this.borderRadius = borderRadius;
			this.borderWidth = borderWidth;
			this.fillColor = fillColor;
			this.borderColor = borderColor;
			this.padding = padding;
			this.Padding = new BorderDouble(10, 5);
			this.HAnchor = HAnchor.ParentLeftRight;

			FlowLayoutWidget textContainer = new FlowLayoutWidget(FlowDirection.TopToBottom);
			textContainer.VAnchor = VAnchor.ParentBottomTop;
			textContainer.HAnchor = HAnchor.ParentLeftRight;

			printerNameText = new TextWidget("", pointSize: textHeight);
			printerNameText.AutoExpandBoundsToText = true;
			printerNameText.HAnchor = HAnchor.ParentCenter;
			printerNameText.TextColor = textColor;

			string printerStatusTextBeg = LocalizedString.Get("Status");
			string printerStatusTextEnd = LocalizedString.Get("Connected");
			string printerStatusTextFull = string.Format("{0}: {1}", printerStatusTextBeg, printerStatusTextEnd);
			printerStatusText = new TextWidget(printerStatusTextFull, pointSize: statusTextHeight);
			printerStatusText.AutoExpandBoundsToText = true;
			printerStatusText.HAnchor = HAnchor.ParentCenter;
			printerStatusText.TextColor = textColor;

			textContainer.AddChild(printerNameText);
			textContainer.AddChild(printerStatusText);

			SetButtonText();

			//this.AnchorAll();
			this.AddChild(textContainer);

			ActivePrinterProfile.Instance.ActivePrinterChanged.RegisterEvent(onActivePrinterChanged, ref unregisterEvents);
			PrinterConnectionAndCommunication.Instance.CommunicationStateChanged.RegisterEvent(onActivePrinterChanged, ref unregisterEvents);
		}

		public override void OnClosed(EventArgs e)
		{
			if (unregisterEvents != null)
			{
				unregisterEvents(this, null);
			}
			base.OnClosed(e);
		}

		private void onActivePrinterChanged(object sender, EventArgs e)
		{
			UiThread.RunOnIdle(SetButtonText);
		}

		private int GetPrinterRecordCount()
		{
			return DataStorage.Datastore.Instance.RecordCount("Printer");
		}

		private void SetButtonText()
		{
			if (PrinterConnectionAndCommunication.Instance.CommunicationState == PrinterConnectionAndCommunication.CommunicationStates.FailedToConnect && PrinterConnectionAndCommunication.Instance.ConnectionFailureMessage != "")
			{
				printerStatusText.Text = "Status: " + PrinterConnectionAndCommunication.Instance.ConnectionFailureMessage;
			}
			else
			{
				string statusStringBeg = LocalizedString.Get("Status").ToUpper();
				string statusString = string.Format("{1}: {0}", PrinterConnectionAndCommunication.Instance.PrinterConnectionStatusVerbose, statusStringBeg);
				printerStatusText.Text = string.Format(statusString, PrinterConnectionAndCommunication.Instance.PrinterConnectionStatusVerbose);
			}
			if (ActivePrinterProfile.Instance.ActivePrinter != null)
			{
				printerNameText.Text = ActivePrinterProfile.Instance.ActivePrinter.Name;
			}
			else
			{
				if (GetPrinterRecordCount() > 0)
				{
					string printerNameLabel = LocalizedString.Get("Select Printer");
					string printerNameLabelFull = string.Format("- {0} -", printerNameLabel);
					printerNameText.Text = (printerNameLabelFull);
				}
				else
				{
					string addPrinterLabel = LocalizedString.Get("Add Printer");
					string addPrinterLabelFull = string.Format("- {0} -", addPrinterLabel);
					printerNameText.Text = (addPrinterLabelFull);
				}
			}
		}

		public override void OnDraw(Graphics2D graphics2D)
		{
			RectangleDouble Bounds = LocalBounds;
			RoundedRect rectBorder = new RoundedRect(Bounds, this.borderRadius);

			graphics2D.Render(rectBorder, borderColor);

			RectangleDouble insideBounds = Bounds;
			insideBounds.Inflate(-this.borderWidth);
			RoundedRect rectInside = new RoundedRect(insideBounds, Math.Max(this.borderRadius - this.borderWidth, 0));

			graphics2D.Render(rectInside, this.fillColor);
			base.OnDraw(graphics2D);
		}
	}

	public class PrinterSelectButton : Button
	{
		private double width = 180;
		private double height = 40;
		private double borderRadius = 0;
		private double borderWidth = 1;
		private double fontSize = 14;
		private double padding = 3;
		private BorderDouble margin = new BorderDouble(0, 0);

		public PrinterSelectButton()
		{
			this.HAnchor = HAnchor.ParentLeftRight;

			//Widgets to show during the four button states
			PrinterSelectViewBase buttonWidgetPressed = getButtonWidgetNormal();
			PrinterSelectViewBase buttonWidgetHover = getButtonWidgetHover();
			PrinterSelectViewBase buttonWidgetNormal = getButtonWidgetNormal();
			PrinterSelectViewBase buttonWidgetDisabled = getButtonWidgetNormal();

			//Create container for the three state widgets for the button
			ButtonViewStates buttonView = new ButtonViewStates(buttonWidgetNormal, buttonWidgetHover, buttonWidgetPressed, buttonWidgetDisabled);
			buttonView.HAnchor = HAnchor.ParentLeftRight;

			this.ToolTipText = "Select a printer".Localize();

			Margin = DefaultMargin;

			OriginRelativeParent = new Vector2(0, 0);

			if (buttonView != null)
			{
				buttonView.Selectable = false;

				AddChild(buttonView);

				HAnchor = HAnchor.FitToChildren;
				VAnchor = VAnchor.FitToChildren;

				if (LocalBounds.Left != 0 || LocalBounds.Bottom != 0)
				{
					// let's make sure that a button has 0, 0 at the lower left
					// move the children so they will fit with 0, 0 at the lower left
					foreach (GuiWidget child in Children)
					{
						child.OriginRelativeParent = child.OriginRelativeParent + new Vector2(-LocalBounds.Left, -LocalBounds.Bottom);
					}

					HAnchor = HAnchor.FitToChildren;
					VAnchor = VAnchor.FitToChildren;
				}

				MinimumSize = new Vector2(Width, Height);
			}
		}

		private PrinterSelectViewBase getButtonWidgetHover()
		{
			RGBA_Bytes borderColor;
			RGBA_Bytes fillColor = ActiveTheme.Instance.PrimaryBackgroundColor;
			if (ActiveTheme.Instance.IsDarkTheme)
			{
				borderColor = new RGBA_Bytes(128, 128, 128);
			}
			else
			{
				borderColor = new RGBA_Bytes(128, 128, 128);
			}
			RGBA_Bytes textColor = ActiveTheme.Instance.PrimaryTextColor;
			PrinterSelectViewBase widget = new PrinterSelectViewBase(
															   this.width,
															   this.height,
															   this.fontSize,
															   this.borderWidth,
															   this.borderRadius,
															   this.padding,
															   textColor,
															   fillColor,
															   borderColor);
			return widget;
		}

		public PrinterSelectViewBase getButtonWidgetNormal()
		{
			RGBA_Bytes fillColor = ActiveTheme.Instance.PrimaryBackgroundColor;
			RGBA_Bytes borderColor;
			if (ActiveTheme.Instance.IsDarkTheme)
			{
				borderColor = new RGBA_Bytes(77, 77, 77);
			}
			else
			{
				borderColor = new RGBA_Bytes(190, 190, 190);
			}

			RGBA_Bytes textColor = ActiveTheme.Instance.PrimaryTextColor;
			PrinterSelectViewBase widget = new PrinterSelectViewBase(
															   this.width,
															   this.height,
															   this.fontSize,
															   this.borderWidth,
															   this.borderRadius,
															   this.padding,
															   textColor,
															   fillColor,
															   borderColor);
			return widget;
		}
	}

	public class ActionBarControlButtonFactory
	{
		private double width = 75;
		private double height = 30;
		private double borderRadius = 3;
		private double borderWidth = 1;
		private double fontSize = 14;
		private double padding = 3;
		private BorderDouble margin = new BorderDouble(5, 0);

		public Button Generate(string buttonText)
		{
			//Widgets to show during the four button states
			ControlButtonViewBase buttonWidgetPressed = getButtonWidgetPressed(buttonText);
			ControlButtonViewBase buttonWidgetHover = getButtonWidgetHover(buttonText);
			ControlButtonViewBase buttonWidgetNormal = getButtonWidgetNormal(buttonText);
			ControlButtonViewBase buttonWidgetDisabled = getButtonWidgetDisabled(buttonText);

			//Create container for the three state widgets for the button
			ButtonViewStates buttonViewWidget = new ButtonViewStates(buttonWidgetNormal, buttonWidgetHover, buttonWidgetPressed, buttonWidgetDisabled);

			//Create button based on view container widget
			Button controlButton = new Button(0, 0, buttonViewWidget);
			controlButton.Margin = margin;

			return controlButton;
		}

		private ControlButtonViewBase getButtonWidgetPressed(string buttonText)
		{
			RGBA_Bytes fillColor = new RGBA_Bytes(63, 63, 70);
			RGBA_Bytes borderColor = new RGBA_Bytes(37, 37, 38);
			RGBA_Bytes textColor = new RGBA_Bytes(230, 230, 230);
			ControlButtonViewBase widget = new ControlButtonViewBase(buttonText,
															   this.width,
															   this.height,
															   this.fontSize,
															   this.borderWidth,
															   this.borderRadius,
															   this.padding,
															   textColor,
															   fillColor,
															   borderColor);
			return widget;
		}

		private ControlButtonViewBase getButtonWidgetHover(string buttonText)
		{
			RGBA_Bytes fillColor = new RGBA_Bytes(63, 63, 70);
			RGBA_Bytes borderColor = RGBA_Bytes.LightGray;
			RGBA_Bytes textColor = new RGBA_Bytes(230, 230, 230);
			ControlButtonViewBase widget = new ControlButtonViewBase(buttonText,
															   this.width,
															   this.height,
															   this.fontSize,
															   this.borderWidth,
															   this.borderRadius,
															   this.padding,
															   textColor,
															   fillColor,
															   borderColor);
			return widget;
		}

		public ControlButtonViewBase getButtonWidgetNormal(string buttonText)
		{
			RGBA_Bytes fillColor = new RGBA_Bytes(245, 245, 245);
			RGBA_Bytes borderColor = new RGBA_Bytes(204, 204, 204);
			RGBA_Bytes textColor = new RGBA_Bytes(69, 69, 69);
			ControlButtonViewBase widget = new ControlButtonViewBase(buttonText,
															   this.width,
															   this.height,
															   this.fontSize,
															   this.borderWidth,
															   this.borderRadius,
															   this.padding,
															   textColor,
															   fillColor,
															   borderColor);
			return widget;
		}

		private ControlButtonViewBase getButtonWidgetDisabled(string buttonText)
		{
			RGBA_Bytes fillColor = new RGBA_Bytes(245, 245, 245);
			RGBA_Bytes borderColor = new RGBA_Bytes(204, 204, 204);
			RGBA_Bytes textColor = new RGBA_Bytes(153, 153, 153);
			ControlButtonViewBase widget = new ControlButtonViewBase(buttonText,
															   this.width,
															   this.height,
															   this.fontSize,
															   this.borderWidth,
															   this.borderRadius,
															   this.padding,
															   textColor,
															   fillColor,
															   borderColor);
			return widget;
		}
	}
}


text:
package io.github.bonigarcia.wdm.test.versions;

import static java.io.File.separator;
import static java.lang.invoke.MethodHandles.lookup;
import static org.assertj.core.api.Assertions.assertThat;
import static org.slf4j.LoggerFactory.getLogger;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.slf4j.Logger;

import io.github.bonigarcia.wdm.cache.CacheHandler;
import io.github.bonigarcia.wdm.config.Config;

/**
 * FilterCacheBy test.
 *
 * @author Boni Garcia
 * @since 3.8.0
 */
class VersionFilterTest {

    final Logger log = getLogger(lookup().lookupClass());

    @ParameterizedTest
    @MethodSource("data")
    void testFilterCacheBy(String version, int expectedVersions) {
        CacheHandler cacheHandler = new CacheHandler(new Config());
        List<File> filteredList = cacheHandler.filterCacheBy(getInputFileList(),
                version, true);

        log.debug("Version {} -- Output {}", version, filteredList);
        assertThat(filteredList.size()).isEqualTo(expectedVersions);
    }

    static Stream<Arguments> data() {
        return Stream.of(Arguments.of("74", 1), Arguments.of("77", 1),
                Arguments.of("79", 2));
    }

    private List<File> getInputFileList() {
        List<File> output = new ArrayList<>();
        File currentFolder = new File(".");
        String[] versions = { "74.0.3729.6", "75.0.3770.140", "75.0.3770.8",
                "75.0.3770.90", "76.0.3809.126", "76.0.3809.68", "77.0.3865.40",
                "78.0.3904.70", "79.0.3945.16", "79.0.3945.36" };
        for (String v : versions) {
            output.add(new File(currentFolder, v + separator + "chromedriver"));
        }
        return output;
    }

}


text:
#if !defined(FIT_VIDEO_CLIP_MESG_HPP)
#define FIT_VIDEO_CLIP_MESG_HPP

#include "fit_mesg.hpp"

namespace fit
{

class VideoClipMesg : public Mesg
{
public:
    class FieldDefNum final
    {
    public:
       static const FIT_UINT8 ClipNumber = 0;
       static const FIT_UINT8 StartTimestamp = 1;
       static const FIT_UINT8 StartTimestampMs = 2;
       static const FIT_UINT8 EndTimestamp = 3;
       static const FIT_UINT8 EndTimestampMs = 4;
       static const FIT_UINT8 ClipStart = 6;
       static const FIT_UINT8 ClipEnd = 7;
       static const FIT_UINT8 Invalid = FIT_FIELD_NUM_INVALID;
    };

    VideoClipMesg(void) : Mesg(Profile::MESG_VIDEO_CLIP)
    {
    }

    VideoClipMesg(const Mesg &mesg) : Mesg(mesg)
    {
    }

    ///////////////////////////////////////////////////////////////////////
    // Checks the validity of clip_number field
    // Returns FIT_TRUE if field is valid
    ///////////////////////////////////////////////////////////////////////
    FIT_BOOL IsClipNumberValid() const
    {
        const Field* field = GetField(0);
        if( FIT_NULL == field )
        {
            return FIT_FALSE;
        }

        return field->IsValueValid();
    }

    ///////////////////////////////////////////////////////////////////////
    // Returns clip_number field
    ///////////////////////////////////////////////////////////////////////
    FIT_UINT16 GetClipNumber(void) const
    {
        return GetFieldUINT16Value(0, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
    }

    ///////////////////////////////////////////////////////////////////////
    // Set clip_number field
    ///////////////////////////////////////////////////////////////////////
    void SetClipNumber(FIT_UINT16 clipNumber)
    {
        SetFieldUINT16Value(0, clipNumber, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
    }

    ///////////////////////////////////////////////////////////////////////
    // Checks the validity of start_timestamp field
    // Returns FIT_TRUE if field is valid
    ///////////////////////////////////////////////////////////////////////
    FIT_BOOL IsStartTimestampValid() const
    {
        const Field* field = GetField(1);
        if( FIT_NULL == field )
        {
            return FIT_FALSE;
        }

        return field->IsValueValid();
    }

    ///////////////////////////////////////////////////////////////////////
    // Returns start_timestamp field
    ///////////////////////////////////////////////////////////////////////
    FIT_DATE_TIME GetStartTimestamp(void) const
    {
        return GetFieldUINT32Value(1, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
    }

    ///////////////////////////////////////////////////////////////////////
    // Set start_timestamp field
    ///////////////////////////////////////////////////////////////////////
    void SetStartTimestamp(FIT_DATE_TIME startTimestamp)
    {
        SetFieldUINT32Value(1, startTimestamp, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
    }

    ///////////////////////////////////////////////////////////////////////
    // Checks the validity of start_timestamp_ms field
    // Returns FIT_TRUE if field is valid
    ///////////////////////////////////////////////////////////////////////
    FIT_BOOL IsStartTimestampMsValid() const
    {
        const Field* field = GetField(2);
        if( FIT_NULL == field )
        {
            return FIT_FALSE;
        }

        return field->IsValueValid();
    }

    ///////////////////////////////////////////////////////////////////////
    // Returns start_timestamp_ms field
    ///////////////////////////////////////////////////////////////////////
    FIT_UINT16 GetStartTimestampMs(void) const
    {
        return GetFieldUINT16Value(2, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
    }

    ///////////////////////////////////////////////////////////////////////
    // Set start_timestamp_ms field
    ///////////////////////////////////////////////////////////////////////
    void SetStartTimestampMs(FIT_UINT16 startTimestampMs)
    {
        SetFieldUINT16Value(2, startTimestampMs, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
    }

    ///////////////////////////////////////////////////////////////////////
    // Checks the validity of end_timestamp field
    // Returns FIT_TRUE if field is valid
    ///////////////////////////////////////////////////////////////////////
    FIT_BOOL IsEndTimestampValid() const
    {
        const Field* field = GetField(3);
        if( FIT_NULL == field )
        {
            return FIT_FALSE;
        }

        return field->IsValueValid();
    }

    ///////////////////////////////////////////////////////////////////////
    // Returns end_timestamp field
    ///////////////////////////////////////////////////////////////////////
    FIT_DATE_TIME GetEndTimestamp(void) const
    {
        return GetFieldUINT32Value(3, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
    }

    ///////////////////////////////////////////////////////////////////////
    // Set end_timestamp field
    ///////////////////////////////////////////////////////////////////////
    void SetEndTimestamp(FIT_DATE_TIME endTimestamp)
    {
        SetFieldUINT32Value(3, endTimestamp, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
    }

    ///////////////////////////////////////////////////////////////////////
    // Checks the validity of end_timestamp_ms field
    // Returns FIT_TRUE if field is valid
    ///////////////////////////////////////////////////////////////////////
    FIT_BOOL IsEndTimestampMsValid() const
    {
        const Field* field = GetField(4);
        if( FIT_NULL == field )
        {
            return FIT_FALSE;
        }

        return field->IsValueValid();
    }

    ///////////////////////////////////////////////////////////////////////
    // Returns end_timestamp_ms field
    ///////////////////////////////////////////////////////////////////////
    FIT_UINT16 GetEndTimestampMs(void) const
    {
        return GetFieldUINT16Value(4, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
    }

    ///////////////////////////////////////////////////////////////////////
    // Set end_timestamp_ms field
    ///////////////////////////////////////////////////////////////////////
    void SetEndTimestampMs(FIT_UINT16 endTimestampMs)
    {
        SetFieldUINT16Value(4, endTimestampMs, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
    }

    ///////////////////////////////////////////////////////////////////////
    // Checks the validity of clip_start field
    // Returns FIT_TRUE if field is valid
    ///////////////////////////////////////////////////////////////////////
    FIT_BOOL IsClipStartValid() const
    {
        const Field* field = GetField(6);
        if( FIT_NULL == field )
        {
            return FIT_FALSE;
        }

        return field->IsValueValid();
    }

    ///////////////////////////////////////////////////////////////////////
    // Returns clip_start field
    // Units: ms
    // Comment: Start of clip in video time
    ///////////////////////////////////////////////////////////////////////
    FIT_UINT32 GetClipStart(void) const
    {
        return GetFieldUINT32Value(6, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
    }

    ///////////////////////////////////////////////////////////////////////
    // Set clip_start field
    // Units: ms
    // Comment: Start of clip in video time
    ///////////////////////////////////////////////////////////////////////
    void SetClipStart(FIT_UINT32 clipStart)
    {
        SetFieldUINT32Value(6, clipStart, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
    }

    ///////////////////////////////////////////////////////////////////////
    // Checks the validity of clip_end field
    // Returns FIT_TRUE if field is valid
    ///////////////////////////////////////////////////////////////////////
    FIT_BOOL IsClipEndValid() const
    {
        const Field* field = GetField(7);
        if( FIT_NULL == field )
        {
            return FIT_FALSE;
        }

        return field->IsValueValid();
    }

    ///////////////////////////////////////////////////////////////////////
    // Returns clip_end field
    // Units: ms
    // Comment: End of clip in video time
    ///////////////////////////////////////////////////////////////////////
    FIT_UINT32 GetClipEnd(void) const
    {
        return GetFieldUINT32Value(7, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
    }

    ///////////////////////////////////////////////////////////////////////
    // Set clip_end field
    // Units: ms
    // Comment: End of clip in video time
    ///////////////////////////////////////////////////////////////////////
    void SetClipEnd(FIT_UINT32 clipEnd)
    {
        SetFieldUINT32Value(7, clipEnd, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD);
    }

};

} // namespace fit

#endif // !defined(FIT_VIDEO_CLIP_MESG_HPP)


text:
"""
Stream WSGI application.

This application listens for events on the RabbitMQ message bus and delivers them to all the
clients which are connected to the stream HTTP endpoint (fan out approach).

Note: This app doesn't need access to MongoDB, just RabbitMQ.
"""

from oslo_config import cfg

from st2stream import config as st2stream_config
from st2common import log as logging
from st2common.middleware.error_handling import ErrorHandlingMiddleware
from st2common.middleware.cors import CorsMiddleware
from st2common.middleware.request_id import RequestIDMiddleware
from st2common.middleware.logging import LoggingMiddleware
from st2common.router import Router
from st2common.util.monkey_patch import monkey_patch
from st2common.constants.system import VERSION_STRING
from st2common.service_setup import setup as common_setup
from st2common.util import spec_loader

LOG = logging.getLogger(__name__)

class StreamingMiddleware(object):
    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        # Forces eventlet to respond immediately upon receiving a new chunk from endpoint rather
        # than buffering it until the sufficient chunk size is reached. The order for this
        # middleware is not important since it acts as pass-through.
        environ['eventlet.minimum_write_chunk_size'] = 0
        return self.app(environ, start_response)

def setup_app(config={}):
    LOG.info('Creating st2stream: %s as OpenAPI app.', VERSION_STRING)

    is_gunicorn = config.get('is_gunicorn', False)
    if is_gunicorn:
        # Note: We need to perform monkey patching in the worker. If we do it in
        # the master process (gunicorn_config.py), it breaks tons of things
        # including shutdown
        monkey_patch()

        st2stream_config.register_opts()
        # This should be called in gunicorn case because we only want
        # workers to connect to db, rabbbitmq etc. In standalone HTTP
        # server case, this setup would have already occurred.
        common_setup(service='stream', config=st2stream_config, setup_db=True,
                     register_mq_exchanges=True,
                     register_signal_handlers=True,
                     register_internal_trigger_types=False,
                     run_migrations=False,
                     config_args=config.get('config_args', None))

    router = Router(debug=cfg.CONF.stream.debug, auth=cfg.CONF.auth.enable)

    spec = spec_loader.load_spec('st2common', 'openapi.yaml')
    transforms = {
        '^/stream/v1/': ['/', '/v1/']
    }
    router.add_spec(spec, transforms=transforms)

    app = router.as_wsgi

    # Order is important. Check middleware for detailed explanation.
    app = StreamingMiddleware(app)
    app = ErrorHandlingMiddleware(app)
    app = CorsMiddleware(app)
    app = LoggingMiddleware(app, router)
    app = RequestIDMiddleware(app)

    return app


text:
[![Build Status](https://travis-ci.org/katoy/rails4-form-after-wizard.svg?branch=master)](https://travis-ci.org/katoy/rails4-form-after-wizard)
[![Dependency Status](https://gemnasium.com/katoy/rails4-form-after-wizard.png)](https://gemnasium.com/katoy/rails4-form-after-wizard)
[![Coverage Status](https://coveralls.io/repos/katoy/rails4-form-after-wizard/badge.png?branch=master)](https://coveralls.io/r/katoy/rails4-form-after-wizard?branch=master)

これは、rails4 アプリケーションでの Form 画面のサンプルです。
[別レポジトリーでの form 画面](https://github.com/katoy/rails4-form-before-wizard) を wizard 形式に変更したものです。

#
# 実行

    $ bundle install
	$ RAILS_ENV=test ./bin/rake db:create db:migrate db:test:prepare
	$ RAILS_ENV=test ./bin/rake spec

[./screenshots/*.png](./screenshots/) に主なシーンのスクリーンショットが保存される。
[./coverage/rcov/index.html](./coverage/rcov/index.html) にテストカバレッジレポートが保存される。

//--- End of File ---


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow.compat.v2 as tf
tf.enable_v2_behavior()

@tf.function
def matmul(a, b):
  return tf.matmul(a, b)

class TfPySmokeTest(tf.test.TestCase):

  def test_matmul(self):
    actual = matmul(tf.constant([[1, 2]]), tf.transpose([[3, 4]]))
    self.assertEqual(11, actual)

if __name__ == "__main__":
  tf.test.main()


text:
package a

type A struct{ _ int32 }


text:
package deprecated

import (
	"context"
	"fmt"
	"net/http"
	"net/url"
	"path"
	"strings"
	"time"

	"go.chromium.org/luci/common/clock"
	"go.chromium.org/luci/common/errors"
	"go.chromium.org/luci/common/logging"
	"go.chromium.org/luci/common/retry/transient"
	"go.chromium.org/luci/server/auth"
	"go.chromium.org/luci/server/auth/openid"
	"go.chromium.org/luci/server/router"
)

// Note: this file is a part of deprecated CookieAuthMethod implementation.

// These are installed into a HTTP router by CookieAuthMethod.InstallHandlers.
const (
	loginURL    = "/auth/openid/login"
	logoutURL   = "/auth/openid/logout"
	callbackURL = "/auth/openid/callback"
)

// errBadDestinationURL is returned by normalizeURL on errors.
var errBadDestinationURL = errors.New("openid: dest URL in LoginURL or LogoutURL must be relative")

// CookieAuthMethod implements auth.Method and auth.UsersAPI and can be used as
// one of authentication method in auth.Authenticator. It is using OpenID for
// login flow, stores session ID in cookies, and session itself in supplied
// SessionStore.
//
// It requires some routes to be added to the router. Use exact same instance
// of CookieAuthMethod in auth.Authenticator and when adding routes via
// InstallHandlers.
//
// DEPRECATED. Do not use.
type CookieAuthMethod struct {
	// SessionStore keeps user sessions in some permanent storage. Must be set,
	// otherwise all methods return ErrNotConfigured.
	SessionStore SessionStore

	// Insecure is true to allow http:// URLs and non-https cookies. Useful for
	// local development.
	Insecure bool

	// IncompatibleCookies is a list of cookies to remove when setting or clearing
	// session cookie. It is useful to get rid of GAE cookies when OpenID cookies
	// are being used. Having both is very confusing.
	IncompatibleCookies []string
}

// Make sure all extra interfaces are implemented.
var _ interface {
	auth.Method
	auth.UsersAPI
	auth.Warmable
	auth.HasHandlers
} = (*CookieAuthMethod)(nil)

// InstallHandlers installs HTTP handlers used in OpenID protocol. Must be
// installed in server HTTP router for OpenID authentication flow to work.
//
// Implements auth.HasHandlers.
func (m *CookieAuthMethod) InstallHandlers(r *router.Router, base router.MiddlewareChain) {
	r.GET(loginURL, base, m.loginHandler)
	r.GET(logoutURL, base, m.logoutHandler)
	r.GET(callbackURL, base, m.callbackHandler)
}

// Warmup prepares local caches. It's optional.
//
// Implements auth.Warmable.
func (m *CookieAuthMethod) Warmup(ctx context.Context) (err error) {
	cfg, err := FetchOpenIDSettings(ctx)
	if err != nil {
		return
	}
	if cfg.DiscoveryURL != "" {
		_, err = openid.FetchDiscoveryDoc(ctx, cfg.DiscoveryURL)
	} else {
		logging.Infof(ctx, "Skipping OpenID warmup, not configured")
	}
	return
}

// Authenticate extracts peer's identity from the incoming request. It is part
// of auth.Method interface.
func (m *CookieAuthMethod) Authenticate(ctx context.Context, r *http.Request) (*auth.User, auth.Session, error) {
	if m.SessionStore == nil {
		return nil, nil, ErrNotConfigured
	}

	// Grab session ID from the cookie.
	sid, err := decodeSessionCookie(ctx, r)
	if err != nil {
		return nil, nil, err
	}
	if sid == "" {
		return nil, nil, nil
	}

	// Grab session (with user information) from the store.
	session, err := m.SessionStore.GetSession(ctx, sid)
	if err != nil {
		return nil, nil, err
	}
	if session == nil {
		(logging.Fields{"sid": sid}).Warningf(ctx, "The session cookie references unknown session")
		return nil, nil, nil
	}
	(logging.Fields{
		"sid":   sid,
		"email": session.User.Email,
	}).Debugf(ctx, "Fetched the session")
	return &session.User, nil, nil
}

// LoginURL returns a URL that, when visited, prompts the user to sign in,
// then redirects the user to the URL specified by dest. It is part of
// auth.UsersAPI interface.
func (m *CookieAuthMethod) LoginURL(ctx context.Context, dest string) (string, error) {
	if m.SessionStore == nil {
		return "", ErrNotConfigured
	}
	return makeRedirectURL(loginURL, dest)
}

// LogoutURL returns a URL that, when visited, signs the user out,
// then redirects the user to the URL specified by dest. It is part of
// auth.UsersAPI interface.
func (m *CookieAuthMethod) LogoutURL(ctx context.Context, dest string) (string, error) {
	if m.SessionStore == nil {
		return "", ErrNotConfigured
	}
	return makeRedirectURL(logoutURL, dest)
}

////

// loginHandler initiates login flow by redirecting user to OpenID login page.
func (m *CookieAuthMethod) loginHandler(ctx *router.Context) {
	c, rw, r := ctx.Context, ctx.Writer, ctx.Request

	dest, err := normalizeURL(r.URL.Query().Get("r"))
	if err != nil {
		replyError(c, rw, err, "Bad redirect URI (%q) - %s", dest, err)
		return
	}

	cfg, err := FetchOpenIDSettings(c)
	if err != nil {
		replyError(c, rw, err, "Can't load OpenID settings - %s", err)
		return
	}

	// `state` will be propagated by OpenID backend and will eventually show up
	// in callback URI handler. See callbackHandler.
	state := map[string]string{
		"dest_url": dest,
		"host_url": r.Host,
	}
	authURI, err := authenticationURI(c, cfg, state)
	if err != nil {
		replyError(c, rw, err, "Can't generate authentication URI - %s", err)
		return
	}
	http.Redirect(rw, r, authURI, http.StatusFound)
}

// logoutHandler nukes active session and redirect back to destination URL.
func (m *CookieAuthMethod) logoutHandler(ctx *router.Context) {
	c, rw, r := ctx.Context, ctx.Writer, ctx.Request

	dest, err := normalizeURL(r.URL.Query().Get("r"))
	if err != nil {
		replyError(c, rw, err, "Bad redirect URI (%q) - %s", dest, err)
		return
	}

	// Close a session if there's one.
	sid, err := decodeSessionCookie(c, r)
	if err != nil {
		replyError(c, rw, err, "Error when decoding session cookie - %s", err)
		return
	}
	if sid != "" {
		(logging.Fields{"sid": sid}).Infof(c, "Closing the session")
		if err = m.SessionStore.CloseSession(c, sid); err != nil {
			replyError(c, rw, err, "Error when closing the session - %s", err)
			return
		}
	}

	// Nuke all session cookies to get to a completely clean state.
	removeCookie(rw, r, sessionCookieName)
	m.removeIncompatibleCookies(rw, r)

	// Redirect to the final destination.
	logging.Infof(c, "Redirecting to %s", dest)
	http.Redirect(rw, r, dest, http.StatusFound)
}

// callbackHandler handles redirect from OpenID backend. Parameters contain
// authorization code that can be exchanged for user profile.
func (m *CookieAuthMethod) callbackHandler(ctx *router.Context) {
	c, rw, r := ctx.Context, ctx.Writer, ctx.Request

	// This code path is hit when user clicks "Deny" on consent page.
	q := r.URL.Query()
	errorMsg := q.Get("error")
	if errorMsg != "" {
		replyError(c, rw, errors.New("login error"), "OpenID login error: %s", errorMsg)
		return
	}

	// Validate inputs.
	code := q.Get("code")
	if code == "" {
		replyError(c, rw, errors.New("login error"), "Missing 'code' parameter")
		return
	}
	stateTok := q.Get("state")
	if stateTok == "" {
		replyError(c, rw, errors.New("login error"), "Missing 'state' parameter")
		return
	}
	state, err := validateStateToken(c, stateTok)
	if err != nil {
		replyError(c, rw, err, "Failed to validate 'state' token")
		return
	}

	// Revalidate "dest_url". It was already validate in loginHandler when
	// generating state token, but just in case.
	dest, err := normalizeURL(state["dest_url"])
	if err != nil {
		replyError(c, rw, err, "Bad redirect URI (%q) - %s", dest, err)
		return
	}

	// Callback URI is hardcoded in OAuth2 client config and must always point
	// to default version on GAE. Yet we want to support logging to non-default
	// versions that have different hostnames. Do some redirect dance here to pass
	// control to required version if necessary (so that it can set cookie on
	// non-default version domain). Same handler with same params, just with
	// different hostname. For most common case of signing in into default version
	// this code path is not triggered.
	if state["host_url"] != r.Host {
		// There's no Scheme in r.URL. Append one, otherwise url.String() returns
		// relative (broken) URL. And replace the hostname with desired one.
		url := *r.URL
		if m.Insecure {
			url.Scheme = "http"
		} else {
			url.Scheme = "https"
		}
		url.Host = state["host_url"]
		logging.Warningf(c, "Redirecting to callback URI on another host %q", url.Host)
		http.Redirect(rw, r, url.String(), http.StatusFound)
		return
	}

	// Use authorization code to grab user profile.
	cfg, err := FetchOpenIDSettings(c)
	if err != nil {
		replyError(c, rw, err, "Can't load OpenID settings - %s", err)
		return
	}
	uid, user, err := handleAuthorizationCode(c, cfg, code)
	if err != nil {
		replyError(c, rw, err, "Error when fetching user profile - %s", err)
		return
	}

	// Grab previous session from the cookie to close it once new one is created.
	prevSid, err := decodeSessionCookie(c, r)
	if err != nil {
		replyError(c, rw, err, "Error when decoding session cookie - %s", err)
		return
	}

	// Create session in the session store.
	expTime := clock.Now(c).Add(sessionCookieToken.Expiration)
	sid, err := m.SessionStore.OpenSession(c, uid, user, expTime)
	if err != nil {
		replyError(c, rw, err, "Error when creating the session - %s", err)
		return
	}
	(logging.Fields{"sid": sid}).Infof(c, "Opened a new session")

	// Kill previous session now that new one is successfully created.
	if prevSid != "" {
		(logging.Fields{"sid": prevSid}).Infof(c, "Closing the previous session")
		if err = m.SessionStore.CloseSession(c, prevSid); err != nil {
			replyError(c, rw, err, "Error when closing the session - %s", err)
			return
		}
	}

	// Set the cookies.
	cookie, err := makeSessionCookie(c, sid, !m.Insecure)
	if err != nil {
		replyError(c, rw, err, "Can't make session cookie - %s", err)
		return
	}
	http.SetCookie(rw, cookie)
	m.removeIncompatibleCookies(rw, r)

	// Redirect to the final destination page.
	logging.Infof(c, "Redirecting to %s", dest)
	http.Redirect(rw, r, dest, http.StatusFound)
}

// removeIncompatibleCookies removes cookies specified by m.IncompatibleCookies.
func (m *CookieAuthMethod) removeIncompatibleCookies(rw http.ResponseWriter, r *http.Request) {
	for _, cookie := range m.IncompatibleCookies {
		removeCookie(rw, r, cookie)
	}
}

////

// normalizeURL verifies URL is parsable and that it is relative.
func normalizeURL(dest string) (string, error) {
	u, err := url.Parse(dest)
	if err != nil {
		return "", err
	}
	// Note: '//host/path' is a location on a server named 'host'.
	if u.IsAbs() || !strings.HasPrefix(u.Path, "/") || strings.HasPrefix(u.Path, "//") {
		return "", errBadDestinationURL
	}
	// path.Clean removes trailing slash. It matters for URLs though. Keep it.
	keepSlash := strings.HasSuffix(u.Path, "/")
	u.Path = path.Clean(u.Path)
	if !strings.HasSuffix(u.Path, "/") && keepSlash {
		u.Path += "/"
	}
	if !strings.HasPrefix(u.Path, "/") {
		return "", errBadDestinationURL
	}
	return u.String(), nil
}

// makeRedirectURL is used to generate login and logout URLs.
func makeRedirectURL(base, dest string) (string, error) {
	dest, err := normalizeURL(dest)
	if err != nil {
		return "", err
	}
	v := url.Values{}
	v.Set("r", dest)
	return base + "?" + v.Encode(), nil
}

// removeCookie sets a cookie to past expiration date so that browser can remove
// it. Also replaced value with junk, in case browser decides to ignore
// expiration time.
func removeCookie(rw http.ResponseWriter, r *http.Request, cookie string) {
	if prev, err := r.Cookie(cookie); err == nil {
		cpy := *prev
		cpy.Value = "deleted"
		cpy.Path = "/"
		cpy.MaxAge = -1
		cpy.Expires = time.Unix(1, 0)
		http.SetCookie(rw, &cpy)
	}
}

// replyError logs the error and replies with HTTP 500 (on transient errors) or
// HTTP 400 on fatal errors (that can happen only on bad requests).
func replyError(ctx context.Context, rw http.ResponseWriter, err error, msg string, args ...interface{}) {
	code := http.StatusBadRequest
	if transient.Tag.In(err) {
		code = http.StatusInternalServerError
	}
	msg = fmt.Sprintf(msg, args...)
	logging.Errorf(ctx, "HTTP %d: %s", code, msg)
	http.Error(rw, msg, code)
}


text:
"""Function helpers.

"""
import numpy as np
from astropy import units as u
from astropy.coordinates import Angle
from astropy.time import Time

from poliastro._math.linalg import norm as norm_fast
from poliastro.core.util import alinspace as alinspace_fast

def norm(vec, axis=None):
    """Norm of a Quantity vector that respects units.

    Parameters
    ----------
    vec : ~astropy.units.Quantity
        Vector with units.
    axis : int or None
        Axis along which to compute the vector norms.

    """
    if axis is not None:
        # axis keyword argument is not yet supported by numba,
        # see https://github.com/numba/numba/issues/2558
        from numpy.linalg import norm as norm_np

        result = norm_np(vec.value, axis=axis)
    else:
        result = norm_fast(vec.value)

    return result << vec.unit

def time_range(
    start, *, num_values=50, spacing=None, end=None, format=None, scale=None
):
    """Generates range of astronomical times.

    .. versionadded:: 0.8.0

    Parameters
    ----------
    start : ~astropy.time.Time or ~astropy.units.Quantity
        Start time.
    num_values : int, optional
        Number of equal spaced time values to be generated, default to 50.
    spacing : ~astropy.time.Time or ~astropy.units.Quantity, optional
        Spacing between periods, optional.
    end : ~astropy.time.Time or equivalent, optional
        End date.

    Returns
    -------
    result: ~astropy.time.Time
        Array of time values.

    """
    start = Time(start, format=format, scale=scale)

    if spacing is not None and end is None:
        result = start + spacing * np.arange(0, num_values)

    elif end is not None and spacing is None:
        end = Time(end, format=format, scale=scale)
        result = start + (end - start) * np.linspace(0, 1, num_values)

    else:
        raise ValueError("Either 'end' or 'spacing' must be specified")

    return result

@u.quantity_input(value=u.rad, values=u.rad)
def find_closest_value(value, values):
    """Calculates the closest value in the given values.

    Parameters
    ----------
    value : ~astropy.units.Quantity
        Reference value.
    values : ~astropy.units.Quantity
        Values to search from.

    """
    index = np.abs(np.asarray(values) * u.rad - value).argmin()
    return values[index]

@u.quantity_input(start=u.rad, stop=u.rad)
def alinspace(start, stop=None, *, num=50, endpoint=True):
    """Return increasing, evenly spaced angular values over a specified interval."""
    if stop is None:
        stop = start + 2 * np.pi * u.rad

    return (
        alinspace_fast(
            start.to_value(u.rad), stop.to_value(u.rad), num, endpoint
        )
        * u.rad
    )

@u.quantity_input(angle=u.rad, limit=u.rad)
def wrap_angle(angle, limit=180 * u.deg):
    return Angle(angle).wrap_at(limit)


text:
from math import sqrt

def is_square(n):
    return n > 0 and sqrt(n).is_integer()

print(is_square(16))
print(is_square(15))
print(is_square(4))


text:
package com.twitter.finagle.memcached.protocol.text

import io.netty.channel.{ChannelHandlerContext, ChannelOutboundHandlerAdapter, ChannelPromise}

/**
 * This encoder handler encodes messages of type `T` to `Buf`s using `encoder`.
 */
private[memcached] class MessageEncoderHandler[T](
    encoder: MessageEncoder[T])
  extends ChannelOutboundHandlerAdapter {

  override def write(ctx: ChannelHandlerContext, msg: Any, promise: ChannelPromise): Unit =
    ctx.write(encoder.encode(msg.asInstanceOf[T]), promise)
}


text:
using System;

namespace SharpVectors.Dom.Svg
{
	/// <summary>
	/// </summary>
	/// <developer>don@donxml.com</developer>
	/// <completed>100</completed>
	public interface ISvgFEGaussianBlurElement:
		ISvgElement,
		ISvgFilterPrimitiveStandardAttributes
	{
		ISvgAnimatedString In1{get;}
		ISvgAnimatedNumber StdDeviationX{get;}
		ISvgAnimatedNumber StdDeviationY{get;}
		void SetStdDeviation(float stdDeviationX, float stdDeviationY);
	}
}


text:
<?php

class MemberGroup extends \Eloquent {
	protected $fillable = [];
	public $timestamps = false;
}


text: brew install ocaml


text:
package main

import "fmt"
import "os/exec"

func main() {
	lsCmd := exec.Command("ping", "-c1", "localhost")
	lsOut, err := lsCmd.Output()
	if err != nil {
		panic(err)
	}
	fmt.Println(string(lsOut))
}


text:
This loopback component enables you to migrate the database and import datas automatcally for the loopback application.

### Installation

1. Install in you loopback project:

  `npm install --save loopback-component-auto-migrate`

2. Create a component-config.json file in your server folder (if you don't already have one)

3. Configure options inside `component-config.json`:

  ```json
  {
    "loopback-component-auto-migrate": {
      "enabled": true,
      "raiseError": false,
      "migration": "auto-migrate-data",
      "models": ["Role"],
      "fixtures": "./test/fixtures/"
    }
  }
  ```
  - `enabled` *Boolean*: optional, whether enable this component. *defaults: true*
  - `raiseError` *Boolean*: optional, whether raise error. *defaults: false*
    * it wont stop to import data if not raise error.
  - `migration` *String* : optional, the migration ways:
    * "auto-migrate": drop and recreate the tables of the database.
    * "auto-migrate-data": drop and recreate the tables, load datas from `fixtures` folder.
    * "auto-update" *defaults*: update the tables of the databse.
    * "auto-update-data": update the tables, load datas from `fixtures` folder.
    * "auto-load-data": load datas from `fixtures` folder.
  - `models` *[array of String]|String*: optional, the models to process. *defaults to the all models in the model-config.json*
    * *String*: a config file location can be used instead of passing all list inside *component-config.json*. eg `"./test/models/model-list"` (you can use yaml, json or cson format by its extension name)
  - `fixtures` *String*: the datas folder to import.
    * the file base name is the lowercase model name with dash seperated if any.
    * the file extension name is the data file format, the following format is supported:
      * cson
      * yaml
      * json

### Usage

#### Automatically use it:

Just enable it on `component-config.json`.

or run `node_modules/.bin/slc-migrate` directly.

set `DEBUG=loopback:component:autoMigrate:*` env variable to show debug info.

When it runs through `component-config.json`, it is attaching the `autoMigrate` promise at `app.get('loopback-component-auto-migrate-done')` that you can use to know when all migrations, data importing etc have finished.

Also the `loopback-component-auto-migrate-status` will be set for convenience:

  * 'loaded': autoMigrate loaded.
  * 'failed': autoMigrate failed.
  * 'done': autoMigrate successful.

#### Manually use it:

```js

autoMigrate = require('loopback-component-auto-migrate/lib/auto-migrate');
autoMigrate(app, {models:['Role'], fixtures: 'yourDataFolder'}).then()

```

#### Options:
Migration can be disabled for the model if you specify `skipMigration` option in the `./server/model-config.json` file:
```
{
  ...
  "customModel": {
      "dataSource": "datasource",
      "public": true,
      "options": {
        "skipMigration": true
      }
  }
  ...
}
```
## History

### v0.2.3

+ attaching done Promise at the app.

### v0.2.0

+ hasMany relation data supports.


text:
package com.github.dockerjava.core.util;

import org.apache.commons.lang.builder.EqualsBuilder;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Representation of filters to service lists.
 */
public class ServiceFiltersBuilder {

    private Map<String, List<String>> filters = new HashMap<>();

    public ServiceFiltersBuilder() {
    }

    public ServiceFiltersBuilder withFilter(String key, String... value) {
        filters.put(key, Arrays.asList(value));
        return this;
    }

    public ServiceFiltersBuilder withFilter(String key, List<String> value) {
        filters.put(key, value);
        return this;
    }

    public List<String> getFilter(String key) {
        return filters.get(key);
    }

    public ServiceFiltersBuilder withIds(List<String> ids) {
        withFilter("id", ids);
        return this;
    }

    public List<String> getIds() {
        return getFilter("id");
    }

    public ServiceFiltersBuilder withNames(List<String> names) {
        withFilter("name", names);
        return this;
    }

    public List<String> getNames() {
        return getFilter("names");
    }

    @Override
    public boolean equals(Object o) {
        return EqualsBuilder.reflectionEquals(this, o);

    }

    @Override
    public int hashCode() {
        return filters.hashCode();
    }

    public Map<String, List<String>> build() {
        return filters;
    }
}


text:
PROMPT Gives a success when object passed to anydata is null
--Arrange
declare
  l_expected department$;
  l_result   integer;
begin
--Act
  ut.expect( anydata.convertObject(l_expected) ).to_be_null();
  l_result :=  ut_assert_processor.get_aggregate_asserts_result();
--Assert
  if l_result = ut_utils.tr_success then
    :test_result := ut_utils.tr_success;
  else
    dbms_output.put_line('expected: '''||ut_utils.tr_success||''', got: '''||l_result||'''' );
  end if;
end;
/


text: Rails.application.config.session_store :cookie_store, key: '_cuhk-air-quality_session'


text:
function bindrituallists() {
    var result = ajaxResponse;
    if (result) {
        var totalItems = result.length;
        $("#home-rituals").html("");
        for (var i = 0; i < totalItems; i++) {
            col3 = $("
").addClass("col-sm-3");
            imageWrapper = $("
").addClass("product-image-wrapper").appendTo(col3);
            singleProduct = $("
").addClass("single-products").appendTo(imageWrapper);
            productinfo = $("
").addClass("productinfo").addClass("text-center").appendTo(singleProduct);
            $("").attr({"href": "rituals=" + result[i].id}).addClass("affair-big-icon").html("").appendTo(productinfo);
            $("").addClass("col-sm-12").html("" + result[i].title + "").appendTo(productinfo);
            $("#home-rituals").append(col3);
        }
        ;
    }
}
/*price range*/
var IsPopUpSignUp;
var IsBooking = false;
var pendingactions = {};
var locationId = 0;
/*scroll to top*/
$(document).ready(function () {
    /*$('#affair-modal').modal({
     keyboard: false
     });*/
    $('#affair-modal').on('hidden.bs.modal', function (e) {
        $('#affair-modal-dialog').removeClass("modal-lg").removeClass("modal-sm");
        $('#affair-modal').modal('hide')
    });
    $(function () {

        $.scrollUp({
            scrollName: 'scrollUp', // Element ID
            scrollDistance: 300, // Distance from top/bottom before showing element (px)
            scrollFrom: 'top', // 'top' or 'bottom'
            scrollSpeed: 300, // Speed back to top (ms)
            easingType: 'linear', // Scroll to top easing (see http://easings.net/)
            animation: 'fade', // Fade, slide, none
            animationSpeed: 200, // Animation in speed (ms)
            scrollTrigger: false, // Set a custom triggering element. Can be an HTML string or jQuery object
            //scrollTarget: false, // Set a custom target element for scrolling to the top
            scrollText: '', // Text for element, can contain HTML
            scrollTitle: false, // Set a custom  title if required.
            scrollImg: false, // Set true to use image
            activeOverlay: false, // Set CSS color to display scrollUp active point, e.g '#00FFFF'
            zIndex: 2147483647 // Z-Index for the overlay
        });
    });

    calljsonservicebyajax("action=getAllRitualsForHome", "service/publicserver.php", function () {
        if (ajaxResponse)
            bindrituallists();
    });

});


text:
require_dependency "semi_static/application_controller"

module SemiStatic
  class GalleriesController < ApplicationController

    require 'semi_static/general'
    include General

    before_action :authenticate_for_semi_static!, :except => [:show]

    layout 'semi_static_dashboards'

    # If we get here as an admin then we are trying to manage the SemiStatic
    # Galleries and Photos. If not we are just trying to get a look at the
    # public photo gallery which is constructed from various Galaries and
    # Photos
    #
    # GET /galleries
    # GET /galleries.json
    def index
      @galleries = Gallery.all
      @photos_without_gallery = Photo.without_gallery
      layout = 'semi_static_dashboards'
      template = 'semi_static/galleries/index'

      respond_to do |format|
        format.html { render :template => template, :layout => layout }
        format.json { render json: @galleries }
      end
    end

    # GET /galleries/1
    # GET /galleries/1.json
    def show
      @gallery = Gallery.find(params[:id])

      respond_to do |format|
        format.html # show.html.erb
        format.json { render json: @gallery }
      end
    end

    # GET /galleries/new
    # GET /galleries/new.json
    def new
      @gallery = Gallery.new(:public => true)

      respond_to do |format|
        format.html # new.html.erb
        format.json { render json: @gallery }
      end
    end

    # GET /galleries/1/edit
    def edit
      @gallery = Gallery.find(params[:id])
    end

    # POST /galleries
    # POST /galleries.json
    def create
      @gallery = Gallery.new(gallery_params)

      respond_to do |format|
        if @gallery.save
          format.html { redirect_to galleries_path, notice: 'Gallery was successfully created.' }
          format.json { render json: @gallery, status: :created, location: @gallery }
        else
          format.html { render action: "new" }
          format.json { render json: @gallery.errors, status: :unprocessable_entity }
        end
      end
    end

    # PUT /galleries/1
    # PUT /galleries/1.json
    def update
      @gallery = Gallery.find(params[:id])

      respond_to do |format|
        if @gallery.update_attributes(gallery_params)
          format.html { redirect_to galleries_path, notice: 'Gallery was successfully updated.' }
          format.json { head :no_content }
        else
          format.html { render action: "edit" }
          format.json { render json: @gallery.errors, status: :unprocessable_entity }
        end
      end
    end

    # DELETE /galleries/1
    # DELETE /galleries/1.json
    def destroy
      @gallery = Gallery.find(params[:id])
      @gallery.destroy

      respond_to do |format|
        format.html { redirect_to galleries_url }
        format.json { head :no_content }
      end
    end

    private

    # Never trust parameters from the scary internet, only allow the white list through.
    def gallery_params
      params.fetch(:gallery, {}).permit(:title, :sub_title, :description, :public, :locale, :position)
    end
  end
end


text:
package com.google.cloud;

import static java.nio.charset.StandardCharsets.UTF_8;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Retrieves Google Cloud project-id and a limited set of instance attributes from Metadata server.
 * @see
 *   https://cloud.google.com/compute/docs/storing-retrieving-metadata
 */
public class MetadataConfig {

  private static final String METADATA_URL = "http://metadata/computeMetadata/v1/";

  private MetadataConfig() {
  }

  public static String getProjectId() {
    return getAttribute("project/project-id");
  }

  public static String getZone() {
    String zoneId = getAttribute("instance/zone");
    if (zoneId.contains("/")) {
      return zoneId.substring(zoneId.lastIndexOf('/') + 1);
    }
    return zoneId;
  }

  public static String getInstanceId() {
    return getAttribute("instance/id");
  }

  public static String getClusterName() {
    return getAttribute("instance/cluster-name");
  }

  private static String getAttribute(String attributeName) {
    try {
      URL url = new URL(METADATA_URL + attributeName);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setRequestProperty("Metadata-Flavor", "Google");
      InputStream input = connection.getInputStream();
      if (connection.getResponseCode() == 200) {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(input, UTF_8))) {
          return reader.readLine();
        }
      }
    } catch (IOException ignore) {
      // ignore
    }
    return null;
  }
}


text:
FROM ubuntu:16.04
MAINTAINER shun

RUN : \
 && set -x \
 && apt-get update \
 && apt-get install -y \
      bash-completion \
      curl \
      git \
      language-pack-ja \
      language-pack-ja-base \
      man \
      manpages-dev \
      ssh \
      sudo \
      unzip \
      zsh \
 && apt-get clean \
 && :

RUN : \
 && useradd shun \
 && usermod -aG sudo shun \
 && echo '%sudo	ALL=(ALL:ALL) NOPASSWD: ALL' > /etc/sudoers.d/sudo-nopasswd \
 && mkdir -p /home/shun/.ssh \
 && touch /home/shun/.ssh/authorized_keys \
 && chown shun:shun -R /home/shun \
 && chmod 700 /home/shun/.ssh \
 && chmod 600 /home/shun/.ssh/authorized_keys \
 && :

RUN : \
 && set -x \
 && apt-get install -y \
      apt-transport-https \
      ca-certificates \
 && apt-get clean \
 && :

RUN : \
 && apt-key adv --keyserver hkp://ha.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D \
 && echo "deb https://apt.dockerproject.org/repo ubuntu-xenial main" > /etc/apt/sources.list.d/docker.list \
 && apt-get update \
 && apt-get install -y \
      docker-engine \
 && apt-get clean \
 && :

RUN : \
 && set -x \
 && apt-get install -y \
      software-properties-common \
 && apt-get clean \
 && add-apt-repository ppa:neovim-ppa/unstable \
 && apt-get update \
 && apt-get install neovim \
 && :

COPY ssh /home/shun/.ssh
COPY bin /home/shun/bin

USER shun
WORKDIR /home/shun
RUN HOME=/home/shun /home/shun/bin/development-environment-setup

COPY docker-entrypoint.sh /usr/local/bin

USER root
RUN ln -sf /usr/share/zoneinfo/Asia/Tokyo /etc/localtime
ENV LANG ja_JP.UTF-8
EXPOSE 22

ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["/usr/sbin/sshd","-D"]


text:
        <title>Zelda Applet</title>

Zelda Applet

        <applet code="Zelda.class"
            width=500
            height=500
            codebase="."
            archive="file:/C:/Apps/BlueJ/lib/bluejcore.jar,file:/C:/Apps/BlueJ/lib/junit.jar,file:/C:/Users/Tim/Timothy Swan/Keepsakes/Programming/Java programs for fun/Zelda V.2/"
            alt="Your browser understands the <APPLET> tag but isn't running the applet, for some reason."
         >

            Your browser is ignoring the <APPLET> tag!
        </applet>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:orientation="vertical" >

    <fragment
        android:id="@+id/navigation_fragment"
        android:name="com.poomoo.edao.navigation.ReturnNavigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/store_information_textView_store_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:paddingLeft="@dimen/margin10"
        android:paddingRight="@dimen/margin10"
        android:paddingTop="@dimen/margin10"
        android:text="贵阳特产水果"
        android:textColor="@color/green"
        android:textSize="@dimen/textsize16" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:paddingLeft="@dimen/margin10"
        android:paddingRight="@dimen/margin5"
        android:paddingTop="@dimen/margin10" >

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center" >

            <ImageView
                android:id="@+id/store_information_imageView_pic"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:scaleType="fitXY"
                android:src="@drawable/ic_love_fund" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1.5"
            android:gravity="center_vertical"
            android:orientation="vertical"
            android:paddingLeft="@dimen/margin5"
            android:paddingRight="@dimen/margin5" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center_vertical"
                android:orientation="horizontal" >

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="3"
                    android:gravity="center_vertical"
                    android:orientation="vertical" >

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:gravity="center_vertical"
                        android:orientation="horizontal" >

                        <RatingBar
                            android:id="@+id/store_information_ratingBar"
                            style="@style/myRatingBar"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:isIndicator="true"
                            android:numStars="5"
                            android:rating="5"
                            android:stepSize="0.1" />
                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:gravity="center_vertical"
                        android:orientation="horizontal" >

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="负责人:"
                            android:textSize="@dimen/textsize12" />

                        <TextView
                            android:id="@+id/store_information_textView_owner"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="XXX"
                            android:textColor="#1995EB"
                            android:textSize="@dimen/textsize12" />
                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:gravity="center_vertical"
                        android:orientation="horizontal" >

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="电话:"
                            android:textSize="@dimen/textsize12" />

                        <TextView
                            android:id="@+id/store_information_textView_tel"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="1888888888"
                            android:textSize="@dimen/textsize12" />
                    </LinearLayout>
                </LinearLayout>
            </LinearLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center_vertical"
                android:orientation="horizontal" >

                <TextView
                    android:id="@+id/store_information_textView_address1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="地址:"
                    android:textSize="@dimen/textsize12" />

                <TextView
                    android:id="@+id/store_information_textView_address"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_toRightOf="@+id/store_information_textView_address1"
                    android:text="世纪城龙禧苑世纪城龙禧苑世纪城龙禧苑世纪城"
                    android:textSize="@dimen/textsize12" />
            </RelativeLayout>
        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal" >

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center" >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_position2" />
        </LinearLayout>

        <TextView
            android:layout_width="5dp"
            android:layout_height="wrap_content" />

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center" >

            <TextView
                android:id="@+id/store_information_textView_distance"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="距离:100m"
                android:textSize="@dimen/textsize10" />
        </LinearLayout>

        <TextView
            android:layout_width="5dp"
            android:layout_height="wrap_content" />

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center" >

            <TextView
                android:id="@+id/store_information_textView_more"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="更多评价"
                android:textColor="@color/textview_selector"
                android:textSize="@dimen/textsize12" />
        </LinearLayout>
    </LinearLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="@dimen/margin10"
        android:background="#F2F2F2" />

</LinearLayout>


text:
<?php

namespace Mobile\IpermindBundle\Model;
use Mobile\IpermindBundle\Model\GameMediator;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Generator
 *
 * @author admin
 */

class Generator {

  private $secret_sequence = array();
  private function __construct(){}

  public static function getInstance(){
      $instance = null;
      if( $instance == null ){
          $instance = new Generator();
      }
      return $instance;
  }

  public function getSecretSequence($level){
      $this->secret_sequence = GameMediator::getStrategy($level);
      return $this->secret_sequence;
  }

}


text:
<?php

class Squareup_Omni_Model_System_Config_Source_Options_Location
{
    protected $_optionsArray = array();

    /**
     * @return array
     */
    public function getAllOptions()
    {
        $collection = Mage::getModel('squareup_omni/location')
            ->getResourceCollection()
            ->addFieldToFilter('status', 1);
        $this->_optionsArray = array();
        if (!empty($collection)) {
            foreach ($collection as $item) {
                $this->_optionsArray[] = array(
                    'label' => $item->getName(),
                    'value'=> $item->getSquareId()
                );
            }

            array_unshift(
                $this->_optionsArray,
                array(
                    'value'=>'', 'label' => Mage::helper('squareup_omni')->__('Please select location')
                )
            );
        }

        return $this->_optionsArray;
    }

    /**
     * Returning the available locations
     * @return array
     */
    public function toOptionArray()
    {
        return $this->getAllOptions();
    }

    /**
     * Get option array
     *
     * @return array
     */
    public function getOptionArray()
    {
        $collection = Mage::getModel('squareup_omni/location')
            ->getResourceCollection()
            ->addFieldToFilter('status', array('eq' => 1));

        if (!empty($collection)) {
            foreach ($collection as $item) {
                $this->_optionsArray[$item->getSquareId()] = $item->getName();
            }
        }

        return $this->_optionsArray;
    }
}

/* Filename: Action.php */
/* Location: app/code/community/Squareup/Omni/Model/System/Config/Source/Options/Action.php */


text:
<TITLE>Review for Robin Hood: Prince of Thieves (1991)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Robin Hood: Prince of Thieves (1991)

reviewed by
Rick Innis

                      ROBIN HOOD, PRINCE OF THIEVES
                       A film review by Rick Innis
                        Copyright 1991 Rick Innis

     I realise this has been extensively reviewed in the past, but as
it's just opened in Britain I thought I'd offer my 2d (old pence) worth.

     Summary: Robin of Locksley returns from the Crusades, accompanied
by a Moorish warrior whose life he saved and who has sworn to repay this
debt of honour, to find his father has been slain and his lands
appropriated by the Sheriff of Nottingham.  Evading pursuit by the
Sheriff's men takes Locksley into the supposedly haunted Sherwood
Forest, where he is accosted by a band of robbers which he then proceeds
to take over, turning them into a force through which he plans to take
his revenge of the Sheriff.

     This film has a lot going for it -- action, adventure and really
wild things by the score.  The script is well written, the plot has some
nice twists and turns in it and the supporting characters are well drawn
-- Marian is fiercely independent and contemptuous of the men's
crusading ambitions, the Sheriff oscillates between being a comic
buffoon and a dangerous madman, and the outlaws are a cheerfully earthy
bunch of Englishmen (with one exception, see below.)

     Unfortunately, to my perceptions, this film has one major flaw --
the star.  In a film in which all bar two of the other characters have
English accents and use British English idioms (and one of them is a
Moor, so that's all right), Costner's American accent and mannerisms jar
dreadfully.  Costner is too clean-cut, decent and wholesomely
all-American to be convincing, and this destroyed a lot of the film for
me.  A decent voice coach would have gone a long way towards sorting
this out.  Unfortunately Christian Slater as Will Scarlet (in a role
severely underplayed, I thought) suffered the same problem.  If everyone
else in the film had had American accents it probably wouldn't have been
so noticeable (c.f., DANGEROUS LIAISONS and AMADEUS), but the mixture
just doesn't work.  I left with the feeling that was originally a
British production which had been hijacked by an American production
company with its eye on the box office and nothing else.

     Verdict: if you sink a few beers first and watch it on video it's
probably bearable, but I think I'll stick with the HTV series with
Michael Praed, made during the early 80's and also now out on video.

--
JANET:           rick@uk.ac.ed.cstr        | Rick Innis, CSTR,
Internet: rick@cstr.ed.ac.uk        | University of Edinburgh,
UUCP:         ..mcsun!ukc!cstr!rick        | Edinburgh, Scotland EH1 1HN.

.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
This is the code block for using a USB camera with Windows 10 IoT Core.

## Methods
The UsbCamera class has these methods:
- **InitializeAsync:** Initializes the first detected camera device asynchronously.
- **StartCameraPreview:** Begins live USB camera feed asynchronously.
- **StopCameraPreview:** Ends live USB camera feed asynchronously.
- **CapturePhoto:** Captures photo from camera feed and stores it in local storage asynchronously. Returns image file as a StorageFile. File is stored in a temporary folder and could be deleted by the system at any time.
- **Dispose:** Performs tasks associated with freeing, releasing, or resetting unmanaged resources.

## Setup
To use this block in your project, you need to perform the following steps:

1. Navigate to your git project folder using Command Prompt and run `git submodule add https://github.com/ms-iot/usb-camera`
2. Next, run `git submodule update`
3. Open your project solution on Visual Studio and right click on Solution -> Add -> Existing Project. Select usb-camera -> UsbCamera -> UsbCamera.csproj.
4. Once usb-camera is added to the solution explorer, right click on References on your project -> Add Reference -> Projects -> Solution. Check UsbCamera and select OK.
5. You should now be able to use UsbCamera objects in your project.

Note: Everytime you clone your project after it's initial creation, you must run the following commands in the project's root folder:
- `git submodule init`
- `git submodule update`

***

This project has adopted the [Microsoft Open Source Code of Conduct](http://microsoft.github.io/codeofconduct). For more information see the [Code of Conduct FAQ](http://microsoft.github.io/codeofconduct/faq.md) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.


text:
package com.facebook.buck.util;

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

import com.facebook.buck.io.DirectoryTraversal;
import com.facebook.buck.io.MorePaths;
import com.google.common.collect.ImmutableSet;

import org.junit.Test;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;
import java.util.regex.Pattern;

public class LicenseCheckTest {

  // Files where we're okay with the license not being the normal Facebook apache one. We also
  // exclude all files under "test/**/testdata/"
  private static final Set<String> NON_APACHE_LICENSE_WHITELIST = ImmutableSet.of(
      // Because it's not originally our code.
      "com/facebook/buck/jvm/java/coverage/ReportGenerator.java",
      "com/facebook/buck/util/WindowsCreateProcessEscape.java",
      "com/facebook/buck/util/WindowsCreateProcessEscapeTest.java");

  @Test
  public void ensureAllSrcFilesHaveTheApacheLicense() throws IOException {
    new JavaCopyrightTraversal(Paths.get("src"), false).traverse();
    new JavaCopyrightTraversal(Paths.get("test"), true).traverse();
  }

  private static class JavaCopyrightTraversal extends DirectoryTraversal {
    private static final Pattern LICENSE_FRAGMENT = Pattern.compile(
        // TODO(simons): This is very lame.
        // The newline character doesn't match "\w", "\\n" so do a non-greedy match until the next
        // part of the copyright.
        "^/\\\\*.*?" +
        "\\\\* Copyright 20\\d\\d-present Facebook, Inc\\..*?" +
        "\\\\* Licensed under the Apache License, Version 2.0 \\(the \"License\"\\); you may.*",
        Pattern.MULTILINE | Pattern.DOTALL);

    private static final Path TEST_DATA = Paths.get("testdata");

    private final boolean ignoreTestData;

    public JavaCopyrightTraversal(Path root, boolean ignoreTestData) {
      super(root);
      this.ignoreTestData = ignoreTestData;
    }

    @Override
    public void visit(Path file, String relativePath) {
      if (!"java".equals(MorePaths.getFileExtension(file)) ||
          // Ignore dangling symlinks.
          !Files.exists(file) ||
          NON_APACHE_LICENSE_WHITELIST.contains(relativePath) ||
          relativePath.startsWith("com/facebook/buck/cli/quickstart/android/")) {
        return;
      }

      if (ignoreTestData) {
        for (Path path : file) {
           if (TEST_DATA.equals(path)) {
             return;
           }
        }
      }

      try {
        String asString = new String(Files.readAllBytes(file), StandardCharsets.UTF_8);

        assertTrue("Check license of: " + relativePath,
            LICENSE_FRAGMENT.matcher(asString).matches());
      } catch (IOException e) {
        fail("Unable to read: " + relativePath);
      }
    }
  }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
J. A. Murray, Syst. veg. ed. 14:911. 1784 May-Jun (Fl. jap. 162. 1784 Aug)

#### Original name
null

### Remarks
null


text:
class Foo {
  {
    Collections.<String>sort(null);
  }
}


text:
<?php

namespace Freisicht\InvoiceImporter;

use Freisicht\InvoiceImporter\Base\ProjectOptionQuery as BaseProjectOptionQuery;

/**
 * Skeleton subclass for performing query and update operations on the 'project_option' table.
 *
 *
 *
 * You should add additional methods to this class to meet the
 * application requirements.  This class will only be generated as
 * long as it does not already exist in the output directory.
 *
 */
class ProjectOptionQuery extends BaseProjectOptionQuery
{

}


text:
package apavlov;

import apavlov.database.Tracker;
import apavlov.input.StubInput;
import apavlov.models.Item;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * The test class for class StartUI.
 *
 * @author Pavlov Artem
 * @since 12.09.2017
 */
public class StartUITest {

    /**
     * The var for get string.
     */
    private StringBuilder sb = new StringBuilder();

    /**
     * The var is lineseperetor (new line).
     */
    private static final String LS = System.lineSeparator();

    /**
     * The war is text welcome program.
     */
    private String welcomeText = String.format("Welcome to program Tracker...%s%s", LS, LS);

    /**
     * The var is text full menu.
     */
    private String menuText = String.format("%2s. %s%s%2s. %s%s%2s. %s%s%2s. %s%s%2s. %s%s%2s. %s%s%2s. %s%s%2s. %s%s%2s. %s%s%2s. %s%s%2s. %s%s%2s. %s%s",
            1, "Show all items;", LS,
            2, "Sort items by id;", LS,
            3, "Sort items by name;", LS,
            4, "Add new item;", LS,
            5, "Search items by name;", LS,
            6, "Delete item by id;", LS,
            7, "Edit item by id;", LS,
            8, "Show all comments item`s by id;", LS,
            9, "Add comment to item by id;", LS,
            10, "Delete comment by index to item by id;", LS,
            11, "Clear comments to item by id;", LS,
            12, "Exit program;", LS);

    /**
     * The var is text exit program.
     */
    private String exitText = String.format("%sProgram is exit...", LS);

    /**
     * The test print all items to console.
     *
     * @throws Exception - check any errors;
     */
    @Test
    public void whenShowAllItems() throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        System.setOut(new PrintStream(out));
        Tracker tracker = new Tracker();
        Item item = new Item("Artem", "student", "001");
        tracker.addItem(item);
        new StartUI(new StubInput(Arrays.asList(new String[]{"1", "12"})), tracker).init();

        String line = String.format("%95s", " ").replace(" ", "-");
        sb.delete(0, sb.length());
        sb.append(welcomeText).append(menuText);
        sb.append(String.format("%s%-5s%-30s%-50s%-11s%s", LS, "ID", "NAME", "DESCRIPTION", "DATE", LS));
        sb.append(String.format("%s%s", line, LS));
        sb.append(String.format("%-5.4s%-30.29s%-50.49s%-11.10s%s", item.getIdItem(), item.getName(), item.getDescription(), item.getDateCreate(), LS));
        sb.append(String.format("%s%s%s", line, LS, LS));
        sb.append(menuText);
        sb.append(exitText);
        assertThat(out.toString(), is(sb.toString()));
    }

    /**
     * The test check sort by id.
     *
     * @throws Exception - check any errors;
     */
    @Test
    public void whenSortById() throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        System.setOut(new PrintStream(out));
        Tracker tracker = new Tracker();
        Item oneItem = new Item("Artem", "student", "002");
        Item twoItem = new Item("Sergey", "student", "001");
        tracker.addItem(oneItem);
        tracker.addItem(twoItem);
        new StartUI(new StubInput(Arrays.asList(new String[]{"2", "12"})), tracker).init();
        assertThat(twoItem.getName(), is(tracker.getAllItems().get(0).getName()));

        sb.delete(0, sb.length());
        sb.append(welcomeText).append(menuText);
        sb.append(String.format("%sThe items is sort by id...%s%s", LS, LS, LS));
        sb.append(menuText);
        sb.append(exitText);
        assertThat(out.toString(), is(sb.toString()));
    }

    /**
     * The test check sort by name.
     *
     * @throws Exception - check any errors;
     */
    @Test
    public void whenSortByName() throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        System.setOut(new PrintStream(out));
        Tracker tracker = new Tracker();
        Item oneItem = new Item("Timur", "student", "001");
        Item twoItem = new Item("Sergey", "student", "002");
        tracker.addItem(oneItem);
        tracker.addItem(twoItem);
        new StartUI(new StubInput(Arrays.asList(new String[]{"3", "12"})), tracker).init();
        assertThat(twoItem.getName(), is(tracker.getAllItems().get(0).getName()));

        sb.delete(0, sb.length());
        sb.append(welcomeText).append(menuText);
        sb.append(String.format("%sThe items is sort by name...%s%s", LS, LS, LS));
        sb.append(menuText);
        sb.append(exitText);
        assertThat(out.toString(), is(sb.toString()));
    }

    /**
     * The test check menu add new item.
     *
     * @throws Exception - check any errors;
     */
    @Test
    public void whenMenuAddItem() throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        System.setOut(new PrintStream(out));
        Tracker tracker = new Tracker();
        new StartUI(new StubInput(Arrays.asList(new String[]{"4", "Artem", "student", "12"})), tracker).init();
        assertThat("Artem", is(tracker.getAllItems().get(0).getName()));

        sb.delete(0, sb.length());
        sb.append(welcomeText).append(menuText);
        sb.append(String.format("%sThe item is be create...%s%s", LS, LS, LS));
        sb.append(menuText);
        sb.append(exitText);
        assertThat(out.toString(), is(sb.toString()));
    }

    /**
     * The test check search items by name.
     *
     * @throws Exception - check any errors;
     */
    @Test
    public void whenSearchByName() throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        System.setOut(new PrintStream(out));
        Tracker tracker = new Tracker();
        Item oneItem = new Item("Alexey", "student", "001");
        Item twoItem = new Item("Alexandr", "student", "002");
        Item threeItem = new Item("Anton", "student", "003");
        tracker.addItem(oneItem);
        tracker.addItem(twoItem);
        tracker.addItem(threeItem);
        new StartUI(new StubInput(Arrays.asList(new String[]{"5", "alex", "12"})), tracker).init();

        String line = String.format("%95s", " ").replace(" ", "-");
        sb.delete(0, sb.length());
        sb.append(welcomeText).append(menuText);
        sb.append(String.format("%s%-5s%-30s%-50s%-11s%s", LS, "ID", "NAME", "DESCRIPTION", "DATE", LS));
        sb.append(String.format("%s%s", line, LS));
        sb.append(String.format("%-5.4s%-30.29s%-50.49s%-11.10s%s", oneItem.getIdItem(), oneItem.getName(), oneItem.getDescription(), oneItem.getDateCreate(), LS));
        sb.append(String.format("%-5.4s%-30.29s%-50.49s%-11.10s%s", twoItem.getIdItem(), twoItem.getName(), twoItem.getDescription(), twoItem.getDateCreate(), LS));
        sb.append(String.format("%s%s%s", line, LS, LS));
        sb.append(menuText);
        sb.append(exitText);
        assertThat(out.toString(), is(sb.toString()));
    }

    /**
     * The test check delete item with base.
     *
     * @throws Exception - check any errors;
     */
    @Test
    public void whenDeleteItem() throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        System.setOut(new PrintStream(out));
        Tracker tracker = new Tracker();
        tracker.addItem(new Item("Artem", "student", "001"));
        tracker.addItem(new Item("Pasha", "student", "002"));
        new StartUI(new StubInput(Arrays.asList(new String[]{"6", "001", "12"})), tracker).init();
        assertThat(1, is(tracker.getAllItems().size()));

        sb.delete(0, sb.length());
        sb.append(welcomeText).append(menuText);
        sb.append(String.format("%sThe item is delete!%s%s", LS, LS, LS));
        sb.append(menuText);
        sb.append(exitText);
        assertThat(out.toString(), is(sb.toString()));
    }

    /**
     * The test check edit item by id.
     *
     * @throws Exception - check any errors;
     */
    @Test
    public void whenEditItemById() throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        System.setOut(new PrintStream(out));
        Tracker tracker = new Tracker();
        tracker.addItem(new Item("Artem", "student", "001"));
        new StartUI(new StubInput(Arrays.asList(new String[]{"7", "001", "Anton", "student", "12"})), tracker).init();
        assertThat("Anton", is(tracker.getAllItems().get(0).getName()));
        sb.delete(0, sb.length());
        sb.append(welcomeText).append(menuText);
        sb.append(String.format("%sThe item is edit!%s%s", LS, LS, LS));
        sb.append(menuText);
        sb.append(exitText);
        assertThat(out.toString(), is(sb.toString()));
    }

    /**
     * The test check add comment by id item`s.
     *
     * @throws Exception - check any errors;
     */
    @Test
    public void whenAddCommentByItemId() throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        System.setOut(new PrintStream(out));
        Tracker tracker = new Tracker();
        tracker.addItem(new Item("Artem", "student", "001"));
        new StartUI(new StubInput(Arrays.asList(new String[]{"9", "001", "make java", "12"})), tracker).init();
        assertThat("make java", is(tracker.getAllItems().get(0).getComments().get(0).getComment()));

        sb.delete(0, sb.length());
        sb.append(welcomeText).append(menuText);
        sb.append(String.format("%sThe comment is add!%s%s", LS, LS, LS));
        sb.append(menuText);
        sb.append(exitText);
        assertThat(out.toString(), is(sb.toString()));
    }

    /**
     * The test check print all comments item`s by id.
     *
     * @throws Exception - check any errors;
     */
    @Test
    public void whenShowAllCommentsItemById() throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        System.setOut(new PrintStream(out));
        Tracker tracker = new Tracker();
        Item item = new Item("Artem", "student", "001");
        tracker.addItem(item);
        tracker.addCommentToItem(item, "make java");
        new StartUI(new StubInput(Arrays.asList(new String[]{"8", "001", "12"})), tracker).init();

        String line = String.format("%80s", " ").replace(" ", "-");
        sb.delete(0, sb.length());
        sb.append(welcomeText).append(menuText);
        sb.append(String.format("%s%-7s%-13s%-11s%-50s%s", LS, "INDEX", "DATE", "TIME", "COMMENT", LS));
        sb.append(String.format("%s%s", line, LS));
        String[] dateAndTime = item.getComments().get(0).getDateAndTimeCreate().split(" ");
        sb.append(String.format("%-7s%-13s%-11s%-50s%s", 1, dateAndTime[0], dateAndTime[1], item.getComments().get(0).getComment(), LS));
        sb.append(String.format("%s%s%s", line, LS, LS));
        sb.append(menuText);
        sb.append(exitText);
        assertThat(out.toString(), is(sb.toString()));
    }

    /**
     * The test check delete comment with item by index.
     *
     * @throws Exception - check any errors;
     */
    @Test
    public void whenDeleteCommentByIndex() throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        System.setOut(new PrintStream(out));
        Tracker tracker = new Tracker();
        Item item = new Item("Artem", "student", "001");
        tracker.addItem(item);
        tracker.addCommentToItem(item, "make java");
        new StartUI(new StubInput(Arrays.asList(new String[]{"10", "001", "1", "12"})), tracker).init();
        assertThat(0, is(tracker.getSizeComments(item)));

        sb.delete(0, sb.length());
        sb.append(welcomeText).append(menuText);
        sb.append(String.format("%sThe comment is delete!%s%s", LS, LS, LS));
        sb.append(menuText);
        sb.append(exitText);
        assertThat(out.toString(), is(sb.toString()));
    }

    /**
     * The test check delete all comments with item by id.
     *
     * @throws Exception - check any errors;
     */
    @Test
    public void whenClearAllCommentsItemById() throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        System.setOut(new PrintStream(out));
        Tracker tracker = new Tracker();
        Item item = new Item("Artem", "student", "001");
        tracker.addItem(item);
        tracker.addCommentToItem(item, "make java");
        tracker.addCommentToItem(item, "play soccer");
        new StartUI(new StubInput(Arrays.asList(new String[]{"11", "001", "12"})), tracker).init();
        assertThat(0, is(tracker.getSizeComments(item)));

        sb.delete(0, sb.length());
        sb.append(welcomeText).append(menuText);
        sb.append(String.format("%sThe comments is clear!%s%s", LS, LS, LS));
        sb.append(menuText);
        sb.append(exitText);
        assertThat(out.toString(), is(sb.toString()));
    }

    /**
     * The test check exit for program.
     *
     * @throws Exception - check any errors;
     */
    @Test
    public void whenExitProgram() throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        System.setOut(new PrintStream(out));
        new StartUI(new StubInput(Arrays.asList(new String[]{"12"})), new Tracker()).init();

        sb.delete(0, sb.length());
        sb.append(welcomeText).append(menuText);
        sb.append(exitText);
        assertThat(out.toString(), is(sb.toString()));
    }
}


text:
package com.cnpc.framework.query.service;

import com.cnpc.framework.base.service.BaseService;
import com.cnpc.framework.query.entity.QueryConfig;

import java.util.List;
import java.util.Map;

public interface QueryService extends BaseService {

    /**
     * 通用加载数据方法
     *
     * @param reqObj 前台请求参数
     * @return
     */
    Map<String, Object> loadData(String reqObj) throws Exception;

    /**
     * 通用数据导出,生成excel
     *
     * @param reqObj    请求参数,可能含多个tab页面
     * @param tableName 表名
     * @return 生成导出文件的名称
     * @throws Exception
     */
    String exportData(String reqObj, String tableName) throws Exception;

    /**
     * 用户自定义的隐藏列
     * @param queryId
     * @param pageName
     * @param userid
     * @return
     */
    List<String> getSelectedColumns(String queryId, String pageName, String userid);

    /**
     * 保存用户自定义设置
     *
     * @param queryConfig
     */
    void deleteAndSave(QueryConfig queryConfig);

    /**
     * 恢复默认
     *
     * @param queryConfig
     */
    void delete(QueryConfig queryConfig);
}