WeixiangYan/CodeTransOcean huggingface dataset:
Task: Disarium numbers







Python: 

def isDisarium(n):
    digitos = len(str(n))
    suma = 0
    x = n
    while x != 0:
        suma += (x % 10) ** digitos
        digitos -= 1
        x //= 10
    if suma == n:
        return True
    else:
        return False

if __name__ == '__main__':
    limite = 19
    cont = 0
    n = 0
    print("The first",limite,"Disarium numbers are:")
    while cont < limite:
        if isDisarium(n):
            print(n, end = " ")
            cont += 1
        n += 1





Ada: with Ada.Text_IO;

procedure Disarium_Numbers is

   Disarium_Count : constant := 19;

   function Is_Disarium (N : Natural) return Boolean is
      Nn  : Natural := N;
      Pos : Natural := 0;
      Sum : Natural := 0;
   begin
      while Nn /= 0 loop
         Nn  := Nn / 10;
         Pos := Pos + 1;
      end loop;
      Nn := N;
      while Nn /= 0 loop
         Sum := Sum + (Nn mod 10) ** Pos;
         Nn  := Nn / 10;
         Pos := Pos - 1;
      end loop;
      return N = Sum;
   end Is_Disarium;

   Count : Natural := 0;
begin
   for N in 0 .. Natural'Last loop
      if Is_Disarium (N) then
         Count := Count + 1;
         Ada.Text_IO.Put (N'Image);
      end if;
      exit when Count = Disarium_Count;
   end loop;
end Disarium_Numbers;
Task: Flow-control structures







Python: 
for i in range(n):
    if (n%2) == 0:
        continue
    if (n%i) == 0:
        result = i
        break
else:
    result = None
    print "No odd factors found"





Ada: <<Top>>
   Put_Line("Hello, World");
   goto Top;
Task: Find if a point is within a triangle







Python: 

from sympy.geometry import Point, Triangle

def sign(pt1, pt2, pt3):
    
    return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)


def iswithin(point, pt1, pt2, pt3):
    
    zval1 = sign(point, pt1, pt2)
    zval2 = sign(point, pt2, pt3)
    zval3 = sign(point, pt3, pt1)
    notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0
    notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0
    return notanyneg or notanypos

if __name__ == "__main__":
    POINTS = [Point(0, 0)]
    TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))
    for pnt in POINTS:
        a, b, c = TRI.vertices
        isornot = "is" if iswithin(pnt, a, b, c) else "is not"
        print("Point", pnt, isornot, "within the triangle", TRI)





Ada: 
generic
	type Dimension is private;
	Zero, Two: Dimension;
	with function "*"(Left, Right: in Dimension) return Dimension is <>;
	with function "/"(Left, Right: in Dimension) return Dimension is <>;
	with function "+"(Left, Right: in Dimension) return Dimension is <>;
	with function "-"(Left, Right: in Dimension) return Dimension is <>;
	with function ">"(Left, Right: in Dimension) return Boolean is <>;
	with function "="(Left, Right: in Dimension) return Boolean is <>;
	with function Image(D: in Dimension) return String is <>;
package Triangle is

	type Point is record
		X: Dimension;
		Y: Dimension;
	end record;

	type Triangle_T is record
		A,B,C: Point;
	end record;

	function Area(T: in Triangle_T) return Dimension;

	function IsPointInTriangle(P: Point; T: Triangle_T) return Boolean;

	function Image(P: Point) return String is
		("(X="&Image(P.X)&", Y="&Image(P.Y)&")")
		with Inline;

	function Image(T: Triangle_T) return String is
		("(A="&Image(T.A)&", B="&Image(T.B)&", C="&Image(T.C)&")")
		with Inline;
end;
Task: Return multiple values







Python: def addsub(x, y):
  return x + y, x - y





Ada: with Ada.Text_IO; use Ada.Text_IO;
procedure MultiReturn is
   procedure SumAndDiff (x, y : Integer; sum, diff : out Integer) is begin
      sum := x + y;
      diff := x - y;
   end SumAndDiff;
   inta : Integer := 5;
   intb : Integer := 3;
   thesum, thediff : Integer;
