text:
namespace SmartSchoolManagementSystem
{
    partial class FundProcess
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.panel2 = new System.Windows.Forms.Panel();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.groupBox3 = new System.Windows.Forms.GroupBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.dateTimePicker1 = new System.Windows.Forms.DateTimePicker();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.label4 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            this.label6 = new System.Windows.Forms.Label();
            this.label7 = new System.Windows.Forms.Label();
            this.textBox3 = new System.Windows.Forms.TextBox();
            this.textBox4 = new System.Windows.Forms.TextBox();
            this.comboBox1 = new System.Windows.Forms.ComboBox();
            this.comboBox2 = new System.Windows.Forms.ComboBox();
            this.label8 = new System.Windows.Forms.Label();
            this.textBox5 = new System.Windows.Forms.TextBox();
            this.label9 = new System.Windows.Forms.Label();
            this.label10 = new System.Windows.Forms.Label();
            this.textBox6 = new System.Windows.Forms.TextBox();
            this.textBox7 = new System.Windows.Forms.TextBox();
            this.panel3 = new System.Windows.Forms.Panel();
            this.button1 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.button3 = new System.Windows.Forms.Button();
            this.button4 = new System.Windows.Forms.Button();
            this.button5 = new System.Windows.Forms.Button();
            this.stdpic = new System.Windows.Forms.Panel();
            this.panel1 = new System.Windows.Forms.Panel();
            this.panel2.SuspendLayout();
            this.groupBox1.SuspendLayout();
            this.groupBox2.SuspendLayout();
            this.groupBox3.SuspendLayout();
            this.panel3.SuspendLayout();
            this.SuspendLayout();
            //
            // panel2
            //
            this.panel2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
            this.panel2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.panel2.Controls.Add(this.textBox2);
            this.panel2.Controls.Add(this.textBox1);
            this.panel2.Controls.Add(this.dateTimePicker1);
            this.panel2.Controls.Add(this.label3);
            this.panel2.Controls.Add(this.label2);
            this.panel2.Controls.Add(this.label1);
            this.panel2.Location = new System.Drawing.Point(2, 53);
            this.panel2.Name = "panel2";
            this.panel2.Size = new System.Drawing.Size(706, 52);
            this.panel2.TabIndex = 1;
            //
            // groupBox1
            //
            this.groupBox1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
            this.groupBox1.Controls.Add(this.comboBox2);
            this.groupBox1.Controls.Add(this.comboBox1);
            this.groupBox1.Controls.Add(this.label7);
            this.groupBox1.Controls.Add(this.textBox4);
            this.groupBox1.Controls.Add(this.textBox3);
            this.groupBox1.Controls.Add(this.label6);
            this.groupBox1.Controls.Add(this.label5);
            this.groupBox1.Controls.Add(this.label4);
            this.groupBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.groupBox1.Location = new System.Drawing.Point(2, 106);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(494, 161);
            this.groupBox1.TabIndex = 2;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "Student Information";
            //
            // groupBox2
            //
            this.groupBox2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
            this.groupBox2.Controls.Add(this.panel3);
            this.groupBox2.Controls.Add(this.textBox7);
            this.groupBox2.Controls.Add(this.textBox6);
            this.groupBox2.Controls.Add(this.label8);
            this.groupBox2.Controls.Add(this.textBox5);
            this.groupBox2.Controls.Add(this.label9);
            this.groupBox2.Controls.Add(this.label10);
            this.groupBox2.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.groupBox2.Location = new System.Drawing.Point(2, 269);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(494, 161);
            this.groupBox2.TabIndex = 3;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "Fund Information";
            //
            // groupBox3
            //
            this.groupBox3.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
            this.groupBox3.Controls.Add(this.stdpic);
            this.groupBox3.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.groupBox3.Location = new System.Drawing.Point(498, 106);
            this.groupBox3.Name = "groupBox3";
            this.groupBox3.Size = new System.Drawing.Size(210, 324);
            this.groupBox3.TabIndex = 3;
            this.groupBox3.TabStop = false;
            this.groupBox3.Text = "Identity";
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label1.Location = new System.Drawing.Point(10, 17);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(38, 17);
            this.label1.TabIndex = 0;
            this.label1.Text = "Date";
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label2.Location = new System.Drawing.Point(274, 18);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(74, 17);
            this.label2.TabIndex = 0;
            this.label2.Text = "Student ID";
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label3.Location = new System.Drawing.Point(504, 19);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(38, 17);
            this.label3.TabIndex = 0;
            this.label3.Text = "Sr #.";
            //
            // dateTimePicker1
            //
            this.dateTimePicker1.Location = new System.Drawing.Point(59, 17);
            this.dateTimePicker1.Name = "dateTimePicker1";
            this.dateTimePicker1.Size = new System.Drawing.Size(200, 20);
            this.dateTimePicker1.TabIndex = 1;
            //
            // textBox1
            //
            this.textBox1.Location = new System.Drawing.Point(365, 18);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(128, 20);
            this.textBox1.TabIndex = 2;
            //
            // textBox2
            //
            this.textBox2.Location = new System.Drawing.Point(553, 17);
            this.textBox2.Name = "textBox2";
            this.textBox2.Size = new System.Drawing.Size(128, 20);
            this.textBox2.TabIndex = 2;
            //
            // label4
            //
            this.label4.AutoSize = true;
            this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label4.Location = new System.Drawing.Point(6, 28);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(45, 17);
            this.label4.TabIndex = 0;
            this.label4.Text = "Name";
            //
            // label5
            //
            this.label5.AutoSize = true;
            this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label5.Location = new System.Drawing.Point(6, 56);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(57, 17);
            this.label5.TabIndex = 0;
            this.label5.Text = "F/Name";
            //
            // label6
            //
            this.label6.AutoSize = true;
            this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label6.Location = new System.Drawing.Point(6, 86);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(42, 17);
            this.label6.TabIndex = 0;
            this.label6.Text = "Class";
            //
            // label7
            //
            this.label7.AutoSize = true;
            this.label7.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label7.Location = new System.Drawing.Point(284, 86);
            this.label7.Name = "label7";
            this.label7.Size = new System.Drawing.Size(55, 17);
            this.label7.TabIndex = 0;
            this.label7.Text = "Section";
            //
            // textBox3
            //
            this.textBox3.Location = new System.Drawing.Point(96, 25);
            this.textBox3.Name = "textBox3";
            this.textBox3.Size = new System.Drawing.Size(392, 23);
            this.textBox3.TabIndex = 2;
            //
            // textBox4
            //
            this.textBox4.Location = new System.Drawing.Point(96, 54);
            this.textBox4.Name = "textBox4";
            this.textBox4.Size = new System.Drawing.Size(392, 23);
            this.textBox4.TabIndex = 2;
            //
            // comboBox1
            //
            this.comboBox1.FormattingEnabled = true;
            this.comboBox1.Location = new System.Drawing.Point(96, 80);
            this.comboBox1.Name = "comboBox1";
            this.comboBox1.Size = new System.Drawing.Size(172, 24);
            this.comboBox1.TabIndex = 3;
            //
            // comboBox2
            //
            this.comboBox2.FormattingEnabled = true;
            this.comboBox2.Location = new System.Drawing.Point(355, 83);
            this.comboBox2.Name = "comboBox2";
            this.comboBox2.Size = new System.Drawing.Size(133, 24);
            this.comboBox2.TabIndex = 4;
            //
            // label8
            //
            this.label8.AutoSize = true;
            this.label8.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label8.Location = new System.Drawing.Point(282, 60);
            this.label8.Name = "label8";
            this.label8.Size = new System.Drawing.Size(36, 17);
            this.label8.TabIndex = 3;
            this.label8.Text = "Paid";
            //
            // textBox5
            //
            this.textBox5.Location = new System.Drawing.Point(108, 22);
            this.textBox5.Name = "textBox5";
            this.textBox5.Size = new System.Drawing.Size(380, 23);
            this.textBox5.TabIndex = 6;
            //
            // label9
            //
            this.label9.AutoSize = true;
            this.label9.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label9.Location = new System.Drawing.Point(6, 59);
            this.label9.Name = "label9";
            this.label9.Size = new System.Drawing.Size(92, 17);
            this.label9.TabIndex = 4;
            this.label9.Text = "Total Amount";
            //
            // label10
            //
            this.label10.AutoSize = true;
            this.label10.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label10.Location = new System.Drawing.Point(6, 25);
            this.label10.Name = "label10";
            this.label10.Size = new System.Drawing.Size(65, 17);
            this.label10.TabIndex = 5;
            this.label10.Text = "Fund For";
            //
            // textBox6
            //
            this.textBox6.Location = new System.Drawing.Point(108, 58);
            this.textBox6.Name = "textBox6";
            this.textBox6.Size = new System.Drawing.Size(170, 23);
            this.textBox6.TabIndex = 3;
            //
            // textBox7
            //
            this.textBox7.Location = new System.Drawing.Point(318, 59);
            this.textBox7.Name = "textBox7";
            this.textBox7.Size = new System.Drawing.Size(170, 23);
            this.textBox7.TabIndex = 3;
            //
            // panel3
            //
            this.panel3.Controls.Add(this.button5);
            this.panel3.Controls.Add(this.button4);
            this.panel3.Controls.Add(this.button3);
            this.panel3.Controls.Add(this.button2);
            this.panel3.Controls.Add(this.button1);
            this.panel3.Location = new System.Drawing.Point(9, 102);
            this.panel3.Name = "panel3";
            this.panel3.Size = new System.Drawing.Size(479, 53);
            this.panel3.TabIndex = 7;
            //
            // button1
            //
            this.button1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(128)))));
            this.button1.Location = new System.Drawing.Point(4, 12);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(84, 31);
            this.button1.TabIndex = 0;
            this.button1.Text = "Add";
            this.button1.UseVisualStyleBackColor = false;
            //
            // button2
            //
            this.button2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(128)))));
            this.button2.Location = new System.Drawing.Point(94, 12);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(84, 31);
            this.button2.TabIndex = 0;
            this.button2.Text = "Save";
            this.button2.UseVisualStyleBackColor = false;
            //
            // button3
            //
            this.button3.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(128)))));
            this.button3.Location = new System.Drawing.Point(184, 12);
            this.button3.Name = "button3";
            this.button3.Size = new System.Drawing.Size(84, 31);
            this.button3.TabIndex = 0;
            this.button3.Text = "Edit";
            this.button3.UseVisualStyleBackColor = false;
            //
            // button4
            //
            this.button4.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(128)))));
            this.button4.Location = new System.Drawing.Point(274, 12);
            this.button4.Name = "button4";
            this.button4.Size = new System.Drawing.Size(84, 31);
            this.button4.TabIndex = 0;
            this.button4.Text = "Preview";
            this.button4.UseVisualStyleBackColor = false;
            //
            // button5
            //
            this.button5.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(128)))));
            this.button5.ForeColor = System.Drawing.Color.Red;
            this.button5.Location = new System.Drawing.Point(364, 12);
            this.button5.Name = "button5";
            this.button5.Size = new System.Drawing.Size(84, 31);
            this.button5.TabIndex = 0;
            this.button5.Text = "Cancel";
            this.button5.UseVisualStyleBackColor = false;
            //
            // stdpic
            //
            this.stdpic.BackColor = System.Drawing.Color.White;
            this.stdpic.BackgroundImage = global::SmartSchoolManagementSystem.Properties.Resources.imageicon1;
            this.stdpic.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.stdpic.Location = new System.Drawing.Point(32, 25);
            this.stdpic.Name = "stdpic";
            this.stdpic.Size = new System.Drawing.Size(142, 135);
            this.stdpic.TabIndex = 7;
            //
            // panel1
            //
            this.panel1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
            this.panel1.BackgroundImage = global::SmartSchoolManagementSystem.Properties.Resources.studentfund;
            this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.panel1.Location = new System.Drawing.Point(2, 1);
            this.panel1.Name = "panel1";
            this.panel1.Size = new System.Drawing.Size(706, 50);
            this.panel1.TabIndex = 0;
            //
            // FundProcess
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(712, 434);
            this.Controls.Add(this.groupBox3);
            this.Controls.Add(this.groupBox2);
            this.Controls.Add(this.groupBox1);
            this.Controls.Add(this.panel2);
            this.Controls.Add(this.panel1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
            this.Name = "FundProcess";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "Fund Process";
            this.panel2.ResumeLayout(false);
            this.panel2.PerformLayout();
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.groupBox2.ResumeLayout(false);
            this.groupBox2.PerformLayout();
            this.groupBox3.ResumeLayout(false);
            this.panel3.ResumeLayout(false);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Panel panel1;
        private System.Windows.Forms.Panel panel2;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.GroupBox groupBox2;
        private System.Windows.Forms.TextBox textBox2;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.DateTimePicker dateTimePicker1;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.GroupBox groupBox3;
        private System.Windows.Forms.ComboBox comboBox2;
        private System.Windows.Forms.ComboBox comboBox1;
        private System.Windows.Forms.Label label7;
        private System.Windows.Forms.TextBox textBox4;
        private System.Windows.Forms.TextBox textBox3;
        private System.Windows.Forms.Label label6;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.TextBox textBox7;
        private System.Windows.Forms.TextBox textBox6;
        private System.Windows.Forms.Label label8;
        private System.Windows.Forms.TextBox textBox5;
        private System.Windows.Forms.Label label9;
        private System.Windows.Forms.Label label10;
        private System.Windows.Forms.Panel panel3;
        private System.Windows.Forms.Button button5;
        private System.Windows.Forms.Button button4;
        private System.Windows.Forms.Button button3;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Panel stdpic;
    }
}


