text:
# File: RigidMotionsParameterSpaceCommon.mpl
#
# Description:
#  This file contains functions used to obtain an arrangement 6 dimensional parameter space of 3D
#  digitized rigid motions.
#  This code has been written for research propose and its aim is to calculate a particular
#  arrangement of quadrics. Therefore, it can or it cannot be useful in study of generic
#  arrangements. The final output are sample points of full dimensional open cells.
#
#  The code was written in relation with the paper: Kacper Pluta, Guillaume Moroz, Yukiko
#  Kenmochi, Pascal Romon, Quadric arrangement in classifying rigid motions of a 3D digital image,
#  2016, https://hal.archives-ouvertes.fr/hal-01334257 referred late on as [Quadrics:2016].
#
# Author:
#  Kacper Pluta - kacper.pluta@esiee.fr
#  Laboratoire d'Informatique Gaspard-Monge - LIGM, A3SI, France
#  Guillaume Moroz - guillaume.moroz@inria.fr
#  INRIA Nancy, France
#
# Date:
#  11/12/2015
#
# License:
#  Simplified BSD License
#
# Copyright (c) 2015, Kacper Pluta, Guillaume Moroz
# All rights reserved.

# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#   * Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL Kacper Pluta and Guillaume Moroz BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#

RigidMotionsParameterSpaceCommon := module()
  option package;
  uses   RigidMotionsMaplePrimesCode;
  local EliminationResultant, RemoveExponants, OneVariableElimination, EliminationGroebner;
  export CayleyTransform, GetNeighborhood, AlgebraicSort, ReduceEvents, AdjustEvents, GenerateEvents,
  SerializeEvents, ReconstructEvents, UnivariatePolynomial;

# Procedure: CayleyTransform
#   Compute Cayley transform for a 3x3 skew-symmetric matrix.
#
# Parameters:
#   vars   - list of variables
#
# Output:
#   3x3 (or 2x2) rotation matrix
#
# Links:
#   https://en.wikipedia.org/wiki/Cayley_transform
CayleyTransform := proc( vars::list )
  local A::Matrix, QLSide::Matrix, QRSide::Matrix, dim:
  dim := nops(vars);
  if dim = 1 then
   A := Matrix( [ [ 0, vars[1] ], [ -vars[1], 0 ] ] ):
  elif dim = 2 then
   A := Matrix( [ [ 0, vars[2]/vars[1] ], [ -vars[2]/vars[1], 0 ] ] );
  elif dim = 3 then
   A := Matrix( [ [ 0, vars[1], vars[2] ], [ -vars[1], 0, vars[3] ],
                                      [ -vars[2], -vars[3], 0 ] ] ):
  else
   error "Unsupported dimension! Check 1, 2 or 3":
  end if:
  dim := upperbound(A)[1];
  QLSide := Matrix( dim, shape = identity ) - A:
  QRSide := LinearAlgebra:-MatrixInverse( Matrix( dim, shape = identity ) + A ):
  return simplify( QLSide . QRSide ):
end proc:

# Procedure: GetNeighborhood
#   Compute a neighborhood
#
# Parameters:
#   nType      - size of neighborhood i.e. N1, N2, N3.
#
# Output:
#   List of vectors
GetNeighborhood := proc( nType::string )
  local n6 := [[1, 0, 0], [0, 1, 0], [0, 0, 1], [-1, 0, 0], [0, -1, 0], [0, 0, -1], [0, 0, 0]]:
  local n18 := [[1, 1, 0], [1, 0, 1], [0, 1, 1], [-1, -1, 0], [-1, 0, -1], [0, -1, -1],
                [-1, 1, 0], [-1, 0, 1], [1, -1, 0], [1, 0, -1], [0, -1, 1], [0, 1, -1]]:
  local n26 := [[1, 1, 1], [-1, 1, 1], [1, -1, 1], [1, 1, -1], [-1, -1, 1], [-1, 1, -1],
                [-1, -1, -1], [1, -1, -1]]:

  if nType = "N1" then
    return n6:
  elif nType = "N2" then
    return( [ op( n6 ), op( n18 ) ] ):
  elif nType = "N3" then
    return( [ op( n6 ), op( n18 ), op(n26) ] ):
  else
    error "Not supported type. Try N1, N2, N3.":
  end if:
end proc:

# Procedure: EliminationGroebner
#   Computes univariate polynomial using Groebner basis and FGb library.
#
# Parameters:
#   S          - a set of quadrics
#   vars       - a list of variables
#
# Comments:
#   To use this procedure you need to install Jean-Charles Faugère's FGb library
#   --http://www-polsys.lip6.fr/~jcf/FGb/FGb/index.html
#
# Output:
#   Univariate polynomial obtained from S.
#
EliminationGroebner := proc(S::list, vars::list)
  option cache;
  local univ := op(FGb:-fgb_gbasis_elim(S, 0, vars[2..], vars[1]));
  if univ = NULL then
    univ := 0;
  fi;
  return univ;
end proc;

# Procedure: EliminationResultant
#   Computes univariate polynomial.
#
# Parameters:
#   S          - a set of polynomials in at least two variables
#   vars       - variables to be eliminated
#
# Output:
#   Univariate polynomial obtained from S in the first variable.
EliminationResultant := proc( S::list, vars::list )
  option cache;
  local p, var, res := S, permm;
  if nops(S) < 2 then
    error "Wrong size of the input set: %1. Expected size is at least 2.", S;
  fi;
  if not andmap(type, S, `polynom`) then
    error "Wrong type of elements. Expected argument is a set of polynomials but received  %1."; S;
  fi;
  if nops(vars) < 1 then
    error "Wrong number of indeterminates. It should be at least 2.";
  fi;
  if nops(vars) = 1 then
    permm := combinat:-permute(res, 2);
    res := [];
    for p in permm do
      res := [op(res), OneVariableElimination(p[1], p[2], vars[1])];
    od;
    return foldl( gcd, op(res) );
  fi;

   for var in vars[2..] do
       permm := combinat:-permute(res, 2);
       res := [];
     for p in permm do
       res := [op(res), OneVariableElimination(p[1], p[2], var)];
     od;
   od;

  return foldl( gcd, op(res) );
end proc:

# Procedure: RemoveExponants
#    Removes exponants in an expression
#
# Parameters:
#    r - expression, the expression to simplify
#
# Output:
#    An arithmetic expression that has the same square free part as r.
RemoveExponants := proc(r)
        local remove_exponant, sqrr, result;
        remove_exponant := e -> if type(e,`^`) then op(1,e) else e end if;
        result := remove_exponant(r);
        if type(r,`*`) then
            result := map(remove_exponant, result);
        end if;
        return result;
end proc;

OneVariableElimination := proc( p, q, v)
    local r;
    if degree(p,v)>0 or degree(q,v)>0 then
        r := resultant(p, q, v);
        r := RemoveExponants(r);
        return r;
    elif nops(indets({p,q}))=1 then
        return gcd(p, q);
    else
        return p;
    end if;
end proc;

# Procedure: UnivariatePolynomial
#   Computes univariate polynomial.
#
# Parameters:
#   S          - a set of quadrics
#   vars       - a list of variables
#
# Comments:
#   If FGb is installed then fgb_gbasis_elim() is used and EliminationResultant, otherwise.
#   Note that, build-in solutions like Groebner:-UnivariatePolynomial are not used because of
#   potential memory explosion or other problems which make them practically useless.
#
# Output:
#   Univariate polynomial obtained from S.
#
UnivariatePolynomial := proc(S::list, vars::list)
  local output;
  if type(FGb, package) then
    return EliminationGroebner([op(S)], vars);
  else
    output := EliminationResultant([op(S)], vars);
    if output = 0 then
      return PolynomialIdeals:-UnivariatePolynomial(PolynomialIdeals:-PolynomialIdeal(S),vars[1]);
    fi;
    return output;
  fi;
end proc;

# Procedure: GenerateEvents
#   Generates events from a univariate polynomial (see EventType)
#
# Parameters:
#    x::polynom     - a univariate polynomial
#    quads::        - a list of quadrics
#
# Output:
#    An Array of events generated from a given univariate polynomial.
GenerateEvents := proc(x::polynom, quads::list)
  uses ArrayTools;
  local events := Array([]), factored, rootsF, sqrFree, rf;
  if nops(indets(x)) = 1 then
    factored := factors(x)[2,..,1];
    for sqrFree in factored do
      rootsF := RootFinding:-Isolate(sqrFree, output='interval');
      for rf in rootsF do
        Append(events, EventType(RealAlgebraicNumber(sqrFree, op(rf)[2][1], op(rf)[2][2]), quads));
      od;
    od;
  fi;
  return events;
end proc;

# Procedure: SerializeEvents
#   Changes (inplace) an Array of events into an Array of strings of unevaluated calls to
#   the constructor of EventType.
#
# Parameters:
#    events::Array     - an Array of events (see EventType)
#
# Output:
#    An Array of strings to unevaluated calls of the constructor of EventType.
SerializeEvents := proc(events::Array)
  return map[inplace](proc(x) sprintf("%a", x) end proc, events);
end proc;

# Procedure: ReconstructEvents
#   Changes (inplace) an Array of strings of unevaluated calls to the constructor of EventType into
#   the proper objects.
#
# Parameters:
#    events::Array     - an Array of events (see SerializeEvents)
#
# Output:
#    An Array of EventType.
ReconstructEvents := proc(events::Array)
  return map[inplace](proc(x) eval(parse(x)) end proc, events);
end proc;

# Procedure: ReduceEvents
#   Returns an array of events such that they are distinct. Each pair of events which are equal are
#   merged in such a way that a list of quadrics of the second on from a pair is merged with the
#   list of the first event.
#
# Parameters:
#    L::Array     - an Array of events
#
# Output:
#    An Array of EventType.
ReduceEvents := proc(L::Array)
  local R, k, j, last, x;
  R := Array([]); k := 0; last := 1;
  for j from 2 to upperbound(L) do
    if Compare(L[j-1], L[j], _rest) <> 0 then
      k := k+1;
      R(k) := EventType(GetRealAlgebraicNumber(L[last]),
              ListTools:-MakeUnique([seq(op(GetQuadrics(x)) ,x=L[last .. j-1])]));
      last := j
    end if;
  end do;
  if last <> j then
    ArrayTools:-Append(R, EventType(GetRealAlgebraicNumber(L[last]),
    ListTools:-MakeUnique([seq(op(GetQuadrics(x)) ,x=L[last .. ()])])))
  fi;
  return R;
end proc;

# Procedure: AdjustEvents
#   Returns an array of events such that the first event will contains all the quadris and the last
#   event will be duplicated with changed interval of the underlaying real algebraic number.
#
# Parameters:
#    L::Array     - an Array of events
#
# Output:
#    An Array of EventType.
AdjustEvents := proc(events::Array, quadNum::integer, variables::list)
  local boundTmp, lastEvent;
  # assign all quadrics to the first even
  events[1] := EventType(GetRealAlgebraicNumber(events[1]), [seq(1..quadNum)]);
  # add the last slice twice but shifted to calculate correctly last quadrics
  boundTmp:= GetInterval(GetRealAlgebraicNumber(events[-1]))[2]+1;
  lastEvent := RealAlgebraicNumber(denom(boundTmp)*variables[1]-numer(boundTmp), boundTmp, boundTmp);
  ArrayTools:-Append(events, EventType(lastEvent, GetQuadrics(events[-1])), inplace=true)
end proc;

# Procedure: AlgebraicSort
#   Sorts [if possible in place] RealAlgebraicNumbers or Events. (see types: RealAlgebraicNumber
#   and EventType).
#
# Parameters:
#   events  - a list or Array of RealAlgebraicNumbers or Events
#
# Output:
#   A increasingly sorted list or Array.
AlgebraicSort :=proc(events)
  # In Maple  <2016 there is a bug which causes: stack limit reached if sorting an empty Array
  if upperbound(events) <> 0 then
     return sort['inplace'](events,
                           proc( l, r )
                             if Compare( l, r ) = -1 then
                               return true:
                             else
                               return false:
                             fi:
                           end proc
                  );
  fi;
  return events;
end proc;

end module;


text:
#     1  public class sync {
#     2      private Object go = new Object();
#     3      private int waiters = 0;
#     4
#     5      public void foo() {
#     6          synchronized (go) {
#     7              waiters++;
#     8          }
#     9      }
#    10  }

# some unrelated functions are removed
type $Ljava/lang/Object; <class  {}>
type $Lsync; <class <$Ljava/lang/Object;> {
  @go <* <$Ljava/lang/Object;>> private,
  @waiters i32 private,
  &Lsync;|foo|__V|(<* <$Lsync;>>) void}>
func &Lsync;|foo|__V| (var %_this <* <$Lsync;>>) void {
  var %Reg1_R33 <* <$Ljava/lang/Object;>>
  var %Reg0_I i32
  var %Reg0_R38 <* void>
  #LINE sync.java:6
  dassign %Reg1_R33 0 (iread ptr <* <$Lsync;>> 1 (dread ptr %_this 0))
  syncenter (dread ptr %Reg1_R33 0)
  #LINE sync.java:7
  dassign %Reg0_I 0 (iread i32 <* <$Lsync;>> 2 (dread ptr %_this 0))
  dassign %Reg0_I 0 (add i32 (
      dread i32 %Reg0_I 0,
      cvt i32 i8 (constval i8 1)))
  iassign <* <$Lsync;>> 2 (dread ptr %_this 0, dread i32 %Reg0_I 0)
  #LINE sync.java:8
  syncexit (dread ptr %Reg1_R33 0)
  #LINE sync.java:9
  return ()
  #LINE sync.java:8
  dassign %Reg0_R38 0 (regread ptr %%thrownval)
  syncexit (dread ptr %Reg1_R33 0)
  throw (dread ptr %Reg0_R38 0)
}
 # EXEC: %irbuild Main.mpl
 # EXEC: %irbuild Main.irb.mpl
 # EXEC: %cmp Main.irb.mpl Main.irb.irb.mpl

