text:
using ElectronicObserver.Data;
using ElectronicObserver.Resource;
using ElectronicObserver.Resource.Record;
using ElectronicObserver.Window.Support;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ElectronicObserver.Window.Dialog
{
	public partial class DialogShipGraphicViewer : Form
	{

		List<string> ImagePathList;
		int CurrentIndex;
		Bitmap CurrentImage;

		Point ImageOffset = new Point();
		Point PreviousMouseLocation = new Point();
		double ZoomRate = 1;
		InterpolationMode Interpolation = InterpolationMode.NearestNeighbor;
		bool AdvMode = false;
		bool RestrictedPatch = false;
		bool DrawsInformation = true;

		private DialogShipGraphicViewer()
		{
			InitializeComponent();
			ImagePathList = new List<string>();

			MouseWheel += DialogShipGraphicViewer_MouseWheel;

			SetStyle(ControlStyles.ResizeRedraw, true);
			ControlHelper.SetDoubleBuffered(DrawingPanel);

			OpenSwfDialog.InitialDirectory = Utility.Configuration.Config.Connection.SaveDataPath + @"kcs2\resources\ship";

			// 背景画像生成
			var back = new Bitmap(16, 16, PixelFormat.Format24bppRgb);
			using (var g = Graphics.FromImage(back))
			{
				g.Clear(Color.White);
				g.FillRectangle(Brushes.LightGray, new Rectangle(0, 0, 8, 8));
				g.FillRectangle(Brushes.LightGray, new Rectangle(8, 8, 8, 8));
			}
			DrawingPanel.BackgroundImage = back;

		}

		public DialogShipGraphicViewer(string path)
			: this()
		{

			Open(path);
		}

		public DialogShipGraphicViewer(string[] pathlist)
			: this()
		{
			Open(pathlist);
		}

		public DialogShipGraphicViewer(int shipID)
			: this()
		{
			Open(shipID);
		}

		private void DialogShipGraphicViewer_Load(object sender, EventArgs e)
		{

			this.Icon = ResourceManager.ImageToIcon(ResourceManager.Instance.Icons.Images[(int)ResourceManager.IconContent.FormAlbumShip]);

			RefreshImage();
		}

		private void DialogShipGraphicViewer_FormClosed(object sender, FormClosedEventArgs e)
		{
			if (DrawingPanel.BackgroundImage != null)
				DrawingPanel.BackgroundImage.Dispose();
			ResourceManager.DestroyIcon(Icon);
		}

		#region Input Controls

		private void DialogShipGraphicViewer_KeyDown(object sender, KeyEventArgs e)
		{

			if (ImagePathList.Count == 0)
				return;

			bool fileChanged = false;

			if (e.KeyCode == Keys.Left)
			{
				CurrentIndex--;
				fileChanged = true;
			}
			else if (e.KeyCode == Keys.Right)
			{
				CurrentIndex++;
				fileChanged = true;

			}
			else if (e.KeyCode == Keys.Up)
			{
				ZoomRate += 0.1;
			}
			else if (e.KeyCode == Keys.Down)
			{
				ZoomRate -= 0.1;

			}
			else if (e.KeyCode == Keys.Oemtilde)
			{   // "@"
				AdvMode = !AdvMode;
				RestrictedPatch = AdvMode && e.Shift;

			}
			else return;

			if (fileChanged)
			{
				CurrentIndex %= ImagePathList.Count;
				if (CurrentIndex < 0)
					CurrentIndex += ImagePathList.Count;

				try
				{
					CurrentImage?.Dispose();
					CurrentImage = null;
					using (var stream = new FileStream(ImagePathList[CurrentIndex], FileMode.Open, FileAccess.Read))
						CurrentImage = new Bitmap(stream);
				}
				catch (Exception ex)
				{
					Utility.Logger.Add(3, $"画像ビューア:画像ロード時にエラーが発生しました。{ex.Message}");
				}
				ImageOffset = new Point();
				ZoomRate = 1;
			}

			ValidateParameters();
			RefreshImage();
		}

		void DialogShipGraphicViewer_MouseWheel(object sender, MouseEventArgs e)
		{
			double wheel_delta = 120;
			ZoomRate += (e.Delta / wheel_delta) * 0.1;
			ValidateParameters();
			RefreshImage();
		}

		private void DrawingPanel_MouseMove(object sender, MouseEventArgs e)
		{
			if (e.Button == System.Windows.Forms.MouseButtons.Left)
			{
				ImageOffset.X += e.Location.X - PreviousMouseLocation.X;
				ImageOffset.Y += e.Location.Y - PreviousMouseLocation.Y;
				RefreshImage();
			}
			PreviousMouseLocation = e.Location;
		}

		private void DrawingPanel_MouseClick(object sender, MouseEventArgs e)
		{
			PreviousMouseLocation = e.Location;
		}

		#endregion

		#region View Control

		private void TopMenu_View_InterpolationMode_Sharp_Click(object sender, EventArgs e)
		{

			foreach (ToolStripMenuItem item in TopMenu_View_InterpolationMode.DropDownItems)
			{
				if (object.ReferenceEquals(item, sender))
					item.CheckState = CheckState.Indeterminate;
				else
					item.CheckState = CheckState.Unchecked;
			}

			if (TopMenu_View_InterpolationMode_Sharp.Checked)
				Interpolation = InterpolationMode.NearestNeighbor;
			else if (TopMenu_View_InterpolationMode_Smooth.Checked)
				Interpolation = InterpolationMode.HighQualityBicubic;

			RefreshImage();
		}

		private void TopMenu_View_Zoom_In_Click(object sender, EventArgs e)
		{
			ZoomRate += 0.1;
			ValidateParameters();
		}

		private void TopMenu_View_Zoom_Out_Click(object sender, EventArgs e)
		{
			ZoomRate -= 0.1;
			ValidateParameters();
		}

		private void TopMenu_View_Zoom_100_Click(object sender, EventArgs e)
		{
			ZoomRate = 1;
			RefreshImage();
		}

		private void TopMenu_View_Zoom_Fit_Click(object sender, EventArgs e)
		{
			RefreshImage();
		}

		private void ValidateParameters()
		{
			ZoomRate = Math.Min(Math.Max(ZoomRate, 0.1), 16);
		}

		#endregion

		#region File Control

		private void Open(string path)
		{
			Open(new string[] { path });
		}

		private void Open(string[] pathlist)
		{
			try
			{
				ImagePathList = pathlist.Where(p => File.Exists(p)).ToList();

				if (ImagePathList.Count == 0)
				{
					MessageBox.Show("画像が見つかりませんでした。", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					return;
				}

				CurrentIndex = 0;
				CurrentImage?.Dispose();
				CurrentImage = null;

				using (var stream = new FileStream(ImagePathList[CurrentIndex], FileMode.Open, FileAccess.Read))
					CurrentImage = new Bitmap(stream);

			}
			catch (Exception ex)
			{
				MessageBox.Show(string.Join("\r\n", pathlist) + "を開けませんでした。\r\n" + ex.GetType().Name + "\r\n" + ex.Message);
				ImagePathList.Clear();
				CurrentImage?.Dispose();
				CurrentImage = null;
			}
			finally
			{
				RefreshImage();
			}

		}

		private void Open(int shipID)
		{
			var ship = KCDatabase.Instance.MasterShips[shipID];

			if (ship == null)
				return;

			var list = new LinkedList<string>();

			void Add(int id, bool isDamaged, string resourceType)
			{
				if (resourceType == KCResourceHelper.ResourceTypeShipName && isDamaged)
					return;

				var path = KCResourceHelper.GetShipImagePath(id, isDamaged, resourceType);
				if (path != null)
					list.AddLast(path);
			}
			void AddShip(int id)
			{
				Add(id, false, KCResourceHelper.ResourceTypeShipBanner);
				Add(id, true, KCResourceHelper.ResourceTypeShipBanner);
				Add(id, false, KCResourceHelper.ResourceTypeShipCard);
				Add(id, true, KCResourceHelper.ResourceTypeShipCard);
				Add(id, false, KCResourceHelper.ResourceTypeShipAlbumZoom);
				Add(id, true, KCResourceHelper.ResourceTypeShipAlbumZoom);
				Add(id, false, KCResourceHelper.ResourceTypeShipAlbumFull);
				Add(id, true, KCResourceHelper.ResourceTypeShipAlbumFull);
				Add(id, false, KCResourceHelper.ResourceTypeShipFull);
				Add(id, true, KCResourceHelper.ResourceTypeShipFull);
				Add(id, false, KCResourceHelper.ResourceTypeShipCutin);
				Add(id, true, KCResourceHelper.ResourceTypeShipCutin);
				Add(id, false, KCResourceHelper.ResourceTypeShipName);
				Add(id, false, KCResourceHelper.ResourceTypeShipSupply);
				Add(id, true, KCResourceHelper.ResourceTypeShipSupply);
			}

			AddShip(shipID);
			foreach (var rec in RecordManager.Instance.ShipParameter.Record.Values.Where(r => r.OriginalCostumeShipID == shipID))
				AddShip(rec.ShipID);

			Open(list.ToArray());
		}

		private void TopMenu_File_Open_Click(object sender, EventArgs e)
		{
			if (OpenSwfDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			{
				Open(OpenSwfDialog.FileNames);
			}
		}

		private void TopMenu_File_CopyToClipboard_Click(object sender, EventArgs e)
		{
			if (CurrentImage == null)
			{
				System.Media.SystemSounds.Exclamation.Play();
				return;
			}

			try
			{
				Clipboard.SetImage(CurrentImage);
			}
			catch (Exception)
			{
				System.Media.SystemSounds.Exclamation.Play();
			}
		}

		private void DialogShipGraphicViewer_DragEnter(object sender, DragEventArgs e)
		{
			if (e.Data.GetDataPresent(DataFormats.FileDrop))
				e.Effect = DragDropEffects.Copy;
			else
				e.Effect = DragDropEffects.None;
		}

		private void DialogShipGraphicViewer_DragDrop(object sender, DragEventArgs e)
		{
			Open((string[])e.Data.GetData(DataFormats.FileDrop));
		}

		#endregion

		#region Drawing

		private void DrawingPanel_Paint(object sender, PaintEventArgs e)
		{
			if (CurrentImage == null)
				return;

			e.Graphics.InterpolationMode = Interpolation;
			e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

			var panelSize = DrawingPanel.Size;

			double zoomRate = ZoomRate;
			if (TopMenu_View_Zoom_Fit.Checked)
			{
				zoomRate = Math.Min((double)panelSize.Width / CurrentImage.Width, (double)panelSize.Height / CurrentImage.Height);
			}

			var imgSize = new SizeF((float)(CurrentImage.Width * zoomRate), (float)(CurrentImage.Height * zoomRate));

			if (DrawsInformation)
			{
				var ship = GetShipFromPath(ImagePathList[CurrentIndex]);

				e.Graphics.DrawString(
					string.Format("{0} / {1}\r\n{2} ({3})\r\nZoom {4:p1}\r\n(←/→キーでページめくり)",
						CurrentIndex + 1, ImagePathList.Count, Path.GetFileName(ImagePathList[CurrentIndex]), ship?.NameWithClass ?? "???", zoomRate),
					Font, Brushes.DimGray, new PointF(0, 0));
			}

			var location = new PointF((panelSize.Width - imgSize.Width) / 2 + ImageOffset.X, (panelSize.Height - imgSize.Height) / 2 + ImageOffset.Y);
			e.Graphics.DrawImage(CurrentImage, new RectangleF(location.X, location.Y, imgSize.Width, imgSize.Height));

			/*// face recognition test
			{
				var ship = GetShipFromPath(ImagePathList[CurrentIndex]);
				if (ship != null)
				{
					var rect = ship.GraphicData.WeddingArea;
					e.Graphics.DrawRectangle(Pens.Magenta,
						(float)(panelSize.Width / 2.0 + ((double)rect.X / CurrentImage.Width - 0.5) * CurrentImage.Width * zoomRate + ImageOffset.X),
						(float)(panelSize.Height / 2.0 + ((double)rect.Y / CurrentImage.Height - 0.5) * CurrentImage.Height * zoomRate + ImageOffset.Y),
						(float)(rect.Width * zoomRate),
						(float)(rect.Height * zoomRate));
				}
			}
			//*/

			if (AdvMode)
			{
				DrawAdvMode(e.Graphics);
			}

		}

		// かん☆これ!!
		private void DrawAdvMode(Graphics g)
		{

			var ship = GetShipFromPath(ImagePathList[CurrentIndex]);
			if (ship == null)
				return;

			var panelSize = DrawingPanel.Size;

			int mainHeight = 200;
			int nameHeight = 64;
			var mainBound = new Rectangle(16, panelSize.Height - mainHeight - 16, panelSize.Width - 32, mainHeight);
			var innerBound = new Rectangle(mainBound.X + 16, mainBound.Y + 16, mainBound.Width - 32, mainBound.Height - 32);
			var nameBound = new Rectangle(16, mainBound.Y - nameHeight - 16, 256, nameHeight);
			var nameInnerBound = new Rectangle(nameBound.X + 16, nameBound.Y + 16, nameBound.Width - 32, nameBound.Height - 32);

			var rand = new Random(401168);      // for fixed drawing

			// window shadow
			using (var pen = new Pen(Color.RoyalBlue, 8))
			{
				pen.LineJoin = LineJoin.Round;
				g.DrawRectangle(pen, new Rectangle(mainBound.X + 2, mainBound.Y + 2, mainBound.Width, mainBound.Height));
				g.DrawRectangle(pen, new Rectangle(nameBound.X + 2, nameBound.Y + 2, nameBound.Width, nameBound.Height));
			}

			// window base
			using (var grad = new LinearGradientBrush(mainBound, Color.FromArgb(0xcc, 0x44, 0xcc, 0xff), Color.FromArgb(0xcc, 0x44, 0x44, 0xff), 90))
			{
				g.FillRectangle(grad, mainBound);
			}
			using (var grad = new LinearGradientBrush(nameBound, Color.FromArgb(0xcc, 0x44, 0xcc, 0xff), Color.FromArgb(0xcc, 0x44, 0x44, 0xff), 90))
			{
				g.FillRectangle(grad, nameBound);
			}

			// decorations
			g.SetClip(mainBound);

			using (var pen = new Pen(Color.FromArgb(0x44, 0xcc, 0xee, 0xff), 4))
			{
				Point center = new Point(mainBound.X + mainHeight * 3 / 4, mainBound.Y + mainHeight * 3 / 4);

				// compass
				g.DrawEllipse(pen, new Rectangle(center.X - 150, center.Y - 150, 300, 300));
				g.DrawEllipse(pen, new Rectangle(center.X - 140, center.Y - 140, 280, 280));
				g.DrawEllipse(pen, new Rectangle(center.X - 16, center.Y - 16, 32, 32));

				int direct = (int)(120 * Math.Sin(Math.PI / 4));

				var path = new GraphicsPath();
				path.AddLines(new Point[] {
						new Point( center.X + direct, center.Y - direct ),
						new Point( center.X + 16, center.Y + 16 ),
						new Point( center.X - direct, center.Y + direct ),
						new Point( center.X - 16, center.Y - 16 )
					});
				path.CloseFigure();
				g.DrawPath(pen, path);

				// bubbles
				for (int i = 0; i < 16; i++)
				{
					int r = (int)(8 + rand.NextDouble() * 24 * i / 8);
					g.DrawEllipse(pen, new Rectangle(
						mainBound.Right - 96 + (int)((rand.NextDouble() * 128 - 64) * (i + 1) / 16),
						mainBound.Bottom - 16 - (i * mainBound.Height) / 16,
						r, r
						));
				}
			}

			g.ResetClip();

			// window frame
			using (var pen = new Pen(Color.White, 8))
			{
				pen.LineJoin = LineJoin.Round;
				g.DrawRectangle(pen, mainBound);
				g.DrawRectangle(pen, nameBound);
			}

			// text
			// don't think (about env that font is not installed), feel
			using (var font = new Font("にゃしぃフォント改二", 32, FontStyle.Regular, GraphicsUnit.Pixel))
			{
				var rec = Resource.Record.RecordManager.Instance.ShipParameter[ship.ShipID];
				string mes = null;

				if (rec == null)
				{
					mes = "……";

				}
				else
				{
					var processedShips = new LinkedList<ShipDataMaster>();
					processedShips.AddLast(ship);

					while (processedShips.Last.Value.RemodelBeforeShip != null && !processedShips.Any(s2 => processedShips.Last.Value.RemodelBeforeShipID == s2.ShipID))
					{
						processedShips.AddLast(processedShips.Last.Value.RemodelBeforeShip);
					}

					foreach (var s in processedShips)
					{
						string mescan = s.MessageGet.Replace("
", "\r\n");
						if (!string.IsNullOrWhiteSpace(mescan))
						{
							mes = mescan;
							break;
						}
					}

					if (mes == null)
					{
						foreach (var s in processedShips)
						{
							string mescan = s.MessageAlbum.Replace("
", "\r\n");
							if (!string.IsNullOrWhiteSpace(mescan))
							{
								mes = mescan;
								break;
							}
						}
					}

					if (mes == null)
						mes = "……";
				}

				if (RestrictedPatch)
				{
					mes = mes
						.Replace("。", "♥")
						.Replace(".\r\n", "♥\r\n")
						.Replace("……", "…")
						.Replace("…", "…♥")
						.Replace("!", "!♥")
						.Replace("?", "?♥")
						.Replace("!", "!♥")
						.Replace("?", "?♥")
						;
				}

				g.DrawString(mes, font, Brushes.RoyalBlue, new Rectangle(innerBound.Location + new Size(2, 2), innerBound.Size));
				g.DrawString(mes, font, Brushes.White, innerBound);

				g.DrawString(ship.NameWithClass, font, Brushes.RoyalBlue, new Rectangle(nameInnerBound.Location + new Size(2, 2), nameInnerBound.Size));
				g.DrawString(ship.NameWithClass, font, Brushes.White, nameInnerBound);
			}
		}

		private void DrawingPanel_Resize(object sender, EventArgs e)
		{
			RefreshImage();
		}

		private void RefreshImage()
		{
			DrawingPanel.Refresh();
		}

		#endregion

		private ShipDataMaster GetShipFromPath(string path)
		{
			path = Path.GetFileNameWithoutExtension(path);

			if (path.Length >= 4 && int.TryParse(path.Substring(0, 4), out var id))
			{
				return KCDatabase.Instance.MasterShips[id];
			}

			return null;
		}

	}
}


text:
{-# LANGUAGE CPP #-}
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
{-# LANGUAGE ViewPatterns, PatternGuards #-}
{-# LANGUAGE FlexibleContexts, ConstraintKinds #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE LambdaCase #-}
{-# OPTIONS_GHC -Wall #-}

{-# OPTIONS_GHC -fno-warn-unused-imports #-} -- TEMP
-- {-# OPTIONS_GHC -fno-warn-unused-binds   #-} -- TEMP

----------------------------------------------------------------------
-- |
-- Module      :  LambdaCCC.TransCode
-- Copyright   :  (c) 2014 Tabula, Inc.
--
-- Maintainer  :  conal@tabula.com
-- Stability   :  experimental
--
-- Transform a Core program to use only standard types
----------------------------------------------------------------------

module LambdaCCC.TransCode where

-- TODO: explicit exports

import Prelude hiding (id,(.),(>>))
import qualified Prelude

import Control.Category (id,(.),(>>>))
import Control.Arrow (arr)
import Control.Monad (unless,(<=<))
import Data.Functor ((<$),(<$>))
import Control.Applicative (pure,(<*>),liftA2)
import Data.Monoid (mempty)
import Data.List (intercalate,isPrefixOf)
import qualified Data.Set as S

-- GHC
import PrelNames (eitherTyConName)

import HERMIT.Core (CoreDef(..))
import HERMIT.Dictionary hiding (externals)
import HERMIT.External (External,ExternalName,external,(.+),CmdTag(Loop))
import HERMIT.GHC
import HERMIT.Kure
import HERMIT.Monad (saveDef,newIdH,Label)
import HERMIT.Plugin (hermitPlugin,phase,interactive)

import HERMIT.Extras hiding (findTyConT)
import qualified HERMIT.Extras as Ex

-- import TypeEncode.Plugin (findCon)

import LambdaCCC.Misc ((<~))

import qualified LambdaCCC.Monomorphize as Mono

{--------------------------------------------------------------------
    Encoding
--------------------------------------------------------------------}

class Enc a where enc :: a -> TransformH x a

instance (Enc a, Enc b) => Enc (a,b) where
  enc (a,b) = (,) <$> enc a <*> enc b
instance Enc a => Enc [a] where enc = mapM enc

instance Enc CoreExpr where
  enc e@(Lit _) = return e
  enc (Var v) = Var <$> enc v   -- Revisit for non-local vars
  enc (App u v) = App <$> enc u <*> enc v
  enc (Lam x e) = Lam <$> enc x <*> enc e
  enc (Let b e) = Let <$> enc b <*> enc e
  enc (Case e _w _ty [(_,dropTvars -> [v],rhs)]) =
    -- TODO: Check whether _w is in rhs
    -- TODO: Maybe drop this special case.
    return $ Let (NonRec v e) rhs
  enc (Case e w ty [alt]) =
    Case <$> enc e
         <*> enc w
         <*> enc ty
         <*> ((:[]) <$> encAlt alt)
  enc (Case _ _ _ _) = error "enc: Case: not a single alternative"
  enc (Cast e _co) = enc e  -- Experiment
  enc (Tick t e) = Tick t <$> enc e
  enc (Type t) = Type <$> enc t
  enc (Coercion _co) = error "enc: Coercion -- ??"

encAlt :: CoreAlt -> TransformH x CoreAlt
encAlt (_,dropTvars -> vs,e) =
  (DataAlt (tupleCon BoxedTuple (length vs)),vs,) <$> enc e

-- Drop type variables including coercions
dropTvars :: Unop [Var]
dropTvars = filter (not . isTyVar)

instance Enc Id where
  enc v | isId v    = newIdT (uqVarName v) . enc (varType v)
        | otherwise = return v

instance Enc Type where
  enc (TyConApp tc tys) | isDistribTC tc = TyConApp tc <$> enc tys
  enc (FunTy a b) = FunTy <$> enc a <*> enc b
  enc t = observeR "enc: unhandled type" $* t

isDistribTC :: TyCon -> Bool
isDistribTC tc =
     any ($ tc) [isTupleTyCon,isFunTyCon] && tyConArity tc == 2
  || tc == unitTyCon

instance Enc CoreBind where
  enc (NonRec v e) = NonRec <$> enc v <*> enc e
  enc (Rec ws) = Rec <$> enc ws

encode :: Enc a => RewriteH a
encode = id >>= enc

{--------------------------------------------------------------------
    Plugin
--------------------------------------------------------------------}

plugin :: Plugin
plugin = hermitPlugin (phase 0 . interactive externals)
 where
   externals =
     [ externC "encodeBind" (encode :: RewriteH CoreBind) "..."
     ]
     ++ Mono.externals

redpajama_set_name: RedPajamaGithub


text:
#pragma once
#include <aws/cloudformation/CloudFormation_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/cloudformation/model/ResponseMetadata.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Xml
{
  class XmlDocument;
} // namespace Xml
} // namespace Utils
namespace CloudFormation
{
namespace Model
{
  class AWS_CLOUDFORMATION_API DetectStackSetDriftResult
  {
  public:
    DetectStackSetDriftResult();
    DetectStackSetDriftResult(const Aws::AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);
    DetectStackSetDriftResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);

    /**
     *
The ID of the drift detection stack set operation.

You can use this
     * operation ID with  DescribeStackSetOperation  to monitor the
     * progress of the drift detection operation.

     */
    inline const Aws::String& GetOperationId() const{ return m_operationId; }

    /**
     *
The ID of the drift detection stack set operation.

You can use this
     * operation ID with  DescribeStackSetOperation  to monitor the
     * progress of the drift detection operation.

     */
    inline void SetOperationId(const Aws::String& value) { m_operationId = value; }

    /**
     *
The ID of the drift detection stack set operation.

You can use this
     * operation ID with  DescribeStackSetOperation  to monitor the
     * progress of the drift detection operation.

     */
    inline void SetOperationId(Aws::String&& value) { m_operationId = std::move(value); }

    /**
     *
The ID of the drift detection stack set operation.

You can use this
     * operation ID with  DescribeStackSetOperation  to monitor the
     * progress of the drift detection operation.

     */
    inline void SetOperationId(const char* value) { m_operationId.assign(value); }

    /**
     *
The ID of the drift detection stack set operation.

You can use this
     * operation ID with  DescribeStackSetOperation  to monitor the
     * progress of the drift detection operation.

     */
    inline DetectStackSetDriftResult& WithOperationId(const Aws::String& value) { SetOperationId(value); return *this;}

    /**
     *
The ID of the drift detection stack set operation.

You can use this
     * operation ID with  DescribeStackSetOperation  to monitor the
     * progress of the drift detection operation.

     */
    inline DetectStackSetDriftResult& WithOperationId(Aws::String&& value) { SetOperationId(std::move(value)); return *this;}

    /**
     *
The ID of the drift detection stack set operation.

You can use this
     * operation ID with  DescribeStackSetOperation  to monitor the
     * progress of the drift detection operation.

     */
    inline DetectStackSetDriftResult& WithOperationId(const char* value) { SetOperationId(value); return *this;}

    inline const ResponseMetadata& GetResponseMetadata() const{ return m_responseMetadata; }

    inline void SetResponseMetadata(const ResponseMetadata& value) { m_responseMetadata = value; }

    inline void SetResponseMetadata(ResponseMetadata&& value) { m_responseMetadata = std::move(value); }

    inline DetectStackSetDriftResult& WithResponseMetadata(const ResponseMetadata& value) { SetResponseMetadata(value); return *this;}

    inline DetectStackSetDriftResult& WithResponseMetadata(ResponseMetadata&& value) { SetResponseMetadata(std::move(value)); return *this;}

  private:

    Aws::String m_operationId;

    ResponseMetadata m_responseMetadata;
  };

} // namespace Model
} // namespace CloudFormation
} // namespace Aws


text:
package dk.nykredit.resilience;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.inject.Qualifier;

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE})
public @interface Resilient {

    Class<? extends BackOffStrategy> strategy() default PolynomialBackoffStrategy.class;

    String executor() default ResilientExecutor.DEFAULT_SCHEDULED_EXECUTOR_SERVICE;

}


text:
Personal details

        Thank you! Your request was sent.

        Your request could not be sent. Please try again.

          First name
          {{model?.personalDetails?.firstName}}

          Last name
          {{model?.personalDetails?.lastName}}

          Credit card type
          {{model?.cardType}}

          Email
          {{model?.personalDetails?.email}}

          Phone
          {{model?.personalDetails?.phone}}

          <button type="button" class="btn btn-default"
            (click)="back()">Back</button>

          <button type="submit" class="btn btn-default"
            (click)="send()">Send</button>


text:
'use strict';

const test = require('tape');
const adminClient = require('../../');

const baseUrl = 'http://localhost:8082/ag-push';
const settings = {
  username: 'admin',
  password: 'admin',
  kcUrl: 'http://localhost:8080/auth',
  kcRealmName: 'master'
};

test('test successful find of applications', (t) => {
  const upsClient = adminClient(baseUrl, settings);

  upsClient.then((client) => {
    // First we need to create an application, we will test create later on

    client.applications.create({name: 'First One'}).then((application) => {
      // If successful, the server returns a 200 with an array of push applications
      client.applications.find().then((applications) => {
        const foundApp = applications.filter(a => a.pushApplicationID === application.pushApplicationID);
        t.equal(foundApp.length, 1, 'the thing we are looking for should be in the list of applications');
        t.equal(Array.isArray(applications), true, 'should be an array returned when finding all');
      }).then(() => {
        // now remove the thing we created,  we will test delete later on
        client.applications.remove(application.pushApplicationID);
        t.end();
      });
    });
  });
});

test('test successful find 1 application', (t) => {
  const upsClient = adminClient(baseUrl, settings);

  upsClient.then((client) => {
    // First we need to create an application, we will test create later on

    client.applications.create({name: 'Second One'}).then((application) => {
      // If successful, the server returns a 200 with an array of push applications
      client.applications.find(application.pushApplicationID).then((application) => {
        t.equal(application.name, 'Second One', 'name should be Second One');
        t.equal(Array.isArray(application.variants), true, 'should be a variant object/array');
        t.equal(Array.isArray(application), false, 'should not be an array returned when finding just one');
      }).then(() => {
        // now remove the thing we created,  we will test delete later on
        client.applications.remove(application.pushApplicationID);
        t.end();
      });
    });
  });
});

test('create application - success', (t) => {
  const upsClient = adminClient(baseUrl, settings);

  upsClient.then((client) => {
    client.applications.create({name: 'Test Create', description: 'Cool Description'}).then((application) => {
      t.equal(application.name, 'Test Create', 'name should be Second One');
      t.equal(application.description, 'Cool Description', 'description should be Cool Description');

      return application;
    }).then((application) => {
      // now remove the thing we created,  we will test delete later on
      client.applications.remove(application.pushApplicationID);
      t.end();
    });
  });
});

test('create application - failure - missing name field', (t) => {
  const upsClient = adminClient(baseUrl, settings);

  upsClient.then((client) => {
    client.applications.create({description: 'Cool Description'}).catch((error) => {
      t.equal(error.name, 'may not be null', 'should have an error for name beining needed');
      t.end();
    });
  });
});

test('update application - success', (t) => {
  const upsClient = adminClient(baseUrl, settings);

  upsClient.then((client) => {
    client.applications.create({name: 'Test Update', description: 'Cool Description'}).then((application) => {
      application.name = 'Been Updated';
      application.description = 'Updated Description';
      return client.applications.update(application).then(() => {
        // Push Applications update doesn't return anything for an update
        t.pass();

        client.applications.remove(application.pushApplicationID);
        t.end();
      });
    });
  });
});

test('update application - failure - no name in the updated value', (t) => {
  const upsClient = adminClient(baseUrl, settings);

  upsClient.then((client) => {
    client.applications.create({name: 'Test Update 2'}).then((application) => {
      delete application.name;
      application.description = 'Updated Description';
      return client.applications.update(application).catch((error) => {
        t.equal(error.name, 'may not be null', 'should have an error for name beining needed');

        client.applications.remove(application.pushApplicationID);
        t.end();
      });
    });
  });
});

test('update application - failure - no pushApplicationId in the updated value', (t) => {
  const upsClient = adminClient(baseUrl, settings);

  upsClient.then((client) => {
    client.applications.create({name: 'Test Update 2'}).then((application) => {
      delete application.pushApplicationID;
      application.description = 'Updated Description';
      return client.applications.update(application).catch((error) => {
        t.equal(error, 'Could not find requested PushApplicationEntity', 'pushApplicationID needed');

        client.applications.remove(application.pushApplicationID);
        t.end();
      });
    });
  });
});

test('remove application - sucess', (t) => {
  const upsClient = adminClient(baseUrl, settings);

  upsClient.then((client) => {
    client.applications.create({name: 'Test Delete 1'}).then((application) => {
      return client.applications.remove(application.pushApplicationID).then(() => {
        t.end();
      });
    });
  });
});

test('remove application - failure - wrong pushApplicationID', (t) => {
  const upsClient = adminClient(baseUrl, settings);

  upsClient.then((client) => {
    client.applications.create({name: 'Test Delete 2'}).then((application) => {
      const pushAppId = application.pushApplicationID;
      delete application.pushApplicationID;
      return client.applications.remove(application.pushApplicationID).catch((error) => {
        t.equal(error, 'Could not find requested PushApplicationEntity', 'pushApplicationID needed');

        // clean up
        client.applications.remove(pushAppId);
        t.end();
      });
    });
  });
});

test('reset application secret - sucess', (t) => {
  const upsClient = adminClient(baseUrl, settings);

  upsClient.then((client) => {
    client.applications.create({name: 'Test Secret 1'}).then((application) => {
      return client.applications.reset(application.pushApplicationID).then((updatedSecret) => {
        t.notEqual(application.masterSecret, updatedSecret.masterSecret, 'master secrets should be different');

        // clean up
        client.applications.remove(application.pushApplicationID);
        t.end();
      });
    });
  });
});

test('reset application secret - failure - wrong pushApplicationID', (t) => {
  const upsClient = adminClient(baseUrl, settings);

  upsClient.then((client) => {
    client.applications.create({name: 'Test Secret 1'}).then((application) => {
      return client.applications.reset('NOT_THE_REAL_ID').catch((err) => {
        t.equal(err, 'Could not find requested PushApplicationEntity', 'should error');
        // clean up
        client.applications.remove(application.pushApplicationID);
        t.end();
      });
    });
  });
});


text:
package main

import (
	"context"
	"flag"
	"net"
	"strconv"

	log "github.com/golang/glog"
	"github.com/openconfig/gribigo/device"

	"net/http"
	_ "net/http/pprof"
)

var (
	certFile = flag.String("cert", "", "cert is the path to the server TLS certificate file")
	keyFile  = flag.String("key", "", "key is the path to the server TLS key file")
	gnmi     = flag.String("gnmi", ":9339", "gnmi listen address")
	gribi    = flag.String("gribi", ":9340", "gribi listen address")
)

func main() {
	flag.Parse()

	if *certFile == "" || *keyFile == "" {
		log.Exitf("must specify a TLS certificate and key file")
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	creds, err := device.TLSCredsFromFile(*certFile, *keyFile)
	if err != nil {
		log.Exitf("cannot initialise TLS, got: %v", err)
	}

	gribiHost, gribiPort, err := splitHostPort(*gribi)
	if err != nil {
		log.Exitf("cannot parse gribi listen address: %s", err)
	}
	gnmiHost, gnmiPort, err := splitHostPort(*gnmi)
	if err != nil {
		log.Exitf("cannot parse gnmi listen address: %s", err)
	}

	d, err := device.New(ctx, creds, device.GNMIAddr(gnmiHost, gnmiPort), device.GRIBIPort(gribiHost, gribiPort))
	if err != nil {
		log.Exitf("cannot start device, %v", err)
	}
	log.Infof("listening on:\n\tgRIBI: %s\n\tgNMI: %s", d.GRIBIAddr(), d.GNMIAddr())
	go func() {
		log.Infof("%v", http.ListenAndServe("localhost:6060", nil))
	}()
	<-ctx.Done()
}

func splitHostPort(address string) (string, int, error) {
	addr, port, err := net.SplitHostPort(address)
	if err != nil {
		return "", 0, err
	}

	portnum, err := strconv.Atoi(port)
	if err != nil {
		return "", 0, err
	}

	return addr, portnum, nil
}


text:
using System;
using System.Web;
using System.Web.Security;
using Orchard.Environment.Configuration;
using Orchard.Logging;
using Orchard.ContentManagement;
using Orchard.Mvc;
using Orchard.Services;

namespace Orchard.Security.Providers {
    public class FormsAuthenticationService : IAuthenticationService {
        private readonly ShellSettings _settings;
        private readonly IClock _clock;
        private readonly IContentManager _contentManager;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private IUser _signedInUser;
        private bool _isAuthenticated;

        public FormsAuthenticationService(ShellSettings settings, IClock clock, IContentManager contentManager, IHttpContextAccessor httpContextAccessor) {
            _settings = settings;
            _clock = clock;
            _contentManager = contentManager;
            _httpContextAccessor = httpContextAccessor;

            Logger = NullLogger.Instance;

            ExpirationTimeSpan = TimeSpan.FromDays(30);
        }

        public ILogger Logger { get; set; }

        public TimeSpan ExpirationTimeSpan { get; set; }

        public void SignIn(IUser user, bool createPersistentCookie) {
            var now = _clock.UtcNow.ToLocalTime();
            var userData = Convert.ToString(user.Id);

            var ticket = new FormsAuthenticationTicket(
                1 /*version*/,
                user.UserName,
                now,
                now.Add(ExpirationTimeSpan),
                createPersistentCookie,
                userData,
                FormsAuthentication.FormsCookiePath);

            var encryptedTicket = FormsAuthentication.Encrypt(ticket);

            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) {
                HttpOnly = true,
                Secure = FormsAuthentication.RequireSSL,
                Path = FormsAuthentication.FormsCookiePath
            };

            var httpContext = _httpContextAccessor.Current();

            if (!String.IsNullOrEmpty(_settings.RequestUrlPrefix)) {
                var cookiePath = httpContext.Request.ApplicationPath;
                if (cookiePath != null && cookiePath.Length > 1) {
                    cookiePath += '/';
                }

                cookiePath += _settings.RequestUrlPrefix;
                cookie.Path = cookiePath;
            }

            if (FormsAuthentication.CookieDomain != null) {
                cookie.Domain = FormsAuthentication.CookieDomain;
            }

            if (createPersistentCookie) {
                cookie.Expires = ticket.Expiration;
            }

            httpContext.Response.Cookies.Add(cookie);

            _isAuthenticated = true;
            _signedInUser = user;
        }

        public void SignOut() {
            _signedInUser = null;
            _isAuthenticated = false;
            FormsAuthentication.SignOut();
        }

        public void SetAuthenticatedUserForRequest(IUser user) {
            _signedInUser = user;
            _isAuthenticated = true;
        }

        public IUser GetAuthenticatedUser() {
            if (_signedInUser != null || _isAuthenticated)
                return _signedInUser;

            var httpContext = _httpContextAccessor.Current();
            if (httpContext == null || !httpContext.Request.IsAuthenticated || !(httpContext.User.Identity is FormsIdentity)) {
                return null;
            }

            var formsIdentity = (FormsIdentity)httpContext.User.Identity;
            var userData = formsIdentity.Ticket.UserData;
            int userId;
            if (!int.TryParse(userData, out userId)) {
                Logger.Fatal("User id not a parsable integer");
                return null;
            }

            _isAuthenticated = true;
            return _signedInUser = _contentManager.Get(userId).As<IUser>();
        }
    }
}


text:
import {
	default as React, Component } from 'react';
var ReactDOM = require('react-dom');

import {
	ReactiveBase,
	DataController,
	ReactiveList
} from '../../app/app.js';

import { Img } from "../../app/stories/Img.js";

class Main extends Component {
	constructor(props) {
		super(props);
		this.CustomQuery = this.CustomQuery.bind(this);

		this.state = {
			defaultSelected: "Default"
		};
		this.handleInputChange = this.handleInputChange.bind(this);
	}

	CustomQuery(value) {
		return {
			query: {
				match_all: {}
			}
		};
	}

	onData(markerData) {
		const marker = markerData._source;
		return (

							{marker.name ? marker.name : ""} - {marker.brand ? marker.brand : ""}

						{marker.brand ? marker.brand : ""}

							{marker.price ? `Priced at $${marker.price}` : "Free Test Drive"}

		);
	}

	handleInputChange(e) {
		const defaultSelected = e.target.value;
		this.setState({
			defaultSelected
		});
	}

	render() {
		return (
			<ReactiveBase
				app="car-store"
				credentials="cf7QByt5e:d2d60548-82a9-43cc-8b40-93cbbe75c34c"
			>

						<DataController
							componentId="CustomSensor"
							appbaseField="name"
							customQuery={this.CustomQuery}
							URLParams={true}
							defaultSelected={this.state.defaultSelected}
							filterLabel="Name label"
							beforeValueChange={() => new Promise((resolve) => resolve())}
						/>
						<input value={this.state.defaultSelected} onChange={this.handleInputChange} placeholder="defaultSelected" />

						<ReactiveList
							componentId="SearchResult"
							appbaseField="name"
							title="Cars"
							from={0}
							size={20}
							onData={this.onData}
							react={{
								and: "CustomSensor"
							}}
						/>

			</ReactiveBase>
		);
	}
}

ReactDOM.render(, document.getElementById('map'));


text:
yum install -y git
yum install -y cmake3
yum install -y make

yum install -y leveldb-devel
yum install -y libmicrohttpd-devel
yum install -y gmp-devel
yum install -y python-pip
# There is a package for gcc-5.2.1, if that's close enough. First you need to enable the Software Collections, then it's available in devtoolset-4:
yum install -y centos-release-scl
yum install -y devtoolset-6-gcc*

scl enable devtoolset-6 bash

# http://mirror.math.princeton.edu/pub/eclipse//technology/epp/downloads/release/oxygen/R/eclipse-cpp-oxygen-R-linux-gtk-x86_64.tar.gz

# libGL is the main OpenGL library (i.e. Mesa).
# libOSMesa is the OSMesa (Off-Screen) interface library.
yum-builddep mesa
# =====================================
# cpp-ethereum - Ethereum C++ client
# =====================================
git clone --recursive https://github.com/ethereum/cpp-ethereum.git
cd cpp-ethereum
# Note: The --recursive option is important. It orders git to clone additional submodules which are required to build the project. If you missed it you can correct your mistake with command git submodule update --init.

# =====================================
# ethminer - Ethereum Miner
# =====================================
git clone --recursive https://github.com/ethereum-mining/ethminer.git


text:
package org.pac4j.core.store;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.pac4j.core.util.CommonHelper;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * Store data in a Guava cache.
 *
 * Add the guava dependency to use this store.
 *
 * @author Jerome Leleu
 * @since 2.0.0
 */
public class GuavaStore<K, O> extends AbstractStore<K, O> {

    private Cache<K, O> cache;

    private int size = 0;

    private int timeout = -1;

    private TimeUnit timeUnit;

    public GuavaStore() {}

    public GuavaStore(final int size, final int timeout, final TimeUnit timeUnit) {
        this.size = size;
        this.timeout = timeout;
        this.timeUnit = timeUnit;
    }

    @Override
    protected void internalInit(final boolean forceReinit) {
        CommonHelper.assertTrue(this.size > 0, "size mut be greater than zero");
        CommonHelper.assertTrue(this.timeout >= 0, "timeout must be greater than zero");
        CommonHelper.assertNotNull("timeUnit", this.timeUnit);

        this.cache = CacheBuilder.newBuilder().maximumSize(this.size)
                .expireAfterWrite(this.timeout, this.timeUnit).build();
    }

    @Override
    protected Optional<O> internalGet(final K key) {
        return Optional.ofNullable(cache.getIfPresent(key));
    }

    @Override
    protected void internalSet(final K key, final O value) {
        cache.put(key, value);
    }

    @Override
    protected void internalRemove(final K key) {
        cache.invalidate(key);
    }

    public Cache<K, O> getCache() {
        return cache;
    }

    public int getSize() {
        return size;
    }

    public void setSize(final int size) {
        this.size = size;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(final int timeout) {
        this.timeout = timeout;
    }

    public TimeUnit getTimeUnit() {
        return timeUnit;
    }

    public void setTimeUnit(final TimeUnit timeUnit) {
        this.timeUnit = timeUnit;
    }

    @Override
    public String toString() {
        return CommonHelper.toNiceString(this.getClass(), "size", size, "timeout", timeout, "timeUnit", timeUnit);
    }
}


text:
package com.appleframework.data.hbase.hql.node.binary;

import java.util.Map;

import com.appleframework.data.hbase.config.SimpleHbaseRuntimeSetting;

import com.appleframework.data.hbase.hql.HQLNodeType;
import com.appleframework.data.hbase.util.CompareUtil;

/**
 * @author xinzhi
 */
public class IsGreaterThanNode extends BinaryNode {

    protected IsGreaterThanNode() {
        super(HQLNodeType.IsGreaterThan);
    }

    @Override
    protected boolean isConditionSatisfied(Map<String, Object> para,
            SimpleHbaseRuntimeSetting runtimeSetting) {
        Object propertyObject = para.get(getProperty());
        Object compareObject = runtimeSetting.interpret(
                propertyObject.getClass(), getCompareValue());
        return CompareUtil.compare(propertyObject, compareObject) > 0;
    }
}


text:
				Visão Geral
				Projetos

				<buttom id="btn_new_project" onclick="boss.ajax.load('/app/project/form_create/', '#modal_dialog', 'active');" class="btn btn-success">
					+ Novo Projeto
				</buttom>

				<form action="" method="post">
					<input name="name" type="text" id="name" class="search form-control" placeholder="Pesquisar">
				</form>

Core Projetos

								Core Projetos

								Editar

								Excluir

Stor Music

								Stor Music

								Editar

								Excluir


text:
"""
testing code for `slack.py`

(c) Stefan LOESCH, oditorium 2016. All Rights Reserved.
Licensed under the MIT License <https://opensource.org/licenses/MIT>.
"""
from django.test import TestCase, RequestFactory
from django.conf import settings
from django.core.urlresolvers import reverse_lazy, reverse
from django.http import HttpResponse, JsonResponse

import json

from . import slack

SLACK_VERSION = "2.2"

#########################################################################################
## SUNDRY HELPER FUNCTIONS AND OBJECTS

@slack.slack_augment
def _function_hello_world_text(request):
    return "Hello World"

@slack.slack_augment
def _function_hello_world_response(request):
    return slack.SlackResponseText("Hello World")

## SLACK REQUEST TEST
class SlackRequestDummy(slack.SlackRequestMixin):
    """a little hack for our slack request"""
    @property
    def slack_text(s):
        return s.text

## SLACK HANDLER EXAMPLE
class SlackViewExample(slack.SlackViewBase):
    """an example for a Slack handler object (for testing)"""

    def run_echo(s, parser):
        """a simple echo handler (returns the remainder)"""
        parser.add_argument('--uppercase', '-u', action='count') # https://docs.python.org/3/library/argparse.html#action
        parse_obj = parser.run()
        out = "-".join(parse_obj.posn)
        if parse_obj.uppercase: out=out.upper()
        return slack.SlackResponseText("you said: {}".format(out))

    @slack.positional_args
    def run_echob(s, posn):
        out = ":".join(posn)
        return slack.SlackResponseText("you said: {}".format(out))

    def run_show(s, parser):
        """shows off"""
        att = slack.Attachment("that's a show-off attachment")
        att.add(att.Author("Stefan Loesch", "https://twitter.com/oditorium",
                "https://pbs.twimg.com/profile_images/491834678383374336/eSPXgb6I_bigger.jpeg"))
        att.add(att.Title("Some Random Stock Photo", "https://www.pexels.com/"))
        att.add(att.Image("https://static.pexels.com/photos/57690/pexels-photo-57690-large.jpeg",
                "https://static.pexels.com/photos/57690/pexels-photo-57690-small.jpeg"))
        att.add(att.Text("This text appears within the attachment!", "This text appears above the attachment!"))
        return slack.SlackResponse("Just showing off!", att)

    def run_version(s, parser):
        return slack.SlackResponseText("""Slack library version {}""".format(slack.__version__))

    def run_help(s, parser):
        return slack.SlackResponseText("""try the 'echo', 'show' or 'version' subcommands""")

SlackViewExample.alias("v", "version")
SlackViewExample.alias("e", "echo")

# TEST API VIEW
test_api_view = SlackViewExample.as_view()

#########################################################################################
## SLACK API OBJECTS TEST
class SlackAPIObjectsTest(TestCase):
    """testing the Slack API without need for a working URL"""

    SLACK_ACCESS = {
        '-token-': '-team-',
    }
    SLACK_USERS = {
        'user-0':  (),                           # no permissions (whatever that means)
        'user-r':  (slack.READ,),                # read permissions
        'user-rx': (slack.READ|slack.EXECUTE,),  # read and execute permissions
        'user-x':  (slack.EXECUTE,),             # only execute permissions (whatever that means)
    }

    def setUp(s):
        s.factory = RequestFactory()
        s.request = s.factory.post('/url/does/not/matter', {
            'token': '-token-',
            'command': '-command-',
            'text': '-text-',
            'user_id': '-user_id-',
            'user_name': '-user_name-',
            'channel_id': '-channel_id-',
            'channel_name': '-channel_name-',
            'team_id': '-team-',
            'team_domain': '-team_domain-',
            'response_url': '-response_url-',
        })

    ####################################################################
    ## TEST SLACK VERSION
    def test_slack_version(s):
        """ensure the version number is correct"""
        s.assertEqual(slack.__version__, SLACK_VERSION)

    ####################################################################
    ## TEST SLACK AUGMENT
    def test_slack_augment(s):
        """testing the @slack_augment decorator"""
        with s.settings(SLACK_ACCESS=s.SLACK_ACCESS, SLACK_USERS=s.SLACK_USERS):

            resp = _function_hello_world_text(s.request)
            s.assertTrue(isinstance(resp, str))
            s.assertEqual(resp, "Hello World")

            resp = _function_hello_world_response(s.request)
            s.assertTrue(isinstance(resp, JsonResponse))
            #s.assertEqual(resp.content, b"Hello World")
            #s.assertEqual(resp.content_type, "text/plain")
            s.assertEqual(resp.status_code, 200)

    ####################################################################
    ## TEST SLACK RESPONSE
    def test_slack_response_text(s):
        """testing the SlackResponseText object"""
        resp = slack.SlackResponseText("the response")
        s.assertEqual (resp.as_dict()['text'], "the response")
        s.assertEqual (resp.as_dict()['response_type'], "ephemeral")
        s.assertEqual (json.loads(resp.as_json()), resp.as_dict())
        s.assertEqual (resp.as_json_response().status_code, 200)
        s.assertTrue (isinstance (resp.as_json_response(), JsonResponse))

        resp = slack.SlackResponseText("the response", in_channel=True)
        s.assertEqual (resp.as_dict()['text'], "the response")
        s.assertEqual (resp.as_dict()['response_type'], "in_channel")
        s.assertEqual (json.loads(resp.as_json()), resp.as_dict())
        s.assertEqual (resp.as_json_response().status_code, 200)
        s.assertTrue (isinstance (resp.as_json_response(), JsonResponse))

    ####################################################################
    ## TEST SLACK ATTACHMENT OBJECTS
    def test_slack_attachment(s):
        """tests the various Slack attachment objects"""

        text=slack.Text('mytext', 'pretext')
        author=slack.Author('name', 'link', 'icon')
        title=slack.Title('title', 'link')
        image=slack.Image('image', 'thumb')
        s.assertEqual(text.as_dict(), {'text': 'mytext', 'pretext': 'pretext'})
        s.assertEqual(author.as_dict(),{"author_name": 'name', "author_link": 'link',"author_icon": 'icon'})
        s.assertEqual(title.as_dict(), {"title": 'title', "title_link": 'link'})
        s.assertEqual(image.as_dict(), {"image_url": 'image', "thumb_url": 'thumb'})

        attach=slack.Attachment('fallback', [text, author, title, image])
        thedict = attach.as_dict()
        s.assertEqual(thedict['fallback'], "fallback")
        s.assertEqual(thedict['text'], "mytext")
        s.assertEqual(thedict['author_link'], "link")
        s.assertEqual(thedict['title'], "title")
        s.assertEqual(thedict['image_url'], "image")

        attach=slack.Attachment('fallback')
        s.assertEqual(attach.as_dict(), {'fallback': 'fallback'})
        attach.add(text)
        s.assertEqual(attach.as_dict(), {'fallback': 'fallback', 'text': 'mytext', 'pretext': 'pretext'})
        attach.add([author, title, image])
        thedict = attach.as_dict()
        s.assertEqual(thedict['author_link'], "link")
        s.assertEqual(thedict['title'], "title")
        s.assertEqual(thedict['image_url'], "image")

        s.assertEqual(attach.Text, slack.Text)
        s.assertEqual(attach.Author, slack.Author)
        s.assertEqual(attach.Title, slack.Title)
        s.assertEqual(attach.Image, slack.Image)

    ####################################################################
    ## TEST SLACK RESPONSE
    def test_slack_response(s):
        """tests the various Slack response objects"""
        att1=slack.Attachment('Attachment 1')
        att2=slack.Attachment('Attachment 2')

        resp=slack.SlackResponse('text')
        s.assertEqual(resp.as_dict(), {'text': 'text', 'response_type': 'ephemeral', 'attachments': []})

        resp=slack.SlackResponse('text', att1)
        s.assertEqual(resp.as_dict(), {'text': 'text', 'response_type': 'ephemeral', 'attachments': [{'fallback': 'Attachment 1'}]})

        resp=slack.SlackResponse('text', [att1])
        s.assertEqual(resp.as_dict(), {'text': 'text', 'response_type': 'ephemeral', 'attachments': [{'fallback': 'Attachment 1'}]})

        resp=slack.SlackResponse('text', [att1,att2])
        s.assertEqual(resp.as_dict()['attachments'][1], {'fallback': 'Attachment 2'})

        resp=slack.SlackResponse('text')
        resp.add(att1)
        s.assertEqual(resp.as_dict(), {'text': 'text', 'response_type': 'ephemeral', 'attachments': [{'fallback': 'Attachment 1'}]})

        resp=slack.SlackResponse('text')
        resp.add([att1])
        s.assertEqual(resp.as_dict(), {'text': 'text', 'response_type': 'ephemeral', 'attachments': [{'fallback': 'Attachment 1'}]})

        resp=slack.SlackResponse('text')
        resp.add([att1,att2])
        s.assertEqual(resp.as_dict()['attachments'][1], {'fallback': 'Attachment 2'})

    ####################################################################
    ## TEST SLACK URL
    def test_slack_url(s):
        """ensure the slack url is produced correctly"""
        r=slack.SlackResponse('text')
        s.assertEqual(r.url('https://my.server.com', "myserver"), "<https://my.server.com|myserver>")
        s.assertEqual(r.url('https://my.server.com'), "<https://my.server.com>")
        s.assertEqual(slack.url('https://my.server.com', "myserver"), "<https://my.server.com|myserver>")
        s.assertEqual(slack.url('https://my.server.com'), "<https://my.server.com>")

    ####################################################################
    ## TEST SLACK HANDLER BASE
    def test_slack_view_base(s):
        """testting the SlackViewBase object"""

        request = SlackRequestDummy()

        request.text = "thecmd and remainder"
        view = slack.SlackViewBase(request)
        response = view.dispatch()
        s.assertEqual(response.response_text, "unknown subcommand 'thecmd'; try 'help'")
        parser = view._parser("and remainder")
        parse_obj = parser.run()
        s.assertEqual(parse_obj.error, False)
        s.assertEqual(parse_obj.posn, ["and", "remainder"])

        request.text = "help"
        response = slack.SlackViewBase(request).dispatch()
        s.assertEqual(response.response_text, "help functionality is not currently implemented")

    ####################################################################
    ## TEST SLACK VIEW EXAMPLE
    def test_slack_view_example(s):
        """testing the SlackViewExample object"""

        request = SlackRequestDummy()

        request.text = "echo I say hello"
        response = SlackViewExample(request).dispatch()
        s.assertEqual(response.response_text, "you said: I-say-hello")

        request.text = "ECHO I say hello"
        response = SlackViewExample(request).dispatch()
        s.assertEqual(response.response_text, "you said: I-say-hello")

        request.text = "e I say hello"
        response = SlackViewExample(request).dispatch()
        s.assertEqual(response.response_text, "you said: I-say-hello")

        request.text = "E I say hello"
        response = SlackViewExample(request).dispatch()
        s.assertEqual(response.response_text, "you said: I-say-hello")

        request.text = "echo -u I say hello"
        response = SlackViewExample(request).dispatch()
        s.assertEqual(response.response_text, "you said: I-SAY-HELLO")

        request.text = "echo --uppercase I say hello"
        response = SlackViewExample(request).dispatch()
        s.assertEqual(response.response_text, "you said: I-SAY-HELLO")

        request.text = "echob I say hello"
        response = SlackViewExample(request).dispatch()
        s.assertEqual(response.response_text, "you said: I:say:hello")

        request.text = "ECHOO I say hello"
        response = SlackViewExample(request).dispatch()
        s.assertEqual(response.response_text, "unknown subcommand 'ECHOO'; try 'help'")

        request.text = "cmd"
        response = SlackViewExample(request).dispatch()
        s.assertEqual(response.response_text, "unknown subcommand 'cmd'; try 'help'")

        request.text = ""
        response = SlackViewExample(request).dispatch()
        s.assertEqual(response.response_text, "unknown subcommand ''; try 'help'")

        request.text = "     "
        response = SlackViewExample(request).dispatch()
        s.assertEqual(response.response_text, "unknown subcommand ''; try 'help'")

#########################################################################################
## SLACK API TEST
class SlackAPITest(TestCase):
    """testing the Slack API (needs a working URL)"""

    SLACK_ACCESS = {
        'token-with-team': 'my-team-id',
        'token-without-team': True,
    }
    SLACK_USERS = {
        'user-0':  (),                           # no permissions (whatever that means)
        'user-r':  (slack.READ,),                # read permissions
        'user-rx': (slack.READ|slack.EXECUTE,),  # read and execute permissions
        'user-x':  (slack.EXECUTE,),             # only execute permissions (whatever that means)
    }

    def setUp(s):
        try: s.url = reverse('slack_test_api')
        except: s.url = None

    ####################################################################
    ## TEST URL DEFINED
    def test_url_defined(s):
        try:
            if settings.SLACK_IGNORE_MISSING_URL_FOR_TESTS: return
        except: pass
        if not s.url: print("""
{0}
the Slack API URL for testing has not been defined, so a number of the tests wont run!

in order to make it work, please insert eg the following code into a suitable `urls.py` file
(please ensure that this url file is part of the global namespace!)

    from tests_slack import SlackViewExample
    urlpatterns += [
        url(r'^slack_test_api$', SlackViewExample.as_view(), name='slack_test_api'),
    ]
{0}
""".format("+"*100))
        # if this assertion fails this means that the URL has not been defined
        s.assertTrue(s.url != None)

    ####################################################################
    ## TEST API ACCESS
    def test_api_access(s):
        """making sure API access only granted with proper tokens"""

        if not s.url: return # checked in test_url_defined
        c = s.client

        with s.settings(SLACK_ACCESS=s.SLACK_ACCESS, SLACK_USERS=s.SLACK_USERS):

            # GET
            response = c.get(s.url)
            #print ("{1.status_code} {1.content}".format(s.url, response))
            s.assertEqual(response.status_code, 403)
            s.assertContains(response, "denied", status_code=403)

            # GET correct token, correct team
            response = c.get(s.url, {'token': 'token-with-team', 'team_id': 'my-team-id'})
            s.assertContains(response, "denied", status_code=403)

            # POST no arguments
            response = c.post(s.url, {})
            #print ("{1.status_code} {1.content}".format(s.url, response))
            s.assertContains(response, "denied", status_code=403)

            # POST wrong token
            response = c.post(s.url, {'token': 'wrong-token', 'team_id': 'my-team-id'})
            s.assertContains(response, "denied", status_code=403)

            # POST correct token, wrong team
            response = c.post(s.url, {'token': 'token-with-team', 'team_id': 'wrong-team-id'})
            s.assertContains(response, "denied", status_code=403)

            # POST correct token, correct team
            response = c.post(s.url, {'token': 'token-with-team', 'team_id': 'my-team-id', 'text': 'help'})
            s.assertEqual(response.status_code, 200)
            #s.assertTrue('text' in response.json().keys())

            # POST correct no-team token, no team
            response = c.post(s.url, {'token': 'token-without-team', 'text': 'help'})
            s.assertEqual(response.status_code, 200)
            #s.assertTrue('text' in response.json().keys())

            # POST correct no-team token, wrong team
            response = c.post(s.url, {'token': 'token-without-team', 'team_id': 'wrong-team-id', 'text': 'help'})
            s.assertEqual(response.status_code, 200)
            #s.assertTrue('text' in response.json().keys())

    def test_api_commands(s):
        """test some of the API commands (the Example Handler must be connected!)"""

        if not s.url: return # checked in test_url_defined
        c = s.client
        with s.settings(SLACK_ACCESS=s.SLACK_ACCESS, SLACK_USERS=s.SLACK_USERS):

            # help
            response = c.post(s.url, {'token': 'token-without-team', 'text': 'help'})
            s.assertEqual(response.status_code, 200)

            # echo
            response = c.post(s.url, {'token': 'token-without-team', 'text': 'echo 123 test'})
            s.assertEqual(response.status_code, 200)

            # show
            response = c.post(s.url, {'token': 'token-without-team', 'text': 'show'})
            s.assertEqual(response.status_code, 200)

    ####################################################################
    ## TEST API FUNCTIONALITY
    def test_api_functionality(s):
        """making sure the API works as it should"""
        if not s.url: return # checked in test_url_defined
        c = s.client
        with s.settings(SLACK_ACCESS=s.SLACK_ACCESS, SLACK_USERS=s.SLACK_USERS):

            # dummy, to be changed
            response = c.post(s.url, {'token': 'token-without-team', 'team_id': 'wrong-team-id', 'text': 'help'})
            #print ("{1.status_code} {1.content}".format(s.url, response))

            s.assertEqual(response.status_code, 200)
            #s.assertTrue('text' in response.json().keys())


text:
<?php

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\NotNull;

class RoomType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $constraints = array(
            new NotNull()
        );

        $builder
            ->add('name', TextType::class, array(
                    'label'         => 'Nom de la room',
                    'required'      => true,
                    'constraints'    => $constraints
                )
            )

            ->add('description', TextareaType::class, array(
                    'label'         => 'Description',
                    'required'      => false
                )
            )

            ->add('isActivated', ChoiceType::class, array(
                    'label'     => 'Activé',
                    'choices'   => array( true => 'Oui', false => 'Non'),
                    'expanded'  => true,
                    'multiple'  => false,
                    'required'  => false
                )
            )

            ->add('pictureName', FileType::class, array(
                    'label' => 'Image',
                    'required' => false
                )
            )

            ->add('users', EntityType::class, array(
                'label' => 'Invités de la room',
                'class' => 'UserBundle:User',
                'choice_label' => 'username',
                'multiple' => true
            ))
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Room'
        ));
    }
}


text:
{% extends 'base.html' %}

{% block content %}
    {% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% if next %}
    {% if user.is_authenticated %}

Your account doesn't have access to this page. To proceed,
    please login with an account that has access.

    {% else %}

Please login to see this page.

    {% endif %}
{% endif %}
{% if request.get_full_path == '/portal/login/?next=/portal/%3FformSubmit%3D' %}

{% else %}

Please Sign In

                        <form method="post" action="{% url 'login' %}">
                            {% csrf_token %}

                                        {{ form.username.label_tag }}
                                        {{ form.username }}

                                        {{ form.password.label_tag }}
                                        {{ form.password }}

                                    <input class="btn btn-primary" type="submit" value="Login" />

                            <input type="hidden" name="next" value="{{ next }}" />
                        </form>

{% endif %}

{% endblock %}

{% block javascript %}

{% endblock %}


text:
namespace content {

const char kMinimalPageDataURL[] =
    "data:text/html,Hello, world";

class AccessibilityModeTest : public ContentBrowserTest {
 protected:
  WebContentsImpl* web_contents() {
    return static_cast<WebContentsImpl*>(shell()->web_contents());
  }

 protected:
  const BrowserAccessibility* FindNode(ax::mojom::Role role,
                                       const std::string& name) {
    const BrowserAccessibility* root = GetManager()->GetRoot();
    CHECK(root);
    return FindNodeInSubtree(*root, role, name);
  }

  BrowserAccessibilityManager* GetManager() {
    WebContentsImpl* web_contents =
        static_cast<WebContentsImpl*>(shell()->web_contents());
    return web_contents->GetRootBrowserAccessibilityManager();
  }

 private:
  const BrowserAccessibility* FindNodeInSubtree(
      const BrowserAccessibility& node,
      ax::mojom::Role role,
      const std::string& name) {
    if (node.GetRole() == role &&
        node.GetStringAttribute(ax::mojom::StringAttribute::kName) == name)
      return &node;
    for (unsigned int i = 0; i < node.PlatformChildCount(); ++i) {
      const BrowserAccessibility* result =
          FindNodeInSubtree(*node.PlatformGetChild(i), role, name);
      if (result)
        return result;
    }
    return nullptr;
  }
};

IN_PROC_BROWSER_TEST_F(AccessibilityModeTest, AccessibilityModeOff) {
  EXPECT_TRUE(NavigateToURL(shell(), GURL(kMinimalPageDataURL)));
  EXPECT_TRUE(web_contents()->GetAccessibilityMode().is_mode_off());
  EXPECT_EQ(nullptr, GetManager());
}

IN_PROC_BROWSER_TEST_F(AccessibilityModeTest, AccessibilityModeComplete) {
  EXPECT_TRUE(NavigateToURL(shell(), GURL(kMinimalPageDataURL)));
  ASSERT_TRUE(web_contents()->GetAccessibilityMode().is_mode_off());

  AccessibilityNotificationWaiter waiter(shell()->web_contents());
  web_contents()->AddAccessibilityMode(ui::kAXModeComplete);
  EXPECT_TRUE(web_contents()->GetAccessibilityMode() == ui::kAXModeComplete);
  waiter.WaitForNotification();
  EXPECT_NE(nullptr, GetManager());
}

IN_PROC_BROWSER_TEST_F(AccessibilityModeTest,
                       AccessibilityModeWebContentsOnly) {
  EXPECT_TRUE(NavigateToURL(shell(), GURL(kMinimalPageDataURL)));
  ASSERT_TRUE(web_contents()->GetAccessibilityMode().is_mode_off());

  AccessibilityNotificationWaiter waiter(shell()->web_contents());
  web_contents()->AddAccessibilityMode(ui::kAXModeWebContentsOnly);
  EXPECT_TRUE(web_contents()->GetAccessibilityMode() ==
              ui::kAXModeWebContentsOnly);
  waiter.WaitForNotification();
  // No BrowserAccessibilityManager expected for this mode.
  EXPECT_EQ(nullptr, GetManager());
}

IN_PROC_BROWSER_TEST_F(AccessibilityModeTest, AddingModes) {
  EXPECT_TRUE(NavigateToURL(shell(), GURL(kMinimalPageDataURL)));

  AccessibilityNotificationWaiter waiter(shell()->web_contents());
  web_contents()->AddAccessibilityMode(ui::kAXModeWebContentsOnly);
  EXPECT_TRUE(web_contents()->GetAccessibilityMode() ==
              ui::kAXModeWebContentsOnly);
  waiter.WaitForNotification();
  EXPECT_EQ(nullptr, GetManager());

  AccessibilityNotificationWaiter waiter2(shell()->web_contents());
  web_contents()->AddAccessibilityMode(ui::kAXModeComplete);
  EXPECT_TRUE(web_contents()->GetAccessibilityMode() == ui::kAXModeComplete);
  waiter2.WaitForNotification();
  EXPECT_NE(nullptr, GetManager());
}

IN_PROC_BROWSER_TEST_F(AccessibilityModeTest,
                       FullAccessibilityHasInlineTextBoxes) {
  // TODO(dmazzoni): On Android we use an ifdef to disable inline text boxes,
  // we should do it with accessibility flags instead. http://crbug.com/672205
#if !defined(OS_ANDROID)
  EXPECT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL)));

  AccessibilityNotificationWaiter waiter(shell()->web_contents(),
                                         ui::kAXModeComplete,
                                         ax::mojom::Event::kLoadComplete);
  GURL url("data:text/html,
Para
");
  EXPECT_TRUE(NavigateToURL(shell(), url));
  waiter.WaitForNotification();

  const BrowserAccessibility* text =
      FindNode(ax::mojom::Role::kStaticText, "Para");
  ASSERT_NE(nullptr, text);
  ASSERT_EQ(1U, text->InternalChildCount());
  BrowserAccessibility* inline_text = text->InternalGetChild(0);
  ASSERT_NE(nullptr, inline_text);
  EXPECT_EQ(ax::mojom::Role::kInlineTextBox, inline_text->GetRole());
#endif  // !defined(OS_ANDROID)
}

IN_PROC_BROWSER_TEST_F(AccessibilityModeTest,
                       MinimalAccessibilityModeHasNoInlineTextBoxes) {
  // TODO(dmazzoni): On Android we use an ifdef to disable inline text boxes,
  // we should do it with accessibility flags instead. http://crbug.com/672205
#if !defined(OS_ANDROID)
  EXPECT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL)));

  AccessibilityNotificationWaiter waiter(
      shell()->web_contents(),
      ui::AXMode::kNativeAPIs | ui::AXMode::kWebContents,
      ax::mojom::Event::kLoadComplete);
  GURL url("data:text/html,
Para
");
  EXPECT_TRUE(NavigateToURL(shell(), url));
  waiter.WaitForNotification();

  const BrowserAccessibility* text =
      FindNode(ax::mojom::Role::kStaticText, "Para");
  ASSERT_NE(nullptr, text);
  EXPECT_EQ(0U, text->InternalChildCount());
#endif  // !defined(OS_ANDROID)
}