text:
module Stupidedi
  module Versions
    module FunctionalGroups
      module ThirtyFifty
        module SegmentDefs

          s = Schema
          e = ElementDefs
          r = ElementReqs

          MAN = s::SegmentDef.build(:MAN, "Marks and Numbers",
            "To indicate identifying marks and numbers for shipping containers",
            e::E88  .simple_use(r::Mandatory,  s::RepeatCount.bounded(1)),
            e::E87  .simple_use(r::Mandatory,  s::RepeatCount.bounded(1)),
            e::E87  .simple_use(r::Optional,   s::RepeatCount.bounded(1)),
            e::E88  .simple_use(r::Relational, s::RepeatCount.bounded(1)),
            e::E87  .simple_use(r::Relational, s::RepeatCount.bounded(1)),
            e::E87  .simple_use(r::Optional,   s::RepeatCount.bounded(1)),

            SyntaxNotes::P.build(4, 5),
            SyntaxNotes::C.build(6, 5))

        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
{-# LANGUAGE GADTs               #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE RankNTypes          #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators       #-}

module Main where

import           Session

import           Control.Concurrent               (forkIO, threadDelay)
import           Control.Natural
import           Control.Remote.Monad.JSON
import           Control.Remote.Monad.JSON.Client
import           Control.Remote.Monad.JSON.Router
import           Control.Remote.Monad.JSON.Server
import           Control.Remote.Monad.JSON.Trace

import           Data.Aeson.Types
import           Data.Monoid
import           Data.Text                        (Text, pack)
import qualified Data.Text.IO                     as IO

import           Data.Scientific                  as Scientific
import           System.Random

main = do
  forkIO $ serverReceiveAPI 4001 "/wobble" $ router sequence $ wrapNT remote
  threadDelay (1000 * 1000)

  putStrLn "Weak Bundle"
  let s = weakSession (traceSendAPI "" $ clientSendAPI "http://localhost:4001/wobble")
  (t,u) <- send s $ do
          say "Hello, "
          t <- temperature
          say "World!"
          u <- uptime "orange"
          return (t,u)
  print t
  print u

  putStrLn "Strong Bundle"
  let s = strongSession (traceSendAPI "" $ clientSendAPI "http://localhost:4001/wobble")
  (t,u) <- send s $ do
          say "Hello, "
          t <- temperature
          say "World!"
          u <- uptime "orange"
          return (t,u)
  print t
  print u

  putStrLn "Ap Bundle"
  let s = applicativeSession (traceSendAPI "" $ clientSendAPI "http://localhost:4001/wobble")
  (t,u) <- send s $
          say "Hello, " *>
          (pure (,) <*> temperature
                    <*  say "World!"
                    <*> uptime "orange")
  print t
  print u

------------------------------------------------------------------------------
-- Client API

say :: Text -> RPC ()
say msg = notification "say" $ List [String msg]

temperature :: RPC Int
temperature = method "temperature" None

uptime :: Text -> RPC Double
uptime nm = method "uptime" $ List [String nm]

------------------------------------------------------------------------------
-- Server API

remote :: Call a -> IO a
remote (CallNotification "say" args) = case args of
    List [String txt] -> do
        IO.putStrLn $ "remote: " <> txt
        return ()
    _ ->  invalidParams
remote (CallMethod "temperature" _) = do
        t <- randomRIO (50, 100 :: Int)
        IO.putStrLn $ "temperature: " <> pack (show t)
        return $ toJSON t
remote (CallMethod "uptime" (List [String nm])) = do
        t <- randomRIO (50, 100 :: Double)
        IO.putStrLn $ nm <> "'s uptime: " <> pack (show t)
        return $ toJSON t
remote _ = methodNotFound


text:
namespace Imgur.API.Tests.Mocks
{
    public static class MockResponses
    {
        public const string SuccessfulResponse =
            "{\"data\":true,\"success\":true,\"status\":200}";

        public const string RawError =
            "{\"data\":\"An error occurred\",\"success\":false,\"status\":500}";

        public const string Error =
            "{\"data\":{\"error\":\"Imgur is over capacity. Please try again.\", \"request\":\"/image/MwJTXbW\", \"method\":\"POST\" }, \"success\":false, \"status\":1203 }";

        public const string ErrorMessage =
            "{\"data\":{\"error\":{\"code\":500,\"message\":\"Could not complete request\",\"type\":\"ImgurException\",\"exception\":{}},\"request\":\"/3/account/sarah/gallery_profile\",\"method\":\"GET\"},\"success\":false,\"status\":500}";

        public const string FailureError =
            "{\"data\":false,\"success\":false,\"status\":400}";

        public const string CacheError =
            "\r\n" +
            " <xml";
    }
}


text:
import {WindowInterface} from '#core/window/interface';

import {toggleExperiment} from '#experiments';

import {Services} from '#service';

import {PageConfig} from '#third_party/subscriptions-project/config';
import {
  ConfiguredRuntime,
  Entitlements,
  SubscribeResponse,
  Entitlement as SwgEntitlement,
} from '#third_party/subscriptions-project/swg';
import {GaaMeteringRegwall} from '#third_party/subscriptions-project/swg-gaa';

import {
  Action,
  ActionStatus,
  SubscriptionAnalytics,
} from '../../../amp-subscriptions/0.1/analytics';
import {SubscriptionsScoreFactor} from '../../../amp-subscriptions/0.1/constants';
import {
  Entitlement,
  GrantReason,
} from '../../../amp-subscriptions/0.1/entitlement';
import {ServiceAdapter} from '../../../amp-subscriptions/0.1/service-adapter';
import {
  AmpFetcher,
  GoogleSubscriptionsPlatform,
} from '../amp-subscriptions-google';

const PLATFORM_ID = 'subscribe.google.com';
const AMP_URL = 'myAMPurl.amp';

describes.realWin('AmpFetcher', {amp: true}, (env) => {
  let fetcher;
  let xhr;

  const sentUrl = 'url';
  const sentArray = [
    'embed',
    'tx',
    'refer',
    'utmS',
    'utmC',
    'utmM',
    'sku',
    true,
    ['exp1', 'exp2'],
    'version',
    'baseUrl',
  ];
  const sentMessage = {
    toArray: function () {
      return sentArray;
    },
  };
  const contentType = 'application/x-www-form-urlencoded;charset=UTF-8';
  const expectedBodyString = 'f.req=' + JSON.stringify(sentArray);

  beforeEach(() => {
    const {win} = env.ampdoc;
    fetcher = new AmpFetcher(win);
    xhr = Services.xhrFor(win);
  });

  it('should support beacon when beacon supported', async () => {
    const expectedBlob = new Blob([expectedBodyString], {type: contentType});
    env.sandbox.stub(WindowInterface, 'getSendBeacon').callsFake(() => {
      return (url, body) => {
        expect(url).to.equal(sentUrl);
        expect(body).to.deep.equal(expectedBlob);
      };
    });
    fetcher.sendBeacon(sentUrl, sentMessage);
  });

  it('should support beacon when beacon not supported', async () => {
    env.sandbox.stub(WindowInterface, 'getSendBeacon').callsFake(() => null);
    env.sandbox.stub(xhr, 'fetch').callsFake((url, init) => {
      expect(url).to.equal(sentUrl);
      expect(init).to.deep.equal({
        method: 'POST',
        headers: {'Content-Type': contentType},
        credentials: 'include',
        body: expectedBodyString,
      });
    });

    fetcher.sendBeacon(sentUrl, sentMessage);
  });
});

describes.realWin('amp-subscriptions-google', {amp: true}, (env) => {
  let ampdoc;
  let pageConfig;
  let platform;
  let serviceAdapter;
  let serviceAdapterMock;
  let getEncryptedDocumentKeyStub;
  let analyticsMock;
  let viewer;
  let xhr;
  let callbacks;
  let methods;
  let ackStub;
  let element;
  let entitlementResponse;
  let rtcButtonElement;
  let win;
  let subscriptionService;

  beforeEach(() => {
    win = env.win;
    ampdoc = env.ampdoc;
    element = env.win.document.createElement('script');
    element.id = 'amp-subscriptions';
    env.win.document.head.appendChild(element);
    env.sandbox.stub(ampdoc, 'getUrl').callsFake(() => AMP_URL);
    pageConfig = new PageConfig('example.org:basic', true);
    xhr = Services.xhrFor(env.win);
    viewer = Services.viewerForDoc(ampdoc);
    ampdoc.params_['viewerUrl'] = 'https://www.google.com/other';
    subscriptionService = {};
    serviceAdapter = new ServiceAdapter(subscriptionService);
    serviceAdapterMock = env.sandbox.mock(serviceAdapter);
    env.sandbox
      .stub(serviceAdapter, 'getPageConfig')
      .callsFake(() => pageConfig);
    env.sandbox
      .stub(serviceAdapter, 'getReaderId')
      .callsFake(() => Promise.resolve('ari1'));
    const analytics = new SubscriptionAnalytics(ampdoc.getRootNode());
    env.sandbox.stub(serviceAdapter, 'getAnalytics').callsFake(() => analytics);
    analyticsMock = env.sandbox.mock(analytics);
    getEncryptedDocumentKeyStub = env.sandbox
      .stub(serviceAdapter, 'getEncryptedDocumentKey')
      .callsFake(() => {
        return null;
      });
    entitlementResponse = {
      source: 'google',
      products: ['example.org:basic'],
      subscriptionToken: 'tok1',
    };
    callbacks = {
      loginRequest: env.sandbox.stub(
        ConfiguredRuntime.prototype,
        'setOnLoginRequest'
      ),
      linkComplete: env.sandbox.stub(
        ConfiguredRuntime.prototype,
        'setOnLinkComplete'
      ),
      flowStarted: env.sandbox.stub(
        ConfiguredRuntime.prototype,
        'setOnFlowStarted'
      ),
      flowCanceled: env.sandbox.stub(
        ConfiguredRuntime.prototype,
        'setOnFlowCanceled'
      ),
      subscribeRequest: env.sandbox.stub(
        ConfiguredRuntime.prototype,
        'setOnNativeSubscribeRequest'
      ),
      subscribeResponse: env.sandbox.stub(
        ConfiguredRuntime.prototype,
        'setOnPaymentResponse'
      ),
    };
    methods = {
      reset: env.sandbox.stub(ConfiguredRuntime.prototype, 'reset'),
      showContributionOptions: env.sandbox.stub(
        ConfiguredRuntime.prototype,
        'showContributionOptions'
      ),
      subscribe: env.sandbox.stub(ConfiguredRuntime.prototype, 'subscribe'),
      showOffers: env.sandbox.stub(ConfiguredRuntime.prototype, 'showOffers'),
      showAbbrvOffer: env.sandbox.stub(
        ConfiguredRuntime.prototype,
        'showAbbrvOffer'
      ),
      linkAccount: env.sandbox.stub(ConfiguredRuntime.prototype, 'linkAccount'),
      consumeShowcaseEntitlementJwt: env.sandbox.stub(
        ConfiguredRuntime.prototype,
        'consumeShowcaseEntitlementJwt'
      ),
    };
    ackStub = env.sandbox.stub(Entitlements.prototype, 'ack');
    toggleExperiment(win, 'swg-gpay-api', true);
    toggleExperiment(win, 'nonswgexp', true);
    platform = new GoogleSubscriptionsPlatform(ampdoc, {}, serviceAdapter);
  });

  afterEach(() => {
    serviceAdapterMock.verify();
    analyticsMock.verify();
    toggleExperiment(win, 'swg-gpay-api', false);
  });

  /** Awaits N times. Allows promises to resolve. */
  async function flush(n = 100) {
    for (let i = 0; i < n; i++) {
      await 'tick';
    }
  }

  function callback(stub) {
    return stub.args[0][0];
  }

  it('should set the current URL in analytics', () => {
    const swgAnalytics = platform.runtime_.analytics();
    expect(swgAnalytics.getContext().getUrl()).to.equal(AMP_URL);
  });

  it('should reset runtime on platform reset', () => {
    expect(methods.reset).to.not.be.called;
    platform.reset();
    expect(methods.reset).to.be.calledOnce.calledWithExactly();
  });

  it('should listen on callbacks', () => {
    expect(callbacks.loginRequest).to.be.calledOnce;
  });

  it('should scope the runtime to one ampdoc', () => {
    expect(platform.runtime_.doc_.ampdoc_).to.equal(ampdoc);
  });

  it('should propagate experiment', () => {
    expect(platform.runtime_.payClient_.getType()).to.equal('PAYJS');
    expect(platform.runtime_.config()['experiments']).to.have.members([
      'gpay-api',
    ]);
  });

  it('should throw if enableLAA and enableMetering are set', () => {
    expect(
      () =>
        new GoogleSubscriptionsPlatform(
          ampdoc,
          {enableLAA: true, enableMetering: true},
          serviceAdapter
        )
    ).to.throw(/enableLAA and enableMetering are mutually exclusive/);
  });

  it('should ignore enableLAA and fallback if url params are missing', async () => {
    env.sandbox
      .stub(viewer, 'getReferrerUrl')
      .callsFake(() => Promise.resolve('http://localhost'));
    platform = new GoogleSubscriptionsPlatform(
      ampdoc,
      {enableLAA: true},
      serviceAdapter
    );
    const fetchStub = env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
      Promise.resolve({
        json: () =>
          Promise.resolve({
            entitlements: {},
          }),
      })
    );

    await platform.getEntitlements();
    expect(fetchStub).to.be.calledOnce;
  });

  it('should ignore enableLAA and not fallback if url params are missing and enableEntitlements is false', async () => {
    env.sandbox
      .stub(viewer, 'getReferrerUrl')
      .callsFake(() => Promise.resolve('http://localhost'));
    platform = new GoogleSubscriptionsPlatform(
      ampdoc,
      {enableLAA: true, enableEntitlements: false},
      serviceAdapter
    );
    const fetchStub = env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
      Promise.resolve({
        json: () =>
          Promise.resolve({
            entitlements: {},
          }),
      })
    );

    await platform.getEntitlements();
    expect(fetchStub).to.not.be.called;
  });

  it('should ignore enableLAA if url params have expired', async () => {
    env.sandbox
      .stub(viewer, 'getReferrerUrl')
      .callsFake(() => Promise.resolve('http://localhost'));
    platform = new GoogleSubscriptionsPlatform(
      ampdoc,
      {enableLAA: true},
      serviceAdapter
    );

    env.sandbox.stub(platform, 'getUrlParams_').returns({
      'gaa_ts': (Date.now() / 1000 - 10).toString(16),
      'gaa_at': 'la',
      'gaa_sig': 'signature',
      'gaa_n': 123456,
    });

    const fetchStub = env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
      Promise.resolve({
        json: () =>
          Promise.resolve({
            entitlements: {},
          }),
      })
    );
    await platform.getEntitlements();
    expect(fetchStub).to.be.calledOnce;
  });

  it('should return LAA if url params present and are in timestamp', async () => {
    env.sandbox
      .stub(viewer, 'getReferrerUrl')
      .callsFake(() => Promise.resolve('http://localhost'));
    platform = new GoogleSubscriptionsPlatform(
      ampdoc,
      {enableLAA: true},
      serviceAdapter
    );
    env.sandbox.stub(platform, 'getUrlParams_').returns({
      'gaa_ts': (Date.now() / 1000 + 10).toString(16),
      'gaa_at': 'la',
      'gaa_sig': 'signature',
      'gaa_n': 123456,
    });
    const fetchStub = env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
      Promise.resolve({
        json: () =>
          Promise.resolve({
            entitlements: {},
          }),
      })
    );
    const ents = await platform.getEntitlements();
    expect(ents.service).to.not.be.null;
    expect(ents.source).to.equal('google:laa');
    expect(fetchStub).to.not.be.called;
  });

  it('should ignore valid LAA if referrer domain is not allowed', async () => {
    env.sandbox
      .stub(viewer, 'getReferrerUrl')
      .callsFake(() => Promise.resolve('http://www.example.com'));
    platform = new GoogleSubscriptionsPlatform(
      ampdoc,
      {enableLAA: true, enableEntitlements: false},
      serviceAdapter
    );
    ampdoc.win.__AMP_MODE.localDev = false;
    env.sandbox.stub(platform, 'getUrlParams_').returns({
      'gaa_ts': (Date.now() / 1000 + 10).toString(16),
      'gaa_at': 'la',
      'gaa_sig': 'signature',
      'gaa_n': 123456,
    });
    const fetchStub = env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
      Promise.resolve({
        json: () =>
          Promise.resolve({
            entitlements: {},
          }),
      })
    );

    const ents = await platform.getEntitlements();
    expect(ents).to.be.null;
    expect(fetchStub).to.not.be.called;
  });

  it('should ignore valid LAA if referrer protocol is not allowed', async () => {
    env.sandbox
      .stub(viewer, 'getReferrerUrl')
      .callsFake(() => Promise.resolve('http://google.com'));
    platform = new GoogleSubscriptionsPlatform(
      ampdoc,
      {enableLAA: true, enableEntitlements: false},
      serviceAdapter
    );
    ampdoc.win.__AMP_MODE.localDev = false;
    env.sandbox.stub(platform, 'getUrlParams_').returns({
      'gaa_ts': (Date.now() / 1000 + 10).toString(16),
      'gaa_at': 'la',
      'gaa_sig': 'signature',
      'gaa_n': 123456,
    });
    const fetchStub = env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
      Promise.resolve({
        json: () =>
          Promise.resolve({
            entitlements: {},
          }),
      })
    );

    const ents = await platform.getEntitlements();
    expect(ents).to.be.null;
    expect(fetchStub).to.not.be.called;
  });

  it('should request metering entitlements if URL params are present and timestamp is valid', async () => {
    env.sandbox
      .stub(viewer, 'getReferrerUrl')
      .callsFake(() => Promise.resolve('http://localhost'));
    platform = new GoogleSubscriptionsPlatform(
      ampdoc,
      {enableMetering: true},
      serviceAdapter
    );
    env.sandbox.stub(platform, 'getUrlParams_').returns({
      'gaa_ts': (Date.now() / 1000 + 10).toString(16),
      'gaa_at': 'g',
      'gaa_sig': 'signature',
      'gaa_n': 123456,
    });
    env.sandbox
      .stub(serviceAdapter, 'loadMeteringState')
      .resolves({id: 'abc123'});
    const fetchStub = env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
      Promise.resolve({
        json: () =>
          Promise.resolve({
            entitlements: [
              {
                source: 'google:metering',
                products: ['example.org:basic'],
                subscriptionToken: 'tok1',
              },
            ],
          }),
      })
    );
    const ents = await platform.getEntitlements();
    expect(ents.service).to.not.be.null;
    expect(ents.source).to.equal('google:metering');

    const fetchUrl = fetchStub.getCall(0).args[0];
    expect(fetchUrl).to.equal(
      'https://news.google.com/swg/_/api/v1/publication/example.org/entitlements?encodedParams=eyJtZXRlcmluZyI6eyJjbGllbnRUeXBlcyI6WzFdLCJvd25lciI6ImV4YW1wbGUub3JnIiwicmVzb3VyY2UiOnsiaGFzaGVkQ2Fub25pY2FsVXJsIjoiMjcwM2YyYjZlZjBlYWFhODEzNzZhMThmYWE3N2E1OTAwOTc1Zjc3MDVkNWQ4YjZlMWEzNzJkNWY2YzJiOTdiYjU5ZjI4M2Q3MzdiNmQ5YWI3N2M1YTNkODQ4YzZlY2UyMDdjZDYwMzU4M2NjMzIyZGQ4MGFiMGI5MzA5MmM2NTAifSwic3RhdGUiOnsiaWQiOiJhYmMxMjMiLCJhdHRyaWJ1dGVzIjpbXX19fQ'
    );
  });

  it('should proxy fetch via AMP fetcher', async () => {
    const fetchStub = env.sandbox
      .stub(xhr, 'fetchJson')
      .callsFake((url, init) => {
        expect(url).to.match(/publication\/example.org/);
        expect(init).to.deep.equal({
          credentials: 'include',
          prerenderSafe: true,
        });
        return Promise.resolve({
          json: () => Promise.resolve({entitlements: entitlementResponse}),
        });
      });

    const ents = await platform.getEntitlements();
    expect(ents.service).to.equal(PLATFORM_ID);
    expect(fetchStub).to.be.calledOnce;
  });

  it('should proxy fetch non-granting response', async () => {
    const fetchStub = env.sandbox
      .stub(xhr, 'fetchJson')
      .callsFake((url, init) => {
        expect(url).to.match(/publication\/example.org/);
        expect(init).to.deep.equal({
          credentials: 'include',
          prerenderSafe: true,
        });
        return Promise.resolve({
          json: () =>
            Promise.resolve({
              entitlements: {
                source: 'subscribe.google.com',
                products: ['example.org:registered_user'],
                subscriptionToken: 'tok1',
              },
            }),
        });
      });

    const ents = await platform.getEntitlements();
    expect(ents.source).to.equal(PLATFORM_ID);
    expect(ents.granted).to.be.false;
    expect(fetchStub).to.be.calledOnce;
  });

  it('should proxy fetch empty response', async () => {
    env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
      Promise.resolve({
        json: () =>
          Promise.resolve({
            entitlements: {},
          }),
      })
    );

    const ents = await platform.getEntitlements();
    expect(ents).to.be.null;
  });

  it('should ack matching entitlements', async () => {
    env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
      Promise.resolve({
        json: () => Promise.resolve({entitlements: entitlementResponse}),
      })
    );

    await platform.getEntitlements();
    expect(ackStub).to.be.calledOnce;
  });

  it('should NOT ack non-matching entitlements', async () => {
    env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
      Promise.resolve({
        json: () =>
          Promise.resolve({
            entitlements: {},
          }),
      })
    );

    await platform.getEntitlements();
    expect(ackStub).to.not.be.called;
  });

  it('should ignore activate when granted', () => {
    platform.activate(
      new Entitlement({
        service: PLATFORM_ID,
        granted: true,
        grantReason: GrantReason.SUBSCRIBER,
      })
    );
    expect(methods.showOffers).to.not.be.called;
    expect(methods.showAbbrvOffer).to.not.be.called;
  });

  it('should show offers on activate when not granted', async () => {
    platform.activate(new Entitlement({service: PLATFORM_ID, granted: false}));
    await flush();

    expect(methods.showOffers).to.be.calledOnce.calledWithExactly({
      list: 'amp',
    });
    expect(methods.showAbbrvOffer).to.not.be.called;
  });

  it('should show abbrv offer on activate when granted non-subscriber', async () => {
    platform.activate(
      new Entitlement({
        service: PLATFORM_ID,
        granted: true,
        grantReason: GrantReason.METERING,
      })
    );
    await flush();

    expect(methods.showAbbrvOffer).to.be.calledOnce.calledWithExactly({
      list: 'amp',
    });
    expect(methods.showOffers).to.not.be.called;
  });

  it('should override show offers with the grant for subscriber', () => {
    const entitlement = new Entitlement({service: PLATFORM_ID, granted: false});
    const grantEntitlement = new Entitlement({
      service: 'local',
      granted: true,
      grantReason: GrantReason.SUBSCRIBER,
    });
    platform.activate(entitlement, grantEntitlement);
    expect(methods.showOffers).to.not.be.called;
    expect(methods.showAbbrvOffer).to.not.be.called;
  });

  it('should override show offers with the grant non-subscriber', async () => {
    const entitlement = new Entitlement({service: PLATFORM_ID, granted: false});
    const grantEntitlement = new Entitlement({
      service: 'local',
      granted: true,
      grantReason: GrantReason.METERING,
    });
    platform.activate(entitlement, grantEntitlement);
    await flush();

    expect(methods.showOffers).to.not.be.called;
    expect(methods.showAbbrvOffer).to.be.calledOnce;
  });

  it('should consume showcase entitlement, if appropriate', async () => {
    platform = new GoogleSubscriptionsPlatform(
      ampdoc,
      {enableMetering: true},
      serviceAdapter
    );
    env.sandbox.stub(platform, 'getUrlParams_').returns({
      'gaa_ts': (Date.now() / 1000 + 10).toString(16),
      'gaa_at': 'g',
      'gaa_sig': 'signature',
      'gaa_n': 123456,
    });
    const entitlement = new Entitlement({service: PLATFORM_ID, granted: true});
    const grantEntitlement = new Entitlement({
      service: 'local',
      granted: true,
      grantReason: GrantReason.METERING,
    });
    platform.activate(entitlement, grantEntitlement);
    await flush();

    expect(methods.consumeShowcaseEntitlementJwt).to.be.called;
  });

  it('should show showcase regwall, if appropriate', async () => {
    platform = new GoogleSubscriptionsPlatform(
      ampdoc,
      {enableMetering: true},
      serviceAdapter
    );
    env.sandbox.stub(platform, 'getUrlParams_').returns({
      'gaa_ts': (Date.now() / 1000 + 10).toString(16),
      'gaa_at': 'g',
      'gaa_sig': 'signature',
      'gaa_n': 123456,
    });
    env.sandbox.stub(serviceAdapter, 'loadMeteringState').resolves(null);
    env.sandbox.stub(platform.fetcher_, 'sendPostToPublisher').resolves();
    env.sandbox.stub(GaaMeteringRegwall, 'show').resolves();
    env.sandbox.stub(serviceAdapter, 'saveMeteringState').resolves();
    const entitlement = new Entitlement({service: PLATFORM_ID, granted: false});
    const continueSpy = env.sandbox.spy();
    platform.activate(entitlement, entitlement, continueSpy);
    await flush();

    expect(platform.fetcher_.sendPostToPublisher).to.be.calledOnce;
    expect(GaaMeteringRegwall.show).to.be.calledOnce;
    expect(serviceAdapter.saveMeteringState).to.be.calledOnce;
    expect(continueSpy).to.be.calledOnce;
  });

  it('should start linking flow when requested', async () => {
    serviceAdapterMock.expects('delegateActionToLocal').never();
    callback(callbacks.loginRequest)({linkRequested: true});
    await 'Event loop tick';
    expect(methods.linkAccount).to.be.calledOnce.calledWithExactly({
      ampReaderId: 'ari1',
    });
  });

  it('should delegate login when linking not requested', () => {
    serviceAdapterMock
      .expects('delegateActionToLocal')
      .withExactArgs(Action.LOGIN, null)
      .returns(Promise.resolve(false))
      .once();
    callback(callbacks.loginRequest)({linkRequested: false});
    expect(methods.linkAccount).to.not.be.called;
  });

  it('should delegate login for a non-google viewer', () => {
    platform.isGoogleViewer_ = false;
    serviceAdapterMock
      .expects('delegateActionToLocal')
      .withExactArgs(Action.LOGIN, null)
      .returns(Promise.resolve(false))
      .once();
    callback(callbacks.loginRequest)({linkRequested: true});
    expect(methods.linkAccount).to.not.be.called;
  });

  it('should not allow prerender for non-google viewer', () => {
    platform.isGoogleViewer_ = false;
    expect(platform.isPrerenderSafe()).to.be.false;
  });

  it('should reauthorize on complete linking', () => {
    analyticsMock
      .expects('actionEvent')
      .withExactArgs(PLATFORM_ID, Action.LINK, ActionStatus.SUCCESS)
      .once();
    serviceAdapterMock.expects('resetPlatforms').once();
    callback(callbacks.linkComplete)();
  });

  it('should reauthorize on canceled linking', () => {
    analyticsMock
      .expects('actionEvent')
      .withExactArgs(PLATFORM_ID, Action.LINK, ActionStatus.REJECTED)
      .once();
    serviceAdapterMock.expects('resetPlatforms').once();
    callback(callbacks.flowCanceled)({flow: 'linkAccount'});
  });

  describe('should log subscribe start', () => {
    let productId;
    let data;

    afterEach(() => {
      analyticsMock
        .expects('actionEvent')
        .withExactArgs(PLATFORM_ID, Action.SUBSCRIBE, ActionStatus.STARTED, {
          active: true,
          product: productId,
        })
        .once();
      callback(callbacks.flowStarted)({flow: Action.SUBSCRIBE, data});
    });
    it('should work without a productId', () => {
      productId = 'unknown productId';
    });

    it('should work with a productId', () => {
      productId = 'PRODUCTID';
      data = {
        product: productId,
      };
    });
  });

  it('should log subscribe cancel', () => {
    analyticsMock
      .expects('actionEvent')
      .withExactArgs(PLATFORM_ID, Action.SUBSCRIBE, ActionStatus.REJECTED)
      .once();
    callback(callbacks.flowCanceled)({flow: Action.SUBSCRIBE});
  });

  describe('should reauthorize on complete subscribe', () => {
    let productId;
    let entitlements;
    const platformKey = 'platformKey';

    afterEach(() => {
      analyticsMock
        .expects('actionEvent')
        .withExactArgs(PLATFORM_ID, Action.SUBSCRIBE, ActionStatus.SUCCESS, {
          active: true,
          product: productId,
        })
        .once();
      const promise = Promise.resolve();
      const response = new SubscribeResponse(
        null,
        null,
        null,
        entitlements,
        productId,
        () => promise,
        null
      );
      const resetPlatformsPromise = new Promise((resolve) => {
        env.sandbox.stub(serviceAdapter, 'resetPlatforms').callsFake(() => {
          resolve();
        });
      });
      callback(callbacks.subscribeResponse)(Promise.resolve(response));
      expect(methods.reset).to.not.be.called;
      return resetPlatformsPromise;
    });

    it('should work without entitlements', () => {
      productId = 'unknown subscriptionToken';
      entitlements = null;
    });

    it('should work with poorly formatted entitlements', () => {
      productId = 'unknown subscriptionToken';
      entitlements = new Entitlements(
        platformKey,
        null,
        [new SwgEntitlement(null, [productId], null)],
        productId
      );
    });

    it('should work with Google formatted entitlements', () => {
      productId = 'myProduct';
      const token = JSON.stringify({
        productId,
      });
      entitlements = new Entitlements(
        platformKey,
        null,
        [new SwgEntitlement('google', [productId], token)],
        productId
      );
    });
  });

  it('should delegate native subscribe request', () => {
    serviceAdapterMock
      .expects('delegateActionToLocal')
      .withExactArgs(Action.SUBSCRIBE, null)
      .returns(Promise.resolve(false))
      .once();
    callback(callbacks.subscribeRequest)();
  });

  it('should reset on successful login', async () => {
    const loginResult = Promise.resolve(true);
    serviceAdapterMock
      .expects('delegateActionToLocal')
      .withExactArgs(Action.LOGIN, null)
      .returns(loginResult)
      .once();
    callback(callbacks.loginRequest)({linkRequested: false});

    await loginResult;
    expect(methods.reset).to.be.calledOnce.calledWithExactly();
  });

  it('should NOT reset on failed login', async () => {
    const loginResult = Promise.resolve(false);
    serviceAdapterMock
      .expects('delegateActionToLocal')
      .withExactArgs(Action.LOGIN, null)
      .returns(loginResult)
      .once();
    callback(callbacks.loginRequest)({linkRequested: false});

    await loginResult;
    expect(methods.reset).to.not.be.called;
  });

  it('should reset on successful subscribe', async () => {
    const loginResult = Promise.resolve(true);
    serviceAdapterMock
      .expects('delegateActionToLocal')
      .withExactArgs(Action.SUBSCRIBE, null)
      .returns(loginResult)
      .once();
    callback(callbacks.subscribeRequest)();

    await loginResult;
    expect(methods.reset).to.be.calledOnce.calledWithExactly();
  });

  it('should infer the viewer from viewerUrl', () => {
    delete ampdoc.params_['viewerUrl'];
    platform = new GoogleSubscriptionsPlatform(ampdoc, {}, serviceAdapter);
    expect(platform.isGoogleViewer_).to.be.false;

    ampdoc.params_['viewerUrl'] = 'https://www.google.com/other';
    platform = new GoogleSubscriptionsPlatform(ampdoc, {}, serviceAdapter);
    expect(platform.isGoogleViewer_).to.be.true;
  });

  it('should infer the viewer from origin', async () => {
    delete ampdoc.params_['viewerUrl'];
    let viewerOrigin = null;
    env.sandbox.stub(viewer, 'getViewerOrigin').callsFake(() => viewerOrigin);

    await 'Event loop tick';

    viewerOrigin = Promise.resolve('');
    platform = new GoogleSubscriptionsPlatform(ampdoc, {}, serviceAdapter);
    await viewerOrigin;
    expect(platform.isGoogleViewer_).to.be.false;

    // Other origin.
    viewerOrigin = Promise.resolve('https://other.com');
    platform = new GoogleSubscriptionsPlatform(ampdoc, {}, serviceAdapter);
    await viewerOrigin;
    expect(platform.isGoogleViewer_).to.be.false;

    // Google origin.
    viewerOrigin = Promise.resolve('https://google.com');
    platform = new GoogleSubscriptionsPlatform(ampdoc, {}, serviceAdapter);
    await viewerOrigin;
    expect(platform.isGoogleViewer_).to.be.true;
  });

  it('should allow prerender if in a google viewer', () => {
    ampdoc.params_['viewerUrl'] = 'https://www.google.com/other';
    platform = new GoogleSubscriptionsPlatform(ampdoc, {}, serviceAdapter);
    expect(platform.isPrerenderSafe()).to.be.true;
  });

  it('should attach button given to decorateUI', () => {
    const elem = env.win.document.createElement('div');
    const decorateStub = env.sandbox.stub(
      platform.runtime_.buttonApi_,
      'attach'
    );
    elem.textContent = 'some html';
    platform.decorateUI(elem, 'subscribe');
    expect(elem.textContent).to.be.equal('');
    expect(decorateStub).to.be.calledWith(elem);
  });

  it('should attach smartbutton given to decorateUI', () => {
    const elem = env.win.document.createElement('div');
    const attachStub = env.sandbox.stub(platform.runtime_, 'attachSmartButton');
    elem.textContent = 'some html';
    elem.setAttribute('subscriptions-lang', 'en');
    platform.decorateUI(elem, 'subscribe-smartbutton');
    expect(elem.textContent).to.be.equal('');
    expect(attachStub).to.be.calledWith(elem, {lang: 'en', theme: 'light'});
  });

  it('should use light smartbutton theme', () => {
    const elem = env.win.document.createElement('div');
    const attachStub = env.sandbox.stub(platform.runtime_, 'attachSmartButton');
    elem.textContent = 'some html';
    elem.setAttribute('subscriptions-lang', 'en');
    platform.decorateUI(elem, 'subscribe-smartbutton-light');
    expect(elem.textContent).to.be.equal('');
    expect(attachStub).to.be.calledWith(elem, {theme: 'light', lang: 'en'});
  });

  it('should use dark smartbutton theme', () => {
    const elem = env.win.document.createElement('div');
    const attachStub = env.sandbox.stub(platform.runtime_, 'attachSmartButton');
    elem.textContent = 'some html';
    elem.setAttribute('subscriptions-lang', 'en');
    platform.decorateUI(elem, 'subscribe-smartbutton-dark');
    expect(elem.textContent).to.be.equal('');
    expect(attachStub).to.be.calledWith(elem, {theme: 'dark', lang: 'en'});
  });

  it('should use message text color', () => {
    const elem = env.win.document.createElement('div');
    const attachStub = env.sandbox.stub(platform.runtime_, 'attachSmartButton');
    elem.textContent = 'some html';
    elem.setAttribute('subscriptions-lang', 'en');
    elem.setAttribute('subscriptions-message-text-color', '#09f');
    platform.decorateUI(elem, 'subscribe-smartbutton');
    expect(elem.textContent).to.be.equal('');
    expect(attachStub).to.be.calledWith(elem, {
      lang: 'en',
      messageTextColor: '#09f',
      theme: 'light',
    });
  });

  it('should use message number', () => {
    const elem = env.win.document.createElement('div');
    const attachStub = env.sandbox.stub(platform.runtime_, 'attachSmartButton');
    elem.textContent = 'some html';
    elem.setAttribute('subscriptions-lang', 'en');
    elem.setAttribute('subscriptions-message-number', 1);
    platform.decorateUI(elem, 'subscribe-smartbutton');
    expect(attachStub).to.be.calledWith(elem, {
      lang: 'en',
      theme: 'light',
      messageNumber: '1', // Message is 'Subscribe with just a few taps' on smartbox button.
    });
  });

  it('should throw if smartButton language is missing', () => {
    //expectAsyncConsoleError(/must have a language attrbiute/);
    const elem = env.win.document.createElement('div');
    elem.textContent = 'some html';
    expect(() => {
      allowConsoleError(() => {
        platform.decorateUI(elem, 'subscribe-smartbutton');
      });
    }).to.throw(/language/);
  });

  it('should show offers if subscribe action is delegated', () => {
    const executeStub = platform.runtime_.showOffers;
    platform.executeAction(Action.SUBSCRIBE);
    expect(executeStub).to.be.calledWith({list: 'amp', isClosable: true});
  });

  it('should do nothing if rtc mapped button is not read ', () => {
    // rtc button
    rtcButtonElement = env.win.document.createElement('button');
    rtcButtonElement.setAttribute('subscriptions-google-rtc', '');
    rtcButtonElement.id = 'rtcTestButton';
    env.win.document.body.appendChild(rtcButtonElement);
    platform.skuMap_ = {
      rtcTestButton: {
        sku: 'testSku',
      },
    };
    const executeStub = platform.runtime_.subscribe;
    platform.executeAction(Action.SUBSCRIBE, 'rtcTestButton');
    expect(executeStub).to.not.be.called;
  });

  it('should show subscribe flow if single sku is mapped ', () => {
    // rtc button
    rtcButtonElement = env.win.document.createElement('button');
    rtcButtonElement.setAttribute('subscriptions-google-rtc-set', '');
    rtcButtonElement.id = 'rtcTestButton';
    env.win.document.body.appendChild(rtcButtonElement);
    platform.skuMap_ = {
      rtcTestButton: {
        sku: 'testSku',
      },
    };
    const executeStub = platform.runtime_.subscribe;
    platform.executeAction(Action.SUBSCRIBE, 'rtcTestButton');
    expect(executeStub).to.be.calledWith('testSku');
  });

  it("should show offers if multiple sku's are mapped", () => {
    // rtc button
    rtcButtonElement = env.win.document.createElement('button');
    rtcButtonElement.setAttribute('subscriptions-google-rtc-set', '');
    rtcButtonElement.id = 'rtcTestButton';
    env.win.document.body.appendChild(rtcButtonElement);
    platform.skuMap_ = {
      rtcTestButton: {
        carouselOptions: {skus: ['testSku1', 'testsku2']},
      },
    };
    const executeStub = platform.runtime_.showOffers;
    platform.executeAction(Action.SUBSCRIBE, 'rtcTestButton');
    expect(executeStub).to.be.calledWith({
      isClosable: true,
      skus: ['testSku1', 'testsku2'],
    });
  });

  it('should show contributions if contribute action is delegated', () => {
    const executeStub = platform.runtime_.showContributionOptions;
    platform.executeAction(Action.CONTRIBUTE);
    expect(executeStub).to.be.calledWith({list: 'amp', isClosable: true});
  });

  it('should link accounts if login action is delegated', async () => {
    const executeStub = platform.runtime_.linkAccount;
    platform.executeAction(Action.LOGIN);
    await 'Event loop tick';
    expect(executeStub).to.be.calledWith();
  });

  describe('getEntitlements', () => {
    it('should convert granted entitlements to internal shape', async () => {
      env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
        Promise.resolve({
          json: () => Promise.resolve({entitlements: entitlementResponse}),
        })
      );

      const entitlement = await platform.getEntitlements();
      expect(entitlement.source).to.be.equal('google');
      expect(entitlement.granted).to.be.equal(true);
      expect(entitlement.grantReason).to.be.equal(GrantReason.SUBSCRIBER);
      expect(entitlement.data).to.deep.equal(entitlementResponse);
    });

    it('should convert non granted internal shape with granted == false', async () => {
      env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
        Promise.resolve({
          json: () =>
            Promise.resolve({
              entitlements: {
                source: 'google',
                products: ['example.org:premium'],
                subscriptionToken: '',
              },
            }),
        })
      );

      const entitlement = await platform.getEntitlements();
      expect(entitlement.source).to.be.equal('google');
      expect(entitlement.granted).to.be.equal(false);
      expect(entitlement.grantReason).to.be.null;
    });
  });

  describe('isReadyToPay', () => {
    // #TODO(jpettitt) remove fake entitlements when swj.js
    // isReadyToPay is available
    /**
     * return a fake entitlements object
     * @param {boolean} isReadyToPay
     * @return {Object}
     */
    function fakeEntitlements(isReadyToPay) {
      return {
        isReadyToPay,
        entitlements: {},
        getEntitlementForThis: () => {},
      };
    }

    it('should treat missing isReadyToPay as false', async () => {
      env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
        Promise.resolve({
          json: () => Promise.resolve({entitlements: entitlementResponse}),
        })
      );

      await platform.getEntitlements();
      expect(
        platform.getSupportedScoreFactor(
          SubscriptionsScoreFactor.IS_READY_TO_PAY
        )
      ).to.equal(0);
    });

    it('should handle isReadyToPay true', async () => {
      env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
        Promise.resolve({
          json: () =>
            Promise.resolve({
              isReadyToPay: true,
              entitlements: entitlementResponse,
            }),
        })
      );
      //#TODO(jpettitt) remove stub when swj.js isRadyToPay is available
      env.sandbox
        .stub(platform.runtime_, 'getEntitlements')
        .resolves(fakeEntitlements(true));

      await platform.getEntitlements();
      expect(
        platform.getSupportedScoreFactor(
          SubscriptionsScoreFactor.IS_READY_TO_PAY
        )
      ).to.equal(1);
    });

    it('should handle isReadyToPay false', async () => {
      env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
        Promise.resolve({
          json: () =>
            Promise.resolve({
              isReadyToPay: false,
              entitlements: entitlementResponse,
            }),
        })
      );
      //#TODO(jpettitt) remove stub when swj.js isRadyToPay is available
      env.sandbox
        .stub(platform.runtime_, 'getEntitlements')
        .resolves(fakeEntitlements(false));

      await platform.getEntitlements();
      expect(
        platform.getSupportedScoreFactor(
          SubscriptionsScoreFactor.IS_READY_TO_PAY
        )
      ).to.equal(0);
    });

    it('should call getEncryptedDocumentKey with google.com', async () => {
      env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
        Promise.resolve({
          json: () => Promise.resolve({entitlements: {}}),
        })
      );

      await platform.getEntitlements();
      expect(getEncryptedDocumentKeyStub).to.be.calledWith('google.com');
    });

    it('should not add encryptedDocumentKey parameter to url', async () => {
      const fetchStub = env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
        Promise.resolve({
          json: () => Promise.resolve({entitlements: {}}),
        })
      );

      await platform.getEntitlements();
      expect(fetchStub).to.be.calledWith(
        'https://news.google.com/swg/_/api/v1/publication/example.org/entitlements'
      );
    });

    it('should add encryptedDocumentKey parameter to url', async () => {
      const fetchStub = env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
        Promise.resolve({
          json: () => Promise.resolve({entitlements: {}}),
        })
      );

      getEncryptedDocumentKeyStub.callsFake(() => 'encryptedDocumentKey');

      await platform.getEntitlements();
      expect(fetchStub).to.be.calledWith(
        'https://news.google.com/swg/_/api/v1/publication/example.org/entitlements?crypt=encryptedDocumentKey'
      );
    });
  });
});