begin
   SumAndDiff (inta, intb, thesum, thediff);
   Put_Line ("Sum:" & Integer'Image (thesum));
   Put_Line ("Diff:" & Integer'Image (thediff));
end MultiReturn;
Task: Change e letters to i in words







Python: 



def ieTwins(s):
    
    longWords = [
        w for w in s.splitlines()
        if 5 < len(w)
    ]
    lexicon = {
        w for w in longWords
        if 'i' in w
    }

    return [
        (w, twin) for w in longWords
        if 'e' in w and (
            twin := w.replace('e', 'i')
        ) in lexicon
    ]




def main():
    
    for pair in ieTwins(
        readFile("unixdict.txt")
    ):
        print(pair)





def readFile(fp):
    
    with open(fp, 'r', encoding='utf-8') as f:
        return f.read()



if __name__ == '__main__':
    main()





Ada: with Ada.Text_Io;
with Ada.Strings.Fixed;
with Ada.Strings.Maps;
with Ada.Containers.Indefinite_Ordered_Maps;

procedure Change_E_To_I is
   use Ada.Text_Io;
   use Ada.Strings;

   Filename : constant String := "unixdict.txt";
   Mapping  : constant Maps.Character_Mapping :=
     Maps.To_Mapping ("Ee", "Ii");

   package Dictionaries is
     new Ada.Containers.Indefinite_Ordered_Maps
       (Key_Type     => String,
        Element_Type => String);

   Dict    : Dictionaries.Map;
   File    : File_Type;
begin
   Open (File, In_File, Filename);
   while not End_Of_File (File) loop
      declare
         Word : constant String := Get_Line (File);
      begin
         Dict.Insert (Word, Word);
      end;
   end loop;
   Close (File);

   for Word of Dict loop
      declare
         Trans : constant String := Fixed.Translate (Word, Mapping);
      begin
         if Word /= Trans and Dict.Contains (Trans) and Word'Length >= 6 then
            Put (Word); Put (" -> "); Put (Trans); New_Line;
         end if;
      end;
   end loop;
end Change_E_To_I;
Task: Fractran







Python: from fractions import Fraction

def fractran(n, fstring='17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33,'
                        '77 / 29, 95 / 23, 77 / 19, 1 / 17, 11 / 13,'
                        '13 / 11, 15 / 14, 15 / 2, 55 / 1'):
    flist = [Fraction(f) for f in fstring.replace(' ', '').split(',')]

    n = Fraction(n)
    while True:
        yield n.numerator
        for f in flist:
            if (n * f).denominator == 1:
                break
        else:
            break
        n *= f
    
if __name__ == '__main__':
    n, m = 2, 15
    print('First %i members of fractran(%i):\n  ' % (m, n) +
          ', '.join(str(f) for f,i in zip(fractran(n), range(m))))





Ada: with Ada.Text_IO;

procedure Fractan is
   
   type Fraction is record Nom: Natural; Denom: Positive; end record;
   type Frac_Arr is array(Positive range <>) of Fraction;
   
   function "/" (N: Natural; D: Positive) return Fraction is
      Frac: Fraction := (Nom => N, Denom => D);
   begin
      return Frac;
   end "/";
   
   procedure F(List: Frac_Arr; Start: Positive; Max_Steps: Natural) is
      N: Positive := Start;
      J: Positive;
   begin
      Ada.Text_IO.Put(" 0:" & Integer'Image(N) & "   ");
      for I in 1 .. Max_Steps loop
	 J := List'First;
	 loop
	    if N mod List(J).Denom = 0 then
	       N := (N/List(J).Denom) * List(J).Nom;
	       exit; 
	    elsif J >= List'Last then
	       return; 
	    else
	       J := J + 1; 
	    end if;
	 end loop;
	 Ada.Text_IO.Put(Integer'Image(I) & ":" & Integer'Image(N) & "   ");
      end loop;
   end F;
   
begin
   
   

   F((17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 
      77/19,  1/17, 11/13, 13/11, 15/14,  15/2, 55/1), 
     2, 15);
   
end Fractan;
Task: Substring_Top and tail







Python: print "knight"[1:]     
print "socks"[:-1]     
print "brooms"[1:-1]   





Ada: with Ada.Text_IO;

procedure Remove_Characters is
   S: String := "upraisers";
   use Ada.Text_IO;
begin
   Put_Line("Full String:   """ & S & """");
   Put_Line("Without_First: """ & S(S'First+1 .. S'Last) & """");
   Put_Line("Without_Last:  """ & S(S'First   .. S'Last-1) & """");
   Put_Line("Without_Both:  """ & S(S'First+1 .. S'Last-1) & """");
end Remove_Characters;
Task: Boolean values







Python: >>> True
True
>>> not True
False
>>> 
>>> False + 0
0
>>> True + 0
1
>>> False + 0j
0j
>>> True * 3.141
3.141
>>> 
>>> not 0
True
>>> not not 0
False
>>> not 1234
False
>>> bool(0.0)
False
>>> bool(0j)
False
>>> bool(1+2j)
True
>>> 
>>> bool([])
False
>>> bool([None])
True
>>> 'I contain something' if (None,) else 'I am empty'
'I contain something'
>>> bool({})
False
>>> bool("")
False
>>> bool("False")
True





Ada:    type Boolean is (False, True);
Task: Multiline shebang







Python: 
"exec" "python" "$0"

print "Hello World"





Ada: #!/bin/bash
sed -n -e '7,$p' < "$0" > mulshbang.adb
gnatmake -q mulshbang
./mulshbang $*
rm mulshbang*
exit 
with Ada.Text_IO, Ada.Command_Line; 

procedure Mulshbang is
  use Ada.Text_IO;
begin
  Put_Line("Name: " & Ada.Command_Line.Command_Name);
  for I in 1 .. Ada.Command_Line.Argument_Count loop
    Put_Line("  Arg" & Integer'Image(I) & ": " &
             Ada.Command_Line.Argument(I));
  end loop;
end Mulshbang;
Task: Bitmap_Histogram







Python: from PIL import Image


image = Image.open("lena.jpg")

width, height = image.size

amount = width * height


total = 0

bw_image = Image.new('L', (width, height), 0)

bm_image = Image.new('1', (width, height), 0)

for h in range(0, height):
    for w in range(0, width):
        r, g, b = image.getpixel((w, h))

        greyscale = int((r + g + b) / 3)
        total += greyscale

        bw_image.putpixel((w, h), gray_scale)


avg = total / amount

black = 0
white = 1

for h in range(0, height):
    for w in range(0, width):
        v = bw_image.getpixel((w, h))

        if v >= avg:
            bm_image.putpixel((w, h), white)
        else:
            bm_image.putpixel((w, h), black)

bw_image.show()
bm_image.show()





Ada: type Pixel_Count is mod 2**64;
type Histogram is array (Luminance) of Pixel_Count;
   
function Get_Histogram (Picture : Grayscale_Image) return Histogram is
   Result : Histogram := (others => 0);
begin
   for I in Picture'Range (1) loop
      for J in Picture'Range (2) loop
         declare
            Count : Pixel_Count renames Result (Picture (I, J));
         begin
            Count := Count + 1;
         end;
      end loop;
   end loop;
   return Result;
end Get_Histogram;
Task: Plot coordinate pairs







Python: >>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]

>>> import pylab
>>> pylab.plot(x, y, 'bo')
>>> pylab.savefig('qsort-range-10-9.png')





Ada: with Gtk.Main;
with Gtk.Window;  use Gtk.Window;
with Gtk.Widget;  use Gtk.Widget;
with Gtk.Handlers;  use Gtk.Handlers;
with Glib;  use Glib;
with Gtk.Extra.Plot;  use Gtk.Extra.Plot;
with Gtk.Extra.Plot_Data;  use Gtk.Extra.Plot_Data;
with Gtk.Extra.Plot_Canvas;  use Gtk.Extra.Plot_Canvas;
with Gtk.Extra.Plot_Canvas.Plot;  use Gtk.Extra.Plot_Canvas.Plot;

procedure PlotCoords is
   package Handler is new Callback (Gtk_Widget_Record);

   Window : Gtk_Window;
   Plot : Gtk_Plot;
   PCP : Gtk_Plot_Canvas_Plot;
   Canvas : Gtk_Plot_Canvas;
   PlotData : Gtk_Plot_Data;
   x, y, dx, dy : Gdouble_Array_Access;

   procedure ExitMain (Object : access Gtk_Widget_Record'Class) is
   begin
      Destroy (Object);  Gtk.Main.Main_Quit;
   end ExitMain;

begin
   x := new Gdouble_Array'(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);
   y := new Gdouble_Array'(2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0);
   Gtk.Main.Init;
   Gtk_New (Window);
   Set_Title (Window, "Plot coordinate pairs with GtkAda");
   Gtk_New (PlotData);
   Set_Points (PlotData, x, y, dx, dy);
   Gtk_New (Plot);
   Add_Data (Plot, PlotData);
   Autoscale (Plot);  Show (PlotData);
   Hide_Legends (Plot);
   Gtk_New (PCP, Plot);  Show (Plot);
   Gtk_New (Canvas, 500, 500);  Show (Canvas);
   Put_Child (Canvas, PCP, 0.15, 0.15, 0.85, 0.85);
   Add (Window, Canvas);
   Show_All (Window);
   Handler.Connect (Window, "destroy",
      Handler.To_Marshaller (ExitMain'Access));
   Gtk.Main.Main;
end PlotCoords;
Task: LZW compression







Python: def compress(uncompressed):
    

    
    dict_size = 256
    dictionary = dict((chr(i), i) for i in range(dict_size))
    

    w = ""
    result = []
    for c in uncompressed:
        wc = w + c
        if wc in dictionary:
            w = wc
        else:
            result.append(dictionary[w])
            
            dictionary[wc] = dict_size
            dict_size += 1
            w = c

    
    if w:
        result.append(dictionary[w])
    return result


def decompress(compressed):
    
    from io import StringIO

    
    dict_size = 256
    dictionary = dict((i, chr(i)) for i in range(dict_size))
    

    
    
    result = StringIO()
    w = chr(compressed.pop(0))
    result.write(w)
    for k in compressed:
        if k in dictionary:
            entry = dictionary[k]
        elif k == dict_size:
            entry = w + w[0]
        else:
            raise ValueError('Bad compressed k: %s' % k)
        result.write(entry)

        
        dictionary[dict_size] = w + entry[0]
        dict_size += 1

        w = entry
    return result.getvalue()



compressed = compress('TOBEORNOTTOBEORTOBEORNOT')
print (compressed)
decompressed = decompress(compressed)
print (decompressed)





Ada: package LZW is

   MAX_CODE : constant := 4095;

   type Codes is new Natural range 0 .. MAX_CODE;
   type Compressed_Data is array (Positive range <>) of Codes;

   function Compress (Cleartext : in String) return Compressed_Data;
   function Decompress (Data : in Compressed_Data) return String;

end LZW;
Task: Check input device is a terminal







Python: from sys import stdin
if stdin.isatty():
    print("Input comes from tty.")
else:
    print("Input doesn't come from tty.")





Ada: with Ada.Text_IO;          use Ada.Text_IO;
with Interfaces.C_Streams; use Interfaces.C_Streams;

procedure Test_tty is
begin
   if Isatty(Fileno(Stdin)) = 0 then
      Put_Line(Standard_Error, "stdin is not a tty.");
   else
      Put_Line(Standard_Error, "stdin is a tty.");
   end if;
end Test_tty;
Task: First 9 prime Fibonacci number







Python: from math import sqrt
from time import time

n = 12
start = time()


def prime(x):
    if x < 2:
        return False
    if x == 2 or x == 3:
        return True
    if x % 2 == 0:
        return False
    for i in range(3, int(sqrt(x)) + 1, 2):
        if x % i == 0:
            return False
    return True


a, b, = 1, 1
fibn = 3
f = []
while len(f) < n:
    a, b, = b, a + b
    if prime(b):
        f.append(b)
        print("fib(%d): %s (%s s)" % (fibn, b, time() - start))
    fibn += 1





Ada: with Ada.Text_IO;

procedure Prime_Fibonacci is

   function Is_Prime (A : Natural) return Boolean is
      D : Natural;
   begin
      if A < 2       then return False; end if;
      if A in 2 .. 3 then return True;  end if;
      if A mod 2 = 0 then return False; end if;
      if A mod 3 = 0 then return False; end if;
      D := 5;
      while D * D <= A loop
         if A mod D = 0 then
            return False;
         end if;
         D := D + 2;
         if A mod D = 0 then
            return False;
         end if;
         D := D + 4;
      end loop;
      return True;
   end Is_Prime;

   F_1   : Natural := 0;
   F_2   : Natural := 1;

   function Fibonacci return Natural is
      R : Natural := F_1 + F_2;
   begin
      F_1 := F_2;
      F_2 := R;
      return R;
   end Fibonacci;

   Count : Natural := 0;
   Fib   : Natural;
begin
   while Count < 9 loop
      Fib := Fibonacci;
      if Is_Prime (Fib) then
         Count := Count + 1;
         Ada.Text_IO.Put_Line (Fib'Image);
      end if;
   end loop;
end Prime_Fibonacci;
Task: Bioinformatics_base count







Python: from collections import Counter

def basecount(dna):
    return sorted(Counter(dna).items())

def seq_split(dna, n=50):
    return [dna[i: i+n] for i in range(0, len(dna), n)]

def seq_pp(dna, n=50):
    for i, part in enumerate(seq_split(dna, n)):
        print(f"{i*n:>5}: {part}")
    print("\n  BASECOUNT:")
    tot = 0
    for base, count in basecount(dna):
        print(f"    {base:>3}: {count}")
        tot += count
    base, count = 'TOT', tot
    print(f"    {base:>3}= {count}")
    
if __name__ == '__main__':
    print("SEQUENCE:")
    sequence = 
    seq_pp(sequence)





Ada: with Ada.Text_Io;

procedure Base_Count is

   type Sequence is new String;
   Test : constant Sequence :=
     "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" &
     "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" &
     "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" &
     "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" &
     "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" &
     "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" &
     "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" &
     "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" &
     "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" &
     "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT";

   Line_Width : constant := 70;

   procedure Put (Seq : Sequence) is
      use Ada.Text_Io;
      package Position_Io is new Ada.Text_Io.Integer_Io (Natural);
      First : Natural := Seq'First;
      Last  : Natural;
   begin
      loop
         Last := Natural'Min (Seq'Last, First + Line_Width - 1);
         Position_Io.Put (First, Width => 3);
         Put (String'(".."));
         Position_Io.Put (Last, Width => 3);
         Put (String'("  "));
         Put (String (Seq (First .. Last)));
         New_Line;
         exit when Last = Seq'Last;
         First := First + Line_Width;
      end loop;
   end Put;

   procedure Count (Seq : Sequence) is
      use Ada.Text_Io;
      A_Count, C_Count : Natural := 0;
      G_Count, T_Count : Natural := 0;
   begin
      for B of Seq loop
         case B is
            when 'A' =>  A_Count := A_Count + 1;
            when 'C' =>  C_Count := C_Count + 1;
            when 'G' =>  G_Count := G_Count + 1;
            when 'T' =>  T_Count := T_Count + 1;
            when others =>
               raise Constraint_Error;
         end case;
      end loop;
      Put_Line ("A: " & A_Count'Image);
      Put_Line ("C: " & C_Count'Image);
      Put_Line ("G: " & G_Count'Image);
      Put_Line ("T: " & T_Count'Image);
      Put_Line ("Total: " & Seq'Length'Image);
   end Count;

begin
   Put (Test);
   Count (Test);
end Base_Count;
Task: Terminal control_Inverse video







Python: 

print "\033[7mReversed\033[m Normal"





Ada: with Ada.Text_IO; use  Ada.Text_IO;

procedure Reverse_Video is 

   Rev_Video  : String := Ascii.ESC & "[7m";
   Norm_Video : String := Ascii.ESC & "[m";

begin
   Put (Rev_Video & "Reversed");
   Put (Norm_Video & " Normal");
end Reverse_Video;
Task: Ulam spiral (for primes)







Python: 
from __future__ import print_function, division
from math import sqrt

def cell(n, x, y, start=1):
    d, y, x = 0, y - n//2, x - (n - 1)//2
    l = 2*max(abs(x), abs(y))
    d = (l*3 + x + y) if y >= x else (l - x - y)
    return (l - 1)**2 + d + start - 1

def show_spiral(n, symbol='
    top = start + n*n + 1
    is_prime = [False,False,True] + [True,False]*(top//2)
    for x in range(3, 1 + int(sqrt(top))):
        if not is_prime[x]: continue
        for i in range(x*x, top, x*2):
            is_prime[i] = False

    cell_str = lambda x: f(x) if is_prime[x] else space
    f = lambda _: symbol 

    if space == None: space = ' '*len(symbol)

    if not len(symbol): 
        max_str = len(str(n*n + start - 1))
        if space == None: space = '.'*max_str + ' '
        f = lambda x: ('%' + str(max_str) + 'd ')%x

    for y in range(n):
        print(''.join(cell_str(v) for v in [cell(n, x, y, start) for x in range(n)]))
    print()

show_spiral(10, symbol=u'♞', space=u'♘') 
show_spiral(9, symbol='', space=' - ')







Ada: generic
   Size: Positive; 
      
   with function Represent(N: Natural) return String;
      
      
      
      
   with procedure Put_String(S: String);
      
   with procedure New_Line;
      
package Generic_Ulam is
   
   procedure Print_Spiral;
   
   
   
end Generic_Ulam;
Task: Bitmap_Bézier curves_Cubic







Python: def cubicbezier(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20):
    pts = []
    for i in range(n+1):
        t = i / n
        a = (1. - t)**3
        b = 3. * t * (1. - t)**2
        c = 3.0 * t**2 * (1.0 - t)
        d = t**3
        
        x = int(a * x0 + b * x1 + c * x2 + d * x3)
        y = int(a * y0 + b * y1 + c * y2 + d * y3)
        pts.append( (x, y) )
    for i in range(n):
        self.line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1])
Bitmap.cubicbezier = cubicbezier

bitmap = Bitmap(17,17)
bitmap.cubicbezier(16,1, 1,4, 3,16, 15,11)
bitmap.chardisplay()








Ada: procedure Cubic_Bezier
          (  Picture        : in out Image;
             P1, P2, P3, P4 : Point;
             Color          : Pixel;
             N              : Positive := 20
          )  is
   Points : array (0..N) of Point;
begin
   for I in Points'Range loop
      declare
         T : constant Float := Float (I) / Float (N);
         A : constant Float := (1.0 - T)**3;
         B : constant Float := 3.0 * T * (1.0 - T)**2;
         C : constant Float := 3.0 * T**2 * (1.0 - T);
         D : constant Float := T**3;
      begin
         Points (I).X := Positive (A * Float (P1.X) + B * Float (P2.X) + C * Float (P3.X) + D * Float (P4.X));
         Points (I).Y := Positive (A * Float (P1.Y) + B * Float (P2.Y) + C * Float (P3.Y) + D * Float (P4.Y));
      end;
   end loop;
   for I in Points'First..Points'Last - 1 loop
      Line (Picture, Points (I), Points (I + 1), Color);
   end loop;
end Cubic_Bezier;
Task: Rendezvous







Python: 
from __future__ import annotations

import asyncio
import sys

from typing import Optional
from typing import TextIO


class OutOfInkError(Exception):
    


class Printer:
    def __init__(self, name: str, backup: Optional[Printer]):
        self.name = name
        self.backup = backup

        self.ink_level: int = 5
        self.output_stream: TextIO = sys.stdout

    async def print(self, msg):
        if self.ink_level <= 0:
            if self.backup:
                await self.backup.print(msg)
            else:
                raise OutOfInkError(self.name)
        else:
            self.ink_level -= 1
            self.output_stream.write(f"({self.name}): {msg}\n")


async def main():
    reserve = Printer("reserve", None)
    main = Printer("main", reserve)

    humpty_lines = [
        "Humpty Dumpty sat on a wall.",
        "Humpty Dumpty had a great fall.",
        "All the king's horses and all the king's men,",
        "Couldn't put Humpty together again.",
    ]

    goose_lines = [
        "Old Mother Goose,",
        "When she wanted to wander,",
        "Would ride through the air,",
        "On a very fine gander.",
        "Jack's mother came in,",
        "And caught the goose soon,",
        "And mounting its back,",
        "Flew up to the moon.",
    ]

    async def print_humpty():
        for line in humpty_lines:
            try:
                task = asyncio.Task(main.print(line))
                await task
            except OutOfInkError:
                print("\t Humpty Dumpty out of ink!")
                break

    async def print_goose():
        for line in goose_lines:
            try:
                task = asyncio.Task(main.print(line))
                await task
            except OutOfInkError:
                print("\t Mother Goose out of ink!")
                break

    await asyncio.gather(print_goose(), print_humpty())


if __name__ == "__main__":
    asyncio.run(main(), debug=True)





Ada: select
   Server.Wake_Up (Parameters);
or delay 5.0;
   
   ...
end select;