IN_PROC_BROWSER_TEST_F(AccessibilityModeTest, AddScreenReaderModeFlag) {
  EXPECT_TRUE(NavigateToURL(shell(), GURL(url::kAboutBlankURL)));

  AccessibilityNotificationWaiter waiter(
      shell()->web_contents(),
      ui::AXMode::kNativeAPIs | ui::AXMode::kWebContents,
      ax::mojom::Event::kLoadComplete);
  GURL url("data:text/html,<input aria-label=Foo placeholder=Bar>");
  EXPECT_TRUE(NavigateToURL(shell(), url));
  waiter.WaitForNotification();

  const BrowserAccessibility* textbox =
      FindNode(ax::mojom::Role::kTextField, "Foo");
  ASSERT_NE(nullptr, textbox);
  EXPECT_FALSE(
      textbox->HasStringAttribute(ax::mojom::StringAttribute::kPlaceholder));
  int original_id = textbox->GetId();

  AccessibilityNotificationWaiter waiter2(shell()->web_contents(), ui::AXMode(),
                                          ax::mojom::Event::kLoadComplete);
  BrowserAccessibilityStateImpl::GetInstance()->AddAccessibilityModeFlags(
      ui::AXMode::kScreenReader);
  waiter2.WaitForNotification();

  const BrowserAccessibility* textbox2 =
      FindNode(ax::mojom::Role::kTextField, "Foo");
  ASSERT_NE(nullptr, textbox2);
  EXPECT_TRUE(
      textbox2->HasStringAttribute(ax::mojom::StringAttribute::kPlaceholder));
  EXPECT_EQ(original_id, textbox2->GetId());
}