ext: mpl

max_stars_repo_name: harmonyos-mirror/OpenArkCompiler-test

max_issues_repo_name: harmonyos-mirror/OpenArkCompiler-test

max_forks_repo_name: harmonyos-mirror/OpenArkCompiler-test


text:
//impulse: /give @p spawn_egg 1 0 {display:{Name:"Laser Spawner"},EntityTag:{id:"minecraft:chicken",CustomName:"MMH_LaserSpawner",Silent:1,NoGravity:1}}
//MMH_loadChunks()
///clone ~1 ~1 ~1 ~2 ~8 ~2 24 1 16

#MMH
repeat process MMH_laserSpawner {
if: /testfor @e[type=Chicken,name=MMH_LaserSpawner]
then {
  MMH_loadChunks()
  /execute @e[type=Chicken,name=MMH_LaserSpawner] ~ ~ ~ scoreboard players operation Rotation MMH_Rotation = @p MMH_Rotation
  /scoreboard players test Rotation MMH_Rotation 0 0
  conditional: /execute @e[type=Chicken,name=MMH_LaserSpawner] ~ ~ ~ clone 24 1 16 25 2 17 ~-3 ~-1 ~-1 masked
  /scoreboard players test Rotation MMH_Rotation 1 1
  conditional: /execute @e[type=Chicken,name=MMH_LaserSpawner] ~ ~ ~ clone 24 3 16 25 4 17 ~ ~-1 ~-3 masked
  /scoreboard players test Rotation MMH_Rotation 2 2
  conditional: /execute @e[type=Chicken,name=MMH_LaserSpawner] ~ ~ ~ clone 24 5 16 25 6 17 ~2 ~-1 ~ masked
  /scoreboard players test Rotation MMH_Rotation 3 3
  conditional: /execute @e[type=Chicken,name=MMH_LaserSpawner] ~ ~ ~ clone 24 7 16 25 8 17 ~-1 ~-1 ~2 masked
  /tp @e[type=Chicken,name=MMH_LaserSpawner] ~ -100 ~
}
}

//impulse: /summon area_effect_cloud ~3 ~1 ~1 {CustomName:"ACV_Laser",Rotation:[-90.0f,0.0f],Duration:2147483647}
//impulse: /summon area_effect_cloud ~-1 ~1 ~3 {CustomName:"ACV_Laser",Rotation:[0.0f,0.0f],Duration:2147483647}
//impulse: /summon area_effect_cloud ~-3 ~1 ~-1 {CustomName:"ACV_Laser",Rotation:[90.0f,0.0f],Duration:2147483647}
//impulse: /summon area_effect_cloud ~1 ~1 ~-3 {CustomName:"ACV_Laser",Rotation:[180.0f,0.0f],Duration:2147483647}


text:
myseries := series(sin(x), x = 0, 10);
poly := convert(myseries, polynom);

plotsetup(gif,plotoutput="plot.gif"):
plot(poly, x = -2*Pi .. 2*Pi, y = -3 .. 3);


text:
# Checks if an expression has domain bounds/shape, and check for either one.
export Has := module ()
    export ModuleApply := proc(e, $)::truefalse;
        Bound(e) or Shape(e);
    end proc;

    export Bound := proc(e, $)::truefalse;
        assigned(Domain:-ExtBound[op(0,e)]) and
        evalb(e :: Domain:-ExtBound[op(0,e)]:-MapleType);
    end proc;

    export Shape := proc(e, $)::truefalse;
        assigned(Domain:-ExtShape[op(0,e)]) and
        evalb(e :: Domain:-ExtShape[op(0,e)]:-MapleType);
    end proc;
end module;

max_stars_repo_name: zaxtax/hakaru

max_issues_repo_name: zaxtax/hakaru

max_forks_repo_name: zaxtax/hakaru


text:
#This module implements `Partition`---Hakaru's replacement for Maple's
#endogenous and unwieldy `piecewise`.

#The outer data structure for a Partition is a function, PARTITION(...), (just like it
#is for piecewise.
Partition:= module()
  option package;

  # Constructor for Partition pieces
  global Piece;

local
  Umap := proc(f,x,$)
    f(op(0,x))( map( p -> Piece(f(condOf(p)),f(valOf(p))), piecesOf(x) )
              , `if`(nops(x)>1,map(f,[op(2..-1,x)]),[])[] )
  end proc,

  isPartitionPieceOf := proc( p, elem_t := anything )
    type(p, 'Piece(PartitionCond, elem_t)');
  end proc,

  isPartitionOf := proc( e, elem_t := anything )
    type(e, 'PARTITION(list(PartitionPiece(elem_t)))' ) or
    type(e, 'PARTITION(list(PartitionPiece(Or(elem_t,PieceRef))),list(elem_t))' );
  end proc,

  ModuleLoad::static:= proc()
    ModuleUnload();
    :-`print/PARTITION`:= proc()
      local SetOfRecords, branch;
      SetOfRecords := piecesOf(PARTITION(args));
      `print/%piecewise`(
        seq([ condOf(eval(branch)), valOf(eval(branch))][], branch= SetOfRecords))
    end proc;

    TypeTools:-AddType(PieceRef, And(specfunc(nonnegint,PieceRef),satisfies(x->nops(x)>0)));
    TypeTools:-AddType(PartitionCond, {relation, boolean, `::`, specfunc({`And`,`Or`,`Not`}), `and`, `or`, `not`});
    TypeTools:-AddType(PartitionPiece, isPartitionPieceOf);
    TypeTools:-AddType(Partition, isPartitionOf);

    # global extensions to maple functionality
    :-`eval/PARTITION` :=
    proc(p, eqs, $)
      Partition:-Simpl(Umap(x->eval(x,eqs), p));
    end proc;

    # :-`depends/PARTITION` :=
    # proc(parts, nms, $)
    # local dp := (x -> depends(x, nms));
    #   # `or`(op ( map(p-> dp(condOf(p)) or dp(valOf(p)), parts) ), dp(x,);
    # end proc;

    :-`diff/PARTITION` := proc()
      local pw, wrt, dpw, r, r0, r1;
      wrt := args[-1];
      pw := PARTITION(args[1..-2]);
      pw  := PartitionToPW(pw);
      dpw := diff(pw, wrt);
      r   := PWToPartition(dpw, 'do_solve');
      r0 := Simpl:-singular_pts(r);

      # probably a better way to do this; we really only want to simplify
      # sums and products of integrals and summations
      r1 := subsindets(r0, algebraic, `simplify`);

      userinfo(10, 'disint_trace',
               printf("  input        : \n\t%a\n\n"
                      "  diff         : \n\t%a\n\n"
                      "  singular pts : \n\t%a\n\n"
                      "  simplified   : \n\t%a\n\n\n"
                      , parts, r, r0, r1 ));

      r1;
    end proc;

    :-`simplify/PARTITION` := Simpl;

    NULL
  end proc,

  ModuleUnload::static:= proc()
    map(proc(x::uneval) try eval(x) catch: NULL; end try end proc,
        ['TypeTools:-RemoveType(Partition)'
        ,'TypeTools:-RemoveType(PartitionPiece)'
        ]);
    NULL
  end proc,

  # abstract out all argument checking for map-like functions
  map_check := proc(p)
  local pos, err;
    if p::indexed then
      pos:= op(p);
      if not [pos]::[posint] then
        err := sprintf("Expected positive integer index; received %a", [pos]);
        return err;
      end if
    else
      pos:= 1
    end if;
    if nargs-1 <= pos then
      err := sprintf("Expected at least %d arguments; received %d", pos+1, nargs-1);
      return err;
    end if;
    if not args[pos+2]::Partition then
      err := sprintf("Expected a Partition; received %a", args[pos+2]);
      return err;
    end if;
    return pos;
  end proc,

  extr_conjs := proc(x,$)
    if x::{specfunc(`And`), `and`} then
      map(extr_conjs, [op(x)])[];
    else
      x
    end if
  end proc;