text:
package main

import (
	"fmt"
	"math/rand"
	"sort"
	"sync"
	"time"

	"concurrentsort"
)

// QuickSortMinSizeCompute returns the best usable concurrency slice limit for quicksort.
// Warning: extremly long
func QuickSortMinSizeCompute(startAt, increase, stopAt, sliceSize, nbRun, nbWorkers int) int {
	fmt.Println("* Determining the best limit for concurrency on a slice of size", sliceSize, "with", nbWorkers, "workers")
	type benchdata struct {
		avg    time.Duration
		values []time.Duration
	}
	bench := make(map[int]*benchdata)
	// Placeholders
	var start time.Time
	var total time.Duration
	var currentDuration time.Duration
	var best int
	currentLimit := startAt
	// Start benchmarking
	for currentLimit = startAt; currentLimit <= stopAt; currentLimit += increase {
		fmt.Println()
		fmt.Println("Benchmarking with limit value at", currentLimit)
		// Init
		bench[currentLimit] = new(benchdata)
		bench[currentLimit].values = make([]time.Duration, 0, nbRun)
		// Run benchmark
		for run := 0; run < nbRun; run++ {
			// Init the slice
			fmt.Printf(" %d", run+1)
			toSort := make(concurrentsort.IntSlice, sliceSize)
			rand.Seed(time.Now().UnixNano())
			indexesByWorker := sliceSize / nbWorkers
			var fillGroup sync.WaitGroup
			for worker := 0; worker < nbWorkers; worker++ {
				start := indexesByWorker * worker
				end := indexesByWorker * (worker + 1)
				if worker == nbWorkers-1 && end != len(toSort) {
					end = len(toSort)
				}
				fillGroup.Add(1)
				go func(s, e int) {
					defer fillGroup.Done()
					for i := s; i < e; i++ {
						toSort[i] = rand.Int()
					}
				}(start, end)
			}
			fillGroup.Wait()
			fmt.Print("I")
			// Sort
			start = time.Now()
			concurrentsort.QuickSortCustom(toSort, nbWorkers, currentLimit)
			bench[currentLimit].values = append(bench[currentLimit].values, time.Since(start))
			fmt.Print("S")
		}
		fmt.Println()
		// Compute average
		total = 0
		for _, currentDuration = range bench[currentLimit].values {
			total += currentDuration
		}
		bench[currentLimit].avg = total / time.Duration(nbRun)
		fmt.Println("Average run is", bench[currentLimit].avg, "with a limit of", currentLimit)
	}
	// Search best
	best = startAt
	list := make(sort.IntSlice, 0, len(bench))
	for limit, data := range bench {
		if data.avg < bench[best].avg {
			best = limit
		}
		list = append(list, limit)
	}
	list.Sort()
	// Print results
	fmt.Println()
	fmt.Println("Summary :")
	for _, limit := range list {
		fmt.Printf("%d\t%v", limit, bench[limit].avg)
		if limit == best {
			fmt.Printf(" *")
		}
		fmt.Println()
	}
	fmt.Println()
	fmt.Println("* Best limit is", best, "with", bench[best].avg)
	return best
}