IN_PROC_BROWSER_TEST_F(AccessibilityModeTest,
                       ReEnablingAccessibilityDoesNotTimeout) {
  EXPECT_TRUE(NavigateToURL(shell(), GURL(kMinimalPageDataURL)));
  ASSERT_TRUE(web_contents()->GetAccessibilityMode().is_mode_off());

  AccessibilityNotificationWaiter waiter(shell()->web_contents());
  web_contents()->AddAccessibilityMode(ui::kAXModeWebContentsOnly);
  EXPECT_TRUE(web_contents()->GetAccessibilityMode() ==
              ui::kAXModeWebContentsOnly);
  waiter.WaitForNotification();
  EXPECT_EQ(nullptr, GetManager());

  AccessibilityNotificationWaiter waiter2(shell()->web_contents());
  web_contents()->SetAccessibilityMode(ui::AXMode());
  web_contents()->AddAccessibilityMode(ui::kAXModeComplete);
  EXPECT_TRUE(web_contents()->GetAccessibilityMode() == ui::kAXModeComplete);
  waiter2.WaitForNotification();
  EXPECT_NE(nullptr, GetManager());
}

}  // namespace content


text:
import datetime

from django.test import TestCase
from django.utils.timezone import now

from oscar.apps.offer import reports

class TestOfferReportGenerator(TestCase):
    def test_generate_csv_no_filter(self):
        generator = reports.OfferReportGenerator(formatter='CSV')
        generator.generate()

    def test_generate_csv_start_and_end_date(self):
        start_date = now() - datetime.timedelta(days=28)
        end_date = now() + datetime.timedelta(days=28)

        generator = reports.OfferReportGenerator(
            start_date=start_date, end_date=end_date, formatter='CSV')
        generator.generate()