export
  piecesOf := proc(x, $)
    local ps, rs;
    ps := op(1,x);
    if nops(x)=2 then
      rs := op(2,x);
      ps := map(mapPiece(proc(c0,v0)
                  local c,c1,v,s; c,v := c0,v0; s := (x->x);
                  if v::PieceRef then
                    c1 := is_lhs(type,c,name);
                    if c1<>FAIL then s := x->subs(c1,x) end if;
                    c, s(op(op(1,v),rs))
                  else
                    c, v
                  end if; end proc), ps );
    elif has(x,PieceRef) then
      error "found piece references (%1) but no table of pieces: %2", indets(x,PieceRef), x
    end if;
    ps;
  end proc,

  condOf := proc(x::specfunc(`Piece`),$)
    op(1,x);
  end proc,

  valOf := proc(x::specfunc(`Piece`),$)
    op(2,x);
  end proc,

  mapPiece := proc(f,$) proc(x::PartitionPiece,$) Piece(f(condOf(x), valOf(x))) end proc; end proc,
  unPiece := mapPiece(ident),
  ident := proc() args end proc,
  is_lhs := proc(test,x0)
    local x := x0;
    if test(rhs(x),_rest) then x := op(0,x)(rhs(x),lhs(x)) end if;
    if test(lhs(x),_rest) then return x
    else                       return FAIL
    end if;
  end proc,

  # This is an alternate (to PARTITION) constructor for partition, which has the
  # same call convention as piecewise, except there are no implicit cases. if
  # there is an otherwise case, its condition is the conjunction of negations of
  # the other conditions.
  ModuleApply := proc()::Partition;
    local ps, as, ops_r;
    if nargs=0 then
      error "empty partition";
    end if;
    ps := [args]; ops_r := iquo(nops(ps),2);
    if nops(ps)::odd then
      ps := [op(1..-2,ps), Not(bool_And(seq(op(2*i-1,ps),i=1..ops_r))), op(-1,ps)];
      ops_r := ops_r+1;
    end if;
    ps := [seq(Piece(op(2*i-1,ps),op(2*i,ps)),i=1..ops_r)];
    PARTITION(ps);
  end proc,

  Pieces := proc(cs0,es0)::list(PartitionPiece);
    local es, cs;
    es := `if`(es0::{set,list},x->x,x->{x})(es0);
    cs := `if`(cs0::{set,list,specfunc(`And`),`and`},x->x,x->{x})(cs0);
    [seq(seq(Piece(c,e),c=cs),e=es)];
  end proc,

  #This is just `map` for Partitions.
  #Allow additional args, just like `map`
  Pmap::static:= proc(f)::Partition;
    local pair,pos,res;
    res := map_check(procname, args);
    if res::string then error res else pos := res; end if;
    PARTITION([seq(
      Piece(condOf(pair)
            ,f(args[2..pos], valOf(pair), args[pos+2..])
         ),pair= piecesOf(args[pos+1]))])
  end proc,

  # a more complex mapping combinator which works on all 3 parts
  # not fully general, but made to work with KB
  # also, does not handle extra arguments (on purpose!)
  Amap::static:= proc(
    funcs::[anything, anything, anything], #`appliable` not inclusive enough.
    part::Partition)::Partition;
    local pair,pos,f,g,h,doIt;
    (f,g,h) := op(funcs);
    #sigh, we don't have a decent 'let', need to use a local proc
    doIt := proc(pair)
    local kb0 := h(condOf(pair));
      Piece( f(condOf(pair), kb0),
             g(valOf(pair), kb0));
    end proc;
    PARTITION(map(doIt,piecesOf(part)));
  end proc,

  Foldr := proc( cons, nil, prt :: Partition, $ )
    foldr(proc(p, x) cons(condOf(p), valOf(p), x); end proc,nil,op(piecesOf(prt)));
  end proc,

  Case := proc(ty,f,g) proc(x) if x::ty then f(x) else g(x) end if end proc end proc,
  Foldr_mb := proc(cons,nil,prt) Case(Partition, x->Foldr(cons,nil,x), x->cons(true,x,nil)) end proc,
  PartitionToPW_mb := Case(Partition, PartitionToPW, x->x),
  PWToPartition_mb := Case(specfunc(piecewise), PWToPartition, x->x),

  PartitionToPW := module()
    export ModuleApply; local pw_cond_ctx;
    ModuleApply := proc(x::Partition, $)
      local parts := piecesOf(x);
        if nops(parts) = 1 and is(op([1,1],parts)) then return op([1,2], parts) end if;
        parts := foldl(pw_cond_ctx, [ [], {} ], op(parts) );
        parts := [seq([condOf(p), valOf(p)][], p=op(1,parts))];
        if op(-2, parts) :: identical(true) then
          parts := subsop(-2=NULL, parts);
      end if;
      piecewise(op(parts));
    end proc;

    pw_cond_ctx := proc(ctx_, p, $)
    local ps, ctx, ctxN, cond, ncond;
      ps, ctx := op(ctx_); cond := condOf(p);
      cond := {extr_conjs(cond)};
      cond := remove(x->x in ctx, cond);
      ncond := `if`(nops(cond)=1
                    , KB:-negate_rel(op(1,cond))
                    , `Not`(bool_And(op(cond))) );
      cond := bool_And(op(cond));
      ctx := ctx union { ncond };
      [ [ op(ps), Piece(cond, valOf(p)) ], ctx ]
    end proc;
  end module,

  isShape := kind ->
  module()
    option record;

    export MakeCtx := proc(p0,_rec)
      local p := p0, pw, p1, wps, ws, vs, cs, w, ps;
      if kind='piecewise' then
        p := Partition:-PWToPartition(p);
      end if;
      w, p1 := Partition:-Simpl:-single_nonzero_piece(p);
      if not w :: identical(true) or p1 <> p then
        [ w, p1 ]
      else
        ps := piecesOf(p);
        wps := map(_rec@valOf, ps);
        ws, vs, cs := map2(op, 1, wps), map2(op, 2, wps), map(condOf, ps);
        if nops(vs) > 0 and
          andmap(v->op(1,vs)=v, vs) and
          ormap(a->a<>{}, ws)
        then
          [ `bool_Or`( op( zip(`bool_And`, ws, cs) ) ) , op(1,vs) ];
        else
          [ true, p0 ];
        end if;
      end if;
    end proc;
    export MapleType := `if`(kind=`PARTITION`,'Partition','specfunc(piecewise)');
  end module,

  # convert a piecewise to a partition, which is straightforward except:
  # - if any of the branches are unreachable, they are removed
  # - if the last clause is (implicitly) `otherwise`, that clause is filled in
  #     appropriately
  # note that if the piecewise does not cover the entire domain,
  #   then this Partition will be 'invalid' (in the sense that it also
  #   will not cover the entire domain) - the 'correct' thing to do would
  #   probably be to add a new clause whose value is 'undefined'
  # the logic of this function is already essentially implemented, by KB
  # in fact, kb_piecewise does something extremely similar to this
  PWToPartition := proc(x::specfunc(piecewise))::Partition;
    # each clause evaluated under the context so far, which is the conjunction
    # of the negations of all clauses so far
    local ctx := true, n := nops(x), cls := [], cnd, ncnd, i, q, ctxC, cl;
    # handles all but the `otherwise` case if there is such a case
    for i in seq(q, q = 1 .. iquo(n, 2)) do
      cnd := op(2*i-1,x); # the clause as given
      # if this clause is unreachable, then every subsequent clause will be as well
      if ctx :: identical(false) then return PARTITION( cls );
      else
        ctxC := `And`(cnd, ctx);              # the condition, along with the context (which is implicit in pw)
        ctxC := Simpl:-condition(ctxC, _rest);

        if cnd :: `=` then ncnd := lhs(cnd) <> rhs(cnd);
        else               ncnd := Not(cnd) end if;

        ctx  := `And`(ncnd, ctx);             # the context for the next clause

        if ctx :: identical(false,[]) then    # this clause is actually unreachable
          return(PARTITION(cls));
        else
          cls := [ op(cls), op(Pieces(ctxC,[op(2*i,x)])) ];
        end if;
      end if;
    end do;

    # if there is an otherwise case, handle that.
    if n::odd then
      ctx := Simpl:-condition(ctx, _rest);
      if not ctx :: identical(false,[]) then
        cls := [ op(cls), op(Pieces(ctx,[op(n,x)])) ];
      end if;
    end if;

    if nops(cls) = 0 then
      WARNING("PWToPartition: the piecewise %1 produced an empty partition", x);
      return 0;
    end if;
    PARTITION( cls );
  end proc,

  # applies a function to the arg if arg::Partition,
  # and if arg::piecewise, then converts the piecewise to a partition,
  # applies the function, then converts back to piecewise
  # this mainly acts as a sanity check
  AppPartOrPw := proc(f,x::Or(Partition,specfunc(piecewise)))
    if x::Partition then f(x);
    else                 PartitionToPW(f(PWToPartition(x))) end if;
  end proc,

  #Check whether the conditions of a Partition depend on any of a set of names.
  ConditionsDepend:= proc(P::Partition, V::{name, list(name), set(name)}, $)
    local p;
    for p in piecesOf(P) do if depends(condOf(p), V) then return true end if end do;
    false
  end proc,

  # The cartesian product of two Partitions
  PProd := proc(p0::Partition,p1::Partition,{_add := `+`})::Partition;
  local ps0, ps1, cs, rs, rs0, rs1;
    ps0,ps1 := map(ps -> sort(piecesOf(ps), key=(z->condOf(z))), [p0,p1])[];
    cs := zip(proc(p0,p1)
                if condOf(p0)=condOf(p1) then
                  Piece(condOf(p0),_add(valOf(p0),valOf(p1))) ;
                else [p0,p1];
                end if;
              end proc, ps0,ps1);
    rs, cs := selectremove(c->type(c,list),cs);
    rs0, rs1 := map(k->map(r->op(k,r),rs),[1,2])[];
    rs := map(r0->map(r1-> Piece( bool_And(condOf(r0),condOf(r1)), _add(valOf(r0),valOf(r1)) )
                      ,rs1)[],rs0);
    PARTITION([op(cs),op(rs)]);
  end proc,

  Simpl := module()
    export ModuleApply := proc(p)
      local ps, qs, qs1, mk;
      if p :: Partition then
        reduce_branches(remove_false_pieces(flatten(p)));
      elif assigned(distrib_op_Partition[op(0,p)]) then
        mk := distrib_op_Partition[op(0,p)];
        ps := [op(p)];
        ps := map(x->Simpl(x,_rest), ps);
        ps, qs := selectremove(type, ps, Partition);
        if nops(ps)=0 then return p end if;
        mk(op(qs),foldr(((a,b)->Partition:-PProd(a,b,_add=mk)),op(ps)));
      else
        subsindets(p,{Partition,indices(distrib_op_Partition,nolist)},x->Simpl(x,_rest));
      end if;
    end proc;
    local distrib_op_Partition := table([`+`=`+`,`*`=`*`]);

    export flatten := module()
      export ModuleApply;
      local unpiece, unpart, unpartProd;

      ModuleApply := proc(pr0, { _with := [ 'Partition', unpart ] } )
        local ty, un_ty, pr1, pr2;
        ty, un_ty := op(_with);

        pr1 := subsindets(pr0, ty, un_ty);
        if pr0 <> pr1 then
          ModuleApply(pr1, _with=[ Or('Partiton',`*`), unpartProd ]);
        else
          pr0
        end if;
      end proc;

      # like Piece, but tries to not be a Piece
      unpiece := proc(c, pr, $)
        if pr :: Partition then
          map(q -> applyop(z->bool_And(z,c),1,q), piecesOf(pr))[]
        else Piece(c, pr) end if
      end proc;

      unpart := proc(pr, $)
        if pr :: Partition then
          PARTITION(map(q -> unpiece(condOf(q),valOf(q)), piecesOf(pr)))
        else pr end if
      end proc:

      unpartProd := proc(pr, $)
      local ps, ws;
        if pr :: `*` then
          ps, ws := selectremove(q->type(q,Partition), [op(pr)]);
          if nops(ps) = 1 then
            Pmap(x->`*`(op(ws),x), unpartProd(piecesOf(pr)));
          else pr end if;
        else unpart(pr) end if;
      end proc;
    end module;

    export single_nonzero_piece_cps := proc(k)
      local r,p; r, p := single_nonzero_piece(_rest);
      if r :: identical(true) then
        args[2]
      else
        k(r, p);
      end if;
    end proc;

    export single_nonzero_piece := proc(e, { _testzero := Testzero })
      local zs, nzs;
      if e :: Partition then
        zs, nzs := selectremove(p -> _testzero(valOf(p)), piecesOf(e));
        if nops(nzs) = 1 then
          return condOf(op(1,nzs)) , valOf(op(1,nzs))
        end if;
      end if;
      true, e
    end proc;

    export remove_false_pieces := proc(e::Partition, $)
      PARTITION(remove(p -> type(KB:-assert(condOf(p), KB:-empty), t_not_a_kb), piecesOf(e)));
    end proc;

   local `&on` := proc(f,k,$) proc(a,b,$) f(k(a),k(b)) end proc end proc;
   local condition_complexity := proc(x) nops(indets(x,PartitionCond)) end proc;

   export reduce_branches := proc(e::Partition, { _testequal := ((a,b) -> Testzero(a-b)) })
     local vs, ps1, ps; ps := piecesOf(e); vs := map(valOf,ps);
     userinfo(3, :-reduce_branches, printf("Input: %a\n", ps));

     if nops(ps)=1 then return op([1,2],ps); end if;
     ps1 := [ListTools:-Categorize(_testequal &on valOf, ps)];
     if nops(ps1) >= nops(ps) then return e; end if;
     userinfo(3, :-reduce_branches, printf("Categorize: %a\n", ps1));

     ps1 := map(p->Piece(bool_Or(condition(bool_Or(map(condOf,p)[]), 'do_solve', 'do_kb')[])
                        ,valOf(op(1,p)))
               ,ps1);
     userinfo(3, :-reduce_branches, printf("condition: %a\n", ps1));

     if nops(ps1)=2 then
       ps1 := sort(ps1, key=tree_size);
       ps1 := subsop([2,1]=Not(op([1,1],ps1)),ps1);
     end if;

     return PARTITION(ps1);
    end proc;

    # Removal of singular points from partitions
    export singular_pts := module()
      # we can simplify the pieces which are equalities and whose LHS or
      # RHS is a name.
      local canSimp := c -> condOf(c) :: `=` and (lhs(condOf(c)) :: name or rhs(condOf(c)) :: name);

      # determines if a given variable `t' has the given upper/lower `bnd'.
      local mentions_t_hi := t -> bnd -> cl -> has(cl, t<bnd) or has(cl, bnd>t);
      local mentions_t_lo := t -> bnd -> cl -> has(cl, bnd<t) or has(cl, t>bnd);

      # replace bounds with what we would get if the equality can be
      # integrated into other pieces
      local replace_with := t -> bnd -> x ->
        if   mentions_t_hi(t)(bnd)(x) then t <= bnd
        elif mentions_t_lo(t)(bnd)(x) then t >= bnd
        else x end if;

      local set_xor := ((a,b)->(a union b) intersect (a minus b));

      # this loops over the pieces to replace, keeping a state consisting of
      # the "rest" of the pieces
      local tryReplacePieces := proc(replPieces, otherPieces,cmp,$)
        local rpp := replPieces, otp := otherPieces, nm, val, rp, rpv;
        for rp in rpp do
          rp, rpv := op(rp);
          nm   := `if`(lhs(rp)::name, lhs(rp), rhs(rp));
          val  := `if`(lhs(rp)::name, rhs(rp), lhs(rp));
          otp := tryReplacePiece( nm, val, rpv, otp, cmp )
        end do;
        otp;
      end proc;

      local eval_IntSum := proc(r,ev,$)
        local q,vs,body,BODY,range,mk,mk_e;
        if r::specfunc({Int,Sum}) then
          mk,body,range := op([0..-1],r);
          mk_e := `if`(mk=Int,'int','sum');
          q := mk_e( BODY(body), eval(range,ev) );
          if not(q :: specfunc(mk_e)) and not has(q,BODY)
          then return q end if;
        end if;
        eval(r,ev);
      end proc;

      local do_eval_for_cmp := proc(eval_cmp, ev, x, $)
        local r;
        try
          r := eval_cmp(eval_IntSum(x,ev));
          userinfo(3, 'Partition', printf("evaluating\n\tsubs(%a,%a)\n\tproduced %a\n",x,ev,r)):
        catch "numeric exception: division by zero":
          r := eval_cmp(limit(x, ev));
          userinfo(3, 'Partition', printf("evaluating\n\tlimit(%a,%a)\n\tproduced %a\n",x,ev,r)):
        end try;
        subsindets(r,And(specfunc(NewSLO:-applyintegrand),anyfunc(anything, identical(0))),_->0);
      end proc;

      local tryReplacePiece := proc(vrNm, vrVal, pc0val, pcs, eval_cmp,$)
        local pcs0 := pcs, pcs1, qs0, qs1, qs2, vrEq := vrNm=vrVal, vs2, ret, q, q_i;
        ret := [ Piece(vrEq, pc0val), op(pcs0) ] ;
        # speculatively replace the conditions
        pcs1 := subsindets(pcs0, relation, replace_with(vrNm)(vrVal));
        # convert to sets and take the "set xor", which will contain
        # only those elements which are not common to both sets.
        qs0, qs1 := seq({op(qs)},qs=(pcs0,pcs1));
        qs2 := set_xor(qs1, qs0);
        # if we have updated precisely two pieces (an upper and lower bound)
        if nops(qs2) = 2 then
          # get the values of those pieces, and the value of the
          # piece to be replaced, if that isn't undefined
          vs2 := map(valOf, qs2);
          if not pc0val :: identical('undefined') then
            vs2 := { pc0val, op(vs2) };
          end if;
          # substitute the equality over the piece values
          vs2 := map(x->do_eval_for_cmp(eval_cmp,vrEq,x), vs2);
          # if they are identically equal, return the original
          # "guess"
          if nops(vs2) = 1 then
            # arbitrarily pick the first candidate to be the one to
            # be replaced
            q := op(1,qs2);
            q_i := seq(`if`(op(i,pcs1)=q,[i],[])[],i=1..nops(pcs1));
            ret := subsop(q_i=op(q_i,pcs0), pcs1);
          end if;
        end if;
        ret;
      end proc;

      export ModuleApply := proc(p_,{eval_cmp:='value'},$)
        local p := p_, r := p, uc, oc;
        # if the partition contains case of the form `x = t', where `t' is a
        # constant (or term??) and `x' is a variable, and the value of that
        # case is `undefined', then we may be able to eliminate it (if another
        # case includes that point)
        r := piecesOf(r);
        uc, oc := selectremove(canSimp, r);
        PARTITION(tryReplacePieces(uc, oc, eval_cmp));
      end proc;
    end module; # singular_pts

    export condition := module()
      local is_extra_sol := x -> (x :: `=` and rhs(x)=lhs(x) and lhs(x) :: name);
      local postproc_for_solve := proc(ctx, ctxSlv)
                               ::{identical(false), list({boolean,relation,specfunc(boolean,And),`and`(boolean)})};
        local ctxC := ctxSlv;
        if ctxC = [] then
          ctxC := [] ;
        elif nops(ctxC)> 1 then
          ctxC := map(x -> postproc_for_solve(ctx, [x], _rest)[], ctxC);
        elif nops(ctxC) = 1 then
          ctxC := op(1,ctxC);
          if ctxC :: set then
            if ctxC :: identical('{}') then
              ctxC := NULL;
            else
              ctxC := remove(is_extra_sol, ctxC);
              ctxC := bool_And(op(ctxC));
            end if ;
            ctxC := [ctxC];
          elif ctxC :: specfunc('piecewise') then
            ctxC := PWToPartition(ctxC, _rest);
            ctxC := [ seq( map( o -> condOf(c) and o
                                , postproc_for_solve(ctx, valOf(c), _rest))[]
                           , c=piecesOf(ctxC) )] ;
          else
            ctxC := FAIL;
          end if;
        else
          ctxC := FAIL;
        end if;
        if ctxC = FAIL then
          error "don't know what to do with %1", ctxSlv;
        else
          ctxC;
        end if;
      end proc;

      export ModuleApply := proc(ctx)::list(PartitionCond);
        local ctxC, ctxC1, ctxC_c, ctxC1_c;
        ctxC := ctx;
        if ctx :: identical(true) then
          error "Simpl:-condition: don't know what to do with %1", ctxC;
        elif condition_complexity(ctx)=1 then
          return [ctx];
        end if;
        if 'do_kb' in {_rest} then
          ctxC1 := KB:-assert( ctxC, KB:-empty );
          ctxC1 := KB:-kb_to_constraints(ctxC1);
          ctxC1 := bool_And(op(ctxC1));
          ctxC1_c, ctxC_c := map(condition_complexity, [ctxC1,ctxC])[];
          if ctxC1_c < ctxC_c then
            ctxC := ctxC1;
            if ctxC1_c = 1 then
              return [ctxC];
            end if;
          end if;
        end if;
        ctxC := KB:-chill(ctxC);

        if 'do_solve' in {_rest} and _Env_HakaruSolve<>false then
          ctxC := solve({ctxC}, 'useassumptions'=true);
          if ctxC = NULL and indets(ctx, specfunc(`exp`)) <> {} then
            ctxC := [ctx];
          else
            ctxC := postproc_for_solve(ctx, [ctxC], _rest);
          end if;
          if indets(ctxC, specfunc({`Or`, `or`})) <> {} then
            userinfo(10, 'Simpl:-condition',
                     printf("output: \n"
                            "  %a\n\n"
                            , ctxC ));
          end if;
        else
          ctxC := Domain:-simpl_relation(ctxC, norty='DNF');
          ctxC := eval(ctxC,`And`=bool_And);
          if ctxC :: specfunc(`Or`) then
            ctxC := [op(ctxC)]
          else
            ctxC := [ctxC];
          end if;
        end if;
        if 'no_split_disj' in {_rest} then
          ctxC := [ bool_Or(op(ctxC)) ];
        end if;
        KB:-warm(ctxC);
      end proc;
    end module; #Simpl:-condition
  end module, #Simpl

  SamePartition := proc(eqCond, eqPart, p0 :: Partition, p1 :: Partition, $)
    local ps0, ps1, pc0, the;
    ps0, ps1 := map(piecesOf,[p0,p1])[];
    if nops(ps0) <> nops(ps1) then return false end if;
    for pc0 in ps0 do
      the, ps1 :=
        selectremove(pc1 ->
          eqCond( condOf(pc1), condOf(pc0) ) and
          eqPart( valOf(pc1) , valOf(pc0)  )     ,ps1);
      if nops(the) <> 1 then
        return false;
      end if;
    end do;
    true;
  end proc