text:
using System;
using DotVVM.Framework.ViewModel;

namespace DotvvmWeb.Views.Docs.Controls.businesspack.DateTimePicker.sample5
{
    public class ViewModel : DotvvmViewModelBase
    {
        public DateTime SelectedDate { get; set; } = DateTime.Now;
    }
}


text:
<?php

namespace dektrium\rbac\models;

use yii\base\InvalidConfigException;
use yii\base\InvalidParamException;
use yii\base\Model;
use yii\helpers\Json;
use yii\rbac\Item;
use dektrium\rbac\validators\RbacValidator;

/**
 * @author Dmitry Erofeev <dmeroff@gmail.com>
 */
abstract class AuthItem extends Model
{
    /**
     * @var string
     */
    public $name;

    /**
     * @var string
     */
    public $description;

    /**
     * @var string
     */
    public $rule;

    /**
     * @var string
     */
    public $data;

    /**
     * @var bool
     */
    public $dataCannotBeDecoded = false;

    /**
     * @var string[]
     */
    public $children = [];

    /**
     * @var \yii\rbac\Role|\yii\rbac\Permission
     */
    public $item;

    /**
     * @var \dektrium\rbac\components\DbManager
     */
    protected $manager;

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        $this->manager = \Yii::$app->authManager;
        if ($this->item instanceof Item) {
            $this->name        = $this->item->name;
            $this->description = $this->item->description;
            $this->children    = array_keys($this->manager->getChildren($this->item->name));

            try {
                if (is_object($this->item->data)) {
                    $this->dataCannotBeDecoded = true;
                } else if ($this->item->data !== null) {
                    $this->data = Json::encode($this->item->data);
                }
            } catch (InvalidParamException $e) {
                $this->dataCannotBeDecoded = true;
            }

            if ($this->item->ruleName !== null) {
                $this->rule = get_class($this->manager->getRule($this->item->ruleName));
            }
        }
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'name' => \Yii::t('rbac', 'Name'),
            'description' => \Yii::t('rbac', 'Description'),
            'children' => \Yii::t('rbac', 'Children'),
            'rule' => \Yii::t('rbac', 'Rule'),
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        return [
            'create' => ['name', 'description', 'children', 'rule', 'data'],
            'update' => ['name', 'description', 'children', 'rule', 'data'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['name', 'required'],
            [['name', 'description', 'rule'], 'trim'],
            ['name', function () {
                if ($this->manager->getItem($this->name) !== null) {
                    $this->addError('name', \Yii::t('rbac', 'Auth item with such name already exists'));
                }
            }, 'when' => function () {
                return $this->scenario == 'create' || $this->item->name != $this->name;
            }],
            ['children', RbacValidator::className()],
            ['rule', function () {
                $rule = $this->manager->getRule($this->rule);

                if (!$rule) {
                    $this->addError('rule', \Yii::t('rbac', 'Rule {0} does not exist', $this->rule));
                }
            }],
            ['data', function () {
                try {
                    Json::decode($this->data);
                } catch (InvalidParamException $e) {
                    $this->addError('data', \Yii::t('rbac', 'Data must be type of JSON ({0})', $e->getMessage()));
                }
            }],
        ];
    }