text:
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EFCoreExtend.Redis.EFCache.Helper
{
    public static class RedisHelper
    {
        public static void Set(this IRedisDBConnect redis, string key, string val)
        {
            var db = redis.GetDatabase();
            db.StringSet(key, val);
        }

        public static void Set(this IRedisDBConnect redis, string key, string val, TimeSpan? expiry)
        {
            var db = redis.GetDatabase();
            db.StringSet(key, val, expiry);
        }

        public static void Set(this IRedisDBConnect redis, string key, string val, DateTime? expiry)
        {
            var db = redis.GetDatabase();
            db.StringSet(key, val);
            db.KeyExpire(key, expiry);
        }

        public static void SetJson(this IRedisDBConnect redis, string key, object val)
        {
            Set(redis, key, JsonConvert.SerializeObject(val));
        }

        public static void SetJson(this IRedisDBConnect redis, string key, object val, TimeSpan expiry)
        {
            Set(redis, key, JsonConvert.SerializeObject(val), expiry);
        }

        public static void SetJson(this IRedisDBConnect redis, string key, object val, DateTime expiry)
        {
            Set(redis, key, JsonConvert.SerializeObject(val), expiry);
        }

        public static bool TryGet(this IRedisDBConnect redis, string key, out string val)
        {
            val = null;
            var db = redis.GetDatabase();
            var strVal = db.StringGet(key);
            if (strVal.HasValue)
            {
                val = strVal.ToString();
                return true;
            }
            return false;
        }

        public static bool TryGet<T>(this IRedisDBConnect redis, string key, out T val)
        {
            val = default(T);
            string strVal;
            if (TryGet(redis, key, out strVal))
            {
                try
                {
                    val = JsonConvert.DeserializeObject<T>(strVal);
                    return true;
                }
                catch
                {
                }
            }
            return false;
        }

        public static bool TryGet(this IRedisDBConnect redis, string key, Type rtnType, out object val)
        {
            val = null;
            string strVal;
            if (TryGet(redis, key, out strVal))
            {
                try
                {
                    val = JsonConvert.DeserializeObject(strVal, rtnType);
                    return true;
                }
                catch
                {
                }
            }
            return false;
        }

        public static bool TryGet(this IRedisDBConnect redis, string key, TimeSpan? expiry, out string val)
        {
            val = null;
            var db = redis.GetDatabase();
            var strVal = db.StringGet(key);
            if (strVal.HasValue)
            {
                val = strVal.ToString();
                db.KeyExpireAsync(key, expiry);
                return true;
            }
            return false;
        }

        public static bool TryGet<T>(this IRedisDBConnect redis, string key, TimeSpan? expiry, out T val)
        {
            val = default(T);
            string strVal;
            if (TryGet(redis, key, expiry, out strVal))
            {
                try
                {
                    val = JsonConvert.DeserializeObject<T>(strVal);
                    return true;
                }
                catch
                {
                }
            }
            return false;
        }

        public static bool TryGet(this IRedisDBConnect redis, string key, DateTime? expiry, out string val)
        {
            val = null;
            var db = redis.GetDatabase();
            var strVal = db.StringGet(key);
            if (strVal.HasValue)
            {
                val = strVal.ToString();
                db.KeyExpireAsync(key, expiry);
                return true;
            }
            return false;
        }

        public static bool TryGet<T>(this IRedisDBConnect redis, string key, DateTime? expiry, out T val)
        {
            val = default(T);
            string strVal;
            if (TryGet(redis, key, expiry, out strVal))
            {
                try
                {
                    val = JsonConvert.DeserializeObject<T>(strVal);
                    return true;
                }
                catch
                {
                }
            }
            return false;
        }

        public static bool TryGet(this IRedisDBConnect redis, string key, DateTime? expiry, Type rtnType, out object val)
        {
            //rtnType: 缓存数据类型(对于反序列化成对象(JSON => Type)时有用,TRtn可能为object,但是可以传递Type进行反序列化成对象)
            val = null;
            string strVal;
            if (TryGet(redis, key, expiry, out strVal))
            {
                try
                {
                    val = JsonConvert.DeserializeObject(strVal, rtnType);
                    return true;
                }
                catch
                {
                }
            }
            return false;
        }

        public static bool DeleteKey(this IRedisDBConnect redis, string key)
        {
            return redis.GetDatabase().KeyDelete(key);
        }

        public static void ClearKeys(this IRedisDBConnect redis, string keypattern)
        {
            redis.GetDatabase().ScriptEvaluate(LuaScript.Prepare(
                " local ks = redis.call('KEYS', @keypattern) " +
                " for i=1,#ks,5000 do " +
                "     redis.call('del', unpack(ks, i, math.min(i+4999, #ks))) " +
                " end " +
                " return true "
                ), new { keypattern = keypattern });
        }

    }
}