;
  uses Hakaru;
end module:


text:
__BEGIN__
def delim(i, c, between = ",")
	between if c.length != i+1
end
__END__
%self.each do |msg|
struct [%msg.name%] {
	%# constructor
	%unless msg.member.empty?
	[%msg.name%](
		const [%m.type%]& [%m.name%]_[%delim(i, msg.member)%]  %|m,i| msg.member.each_with_index
		) :
		[%m.name%]([%m.name%]_)[%delim(i, msg.member)%]  %|m,i| msg.member.each_with_index
	{ }
	%end

	%# members
	[%m.type%] [%m.name%];  %|m| msg.member.each

	static const int id = [%msg.id%];  %>if msg.id
};

%end
%# vim: syntax=mplex

max_stars_repo_name: frsyuki/mplex

max_issues_repo_name: frsyuki/mplex

max_forks_repo_name: frsyuki/mplex


text:
(*
 Copyright (C) 2017 M.A.L. Marques
 Copyright (C) 2018 Susi Lehtola

 This Source Code Form is subject to the terms of the Mozilla Public
 License, v. 2.0. If a copy of the MPL was not distributed with this
 file, You can obtain one at http://mozilla.org/MPL/2.0/.
*)

(* type: gga_exc *)
(* prefix:
  gga_x_lsrpbe_params *params;

  assert(p->params != NULL);
  params = (gga_x_lsrpbe_params * )(p->params);
*)

lsrpbe_f0 := s -> 1 + params_a_kappa * (
  1 - exp(-params_a_mu*s^2/params_a_kappa)
) - (params_a_kappa+1)*(1 - exp(-params_a_alpha*s^2)):
lsrpbe_f  := x -> lsrpbe_f0(X2S*x):

f := (rs, z, xt, xs0, xs1) -> gga_exchange(lsrpbe_f, rs, z, xs0, xs1):


text:
#If X ~ Exp(λ) then kX ~ Exp(λ/k).

#Equivalent: If X ~ Exp(α) then kX ~ Exp(kα)

#Proof:
PDF_exponential := (alpha, x) -> exp(-x/alpha)/alpha;

PDF_kX := (alpha, x, k) -> PDF_exponential(alpha, x/k)/k;
simplify(PDF_kX(alpha, x, k));

PDF_exp_scaled := (alpha, x, k) -> PDF_exponential(k*alpha, x);
simplify(PDF_exp_scaled(alpha, x, k));

evalb(PDF_kX(alpha, x, k) = PDF_exp_scaled(alpha, x, k));

max_stars_repo_name: vmchale/hakaru

max_issues_repo_name: vmchale/hakaru

max_forks_repo_name: vmchale/hakaru


text:
(*
 Copyright (C) 2017 M.A.L. Marques

 This Source Code Form is subject to the terms of the Mozilla Public
 License, v. 2.0. If a copy of the MPL was not distributed with this
 file, You can obtain one at http://mozilla.org/MPL/2.0/.
*)

(* type: gga_exc *)

pbea_mu    := 0.00361218645365094697:
pbea_alpha := 0.52:

pbea_f  := x -> 1 + KAPPA_PBE*(1 - (1 + pbea_mu*x^2/(pbea_alpha*KAPPA_PBE))^(-pbea_alpha)):

f := (rs, z, xt, xs0, xs1) -> gga_exchange(pbea_f, rs, z, xs0, xs1):


text:
func $foo (var %i i32) i32 {
  dowhile {
    dassign %i (
      mul i32 (dread i32 %i, dread i32 %i))
    dassign %i (
      add i32 (dread i32 %i, constval i32 1) )} (
        lt i32 i32 ( dread i32 %i, constval i32 10) )
  return ( constval i32 0 )
}
 # EXEC: %irbuild Main.mpl
 # EXEC: %irbuild Main.irb.mpl
 # EXEC: %cmp Main.irb.mpl Main.irb.irb.mpl


text:
# Extract a domain from an expression
export Extract := module ()
  uses Domain_Type, Utilities;
  export ModuleApply := proc(e, kb, $) :: [ HDomain, anything, list(`=`) ];
    local b, eb, s, es, kb1, rn, ws;
    b, eb, ws := op(Bound(e));
    kb1, rn := Domain:-Bound:-toKB(b)[];
    b, eb, ws := subs(rn,[b,eb,ws])[];
    s, es := op(Shape(eb, kb1));
    [ DOMAIN(b, s), es, ws ];
  end proc;

  # Extract a domain bound from an expression
  # This pops off the integration constructors recursively, keeping
  # track of the bounds in a KB (which literally become the DBound).
  export Bound := module ()
    export ModuleApply := proc(e, $) :: [ DomBound, anything, list(`=`) ];
      local arg, vars, kb, ws, w0;
      arg, vars, ws := do_extract(e)[];
      vars := Domain:-Bound:-withVarsIxs(DBound(vars));
      ws := map(`*`@op,ws);
      w0 := op(1,ws); ws := subsop(1=NULL,ws);
      if not(nops(ws)=nops(op(1,vars))) then
        error "number of outer weights doesn't match number of vars: %1, %2",
              op(1,vars), ws;
      end if;
      [ vars , w0*arg, zip(`=`,map2(op,1,op(1,vars)),ws) ];
    end proc;

    local do_extract_arg := proc(kind, arg_)
      local x0, x, vars, ws,
            arg := op(1,arg_),
            rest := op(2..-1,arg_),
            rng;
      x0  := ExtBound[kind]:-ExtractVar(rest);   # variable name
      rng := ExtBound[kind]:-ExtractRange(rest); # variable range
      x   := DInto(x0, rng, kind);               # the variable spec
      arg, vars, ws := do_extract(arg)[];
      [ arg, [ op(vars), x ], [ op(ws), [] ]];
    end proc;

    local do_extract := proc(arg, $)
      local sub, prod, svars, vs, ssum, ws, wc;
      if arg :: `*` then
        sub := map(do_extract, [op(arg)]);
        prod, svars := selectremove(x->op(2,x)=[],sub);
        if nops(svars) = 1 then
          [   op([1,1],svars)
            , op([1,2],svars)
            , applyop(w-> [op(w),op(map2(op,1,prod))], -1,
                      op([1,3],svars)) ];
        else
          [ arg, [], [[]] ];
        end if;
      elif arg :: `+` then
        sub := map(do_extract, [op(arg)]);
        svars := map2(op,2,sub);
        if the(map(nops,svars)) then
          vs[0] := map(sv->map2(op,1,sv), svars);      # a list of lists of variables
          vs[1] := map2(op,1, op(1,svars));            # a list of 'fresh' variables
          vs[2] := map(v->zip(`=`,v,vs[1]), vs[0]);    # variable renamings
          svars := zip(subs,vs[2], svars);             # dombounds renamed
          if the(svars) then
            ssum := zip(subs,vs[2],map2(op,1,sub));    # sub-arg summands
            ws   := zip(subs,vs[2],map2(op,3,sub));    # sub-arg weights
            # factor out common weight
            ws   := map(x->{op(map(op,x))}, ws);
            wc   := `intersect`(op(ws));
            ws   := [op(map(w -> w minus wc, ws))];
            ws   := map(`[]`@op, ws);
            wc   := [op(wc)];
            # non-common weights are pushed down
            ssum := zip(((s,w)->`*`(s,op(w))), ssum, ws);
            [ `+`(op(ssum)),
              op(1, svars),
              [ wc$(nops(op(1,svars))), [] ] ];
          else
            [ arg, [], [[]] ]
          end if;
        else
          [ arg, [], [[]] ]
        end if;
      elif Domain:-Has:-Bound(arg) then
        do_extract_arg(op(0,arg), [op(arg)]);
      else
        [ arg, [], [[]] ]
      end if;
    end proc;
  end module;

  # Extract a domain shape from an expression
  # This extracts the domain shape from individual multiplicands of
  # expressions, and multiplies the subexpressions back together.
  # essentially this assumes a distributive law (of domain shapes over
  # products)
  export Shape := module ()
    export ModuleApply := proc(e, kb:=KB:-empty) :: [ anything, anything ];
      local ixs, w, e1;
      ixs := [indices(ExtShape, 'nolist')];
      w, e1 := do_gets(ixs, true, e, kb) [];
      if not ('no_simpl' in {_rest}) then
        w := simpl_shape(w);
      end if;
      [ w, e1 ];
    end proc;

    local do_get := proc(f, f_ty, e, kb, $)
      local sub, inds, rest;
      if e::`*` then
        sub := map(x->do_get(f, f_ty,x,kb), [op(e)]);
        [ `And`(op(map2(op,1,sub))), `*`(op(map2(op,2,sub))) ]
      elif e::`^` then
        inds, rest := do_get(f, f_ty, op(1,e), kb) [] ;
        [ inds, subsop(1=rest, e) ]
      elif e:: f_ty then
        f(e,((z,kb1)->ModuleApply(z,kb1,'no_simpl')),kb)
      else
        [ true, e ]
      end if
    end proc;

    # apply a list of extractors, in order, until all fail to produce
    # any output .
    local do_gets := proc(todo::list, w, e, kb, $)
      local t0, ts, w1, e1;
      if nops(todo) = 0 then
        [ w, e ]
      else
        t0 := op(1, todo);
        ts := op(subsop(1=NULL, todo));
        w1, e1 := do_get(ExtShape[t0]:-MakeCtx
                         ,ExtShape[t0]:-MapleType
                         ,e,kb) [] ;
        ts := `if`(is(w1), [ts], [ts, t0]);
        do_gets( ts, bool_And(w1, w), e1, kb );
      end if;
    end proc;

    # todo: simplify the shape
    local simpl_shape := proc(e0,$)
      local e := simpl_relation(e0);
      e := subsindets(e, specfunc(`Or`) , x->DSum(op(x)));
      e := subsindets(e, specfunc(`And`), x->DConstrain(op(x)));
      e;
    end proc;
  end module;