    /**
     * Saves item.
     *
     * @return bool
     */
    public function save()
    {
        if ($this->validate() == false) {
            return false;
        }

        if ($isNewItem = ($this->item === null)) {
            $this->item = $this->createItem($this->name);
        } else {
            $oldName = $this->item->name;
        }

        $this->item->name        = $this->name;
        $this->item->description = $this->description;
        $this->item->data        = $this->data == null ? null : Json::decode($this->data);
        $this->item->ruleName    = empty($this->rule) ? null : $this->rule;

        if ($isNewItem) {
            \Yii::$app->session->setFlash('success', \Yii::t('rbac', 'Item has been created'));
            $this->manager->add($this->item);
        } else {
            \Yii::$app->session->setFlash('success', \Yii::t('rbac', 'Item has been updated'));
            $this->manager->update($oldName, $this->item);
        }

        $this->updateChildren();

        $this->manager->invalidateCache();

        return true;
    }

    /**
     * Updated items children.
     */
    protected function updateChildren()
    {
        $children = $this->manager->getChildren($this->item->name);
        $childrenNames = array_keys($children);

        if (is_array($this->children)) {
            // remove children that
            foreach (array_diff($childrenNames, $this->children) as $item) {
                $this->manager->removeChild($this->item, $children[$item]);
            }
            // add new children
            foreach (array_diff($this->children, $childrenNames) as $item) {
                $this->manager->addChild($this->item, $this->manager->getItem($item));
            }
        } else {
            $this->manager->removeChildren($this->item);
        }
    }