text:
"""
Display return data as a progress bar
"""

try:
    import progressbar

    HAS_PROGRESSBAR = True
except ImportError:
    HAS_PROGRESSBAR = False

def __virtual__():
    return True if HAS_PROGRESSBAR else False

def output(ret, bar, **kwargs):  # pylint: disable=unused-argument
    """
    Update the progress bar
    """
    if "return_count" in ret:
        val = ret["return_count"]
        # Avoid to fail if targets are behind a syndic. In this case actual return count will be
        # higher than targeted by MoM itself.
        # TODO: implement a way to get the proper target minions count and remove this workaround.
        # Details are in #44239.
        if val > bar.maxval:
            bar.maxval = val
        bar.update(val)
    return ""

def progress_iter(progress):
    """
    Initialize and return a progress bar iter
    """
    widgets = [
        progressbar.Percentage(),
        " ",
        progressbar.Bar(),
        " ",
        progressbar.Timer(),
        " Returns: [",
        progressbar.Counter(),
        "/{}]".format(progress["minion_count"]),
    ]
    bar = progressbar.ProgressBar(widgets=widgets, maxval=progress["minion_count"])
    bar.start()
    return bar


text:
// The Executor implements most of the SCXML interpretation pseudo-code.
// See: http://www.w3.org/TR/scxml/#AlgorithmforSCXMLInterpretation
#ifndef STATE_CHART_INTERNAL_EXECUTOR_H_
#define STATE_CHART_INTERNAL_EXECUTOR_H_