end module;


text:
print_comp:=proc(A,coord::list,dim::integer,{diag:=false,tp:=dn})

  local i, j;
  local s;
  local cn,cm;

  if dim = 0 then
  s:= "";
  s:= cat(s,convert(A,string));
  s:= cat(s,"_expr");
  s:= cat(s,sprintf(":="));
  s:= cat(s,convert(grcomponent(A),string));
  s:= cat(s,sprintf(";\n"));
  return s;
  end if;

  if dim = 1 then
  s:="";
   for i from 1 to nops(coord)-1 do
    cn:=coord[i];
    s:= cat(s,convert(A||cn,string));
    s:= cat(s,"_expr");
    s:= cat(s,sprintf(":="));
    s:=cat(s,convert(grcomponent(A(tp),[coord[i]]),string));
    s:= cat(s,sprintf(";\n"));
   end do;
    return s;
  end if;

  if dim = 2 then
  s:="";
  if not(diag) then
   for i from 1 to nops(coord)-1 do
   for j from 1 to nops(coord)-1 do
    cn:=coord[i];
    cm := coord[j];
    s:=cat(s,convert(A||cn||cm,string));
    s:= cat(s,"_expr");
    s:=cat(s,sprintf(":="));
    s:=cat(s,convert(grcomponent(A(tp,tp),[coord[i],coord[j]]),string));
    s:=cat(s,sprintf(";\n"));
   end do;
   end do;

  else
   for i from 1 to nops(coord)-1 do
    cn:=coord[i];
    s:=cat(s,convert(A||cn||cn,string));
    s:= cat(s,"_expr");
    s:=cat(s,sprintf(":="));
    s:=cat(s,convert(grcomponent(A(tp,tp),[coord[i],coord[i]]),string));
    s:=cat(s,sprintf(";\n"));
   end do;
   end if;

   return s;
  end if;

end proc;


text: printf("Hello world!\n");

max_stars_repo_name: JStearsman/hello-worlds

max_issues_repo_name: JStearsman/hello-worlds

max_forks_repo_name: JStearsman/hello-worlds