    /**
     * @return array An array of unassigned items.
     */
    abstract public function getUnassignedItems();

    /**
     * @param  string         $name
     * @return \yii\rbac\Item
     */
    abstract protected function createItem($name);
}


text:
package com.google.cloud.dataflow.sdk.runners.dataflow;

import static com.google.cloud.dataflow.sdk.util.Structs.addBoolean;
import static com.google.cloud.dataflow.sdk.util.Structs.addDictionary;
import static com.google.cloud.dataflow.sdk.util.Structs.addLong;

import com.google.api.services.dataflow.model.SourceMetadata;
import com.google.cloud.dataflow.sdk.io.FileBasedSource;
import com.google.cloud.dataflow.sdk.io.Read;
import com.google.cloud.dataflow.sdk.io.Source;
import com.google.cloud.dataflow.sdk.options.ValueProvider;
import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator;
import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TransformTranslator;
import com.google.cloud.dataflow.sdk.runners.DataflowPipelineTranslator.TranslationContext;
import com.google.cloud.dataflow.sdk.transforms.PTransform;
import com.google.cloud.dataflow.sdk.util.PropertyNames;
import com.google.cloud.dataflow.sdk.values.PValue;

import java.util.HashMap;
import java.util.Map;

/**
 * Translator for the {@code Read} {@code PTransform} for the Dataflow back-end.
 */