#include <string>
#include <vector>

#include "statechart/platform/types.h"

namespace state_chart {
class Model;
class Runtime;
namespace model {
class Transition;
}  // namespace model
}  // namespace state_chart

namespace state_chart {

// This class executes the StateChart with the same semantics as the algorithm
// for SCXML interpretation. An Executor instance may be shared for various
// instances of Model and Runtime. In general, StateMachine instances share the
// same Executor instance, may (or may not) share the same Model, and will own
// an instance of Runtime. The methods on Executor reflects this by allowing
// different Model and Runtime instances to be passed in as parameters.
// These input parameters should be non-null. If anyone of them is nullptr no
// action is performed.
class Executor {
 public:
  Executor() = default;
  Executor(const Executor&) = delete;
  Executor& operator=(const Executor&) = delete;
  virtual ~Executor() = default;

  // Start the execution of the machine by entering the initial state
  // and executing until the state machine reaches a stable state. A stable
  // state is one where there are no transitions and no internal events that
  // can be processed.
  virtual void Start(const Model* model, Runtime* runtime) const;

  // Notify the Executor of an external event. Executes transitions based on
  // this event until the state machine reaches a stable state.
  // This corresponds to a 'macro step' in the SCXML algorithm specification.
  // Parameter payload may be an empty string (i.e. no payload).
  virtual void SendEvent(const Model* model, Runtime* runtime,
                         const string& event, const string& payload) const;