text:
[0][6]{c:$0000ff}Subtitles downloaded by MiniSubDownloader:|{c:$ff7070}{y:u}http://minisubdownloader.org
[6][21]{c:$0000ff}{s:22}Subtitles downloaded by MiniSubDownloader:|{c:$ff7070}{s:26}{y:u}http://minisubdownloader.org||Cersei:|The Tyrells are a problem.
[21][48]The Tyrells helped us|defeat Stannis Baratheon.
[48][62]You must see Highgarden.
[63][87]I don't think the queen would|let me leave King's Landing.
[87][106]Once I marry Joffrey,|I'll be queen.
[106][143]And if you were|to marry Loras...
[143][169]You must give yourself|to the Lord of Light.
[170][195]- I have a wife.|- She's shut away in a tower.
[195][227]And she's given you no sons,|only stillborns.
[227][265]I lost one son to the Kingslayer,|strangled with a chain.
[266][281]I grieve for|your sons, my lord.
[282][304]I don't want your grief.|I want my vengeance.
[341][372]Do that again and I'll|take your other hand.
[372][395]- What value was the mill?|- I seized an opportunity.
[395][427]We took hostages-- Willem|Lannister, Martyn Lannister.
[427][453]Willem and Martyn Lannister|are 14 years old.
[453][473]I'm not your enemy.
[474][507]- This woman is evil!|- Take him to the dungeon and lock him in a cell.
[508][521]You want to assassinate a girl?
[521][551]- Based on whose information?|- Varys: Ser Jorah Mormont.
[551][574]He is serving as advisor|to the Targaryens.
[574][597]You bring us the whispers|of a traitor.
[598][620]Beric Dondarrion?|If you mean to murder me,
[621][638]then bloody well|get on with it.
[639][662]You'll die soon enough,|but it won't be murder.
[663][688]I sentence you|to trial by combat.
[705][730]- ( dragon screeching )|- Is it done, then?
[730][743]_
[744][756]_
[757][770]_
[777][791]_
[792][803]_
[805][825]_
[827][838]_
[839][856]Dracarys.
[856][873]( screaming )
[950][982]( theme music playing )
[2022][2048]( fire crackling )
[2084][2135]Lord, cast your light upon us.
[2139][2161]Men:|Lord of Light, defend us.
[2191][2209]Show us the truth.
[2210][2233]Strike this man down|if he is guilty.
[2234][2258]Give strength to his sword|if he is true.
[2259][2300]Lord of Light, give us wisdom.
[2348][2373]For the night is dark
[2374][2388]and full of terrors.
[2389][2419]Men: For the night is|dark and full of terrors.
[2731][2752]( shouts )
[3152][3171]( screams )
[3236][3255]Get back.
[3526][3553]( men chanting )|Guilty. Guilty. Guilty.
[3553][3580]Guilty. Guilty.|Guilty.
[3581][3608]Guilty.|Guilty. Guilty.
[3608][3637]Guilty. Guilty.|Guilty.
[3637][3652]Kill him!
[3652][3681]( chanting continues )
[3700][3718]( shouts )
[3740][3761]( chanting stops )
[3839][3859]Lord, cast your light|upon this man, your servant.
[3859][3877]Bring him back|from death and darkness.
[3878][3890]His flame has been|extinguished.
[3891][3908]- Restore it.|- ( shouting )
[3908][3924]Thoros: For the night is|dark and full of terrors.
[3924][3946]- Lord, cast...|- Arya, don't!
[3947][3971]Bring him back|from death and darkness...
[3971][3989]No!
[3989][4020]Let go of me!|Let me go!
[4020][4051]Looks like their god likes me|more than your butcher's boy.
[4051][4067]Burn in hell!
[4068][4087]Beric:|He will.
[4123][4153]But not today.
[4385][4420]Orell says there are crows|patrolling on the Wall.
[4421][4446]Tell me what you know.
[4447][4464]There are four|to a patrol--
[4464][4483]two builders to check|for structural damage,
[4483][4498]two rangers to watch|for enemies.
[4498][4519]How often do these|patrols go out?
[4532][4548]It varies.
[4548][4575]If I knew where on the Wall we|were heading, I could tell you.
[4575][4600]You'd like to know that.
[4618][4645]There are 19 castles|guarding the Wall.
[4659][4683]How many are manned?
[4683][4707]Three.
[4707][4734]You sure of that?
[4751][4767]Which three?
[4794][4808]Castle Black.
[4809][4827]Aye, Castle Black.
[4827][4848]Everyone knows Castle Black.
[4849][4869]Which others?
[4921][4945]Eastwatch-by-the-Sea
[4945][4974]and the Shadow Tower.
[4995][5016]How many men remain|in Castle Black?
[5017][5034]- 1,000.|- Liar.
[5055][5076]What happens to your eagle|after I kill you?
[5076][5102]Does he drift away like a|kite with his strings cut
[5102][5125]or does he just flop|dead to the ground?
[5125][5140]He's no crow.
[5141][5164]Just 'cause you want him inside|you don't make him one of us.
[5165][5190]I'm not afraid of you.
[5252][5271]I like you, boy.
[5272][5301]But if you lie to me,
[5301][5333]I'll pull your guts out|through your throat.
[5357][5379]1,000 men.
[5429][5458]We'll find out soon enough.
[5527][5543]I don't need you to protect me.
[5544][5558]Of course you do.
[5558][5586]Who stopped Rattleshirt when he|was about to cut your throat?
[5587][5615]Who vouched for you with Mance?
[5615][5635]It seems you owe me a debt.
[5649][5674]- Give it back.|- Well, I stole it.
[5674][5711]It's mine. If you want|it, come steal it back.
[5732][5750]Ygritte!
[5760][5781]Ygritte!
[5817][5843]Ygritte!|Seven hells.
[5844][5865]Ygritte!
[5900][5924]Is Orell right?
[5924][5944]Are you still a crow?
[5958][5992]It's time you proved yourself.
[5992][6009]Ygritte.
[6010][6036]You swore some vows.
[6036][6055]I want you to break 'em.
[6084][6108]I want you to see me.
[6133][6156]All of me.
[6293][6311]We shouldn't.
[6335][6353]We should.
[6515][6541]( breathing heavily )
[6551][6573]Why are you still dressed?
[6573][6598]You know nothing,|Jon Sno--
[6610][6633]( moaning )
[6750][6769]That thing you did
[6769][6789]with your mouth--
[6804][6833]is that what lords do to|their ladies in the South?
[6833][6854]I don't know.
[6855][6872]I just wanted to kiss|you there is all.
[6873][6887]Hmm.
[6888][6905]You seemed to like it.
[6905][6929]Aye, I liked it some.
[6929][6945]Who taught you that?
[6945][6974]There's been no one else.|Only you.
[6974][6993]A maid.
[6994][7012]You were a maid.
[7012][7041]I was a man|of the Night's Watch.
[7059][7081]How about you?|Were you a maid?
[7081][7095]What do you think?
[7096][7124]- Who was he?|- Just a boy.
[7125][7151]He came trading|with his brothers.
[7151][7183]He had red hair like me.|Kissed by fire.
[7183][7202]But...
[7203][7227]he was weak.
[7228][7245]Not like you.
[7245][7264]That was the first one.
[7265][7284]Then there was this Thenn boy.
[7285][7319]Spoke no Common, but gods,|he was built like a mammoth.
[7319][7351]Yeah, thanks.|I think I've heard enough.
[7379][7398]We'd best get back.
[7398][7422]Tormund--
[7445][7465]I'm not done with you yet.
[7535][7559]How long's it been|since you had a bath?
[7716][7736]Let's not go back.
[7749][7775]Let's stay here a while longer.
[7799][7832]I don't ever want to leave|this cave, Jon Snow.
[7853][7873]Not ever.
[7977][7994]Hound:|I want my gold.
[7994][8008]Thoros: It says it clearly|right there on that note
[8009][8024]you'll be repaid in full|when the war is over.
[8025][8048]Piss on that!|You're nothing but thieves.
[8049][8071]We're outlaws.|Outlaws steal.
[8071][8086]You're lucky|we didn't kill you.
[8086][8096]Come try it, archer.
[8096][8112]I'll shove those arrows|up your ass.
[8113][8138]You can't let him go. He's a murderer.|He's guilty.
[8138][8160]- Not in the eyes of god.|- You can't!
[8160][8192]Enough! The judgment|isn't ours to make.
[8217][8250]Go in peace, Sandor Clegane.
[8250][8268]The Lord of Light|isn't done with you yet.
[8318][8347]Man:|Riders coming through!
[8348][8379]( horses neighing )
[8454][8469]The Kingslayer.
[8469][8480]Down!
[8480][8502]On your knees.
[8502][8533]Lord Bolton, I give you|the Kingslayer.
[8533][8550]( groans )
[8550][8569]Pick him up, Locke.
[8635][8650]You've lost a hand.
[8650][8678]No, my lord, he has it here.
[8713][8733]- Take this away.|- Send it to his father?
[8733][8754]You'll hold your tongue|unless you want to lose it.
[8765][8791]Cut her free.|Apologies, my lady.
[8792][8812]You're under my protection now.
[8812][8839]Thank you, my lord.
[8871][8892]Find suitable rooms|for our guests.
[8892][8919]We'll speak later.
[8936][8951]Lord Bolton.
[8989][9009]Is there word from the capital?
[9022][9038]You haven't heard?
[9053][9079]Stannis Baratheon laid siege|to King's Landing.
[9080][9104]Sailed into Blackwater Bay.
[9104][9137]Stormed the gates|with thousands of men.
[9150][9167]And your sister...
[9221][9242]How can I put this?
[9264][9281]Your sister...
[9295][9316]is alive and well.
[9317][9345]Your father's forces prevailed.
[9362][9381]Ser Jaime isn't well.
[9381][9406]Take him to Qyburn.
[9532][9555]( winces )
[9556][9577]( groans )
[9595][9624]- Will I die?|- No.
[9624][9638]The corruption has spread.
[9638][9658]I fear it must be cut away.
[9659][9689]The safest course would be|to take the whole arm off.
[9690][9714]Then you'll die.
[9730][9754]You're no maester.
[9755][9782]Where's your chain?
[9782][9803]The Citadel stripped me of it.
[9803][9836]They found some|of my experiments
[9836][9856]too bold.
[9856][9892]I can leave your upper arm,|make the cut at your elbow.
[9893][9930]I don't need my right hand|to kill you.
[9941][9965]I can take away|the rotting flesh
[9965][9992]and try and burn out|the corruption
[9992][10015]- with boiling wine.|- Mmm.
[10015][10037]With any luck,|that will suffice.
[10038][10063]You'll need milk of the poppy.
[10076][10096]- No milk of the poppy.|- There will be pain.
[10096][10128]- I'll scream.|- Quite a bit of pain.
[10128][10149]I'll scream loudly.
[10235][10264]( groans )
[10264][10287]( scissors snipping )
[10300][10313]( groans )
[10313][10335]( breathing heavily )
[10430][10455]( screams )
[10496][10513]Lord Baelish.
[10513][10529]Your Grace.
[10530][10549]I wonder if I might|ask you for a favor.
[10550][10564]Of course, Your Grace.
[10564][10578]I have reason to believe|that House Tyrell
[10578][10599]do not hold the crown's|best interests at heart.
[10599][10644]I see. And have you shared these|suspicions with Lord Tywin?
[10644][10673]My father's a practical man.|He appreciates facts.
[10674][10701]Myself, I often|find them a hindrance.
[10701][10732]And he appreciates those who aid|his family, as you well know.
[10732][10748]He's almost as generous|to those who help us
[10748][10780]as he is unpleasant|towards those who don't.
[10780][10805]You have a good working|relationship with the Tyrells.
[10805][10834]I thought you might look into it|before you leave the capital.
[10835][10856]- I shall do my best.|- Thank you.
[10857][10891]And your best will prove better than|when I asked you to locate Arya Stark?
[10892][10909]I assure you that it will.
[10962][10982]( liquid pouring )
[10982][11005]Gods, boy, that's enough.|We're not in a tavern.
[11006][11020]- Pardon, my lady.|- No need to speak.
[11020][11042]Are there any figs?|Fetch some.
[11043][11064]I always take figs|midafternoon.
[11064][11079]They help move the bowels.
[11079][11100]To what do I owe this summons?
[11100][11120]Thank you for seeing me,|my lady.
[11121][11143]I had hoped we might discuss|a few financial matters.
[11143][11181]I climbed all those steps to|discuss financial matters?
[11181][11194]It's the royal wedding.
[11194][11208]I'm told you had a hand|in planning it.
[11209][11220]Naturally.
[11221][11245]It's shaping up to be|a very involved affair.
[11246][11267]The word extravagant|has been used.
[11267][11284]What good|is the word extravagant
[11284][11308]if it can't be used|to describe a royal wedding?
[11308][11329]- I understand that.|- Good.
[11329][11354]But, as Master of Coin,|it falls upon me
[11354][11371]to calculate the cost|for the crown.
[11371][11396]As of now, it's a huge expense.
[11397][11408]And?
[11408][11445]And we're at war, Lady Olenna.
[11445][11469]Oh, I'd nearly forgotten.
[11469][11483]Yes, and maintaining|supply lines--
[11483][11501]I can't think|how it slipped my mind.
[11501][11527]What is it, 12,000 infantrymen
[11527][11545]the Tyrell family has supplied?
[11546][11568]1,800 mounted lances.
[11569][11588]2,000 in support.
[11589][11620]Provisions so this city|might survive the winter.
[11620][11637]A million bushels of wheat.
[11637][11673]Half a million bushels each|of barley, oats, and rye.
[11673][11691]20,000 head of cattle.
[11691][11707]50,000 sheep.
[11707][11732]You don't have to lecture me|about wartime expenses.
[11732][11752]I'm quite familiar with them.
[11753][11769]And we are so grateful|for your contributions
[11770][11795]which are necessary for the|preservation of the realm.
[11796][11814]As is a royal wedding.
[11814][11840]The people are hungry|for more than just food.
[11840][11855]They crave distractions.
[11855][11888]And if we don't provide them,|they'll create their own.
[11888][11914]And their distractions|are likely to end
[11915][11937]with us being torn to pieces.
[11938][11961]A royal wedding is much safer.
[11961][11992]- Wouldn't you say?|- I would.
[11992][12014]And traditionally paid for
[12014][12035]- by the royal family.|- ( door opens )
[12048][12072]I was told you were|drunk, impertinent,
[12072][12092]and thoroughly debauched.
[12092][12108]You can imagine|my disappointment
[12108][12138]at finding nothing but a|browbeaten bookkeeper.
[12157][12183]Where did you go|for them, Volantis?
[12194][12212]- My lady--|- Oh, very well.
[12212][12232]I won't have it said|that House Tyrell
[12233][12250]refuses to play its part.
[12250][12265]We'll pay for half the expenses
[12266][12292]and the celebrations|will go on as planned.
[12292][12310]- Is that sufficient?|- Quite sufficient. Thank you.
[12311][12334]Very good, then. That's settled.|Good day.
[12365][12386]Give me that.
[12434][12452]Arya:|What are you doing?
[12463][12483]Just mending|Lord Beric's armor.
[12484][12506]Why?
[12506][12530]I'm going to stay on|and smith for the Brotherhood.
[12530][12549]Have you lost your mind?
[12549][12584]When the Lannisters find this place,|you think they'll spare the smiths?
[12585][12601]They'll cave your head in|with your own helmet.
[12601][12629]The Lannisters wanted to kill me long|before I joined the Brotherhood.
[12629][12648]You don't have to do this.
[12649][12667]I want to.
[12667][12682]They need good men.
[12682][12715]Robb needs good men, too.|We're leaving tomorrow.
[12715][12739]- And then you--|- What? Serve him?
[12750][12780]I've served men my entire life.
[12780][12798]I served Master Mott|at King's Landing
[12798][12824]and he sold me to the Watch.
[12825][12841]I served Lord Tywin|at Harrenhal,
[12841][12870]wondering every day if I'd|get tortured or killed.
[12882][12895]I'm done serving.
[12895][12918]You just said you were|serving Lord Beric.
[12931][12966]He may be their leader,|but they chose him.
[12967][12998]These men are brothers.|They're a family.
[13016][13034]I've never had a family.
[13064][13081]I can be your family.
[13112][13140]You wouldn't be my family.
[13140][13156]You'd be "my lady."
[13295][13325]- ( men shouting )|- ( swords clanging )
[13345][13363]Willem.
[13363][13388]( sounds get closer )
[13389][13405]Willem!
[13435][13468]- Is this a rescue?|- Lannister filth! Take him!
[13469][13492]Please, I didn't do anything.|I'm just a squire.
[13493][13511]- Please--|- ( squelches )
[13638][13653]Bring them in.
[13817][13833]Is that all of them?
[13855][13886]It took five of you to|murder two unarmed squires?
[13886][13905]Not murder, Your Grace.
[13906][13921]Vengeance.
[13921][13946]Vengeance?
[13947][13970]Those boys didn't|kill your sons.
[13971][14002]I saw Harrion die on the|battlefield and Torrhen--
[14002][14022]Was strangled|by the Kingslayer.
[14022][14045]- They were his kin.|- They were boys!
[14067][14084]Look at them.
[14102][14119]Tell your mother|to look at them.
[14119][14142]She killed them as much as I.
[14142][14169]My mother had nothing|to do with this.
[14169][14187]This was your treason.
[14188][14212]It's treason|to free your enemies.
[14212][14233]In war, you kill your enemies.
[14234][14255]Did your father|not teach you that, boy?
[14255][14275]- ( grunts )|- Leave him.
[14317][14333]Aye.
[14333][14357]Leave me to the king.
[14357][14394]He wants to give me a scolding|before he sets me free.
[14405][14439]That's how he deals|with treason.
[14439][14462]Our King in the North.
[14462][14486]Or should I call him
[14486][14517]the King Who Lost the North?
[14545][14570]Escort Lord Karstark|to the dungeon.
[14570][14587]Hang the rest.
[14588][14602]Mercy, sire!|I didn't kill anyone.
[14603][14617]I only watched for the guards.
[14618][14639]This one was only the watcher.
[14639][14660]Hang him last so he can|watch the others die.
[14660][14681]Man: Please! Please, no.|They made me do it!
[14682][14721]They made me!|They made me!
[14802][14826]Word of this|can't leave Riverrun.
[14827][14845]They were Tywin|Lannister's nephews.
[14846][14863]The Lannisters pay their debts.
[14863][14877]They never stop|talking about it.
[14877][14897]Would you make me a liar|as well as a murderer?
[14897][14914]It wouldn't be lying.
[14915][14937]We will bury them|and remain silent
[14937][14951]until the war is done.
[14951][14965]I'm not fighting for justice
[14966][14994]if I don't serve justice|to murderers in my ranks,
[14995][15024]no matter how highborn.
[15025][15050]He has to die.
[15051][15078]The Karstarks are Northmen.
[15078][15101]They won't forgive|the killing of their lord.
[15102][15121]Your mother's right.
[15122][15149]If you do this, the|Karstarks will abandon you.
[15150][15170]You tended to their wounds.
[15171][15198]You brought them supper.|Now they're dead.
[15198][15236]And more boys will keep dying|until this war is over.
[15237][15258]You need Karstark men|to end it.
[15258][15283]Spare his life.|Keep him as a hostage.
[15283][15304]A hostage.
[15304][15337]Tell the Karstarks that as|long as they remain loyal,
[15338][15358]he will not be harmed.
[15445][15474]( thunder rumbling )
[15608][15641]The blood of the First Men|flows through my veins
[15641][15672]as much as yours, boy.
[15672][15699]I fought the Mad King|for your father.
[15699][15735]I fought Joffrey for you.
[15736][15750]We are kin--
[15751][15774]Stark and Karstark.
[15774][15798]That didn't stop you|from betraying me.
[15798][15814]And it won't save you now.
[15814][15843]I don't want it to save me.
[15843][15880]I want it to haunt you|to the end of your days.
[15889][15906]Kneel, my lord.
[15996][16021]Rickard Karstark,
[16022][16037]Lord of Karhold,
[16038][16073]here in sight of gods and|men, I sentence you to die.
[16073][16102]Would you speak a final word?
[16113][16139]Kill me and be cursed.
[16139][16170]You are no king of mine.
[16311][16336]Arya:|Joffrey.
[16337][16357]Cersei.
[16373][16393]Ilyn Payne.
[16409][16429]Ser Meryn.
[16460][16481]The Hound.
[16516][16535]What are you|going to do with me?
[16536][16562]At first light|we'll ride for Riverrun.
[16562][16581]Your brother's there now.
[16581][16606]He'll make a contribution|to our cause
[16606][16623]and you can go home.
[16623][16651]I'm a hostage|and you're selling me.
[16651][16665]Don't think of it that way.
[16666][16692]- But it is that way.|- It is.
[16693][16721]- And it isn't.|- More is than isn't.
[16741][16772]Beric admired your father|a great deal, you know.
[16773][16794]He wanted to refuse|your ransom altogether.
[16794][16829]- So why don't you?|- We need the gold.
[16951][16967]Do I frighten you, child?
[16968][16986]No.
[17014][17032]You're angry with me.
[17032][17048]And I don't blame you.
[17049][17064]But letting him go|was the right thing.
[17064][17090]I have more reason than most|to want him hanged.
[17090][17115]- I thought he killed you.|- He did.
[17115][17134]But how...?
[17134][17156]Thoros...
[17156][17175]how many times|have you brought me back?
[17175][17210]It's the Lord of Light|brings you back.
[17210][17232]I'm just the lucky drunk|who says the words.
[17233][17259]- How many times?|- Five, I think.
[17259][17281]No, this makes six.
[17281][17294]Six.
[17295][17325]There was the first time--|the Mountain.
[17325][17340]Show her.
[17341][17378]Lance right through the chest.
[17379][17403]Then I was stabbed|in the belly.
[17403][17417]Then it was an arrow|in the back.
[17417][17445]And that axe in the side.
[17445][17478]Then the Lannisters caught me|and executed me for treason.
[17494][17517]Was it a hanging|or a dagger in the eye?
[17518][17549]Both.|Fuckers couldn't decide.
[17549][17575]And the Hound makes six.
[17575][17596]Second time I've been|killed by a Clegane.
[17597][17617]Thoros:|You'd think you'd learn.
[17634][17659]It's not getting|any easier, you know.
[17660][17680]Beric:|I know.
[17680][17701]Every time I come back,
[17701][17722]I'm a bit less.
[17738][17762]Pieces of you get chipped away.
[17777][17800]Could you bring back|a man without a head?
[17820][17856]Not six times.|Just once.
[17856][17885]I don't think it works|that way, child.
[17935][17971]He was a good man, Ned Stark.
[17972][18011]He's at rest now, somewhere.
[18011][18035]I would never wish|my life upon him.
[18035][18057]I would.
[18080][18101]You're alive.
[18151][18181]Lord, cast your light upon me.
[18191][18225]Protect me in the darkness.
[18225][18260]Burn away my sins.
[18260][18293]Help me serve you.
[18293][18315]Use me as you will.
[18340][18366]For the night is dark
[18366][18391]and full of terrors.
[18391][18411]( door opens )
[18502][18531]I have prayed day and night|for you to come to me.
[18547][18568]My lady.
[18568][18596]I meant to come sooner.
[18597][18629]- The battle--|- I know of your troubles, my king.
[18630][18657]The Lady Melisandre|has told me everything.
[18657][18682]Yes, of course.
[18775][18807]You mustn't despair.|Your claim is true.
[18808][18835]- You will be victorious.|- I believed that once.
[18836][18870]You are the one god's champion
[18870][18893]and the finest man|I've ever known.
[18893][18918]Selyse.
[18931][18956]I've broken a sacred vow.
[18991][19005]I've sinned.
[19005][19036]- No.|- I've wronged you.
[19037][19073]- I have shamed you.|- You're doing god's work.
[19073][19094]You don't understand.
[19150][19171]The Red Woman--
[19187][19205]the Lady Melisandre--
[19206][19225]I know, Stannis.
[19226][19266]The Lady Melisandre|has told me everything.
[19267][19299]No act done in service|of the Lord of Light
[19299][19327]can ever be a sin.
[19327][19360]When she told me,
[19360][19402]I wept with joy.
[19507][19544]Oh, my sweet boys.
[19559][19596]Petyr, Tommard,
[19596][19616]Edric.
[19627][19664]I thank god every day
[19665][19695]for bringing Melisandre to us.
[19695][19719]She gave you a son.
[19732][19758]I gave you...
[19770][19794]- nothing.|- That's not true.
[19843][19869]So you've come|to see her as well?
[19893][19913]There is no need.
[19927][19952]You must keep away|from such distractions.
[19953][19970]She's my daughter.
[19992][20006]I want to see her.
[20033][20059]You are a king.
[20060][20088]You don't need my permission.
[20125][20153]Girl:|♪ Under the sea ♪
[20153][20184]♪ I know, I know ♪
[20184][20209]♪ Oh, oh, oh ♪
[20209][20241]♪ The birds have scales ♪
[20241][20270]♪ And the fish take wing ♪
[20270][20301]♪ I know, I know ♪
[20301][20331]♪ Oh, oh, oh... ♪
[20331][20347]Stannis:|Shireen.
[20348][20367]Father!
[20396][20416]( sighs )
[20444][20465]You've grown|since I last saw you.
[20466][20501]Mother said you fought|in a battle.
[20501][20517]Did you win?
[20530][20550]No.
[20550][20575]Did the Onion Knight|come back with you?
[20588][20609]He did.
[20610][20627]He fought bravely.
[20627][20644]He hasn't come to visit me.
[20644][20674]He said he'd bring me back a|present from the capital.
[20675][20691]He won't be visiting, child.
[20692][20717]Why not?|He's my friend.
[20717][20733]Look.
[20733][20758]( drawer opens )
[20804][20825]He made this for me.
[20825][20849]But don't tell Mother|I have it.
[20849][20868]It's a secret.
[20869][20895]Mother doesn't like|the Onion Knight.
[20917][20940]Ser Davos is a traitor.
[20960][20993]He's rotting in a dungeon|cell for his crime.
[21085][21105]Best forget him.
[21138][21182]( door opens, closes )
[21223][21252]Not so hard.|You'll scrub the skin off.
[21252][21267]What are you doing here?
[21267][21280]I need a bath.
[21281][21307]Help me out of these rags.
[21377][21402]Now get out.
[21526][21542]There's another tub.
[21543][21572]This one suits me fine.
[21699][21727]Don't worry.|I'm not interested.
[21727][21748]( exhales )
[21748][21781]If I faint, pull me out.
[21781][21812]I don't intend to be the first|Lannister to die in a bathtub.
[21812][21830]Why should I care how you die?
[21830][21860]You swore a solemn vow,|remember?
[21860][21897]You're supposed to get me to|King's Landing in one piece.
[21907][21932]Not going so well, is it?
[21932][21958]No wonder Renly died|with you guarding him.
[22056][22080]That was unworthy.|Forgive me.
[22080][22100]You protected me|better than most--
[22100][22127]- Don't you mock me.|- I'm apologizing.
[22145][22166]I'm sick of fighting.
[22166][22181]Let's call a truce.
[22181][22199]You need trust to have a truce.
[22213][22236]I trust you.
[22304][22335]There it is.|There's the look.
[22335][22360]I've seen it for 17 years
[22360][22377]on face after face.
[22377][22409]You all despise me.
[22410][22427]Kingslayer.
[22427][22449]Oathbreaker.
[22449][22478]A man without honor.
[22535][22550]You've heard of wildfire?
[22551][22566]Of course.
[22566][22594]The Mad King|was obsessed with it.
[22594][22619]He loved to watch people burn,
[22620][22645]the way their skin|blackened and blistered
[22645][22671]and melted off their bones.
[22672][22693]He burned lords he didn't like.
[22694][22714]He burned Hands|who disobeyed him.
[22715][22749]He burned anyone|who was against him.
[22763][22796]Before long, half the|country was against him.
[22824][22850]Aerys saw traitors everywhere.
[22865][22906]So he had his pyromancer|place caches of wildfire
[22906][22930]all over the city--
[22931][22953]beneath the Sept of Baelor
[22954][22971]and the slums of Flea Bottom.
[22972][23005]Under houses, stables, taverns.
[23005][23038]Even beneath|the Red Keep itself.
[23056][23080]Finally,
[23080][23112]the day of reckoning came.
[23113][23136]Robert Baratheon|marched on the capital
[23137][23157]after his victory|at the Trident.
[23158][23182]But my father arrived first
[23182][23209]with the whole Lannister|army at his back,
[23210][23254]promising to defend the city|against the rebels.
[23272][23293]I knew my father|better than that.
[23293][23327]He's never been one|to pick the losing side.
[23327][23353]I told the Mad King as much.
[23353][23390]I urged him|to surrender peacefully.
[23391][23423]But the king didn't|listen to me.
[23423][23450]He didn't listen to Varys|who tried to warn him.
[23450][23494]But he did listen|to Grand Maester Pycelle,
[23494][23521]that grey, sunken cunt.
[23535][23564]"You can trust|the Lannisters," he said.
[23581][23603]"The Lannisters|have always been
[23604][23626]true friends|of the crown."
[23648][23675]So we opened the gates
[23675][23697]and my father sacked the city.
[23698][23732]Once again, I came to the king,
[23732][23764]begging him to surrender.
[23800][23825]He told me to...
[23825][23850]bring him my father's head.
[23864][23884]Then he...
[23885][23915]turned to his pyromancer.
[23915][23943]"Burn them all," he said.
[23953][23984]"Burn them in their homes.
[23984][24005]Burn them|in their beds."
[24019][24067]Tell me, if your precious Renly
[24067][24096]commanded you to kill|your own father
[24096][24126]and stand by while|thousands of men,
[24127][24149]women, and children|burned alive,
[24149][24176]would you have done it?
[24177][24195]Would you have|kept your oath then?
[24235][24271]First, I killed the pyromancer.
[24271][24307]And then when the king|turned to flee,
[24307][24342]I drove my sword into his back.
[24355][24380]"Burn them all,"|he kept saying.
[24380][24400]"Burn them all."
[24400][24422]I don't think|he expected to die.
[24423][24452]He-- he meant to...
[24467][24492]burn with the rest of us
[24493][24521]and rise again,
[24521][24540]reborn as a dragon
[24540][24559]to turn his enemies to ash.
[24597][24633]I slit his throat to make sure|that didn't happen.
[24674][24711]That's where Ned Stark|found me.
[24712][24734]If this is true...
[24750][24769]why didn't you tell anyone?
[24789][24807]Why didn't you tell Lord Stark?
[24808][24823]Stark?
[24823][24848]You think
[24848][24888]the honorable Ned Stark
[24888][24921]wanted to hear my side?
[24921][24948]He judged me guilty
[24948][24972]the moment he set eyes on me.
[24973][25003]( breathing heavily )
[25003][25042]By what right does the wolf
[25042][25062]judge the lion?
[25075][25091]- By what right?|- Help! Help!
[25091][25107]The Kingslayer!
[25120][25141]Jaime.
[25141][25161]My name is Jaime.
[25193][25217]Shireen:|Onion Knight.
[25217][25237]Ser Onion Knight.
[25249][25273]Princess? Gods, what|are you doing here?
[25274][25298]- Shh, you'll wake Bert.|- Bert?
[25299][25329]He's the fat one.|He's on guard duty tonight.
[25330][25349]He likes to drink wine|and sleep a lot.
[25349][25375]Go back to your room. You're|not supposed to be here.
[25375][25396]- If your father knew--|- He said you were a traitor.
[25397][25419]Are you?
[25419][25445]I am, child.
[25445][25465]I disobeyed my king,|your father,
[25465][25483]and now I'm paying the price.
[25484][25509]I don't care.|You're my friend.
[25509][25529]You must get bored down here.
[25529][25548]I brought you|something to read.
[25549][25567]It's about Aegon|and his dragons.
[25567][25602]Aegon used to live here.|Did you know that?
[25602][25620]- And the Targaryens built this castle.|- Aye.
[25620][25643]- So they did.|- You can hide the book under your cloak.
[25643][25667]It's a good one.|I'll bring you more.
[25667][25696]Thank you, my lady.|I'm sure it's a fine book,
[25696][25710]but it's wasted on me.
[25711][25735]Take it.|I have more.
[25747][25773]My lady, I can't read|the words.
[25773][25794]You can't?
[25794][25821]I'll teach you. I'll come when|Bert's on duty and teach you.
[25821][25840]- No. No. No.|- It's easy. It'll be fun.
[25840][25862]- Go. We can't.|- Why not?
[25862][25890]What will they do,|lock us in cells?
[25890][25910]( laughs )
[25952][25969]I wouldn't know where to start.
[25970][25987]At the beginning.
[25987][26006]This word is Aegon.
[26007][26048]When you see A, E, and G|together like that,
[26048][26067]it sounds like egg.
[26067][26086]And the title of the whole book
[26087][26108]is "An History|of Aegon the Conqueror
[26109][26130]and His Conquest|of Westeros."
[26131][26168]( men shouting orders )
[26253][26269]Jorah: It was a|bitch of a siege.
[26269][26291]Mm, you were first through|the breach at Pyke?
[26291][26326]The second. Thoros of|Myr went in alone,
[26326][26348]waving that|flaming sword of his.
[26348][26375]Thoros of Myr.|Bloody madman.
[26376][26405]Robert knighted you|after the battle?
[26405][26424]Proudest moment of my life.
[26424][26456]One knee in the dust, the|king's sword on my shoulder,
[26457][26470]listening to the words.
[26470][26507]"In the name of the Warrior,|I charge you to be brave."
[26508][26537]All I could think of|was how badly I had to piss.
[26537][26550]( laughs )
[26550][26576]Jorah: In full plate|metal for 16 hours.
[26577][26596]Never occurred to me|till the fighting was over.
[26597][26629]I was very nearly the first man|knighted to piss on the king's boots.
[26629][26647]( laughs )
[26647][26669]Robert would have laughed.
[26670][26696]He was a good man,|a great warrior.
[26714][26733]And a terrible king.
[26734][26767]I burned away my years|fighting for terrible kings.
[26768][26783]- You swore an oath.|- Yes.
[26783][26802]And a man of honor|keeps his vows,
[26802][26837]even if he's serving|a drunk or a lunatic.
[26837][26863]Just once in my life|before it's over,
[26863][26893]I want to know what it's|like to serve with pride,
[26894][26925]to fight for someone|I believe in.
[26925][26943]Do you believe in her?
[26971][26990]With all my heart.
[27041][27052]These are the ones?
[27054][27075]Yes, khaleesi.|The officers.
[27093][27117]_
[27122][27166]_
[27172][27211]_
[27255][27276]_
[27350][27369]_
[27370][27387]_
[27388][27405]_
[27406][27422]_
[27434][27458]All Unsullied boys|are given new names
[27458][27474]when they are cut--
[27475][27504]Grey Worm, Red Flea, Black Rat.
[27504][27532]Names that remind them|what they are--
[27532][27557]vermin.
[27592][27617]_
[27618][27657]_
[27658][27677]_
[27682][27708]_
[27709][27754]_
[27765][27789]_
[27790][27806]_
[27810][27841]_
[27845][27890]_
[27897][27993]_
[28026][28043]Jorah: King Robert|wanted her dead.
[28044][28057]Of course he wanted her dead.
[28058][28094]She's a Targaryen.|The last Targaryen.
[28094][28121]I suppose no one on the small|council could speak sense to him.
[28122][28151]- I didn't sit on the small council.|- No?
[28151][28177]Doesn't the Lord Commander of|the Kingsguard traditionally--
[28178][28196]Traditionally, yes,|but I killed a dozen
[28197][28218]of Robert's friends|during his rebellion.
[28240][28256]He didn't want advice|on how to govern
[28257][28276]from a man who had fought|for the Mad King.
[28276][28295]Can't say I minded much.
[28297][28327]I always hated the politics.
[28328][28347]Yeah, I imagine I would, too.
[28347][28372]Hours spent jabbering|about backstabbings
[28372][28404]- and betrayals the world over.|- Mm-hmm.
[28435][28454]Still, she'll have|to wade through that muck
[28455][28477]if she wants to rule|the Seven Kingdoms.
[28477][28498]She'll have good men|around her to advise her,
[28498][28513]men with experience.
[28513][28528]Which men do you have in mind?
[28529][28549]Forgive me, Ser Jorah,|for what I'm about to say,
[28549][28585]but your reputation in Westeros|has suffered over the years.
[28585][28609]It suffered for a reason.
[28609][28627]I sold men into slavery.
[28627][28646]I don't know if your|presence by her side
[28646][28669]will help our cause|when we go home.
[28669][28687]Our cause?
[28687][28708]Forgive me, Ser|Barristan, but I was busy
[28708][28730]defending the khaleesi against|King Robert's assassins
[28730][28748]while you were still|bowing to the man.
[28749][28779]We both want her to rule.|Am I wrong?
[28779][28805]You only joined us|a few days ago.
[28806][28827]I can't speak|to your intentions.
[28827][28849]If we're truly|her loyal servants,
[28849][28877]we will do whatever|needs to be done,
[28877][28903]no matter the cost,|no matter our pride.
[28904][28929]You're not Lord Commander here.
[28930][28955]You're just another exile.
[28956][28976]And I take my orders|from the queen.
[29058][29086]- Talisa: Come to bed.|- You were right.
[29098][29116]The Karstarks are gone.
[29126][29148]Almost half our forces.
[29149][29184]Tywin Lannister knows what he|needs to do to make us unravel.
[29184][29213]Nothing.
[29213][29234]Only wait.
[29235][29260]Don't let him.
[29260][29281]What can I do?
[29281][29296]Attack King's Landing?
[29296][29317]There's nothing|he'd like better.
[29318][29338]He'd crush us in a day.
[29348][29359]We could ride north.
[29360][29386]Take your land back|from the Greyjoys.
[29387][29419]- Wait out the winter.|- Winter could last five years.
[29420][29433]Once my bannermen|are home again,
[29434][29461]sitting by the fire,|surrounded by their families,
[29462][29493]warm and safe, they'll|never ride south again.
[29493][29514]When I gathered|my lords together,
[29515][29534]we had a purpose, a mission.
[29534][29562]Now we're like a band|of bickering children.
[29585][29604]Give them a new purpose.
[29605][29622]What?
[29637][29659]Oh, I don't know.
[29659][29684]I don't even know|where Winterfell is.
[29711][29730]Here.
[29762][29798]And we're here.|King's Landing--
[29867][29882]What is it?
[29915][29946]I can't force them|to meet us in the field
[29947][29971]and I can't attack them|where they're strongest,
[29971][30000]but I can attack them|where they're not.
[30012][30040]And Casterly Rock|can't run away.
[30053][30083]I'm going to take|their home away from them.
[30096][30118]Can you do it?
[30118][30148]I need men to replace the|Karstarks who marched home.
[30149][30175]There is only one person|in this kingdom
[30175][30207]with that kind of army who hasn't|already sided with the Lannisters.
[30221][30248]The man whose daughter|I was supposed to marry--
[30259][30278]Walder Frey.
[30366][30389]He's such a splendid fighter.
[30389][30423]Do you have any idea|when we might...
[30423][30459]I'll plant the seed as soon|as Joffrey and I are married.
[30460][30475]It should grow quickly.
[30475][30491]Joffrey won't let me leave.
[30492][30519]He's got too many reasons|to keep me here.
[30519][30553]And only one to let you go.
[30553][30575]Because it will please me.
[30575][30596]Man:|Squire!
[30631][30648]Well fought, ser.
[30648][30676]That was no fight.|I don't know you.
[30676][30700]Olyver, if it please you.
[30721][30750]I should like to see you spar|with a proper partner, ser.
[30750][30774]( chuckles )
[30831][30846]How did you know?
[30846][30865]Know what?
[30879][30897]That I wanted to.
[30897][30916]My lord...
[30956][30973]I'll have you know|I'm to be married soon
[30973][31004]and even my intended|hasn't the slightest notion.
[31004][31035]They rarely do,|in my experience.
[31036][31059]You have a good deal|of experience, do you?
[31069][31090]With the husbands.
[31179][31202]That didn't take long.
[31203][31225]Well, it took long enough.
[31240][31270]It seems our Knight of Flowers|is engaged to be wed.
[31270][31288]Is he?
[31289][31312]And...
[31312][31330]who's the lucky girl?
[31330][31365]Littlefinger: She may not be|the grandest ship in the world
[31366][31390]or the fastest,
[31391][31412]but she's mine.
[31448][31467]I've always wanted a ship.
[31468][31489]Now I want a dozen.
[31489][31516]- Strange, isn't it?|- What is?
[31516][31538]It doesn't matter what we want,
[31538][31556]once we get it,
[31556][31574]then we want something else.
[31601][31628]Your hair is different.
[31629][31645]Is it?
[31645][31661]Lady Margaery|wears it that way.
[31662][31686]Many ladies wear it this way.
[31686][31703]I have good news.
[31704][31725]I'll be leaving the city soon.
[31725][31740]You still want me|to come with you?
[31740][31762]It's not a question|of what I want.
[31763][31785]It's what you want.
[31785][31797]You want to go home, don't you?
[31797][31822]Of course.|More than anything.
[31843][31877]But maybe it would|be better to wait.
[31878][31906]I've been thinking|how dangerous it would be.
[31906][31935]Not just for me, but for you.
[31935][31948]You've been so kind.
[31948][31980]I'd feel terrible if|anything happened to you.
[31991][32013]I can't tell you|how touched I am
[32014][32046]by your concern for my welfare.
[32046][32074]I hope you know that|I'm your friend, Sansa.
[32075][32095]Your true friend.
[32096][32113]I do, Lord Baelish.
[32113][32140]- Petyr.|- Petyr.
[32140][32161]If you wish to stay,
[32161][32191]then of course you will stay.
[32240][32264]We'll speak again|when I return.
[32394][32415]Tywin:|You're late.
[32416][32444]What's she doing here?
[32444][32465]Our business concerns her, too.
[32465][32483]Sit.
[32503][32519]You'll be pleased to learn
[32520][32550]that after one conversation|with Olenna Tyrell,
[32551][32571]I've saved the crown
[32571][32599]hundreds of thousands|on this wedding.
[32600][32610]Never mind that now.
[32610][32626]We have something|important to discuss.
[32626][32650]I'm Master of Coin.|Saving money is important.
[32659][32673]Stop that.
[32674][32693]You're making me uncomfortable.
[32693][32723]Your sister has learned that|your new friends the Tyrells
[32723][32753]are plotting to marry|Sansa Stark to Ser Loras.
[32754][32772]Very well.
[32772][32792]She's a lovely girl.
[32793][32813]Missing some of Loras'|favorite bits,
[32813][32831]but I'm sure they'll make do.
[32831][32857]- Your jokes are not appreciated.|- It wasn't my best, but--
[32857][32888]I bring them into the royal fold|and this is how they repay me,
[32888][32923]by trying to steal the key to|the North out from under me.
[32923][32940]Sansa is the key to the North?
[32940][32964]I seem to remember|she has an older brother.
[32964][32984]The Karstarks|have marched home.
[32985][33014]The young wolf has lost half his army.|His days are numbered.
[33014][33045]Theon Greyjoy murdered|both his brothers.
[33046][33079]That makes Sansa Stark|the heir to Winterfell.
[33080][33118]And I am not about to hand|her over to the Tyrells.
[33118][33141]Tyrion: The Tyrell army is|helping us to win this war.
[33142][33169]Do you really think|it's wise to refuse them?
[33170][33188]There's nothing to refuse.|This is a plot.
[33188][33216]Plots are not public knowledge.
[33216][33234]And the Tyrells|won't carry this one out
[33234][33256]until after Joffrey's wedding.
[33256][33294]We need to act first and|kill this union in its crib.
[33294][33308]And how do we do that?
[33308][33331]We find Sansa Stark|a different husband.
[33331][33357]- Wonderful.|- Yes, it is.
[33433][33449]You can't mean it.
[33449][33464]I can and I do.
[33464][33495]Joffrey has made this|poor girl's life miserable
[33496][33516]since the day he took|her father's head.
[33516][33547]Now she's finally free of|him and you give her to me?
[33547][33564]That's cruel even for you.
[33564][33583]Do you intend|on mistreating her?
[33583][33603]The girl's happiness|is not my concern,
[33603][33625]- nor should it be yours.|- She's a child!
[33626][33654]She's flowered, I assure you. She|and I have discussed it at length.
[33655][33690]There, you see? You will wed her,|bed her, and put a child in her.
[33690][33720]- Surely you're capable of that.|- And if I refuse?
[33721][33748]You wanted to be rewarded|for your valor in battle.
[33748][33788]Sansa Stark is a finer reward than|you could ever dare hope for.
[33788][33813]And it is past time|you were wed.
[33814][33842]I was wed.
[33842][33868]Or don't you remember?
[33882][33904]Only too well.
[33904][33938]Cersei: You should be|thanking the gods for this.
[33938][33954]This is more than you deserve.
[33955][33979]Tywin:|Tyrion will do as he's bid.
[33980][34000]As will you.
[34014][34035]What do you mean?
[34036][34054]You'll marry Ser Loras.
[34076][34101]- I will not.|- The boy is heir to Highgarden.
[34101][34126]Tyrion will secure the North,|you will secure the Reach.
[34126][34153]- No, I won't do it.|- Yes, you will.
[34154][34181]You're still fertile. You need|to marry again and breed.
[34181][34203]I am Queen Regent,|not some broodmare.
[34203][34230]You're my daughter!
[34230][34246]You will do as I command
[34247][34269]and you will marry Loras Tyrell
[34269][34293]and put an end|to the disgusting rumors
[34293][34321]about you once and for all.
[34321][34342]Father, don't make me|do it again, please.
[34343][34368]Not another word.
[34369][34399]My children.
[34400][34439]You've disgraced the Lannister|name for far too long.
[34551][34584]♪ It's always summer ♪
[34584][34618]♪ Under the sea ♪
[34618][34647]♪ I know, I know ♪
[34647][34683]♪ Oh, oh, oh ♪
[34683][34724]♪ The birds have scales ♪
[34724][34760]♪ And the fish take wing ♪
[34761][34791]♪ I know, I know ♪
[34791][34827]♪ Oh, oh, oh ♪
[34827][34862]♪ The rain is dry ♪
[34862][34895]♪ And snow falls up ♪
[34896][34923]♪ I know, I know ♪
[34924][34960]♪ Oh, oh, oh ♪
[34960][34998]♪ The stones crack open ♪
[34999][35041]♪ The water burns ♪
[35041][35081]♪ The shadows come to dance ♪
[35081][35107]♪ My lord ♪
[35108][35140]♪ The shadows come ♪
[35140][35166]♪ To play ♪
[35166][35205]♪ The shadows come to dance ♪
[35205][35227]♪ My lord ♪
[35227][35261]♪ The shadows come ♪
[35262][35297]♪ To stay. ♪
[35297][35497]{c:$0000ff}Subtitles downloaded by MiniSubDownloader:|{c:$ff7070}{y:u}http://minisubdownloader.org