public class ReadTranslator implements TransformTranslator<Read.Bounded<?>> {
  @Override
  public void translate(Read.Bounded<?> transform, TranslationContext context) {
    translateReadHelper(transform.getSource(), transform, context);
  }

  public static <T> void translateReadHelper(Source<T> source,
      PTransform<?, ? extends PValue> transform,
      DataflowPipelineTranslator.TranslationContext context) {
    try {
      // TODO: Move this validation out of translation once IOChannelUtils is portable
      // and can be reconstructed on the worker.
      if (source instanceof FileBasedSource) {
        ValueProvider<String> filePatternOrSpec =
            ((FileBasedSource<?>) source).getFileOrPatternSpecProvider();
        if (filePatternOrSpec.isAccessible()) {
          context.getPipelineOptions()
              .getPathValidator()
              .validateInputFilePatternSupported(filePatternOrSpec.get());
        }
      }

      context.addStep(transform, "ParallelRead");
      context.addInput(PropertyNames.FORMAT, PropertyNames.CUSTOM_SOURCE_FORMAT);
      context.addInput(
          PropertyNames.SOURCE_STEP_INPUT,
          cloudSourceToDictionary(
              CustomSources.serializeToCloudSource(source, context.getPipelineOptions())));
      context.addValueOnlyOutput(PropertyNames.OUTPUT, context.getOutput(transform));
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  // Represents a cloud Source as a dictionary for encoding inside the {@code SOURCE_STEP_INPUT}
  // property of CloudWorkflowStep.input.
  private static Map<String, Object> cloudSourceToDictionary(
      com.google.api.services.dataflow.model.Source source) {
    // Do not translate encoding - the source's encoding is translated elsewhere
    // to the step's output info.
    Map<String, Object> res = new HashMap<>();
    addDictionary(res, PropertyNames.SOURCE_SPEC, source.getSpec());
    if (source.getMetadata() != null) {
      addDictionary(res, PropertyNames.SOURCE_METADATA,
          cloudSourceMetadataToDictionary(source.getMetadata()));
    }
    if (source.getDoesNotNeedSplitting() != null) {
      addBoolean(
          res, PropertyNames.SOURCE_DOES_NOT_NEED_SPLITTING, source.getDoesNotNeedSplitting());
    }
    return res;
  }

  private static Map<String, Object> cloudSourceMetadataToDictionary(SourceMetadata metadata) {
    Map<String, Object> res = new HashMap<>();
    if (metadata.getProducesSortedKeys() != null) {
      addBoolean(res, PropertyNames.SOURCE_PRODUCES_SORTED_KEYS, metadata.getProducesSortedKeys());
    }
    if (metadata.getEstimatedSizeBytes() != null) {
      addLong(res, PropertyNames.SOURCE_ESTIMATED_SIZE_BYTES, metadata.getEstimatedSizeBytes());
    }
    if (metadata.getInfinite() != null) {
      addBoolean(res, PropertyNames.SOURCE_IS_INFINITE, metadata.getInfinite());
    }
    return res;
  }
}


text:
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.

package org.uma.jmetal.util.experiment.util;

import org.uma.jmetal.solution.Solution;
import org.uma.jmetal.util.JMetalLogger;
import org.uma.jmetal.util.experiment.Experiment;
import org.uma.jmetal.util.parallel.SynchronousParallelTaskExecutor;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.logging.Level;

/**
 * Class for executing independent runs of algorithms
 *
 * @author Antonio J. Nebro <antonio@lcc.uma.es>
 */
public class MultithreadedExperimentExecutor<S extends Solution<?>, Result>
    implements SynchronousParallelTaskExecutor<Object> {
  private Collection<EvaluationTask<S,Result>> taskList;
  private int numberOfThreads;
  private ExecutorService executor;

  /** Constructor */
  public MultithreadedExperimentExecutor(int threads) {
    numberOfThreads = threads;
    if (threads == 0) {
      numberOfThreads = Runtime.getRuntime().availableProcessors();
    } else if (threads < 0) {
      JMetalLogger.logger.severe("MultithreadedExperimentExecutor: the number of threads" +
        " cannot be negative number " + threads);
    } else {
      numberOfThreads = threads;
    }
    JMetalLogger.logger.info("THREADS: " + numberOfThreads);
  }

  @Override
  public void start(Object configuration) {
    executor = Executors.newFixedThreadPool(numberOfThreads);
    JMetalLogger.logger.info("Cores: " + numberOfThreads);
    taskList = null;
  }

  public void addTask(Object[] taskParameters) {
    if (taskList == null) {
      taskList = new ArrayList<EvaluationTask<S,Result>>();
    }

    @SuppressWarnings("unchecked")
    TaggedAlgorithm<Result> algorithm = (TaggedAlgorithm<Result>) taskParameters[0];
    Integer id = (Integer) taskParameters[1];
    Experiment<?,?> experimentData = (Experiment<?,?>) taskParameters[2] ;
    taskList.add(new EvaluationTask<S, Result>(algorithm, id, experimentData));
  }

  public Object parallelExecution() {
    List<Future<Object>> future = null;
    try {
      future = executor.invokeAll(taskList);
    } catch (InterruptedException e1) {
      JMetalLogger.logger.log(Level.SEVERE, "Error", e1);
    }
    List<Integer> resultList = new Vector<Integer>();

    for (Future<Object> result : future) {
      Object returnValue = null;
      try {
        returnValue = result.get();
        resultList.add((Integer) returnValue);
      } catch (InterruptedException e) {
        JMetalLogger.logger.log(Level.SEVERE, "Error", e);
      } catch (ExecutionException e) {
        JMetalLogger.logger.log(Level.SEVERE, "Error", e);
      }
    }

    taskList = null;
    return null;
  }

  public void stop() {
    executor.shutdown();
  }
}


text:
<?php

namespace Sylius\Component\Core\Repository;

use Pagerfanta\Pagerfanta;
use Sylius\Component\Resource\Repository\RepositoryInterface;

/**
 * @author Łukasz Chruściel <lukasz.chrusciel@lakion.com>
 */
interface PaymentRepositoryInterface extends RepositoryInterface
{
    /**
     * @param array|null $criteria
     * @param array|null $sorting
     *
     * @return Pagerfanta
     */
    public function createFilterPaginator(array $criteria = null, array $sorting = null);
}


text:
class MatchDetails{
public:
	MatchDetails(std::string XMLPath);
	PlayerDetails getPlayer(std::string);

	std::string getDetail(std::string s){return details[s];}
	PlayerDetails getPlayer(int i){return pDetails[i];}
private:
	std::map<std::string,std::string> details;
	std::vector<PlayerDetails> pDetails;

	void getDetails(tinyxml2::XMLNode *n);
	void getPlayerDetails(tinyxml2::XMLNode *n);
};


text:
"""
This module contains tests for the L{axiom.store.ItemQuery.paginate} method.
"""

from twisted.trial.unittest import TestCase

from axiom.store import Store
from axiom.item import Item
from axiom.attributes import integer, compoundIndex

from axiom.test.util import QueryCounter

class SingleColumnSortHelper(Item):
    mainColumn = integer(indexed=True)
    other = integer()
    compoundIndex(mainColumn, other)

class MultiColumnSortHelper(Item):
    columnOne = integer()
    columnTwo = integer()
    compoundIndex(columnOne, columnTwo)

class CrossTransactionIteration(TestCase):

    def test_separateTransactions(self):
        """
        Verify that 'paginate' is iterable in separate transactions.
        """
        s = Store()
        b1 = SingleColumnSortHelper(store=s, mainColumn=1)
        b2 = SingleColumnSortHelper(store=s, mainColumn=2)
        b3 = SingleColumnSortHelper(store=s, mainColumn=3)
        itr = s.transact(lambda : iter(s.query(SingleColumnSortHelper).paginate()))
        self.assertIdentical(s.transact(next, itr), b1)
        self.assertEquals(s.transact(lambda : (next(itr), next(itr))),
                          (b2, b3))
        self.assertRaises(StopIteration, lambda : s.transact(next, itr))

    def test_moreItemsNotMoreWork(self):
        """
        Verify that each step of a paginate does not become more work as items
        are added.
        """
        s = Store()
        self._checkEfficiency(s.query(SingleColumnSortHelper))

    def test_moreItemsNotMoreWorkSorted(self):
        """
        Verify that each step of a paginate does not become more work as more
        items are added even if a sort is given.
        """
        s = Store()
        self._checkEfficiency(s.query(SingleColumnSortHelper,
                                      sort=SingleColumnSortHelper.mainColumn.ascending))

    def test_moreItemsNotMoreWorkRestricted(self):
        s = Store()
        self._checkEfficiency(s.query(SingleColumnSortHelper,
                                      SingleColumnSortHelper.other == 6,
                                      sort=SingleColumnSortHelper.mainColumn.ascending))

    def _checkEfficiency(self, qry):
        s = qry.store
        mnum = [0]
        def more():
            mnum[0] += 1
            SingleColumnSortHelper(store=s, mainColumn=mnum[0], other=6)
        for i in range(5):
            more()

        qc = QueryCounter(s)
        # Sanity check: calling paginate() shouldn't do _any_ DB work.
        L = []
        m = qc.measure(
            # Let's also keep the page-size to 1, forcing the implementation to
            # get exactly 1 item each time.  (Otherwise the first N items will
            # take a fixed amount of work, the next 10, and so on, but each
            # subsequent item will take 0, breaking our attempt to measure
            # below)
            lambda : L.append(qry.paginate(pagesize=1)))
        self.assertEqual(m, 0)
        y = L.pop()
        g = iter(y)
        # startup costs a little more, so ignore that
        # s.debug = True
        what = qc.measure(next, g)                # 1
        oneunit = qc.measure(next, g)                   # 2
        otherunit = qc.measure(next, g)
        self.assertEqual(otherunit, oneunit) # 3
        # Now, make some more data

        for i in range(3):
            more()
        # and make sure that doesn't increase the amount of work
        self.assertEqual(qc.measure(next, g), oneunit) # 4
        self.assertEqual(qc.measure(next, g), oneunit) # 5
        self.assertEqual(qc.measure(next, g), oneunit) # 6

        # one more sanity check - we're at the end.
        self.assertEqual(next(g).mainColumn, 7)
        self.assertEqual(next(g).mainColumn, 8)
        self.assertEqual(list(g), [])

    def test_storeIDTiebreaker(self):
        """
        Verify that items whose sort column are identical are all returned and
        deterministically ordered.
        """
        s = Store()
        x = [SingleColumnSortHelper(store=s, mainColumn=1234) for nothing in range(10)]
        first = SingleColumnSortHelper(store=s, mainColumn=1233)
        last = SingleColumnSortHelper(store=s, mainColumn=1235)
        # This is sensitive to page size, so let's test it at lots of places
        # where edge-cases are likely to develop in the implementation.
        for pagesize in list(range(1, 30)) + [1000]:
            # The ordering here in the asserts might look a little weird - that we
            # ascend by storeID in both cases regardless of the order of the sort,
            # but it's intentional.  The storeID is merely to be a tiebreaker to
            # provide a stable sort.  You could be sorting by any number of
            # compound columns, 'ascending' for your particular column might mean
            # something odd or contradictory to 'ascending' for storeID's
            # 'ascending'.  If you want guaranteed stability on storeID, do that.
            self.assertEqual(
                list(s.query(
                        SingleColumnSortHelper,
                        sort=SingleColumnSortHelper.mainColumn.descending
                        ).paginate(pagesize=pagesize)),
                [last] + x + [first])

            self.assertEqual(
                list(s.query(
                        SingleColumnSortHelper,
                        sort=SingleColumnSortHelper.mainColumn.ascending
                        ).paginate(pagesize=pagesize)),
                [first] + x + [last])

    def test_moreThanOneColumnSort(self):
        """
        Verify that paginate works with queries that have complex sort expressions.

        Note: it doesn't.
        """
        s = Store()

        x = MultiColumnSortHelper(store=s, columnOne=1, columnTwo=9)
        y1 = MultiColumnSortHelper(store=s, columnOne=2, columnTwo=1)
        y2 = MultiColumnSortHelper(store=s, columnOne=2, columnTwo=2)
        y3 = MultiColumnSortHelper(store=s, columnOne=2, columnTwo=3)
        y4 = MultiColumnSortHelper(store=s, columnOne=2, columnTwo=4)
        z = MultiColumnSortHelper(store=s, columnOne=3, columnTwo=5)
        self.assertEqual(list(
                s.query(MultiColumnSortHelper,
                        sort=[MultiColumnSortHelper.columnOne.ascending,
                              MultiColumnSortHelper.columnTwo.ascending]
                        ).paginate(pagesize=1)),
                          [x, y1, y2, y3, y4, z])

    test_moreThanOneColumnSort.todo = (
        "There's no use-case for this yet, but it would be a consistent "
        "extension of the API.")


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Tanacetum nubigenum Wall. ex DC.

### Remarks
null


text:
class CreateMenus < ActiveRecord::Migration
  def change
    create_table :spree_menus do |t|
      t.string :name
      t.string :presentation
      t.string :url
      t.integer :position
      t.integer :parent_id
      t.boolean :visible

      t.timestamps
    end
  end
end


text:
@implementation UIHomescreenView
{
    NSUInteger _page;
}

@synthesize dataSource;

- (void)loadIconsForPage:(NSUInteger)page
{
    _page = page;
    for (int i = 0; i < self.rows; i++) {
        for (int j = 0; j < self.columns; j++) {
            IndexPath3D *indexPath = [[IndexPath3D alloc] initWithPage:page withRow:i withColumn:j];
            UIHomescreenIcon *icon = [self.dataSource homescreenView:self iconForPositionAtIndexPath3D:indexPath];
            icon.delegate = self.delegate;
            icon.indexPath = indexPath;
            icon.homescreenView = self;
            CGRect frame = icon.frame;
            frame.origin.x = 10 + j * self.spacingColumns;
            frame.origin.y = 10 + i * self.spacingRows;
            icon.frame = frame;
            [self addSubview:icon];
        }
    }
}

- (void)reloadData
{
    [self loadIconsForPage:_page];
}

@end


text: This event is delivered when user pressing down a key