 protected:
  // Handles all internal events until the state machine reaches a stable state.
  // This corresponds to mainEventLoop() procedure above from lines 6 to 35.
  // Input params 'model' & 'runtime' must be non-null.
  virtual void ExecuteUntilStable(const Model* model, Runtime* runtime) const;

  // Handles a single external event. This corresponds to the mainEventLoop()
  // procedure above from lines 40 to 53.
  // Parameter payload may be an empty string (i.e. no payload).
  // Input params 'model' & 'runtime' must be non-null.
  virtual void ProcessExternalEvent(const Model* model, Runtime* runtime,
                                    const string& event,
                                    const string& payload) const;

  // Execute a microstep. This takes a list of transitions, exits all their
  // source states, runs their executable blocks and finally enters all the
  // target states.
  // Input params 'model' & 'runtime' must be non-null.
  virtual void MicroStep(
      const Model* model, Runtime* runtime,
      const std::vector<const model::Transition*>& transitions) const;

  // Enters the target states of the transitions, calling their <onentery>
  // executable blocks.
  // Input params 'model' & 'runtime' must be non-null.
  virtual void EnterStates(
      const Model* model, Runtime* runtime,
      const std::vector<const model::Transition*>& transitions) const;

  // Exits the source states of the transitions, calling <onexit> executable
  // blocks.
  // Input params 'model' & 'runtime' must be non-null.
  virtual void ExitStates(
      const Model* model, Runtime* runtime,
      const std::vector<const model::Transition*>& transitions) const;

  // Assigns event data to the '_event' variable in the runtime's datamodel.
  // Parameters:
  //   event   The event name.
  //   payload The event data.
  //
  // Input params 'model' & 'runtime' must be non-null.
  virtual void AssignEventData(Runtime* runtime, const string& event,
                               const string& payload) const;

  // Shutdown the state machine by exiting all states in the correct order.
  // Input params 'model' & 'runtime' must be non-null.
  virtual void Shutdown(const Model* model, Runtime* runtime) const;
};

}  // namespace state_chart

#endif  // STATE_CHART_INTERNAL_EXECUTOR_H_


text:
from __future__ import absolute_import

from tornado import web
from tornado import gen

from .control import ControlHandler

class ListWorkers(ControlHandler):
    @web.authenticated
    @gen.coroutine
    def get(self):
        """
List workers

**Example request**:

.. sourcecode:: http

  GET /api/workers HTTP/1.1
  Host: localhost:5555

**Example response**:

.. sourcecode:: http

  HTTP/1.1 200 OK
  Content-Length: 119
  Content-Type: application/json; charset=UTF-8

  {
      "celery@worker1": {
          "completed_tasks": 0,
          "concurrency": 4,
          "queues": [
              "celery"
          ],
          "running_tasks": 0,
          "status": true
      },
      "celery@worker2": {
          "completed_tasks": 0,
          "concurrency": 4,
          "queues": [],
          "running_tasks": 0,
          "status": false
      }
  }

:reqheader Authorization: optional OAuth token to authenticate
:statuscode 200: no error
:statuscode 401: unauthorized request
        """
        refresh = self.get_argument('refresh', default=False, type=bool)
        workername = self.get_argument('workername', default=None)
        if self.worker_cache and not refresh and\
                workername in self.worker_cache:
            self.write({workername: self.worker_cache[workername]})
            return

        if refresh:
            yield self.update_cache(workername=workername)

        if workername and not self.is_worker(workername):
            raise web.HTTPError(404, "Unknown worker '%s'" % workername)

        if workername:
            self.write({workername: self.worker_cache[workername]})
        else:
            self.write(self.worker_cache)