max_stars_repo_name: backup-fork/subtitle-tools

max_issues_repo_name: backup-fork/subtitle-tools

max_forks_repo_name: backup-fork/subtitle-tools


text:
# Simplicial constructions for a proof of the Hurewicz theorem

`is_element/K/hurewicz` := (A::set) -> (d::posint) -> proc(x)
 if not(`is_element/prime_simplex`(A)(x)) then
  return false;
 fi;

 if nops(select(a -> x[a]>0,A)) > d then
  return false;
 fi;

 return true;
end:

`random_element/K/hurewicz` := (A::set) -> (d::posint) -> proc()
 local k,i,B,x,a;
 k := rand(1..min(nops(A),d))();
 B := {};
 for i from 1 to k do
  B := {op(B),random_element_of(A minus B)};
 od:
 x := `random_element/prime_simplex`(B)();
 for a in A minus B do x[a] := 0; od;
 return eval(x);
end:

`list_elements/K_hurewicz` := NULL:
`count_elements/K_hurewicz` := NULL:

######################################################################

`is_element/L/hurewicz` := (A::set) -> (d::posint) -> proc(tx)
 local t,x;

 if not(type(tx,list)) and nops(tx) = 2 then
  return false;
 fi;

 t,x := op(tx);

 if not(type(t,realcons) and is(t >= 0) and is(t <= 1)) then
  return false;
 fi;

 if not(`is_element/prime_simplex`(A)(x)) then
  return false;
 fi;

 if t = 1 then
  return true;
 fi;

 if `is_element/K/hurewicz`(A)(d)(x) then
  return true;
 fi;

 return false;
end:

`random_element/L/hurewicz` := (A::set) -> (d::posint) -> proc()
 if rand(1..2)() = 1 then
  return [1,`random_element/prime_simplex`(A)()];
 else
  return [rand(0..12)()/12,`random_element/K/hurewicz`(A)(d)()];
 fi;
end:

`list_elements/L_hurewicz` := NULL:
`count_elements/L_hurewicz` := NULL:

######################################################################

`u1/hurewicz` := (A::set) -> (d::posint) -> proc(x)
 local JJ,J,j;
 if nops(A) <= d then return 0; fi;
 JJ := combinat[choose](A,nops(A) - d);
 return min(seq(max(seq(x[j],j in J)),J in JJ));
end:

`w1/hurewicz` := (A::set) -> (d::posint) -> proc(tx)
 local t,x,u1;
 t,x := op(tx);
 u1 := `u1/hurewicz`(A)(d)(x);
 return min(u1+(1+t)/2,1);
end:

`f1/hurewicz` := (A::set) -> (d::posint) -> proc(tx)
 local t,x,y,a;
 t,x := op(tx);
 y := table():
 for a in A do
  y[a] := max(0,x[a]-(1-t)/2,2*x[a]-1);
 od:
 return eval(y);
end:

`h1/hurewicz` := (A::set) -> (d::posint) -> proc(tx)
 return [`w1/hurewicz`(A)(d)(tx),`f1/hurewicz`(A)(d)(tx)];
end: